diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..0655d8e56 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "oRTP"] + path = oRTP + url = git://git.linphone.org/ortp.git +[submodule "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/mediastreamer2/.gitignore b/linphone/mediastreamer2/.gitignore deleted file mode 100644 index 6be2672d9..000000000 --- a/linphone/mediastreamer2/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -*.la -*.lo -.deps -.libs -Makefile -Makefile.in -aclocal.m4 -autom4te.cache -compile -config.guess -config.h -config.h.in -config.log -config.status -config.sub -configure -depcomp -install-sh -intltool-extract -intltool-merge -intltool-update -libtool -ltmain.sh -mediastreamer-config.h -mediastreamer-config.h.in -mediastreamer.pc -mediastreamer2.spec -missing -mkinstalldirs -stamp-h1 diff --git a/linphone/mediastreamer2/.indent.pro b/linphone/mediastreamer2/.indent.pro deleted file mode 100644 index 0f9555875..000000000 --- a/linphone/mediastreamer2/.indent.pro +++ /dev/null @@ -1,4 +0,0 @@ --kr ---use-tabs ---tab-size4 - diff --git a/linphone/mediastreamer2/AUTHORS b/linphone/mediastreamer2/AUTHORS deleted file mode 100644 index ff6dbf174..000000000 --- a/linphone/mediastreamer2/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Simon MORLAT \ No newline at end of file diff --git a/linphone/mediastreamer2/COPYING b/linphone/mediastreamer2/COPYING deleted file mode 100644 index d60c31a97..000000000 --- a/linphone/mediastreamer2/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE 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. - - 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 -convey 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 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 - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision 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, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This 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 Library General -Public License instead of this License. diff --git a/linphone/mediastreamer2/ChangeLog b/linphone/mediastreamer2/ChangeLog deleted file mode 100644 index e69de29bb..000000000 diff --git a/linphone/mediastreamer2/Makefile.am b/linphone/mediastreamer2/Makefile.am deleted file mode 100644 index fb246149b..000000000 --- a/linphone/mediastreamer2/Makefile.am +++ /dev/null @@ -1,54 +0,0 @@ - -EXTRA_DIST=mediastreamer-config.h.in pkg.list autogen.sh mediastreamer.pc.in mediastreamer2.spec.in mediastreamer2.spec Makefile.macosx - -SUBDIRS=src build include tests help - -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = mediastreamer.pc - -## oRTP packaging methods: - -# `make rpm' - -.phony: rpm - -rpm: - $(MAKE) dist -# - TAR_OPTIONS=--wildcards rpmbuild -ta --clean --rmsource --rmspec $(PACKAGE)-$(VERSION).tar.gz - -# `make package' - -if WITH_EPM - -.PHONY: package - -PKG_NAME = $(PACKAGE)-$(VERSION)-$(RELEASE) -BUILDROOT=`pwd`/epm-install - -package: $(srcdir)/pkg.list $(srcdir)/configure - [ -n "$(BUILDROOT)" ] && rm -rf $(BUILDROOT)/* - [ -n "$(PKG_NAME).*" ] && rm -f $(PKG_NAME).* - $(MAKE) install DESTDIR=$(BUILDROOT) - $(MKEPMLIST) -u $(SYS_USER) -g $(SYS_GROUP) --prefix $(prefix) \ - $(BUILDROOT)/$(prefix) > files.list - $(EPM) -v -f native -g -n -a $(ARCH) --keep-files --output-dir pkg \ - srcdir=$(srcdir) \ - top_srcdir=$(top_srcdir) \ - top_builddir=$(top_builddir) \ - PACKAGE=$(PACKAGE) \ - SUMMARY="$(SUMMARY)" \ - VERSION=$(ORTP_PKGCONFIG_VERSION) \ - RELEASE=$(RELEASE) \ - LICENSE="$(LICENSE)" \ - VENDOR="$(VENDOR)" \ - PACKAGER="$(PACKAGER)" \ - $(PACKAGE) $(srcdir)/pkg.list - rm -rf $(BUILDROOT) - mv -f pkg/$(PACKAGE)-$(ORTP_PKGCONFIG_VERSION)-$(RELEASE).$(EPM_PKG_EXT) $(PKG_NAME).$(ARCH).$(EPM_PKG_EXT) - -clean-local: - rm -rf pkg $(BUILDROOT) - rm -f files.list - -endif WITH_EPM diff --git a/linphone/mediastreamer2/Makefile.macosx b/linphone/mediastreamer2/Makefile.macosx deleted file mode 100644 index bff389626..000000000 --- a/linphone/mediastreamer2/Makefile.macosx +++ /dev/null @@ -1,76 +0,0 @@ -# MacOS X Temporary make file -# H.M 2007.05.23 - -SPEEXDIR = ../../../speex-1.2beta1 -GSMDIR = ../../../gsm-1.0-pl12 -ORTPDIR = ../../oRTP - -INCPATH = -I../include -I$(ORTPDIR)/include -I$(SPEEXDIR)/include -I$(GSMDIR)/inc/ -LIBPATH = -L. -L../../../gsm-1.0-pl12/lib -FRAMEWORK = -framework CoreAudio -framework AudioToolbox -framework Carbon -framework AudioUnit -CFLUGS = -g $(INCPATH) -DWORDS_BIGENDIAN -DDEBUG -#CFLUGS = $(INCPATH) -DWORDS_BIGENDIAN - - -LIBOBJ = mscommon.o msqueue.o msfilerec.o msfilter.o msspeex.o mssndcard.o alaw.o ulaw.o msconf.o msjoin.o msrtp.o ice.o tee.o gsm.o speexec.o audiostream.o msticker.o macsnd.o msfileplayer.o -DYLIB = libms.dylib - -all: echo - -echo: ../tests/echo.c $(DYLIB) - cc -c $(CFLUGS) ../tests/echo.c - cc -o echo $(FRAMEWORK) $(LIBPATH) echo.o $(DYLIB) -lortp -lspeex -lgsm - -clean: - rm -rf *.o *.dylib - -$(DYLIB): $(LIBOBJ) libortp.dylib libspeex.dylib - cc -o $(DYLIB) $(FRAMEWORK) -dynamiclib -compatibility_version 1 -current_version 1 $(LIBOBJ) $(LIBPATH) -lortp -lspeex -lgsm - -libortp.dylib: - cp $(ORTPDIR)/src/.libs/libortp.dylib . - install_name_tool -id @executable_path/libortp.dylib libortp.dylib - -libspeex.dylib: - cp $(SPEEXDIR)/libspeex/.libs/libspeex.dylib . - install_name_tool -id @executable_path/libspeex.dylib libspeex.dylib - -msfileplayer.o: msfileplayer.c - gcc -c $(CFLUGS) msfileplayer.c -msticker.o: msticker.c - gcc -c $(CFLUGS) msticker.c -audiostream.o: audiostream.c - gcc -c $(CFLUGS) audiostream.c -speexec.o: speexec.c - gcc -c $(CFLUGS) speexec.c -gsm.o: gsm.c - gcc -c $(CFLUGS) gsm.c -tee.o: tee.c - gcc -c $(CFLUGS) tee.c -ice.o: ice.c - gcc -c $(CFLUGS) ice.c -msrtp.o: msrtp.c - gcc -c $(CFLUGS) msrtp.c -msjoin.o: msjoin.c - gcc -c $(CFLUGS) msjoin.c -msconf.o: msconf.c - gcc -c $(CFLUGS) msconf.c -msfilter.o: msfilter.c - gcc -c $(CFLUGS) msfilter.c -alaw.o: alaw.c - gcc -c $(CFLUGS) alaw.c -ulaw.o: ulaw.c - gcc -c $(CFLUGS) ulaw.c -msfilerec.o: msfilerec.c - gcc -c $(CFLUGS) msfilerec.c -msspeex.o: msspeex.c - gcc -c $(CFLUGS) msspeex.c -mssndcard.o: mssndcard.c - gcc -c $(CFLUGS) mssndcard.c -msqueue.o: msqueue.c - gcc -c $(CFLUGS) msqueue.c -macsnd.o: macsnd.c - gcc -c $(CFLUGS) macsnd.c - -mscommon.o: mscommon.c - gcc -c $(CFLUGS) -DPACKAGE_PLUGINS_DIR=\".\" mscommon.c diff --git a/linphone/mediastreamer2/NEWS b/linphone/mediastreamer2/NEWS deleted file mode 100644 index 0b4abfc4b..000000000 --- a/linphone/mediastreamer2/NEWS +++ /dev/null @@ -1,56 +0,0 @@ -mediastreamer-2.3.2: ???????? - * use libv4l2 when possible to benefit from hardware pixel conversion - * added jpeg over RTP support - -mediastreamer-2.3.1: October 5, 2009 - * preserve ratio in windows video display (not yet implemented for linux/SDL) - -mediastreamer-2.3.0: September 17, 2009 - * integrate directshow capture filter for mingw (was a plugin before) - * builds on windows with mingw/msys using ./configure && make (see linphone's README.mingw) - * new parametric equalizer filter (to modify gains per frequency bands), working with natural curves - * new noise-gate feature added to MSVolume - * list of soundcard dynamically updates on windows upon device plugs/unplugs - * MSVolume echo limiter feature improved - -mediastreamer-2.2.4: May 4, 2009 - * fix crash during video window resizing on windows - * improve documentation - * various little improvements - -mediastreamer-2.2.3: 21, January 2009 - * rfc3984 support improved - * webcam support on windows largely improved (vfw mode) - * support for configuring video size up to svga - * video output can automatically resize to the size of received video stream - * fix crash when resizing video window - * new MSWebcam object to provide Webcam management and MSFilter instantiation - * alsa bugfixes - -mediastreamer-2.2.2: 6, october 2008 - * new winsnd3.c file for support of soundcard under windows (seems to work a bit better) - * bugfixes - -mediastreamer-2.2.1: 25, january 2008 - * video output resizing - * 4CIF and VGA support - * bugfixes - * added snow codec (experimental) - * enable setting of max rtp payload size for all encoders - -mediastreamer-2.2.0: 19, November 2007 - * new "no webcam" screen - * bandwidth settings improvements - * new REQ_VFU command to request a video encoder to send an I-frame - (implemented for ffmpeg based encoders) - * contributed macosx sound support - * new MSVolume filter to make sound power measurements - * rate control of ffmpeg video codecs - -mediastreamer-2.1.0: 23, January 2007 - * add support for Video4Linux V2 cameras - * support for mpjeg cameras - * webcam support on windows operational - * video window display ok on windows - * fix bug with quickcam driver on linux - * bandwidth setting improvements. diff --git a/linphone/mediastreamer2/README b/linphone/mediastreamer2/README deleted file mode 100644 index bf67fab8a..000000000 --- a/linphone/mediastreamer2/README +++ /dev/null @@ -1,99 +0,0 @@ -Project : mediastreamer2 - a modular sound and video processing and streaming -Email : simon.morlat_at_linphone.org -License : GPL -Home Page : http://savannah.gnu.org/projects/linphone - -Mediastreamer2 is a GPL licensed library to make audio and -video real-time streaming and processing. Written in pure C, -it is based upon the ortp library. - -Design: ------- - -Using mediastreamer2 will allow you to chain filters in a graph. Each -filter will be responsible for doing some kind of processing and will -deliver data to the next filter. As an example, you could get some -data from network and unpack it in an RTP filter. This RTP filter will -deliver the data to a decoder (speex, G711...) which will deliver it -to a filter that is able to play the PCM data or record it into a .wav -file. - -There is a doxygen documentation for more information. - -Features: --------- - -mediastreamer2 already provides a large set of filters. -Here is a complete list of built-in filters. - - All supported platforms: - * RTP receiver - * RTP sender - * tee (duplicate data) - - Audio Filters: - * audio capture - * audio playback - * mme API (windows) - * alsa API (linux) - * oss API (linux) - * arts API (linux) - * portaudio API (macosx and other) - * macsnd API (native macosx API -please do more testing...-) - * aq (audio queue, macos API too) - * several audio encoder/decoder: PCMU, PCMA, speex, gsm - * wav file reader. - * wav file recorder. - * resampler. - * conference bridge. - * volume analyser, gain control, and automatic gain control. - * acoustic echo canceller. - * dtmf generation filter. - * parametric equalizer, can be used to compensate the spectral response of a bad quality speaker or microphone - - Video Filters: - * video capture - * v4w API (windows, deprecated) - * directshow API (windows) - * video4linux and video4linux2 APIs (linux) - * video display - * v4w API (windows) - * SDL API (linux, macosx...) - * several audio encoder/decoder: H263-1998, MP4V-ES, theora - * image resizer. - * format converter. (RBG24, I420...) - - Plugin Filters: - * iLBC decoder/encoder. - * H264 codec, based on x264 - - -Note that, you can build your own components/filters to do your -own processing or support other codecs. - -Installation procedure: ------------------------ - -The program is known to run on linux, but might work -on any unix and windows systems. - - $> ./configure - $> make - $> su -c 'make install' - -Contact information: --------------------- - -For more information on mediastreamer2, any contributions, or any remarks, -you can contact me at . - -Use the *linphone* mailing list for question about mediastreamer2. - . - -Subscribe by writing to: - with a subject set to "subscribe". - -Commercial support and licensing is provided by Belledonne Communications -http://www.belledonne-communications.com - - diff --git a/linphone/mediastreamer2/acinclude.m4 b/linphone/mediastreamer2/acinclude.m4 deleted file mode 100644 index 98f1b4687..000000000 --- a/linphone/mediastreamer2/acinclude.m4 +++ /dev/null @@ -1,180 +0,0 @@ -dnl -*- autoconf -*- -AC_DEFUN([MS_CHECK_DEP],[ - dnl $1=dependency description - dnl $2=dependency short name, will be suffixed with _CFLAGS and _LIBS - dnl $3=headers's place - dnl $4=lib's place - dnl $5=header to check - dnl $6=lib to check - dnl $7=function to check in library - - dep_name=$2 - dep_headersdir=$3 - dep_libsdir=$4 - dep_header=$5 - dep_lib=$6 - dep_funclib=$7 - other_libs=$8 - - CPPFLAGS_save=$CPPFLAGS - LDFLAGS_save=$LDFLAGS - LIBS_save=$LIBS - - case "$target_os" in - *mingw*) - ms_check_dep_mingw_found=yes - ;; - esac - if test "$ms_check_dep_mingw_found" != "yes" ; then - CPPFLAGS=`echo "-I$dep_headersdir"|sed -e "s:-I/usr/include[\ ]*$::"` - LDFLAGS=`echo "-L$dep_libsdir"|sed -e "s:-L/usr/lib\(64\)*[\ ]*::"` - else - CPPFLAGS="-I$dep_headersdir" - LDFLAGS="-L$dep_libsdir" - fi - - - LIBS="-l$dep_lib" - - - $2_CFLAGS="$CPPFLAGS" - $2_LIBS="$LDFLAGS $LIBS" - - AC_CHECK_HEADERS([$dep_header],[AC_CHECK_LIB([$dep_lib],[$dep_funclib],found=yes,found=no, [$other_libs]) - ],found=no) - - if test "$found" = "yes" ; then - eval $2_found=yes - else - eval $2_found=no - eval $2_CFLAGS= - eval $2_LIBS= - fi - AC_SUBST($2_CFLAGS) - AC_SUBST($2_LIBS) - CPPFLAGS=$CPPFLAGS_save - LDFLAGS=$LDFLAGS_save - LIBS=$LIBS_save -]) - - -AC_DEFUN([MS_CHECK_VIDEO],[ - - dnl conditionnal build of video support - AC_ARG_ENABLE(video, - [ --enable-video Turn on video support compiling], - [case "${enableval}" in - yes) video=true ;; - no) video=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-video) ;; - esac],[video=true]) - - AC_ARG_WITH( ffmpeg, - [ --with-ffmpeg Sets the installation prefix of ffmpeg, needed for video support. [default=/usr] ], - [ ffmpegdir=${withval}],[ ffmpegdir=/usr ]) - - if test "$video" = "true"; then - - dnl test for ffmpeg presence - PKG_CHECK_MODULES(FFMPEG, [libavcodec >= 51.0.0 ],ffmpeg_found=yes , ffmpeg_found=no) - if test x$ffmpeg_found = xno ; then - AC_MSG_ERROR([Could not find libavcodec (from ffmpeg) headers and library. This is mandatory for video support]) - fi - PKG_CHECK_MODULES(SWSCALE, [libswscale >= 0.7.0 ],swscale_found=yes , swscale_found=no) - if test x$swscale_found = xno ; then - AC_MSG_ERROR([Could not find libswscale (from ffmpeg) headers and library. This is mandatory for video support]) - fi - - dnl check for new/old ffmpeg header file layout - CPPFLAGS_save=$CPPFLAGS - CPPFLAGS="$FFMPEG_CFLAGS $CPPFLAGS" - AC_CHECK_HEADERS(libavcodec/avcodec.h) - CPPFLAGS=$CPPFLAGS_save - - dnl to workaround a bug on debian and ubuntu, check if libavcodec needs -lvorbisenc to compile - AC_CHECK_LIB(avcodec,avcodec_register_all, novorbis=yes , [ - LIBS="$LIBS -lvorbisenc" - ], $FFMPEG_LIBS ) - - dnl when swscale feature is not provided by - dnl libswscale, its features are swallowed by - dnl libavcodec, but without swscale.h and without any - dnl declaration into avcodec.h (this is to be - dnl considered as an ffmpeg bug). - dnl - dnl #if defined(HAVE_LIBAVCODEC_AVCODEC_H) && !defined(HAVE_LIBSWSCALE_SWSCALE_H) - dnl # include "swscale.h" // private linhone swscale.h - dnl #endif - CPPFLAGS_save=$CPPFLAGS - CPPFLAGS="$SWSCALE_CFLAGS $CPPFLAGS" - AC_CHECK_HEADERS(libswscale/swscale.h) - CPPFLAGS=$CPPFLAGS_save - - AC_ARG_ENABLE(sdl, - [ --disable-sdl Disable SDL support], - [case "${enableval}" in - yes) enable_sdl=true ;; - no) enable_sdl=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-sdl) ;; - esac],[enable_sdl=true]) - - sdl_found=no - if test "$enable_sdl" = "true"; then - PKG_CHECK_MODULES(SDL, [sdl >= 1.2.0 ],sdl_found=yes,sdl_found=no) - - if test "$sdl_found" = "no" && test "$mingw_found" != "yes"; then - AC_MSG_ERROR([Could not find libsdl headers and library. This is mandatory for video support]) - fi - fi - - AC_ARG_ENABLE(theora, - [ --disable-theora Disable theora support], - [case "${enableval}" in - yes) theora=true ;; - no) theora=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-theora) ;; - esac],[theora=true]) - - if test x$theora = xtrue; then - PKG_CHECK_MODULES(THEORA, [theora >= 1.0alpha7 ], [have_theora=yes], - [have_theora=no]) - fi - - AC_ARG_ENABLE(x11, - [ --disable-x11 Disable X11 support], - [case "${enableval}" in - yes) enable_x11=true ;; - no) enable_x11=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-x11) ;; - esac],[enable_x11=true]) - - if test "$enable_x11" = "true"; then - AC_CHECK_HEADERS(X11/Xlib.h) - fi - - VIDEO_CFLAGS=" $FFMPEG_CFLAGS -DVIDEO_ENABLED" - VIDEO_LIBS=" $FFMPEG_LIBS $SWSCALE_LIBS" - - if test "$sdl_found" = "yes" ; then - VIDEO_CFLAGS="$VIDEO_CFLAGS $SDL_CFLAGS -DHAVE_SDL" - VIDEO_LIBS="$VIDEO_LIBS $SDL_LIBS" - fi - - if test "${ac_cv_header_X11_Xlib_h}" = "yes" ; then - VIDEO_LIBS="$VIDEO_LIBS -lX11" - fi - - if test "$mingw_found" = "yes" ; then - VIDEO_LIBS="$VIDEO_LIBS -lvfw32" - fi - - case $target_os in - *darwin*) - LIBS="$LIBS -framework QuickTime" - ;; - esac - fi - - AC_SUBST(VIDEO_CFLAGS) - AC_SUBST(VIDEO_LIBS) -]) diff --git a/linphone/mediastreamer2/autogen.sh b/linphone/mediastreamer2/autogen.sh deleted file mode 100755 index f88915e64..000000000 --- a/linphone/mediastreamer2/autogen.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh - -AM_VERSION="1.10" -if ! type aclocal-$AM_VERSION 1>/dev/null 2>&1; then - # automake-1.10 (recommended) is not available on Fedora 8 - AUTOMAKE=automake - ACLOCAL=aclocal -else - ACLOCAL=aclocal-${AM_VERSION} - AUTOMAKE=automake-${AM_VERSION} -fi - -if test -f /opt/local/bin/glibtoolize ; then - # darwin - LIBTOOLIZE=/opt/local/bin/glibtoolize -else - LIBTOOLIZE=libtoolize -fi -if test -d /opt/local/share/aclocal ; then - ACLOCAL_ARGS="-I /opt/local/share/aclocal" -fi - -echo "Generating build scripts in mediastreamer..." -set -x -$LIBTOOLIZE --copy --force -$ACLOCAL $ACLOCAL_ARGS -autoheader -$AUTOMAKE --force-missing --add-missing --copy -autoconf - diff --git a/linphone/mediastreamer2/build/Makefile.am b/linphone/mediastreamer2/build/Makefile.am deleted file mode 100755 index 7d64e0e78..000000000 --- a/linphone/mediastreamer2/build/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS= win32native win32-novideo wince winmob diff --git a/linphone/mediastreamer2/build/win32-novideo/.gitignore b/linphone/mediastreamer2/build/win32-novideo/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/mediastreamer2/build/win32-novideo/Makefile.am b/linphone/mediastreamer2/build/win32-novideo/Makefile.am deleted file mode 100755 index b8a8dc25a..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=alldescs.h mediastreamer2.vcproj mediastream.vcproj mediastreamer2.def - diff --git a/linphone/mediastreamer2/build/win32-novideo/alldescs.h b/linphone/mediastreamer2/build/win32-novideo/alldescs.h deleted file mode 100755 index 146f85da8..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/alldescs.h +++ /dev/null @@ -1,70 +0,0 @@ -#include "mediastreamer2/msfilter.h" - -extern MSFilterDesc ms_alaw_dec_desc; -extern MSFilterDesc ms_alaw_enc_desc; -extern MSFilterDesc ms_ulaw_dec_desc; -extern MSFilterDesc ms_ulaw_enc_desc; -extern MSFilterDesc ms_file_player_desc; -extern MSFilterDesc ms_rtp_send_desc; -extern MSFilterDesc ms_rtp_recv_desc; -extern MSFilterDesc ms_dtmf_gen_desc; -extern MSFilterDesc ms_file_rec_desc; -extern MSFilterDesc ms_speex_dec_desc; -extern MSFilterDesc ms_speex_enc_desc; -extern MSFilterDesc ms_gsm_dec_desc; -extern MSFilterDesc ms_gsm_enc_desc; -extern MSFilterDesc ms_speex_ec_desc; -extern MSFilterDesc ms_tee_desc; -extern MSFilterDesc ms_conf_desc; -//extern MSFilterDesc alsa_write_desc; -//extern MSFilterDesc alsa_read_desc; -//extern MSFilterDesc oss_read_desc; -//extern MSFilterDesc oss_write_desc; -//extern MSFilterDesc ms_arts_read_desc; -//extern MSFilterDesc ms_arts_write_desc; -//extern MSFilterDesc ms_v4l_desc; -//extern MSFilterDesc ms_sdl_out_desc; -//extern MSFilterDesc ms_h263_enc_desc; -//extern MSFilterDesc ms_h263_dec_desc; -extern MSFilterDesc ms_join_desc; -extern MSFilterDesc ms_resample_desc; -extern MSFilterDesc ms_volume_desc; -extern MSFilterDesc ms_ice_desc; -extern MSFilterDesc ms_equalizer_desc; -MSFilterDesc * ms_filter_descs[]={ -&ms_alaw_dec_desc, -&ms_alaw_enc_desc, -&ms_ulaw_dec_desc, -&ms_ulaw_enc_desc, -&ms_file_player_desc, -&ms_rtp_send_desc, -&ms_rtp_recv_desc, -&ms_dtmf_gen_desc, -&ms_file_rec_desc, -&ms_speex_dec_desc, -&ms_speex_enc_desc, -&ms_gsm_dec_desc, -&ms_gsm_enc_desc, -&ms_speex_ec_desc, -&ms_tee_desc, -&ms_conf_desc, -//&alsa_write_desc, -//&alsa_read_desc, -//&oss_read_desc, -//&oss_write_desc, -//&ms_arts_read_desc, -//&ms_arts_write_desc, -//&ms_v4l_desc, -//&ms_sdl_out_desc, -//&ms_h263_enc_desc, -//&ms_h263_dec_desc, -&ms_join_desc, -#ifndef DISABLE_RESAMPLE -&ms_resample_desc, -#endif -&ms_volume_desc, -&ms_ice_desc, -&ms_equalizer_desc, -NULL -}; - diff --git a/linphone/mediastreamer2/build/win32-novideo/mediastream.vcproj b/linphone/mediastreamer2/build/win32-novideo/mediastream.vcproj deleted file mode 100755 index b44c28431..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/mediastream.vcproj +++ /dev/null @@ -1,143 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.def b/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.def deleted file mode 100755 index 8287deb3b..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.def +++ /dev/null @@ -1,82 +0,0 @@ -LIBRARY mediastreamer2 - -EXPORTS - - ms_init - ms_exit - - ms_filter_new - ms_filter_new_from_desc - ms_filter_destroy - ms_filter_create_encoder - ms_filter_create_decoder - ms_filter_call_method - ms_filter_call_method_noarg - ms_filter_link - ms_filter_unlink - ms_filter_preprocess - ms_filter_postprocess - ms_filter_codec_supported - ms_filter_register - ms_filter_new_from_name - ms_filter_set_notify_callback - - ms_snd_card_new - ms_snd_card_manager_destroy - ms_snd_card_manager_reload - ms_snd_card_manager_add_card - ms_snd_card_manager_register_desc - ms_snd_card_create_reader - ms_snd_card_create_writer - ms_snd_card_get_name - ms_snd_card_get_string_id - ms_snd_card_manager_get - ms_snd_card_manager_get_default_card - ms_snd_card_manager_get_default_capture_card - ms_snd_card_manager_get_default_playback_card - ms_snd_card_manager_get_card - ms_snd_card_manager_get_list - ms_snd_card_dup - ms_snd_card_destroy - ms_snd_card_set_level - ms_snd_card_get_level - ms_snd_card_set_capture - ms_snd_card_set_control - ms_snd_card_get_control - - ms_ticker_new - ms_ticker_set_name - ms_ticker_destroy - ms_ticker_attach - ms_ticker_detach - ms_ticker_set_time_func - ms_ticker_print_graphs - - ms_bufferizer_init - ms_bufferizer_uninit - ms_bufferizer_read - ms_bufferizer_put - ms_bufferizer_put_from_queue - - audio_stream_start - audio_stream_stop - audio_stream_free - create_duplex_rtpsession - - ms_load_plugins - - ms_is_ipv6 - - ms_sleep - - ms_queue_init - ms_queue_flush - - ms_list_free - ms_list_for_each - ms_list_append - ms_list_remove - - ms_discover_mtu - ms_set_mtu - \ No newline at end of file diff --git a/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.vcproj b/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.vcproj deleted file mode 100755 index e57e5b06f..000000000 --- a/linphone/mediastreamer2/build/win32-novideo/mediastreamer2.vcproj +++ /dev/null @@ -1,416 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/win32native/.gitignore b/linphone/mediastreamer2/build/win32native/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/mediastreamer2/build/win32native/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/mediastreamer2/build/win32native/Makefile.am b/linphone/mediastreamer2/build/win32native/Makefile.am deleted file mode 100755 index 82fc5635a..000000000 --- a/linphone/mediastreamer2/build/win32native/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=alldescs.h mediastreamer2.vcproj mediastream.vcproj videodisplay.vcproj mediastreamer2.def - diff --git a/linphone/mediastreamer2/build/win32native/alldescs.h b/linphone/mediastreamer2/build/win32native/alldescs.h deleted file mode 100755 index a83db96ee..000000000 --- a/linphone/mediastreamer2/build/win32native/alldescs.h +++ /dev/null @@ -1,90 +0,0 @@ -#include "mediastreamer2/msfilter.h" - -extern MSFilterDesc ms_alaw_dec_desc; -extern MSFilterDesc ms_alaw_enc_desc; -extern MSFilterDesc ms_ulaw_dec_desc; -extern MSFilterDesc ms_ulaw_enc_desc; -extern MSFilterDesc ms_file_player_desc; -extern MSFilterDesc ms_rtp_send_desc; -extern MSFilterDesc ms_rtp_recv_desc; -extern MSFilterDesc ms_dtmf_gen_desc; -extern MSFilterDesc ms_file_rec_desc; -extern MSFilterDesc ms_speex_dec_desc; -extern MSFilterDesc ms_speex_enc_desc; -extern MSFilterDesc ms_gsm_dec_desc; -extern MSFilterDesc ms_gsm_enc_desc; -extern MSFilterDesc ms_speex_ec_desc; -extern MSFilterDesc ms_tee_desc; -extern MSFilterDesc ms_void_sink_desc; -extern MSFilterDesc ms_conf_desc; -extern MSFilterDesc ms_v4w_desc; -extern MSFilterDesc ms_video_out_desc; -extern MSFilterDesc ms_h263_enc_desc; -extern MSFilterDesc ms_h263_dec_desc; -extern MSFilterDesc ms_h263_old_enc_desc; -extern MSFilterDesc ms_h263_old_dec_desc; -extern MSFilterDesc ms_mpeg4_enc_desc; -extern MSFilterDesc ms_mpeg4_dec_desc; -extern MSFilterDesc ms_snow_enc_desc; -extern MSFilterDesc ms_snow_dec_desc; -extern MSFilterDesc ms_theora_enc_desc; -extern MSFilterDesc ms_theora_dec_desc; -extern MSFilterDesc ms_mjpeg_enc_desc; -extern MSFilterDesc ms_mjpeg_dec_desc; -extern MSFilterDesc ms_size_conv_desc; -extern MSFilterDesc ms_pix_conv_desc; -extern MSFilterDesc ms_join_desc; -extern MSFilterDesc ms_resample_desc; -extern MSFilterDesc ms_volume_desc; -extern MSFilterDesc ms_static_image_desc; -extern MSFilterDesc ms_mire_desc; -extern MSFilterDesc ms_vfw_desc; -extern MSFilterDesc ms_ice_desc; -extern MSFilterDesc ms_equalizer_desc; -MSFilterDesc * ms_filter_descs[]={ -&ms_alaw_dec_desc, -&ms_alaw_enc_desc, -&ms_ulaw_dec_desc, -&ms_ulaw_enc_desc, -&ms_file_player_desc, -&ms_rtp_send_desc, -&ms_rtp_recv_desc, -&ms_dtmf_gen_desc, -&ms_file_rec_desc, -&ms_speex_dec_desc, -&ms_speex_enc_desc, -&ms_gsm_dec_desc, -&ms_gsm_enc_desc, -&ms_speex_ec_desc, -&ms_tee_desc, -&ms_void_sink_desc, -&ms_conf_desc, -&ms_v4w_desc, -&ms_video_out_desc, -&ms_h263_old_enc_desc, -&ms_h263_old_dec_desc, -&ms_h263_enc_desc, -&ms_h263_dec_desc, -&ms_mpeg4_enc_desc, -&ms_mpeg4_dec_desc, -&ms_snow_enc_desc, -&ms_snow_dec_desc, -&ms_theora_enc_desc, -&ms_theora_dec_desc, -&ms_mjpeg_enc_desc, -&ms_mjpeg_dec_desc, -&ms_size_conv_desc, -&ms_pix_conv_desc, -&ms_join_desc, -#ifndef NORESAMPLE -&ms_resample_desc, -#endif -&ms_volume_desc, -&ms_static_image_desc, -&ms_mire_desc, -&ms_vfw_desc, -&ms_ice_desc, -&ms_equalizer_desc, -NULL -}; - diff --git a/linphone/mediastreamer2/build/win32native/mediastream.vcproj b/linphone/mediastreamer2/build/win32native/mediastream.vcproj deleted file mode 100755 index 1dd3ec7b0..000000000 --- a/linphone/mediastreamer2/build/win32native/mediastream.vcproj +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/win32native/mediastreamer2.def b/linphone/mediastreamer2/build/win32native/mediastreamer2.def deleted file mode 100755 index e13dd8674..000000000 --- a/linphone/mediastreamer2/build/win32native/mediastreamer2.def +++ /dev/null @@ -1,117 +0,0 @@ -LIBRARY mediastreamer2 - -EXPORTS - - ms_init - ms_exit - - ms_filter_new - ms_filter_new_from_desc - ms_filter_destroy - ms_filter_create_encoder - ms_filter_create_decoder - ms_filter_call_method - ms_filter_call_method_noarg - ms_filter_link - ms_filter_unlink - ms_filter_preprocess - ms_filter_postprocess - ms_filter_codec_supported - ms_filter_register - ms_filter_new_from_name - ms_filter_set_notify_callback - - ms_snd_card_new - ms_snd_card_manager_destroy - ms_snd_card_manager_reload - ms_snd_card_manager_add_card - ms_snd_card_manager_register_desc - ms_snd_card_create_reader - ms_snd_card_create_writer - ms_snd_card_get_name - ms_snd_card_get_string_id - ms_snd_card_manager_get - ms_snd_card_manager_get_default_card - ms_snd_card_manager_get_default_capture_card - ms_snd_card_manager_get_default_playback_card - ms_snd_card_manager_get_card - ms_snd_card_manager_get_list - ms_snd_card_dup - ms_snd_card_destroy - ms_snd_card_set_level - ms_snd_card_get_level - ms_snd_card_set_capture - ms_snd_card_set_control - ms_snd_card_get_control - - ms_ticker_new - ms_ticker_set_name - ms_ticker_destroy - ms_ticker_attach - ms_ticker_detach - ms_ticker_set_time_func - ms_ticker_print_graphs - - ms_bufferizer_init - ms_bufferizer_uninit - ms_bufferizer_read - ms_bufferizer_put - ms_bufferizer_put_from_queue - - audio_stream_start - audio_stream_stop - audio_stream_free - create_duplex_rtpsession - - ms_load_plugins - - ms_display_new - ms_display_set_window_id - ms_display_desc_set_default - ms_display_destroy - - video_preview_stop - video_preview_start - video_stream_new - video_stream_start - video_stream_stop - video_stream_iterate - video_stream_set_sent_video_size - - ms_is_ipv6 - - yuv_buf_alloc - yuv_buf_init_from_mblk - yuv_buf_init_from_mblk_with_size - - ms_sleep - - ms_queue_init - ms_queue_flush - - rfc3984_init - rfc3984_uninit - rfc3984_pack - rfc3984_unpack - rfc3984_set_mode - - ms_list_free - ms_list_for_each - ms_list_append - ms_list_remove - - ms_discover_mtu - ms_set_mtu - - ms_web_cam_new - ms_web_cam_manager_reload - ms_web_cam_manager_get_default_cam - ms_web_cam_manager_get - ms_web_cam_manager_get_list - ms_web_cam_manager_get_cam - ms_web_cam_manager_add_cam - ms_web_cam_manager_register_desc - ms_web_cam_create_reader - ms_web_cam_get_driver_type - ms_web_cam_get_name - ms_web_cam_get_string_id diff --git a/linphone/mediastreamer2/build/win32native/mediastreamer2.vcproj b/linphone/mediastreamer2/build/win32native/mediastreamer2.vcproj deleted file mode 100755 index 93dd6356a..000000000 --- a/linphone/mediastreamer2/build/win32native/mediastreamer2.vcproj +++ /dev/null @@ -1,504 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/win32native/videodisplay.vcproj b/linphone/mediastreamer2/build/win32native/videodisplay.vcproj deleted file mode 100755 index 5784ff317..000000000 --- a/linphone/mediastreamer2/build/win32native/videodisplay.vcproj +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/wince/Makefile.am b/linphone/mediastreamer2/build/wince/Makefile.am deleted file mode 100755 index 07d97c86e..000000000 --- a/linphone/mediastreamer2/build/wince/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=alldescs.h mediastreamer2.vcproj mediastreamer2.def - diff --git a/linphone/mediastreamer2/build/wince/alldescs.h b/linphone/mediastreamer2/build/wince/alldescs.h deleted file mode 100644 index e5e179401..000000000 --- a/linphone/mediastreamer2/build/wince/alldescs.h +++ /dev/null @@ -1,68 +0,0 @@ -#include "mediastreamer2/msfilter.h" - -extern MSFilterDesc ms_alaw_dec_desc; -extern MSFilterDesc ms_alaw_enc_desc; -extern MSFilterDesc ms_ulaw_dec_desc; -extern MSFilterDesc ms_ulaw_enc_desc; -extern MSFilterDesc ms_file_player_desc; -extern MSFilterDesc ms_rtp_send_desc; -extern MSFilterDesc ms_rtp_recv_desc; -extern MSFilterDesc ms_dtmf_gen_desc; -extern MSFilterDesc ms_file_rec_desc; -extern MSFilterDesc ms_speex_dec_desc; -extern MSFilterDesc ms_speex_enc_desc; -//extern MSFilterDesc ms_gsm_dec_desc; -//extern MSFilterDesc ms_gsm_enc_desc; -extern MSFilterDesc ms_speex_ec_desc; -extern MSFilterDesc ms_tee_desc; -extern MSFilterDesc ms_conf_desc; -//extern MSFilterDesc alsa_write_desc; -//extern MSFilterDesc alsa_read_desc; -//extern MSFilterDesc oss_read_desc; -//extern MSFilterDesc oss_write_desc; -//extern MSFilterDesc ms_arts_read_desc; -//extern MSFilterDesc ms_arts_write_desc; -//extern MSFilterDesc ms_v4l_desc; -//extern MSFilterDesc ms_sdl_out_desc; -//extern MSFilterDesc ms_h263_enc_desc; -//extern MSFilterDesc ms_h263_dec_desc; -extern MSFilterDesc ms_join_desc; -extern MSFilterDesc ms_resample_desc; -extern MSFilterDesc ms_volume_desc; -extern MSFilterDesc ms_ice_desc; -extern MSFilterDesc ms_void_sink_desc; -MSFilterDesc * ms_filter_descs[]={ -&ms_alaw_dec_desc, -&ms_alaw_enc_desc, -&ms_ulaw_dec_desc, -&ms_ulaw_enc_desc, -&ms_file_player_desc, -&ms_rtp_send_desc, -&ms_rtp_recv_desc, -&ms_dtmf_gen_desc, -&ms_file_rec_desc, -&ms_speex_dec_desc, -&ms_speex_enc_desc, -//&ms_gsm_dec_desc, -//&ms_gsm_enc_desc, -&ms_speex_ec_desc, -&ms_tee_desc, -&ms_conf_desc, -//&alsa_write_desc, -//&alsa_read_desc, -//&oss_read_desc, -//&oss_write_desc, -//&ms_arts_read_desc, -//&ms_arts_write_desc, -//&ms_v4l_desc, -//&ms_sdl_out_desc, -//&ms_h263_enc_desc, -//&ms_h263_dec_desc, -&ms_join_desc, -&ms_resample_desc, -&ms_volume_desc, -&ms_ice_desc, -&ms_void_sink_desc, -NULL -}; - diff --git a/linphone/mediastreamer2/build/wince/mediastreamer2.def b/linphone/mediastreamer2/build/wince/mediastreamer2.def deleted file mode 100644 index 80dad5f0b..000000000 --- a/linphone/mediastreamer2/build/wince/mediastreamer2.def +++ /dev/null @@ -1,129 +0,0 @@ -LIBRARY mediastreamer2 - -EXPORTS - - ms_init - ms_exit - - ms_filter_new - ms_filter_new_from_desc - ms_filter_destroy - ms_filter_create_encoder - ms_filter_create_decoder - ms_filter_call_method - ms_filter_call_method_noarg - ms_filter_link - ms_filter_unlink - ms_filter_preprocess - ms_filter_postprocess - ms_filter_codec_supported - ms_filter_register - ms_filter_new_from_name - ms_filter_set_notify_callback - ms_filter_get_encoder - - ms_snd_card_new - ms_snd_card_manager_destroy - ms_snd_card_manager_reload - ms_snd_card_manager_add_card - ms_snd_card_manager_register_desc - ms_snd_card_create_reader - ms_snd_card_create_writer - ms_snd_card_get_name - ms_snd_card_get_string_id - ms_snd_card_manager_get - ms_snd_card_manager_get_default_card - ms_snd_card_manager_get_default_capture_card - ms_snd_card_manager_get_default_playback_card - ms_snd_card_manager_get_card - ms_snd_card_manager_get_list - ms_snd_card_dup - ms_snd_card_destroy - ms_snd_card_set_level - ms_snd_card_get_level - ms_snd_card_set_capture - ms_snd_card_set_control - ms_snd_card_get_control - - ms_web_cam_new - ms_web_cam_manager_reload - ms_web_cam_manager_get_default_cam - ms_web_cam_manager_get - ms_web_cam_manager_get_list - ms_web_cam_manager_get_cam - ms_web_cam_manager_add_cam - ms_web_cam_manager_register_desc - ms_web_cam_create_reader - ms_web_cam_get_driver_type - ms_web_cam_get_name - ms_web_cam_get_string_id - - ms_ticker_new - ms_ticker_set_name - ms_ticker_destroy - ms_ticker_attach - ms_ticker_detach - ms_ticker_set_time_func - ms_ticker_print_graphs - - - ms_bufferizer_init - ms_bufferizer_uninit - ms_bufferizer_read - ms_bufferizer_put - ms_bufferizer_put_from_queue - - ms_queue_init - ms_queue_flush - - rfc3984_init - rfc3984_uninit - rfc3984_pack - rfc3984_unpack - rfc3984_set_mode - - ms_load_plugins - - audio_stream_start - audio_stream_alive - audio_stream_enable_automatic_gain_control - audio_stream_set_echo_canceler_params - audio_stream_enable_gain_control - audio_stream_enable_echo_limiter - audio_stream_new - audio_stream_set_rtcp_information - audio_stream_start_with_files - audio_stream_start_now - audio_stream_set_relay_session_id - audio_stream_play_received_dtmfs - audio_stream_set_mic_gain - audio_stream_stop - audio_stream_play - audio_stream_record - ms_snd_card_get_capabilities - ring_start_with_cb - ring_start - ring_stop - audio_stream_send_dtmf - ms_discover_mtu - ms_set_mtu - - ms_list_append - ms_list_remove - ms_list_free - ms_list_for_each - ms_list_find - ms_list_for_each2 - ms_list_find_custom - ms_list_size - ms_list_nth_data - ms_list_remove_link - ms_list_index - ms_list_prepend - ms_list_position - - ms_time - ms_get_payload_max_size - ms_sleep - - \ No newline at end of file diff --git a/linphone/mediastreamer2/build/wince/mediastreamer2.vcproj b/linphone/mediastreamer2/build/wince/mediastreamer2.vcproj deleted file mode 100644 index ac78735cf..000000000 --- a/linphone/mediastreamer2/build/wince/mediastreamer2.vcproj +++ /dev/null @@ -1,1568 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/winmob/Makefile.am b/linphone/mediastreamer2/build/winmob/Makefile.am deleted file mode 100755 index 29f98410c..000000000 --- a/linphone/mediastreamer2/build/winmob/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=alldescs.h mediastreamer2.vcproj mediastreamer2.sln mediastreamer2.def - diff --git a/linphone/mediastreamer2/build/winmob/alldescs.h b/linphone/mediastreamer2/build/winmob/alldescs.h deleted file mode 100644 index e5e179401..000000000 --- a/linphone/mediastreamer2/build/winmob/alldescs.h +++ /dev/null @@ -1,68 +0,0 @@ -#include "mediastreamer2/msfilter.h" - -extern MSFilterDesc ms_alaw_dec_desc; -extern MSFilterDesc ms_alaw_enc_desc; -extern MSFilterDesc ms_ulaw_dec_desc; -extern MSFilterDesc ms_ulaw_enc_desc; -extern MSFilterDesc ms_file_player_desc; -extern MSFilterDesc ms_rtp_send_desc; -extern MSFilterDesc ms_rtp_recv_desc; -extern MSFilterDesc ms_dtmf_gen_desc; -extern MSFilterDesc ms_file_rec_desc; -extern MSFilterDesc ms_speex_dec_desc; -extern MSFilterDesc ms_speex_enc_desc; -//extern MSFilterDesc ms_gsm_dec_desc; -//extern MSFilterDesc ms_gsm_enc_desc; -extern MSFilterDesc ms_speex_ec_desc; -extern MSFilterDesc ms_tee_desc; -extern MSFilterDesc ms_conf_desc; -//extern MSFilterDesc alsa_write_desc; -//extern MSFilterDesc alsa_read_desc; -//extern MSFilterDesc oss_read_desc; -//extern MSFilterDesc oss_write_desc; -//extern MSFilterDesc ms_arts_read_desc; -//extern MSFilterDesc ms_arts_write_desc; -//extern MSFilterDesc ms_v4l_desc; -//extern MSFilterDesc ms_sdl_out_desc; -//extern MSFilterDesc ms_h263_enc_desc; -//extern MSFilterDesc ms_h263_dec_desc; -extern MSFilterDesc ms_join_desc; -extern MSFilterDesc ms_resample_desc; -extern MSFilterDesc ms_volume_desc; -extern MSFilterDesc ms_ice_desc; -extern MSFilterDesc ms_void_sink_desc; -MSFilterDesc * ms_filter_descs[]={ -&ms_alaw_dec_desc, -&ms_alaw_enc_desc, -&ms_ulaw_dec_desc, -&ms_ulaw_enc_desc, -&ms_file_player_desc, -&ms_rtp_send_desc, -&ms_rtp_recv_desc, -&ms_dtmf_gen_desc, -&ms_file_rec_desc, -&ms_speex_dec_desc, -&ms_speex_enc_desc, -//&ms_gsm_dec_desc, -//&ms_gsm_enc_desc, -&ms_speex_ec_desc, -&ms_tee_desc, -&ms_conf_desc, -//&alsa_write_desc, -//&alsa_read_desc, -//&oss_read_desc, -//&oss_write_desc, -//&ms_arts_read_desc, -//&ms_arts_write_desc, -//&ms_v4l_desc, -//&ms_sdl_out_desc, -//&ms_h263_enc_desc, -//&ms_h263_dec_desc, -&ms_join_desc, -&ms_resample_desc, -&ms_volume_desc, -&ms_ice_desc, -&ms_void_sink_desc, -NULL -}; - diff --git a/linphone/mediastreamer2/build/winmob/echo/echo.vcproj b/linphone/mediastreamer2/build/winmob/echo/echo.vcproj deleted file mode 100644 index 5a8b40e64..000000000 --- a/linphone/mediastreamer2/build/winmob/echo/echo.vcproj +++ /dev/null @@ -1,227 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/build/winmob/mediastreamer2.def b/linphone/mediastreamer2/build/winmob/mediastreamer2.def deleted file mode 100644 index 80dad5f0b..000000000 --- a/linphone/mediastreamer2/build/winmob/mediastreamer2.def +++ /dev/null @@ -1,129 +0,0 @@ -LIBRARY mediastreamer2 - -EXPORTS - - ms_init - ms_exit - - ms_filter_new - ms_filter_new_from_desc - ms_filter_destroy - ms_filter_create_encoder - ms_filter_create_decoder - ms_filter_call_method - ms_filter_call_method_noarg - ms_filter_link - ms_filter_unlink - ms_filter_preprocess - ms_filter_postprocess - ms_filter_codec_supported - ms_filter_register - ms_filter_new_from_name - ms_filter_set_notify_callback - ms_filter_get_encoder - - ms_snd_card_new - ms_snd_card_manager_destroy - ms_snd_card_manager_reload - ms_snd_card_manager_add_card - ms_snd_card_manager_register_desc - ms_snd_card_create_reader - ms_snd_card_create_writer - ms_snd_card_get_name - ms_snd_card_get_string_id - ms_snd_card_manager_get - ms_snd_card_manager_get_default_card - ms_snd_card_manager_get_default_capture_card - ms_snd_card_manager_get_default_playback_card - ms_snd_card_manager_get_card - ms_snd_card_manager_get_list - ms_snd_card_dup - ms_snd_card_destroy - ms_snd_card_set_level - ms_snd_card_get_level - ms_snd_card_set_capture - ms_snd_card_set_control - ms_snd_card_get_control - - ms_web_cam_new - ms_web_cam_manager_reload - ms_web_cam_manager_get_default_cam - ms_web_cam_manager_get - ms_web_cam_manager_get_list - ms_web_cam_manager_get_cam - ms_web_cam_manager_add_cam - ms_web_cam_manager_register_desc - ms_web_cam_create_reader - ms_web_cam_get_driver_type - ms_web_cam_get_name - ms_web_cam_get_string_id - - ms_ticker_new - ms_ticker_set_name - ms_ticker_destroy - ms_ticker_attach - ms_ticker_detach - ms_ticker_set_time_func - ms_ticker_print_graphs - - - ms_bufferizer_init - ms_bufferizer_uninit - ms_bufferizer_read - ms_bufferizer_put - ms_bufferizer_put_from_queue - - ms_queue_init - ms_queue_flush - - rfc3984_init - rfc3984_uninit - rfc3984_pack - rfc3984_unpack - rfc3984_set_mode - - ms_load_plugins - - audio_stream_start - audio_stream_alive - audio_stream_enable_automatic_gain_control - audio_stream_set_echo_canceler_params - audio_stream_enable_gain_control - audio_stream_enable_echo_limiter - audio_stream_new - audio_stream_set_rtcp_information - audio_stream_start_with_files - audio_stream_start_now - audio_stream_set_relay_session_id - audio_stream_play_received_dtmfs - audio_stream_set_mic_gain - audio_stream_stop - audio_stream_play - audio_stream_record - ms_snd_card_get_capabilities - ring_start_with_cb - ring_start - ring_stop - audio_stream_send_dtmf - ms_discover_mtu - ms_set_mtu - - ms_list_append - ms_list_remove - ms_list_free - ms_list_for_each - ms_list_find - ms_list_for_each2 - ms_list_find_custom - ms_list_size - ms_list_nth_data - ms_list_remove_link - ms_list_index - ms_list_prepend - ms_list_position - - ms_time - ms_get_payload_max_size - ms_sleep - - \ No newline at end of file diff --git a/linphone/mediastreamer2/build/winmob/mediastreamer2.sln b/linphone/mediastreamer2/build/winmob/mediastreamer2.sln deleted file mode 100644 index 8a3de9d24..000000000 --- a/linphone/mediastreamer2/build/winmob/mediastreamer2.sln +++ /dev/null @@ -1,60 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mediastreamer2", "mediastreamer2.vcproj", "{177F5AE2-A40C-4412-8F26-7F85FA32464E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "echo", "echo\echo.vcproj", "{B616AC95-748E-4CD5-89AC-772DC3C069D9}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {177F5AE2-A40C-4412-8F26-7F85FA32464E}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {B616AC95-748E-4CD5-89AC-772DC3C069D9}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/linphone/mediastreamer2/build/winmob/mediastreamer2.vcproj b/linphone/mediastreamer2/build/winmob/mediastreamer2.vcproj deleted file mode 100644 index 8758723c2..000000000 --- a/linphone/mediastreamer2/build/winmob/mediastreamer2.vcproj +++ /dev/null @@ -1,933 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/mediastreamer2/configure.ac b/linphone/mediastreamer2/configure.ac deleted file mode 100644 index a3affd4a5..000000000 --- a/linphone/mediastreamer2/configure.ac +++ /dev/null @@ -1,659 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. -AC_INIT([mediastreamer],[2.3.1]) - -AC_MSG_NOTICE([$PACKAGE_NAME-$PACKAGE_VERSION A mediastreaming library for telephony application.]) -AC_MSG_NOTICE([licensed under the terms of the General Public License (GPL)]) - -AC_CANONICAL_SYSTEM - -dnl Source packaging numbers -MEDIASTREAMER_MAJOR_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f1) -MEDIASTREAMER_MINOR_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f2) -MEDIASTREAMER_MICRO_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f3) -MEDIASTREAMER_EXTRA_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f4) - -LIBMEDIASTREAMER_SO_CURRENT=0 dnl increment this number when you add/change/remove an interface -LIBMEDIASTREAMER_SO_REVISION=1 dnl increment this number when you change source code, without changing interfaces; set to 0 when incrementing CURRENT -LIBMEDIASTREAMER_SO_AGE=0 dnl increment this number when you add an interface, set to 0 if you remove an interface - -LIBMEDIASTREAMER_SO_VERSION=$LIBMEDIASTREAMER_SO_CURRENT:$LIBMEDIASTREAMER_SO_REVISION:$LIBMEDIASTREAMER_SO_AGE -MEDIASTREAMER_VERSION=${MEDIASTREAMER_MAJOR_VERSION}.${MEDIASTREAMER_MINOR_VERSION}.${MEDIASTREAMER_MICRO_VERSION} - -if test -n "$MEDIASTREAMER_EXTRA_VERSION" ; then - MEDIASTREAMER_VERSION="${MEDIASTREAMER_VERSION}.${MEDIASTREAMER_EXTRA_VERSION}" -fi - -AC_SUBST(LIBMEDIASTREAMER_SO_VERSION) -AC_SUBST(MEDIASTREAMER_VERSION) - -PACKAGE=mediastreamer - -OS=`uname|sed -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'` -AC_MSG_RESULT([Building Package on ${OS}]) - -AM_INIT_AUTOMAKE([tar-ustar]) -m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])],) -AC_CONFIG_HEADERS(mediastreamer-config.h) -AC_DEFINE_UNQUOTED(MEDIASTREAMER_MAJOR_VERSION,$MEDIASTREAMER_MAJOR_VERSION, [major version]) -AC_DEFINE_UNQUOTED(MEDIASTREAMER_MINOR_VERSION,$MEDIASTREAMER_MINOR_VERSION, [minor version]) -AC_DEFINE_UNQUOTED(MEDIASTREAMER_MICRO_VERSION,$MEDIASTREAMER_MICRO_VERSION, [micro version]) -AC_DEFINE_UNQUOTED(MEDIASTREAMER_VERSION,"$MEDIASTREAMER_VERSION",[MEDIASTREAMER version number]) - -MS_PUBLIC_CFLAGS= - -AC_SUBST([mkdir_p]) - -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], -[ - if test "$USER" = "smorlat" ; then - wall_werror=yes - else - wall_werror=no - fi -] -) - -CFLAGS="-DORTP_INET6 $CFLAGS " - -dnl enable ipv6 support -AC_ARG_ENABLE(ipv6, - [ --enable-ipv6 Turn on ipv6 support], - [case "${enableval}" in - yes) ipv6=true;; - no) ipv6=false;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-ipv6) ;; - esac],[ipv6=true]) -if test x$ipv6 = xtrue ; then - CFLAGS="$CFLAGS -DINET6" -fi - - -AC_ARG_ENABLE(debug, - [ --enable-debug=[yes/no] enables the display of traces showing the execution of the library. [default=yes]], - [case "${enableval}" in - yes) debug_enabled=yes;; - no) debug_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-debug");; - esac], - [debug_enabled=no] ) - - -dnl Checks for programs. -AC_PROG_CC -AC_PROG_CXX -AC_PROG_OBJC -AC_LIBTOOL_WIN32_DLL -AC_PROG_LIBTOOL -AC_ENABLE_SHARED(yes) -AC_ENABLE_STATIC(no) - -if test "$GCC" != "yes" ; then - case $target_os in - *hpux*) - dnl we are probably using HPUX cc compiler, so add a +O2 to CFLAGS - CFLAGS="$CFLAGS +O2 -g " - ;; - esac -else - CFLAGS="$CFLAGS -Wall" -fi - - - -if test $debug_enabled = "yes"; then - CFLAGS="$CFLAGS -g -DDEBUG" -else - CFLAGS="$CFLAGS -O2 -g " -fi - -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 - -macosx_found=no -mingw32ce_found=no - -dnl add thread flags -case $target_os in - *darwin*) - MSPLUGINS_CFLAGS="" - MSPLUGINS_LIBS="-dynamiclib" - macosx_found=yes - LIBS="$LIBS -framework CoreFoundation -framework AudioToolbox -framework CoreAudio" - ;; - *mingw32ce) - CFLAGS="$CFLAGS -DINET6 -DORTP_INET6 -D_WIN32_WINNT=0x0501 -D_WIN32_WCE -DORTP_STATIC" - CXXFLAGS="$CXXFLAGS -DINET6 -DORTP_INET6 -D_WIN32_WINNT=0x0501 -DORTP_STATIC -D_WIN32_WCE" -dnl ORTP_STATIC to tell ortp not to export its variable with dllexport, as if we were building statically, or dynamically on linux - LIBS="$LIBS -lws2" - mingw_found=yes - mingw32ce_found=yes - build_tests=no - ;; - *mingw*) - CFLAGS="$CFLAGS -DINET6 -DORTP_INET6 -D_WIN32_WINNT=0x0501 -DORTP_STATIC" - CXXFLAGS="$CXXFLAGS -DINET6 -DORTP_INET6 -D_WIN32_WINNT=0x0501 -DORTP_STATIC" -dnl ORTP_STATIC to tell ortp not to export its variable with dllexport, as if we were building statically, or dynamically on linux - LIBS="$LIBS -lws2_32 -lwinmm " - mingw_found=yes - ;; - *) - MSPLUGINS_CFLAGS="-pthread" - MSPLUGINS_LIBS="-shared -pthread" - CFLAGS="$CFLAGS -pthread -D_REENTRANT" - LIBS="$LIBS -pthread -lpthread" - ;; -esac - -AM_CONDITIONAL(BUILD_MACOSX, test x$macosx_found = xyes) - -AM_CONDITIONAL(BUILD_TESTS,test x$build_tests != xno) - -AC_CONFIG_COMMANDS([libtool-hacking],[ -if test "$mingw_found" = "yes" ; then - echo "Hacking libtool to work with mingw..." - sed -e 's/\*\" \$a_deplib \"\*/\*/' < ./libtool > libtool.tmp - cp -f ./libtool.tmp ./libtool - rm -f ./libtool.tmp -else - echo "No need to hack libtool." -fi -], [mingw_found=$mingw_found]) - - -dnl prefer fixed point computations -AC_ARG_ENABLE(fixed_point, - [ --enable-fixed-point Turn on fixed point computations (default: guess)], - [case "${enableval}" in - yes) fixed_point=true;; - no) fixed_point=false;; - guess) fixed_point=guess;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-fixed-point) ;; - esac],[fixed_point=guess]) - -if test "$fixed_point" = "guess" ; then - AC_MSG_CHECKING([whether fixed point arithmetic is preferred]) - case ${target_cpu}${host_cpu} in - *bfin*) - fixed_point=true - ;; - *arm*) - fixed_point=true - ;; - *) - fixed_point=false - ;; - esac - AC_MSG_RESULT([$fixed_point]) -fi - - -if test x$fixed_point = xtrue ; then - MS_PUBLIC_CFLAGS="$MS_PUBLIC_CFLAGS -DMS_FIXED_POINT" -fi - - -dnl initialize pkg-config so that we can use it within if else fi statements. -PKG_PROG_PKG_CONFIG() - -AC_SUBST(MSPLUGINS_CFLAGS) -AC_SUBST(MSPLUGINS_LIBS) - -AC_CHECK_LIB(rt,clock_gettime,[LIBS="$LIBS -lrt"]) - -dnl ********************************* -dnl various checks for soundcard apis -dnl ********************************* - -found_sound=no - -if test x$mingw_found = xyes ; then - found_sound=yes -fi - -AC_ARG_ENABLE(oss, - [ --enable-oss Disable oss support], - [case "${enableval}" in - yes) oss=true ;; - no) oss=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-oss) ;; - esac],[oss=true]) - -if "$oss" = "true"; then -AC_CHECK_HEADERS(soundcard.h sys/soundcard.h machine/soundcard.h sys/audio.h) -if test "${ac_cv_header_sys_soundcard_h}" = "yes" || \ - test "${ac_cv_header_soundcard_h}" = "yes" || \ - test "${ac_cv_header_sys_audio_h}" = "yes" || \ - test "${ac_cv_header_machine_soundcard_h}" = "yes"; then - found_sound=yes -else - oss=false -fi -fi - -AM_CONDITIONAL(BUILD_OSS, test x$oss = xtrue) - -dnl conditionnal build of ALSA support -AC_ARG_ENABLE(alsa, - [ --enable-alsa Turn on alsa native support compiling], - [case "${enableval}" in - yes) alsa=true ;; - no) alsa=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-alsa) ;; - esac],[alsa=true]) - -if test "$alsa" = "true"; then - AC_CHECK_HEADERS(alsa/asoundlib.h, - [ AC_CHECK_LIB(asound,snd_pcm_open, - [ ALSA_LIBS="-lasound" - found_sound=yes - AC_DEFINE(__ALSA_ENABLED__,1,[defined if alsa support is available]) - alsa_enabled=true - ]) - ] - ) -fi -AC_SUBST(ALSA_LIBS) - -AM_CONDITIONAL(BUILD_ALSA, test x$alsa_enabled = xtrue) - - -AC_ARG_ENABLE(artsc, - [ --enable-artsc Turn on artsc (kde<4) sound input/output (no) ], - [case "${enableval}" in - yes) artsc=true ;; - no) artsc=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-artsc) ;; - esac],[artsc=no]) - -arts_enabled=false - -if test "$artsc" = "true" ; then - - dnl check for arts (kde sound daemon) support - PKG_CHECK_MODULES(ARTS, [artsc],[ - dnl New detection - arts_enabled=true - ],[ - dnl Old detection - if test x$artsc = xtrue ; then - AC_CHECK_HEADERS(kde/artsc/artsc.h, - [ AC_CHECK_LIB(artsc,arts_init, - [ ARTS_LIBS="-lartsc" - arts_enabled=true - ]) - ] - ) - fi - AC_SUBST(ARTS_LIBS) - ]) -fi - -if test x$arts_enabled = xtrue; then - found_sound=yes - AC_DEFINE(__ARTS_ENABLED__,1,[defined if arts support is available]) -fi - -AM_CONDITIONAL(BUILD_ARTS, test x$arts_enabled = xtrue) - -AC_ARG_ENABLE(portaudio, - [ --enable-portaudio Turn on portaudio native support compiling], - [case "${enableval}" in - yes) portaudio=true ;; - no) portaudio=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-portaudio) ;; - esac],[portaudio=false]) - -if test "$portaudio" = "true"; then - AC_CHECK_HEADERS(portaudio.h, - [ AC_CHECK_LIB(portaudio,Pa_Initialize, - [ PORTAUDIO_LIBS="-lportaudio" - found_sound=yes - AC_DEFINE(__PORTAUDIO_ENABLED__,1,[defined if portaudio support is available]) - portaudio_enabled=true - ]) - ] - ) -fi - -AC_SUBST(PORTAUDIO_LIBS) -AM_CONDITIONAL(BUILD_PORTAUDIO, test x$portaudio_enabled = xtrue) - -AC_ARG_ENABLE(macsnd, - [ --enable-macsnd Turn on native macosx sound support (default=no)], - [case "${enableval}" in - yes) macsnd=true ;; - no) macsnd=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-macsnd) ;; - esac],[macsnd=false]) - -if test "$macsnd" = "true"; then - AC_DEFINE(__MACSND_ENABLED__,1,[defined if native macosx sound support is available]) - macsnd_enabled=true - found_sound=yes -fi - -AM_CONDITIONAL(BUILD_MACSND, test x$macsnd_enabled = xtrue) - -AC_ARG_ENABLE(macaqsnd, - [ --enable-macaqsnd Turn on native macosx Audio Queue sound support (default=yes)], - [case "${enableval}" in - yes) macaqsnd=true ;; - no) macaqsnd=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-macaqsnd) ;; - esac],[macaqsnd=true]) - -if test "$macosx_found" != "yes" ; then - macaqsnd=false -fi - -if test "$macaqsnd" = "true"; then - AC_DEFINE(__MAC_AQ_ENABLED__,1,[defined if native macosx AQ sound support is available]) - found_sound=yes -fi - -AM_CONDITIONAL(BUILD_MACAQSND, test x$macaqsnd = xtrue) - -AC_ARG_ENABLE(jack, - [ --disable-jack Disable jack support], - [case "${enableval}" in - yes) jack=true ;; - no) jack=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-jack) ;; - esac],[jack=true]) - -if test x$jack = xtrue; then - -dnl Check for samplerate libraries -dnl Check for jack libraries (sound output plugin) -PKG_CHECK_MODULES(JACK,jack >= 0.15.0, -[ - dnl we' found jack devel files - PKG_CHECK_MODULES(SAMPLERATE, samplerate >= 0.0.13, - [AC_DEFINE(__JACK_ENABLED__,1,[Jack support]) - found_sound=yes - jack_found=yes] , - [echo "libsamplerate not found, jack support disabled."]) - AC_SUBST(SAMPLERATE_CFLAGS) - AC_SUBST(SAMPLERATE_LIBS) -], -[echo "No jack support."] ) - -if test x$jack_found = xno ; then - dnl reset flags - JACK_CFLAGS= - JACK_LIBS= - SAMPLERATE_CFLAGS= - SAMPLERATE_LIBS= -fi - -AC_SUBST(JACK_CFLAGS) -AC_SUBST(JACK_LIBS) - -fi - -if test "$found_sound" = "no"; then - AC_MSG_WARN([Could not find a support sound driver API]) -fi - - -dnl ************************************* -dnl check for various codecs libraries -dnl ************************************* - -AC_ARG_ENABLE(speex, - [ --disable-speex Disable speex support], - [case "${enableval}" in - yes) speex=true ;; - no) speex=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-speex) ;; - esac],[speex=true]) - -if test x$speex = xtrue; then - -dnl check for installed version of speex -PKG_CHECK_MODULES(SPEEX, speex >= 1.2beta3, - [ AC_DEFINE(HAVE_SPEEX_NOISE,1,[tells whether the noise arg of speex_echo_cancel can be used]) ], - [try_other_speex=yes] -) -PKG_CHECK_MODULES(SPEEX, speex >= 1.2beta3, build_speex=yes) -build_resample=false -PKG_CHECK_MODULES(SPEEXDSP, speexdsp >= 1.2beta3, - [SPEEX_LIBS="$SPEEX_LIBS $SPEEXDSP_LIBS" - AC_DEFINE(HAVE_SPEEXDSP,1,[have speexdsp library]) - build_resample=yes] , - [AC_MSG_NOTICE([No speexdsp library found.]) -] -) -AC_SUBST(SPEEX_CFLAGS) -AC_SUBST(SPEEX_LIBS) - -fi - -AM_CONDITIONAL(BUILD_SPEEX, test x$build_speex = xyes ) -AM_CONDITIONAL(BUILD_RESAMPLE, test x$build_resample = xyes ) - -AC_ARG_ENABLE(gsm, - [ --disable-gsm Disable gsm support], - [case "${enableval}" in - yes) gsm=true ;; - no) gsm=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --disable-gsm) ;; - esac],[gsm=true]) - -if test x$gsm = xtrue; then - -dnl check for gsm -build_gsm=no -AC_ARG_WITH( gsm, - [ --with-gsm Sets the installation prefix of gsm codec library [default=/usr] ], - [ gsmdir=${withval}],[ gsmdir=/usr ]) - -if test x"$gsmdir" != xno ; then - test x"$gmsdir" = xyes && gsmdir=/usr - MS_CHECK_DEP([gsm codec],[GSM],[${gsmdir}/include], - [${gsmdir}/lib],[gsm/gsm.h],[gsm],[gsm_create]) - if test "$GSM_found" = "yes" ; then - build_gsm=yes - fi -else - build_gsm=no -fi - -fi - -AM_CONDITIONAL(BUILD_GSM, test x$build_gsm = xyes ) - -MS_CHECK_VIDEO -AM_CONDITIONAL(BUILD_VIDEO, test "$video" = "true") -AM_CONDITIONAL(BUILD_THEORA, test "$have_theora" = "yes") -AM_CONDITIONAL(BUILD_WIN32, test "$mingw_found" = "yes") -AM_CONDITIONAL(BUILD_WIN32_WCE, test "$mingw32ce_found" = "yes") - -dnl ********************************************* -dnl setup oRTP dependency -dnl ********************************************* -AC_ARG_ENABLE(external-ortp, - [ --enable-external-ortp Use external oRTP library], - [case "${enableval}" in - yes) external_ortp=true ;; - no) external_ortp=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-external-ortp) ;; - esac],[external_ortp=false]) - -if test "$external_ortp" = 'false'; then - if test -e $srcdir/../oRTP/include/ortp/ortp.h ; then - echo "building from linphone source tree, using ../oRTP/include/ortp/ortp.h" - ORTP_CFLAGS="-I\$(top_srcdir)/../oRTP/include" - ORTP_LIBS="\$(top_builddir)/../oRTP/src/libortp.la" - if test x$ac_cv_c_bigendian = xyes ; then - ORTP_CFLAGS="$ORTP_CFLAGS -DORTP_BIGENDIAN" - fi - else - external_ortp=true - fi -fi -if test "$external_ortp" = 'true'; then - PKG_CHECK_MODULES(ORTP, ortp >= 0.9.0, , - [ AC_MSG_ERROR([Couldn't find ortp library]) ] ) -fi -AC_SUBST(ORTP_CFLAGS) -AC_SUBST(ORTP_LIBS) - - -dnl check dlopen support in headers and libraries, so that we can use mediastreamer plugins -AC_CHECK_HEADERS(dlfcn.h) -have_dlopen=false -AC_CHECK_LIB(dl,dlopen,[LIBS="$LIBS -ldl"; have_dlopen=true]) -AC_CHECK_FUNC(dlopen,[have_dlopen=true]) -if test "$have_dlopen" = "true" ; then - AC_DEFINE(HAVE_DLOPEN,1,[Defined if dlopen() is availlable]) -fi - -dnl check various things -AC_FUNC_ALLOCA - -if test "x${prefix}" = "xNONE"; then - package_prefix=${ac_default_prefix} -else - package_prefix=${prefix} -fi - -if test x$mingw_found = xyes ; then - package_prefix="." -fi - -dnl define path of plugins: -AC_DEFINE_UNQUOTED(PACKAGE_PLUGINS_DIR, "${package_prefix}/lib/mediastreamer/plugins" ,[path of plugins]) -PACKAGE_PLUGINS_DIR="${package_prefix}/lib/mediastreamer/plugins" -AC_SUBST(PACKAGE_PLUGINS_DIR) - -PACKAGE_DATA_DIR="$prefix/share" -AC_DEFINE_UNQUOTED(PACKAGE_DATA_DIR, "${package_prefix}/share" ,[path of data]) -AC_SUBST(PACKAGE_DATA_DIR) - -dnl check for video4linux headers -AC_CHECK_HEADERS(linux/videodev.h linux/videodev2.h) -if test "${ac_cv_header_linux_videodev_h}" = "yes" || \ - test "${ac_cv_header_linux_videodev2_h}" = "yes" ; then - found_v4l=yes -else - found_v4l=no -fi - -AM_CONDITIONAL(BUILD_V4L, test x$found_v4l = xyes ) - -PKG_CHECK_MODULES(LIBV4L2, libv4l2, - [AC_DEFINE(HAVE_LIBV4L2,1,[Defined if we have libv4l2])] - ,[echo "No libv4l2 found."] -) -PKG_CHECK_MODULES(LIBV4L1, libv4l1, - [AC_DEFINE(HAVE_LIBV4L1,1,[Defined if we have libv4l1])] - ,[echo "No libv4l1 found."] -) - -dnl ################################################## -dnl # Check for doxygen -dnl ################################################## - -AC_PATH_PROG(DOXYGEN,doxygen,false) -AM_CONDITIONAL(HAVE_DOXYGEN, test $DOXYGEN != false) - - -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 mediastreaming library." -AC_SUBST(SUMMARY) -PACKAGER=anonymous -AC_SUBST(PACKAGER) -LICENSE=GPL -AC_SUBST(LICENSE) -VENDOR=Linphone -AC_SUBST(VENDOR) -RELEASE=1 -AC_SUBST(RELEASE) - -CFLAGS="$CFLAGS $MS_PUBLIC_CFLAGS" -CXXFLAGS="$CXXFLAGS $MS_PUBLIC_CFLAGS" -dnl: these ones gets exported in pkgconfig file. -AC_SUBST(MS_PUBLIC_CFLAGS) - -AC_OUTPUT( -Makefile -include/Makefile -include/mediastreamer2/Makefile -src/Makefile -tests/Makefile -build/Makefile -build/win32native/Makefile -build/win32-novideo/Makefile -build/wince/Makefile -build/winmob/Makefile -mediastreamer.pc -mediastreamer2.spec -help/Makefile -help/Doxyfile -help/doxygen.dox -) diff --git a/linphone/mediastreamer2/help/.gitignore b/linphone/mediastreamer2/help/.gitignore deleted file mode 100644 index 8d4b209b9..000000000 --- a/linphone/mediastreamer2/help/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Doxyfile -doxygen.dox diff --git a/linphone/mediastreamer2/help/Doxyfile.in b/linphone/mediastreamer2/help/Doxyfile.in deleted file mode 100644 index 1c7f5b41c..000000000 --- a/linphone/mediastreamer2/help/Doxyfile.in +++ /dev/null @@ -1,234 +0,0 @@ -# Doxyfile 1.4.1 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = mediastreamer2 -PROJECT_NUMBER = @MEDIASTREAMER_VERSION@ -OUTPUT_DIRECTORY = doc -CREATE_SUBDIRS = NO -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = NO -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = NO -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = YES -OPTIMIZE_OUTPUT_JAVA = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = YES -HIDE_UNDOC_CLASSES = YES -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = NO -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = YES -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = . \ - ../include/ \ - ../src -FILE_PATTERNS = *.h \ - *.c \ - *.dox -RECURSIVE = YES -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXAMPLE_PATH = ../ -EXAMPLE_PATTERNS = -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -VERBATIM_HEADERS = NO -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 1 -GENERATE_TREEVIEW = NO -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = YES -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = YES -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = ../include/mediastreamer2 -INCLUDE_FILE_PATTERNS = *.h -PREDEFINED = DOXYGEN -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = YES -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 1000 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/linphone/mediastreamer2/help/Makefile.am b/linphone/mediastreamer2/help/Makefile.am deleted file mode 100644 index fdc5bb258..000000000 --- a/linphone/mediastreamer2/help/Makefile.am +++ /dev/null @@ -1,32 +0,0 @@ - -EXTRA_DIST = Doxyfile.in doxygen.dox.in - -#html doc -if HAVE_DOXYGEN - -SOURCES=$(top_srcdir)/include/mediastreamer2/*.h $(top_srcdir)/src/*.c $(top_srcdir)/src/*.h - -# doxdir & pkgdocdir are not always defined by automake -docdir=$(datadir)/doc -pkgdocdir=$(docdir)/$(PACKAGE)-$(VERSION) -doc_htmldir=$(pkgdocdir)/html - -doc_html_DATA = $(top_builddir)/help/doc/html/html.tar - -$(doc_html_DATA): $(top_builddir)/help/doc/html/index.html - cd $(. - * - * @section definitions Some definitions. - * - * Filter: - * A filter is a mediastreamer2 component that process data. A filter - * have 0 or several INPUT pins and 0 or several OUTPUT pins. - * Here is a list of possible use of filters: - *
- *   capture audio or video data.
- *   play audio or display video data.
- *   send or receive RTP data.
- *   encode or decode audio or video data.
- *   transform (resize video, resample audio...) data.
- *   duplicate any kind of data.
- *   mix audio/video data.
- * 
- * Graph: - * A graph is a manager of filters connected together. It will transfer - * data from OUTPUT pins to INPUT pins and will be responsible for - * running filters. - * - * @section when_do_i_use_mediastreamer2 How do I use mediastremer2? - * - * Mediastreamer2 can be used for a lot of different purpose. The primary - * use is to manage RTP audio and video session. You will need to use - * the API to build filters, link them together in a graph. Then the - * ticker API will help you to start and stop the graph. - * - * Basic graph sample: - * - *
- *  AUDIO CAPTURE   -->   ENCODE  -->     RTP
- *      FILTER      -->   FILTER  -->    FILTER
- * 
- * - * - * The above graph is composed of three filters. The first one has no input: - * tt captures audio data directly from the drivers and provide it to the - * OUTPUT pin. This data is sent to the INPUT pin of the encoder which of - * course encode the data and send it to its OUTPUT pin. This pin is connected - * to the INPUT pin of a filter capable to build and send RTP packets. - * - * The modular design helps you to encode in many different format just by - * replacing the "ENCODE FILTER" with another one. mediastreamer2 contains - * internal support for g711u, g711a, speex and gsm. You can add new encoding - * format by implementing new filters which can then be dynamically loaded. - * - * @section list_of_filters List of existing filters. - * - * mediastreamer2 already provides a large set of filters. Here is a complete - * list of built-in filters. - * - *
- * All supported platforms:
- *   RTP receiver
- *   RTP sender
- *   tee (duplicate data)
- *
- * Audio Filters:
- *   audio capture
- *   audio playback
- *     mme API (windows)
- *     alsa API (linux)
- *     oss API (linux)
- *     arts API (linux)
- *     portaudio API (macosx and other)
- *   macsnd API (native macosx API -please do more testing...-)
- *   several audio encoder/decoder: PCMU, PCMA, speex, gsm
- *   wav file reader.
- *   wav file recorder.
- *   resampler.
- *   conference bridge.
- *   volume analyser.
- *   acoustic echo canceller.
- *   dtmf generation filter.
- *
- * Video Filters:
- *   video capture
- *     v4w API (windows)
- *     directshow API (windows)
- *     video4linux API (linux)
- *   video display
- *     v4w API (windows)
- *     SDL API (linux, macosx...)
- *   several audio encoder/decoder: H263-1998, MP4V-ES, theora
- *   image resizer.
- *   format converter. (RBG24, I420...)
- *
- * Plugin Filters:
- *  iLBC decoder/encoder.
- * 
- * - * @section what_thanks Thanks - * - * Thanks to all the contributors and to all bug reporters. - * Enjoy mediastreamer2! - * - */ - -/** - * @defgroup mediastreamer2_api Mediastreamer2 API - * @brief All API to manage mediastreamer2 library. - * - */ - -/** - * @defgroup mediastreamer2_init Init API - manage mediastreamer2 library. - * @ingroup mediastreamer2_api - * @brief Init API to manage mediastreamer2 library. - * - * This file provide the API needed to initialize - * and reset the mediastreamer2 library. - */ - -/** - * @defgroup mediastreamer2_soundcard Sound Card API - manage audio capture/play filters. - * @ingroup mediastreamer2_api - * @brief Sound Card API to manage audio capture/play filters. - * - * This file provide the API needed to manage - * soundcard filters. - */ - -/** - * @defgroup mediastreamer2_filter Filter API - manage mediastreamer2 filters. - * @ingroup mediastreamer2_api - * @brief Filter API to manage mediastreamer2 filters. - * - * This file provide the API needed to create, link, - * unlink, find and destroy filter. - * - * It also provides definitions if you wish to implement - * your own filters. - */ - -/** - * @defgroup mediastreamer2_ticker Ticker API - manage mediastreamer2 graphs. - * @ingroup mediastreamer2_api - * @brief Ticker API to manage mediastreamer2 graphs. - * - * This file provide the API needed to create, start - * and stop a graph. - */ - - -/** - * @page mediastreamer2_readme README - * @verbinclude README - */ - -/** - * @page mediastreamer2_install INSTALL - * @verbinclude INSTALL - */ - -/** - * @page mediastreamer2_license COPYING - * @verbinclude COPYING - */ - -/** - * @page mediastreamer2_changelog ChangeLog - * @verbinclude ChangeLog - */ - diff --git a/linphone/mediastreamer2/help/ht0-buildagraph.dox b/linphone/mediastreamer2/help/ht0-buildagraph.dox deleted file mode 100644 index 9acc3b0e5..000000000 --- a/linphone/mediastreamer2/help/ht0-buildagraph.dox +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @defgroup howto0_samplegraph Howto 1: build a sample audio graph. - * @ingroup mediastreamer2 - -

Initialize mediastreamer2

- -When using mediastreamer2, your first task is to initialize the -library: - -
-	##include 
-
-	int i;
-
-	i=ms_init();
-	if (i!=0)
-	  return -1;
-
-
- -Mediastreamer2 provides internal components which are called filters. Those -filters must be linked together so that OUTPUT from one filter is sent to -INPUT of the other filters. - -Usually, filters are used for processing audio or video data. They could -capture data, play/draw data, encode/decode data, mix data (conference), -transform data (echo canceller). One of the most important filter is the -RTP filters that are able to send and receive RTP data. - -

Graph sample

- -If you are using mediastreamer2, you probably want to do Voice Over IP -and get a graph providing a 2 way communication. This 2 graphs are very -simple: - -This first graph shows the filters needed to capture data from a sound -card, encode them and send it through an RTP session. - -
-             AUDIO    ->    ENCODER   ->   RTP
-            CAPTURE   ->              ->  SENDER
-
- - This second graph shows the filters needed to receive data from an RTP -session decode it and send it to the playback device. - -
-        RTP      ->    DECODER   ->   DTMF       ->   AUDIO
-       RECEIVER  ->              ->  GENERATION  ->  PLAYBACK
-
- -

Code to initiate the filters of the Graph sample

- -Note that the NULL/error checks are not done for better reading. -To build the graph, you'll need some information: you need to -select the sound card and of course have an RTP session created -with oRTP. - -
-	MSSndCard *sndcard;
-	sndcard=ms_snd_card_manager_get_default_card(ms_snd_card_manager_get());
-
-        /* audio capture filter */
-	MSFilter *soundread=ms_snd_card_create_reader(captcard);
-	MSFilter *soundwrite=ms_snd_card_create_writer(playcard);
-
-	MSFilter *encoder=ms_filter_create_encoder("PCMU");
-	MSFilter *decoder=ms_filter_create_decoder("PCMU");
-
-	MSFilter *rtpsend=ms_filter_new(MS_RTP_SEND_ID);
-	MSFilter *rtprecv=ms_filter_new(MS_RTP_RECV_ID);
-
-	RtpSession *rtp_session = *** your_ortp_session *** ;
-
-	ms_filter_call_method(rtpsend,MS_RTP_SEND_SET_SESSION,rtp_session);
-	ms_filter_call_method(rtprecv,MS_RTP_RECV_SET_SESSION,rtp_session);
-
-	MSFilter *dtmfgen=ms_filter_new(MS_DTMF_GEN_ID);
-
- -In most cases, the above graph is not enough: you'll need to configure -filter's options. As an example, you need to set sampling rate of sound -cards' filters: - -
-        int sr = 8000;
-	int chan=1;
-	ms_filter_call_method(soundread,MS_FILTER_SET_SAMPLE_RATE,&sr);
-	ms_filter_call_method(soundwrite,MS_FILTER_SET_SAMPLE_RATE,&sr);
-	ms_filter_call_method(stream->encoder,MS_FILTER_SET_SAMPLE_RATE,&sr);
-	ms_filter_call_method(stream->decoder,MS_FILTER_SET_SAMPLE_RATE,&sr);
-
-	ms_filter_call_method(soundwrite,MS_FILTER_SET_NCHANNELS, &chan);
-
-        /* if you have some fmtp parameters (from SDP for example!)
-        char *fmtp1 = ** get your fmtp line **;
-        char *fmtp2 = ** get your fmtp line **;
-	ms_filter_call_method(stream->encoder,MS_FILTER_ADD_FMTP, (void*)fmtp1);
-	ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)fmtp2);
-
- - -

Code to link the filters and run the graph sample

- -
-	ms_filter_link(stream->soundread,0,stream->encoder,0);
-	ms_filter_link(stream->encoder,0,stream->rtpsend,0);
-
-	ms_filter_link(stream->rtprecv,0,stream->decoder,0);
-	ms_filter_link(stream->decoder,0,stream->dtmfgen,0);
-	ms_filter_link(stream->dtmfgen,0,stream->soundwrite,0);	
-
- -Then you need to 'attach' the filters to a ticker. A ticker is a graph -manager responsible for running filters. - -In the above case, there is 2 independant graph within the ticker: you -need to attach the first element of each graph (the one that does not -contains any INPUT pins) - -
-	/* create ticker */
-	MSTicker *ticker=ms_ticker_new();
-
-	ms_ticker_attach(ticker,soundread);
-	ms_ticker_attach(ticker,rtprecv);
-
- -

Code to unlink the filters and stop the graph sample

- -
-	ms_ticker_detach(ticker,soundread);
-	ms_ticker_detach(ticker,rtprecv);
-
-	ms_filter_unlink(stream->soundread,0,stream->encoder,0);
-	ms_filter_unlink(stream->encoder,0,stream->rtpsend,0);
-
-	ms_filter_unlink(stream->rtprecv,0,stream->decoder,0);
-	ms_filter_unlink(stream->decoder,0,stream->dtmfgen,0);
-	ms_filter_unlink(stream->dtmfgen,0,stream->soundwrite,0);
-
-	if (rtp_session!=NULL) rtp_session_destroy(rtp_session);
-	if (rtpsend!=NULL) ms_filter_destroy(rtpsend);
-	if (rtprecv!=NULL) ms_filter_destroy(rtprecv);
-	if (soundread!=NULL) ms_filter_destroy(soundread);
-	if (soundwrite!=NULL) ms_filter_destroy(soundwrite);
-	if (encoder!=NULL) ms_filter_destroy(encoder);
-	if (decoder!=NULL) ms_filter_destroy(decoder);
-	if (dtmfgen!=NULL) ms_filter_destroy(dtmfgen);
-	if (ticker!=NULL) ms_ticker_destroy(ticker);
-
- -*/ \ No newline at end of file diff --git a/linphone/mediastreamer2/include/.gitignore b/linphone/mediastreamer2/include/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/mediastreamer2/include/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/mediastreamer2/include/Makefile.am b/linphone/mediastreamer2/include/Makefile.am deleted file mode 100644 index c7b5d9316..000000000 --- a/linphone/mediastreamer2/include/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS=mediastreamer2 diff --git a/linphone/mediastreamer2/include/mediastreamer2/.gitignore b/linphone/mediastreamer2/include/mediastreamer2/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/mediastreamer2/include/mediastreamer2/Makefile.am b/linphone/mediastreamer2/include/mediastreamer2/Makefile.am deleted file mode 100644 index 74673ce14..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/Makefile.am +++ /dev/null @@ -1,29 +0,0 @@ - -mediastreamer2_includedir=$(includedir)/mediastreamer2 - -mediastreamer2_include_HEADERS= ice.h \ - msfilter.h \ - msqueue.h \ - mscommon.h \ - allfilters.h \ - msticker.h \ - msrtp.h \ - dtmfgen.h \ - msfilerec.h \ - msfileplayer.h \ - mssndcard.h \ - mediastream.h \ - msv4l.h \ - msvideo.h \ - waveheader.h \ - msvideoout.h \ - msvolume.h \ - mstee.h \ - rfc3984.h \ - mswebcam.h \ - dsptools.h \ - msequalizer.h \ - msspeexec.h - -EXTRA_DIST=$(mediastreamer2_include_HEADERS) - diff --git a/linphone/mediastreamer2/include/mediastreamer2/allfilters.h b/linphone/mediastreamer2/include/mediastreamer2/allfilters.h deleted file mode 100644 index eb6440506..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/allfilters.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef allfilters_h -#define allfilters_h - -/* this is the enum where to add your own filter id. -Please take care of always add new IDs at the end in order to preserve the binary interface*/ -/*this id is used for type checking of methods, events with filters */ -/*it must be used also to create filters */ -typedef enum MSFilterId{ - MS_FILTER_NOT_SET_ID, - MS_FILTER_PLUGIN_ID, /* no type checking will be performed on plugins */ - MS_FILTER_BASE_ID, - MS_ALSA_READ_ID, - MS_ALSA_WRITE_ID, - MS_OSS_READ_ID, - MS_OSS_WRITE_ID, - MS_ULAW_ENC_ID, - MS_ULAW_DEC_ID, - MS_ALAW_ENC_ID, - MS_ALAW_DEC_ID, - MS_RTP_SEND_ID, - MS_RTP_RECV_ID, - MS_FILE_PLAYER_ID, - MS_FILE_REC_ID, - MS_DTMF_GEN_ID, - MS_SPEEX_ENC_ID, - MS_SPEEX_DEC_ID, - MS_GSM_ENC_ID, - MS_GSM_DEC_ID, - MS_V4L_ID, - MS_SDL_OUT_ID, - MS_H263_ENC_ID, - MS_H263_DEC_ID, - MS_ARTS_READ_ID, - MS_ARTS_WRITE_ID, - MS_WINSND_READ_ID, - MS_WINSND_WRITE_ID, - MS_SPEEX_EC_ID, - MS_PIX_CONV_ID, - MS_TEE_ID, - MS_SIZE_CONV_ID, - MS_CONF_ID, - MS_THEORA_ENC_ID, - MS_THEORA_DEC_ID, - MS_PASND_READ_ID, - MS_PASND_WRITE_ID, - MS_MPEG4_ENC_ID, - MS_MPEG4_DEC_ID, - MS_MJPEG_DEC_ID, - MS_JOIN_ID, - MS_RESAMPLE_ID, - MS_VIDEO_OUT_ID, - MS_VOLUME_ID, - MS_SNOW_DEC_ID, - MS_SNOW_ENC_ID, - MS_CA_READ_ID, - MS_CA_WRITE_ID, - MS_WINSNDDS_READ_ID, - MS_WINSNDDS_WRITE_ID, - MS_STATIC_IMAGE_ID, - MS_V4L2_CAPTURE_ID, - MS_H263_OLD_DEC_ID, - MS_H263_OLD_ENC_ID, - MS_MIRE_ID, - MS_VFW_ID, - MS_ICE_ID, - MS_VOID_SINK_ID, - MS_DSCAP_ID, - MS_AQ_READ_ID, - MS_AQ_WRITE_ID, - MS_EQUALIZER_ID, - MS_JPEG_DEC_ID, - MS_JPEG_ENC_ID, -} MSFilterId; - - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/dsptools.h b/linphone/mediastreamer2/include/mediastreamer2/dsptools.h deleted file mode 100644 index 711e075b7..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/dsptools.h +++ /dev/null @@ -1,388 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2009 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. -*/ -/* This file contains useful DSP routines from the speex project. -*/ - -/* Copyright (C) 2002-2006 Jean-Marc Valin - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - Neither the name of the Xiph.org Foundation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 FOUNDATION 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. -*/ - -#ifndef ms_dsptools_h -#define ms_dsptools_h - -#include - -typedef int32_t ms_int32_t; - -#ifdef MS_FIXED_POINT - -typedef short ms_word16_t; -typedef int ms_word32_t; -typedef int ms_mem_t; -typedef short ms_coef_t; - -#define QCONST16(x,bits) ((ms_word16_t)(.5+(x)*(((ms_word32_t)1)<<(bits)))) -#define QCONST32(x,bits) ((ms_word32_t)(.5+(x)*(((ms_word32_t)1)<<(bits)))) - -#define NEG16(x) (-(x)) -#define NEG32(x) (-(x)) -#define EXTRACT16(x) ((ms_word16_t)(x)) -#define EXTEND32(x) ((ms_word32_t)(x)) -#define SHR16(a,shift) ((a) >> (shift)) -#define SHL16(a,shift) ((a) << (shift)) -#define SHR32(a,shift) ((a) >> (shift)) -#define SHL32(a,shift) ((a) << (shift)) -#define PSHR16(a,shift) (SHR16((a)+((1<<((shift))>>1)),shift)) -#define PSHR32(a,shift) (SHR32((a)+((EXTEND32(1)<<((shift))>>1)),shift)) -#define VSHR32(a, shift) (((shift)>0) ? SHR32(a, shift) : SHL32(a, -(shift))) -#define SATURATE16(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) -#define SATURATE32(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) - -#define SHR(a,shift) ((a) >> (shift)) -#define SHL(a,shift) ((ms_word32_t)(a) << (shift)) -#define PSHR(a,shift) (SHR((a)+((EXTEND32(1)<<((shift))>>1)),shift)) -#define SATURATE(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) - - -#define ADD16(a,b) ((ms_word16_t)((ms_word16_t)(a)+(ms_word16_t)(b))) -#define SUB16(a,b) ((ms_word16_t)(a)-(ms_word16_t)(b)) -#define ADD32(a,b) ((ms_word32_t)(a)+(ms_word32_t)(b)) -#define SUB32(a,b) ((ms_word32_t)(a)-(ms_word32_t)(b)) - - -/* result fits in 16 bits */ -#define MULT16_16_16(a,b) ((((ms_word16_t)(a))*((ms_word16_t)(b)))) - -/* (ms_word32_t)(ms_word16_t) gives TI compiler a hint that it's 16x16->32 multiply */ -#define MULT16_16(a,b) (((ms_word32_t)(ms_word16_t)(a))*((ms_word32_t)(ms_word16_t)(b))) - -#define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b)))) -#define MULT16_32_Q12(a,b) ADD32(MULT16_16((a),SHR((b),12)), SHR(MULT16_16((a),((b)&0x00000fff)),12)) -#define MULT16_32_Q13(a,b) ADD32(MULT16_16((a),SHR((b),13)), SHR(MULT16_16((a),((b)&0x00001fff)),13)) -#define MULT16_32_Q14(a,b) ADD32(MULT16_16((a),SHR((b),14)), SHR(MULT16_16((a),((b)&0x00003fff)),14)) - -#define MULT16_32_Q11(a,b) ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11)) -#define MAC16_32_Q11(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11))) - -#define MULT16_32_P15(a,b) ADD32(MULT16_16((a),SHR((b),15)), PSHR(MULT16_16((a),((b)&0x00007fff)),15)) -#define MULT16_32_Q15(a,b) ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15)) -#define MAC16_32_Q15(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15))) - - -#define MAC16_16_Q11(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),11))) -#define MAC16_16_Q13(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),13))) -#define MAC16_16_P13(c,a,b) (ADD32((c),SHR(ADD32(4096,MULT16_16((a),(b))),13))) - -#define MULT16_16_Q11_32(a,b) (SHR(MULT16_16((a),(b)),11)) -#define MULT16_16_Q13(a,b) (SHR(MULT16_16((a),(b)),13)) -#define MULT16_16_Q14(a,b) (SHR(MULT16_16((a),(b)),14)) -#define MULT16_16_Q15(a,b) (SHR(MULT16_16((a),(b)),15)) - -#define MULT16_16_P13(a,b) (SHR(ADD32(4096,MULT16_16((a),(b))),13)) -#define MULT16_16_P14(a,b) (SHR(ADD32(8192,MULT16_16((a),(b))),14)) -#define MULT16_16_P15(a,b) (SHR(ADD32(16384,MULT16_16((a),(b))),15)) - -#define MUL_16_32_R15(a,bh,bl) ADD32(MULT16_16((a),(bh)), SHR(MULT16_16((a),(bl)),15)) - -#define DIV32_16(a,b) ((ms_word16_t)(((ms_word32_t)(a))/((ms_word16_t)(b)))) -#define PDIV32_16(a,b) ((ms_word16_t)(((ms_word32_t)(a)+((ms_word16_t)(b)>>1))/((ms_word16_t)(b)))) -#define DIV32(a,b) (((ms_word32_t)(a))/((ms_word32_t)(b))) -#define PDIV32(a,b) (((ms_word32_t)(a)+((ms_word16_t)(b)>>1))/((ms_word32_t)(b))) - -#ifdef ARM5E_ASM -#error "Fix me" -#elif defined (ARM4_ASM) -#error "Fix me" -#elif defined (BFIN_ASM) - -#undef PDIV32_16 -static inline ms_word16_t PDIV32_16(ms_word32_t a, ms_word16_t b) -{ - ms_word32_t res, bb; - bb = b; - a += b>>1; - __asm__ ( - "P0 = 15;\n\t" - "R0 = %1;\n\t" - "R1 = %2;\n\t" - //"R0 = R0 + R1;\n\t" - "R0 <<= 1;\n\t" - "DIVS (R0, R1);\n\t" - "LOOP divide%= LC0 = P0;\n\t" - "LOOP_BEGIN divide%=;\n\t" - "DIVQ (R0, R1);\n\t" - "LOOP_END divide%=;\n\t" - "R0 = R0.L;\n\t" - "%0 = R0;\n\t" - : "=m" (res) - : "m" (a), "m" (bb) - : "P0", "R0", "R1", "cc"); - return res; -} - -#undef DIV32_16 -static inline ms_word16_t DIV32_16(ms_word32_t a, ms_word16_t b) -{ - ms_word32_t res, bb; - bb = b; - /* Make the roundinf consistent with the C version - (do we need to do that?)*/ - if (a<0) - a += (b-1); - __asm__ ( - "P0 = 15;\n\t" - "R0 = %1;\n\t" - "R1 = %2;\n\t" - "R0 <<= 1;\n\t" - "DIVS (R0, R1);\n\t" - "LOOP divide%= LC0 = P0;\n\t" - "LOOP_BEGIN divide%=;\n\t" - "DIVQ (R0, R1);\n\t" - "LOOP_END divide%=;\n\t" - "R0 = R0.L;\n\t" - "%0 = R0;\n\t" - : "=m" (res) - : "m" (a), "m" (bb) - : "P0", "R0", "R1", "cc"); - return res; -} - -#undef MAX16 -static inline ms_word16_t MAX16(ms_word16_t a, ms_word16_t b) -{ - ms_word32_t res; - __asm__ ( - "%1 = %1.L (X);\n\t" - "%2 = %2.L (X);\n\t" - "%0 = MAX(%1,%2);" - : "=d" (res) - : "%d" (a), "d" (b) - ); - return res; -} - -#undef MULT16_32_Q15 -static inline ms_word32_t MULT16_32_Q15(ms_word16_t a, ms_word32_t b) -{ - ms_word32_t res; - __asm__ - ( - "A1 = %2.L*%1.L (M);\n\t" - "A1 = A1 >>> 15;\n\t" - "%0 = (A1 += %2.L*%1.H) ;\n\t" - : "=&W" (res), "=&d" (b) - : "d" (a), "1" (b) - : "A1" - ); - return res; -} - -#undef MAC16_32_Q15 -static inline ms_word32_t MAC16_32_Q15(ms_word32_t c, ms_word16_t a, ms_word32_t b) -{ - ms_word32_t res; - __asm__ - ( - "A1 = %2.L*%1.L (M);\n\t" - "A1 = A1 >>> 15;\n\t" - "%0 = (A1 += %2.L*%1.H);\n\t" - "%0 = %0 + %4;\n\t" - : "=&W" (res), "=&d" (b) - : "d" (a), "1" (b), "d" (c) - : "A1" - ); - return res; -} - -#undef MULT16_32_Q14 -static inline ms_word32_t MULT16_32_Q14(ms_word16_t a, ms_word32_t b) -{ - ms_word32_t res; - __asm__ - ( - "%2 <<= 1;\n\t" - "A1 = %1.L*%2.L (M);\n\t" - "A1 = A1 >>> 15;\n\t" - "%0 = (A1 += %1.L*%2.H);\n\t" - : "=W" (res), "=d" (a), "=d" (b) - : "1" (a), "2" (b) - : "A1" - ); - return res; -} - -#undef MAC16_32_Q14 -static inline ms_word32_t MAC16_32_Q14(ms_word32_t c, ms_word16_t a, ms_word32_t b) -{ - ms_word32_t res; - __asm__ - ( - "%1 <<= 1;\n\t" - "A1 = %2.L*%1.L (M);\n\t" - "A1 = A1 >>> 15;\n\t" - "%0 = (A1 += %2.L*%1.H);\n\t" - "%0 = %0 + %4;\n\t" - : "=&W" (res), "=&d" (b) - : "d" (a), "1" (b), "d" (c) - : "A1" - ); - return res; -} - - - -#endif - - - -#else - -typedef float ms_mem_t; -typedef float ms_coef_t; -typedef float ms_lsp_t; -typedef float ms_sig_t; -typedef float ms_word16_t; -typedef float ms_word32_t; - -#define Q15ONE 1.0f -#define LPC_SCALING 1.f -#define SIG_SCALING 1.f -#define LSP_SCALING 1.f -#define GAMMA_SCALING 1.f -#define GAIN_SCALING 1.f -#define GAIN_SCALING_1 1.f - - -#define VERY_SMALL 1e-15f -#define VERY_LARGE32 1e15f -#define VERY_LARGE16 1e15f -#define Q15_ONE ((ms_word16_t)1.f) - -#define QCONST16(x,bits) (x) -#define QCONST32(x,bits) (x) - -#define NEG16(x) (-(x)) -#define NEG32(x) (-(x)) -#define EXTRACT16(x) (x) -#define EXTEND32(x) (x) -#define SHR16(a,shift) (a) -#define SHL16(a,shift) (a) -#define SHR32(a,shift) (a) -#define SHL32(a,shift) (a) -#define PSHR16(a,shift) (a) -#define PSHR32(a,shift) (a) -#define VSHR32(a,shift) (a) -#define SATURATE16(x,a) (x) -#define SATURATE32(x,a) (x) - -#define PSHR(a,shift) (a) -#define SHR(a,shift) (a) -#define SHL(a,shift) (a) -#define SATURATE(x,a) (x) - -#define ADD16(a,b) ((a)+(b)) -#define SUB16(a,b) ((a)-(b)) -#define ADD32(a,b) ((a)+(b)) -#define SUB32(a,b) ((a)-(b)) -#define MULT16_16_16(a,b) ((a)*(b)) -#define MULT16_16(a,b) ((ms_word32_t)(a)*(ms_word32_t)(b)) -#define MAC16_16(c,a,b) ((c)+(ms_word32_t)(a)*(ms_word32_t)(b)) - -#define MULT16_32_Q11(a,b) ((a)*(b)) -#define MULT16_32_Q13(a,b) ((a)*(b)) -#define MULT16_32_Q14(a,b) ((a)*(b)) -#define MULT16_32_Q15(a,b) ((a)*(b)) -#define MULT16_32_P15(a,b) ((a)*(b)) - -#define MAC16_32_Q11(c,a,b) ((c)+(a)*(b)) -#define MAC16_32_Q15(c,a,b) ((c)+(a)*(b)) - -#define MAC16_16_Q11(c,a,b) ((c)+(a)*(b)) -#define MAC16_16_Q13(c,a,b) ((c)+(a)*(b)) -#define MAC16_16_P13(c,a,b) ((c)+(a)*(b)) -#define MULT16_16_Q11_32(a,b) ((a)*(b)) -#define MULT16_16_Q13(a,b) ((a)*(b)) -#define MULT16_16_Q14(a,b) ((a)*(b)) -#define MULT16_16_Q15(a,b) ((a)*(b)) -#define MULT16_16_P15(a,b) ((a)*(b)) -#define MULT16_16_P13(a,b) ((a)*(b)) -#define MULT16_16_P14(a,b) ((a)*(b)) - -#define DIV32_16(a,b) (((ms_word32_t)(a))/(ms_word16_t)(b)) -#define PDIV32_16(a,b) (((ms_word32_t)(a))/(ms_word16_t)(b)) -#define DIV32(a,b) (((ms_word32_t)(a))/(ms_word32_t)(b)) -#define PDIV32(a,b) (((ms_word32_t)(a))/(ms_word32_t)(b)) - - -#endif - -#define MIN16(a,b) ((a) < (b) ? (a) : (b)) /**< Maximum 16-bit value. */ - -#ifdef __cplusplus -extern "C"{ -#endif - -/*abstraction layer over kiss fft, taken from speex as well*/ - -/** Compute tables for an FFT */ -void *ms_fft_init(int size); - -/** Destroy tables for an FFT */ -void ms_fft_destroy(void *table); - -/** Forward (real to half-complex) transform */ -void ms_fft(void *table, ms_word16_t *in, ms_word16_t *out); - -/** Backward (half-complex to real) transform */ -void ms_ifft(void *table, ms_word16_t *in, ms_word16_t *out); - -/** digital filtering api*/ -void ms_fir_mem16(const ms_word16_t *x, const ms_coef_t *num, ms_word16_t *y, int N, int ord, ms_mem_t *mem); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/dtmfgen.h b/linphone/mediastreamer2/include/mediastreamer2/dtmfgen.h deleted file mode 100644 index 0ea4b930d..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/dtmfgen.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef dtmfgen_h -#define dtmfgen_h - -#include "msfilter.h" - -#define MS_DTMF_GEN_PUT MS_FILTER_METHOD(MS_DTMF_GEN_ID,0,const char) - -extern MSFilterDesc ms_dtmf_gen_desc; - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/ice.h b/linphone/mediastreamer2/include/mediastreamer2/ice.h deleted file mode 100644 index df986c8c8..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/ice.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef ice_hh -#define ice_hh - -#include "msfilter.h" -#include "ortp/stun_udp.h" -#include "ortp/stun.h" -#include "ortp/ortp.h" - -/* list of state for STUN connectivity check */ -#define ICE_PRUNED -1 -#define ICE_FROZEN 0 -#define ICE_WAITING 1 -#define ICE_IN_PROGRESS 2 /* STUN request was sent */ -#define ICE_SUCCEEDED 3 -#define ICE_FAILED 4 /* no answer or unrecoverable failure */ - - -struct SdpCandidate { - /* mandatory attributes: draft 19 */ - int foundation; - int component_id; - char transport[20]; - int priority; - char conn_addr[64]; - int conn_port; - char cand_type[20]; - char rel_addr[64]; - int rel_port; - - /* optionnal attributes: draft 19 */ - char extension_attr[512]; /* *(SP extension-att-name SP extension-att-value) */ -}; - -struct CandidatePair { - - struct SdpCandidate local_candidate; - struct SdpCandidate remote_candidate; - long long pair_priority; - /* additionnal information */ - int rem_controlling; - UInt96 tid; - int connectivity_check; - int retransmission_number; - uint64_t retransmission_time; - int nominated_pair; -}; - -#define MAX_ICE_CANDIDATES 10 - -struct IceCheckList { - struct CandidatePair cand_pairs[MAX_ICE_CANDIDATES]; - int nominated_pair_index; - - char loc_ice_ufrag[256]; - char loc_ice_pwd[256]; - char rem_ice_ufrag[256]; - char rem_ice_pwd[256]; - - int rem_controlling; - uint64_t tiebreak_value; - -#define ICE_CL_RUNNING 0 -#define ICE_CL_COMPLETED 1 -#define ICE_CL_FAILED 2 - int state; - - int RTO; - int Ta; - uint64_t keepalive_time; -}; - -#define MS_ICE_SET_SESSION MS_FILTER_METHOD(MS_ICE_ID,0,RtpSession*) -#define MS_ICE_SET_CANDIDATEPAIRS MS_FILTER_METHOD(MS_ICE_ID,1,struct CandidatePair*) - -extern MSFilterDesc ms_ice_desc; - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/mediastream.h b/linphone/mediastreamer2/include/mediastreamer2/mediastream.h deleted file mode 100644 index e0b971fce..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/mediastream.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifndef MEDIASTREAM_H -#define MEDIASTREAM_H - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/mswebcam.h" -#include "mediastreamer2/msvideo.h" -#include "ortp/ortp.h" -#include "ortp/event.h" -#include - -#if defined(_WIN32_WCE) -time_t ms_time (time_t *t); -#else -#define ms_time time -#endif - -typedef enum EchoLimiterType{ - ELInactive, - ELControlMic, - ELControlSpeaker -} EchoLimiterType; - -struct _AudioStream -{ - MSTicker *ticker; - RtpSession *session; - MSFilter *soundread; - MSFilter *soundwrite; - MSFilter *encoder; - MSFilter *decoder; - MSFilter *rtprecv; - MSFilter *rtpsend; - MSFilter *dtmfgen; - MSFilter *ec;/*echo canceler*/ - MSFilter *volsend,*volrecv; /*MSVolumes*/ - MSFilter *read_resampler; - MSFilter *write_resampler; - MSFilter *equalizer; - uint64_t last_packet_count; - time_t last_packet_time; - EchoLimiterType el_type; /*use echo limiter: two MSVolume, measured input level controlling local output level*/ - int ec_tail_len; /*milliseconds*/ - int ec_delay; /*milliseconds*/ - int ec_framesize; /* number of fft points */ - bool_t play_dtmfs; - bool_t use_gc; - bool_t use_agc; - bool_t eq_active; - bool_t use_ng;/*noise gate*/ -}; - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct _AudioStream AudioStream; - -struct _RingStream -{ - MSTicker *ticker; - MSFilter *source; - MSFilter *sndwrite; -}; - -typedef struct _RingStream RingStream; - - - -/* start a thread that does sampling->encoding->rtp_sending|rtp_receiving->decoding->playing */ -AudioStream *audio_stream_start (RtpProfile * prof, int locport, const char *remip, - int remport, int payload_type, int jitt_comp, bool_t echo_cancel); - -AudioStream *audio_stream_start_with_sndcards(RtpProfile * prof, int locport, const char *remip4, int remport, int payload_type, int jitt_comp, MSSndCard *playcard, MSSndCard *captcard, bool_t echocancel); - -int audio_stream_start_with_files (AudioStream * stream, RtpProfile * prof, - const char *remip, int remport, int rem_rtcp_port, - int pt, int jitt_comp, - const char * infile, const char * outfile); - -void audio_stream_play(AudioStream *st, const char *name); -void audio_stream_record(AudioStream *st, const char *name); - -void audio_stream_set_rtcp_information(AudioStream *st, const char *cname, const char *tool); - -void audio_stream_play_received_dtmfs(AudioStream *st, bool_t yesno); - -/* those two function do the same as audio_stream_start() but in two steps -this is useful to make sure that sockets are open before sending an invite; -or to start to stream only after receiving an ack.*/ -AudioStream *audio_stream_new(int locport, bool_t ipv6); -int audio_stream_start_now(AudioStream * stream, RtpProfile * prof, const char *remip, int remport, int rem_rtcp_port, int payload_type, int jitt_comp,MSSndCard *playcard, MSSndCard *captcard, bool_t echo_cancel); -void audio_stream_set_relay_session_id(AudioStream *stream, const char *relay_session_id); -/*returns true if we are still receiving some data from remote end in the last timeout seconds*/ -bool_t audio_stream_alive(AudioStream * stream, int timeout); - -/*enable echo-limiter dispositve: one MSVolume in input branch controls a MSVolume in the output branch*/ -void audio_stream_enable_echo_limiter(AudioStream *stream, EchoLimiterType type); - -/*enable gain control, to be done before start() */ -void audio_stream_enable_gain_control(AudioStream *stream, bool_t val); - -/*enable automatic gain control, to be done before start() */ -void audio_stream_enable_automatic_gain_control(AudioStream *stream, bool_t val); - -/*to be done before start */ -void audio_stream_set_echo_canceller_params(AudioStream *st, int tail_len_ms, int delay_ms, int framesize); - -void audio_stream_set_mic_gain(AudioStream *stream, float gain); - -/*enable noise gate, must be done before start()*/ -void audio_stream_enable_noise_gate(AudioStream *stream, bool_t val); - -/*enable parametric equalizer in the stream that goes to the speaker*/ -void audio_stream_enable_equalizer(AudioStream *stream, bool_t enabled); - -void audio_stream_equalizer_set_gain(AudioStream *stream, int frequency, float gain, int freq_width); - -/* stop the audio streaming thread and free everything*/ -void audio_stream_stop (AudioStream * stream); - -RingStream *ring_start (const char * file, int interval, MSSndCard *sndcard); -RingStream *ring_start_with_cb(const char * file, int interval, MSSndCard *sndcard, MSFilterNotifyFunc func, void * user_data); -void ring_stop (RingStream * stream); - - -/* send a dtmf */ -int audio_stream_send_dtmf (AudioStream * stream, char dtmf); - -void audio_stream_set_default_card(int cardindex); - - -/***************** - Video Support - *****************/ - - -struct _VideoStream -{ - MSTicker *ticker; - RtpSession *session; - MSFilter *source; - MSFilter *pixconv; - MSFilter *sizeconv; - MSFilter *tee; - MSFilter *output; - MSFilter *encoder; - MSFilter *decoder; - MSFilter *rtprecv; - MSFilter *rtpsend; - OrtpEvQueue *evq; - MSVideoSize sent_vsize; - int corner; /*for selfview*/ - bool_t adapt_bitrate; -}; - -typedef struct _VideoStream VideoStream; - -VideoStream *video_stream_new(int locport, bool_t use_ipv6); -void video_stream_enable_adaptive_bitrate_control(VideoStream *s, bool_t yesno); -int video_stream_start(VideoStream * stream, RtpProfile *profile, const char *remip, int remport, int rem_rtcp_port, - int payload, int jitt_comp, MSWebCam *device); -void video_stream_set_relay_session_id(VideoStream *stream, const char *relay_session_id); -void video_stream_set_rtcp_information(VideoStream *st, const char *cname, const char *tool); -/*function to call periodically to handle various events */ -void video_stream_iterate(VideoStream *stream); -void video_stream_send_vfu(VideoStream *stream); -void video_stream_stop(VideoStream * stream); -void video_stream_set_sent_video_size(VideoStream *stream, MSVideoSize vsize); -void video_stream_enable_self_view(VideoStream *stream, bool_t val); -unsigned long video_stream_get_native_window_id(VideoStream *stream); - - -VideoStream * video_preview_start(MSWebCam *device, MSVideoSize vsize); -void video_preview_stop(VideoStream *stream); - -int video_stream_recv_only_start(VideoStream * stream, RtpProfile *profile, const char *remip, int remport, int payload, int jitt_comp); -int video_stream_send_only_start(VideoStream * stream, RtpProfile *profile, const char *remip, int remport, - int rem_rtcp_port, int payload, int jitt_comp, MSWebCam *device); -void video_stream_recv_only_stop(VideoStream *stream); -void video_stream_send_only_stop(VideoStream *stream); - - -bool_t ms_is_ipv6(const char *address); - -#ifdef __cplusplus -} -#endif - - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/mscommon.h b/linphone/mediastreamer2/include/mediastreamer2/mscommon.h deleted file mode 100644 index 869feeff3..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/mscommon.h +++ /dev/null @@ -1,204 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ -#ifndef mscommon_h -#define mscommon_h - -#include - -#define ms_malloc ortp_malloc -#define ms_malloc0 ortp_malloc0 -#define ms_realloc ortp_realloc -#define ms_new ortp_new -#define ms_new0 ortp_new0 -#define ms_free ortp_free -#define ms_strdup ortp_strdup -#define ms_strdup_printf ortp_strdup_printf - -#define ms_mutex_t ortp_mutex_t -#define ms_mutex_init ortp_mutex_init -#define ms_mutex_destroy ortp_mutex_destroy -#define ms_mutex_lock ortp_mutex_lock -#define ms_mutex_unlock ortp_mutex_unlock - -#define ms_cond_t ortp_cond_t -#define ms_cond_init ortp_cond_init -#define ms_cond_wait ortp_cond_wait -#define ms_cond_signal ortp_cond_signal -#define ms_cond_broadcast ortp_cond_broadcast -#define ms_cond_destroy ortp_cond_destroy - -#ifdef WIN32 -static inline void ms_debug(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_DEBUG, fmt, args); - va_end (args); -} -#else -#ifdef DEBUG -static inline void ms_debug(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_DEBUG, fmt, args); - va_end (args); -} -#else -#define ms_debug(...) -#endif -#endif - - - -#define ms_message ortp_message -#define ms_warning ortp_warning -#define ms_error ortp_error -#define ms_fatal ortp_fatal - -#define ms_return_val_if_fail(_expr_,_ret_)\ - if (!(_expr_)) { ms_error("assert "#_expr_ "failed"); return (_ret_);} - -#define ms_return_if_fail(_expr_) \ - if (!(_expr_)){ ms_error("assert "#_expr_ "failed"); return ;} - -#define ms_thread_t ortp_thread_t -#define ms_thread_create ortp_thread_create -#define ms_thread_join ortp_thread_join -#define ms_thread_exit ortp_thread_exit - -struct _MSList { - struct _MSList *next; - struct _MSList *prev; - void *data; -}; - -typedef struct _MSList MSList; - - -#define ms_list_next(elem) ((elem)->next) - - -#ifdef __cplusplus -extern "C"{ -#endif - -MSList * ms_list_append(MSList *elem, void * data); -MSList * ms_list_prepend(MSList *elem, void * data); -MSList * ms_list_free(MSList *elem); -MSList * ms_list_concat(MSList *first, MSList *second); -MSList * ms_list_remove(MSList *first, void *data); -int ms_list_size(const MSList *first); -void ms_list_for_each(const MSList *list, void (*func)(void *)); -void ms_list_for_each2(const MSList *list, void (*func)(void *, void *), void *user_data); -MSList *ms_list_remove_link(MSList *list, MSList *elem); -MSList *ms_list_find(MSList *list, void *data); -MSList *ms_list_find_custom(MSList *list, int (*compare_func)(const void *, const void*), void *user_data); -void * ms_list_nth_data(const MSList *list, int index); -int ms_list_position(const MSList *list, MSList *elem); -int ms_list_index(const MSList *list, void *data); -MSList *ms_list_insert_sorted(MSList *list, void *data, int (*compare_func)(const void *, const void*)); -MSList *ms_list_insert(MSList *list, MSList *before, void *data); -MSList *ms_list_copy(const MSList *list); - -#undef MIN -#define MIN(a,b) ((a)>(b) ? (b) : (a)) -#undef MAX -#define MAX(a,b) ((a)>(b) ? (a) : (b)) - -/** - * @file mscommon.h - * @brief mediastreamer2 mscommon.h include file - * - * This file provide the API needed to initialize - * and reset the mediastreamer2 library. - * - */ - -/** - * @defgroup mediastreamer2_init Init API - manage mediastreamer2 library. - * @ingroup mediastreamer2_api - * @{ - */ - - -/** - * Initialize the mediastreamer2 library. - * - * This must be called once before calling any other API. - */ -void ms_init(void); - -/** - * Load plugins from a specific directory. - * This method basically loads all libraries in the specified directory and attempts to call a C function called - * \_init. For example if a library 'libdummy.so' or 'libdummy.dll' is found, then the loader tries to locate - * a C function called 'libdummy_init()' and calls it if it exists. - * ms_load_plugins() can be used to load non-mediastreamer2 plugins as it does not expect mediastreamer2 specific entry points. - * - * @param directory A directory where plugins library are available. - * - * Returns: >0 if successfull, 0 if not plugins loaded, -1 otherwise. - */ -int ms_load_plugins(const char *directory); - -/** - * Release resource allocated in the mediastreamer2 library. - * - * This must be called once before closing program. - */ -void ms_exit(void); - -struct _MSSndCardDesc; - -void ms_sleep(int seconds); - -/** - * The max payload size allowed. - * Filters that generate data that can be sent through RTP should make packets - * whose size is below ms_get_payload_max_size(). - * The default value is 1440 computed as the standart internet MTU minus IPv6 header, - * UDP header and RTP header. As IPV4 header is smaller than IPv6 header, this - * value works for both. - * -**/ -int ms_get_payload_max_size(); - -void ms_set_payload_max_size(int size); - -/** - * Returns the network Max Transmission Unit to reach destination_host. - * This will attempt to send one or more big packets to destination_host, to a random port. - * Those packets are filled with zeroes. -**/ -int ms_discover_mtu(const char *destination_host); - -/** - * Set mediastreamer default mtu, used to compute the default RTP max payload size. - * This function will call ms_set_payload_max_size(mtu-[ipv6 header size]). -**/ -void ms_set_mtu(int mtu); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msequalizer.h b/linphone/mediastreamer2/include/mediastreamer2/msequalizer.h deleted file mode 100644 index cebecaaf3..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msequalizer.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2009 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. -*/ - -#ifndef msequalizer_h -#define msequalizer_h - -#include - -typedef struct _MSEqualizerGain{ - float frequency; ///< In hz - float gain; ///< between 0-1.2 - float width; ///< frequency band width around mid frequency for which the gain is applied, in Hz. Use 0 for the lowest frequency resolution. -}MSEqualizerGain; - -#define MS_EQUALIZER_SET_GAIN MS_FILTER_METHOD(MS_EQUALIZER_ID,0,MSEqualizerGain) -#define MS_EQUALIZER_GET_GAIN MS_FILTER_METHOD(MS_EQUALIZER_ID,1,MSEqualizerGain) -#define MS_EQUALIZER_SET_ACTIVE MS_FILTER_METHOD(MS_EQUALIZER_ID,2,int) -/**dump the spectral response into a table of float. The table must be sized according to the value returned by - * MS_EQUALIZER_GET_NUM_FREQUENCIES -**/ -#define MS_EQUALIZER_DUMP_STATE MS_FILTER_METHOD(MS_EQUALIZER_ID,3,float) - -/**returns the number of frequencies*/ -#define MS_EQUALIZER_GET_NUM_FREQUENCIES MS_FILTER_METHOD(MS_EQUALIZER_ID,4,int) - - -#endif - diff --git a/linphone/mediastreamer2/include/mediastreamer2/msfileplayer.h b/linphone/mediastreamer2/include/mediastreamer2/msfileplayer.h deleted file mode 100644 index 8e1931448..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msfileplayer.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ -#ifndef msfileplayer_h -#define msfileplayer_h - -#include "msfilter.h" - - -/*methods*/ -#define MS_FILE_PLAYER_OPEN MS_FILTER_METHOD(MS_FILE_PLAYER_ID,0,const char*) -#define MS_FILE_PLAYER_START MS_FILTER_METHOD_NO_ARG(MS_FILE_PLAYER_ID,1) -#define MS_FILE_PLAYER_STOP MS_FILTER_METHOD_NO_ARG(MS_FILE_PLAYER_ID,2) -#define MS_FILE_PLAYER_CLOSE MS_FILTER_METHOD_NO_ARG(MS_FILE_PLAYER_ID,3) -/* set loop mode: - -1: no looping, - 0: loop at end of file, - x>0, loop after x miliseconds after eof -*/ -#define MS_FILE_PLAYER_LOOP MS_FILTER_METHOD(MS_FILE_PLAYER_ID,4,int) -#define MS_FILE_PLAYER_DONE MS_FILTER_METHOD(MS_FILE_PLAYER_ID,5,int) -#define MS_FILE_PLAYER_BIG_BUFFER MS_FILTER_METHOD(MS_FILE_PLAYER_ID,6,int) - -/*events*/ -#define MS_FILE_PLAYER_EOF MS_FILTER_EVENT_NO_ARG(MS_FILE_PLAYER_ID,0) - -#endif - diff --git a/linphone/mediastreamer2/include/mediastreamer2/msfilerec.h b/linphone/mediastreamer2/include/mediastreamer2/msfilerec.h deleted file mode 100644 index b46cb38ac..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msfilerec.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ -#ifndef msfilerec_h -#define msfilerec_h - -#include "msfilter.h" - -extern MSFilterDesc ms_file_rec_desc; - -#define MS_FILE_REC_OPEN MS_FILTER_METHOD(MS_FILE_REC_ID,0,const char) -#define MS_FILE_REC_START MS_FILTER_METHOD_NO_ARG(MS_FILE_REC_ID,1) -#define MS_FILE_REC_STOP MS_FILTER_METHOD_NO_ARG(MS_FILE_REC_ID,2) -#define MS_FILE_REC_CLOSE MS_FILTER_METHOD_NO_ARG(MS_FILE_REC_ID,3) - - - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msfilter.h b/linphone/mediastreamer2/include/mediastreamer2/msfilter.h deleted file mode 100644 index 3828144bf..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msfilter.h +++ /dev/null @@ -1,508 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef msfilter_h -#define msfilter_h - -#include "mscommon.h" -#include "msqueue.h" -#include "allfilters.h" - -/** - * @file msfilter.h - * @brief mediastreamer2 msfilter.h include file - * - * This file provide the API needed to create, link, - * unlink, find and destroy filter. - * - * It also provides definitions if you wish to implement - * your own filters. - * - */ - -/** - * @defgroup mediastreamer2_filter Filter API - manage mediastreamer2 filters. - * @ingroup mediastreamer2_api - * @{ - */ - -/** - * Structure for filter's methods (init, preprocess, process, postprocess, uninit). - * @var MSFilterFunc - */ -typedef void (*MSFilterFunc)(struct _MSFilter *f); - -/** - * Structure for filter's methods used to set filter's options. - * @var MSFilterMethodFunc - */ -typedef int (*MSFilterMethodFunc)(struct _MSFilter *f, void *arg); - -/** - * Structure for filter's methods used as a callback to notify events. - * @var MSFilterNotifyFunc - */ -typedef void (*MSFilterNotifyFunc)(void *userdata , unsigned int id, void *arg); - -struct _MSFilterMethod{ - int id; - MSFilterMethodFunc method; -}; - - -/** - * Structure for holding filter's methods to set filter's options. - * @var MSFilterMethod - */ -typedef struct _MSFilterMethod MSFilterMethod; - -enum _MSFilterCategory{ - MS_FILTER_OTHER, - MS_FILTER_ENCODER, - MS_FILTER_DECODER -}; - -/** - * Structure to describe filter's category. - *
- *     MS_FILTER_OTHER
- *     MS_FILTER_ENCODER
- *     MS_FILTER_DECODER
- * 
- * @var MSFilterCategory - */ -typedef enum _MSFilterCategory MSFilterCategory; - -enum _MSFilterFlags{ - MS_FILTER_IS_PUMP = 1 -}; - -typedef enum _MSFilterFlags MSFilterFlags; - -struct _MSFilterDesc{ - MSFilterId id; /* the id declared in allfilters.h */ - const char *name; /* filter name */ - const char *text; /*some descriptive text*/ - MSFilterCategory category; - const char *enc_fmt; /* must be set if MS_FILTER_ENCODER/MS_FILTER_DECODER */ - int ninputs; /*number of inputs */ - int noutputs; /*number of outputs */ - MSFilterFunc init; - MSFilterFunc preprocess; /* called once before processing */ - MSFilterFunc process; /* called every tick to do the filter's job*/ - MSFilterFunc postprocess; /*called once after processing */ - MSFilterFunc uninit; - MSFilterMethod *methods; - unsigned int flags; -}; - -/** - * Structure for filter's description. - * @var MSFilterDesc - */ -typedef struct _MSFilterDesc MSFilterDesc; - -struct _MSFilter{ - MSFilterDesc *desc; - /*protected attributes */ - ms_mutex_t lock; - MSQueue **inputs; - MSQueue **outputs; - MSFilterNotifyFunc notify; - void *notify_ud; - void *data; - struct _MSTicker *ticker; - /*private attributes */ - uint32_t last_tick; - bool_t seen; -}; - - -/** - * Structure to create/link/unlink/destroy filter's object. - * @var MSFilter - */ -typedef struct _MSFilter MSFilter; - -struct _MSConnectionPoint{ - MSFilter *filter; - int pin; -}; - -/** - * Structure that represents a connection point of a MSFilter - * @var MSConnectionPoint - */ -typedef struct _MSConnectionPoint MSConnectionPoint; - -struct _MSConnectionHelper{ - MSConnectionPoint last; -}; - -/** - * Structure that holds data when using the ms_connection_helper_* functions. - * @var MSConnectionHelper -**/ -typedef struct _MSConnectionHelper MSConnectionHelper; - - -#ifdef __cplusplus -extern "C"{ -#endif - -/** - * Register a filter description. (plugins use only!) - * - * When you build your own plugin, this method will - * add the encoder or decoder to the internal list - * of supported codec. Then, this plugin can be used - * transparently from the application. - * - * ms_filter_get_encoder, ms_filter_get_decoder, - * ms_filter_create_encoder, ms_filter_create_decoder - * and ms_filter_codec_supported - * can then be used as if the codec was internally. - * supported. - * - * @param desc a filter description. - */ -void ms_filter_register(MSFilterDesc *desc); - -/** - * Retrieve encoders according to codec name. - * - * Internal supported codecs: - * PCMU, PCMA, speex, gsm - * Existing Public plugins: - * iLBC - * - * @param mime A string indicating the codec. - * - * Returns: a MSFilterDesc if successfull, NULL otherwise. - */ -MSFilterDesc * ms_filter_get_encoder(const char *mime); - -/** - * Retrieve decoders according to codec name. - * - * Internal supported codecs: - * PCMU, PCMA, speex, gsm - * Existing Public plugins: - * iLBC - * - * @param mime A string indicating the codec. - * - * Returns: a MSFilterDesc if successfull, NULL otherwise. - */ -MSFilterDesc * ms_filter_get_decoder(const char *mime); - -/** - * Create encoder filter according to codec name. - * - * Internal supported codecs: - * PCMU, PCMA, speex, gsm - * Existing Public plugins: - * iLBC - * - * @param mime A string indicating the codec. - * - * Returns: a MSFilter if successfull, NULL otherwise. - */ -MSFilter * ms_filter_create_encoder(const char *mime); - -/** - * Create decoder filter according to codec name. - * - * Internal supported codecs: - * PCMU, PCMA, speex, gsm - * Existing Public plugins: - * iLBC - * - * @param mime A string indicating the codec. - * - * Returns: a MSFilter if successfull, NULL otherwise. - */ -MSFilter * ms_filter_create_decoder(const char *mime); - -/** - * Check if a encode or decode filter exists for a codec name. - * - * Internal supported codecs: - * PCMU, PCMA, speex, gsm - * Existing Public plugins: - * iLBC - * - * @param mime A string indicating the codec. - * - * Returns: TRUE if successfull, FALSE otherwise. - */ -bool_t ms_filter_codec_supported(const char *mime); - -/** - * Create decoder filter according to a filter's MSFilterId. - * - * @param id A MSFilterId identifier for the filter. - * - * Returns: a MSFilter if successfull, NULL otherwise. - */ -MSFilter *ms_filter_new(MSFilterId id); - -/** - * Create decoder filter according to a filter's name. - * - * @param name A name for the filter. - * - * Returns: a MSFilter if successfull, NULL otherwise. - */ -MSFilter *ms_filter_new_from_name(const char *name); - -/** - * Create decoder filter according to a filter's description. - * - * The primary use is to create your own filter's in your - * application and avoid registration inside mediastreamer2. - * - * @param desc A MSFilterDesc for the filter. - * - * Returns: a MSFilter if successfull, NULL otherwise. - */ -MSFilter *ms_filter_new_from_desc(MSFilterDesc *desc); - -/** - * Link one OUTPUT pin from a filter to an INPUT pin of another filter. - * - * All data coming from the OUTPUT pin of one filter will be distributed - * to the INPUT pin of the second filter. - * - * @param f1 A MSFilter object containing the OUTPUT pin - * @param pin1 An index of an OUTPUT pin. - * @param f2 A MSFilter object containing the INPUT pin - * @param pin2 An index of an INPUT pin. - * - * Returns: 0 if sucessful, -1 otherwise. - */ -int ms_filter_link(MSFilter *f1, int pin1, MSFilter *f2, int pin2); - -/** - * Unlink one OUTPUT pin from a filter to an INPUT pin of another filter. - * - * @param f1 A MSFilter object containing the OUTPUT pin - * @param pin1 An index of an OUTPUT pin. - * @param f2 A MSFilter object containing the INPUT pin - * @param pin2 An index of an INPUT pin. - * - * Returns: 0 if sucessful, -1 otherwise. - */ -int ms_filter_unlink(MSFilter *f1, int pin1, MSFilter *f2, int pin2); - -/** - * Call a filter's method to set or get options. - * - * @param f A MSFilter object. - * @param id A private filter ID for the option. - * @param arg A private user data for the filter. - * - * Returns: 0 if successfull, -1 otherwise. - */ -int ms_filter_call_method(MSFilter *f, unsigned int id, void *arg); - -/** - * Call a filter's method to set options. - * - * @param f A MSFilter object. - * @param id A private filter ID for the option. - * - * Returns: 0 if successfull, -1 otherwise. - */ -int ms_filter_call_method_noarg(MSFilter *f, unsigned int id); - -/** - * Set a callback on filter's to be informed of private filter's event. - * - * @param f A MSFilter object. - * @param fn A MSFilterNotifyFunc that will be called. - * @param userdata A pointer to private data. - * - * Returns: 0 if successfull, -1 otherwise. - */ -void ms_filter_set_notify_callback(MSFilter *f, MSFilterNotifyFunc fn, void *userdata); - -/** - * Get MSFilterId's filter. - * - * @param f A MSFilter object. - * - * Returns: MSFilterId if successfull, -1 otherwise. - */ -MSFilterId ms_filter_get_id(MSFilter *f); - - -/** - * Obtain the list of current filter's neighbours, ie filters that are part of same graph. - * - * Returns: a MSList of MSFilter, that needs to be freed by the caller when no more needed. -**/ -MSList * ms_filter_find_neighbours(MSFilter *me); - -/** - * Destroy a filter object. - * - * @param f A MSFilter object. - * - */ -void ms_filter_destroy(MSFilter *f); - -/** - * Initialize a MSConnectionHelper. - * - * @param h A MSConnectionHelper, usually (but not necessarily) on stack - * -**/ -void ms_connection_helper_start(MSConnectionHelper *h); - -/** - * \brief Enter a MSFilter to be connected into the MSConnectionHelper object. - * - * This functions enters a MSFilter to be connected into the MSConnectionHelper - * object and connects it to the last entered if not the first one. - * The MSConnectionHelper is useful to reduce the amount of code necessary to create graphs in case - * the connections are made in an ordered manner and some filters are present conditionally in graphs. - * For example, instead of writing - * \code - * ms_filter_link(f1,0,f2,1); - * ms_filter_link(f2,0,f3,0); - * ms_filter_link(f3,1,f4,0); - * \endcode - * You can write: - * \code - * MSConnectionHelper h; - * ms_connection_helper_start(&h); - * ms_connection_helper_link(&h,f1,-1,0); - * ms_connection_helper_link(&h,f2,1,0); - * ms_connection_helper_link(&h,f3,0,1); - * ms_connection_helper_link(&h,f4,0,-1); - * \endcode - * Which is a bit longer to write here, but now imagine f2 needs to be present in the graph only - * in certain conditions: in the first case you have rewrite the two first lines, in the second case - * you just need to replace the fourth line by: - * \code - * if (my_condition) ms_connection_helper_link(&h,f2,1,0); - * \endcode - * - * @param h a connection helper - * @param f a MSFilter - * @param inpin an input pin number with which the MSFilter needs to connect to previously entered MSFilter - * @param outpin an output pin number with which the MSFilter needs to be connected to the next entered MSFilter - * - * Returns: the return value of ms_filter_link() that is called internally to this function. -**/ -int ms_connection_helper_link(MSConnectionHelper *h, MSFilter *f, int inpin, int outpin); - - -/** - * \brief Enter a MSFilter to be disconnected into the MSConnectionHelper object. - * Process exactly the same way as ms_connection_helper_link() but calls ms_filter_unlink() on the - * entered filters. -**/ -int ms_connection_helper_unlink(MSConnectionHelper *h, MSFilter *f, int inpin, int outpin); - -/* I define the id taking the lower bits of the address of the MSFilterDesc object, -the method index (_cnt_) and the argument size */ -/* I hope using this to avoid type mismatch (calling a method on the wrong filter)*/ -#define MS_FILTER_METHOD_ID(_id_,_cnt_,_argsize_) \ - ( (((unsigned long)(_id_)) & 0xFFFF)<<16 | (_cnt_<<8) | (_argsize_ & 0xFF )) - -#define MS_FILTER_METHOD(_id_,_count_,_argtype_) \ - MS_FILTER_METHOD_ID(_id_,_count_,sizeof(_argtype_)) - -#define MS_FILTER_METHOD_NO_ARG(_id_,_count_) \ - MS_FILTER_METHOD_ID(_id_,_count_,0) - - -#define MS_FILTER_BASE_METHOD(_count_,_argtype_) \ - MS_FILTER_METHOD_ID(MS_FILTER_BASE_ID,_count_,sizeof(_argtype_)) - -#define MS_FILTER_BASE_METHOD_NO_ARG(_count_) \ - MS_FILTER_METHOD_ID(MS_FILTER_BASE_ID,_count_,0) - -#define MS_FILTER_EVENT(_id_,_count_,_argtype_) \ - MS_FILTER_METHOD_ID(_id_,_count_,sizeof(_argtype_)) - -#define MS_FILTER_EVENT_NO_ARG(_id_,_count_)\ - MS_FILTER_METHOD_ID(_id_,_count_,0) - -/* some MSFilter base generic methods:*/ -#define MS_FILTER_SET_SAMPLE_RATE MS_FILTER_BASE_METHOD(0,int) -#define MS_FILTER_GET_SAMPLE_RATE MS_FILTER_BASE_METHOD(1,int) -#define MS_FILTER_SET_BITRATE MS_FILTER_BASE_METHOD(2,int) -#define MS_FILTER_GET_BITRATE MS_FILTER_BASE_METHOD(3,int) -#define MS_FILTER_GET_NCHANNELS MS_FILTER_BASE_METHOD(5,int) -#define MS_FILTER_SET_NCHANNELS MS_FILTER_BASE_METHOD(6,int) -#define MS_FILTER_ADD_FMTP MS_FILTER_BASE_METHOD(7,const char) -#define MS_FILTER_ADD_ATTR MS_FILTER_BASE_METHOD(8,const char) -#define MS_FILTER_SET_MTU MS_FILTER_BASE_METHOD(9,int) -#define MS_FILTER_GET_MTU MS_FILTER_BASE_METHOD(10,int) - - -/* more specific methods: to be moved into implementation specific header files*/ -#define MS_FILTER_SET_FRAMESIZE MS_FILTER_BASE_METHOD(11,int) -#define MS_FILTER_SET_FILTERLENGTH MS_FILTER_BASE_METHOD(12,int) -#define MS_FILTER_SET_OUTPUT_SAMPLE_RATE MS_FILTER_BASE_METHOD(13,int) -#define MS_FILTER_ENABLE_DIRECTMODE MS_FILTER_BASE_METHOD(14,int) -#define MS_FILTER_ENABLE_VAD MS_FILTER_BASE_METHOD(15,int) -#define MS_FILTER_GET_STAT_DISCARDED MS_FILTER_BASE_METHOD(16,int) -#define MS_FILTER_GET_STAT_MISSED MS_FILTER_BASE_METHOD(17,int) -#define MS_FILTER_GET_STAT_INPUT MS_FILTER_BASE_METHOD(18,int) -#define MS_FILTER_GET_STAT_OUTPUT MS_FILTER_BASE_METHOD(19,int) -#define MS_FILTER_ENABLE_AGC MS_FILTER_BASE_METHOD(20,int) -#define MS_FILTER_SET_PLAYBACKDELAY MS_FILTER_BASE_METHOD(21,int) -#define MS_FILTER_ENABLE_HALFDUPLEX MS_FILTER_BASE_METHOD(22,int) -#define MS_FILTER_SET_VAD_PROB_START MS_FILTER_BASE_METHOD(23,int) -#define MS_FILTER_SET_VAD_PROB_CONTINUE MS_FILTER_BASE_METHOD(24,int) -#define MS_FILTER_SET_MAX_GAIN MS_FILTER_BASE_METHOD(25,int) - -#define MS_CONF_SPEEX_PREPROCESS_MIC MS_FILTER_EVENT(MS_CONF_ID, 1, void*) -#define MS_CONF_CHANNEL_VOLUME MS_FILTER_EVENT(MS_CONF_ID, 3, void*) - -#define MS_SPEEX_EC_PREPROCESS_MIC MS_FILTER_EVENT(MS_SPEEX_EC_ID, 1, void*) -#define MS_SPEEX_EC_ECHO_STATE MS_FILTER_EVENT(MS_SPEEX_EC_ID, 2, void*) -/** @} */ - -/*private methods*/ -void ms_filter_process(MSFilter *f); -void ms_filter_preprocess(MSFilter *f, struct _MSTicker *t); -void ms_filter_postprocess(MSFilter *f); -bool_t ms_filter_inputs_have_data(MSFilter *f); -void ms_filter_notify(MSFilter *f, unsigned int id, void *arg); -void ms_filter_notify_no_arg(MSFilter *f, unsigned int id); -#define ms_filter_lock(f) ms_mutex_lock(&(f)->lock) -#define ms_filter_unlock(f) ms_mutex_unlock(&(f)->lock) -void ms_filter_unregister_all(void); - -#ifdef __cplusplus -} -#endif - -/* used by awk script in Makefile.am to generate alldescs.c */ -#define MS_FILTER_DESC_EXPORT(desc) - -/* xgettext markup */ -#define N_(String) String - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msqueue.h b/linphone/mediastreamer2/include/mediastreamer2/msqueue.h deleted file mode 100644 index 98e776d2b..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msqueue.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ -#ifndef MSQUEUE_H -#define MSQUEUE_H - -#include "ortp/str_utils.h" - -/* for the moment these are stupid queues limited to one element*/ - -typedef struct _MSCPoint{ - struct _MSFilter *filter; - int pin; -} MSCPoint; - -typedef struct _MSQueue -{ - queue_t q; - MSCPoint prev; - MSCPoint next; -}MSQueue; - - -MSQueue * ms_queue_new(struct _MSFilter *f1, int pin1, struct _MSFilter *f2, int pin2 ); - -static inline mblk_t *ms_queue_get(MSQueue *q){ - return getq(&q->q); -} - -static inline void ms_queue_put(MSQueue *q, mblk_t *m){ - putq(&q->q,m); - return; -} - -static inline mblk_t * ms_queue_peek_last(MSQueue *q){ - return qlast(&q->q); -} - -static inline bool_t ms_queue_empty(MSQueue *q){ - return qempty(&q->q); -} - -#ifdef __cplusplus -extern "C" -{ -#endif - -/*init a queue on stack*/ -void ms_queue_init(MSQueue *q); - -void ms_queue_flush(MSQueue *q); - -void ms_queue_destroy(MSQueue *q); - -#define mblk_set_timestamp_info(m,ts) (m)->reserved1=(ts); -#define mblk_get_timestamp_info(m) ((m)->reserved1) -#define mblk_set_marker_info(m,bit) (m)->reserved2=((m)->reserved2|bit) -#define mblk_get_marker_info(m) ((m)->reserved2&0x1) -#define mblk_set_rate(m,bits) (m)->reserved2=((m)->reserved2|(bits)<<1) -#define mblk_get_rate(m) (((m)->reserved2>>1)&0x3) -#define mblk_set_payload_type(m,bits) (m)->reserved2=((m)->reserved2|(bits<<3)) -#define mblk_get_payload_type(m) (((m)->reserved2>>3)&0x7F) -#define mblk_set_precious_flag(m,bit) (m)->reserved2=(m)->reserved2|((bit & 0x1)<<10) /*use to prevent mirroring*/ -#define mblk_get_precious_flag(m) (((m)->reserved2)>>10 & 0x1) - -struct _MSBufferizer{ - queue_t q; - int size; -}; - -typedef struct _MSBufferizer MSBufferizer; - -/*allocates and initialize */ -MSBufferizer * ms_bufferizer_new(void); - -/*initialize in memory */ -void ms_bufferizer_init(MSBufferizer *obj); - -void ms_bufferizer_put(MSBufferizer *obj, mblk_t *m); - -/* put every mblk_t from q, into the bufferizer */ -void ms_bufferizer_put_from_queue(MSBufferizer *obj, MSQueue *q); - -int ms_bufferizer_read(MSBufferizer *obj, uint8_t *data, int datalen); - -/* returns the number of bytes available in the bufferizer*/ -static inline int ms_bufferizer_get_avail(MSBufferizer *obj){ - return obj->size; -} - -/* purge all data pending in the bufferizer */ -void ms_bufferizer_flush(MSBufferizer *obj); - -void ms_bufferizer_uninit(MSBufferizer *obj); - -void ms_bufferizer_destroy(MSBufferizer *obj); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msrtp.h b/linphone/mediastreamer2/include/mediastreamer2/msrtp.h deleted file mode 100644 index 13ac30a65..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msrtp.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifndef msrtp_hh -#define msrtp_hh - -#include "msfilter.h" -#include "ice.h" -#include "ortp/ortp.h" - -#define MS_RTP_RECV_SET_SESSION MS_FILTER_METHOD(MS_RTP_RECV_ID,0,RtpSession*) - -#define MS_RTP_SEND_SET_SESSION MS_FILTER_METHOD(MS_RTP_SEND_ID,0,RtpSession*) - -#define MS_RTP_SEND_SEND_DTMF MS_FILTER_METHOD(MS_RTP_SEND_ID,1,const char) - -#define MS_RTP_SEND_MUTE_MIC MS_FILTER_METHOD_NO_ARG(MS_RTP_SEND_ID,3) - -#define MS_RTP_SEND_UNMUTE_MIC MS_FILTER_METHOD_NO_ARG(MS_RTP_SEND_ID,4) - -#define MS_RTP_SEND_SET_RELAY_SESSION_ID MS_FILTER_METHOD(MS_RTP_SEND_ID,5,const char *) - -#define MS_RTP_SEND_SET_DTMF_DURATION MS_FILTER_METHOD(MS_RTP_SEND_ID,1,int) - -extern MSFilterDesc ms_rtp_send_desc; -extern MSFilterDesc ms_rtp_recv_desc; - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/mssndcard.h b/linphone/mediastreamer2/include/mediastreamer2/mssndcard.h deleted file mode 100644 index ea197482f..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/mssndcard.h +++ /dev/null @@ -1,436 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef sndcard_h -#define sndcard_h - -#include "mscommon.h" - -/** - * @file mssndcard.h - * @brief mediastreamer2 mssndcard.h include file - * - * This file provide the API needed to manage - * soundcard filters. - * - */ - -/** - * @defgroup mediastreamer2_soundcard Sound Card API - manage audio capture/play filters. - * @ingroup mediastreamer2_api - * @{ - */ - -struct _MSSndCardManager{ - MSList *cards; - MSList *descs; -}; - -/** - * Structure for sound card manager object. - * @var MSSndCardManager - */ -typedef struct _MSSndCardManager MSSndCardManager; - -enum _MSSndCardMixerElem{ - MS_SND_CARD_MASTER, - MS_SND_CARD_PLAYBACK, - MS_SND_CARD_CAPTURE -}; - -/** - * Structure for sound card mixer values. - * @var MSSndCardMixerElem - */ -typedef enum _MSSndCardMixerElem MSSndCardMixerElem; - -enum _MSSndCardCapture { - MS_SND_CARD_MIC, - MS_SND_CARD_LINE -}; - -/** - * Structure for sound card capture source values. - * @var MSSndCardCapture - */ -typedef enum _MSSndCardCapture MSSndCardCapture; - -enum _MSSndCardControlElem { - MS_SND_CARD_MASTER_MUTE, - MS_SND_CARD_PLAYBACK_MUTE, - MS_SND_CARD_CAPTURE_MUTE -}; - -/** - * Structure for sound card mixer values. - * @var MSSndCardControlElem - */ -typedef enum _MSSndCardControlElem MSSndCardControlElem; - -struct _MSSndCard; - -typedef void (*MSSndCardDetectFunc)(MSSndCardManager *obj); -typedef void (*MSSndCardInitFunc)(struct _MSSndCard *obj); -typedef void (*MSSndCardUninitFunc)(struct _MSSndCard *obj); -typedef void (*MSSndCardSetLevelFunc)(struct _MSSndCard *obj, MSSndCardMixerElem e, int percent); -typedef void (*MSSndCardSetCaptureFunc)(struct _MSSndCard *obj, MSSndCardCapture e); -typedef int (*MSSndCardGetLevelFunc)(struct _MSSndCard *obj, MSSndCardMixerElem e); -typedef int (*MSSndCardSetControlFunc)(struct _MSSndCard *obj, MSSndCardControlElem e, int val); -typedef int (*MSSndCardGetControlFunc)(struct _MSSndCard *obj, MSSndCardControlElem e); -typedef struct _MSFilter * (*MSSndCardCreateReaderFunc)(struct _MSSndCard *obj); -typedef struct _MSFilter * (*MSSndCardCreateWriterFunc)(struct _MSSndCard *obj); -typedef struct _MSSndCard * (*MSSndCardDuplicateFunc)(struct _MSSndCard *obj); -typedef void (*MSSndCardUnloadFunc)(MSSndCardManager *obj); - -struct _MSSndCardDesc{ - const char *driver_type; - MSSndCardDetectFunc detect; - MSSndCardInitFunc init; - MSSndCardSetLevelFunc set_level; - MSSndCardGetLevelFunc get_level; - MSSndCardSetCaptureFunc set_capture; - MSSndCardSetControlFunc set_control; - MSSndCardGetControlFunc get_control; - MSSndCardCreateReaderFunc create_reader; - MSSndCardCreateWriterFunc create_writer; - MSSndCardUninitFunc uninit; - MSSndCardDuplicateFunc duplicate; - MSSndCardUnloadFunc unload; - -}; - -/** - * Structure for sound card description object. - * @var MSSndCardDesc - */ -typedef struct _MSSndCardDesc MSSndCardDesc; - -#define MS_SND_CARD_CAP_DISABLED (0) -#define MS_SND_CARD_CAP_CAPTURE (1) -#define MS_SND_CARD_CAP_PLAYBACK (1<<1) - -struct _MSSndCard{ - MSSndCardDesc *desc; - char *name; - char *id; - unsigned int capabilities; - void *data; -}; - -/** - * Structure for sound card object. - * @var MSSndCard - */ -typedef struct _MSSndCard MSSndCard; - -#ifdef __cplusplus -extern "C"{ -#endif - -/** - * @defgroup mediastreamer2_soundcardmanager Sound Card Manager API - * @ingroup mediastreamer2_soundcard - * @{ - */ - -/** - * Retreive a sound card manager object. - * - * Returns: MSSndCardManager if successfull, NULL otherwise. - */ -MSSndCardManager * ms_snd_card_manager_get(void); - -/** - * Destroy a sound card manager object. - * - */ -void ms_snd_card_manager_destroy(void); - -/** - * Retreive a sound card object based on its name. - * - * @param m A sound card manager containing sound cards. - * @param id A name for card to search. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_manager_get_card(MSSndCardManager *m, const char *id); - -/** - * Retreive the default sound card object. - * - * @param m A sound card manager containing sound cards. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_manager_get_default_card(MSSndCardManager *m); - -/** - * Retreive the default capture sound card object. - * - * @param m A sound card manager containing sound cards. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_manager_get_default_capture_card(MSSndCardManager *m); - -/** - * Retreive the default playback sound card object. - * - * @param m A sound card manager containing sound cards. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_manager_get_default_playback_card(MSSndCardManager *m); - -/** - * Retreive the list of sound card objects. - * - * @param m A sound card manager containing sound cards. - * - * Returns: MSList of cards if successfull, NULL otherwise. - */ -const MSList * ms_snd_card_manager_get_list(MSSndCardManager *m); - -/** - * Add a sound card object in a sound card manager's list. - * - * @param m A sound card manager containing sound cards. - * @param c A sound card object. - * - */ -void ms_snd_card_manager_add_card(MSSndCardManager *m, MSSndCard *c); - -/** - * Register a sound card description in a sound card manager. - * - * @param m A sound card manager containing sound cards. - * @param desc A sound card description object. - * - */ -void ms_snd_card_manager_register_desc(MSSndCardManager *m, MSSndCardDesc *desc); - -/** - * Ask all registered MSSndCardDesc to re-detect their soundcards. - * @param m The sound card manager. -**/ -void ms_snd_card_manager_reload(MSSndCardManager *m); - -/** @} */ - -/** - * @defgroup mediastreamer2_soundcardfilter Sound Card Filter API - * @ingroup mediastreamer2_soundcard - * @{ - */ - -/** - * Create an INPUT filter based on the selected sound card. - * - * @param obj A sound card object. - * - * Returns: A MSFilter if successfull, NULL otherwise. - */ -struct _MSFilter * ms_snd_card_create_reader(MSSndCard *obj); - -/** - * Create an OUPUT filter based on the selected sound card. - * - * @param obj A sound card object. - * - * Returns: A MSFilter if successfull, NULL otherwise. - */ -struct _MSFilter * ms_snd_card_create_writer(MSSndCard *obj); - -/** - * Create a new sound card object. - * - * @param desc A sound card description object. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_new(MSSndCardDesc *desc); - -/** - * Destroy sound card object. - * - * @param obj A MSSndCard object. - */ -void ms_snd_card_destroy(MSSndCard *obj); - -/** - * Duplicate a sound card object. - * - * This helps to open several time a sound card. - * - * @param card A sound card object. - * - * Returns: MSSndCard if successfull, NULL otherwise. - */ -MSSndCard * ms_snd_card_dup(MSSndCard *card); - -/** - * Retreive a sound card's driver type string. - * - * Internal driver types are either: "OSS, ALSA, WINSND, PASND, CA" - * - * @param obj A sound card object. - * - * Returns: a string if successfull, NULL otherwise. - */ -const char *ms_snd_card_get_driver_type(const MSSndCard *obj); - -/** - * Retreive a sound card's name. - * - * @param obj A sound card object. - * - * Returns: a string if successfull, NULL otherwise. - */ -const char *ms_snd_card_get_name(const MSSndCard *obj); - -/** - * Retreive sound card's name ($driver_type: $name). - * - * @param obj A sound card object. - * - * Returns: A string if successfull, NULL otherwise. - */ -const char *ms_snd_card_get_string_id(MSSndCard *obj); - - -/** - * Retreive sound card's capabilities. - * - *
- *   MS_SND_CARD_CAP_CAPTURE
- *   MS_SND_CARD_CAP_PLAYBACK
- *   MS_SND_CARD_CAP_CAPTURE|MS_SND_CARD_CAP_PLAYBACK
- * 
- * - * @param obj A sound card object. - * - * Returns: A unsigned int if successfull, 0 otherwise. - */ -unsigned int ms_snd_card_get_capabilities(const MSSndCard *obj); - -/** - * Set some mixer level value. - * - *
- *   MS_SND_CARD_MASTER,
- *   MS_SND_CARD_PLAYBACK,
- *   MS_SND_CARD_CAPTURE
- * 
- * Note: not implemented on all sound card filters. - * - * @param obj A sound card object. - * @param e A sound card mixer object. - * @param percent A volume level. - * - */ -void ms_snd_card_set_level(MSSndCard *obj, MSSndCardMixerElem e, int percent); - -/** - * Get some mixer level value. - * - *
- *   MS_SND_CARD_MASTER,
- *   MS_SND_CARD_PLAYBACK,
- *   MS_SND_CARD_CAPTURE
- * 
- * Note: not implemented on all sound card filters. - * - * @param obj A sound card object. - * @param e A sound card mixer object. - * - * Returns: A int if successfull, <0 otherwise. - */ -int ms_snd_card_get_level(MSSndCard *obj, MSSndCardMixerElem e); - -/** - * Set some source for capture. - * - *
- *   MS_SND_CARD_MIC,
- *   MS_SND_CARD_LINE
- * 
- * Note: not implemented on all sound card filters. - * - * @param obj A sound card object. - * @param c A sound card capture value. - * - * Returns: A int if successfull, 0 otherwise. - */ -void ms_snd_card_set_capture(MSSndCard *obj, MSSndCardCapture c); - -/** - * Set some mixer control. - * - *
- *   MS_SND_CARD_MASTER_MUTE, -> 0: unmute, 1: mute
- *   MS_SND_CARD_PLAYBACK_MUTE, -> 0: unmute, 1: mute
- *   MS_SND_CARD_CAPTURE_MUTE -> 0: unmute, 1: mute
- * 
- * Note: not implemented on all sound card filters. - * - * @param obj A sound card object. - * @param e A sound card control object. - * @param percent A value for control. - * - * Returns: 0 if successfull, <0 otherwise. - */ -int ms_snd_card_set_control(MSSndCard *obj, MSSndCardControlElem e, int val); - -/** - * Get some mixer control. - * - *
- *   MS_SND_CARD_MASTER_MUTE, -> return 0: unmute, 1: mute
- *   MS_SND_CARD_PLAYBACK_MUTE, -> return 0: unmute, 1: mute
- *   MS_SND_CARD_CAPTURE_MUTE -> return 0: unmute, 1: mute
- * 
- * Note: not implemented on all sound card filters. - * - * @param obj A sound card object. - * @param e A sound card mixer object. - * - * Returns: A int if successfull, <0 otherwise. - */ -int ms_snd_card_get_control(MSSndCard *obj, MSSndCardControlElem e); - -/** - * Create a alsa card with user supplied pcm name and mixer name. - * @param pcmdev The pcm device name following alsa conventions (ex: plughw:0) - * @param mixdev The mixer device name following alsa conventions. - * - * Returns: a MSSndCard object, NULL if alsa support is not available. - */ -MSSndCard * ms_alsa_card_new_custom(const char *pcmdev, const char *mixdev); - - -/** @} */ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msspeexec.h b/linphone/mediastreamer2/include/mediastreamer2/msspeexec.h deleted file mode 100644 index e9bc24d26..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msspeexec.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006-2009 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. - -msspeexec.h : interface of the speex echo canceler integration in mediastreamer2 - -*/ - -#ifndef msspeexec_h -#define msspeexec_h - -#include - -/** sets the tail length in milliseconds*/ -#define MS_SPEEX_EC_SET_TAIL_LENGTH MS_FILTER_METHOD(MS_SPEEX_EC_ID,0,int) - -/** sets the minimum delay of the echo if known. This optimizes the convergence*/ -#define MS_SPEEX_EC_SET_DELAY MS_FILTER_METHOD(MS_SPEEX_EC_ID,1,int) - -/** sets the frame size for the AU-MDF algorithm, in number of fft points*/ -#define MS_SPEEX_EC_SET_FRAME_SIZE MS_FILTER_METHOD(MS_SPEEX_EC_ID,2,int) - - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/mstee.h b/linphone/mediastreamer2/include/mediastreamer2/mstee.h deleted file mode 100644 index dd418bfda..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/mstee.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ -#ifndef mstee_h -#define mstee_h - -#include "msfilter.h" - -/*mute/unmute some outputs of the MSTee */ -#define MS_TEE_UNMUTE MS_FILTER_METHOD(MS_TEE_ID,0,int) -#define MS_TEE_MUTE MS_FILTER_METHOD(MS_TEE_ID,1,int) - - - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msticker.h b/linphone/mediastreamer2/include/mediastreamer2/msticker.h deleted file mode 100644 index 12a430e07..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msticker.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifndef MS_TICKER_H -#define MS_TICKER_H - - -#include "msfilter.h" -#include "mscommon.h" - -/** - * @file msticker.h - * @brief mediastreamer2 msticker.h include file - * - * This file provide the API needed to create, start - * and stop a graph. - * - */ - -/** - * @defgroup mediastreamer2_ticker Ticker API - manage mediastreamer2 graphs. - * @ingroup mediastreamer2_api - * @{ - */ - - -/** - * Structure for method getting time in miliseconds from an external source. - * @var MSTickerTimeFunc - */ -typedef uint64_t (*MSTickerTimeFunc)(void *); - -struct _MSTicker -{ - ms_mutex_t lock; - ms_cond_t cond; - MSList *execution_list; /* the list of source filters to be executed.*/ - ms_thread_t thread; /* the thread ressource*/ - int interval; /* in miliseconds*/ - int exec_id; - uint32_t ticks; - uint64_t time; /* a time since the start of the ticker expressed in milisec*/ - uint64_t orig; /* a relative time to take in account difference between time base given by consecutive get_cur_time_ptr() functions.*/ - MSTickerTimeFunc get_cur_time_ptr; - void *get_cur_time_data; - char *name; - bool_t run; /* flag to indicate whether the ticker must be run or not */ -#ifdef WIN32_TIMERS - HANDLE TimeEvent; -#endif -}; - -/** - * Structure for ticker object. - * @var MSTicker - */ -typedef struct _MSTicker MSTicker; - - -#ifdef __cplusplus -extern "C"{ -#endif - - -/** - * Create a ticker that will be used to start - * and stop a graph. - * - * Returns: MSTicker * if successfull, NULL otherwise. - */ -MSTicker *ms_ticker_new(void); - -/** - * Set a name to the ticker (used for logging) -**/ -void ms_ticker_set_name(MSTicker *ticker, const char *name); - -/** - * Attach a chain of filters to a ticker. - * The processing chain will be executed until ms_ticker_detach - * will be called. - * - * @param ticker A #MSTicker object. - * @param f A #MSFilter object. - * - * Returns: 0 if successfull, -1 otherwise. - */ -int ms_ticker_attach(MSTicker *ticker,MSFilter *f); - -/** - * Dettach a chain of filters to a ticker. - * The processing chain will no more be executed. - * - * @param ticker A #MSTicker object. - * @param f A #MSFilter object. - * - * - * Returns: 0 if successfull, -1 otherwise. - */ -int ms_ticker_detach(MSTicker *ticker,MSFilter *f); - -/** - * Destroy a ticker. - * - * @param ticker A #MSTicker object. - * - */ -void ms_ticker_destroy(MSTicker *ticker); - -/** - * Override MSTicker's time function. - * This can be used to control the ticker from an external time provider, for example the - * clock of a sound card. - * - * @param ticker A #MSTicker object. - * @param func A replacement method for calculating "current time" - * @param user_data Any pointer to user private data. - */ -void ms_ticker_set_time_func(MSTicker *ticker, MSTickerTimeFunc func, void *user_data); - -/** - * Print on stdout all filters of a ticker. (INTERNAL: DO NOT USE) - * - * @param ticker A #MSTicker object. - */ -void ms_ticker_print_graphs(MSTicker *ticker); - -/* private functions:*/ - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msv4l.h b/linphone/mediastreamer2/include/mediastreamer2/msv4l.h deleted file mode 100644 index 2d7056d0b..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msv4l.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef msv4l_h -#define msv4l_h - -#include "msfilter.h" - -#define MS_V4L_START MS_FILTER_METHOD_NO_ARG(MS_V4L_ID,0) -#define MS_V4L_STOP MS_FILTER_METHOD_NO_ARG(MS_V4L_ID,1) -#define MS_V4L_SET_DEVICE MS_FILTER_METHOD(MS_V4L_ID,2,int) -#define MS_V4L_SET_IMAGE MS_FILTER_METHOD(MS_V4L_ID,3,char) - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msvideo.h b/linphone/mediastreamer2/include/mediastreamer2/msvideo.h deleted file mode 100644 index f96129d83..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msvideo.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef msvideo_h -#define msvideo_h - -#include "msfilter.h" - -/* some global constants for video MSFilter(s) */ -#define MS_VIDEO_SIZE_SQCIF_W 128 -#define MS_VIDEO_SIZE_SQCIF_H 96 -#define MS_VIDEO_SIZE_QCIF_W 176 -#define MS_VIDEO_SIZE_QCIF_H 144 -#define MS_VIDEO_SIZE_CIF_W 352 -#define MS_VIDEO_SIZE_CIF_H 288 -#define MS_VIDEO_SIZE_ICIF_W 352 -#define MS_VIDEO_SIZE_ICIF_H 576 -#define MS_VIDEO_SIZE_4CIF_W 704 -#define MS_VIDEO_SIZE_4CIF_H 576 - -#define MS_VIDEO_SIZE_QQVGA_W 160 -#define MS_VIDEO_SIZE_QQVGA_H 120 -#define MS_VIDEO_SIZE_QVGA_W 320 -#define MS_VIDEO_SIZE_QVGA_H 240 -#define MS_VIDEO_SIZE_VGA_W 640 -#define MS_VIDEO_SIZE_VGA_H 480 -#define MS_VIDEO_SIZE_SVGA_W 800 -#define MS_VIDEO_SIZE_SVGA_H 600 - -#define MS_VIDEO_SIZE_NS1_W 324 -#define MS_VIDEO_SIZE_NS1_H 248 - -#define MS_VIDEO_SIZE_QSIF_W 176 -#define MS_VIDEO_SIZE_QSIF_H 120 -#define MS_VIDEO_SIZE_SIF_W 352 -#define MS_VIDEO_SIZE_SIF_H 240 -#define MS_VIDEO_SIZE_ISIF_W 352 -#define MS_VIDEO_SIZE_ISIF_H 480 -#define MS_VIDEO_SIZE_4SIF_W 704 -#define MS_VIDEO_SIZE_4SIF_H 480 - -#define MS_VIDEO_SIZE_288P_W 512 -#define MS_VIDEO_SIZE_288P_H 288 -#define MS_VIDEO_SIZE_448P_W 768 -#define MS_VIDEO_SIZE_448P_H 448 -#define MS_VIDEO_SIZE_576P_W 1024 -#define MS_VIDEO_SIZE_576P_H 576 -#define MS_VIDEO_SIZE_720P_W 1280 -#define MS_VIDEO_SIZE_720P_H 720 -#define MS_VIDEO_SIZE_1080P_W 1920 -#define MS_VIDEO_SIZE_1080P_H 1080 - -#define MS_VIDEO_SIZE_SDTV_W 768 -#define MS_VIDEO_SIZE_SDTV_H 576 -#define MS_VIDEO_SIZE_HDTVP_W 1920 -#define MS_VIDEO_SIZE_HDTVP_H 1200 - -#define MS_VIDEO_SIZE_XGA_W 1024 -#define MS_VIDEO_SIZE_XGA_H 768 -#define MS_VIDEO_SIZE_WXGA_W 1080 -#define MS_VIDEO_SIZE_WXGA_H 768 - -#define MS_VIDEO_SIZE_MAX_W MS_VIDEO_SIZE_1024_W -#define MS_VIDEO_SIZE_MAX_H MS_VIDEO_SIZE_1024_H - - -/* those structs are part of the ABI: don't change their size otherwise binary plugins will be broken*/ - -typedef struct MSVideoSize{ - int width,height; -} MSVideoSize; - -typedef struct MSRect{ - int x,y,w,h; -} MSRect; - -#define MS_VIDEO_SIZE_CIF (MSVideoSize){MS_VIDEO_SIZE_CIF_W,MS_VIDEO_SIZE_CIF_H} -#define MS_VIDEO_SIZE_QCIF (MSVideoSize){MS_VIDEO_SIZE_QCIF_W,MS_VIDEO_SIZE_QCIF_H} -#define MS_VIDEO_SIZE_4CIF (MSVideoSize){MS_VIDEO_SIZE_4CIF_W,MS_VIDEO_SIZE_4CIF_H} - -#define MS_VIDEO_SIZE_QQVGA (MSVideoSize){MS_VIDEO_SIZE_QQVGA_W,MS_VIDEO_SIZE_QQVGA_H} -#define MS_VIDEO_SIZE_QVGA (MSVideoSize){MS_VIDEO_SIZE_QVGA_W,MS_VIDEO_SIZE_QVGA_H} -#define MS_VIDEO_SIZE_VGA (MSVideoSize){MS_VIDEO_SIZE_VGA_W,MS_VIDEO_SIZE_VGA_H} - -#define MS_VIDEO_SIZE_720P (MSVideoSize){MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H} - -#define MS_VIDEO_SIZE_NS1 (MSVideoSize){MS_VIDEO_SIZE_NS1_W,MS_VIDEO_SIZE_NS1_H} - -#define MS_VIDEO_SIZE_XGA (MSVideoSize){MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H} - -#define MS_VIDEO_SIZE_SVGA (MSVideoSize){MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H} - -/*deprecated: use MS_VIDEO_SIZE_SVGA*/ -#define MS_VIDEO_SIZE_800X600_W MS_VIDEO_SIZE_SVGA_W -#define MS_VIDEO_SIZE_800X600_H MS_VIDEO_SIZE_SVGA_H -#define MS_VIDEO_SIZE_800X600 MS_VIDEO_SIZE_SVGA -/*deprecated use MS_VIDEO_SIZE_XGA*/ -#define MS_VIDEO_SIZE_1024_W 1024 -#define MS_VIDEO_SIZE_1024_H 768 -#define MS_VIDEO_SIZE_1024 MS_VIDEO_SIZE_XGA - -typedef enum{ - MS_YUV420P, - MS_YUYV, - MS_RGB24, - MS_RGB24_REV, /*->microsoft down-top bitmaps */ - MS_MJPEG, - MS_UYVY, - MS_YUY2, /* -> same as MS_YUYV */ - MS_PIX_FMT_UNKNOWN -}MSPixFmt; - -typedef struct _MSPicture{ - int w,h; - uint8_t *planes[4]; /*we usually use 3 planes, 4th is for compatibility */ - int strides[4]; /*with ffmpeg's swscale.h */ -}MSPicture; - -typedef struct _MSPicture YuvBuf; /*for backward compatibility*/ - -#ifdef __cplusplus -extern "C"{ -#endif - -int ms_pix_fmt_to_ffmpeg(MSPixFmt fmt); -MSPixFmt ffmpeg_pix_fmt_to_ms(int fmt); -MSPixFmt ms_fourcc_to_pix_fmt(uint32_t fourcc); -void ms_ffmpeg_check_init(void); -int yuv_buf_init_from_mblk(MSPicture *buf, mblk_t *m); -void yuv_buf_init_from_mblk_with_size(MSPicture *buf, mblk_t *m, int w, int h); -mblk_t * yuv_buf_alloc(MSPicture *buf, int w, int h); -void yuv_buf_copy(uint8_t *src_planes[], const int src_strides[], - uint8_t *dst_planes[], const int dst_strides[3], MSVideoSize roi); -void yuv_buf_mirror(YuvBuf *buf); -void rgb24_revert(uint8_t *buf, int w, int h, int linesize); -void rgb24_copy_revert(uint8_t *dstbuf, int dstlsz, - const uint8_t *srcbuf, int srclsz, MSVideoSize roi); - -static inline bool_t ms_video_size_greater_than(MSVideoSize vs1, MSVideoSize vs2){ - return (vs1.width>=vs2.width) && (vs1.height>=vs2.height); -} - -static inline MSVideoSize ms_video_size_max(MSVideoSize vs1, MSVideoSize vs2){ - return ms_video_size_greater_than(vs1,vs2) ? vs1 : vs2; -} - -static inline MSVideoSize ms_video_size_min(MSVideoSize vs1, MSVideoSize vs2){ - return ms_video_size_greater_than(vs1,vs2) ? vs2 : vs1; -} - -static inline bool_t ms_video_size_equal(MSVideoSize vs1, MSVideoSize vs2){ - return vs1.width==vs2.width && vs1.height==vs2.height; -} - -MSVideoSize ms_video_size_get_just_lower_than(MSVideoSize vs); - -#ifdef __cplusplus -} -#endif - -#define MS_FILTER_SET_VIDEO_SIZE MS_FILTER_BASE_METHOD(100,MSVideoSize) -#define MS_FILTER_GET_VIDEO_SIZE MS_FILTER_BASE_METHOD(101,MSVideoSize) - -#define MS_FILTER_SET_PIX_FMT MS_FILTER_BASE_METHOD(102,MSPixFmt) -#define MS_FILTER_GET_PIX_FMT MS_FILTER_BASE_METHOD(103,MSPixFmt) - -#define MS_FILTER_SET_FPS MS_FILTER_BASE_METHOD(104,float) -#define MS_FILTER_GET_FPS MS_FILTER_BASE_METHOD(105,float) - -/* request a video-fast-update (=I frame for H263,MP4V-ES) to a video encoder*/ -#define MS_FILTER_REQ_VFU MS_FILTER_BASE_METHOD_NO_ARG(106) - -#define MS_FILTER_SET_IMAGE MS_FILTER_BASE_METHOD(107,char) - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msvideoout.h b/linphone/mediastreamer2/include/mediastreamer2/msvideoout.h deleted file mode 100644 index 0384f6d39..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msvideoout.h +++ /dev/null @@ -1,104 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef msvideoout_h -#define msvideoout_h - -#include -#include - - -struct _MSDisplay; - -typedef enum _MSDisplayEventType{ - MS_DISPLAY_RESIZE_EVENT -}MSDisplayEventType; - -typedef struct _MSDisplayEvent{ - MSDisplayEventType evtype; - int w,h; -}MSDisplayEvent; - -typedef struct _MSDisplayDesc{ - /*init requests setup of the display window at the proper size, given - in frame_buffer argument. Memory buffer (data,strides) must be fulfilled - at return. init() might be called several times upon screen resize*/ - bool_t (*init)(struct _MSDisplay *, MSPicture *frame_buffer); - void (*lock)(struct _MSDisplay *);/*lock before writing to the framebuffer*/ - void (*unlock)(struct _MSDisplay *);/*unlock after writing to the framebuffer*/ - void (*update)(struct _MSDisplay *); /*display the picture to the screen*/ - void (*uninit)(struct _MSDisplay *); - bool_t (*pollevent)(struct _MSDisplay *, MSDisplayEvent *ev); - long default_window_id; -}MSDisplayDesc; - -typedef struct _MSDisplay{ - MSDisplayDesc *desc; - long window_id; /*window id if the display should use an existing window*/ - void *data; - bool_t use_external_window; -} MSDisplay; - - -#define ms_display_init(d,fbuf) (d)->desc->init(d,fbuf) -#define ms_display_lock(d) if ((d)->desc->lock) (d)->desc->lock(d) -#define ms_display_unlock(d) if ((d)->desc->unlock) (d)->desc->unlock(d) -#define ms_display_update(d) if ((d)->desc->update) (d)->desc->update(d) -bool_t ms_display_poll_event(MSDisplay *d, MSDisplayEvent *ev); - -extern MSDisplayDesc ms_sdl_display_desc; - -#if (defined(WIN32) || defined(_WIN32_WCE)) && !defined(MEDIASTREAMER_STATIC) -#if defined(MEDIASTREAMER2_EXPORTS) && defined(INVIDEOUT_C) - #define MSVAR_DECLSPEC __declspec(dllexport) -#else - #define MSVAR_DECLSPEC __declspec(dllimport) -#endif -#else - #define MSVAR_DECLSPEC extern -#endif - -#ifdef __cplusplus -extern "C"{ -#endif - -/*plugins can set their own display using this method:*/ -void ms_display_desc_set_default(MSDisplayDesc *desc); - -MSDisplayDesc * ms_display_desc_get_default(void); -void ms_display_desc_set_default_window_id(MSDisplayDesc *desc, long id); - -MSVAR_DECLSPEC MSDisplayDesc ms_win_display_desc; - -MSDisplay *ms_display_new(MSDisplayDesc *desc); -void ms_display_set_window_id(MSDisplay *d, long window_id); -void ms_display_destroy(MSDisplay *d); - -#define MS_VIDEO_OUT_SET_DISPLAY MS_FILTER_METHOD(MS_VIDEO_OUT_ID,0,MSDisplay*) -#define MS_VIDEO_OUT_HANDLE_RESIZING MS_FILTER_METHOD_NO_ARG(MS_VIDEO_OUT_ID,1) -#define MS_VIDEO_OUT_SET_CORNER MS_FILTER_METHOD(MS_VIDEO_OUT_ID,2,int) -#define MS_VIDEO_OUT_AUTO_FIT MS_FILTER_METHOD(MS_VIDEO_OUT_ID,3,int) -#define MS_VIDEO_OUT_ENABLE_MIRRORING MS_FILTER_METHOD(MS_VIDEO_OUT_ID,4,int) -#define MS_VIDEO_OUT_GET_NATIVE_WINDOW_ID MS_FILTER_METHOD(MS_VIDEO_OUT_ID,5,unsigned long) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/msvolume.h b/linphone/mediastreamer2/include/mediastreamer2/msvolume.h deleted file mode 100644 index cf2f02b21..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/msvolume.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef msvolume_h -#define msvolume_h - -#include "msfilter.h" - -/** - * The Volume MSFilter can do: - * - measurements of the input signal power, returned in dbm0 or linear scale - * - apply a gain to the input signal and output this amplified signal to its output. - * By default gain is 1, in which case the filter does not modify the signal (and even does not - * copy the buffers, just post them on its output queue. -**/ - - -/*returns a volume meter in db0 (max=0 db0)*/ -#define MS_VOLUME_GET MS_FILTER_METHOD(MS_VOLUME_ID,0,float) -/*returns a volume in linear scale between 0 and 1 */ -#define MS_VOLUME_GET_LINEAR MS_FILTER_METHOD(MS_VOLUME_ID,1,float) -/* set a gain */ -#define MS_VOLUME_SET_GAIN MS_FILTER_METHOD(MS_VOLUME_ID,2,float) - -#define MS_VOLUME_GET_EA_STATE MS_FILTER_METHOD(MS_VOLUME_ID,3, int) - -#define MS_VOLUME_SET_PEER MS_FILTER_METHOD(MS_VOLUME_ID,4, MSFilter ) - -#define MS_VOLUME_SET_EA_THRESHOLD MS_FILTER_METHOD(MS_VOLUME_ID,5,float) - -#define MS_VOLUME_SET_EA_SPEED MS_FILTER_METHOD(MS_VOLUME_ID,6,float) - -#define MS_VOLUME_SET_EA_FORCE MS_FILTER_METHOD(MS_VOLUME_ID,7,float) - -#define MS_VOLUME_ENABLE_AGC MS_FILTER_METHOD(MS_VOLUME_ID,8,int) - -#define MS_VOLUME_ENABLE_NOISE_GATE MS_FILTER_METHOD(MS_VOLUME_ID,9,int) - -#define MS_VOLUME_SET_NOISE_GATE_THRESHOLD MS_FILTER_METHOD(MS_VOLUME_ID,10,float) - -#define MS_VOLUME_SET_EA_SUSTAIN MS_FILTER_METHOD(MS_VOLUME_ID,11,int) - -#define MS_VOLUME_SET_NOISE_GATE_FLOORGAIN MS_FILTER_METHOD(MS_VOLUME_ID,12,float) - -extern MSFilterDesc ms_volume_desc; - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/mswebcam.h b/linphone/mediastreamer2/include/mediastreamer2/mswebcam.h deleted file mode 100644 index f56f1f81b..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/mswebcam.h +++ /dev/null @@ -1,233 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef webcam_h -#define webcam_h - -#include "mscommon.h" - -/** - * @file mswebcam.h - * @brief mediastreamer2 mswebcam.h include file - * - * This file provide the API needed to manage - * soundcard filters. - * - */ - -/** - * @defgroup mediastreamer2_webcam Camera API - manage video capture devices - * @ingroup mediastreamer2_api - * @{ - */ - -struct _MSWebCamManager{ - MSList *cams; - MSList *descs; -}; - -/** - * Structure for webcam manager object. - * @var MSWebCamManager - */ -typedef struct _MSWebCamManager MSWebCamManager; - - -struct _MSWebCam; - -typedef void (*MSWebCamDetectFunc)(MSWebCamManager *obj); -typedef void (*MSWebCamInitFunc)(struct _MSWebCam *obj); -typedef void (*MSWebCamUninitFunc)(struct _MSWebCam *obj); -typedef struct _MSFilter * (*MSWebCamCreateReaderFunc)(struct _MSWebCam *obj); - -struct _MSWebCamDesc{ - const char *driver_type; - MSWebCamDetectFunc detect; - MSWebCamInitFunc init; - MSWebCamCreateReaderFunc create_reader; - MSWebCamUninitFunc uninit; -}; - -/** - * Structure for sound card description object. - * @var MSWebCamDesc - */ -typedef struct _MSWebCamDesc MSWebCamDesc; - -struct _MSWebCam{ - MSWebCamDesc *desc; - char *name; - char *id; - void *data; -}; - -/** - * Structure for sound card object. - * @var MSWebCam - */ -typedef struct _MSWebCam MSWebCam; - -#ifdef __cplusplus -extern "C"{ -#endif - -/** - * Retreive a webcam manager object. - * - * Returns: MSWebCamManager if successfull, NULL otherwise. - */ -MSWebCamManager * ms_web_cam_manager_get(void); - -/** - * Destroy the webcam manager object. - * - */ -void ms_web_cam_manager_destroy(void); - -/** - * Retreive a webcam object based on its name. - * - * @param m A webcam manager containing webcam. - * @param id A name for card to search. - * - * Returns: MSWebCam if successfull, NULL otherwise. - */ -MSWebCam * ms_web_cam_manager_get_cam(MSWebCamManager *m, const char *id); - -/** - * Retreive the default webcam object. - * - * @param m A webcam manager containing webcams. - * - * Returns: MSWebCam if successfull, NULL otherwise. - */ -MSWebCam * ms_web_cam_manager_get_default_cam(MSWebCamManager *m); - -/** - * Retreive the list of webcam objects. - * - * @param m A webcam manager containing webcams. - * - * Returns: MSList of cards if successfull, NULL otherwise. - */ -const MSList * ms_web_cam_manager_get_list(MSWebCamManager *m); - -/** - * Add a webcam object in a webcam manager's list. - * - * @param m A webcam manager containing webcams - * @param c A web cam object. - * - */ -void ms_web_cam_manager_add_cam(MSWebCamManager *m, MSWebCam *c); - -/** - * Add a webcam object on top of list of the webcam manager's list. - * - * @param m A webcam manager containing webcams - * @param c A web cam object. - * - */ -void ms_web_cam_manager_prepend_cam(MSWebCamManager *m, MSWebCam *c); - - -/** - * Register a webcam descriptor in a webcam manager. - * - * @param m A webcam manager containing sound cards. - * @param desc A webcam descriptor object. - * - */ -void ms_web_cam_manager_register_desc(MSWebCamManager *m, MSWebCamDesc *desc); - - -/** - * Ask all registered MSWebCamDesc to detect the webcams again. - * - * @param m A webcam manager -**/ -void ms_web_cam_manager_reload(MSWebCamManager *m); - -/** - * Create an INPUT filter based on the selected camera. - * - * @param obj A webcam object. - * - * Returns: A MSFilter if successfull, NULL otherwise. - */ -struct _MSFilter * ms_web_cam_create_reader(MSWebCam *obj); - -/** - * Create a new webcam object. - * - * @param desc A webcam description object. - * - * Returns: MSWebCam if successfull, NULL otherwise. - */ -MSWebCam * ms_web_cam_new(MSWebCamDesc *desc); - -/** - * Destroy webcam object. - * - * @param obj A MSWebCam object. - */ -void ms_web_cam_destroy(MSWebCam *obj); - - -/** - * Retreive a webcam's driver type string. - * - * Internal driver types are either: "V4L V4LV2" - * - * @param obj A webcam object. - * - * Returns: a string if successfull, NULL otherwise. - */ -const char *ms_web_cam_get_driver_type(const MSWebCam *obj); - -/** - * Retreive a webcam's name. - * - * @param obj A webcam object. - * - * Returns: a string if successfull, NULL otherwise. - */ -const char *ms_web_cam_get_name(const MSWebCam *obj); - -/** - * Retreive webcam's id: ($driver_type: $name). - * - * @param obj A webcam object. - * - * Returns: A string if successfull, NULL otherwise. - */ -const char *ms_web_cam_get_string_id(MSWebCam *obj); - - -/*specific methods for static image:*/ - -void ms_static_image_set_default_image(const char *path); - -#ifdef __cplusplus -} -#endif - -/** @} */ - -#endif diff --git a/linphone/mediastreamer2/include/mediastreamer2/rfc3984.h b/linphone/mediastreamer2/include/mediastreamer2/rfc3984.h deleted file mode 100644 index aa9a45127..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/rfc3984.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef rfc3984_h -#define rfc3984_h - -#include "mediastreamer2/mscommon.h" -#include "mediastreamer2/msqueue.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -typedef struct Rfc3984Context{ - MSQueue q; - mblk_t *m; - int maxsz; - uint32_t last_ts; - uint8_t mode; - bool_t stap_a_allowed; - uint8_t reserved; -} Rfc3984Context; - -void rfc3984_init(Rfc3984Context *ctx); - -void rfc3984_set_mode(Rfc3984Context *ctx, int mode); - -/* some stupid phones don't decode STAP-A packets ...*/ -void rfc3984_enable_stap_a(Rfc3984Context *ctx, bool_t yesno); - -/*process NALUs and pack them into rtp payloads */ -void rfc3984_pack(Rfc3984Context *ctx, MSQueue *naluq, MSQueue *rtpq, uint32_t ts); - -/*process incoming rtp data and output NALUs, whenever possible*/ -void rfc3984_unpack(Rfc3984Context *ctx, mblk_t *im, MSQueue *naluq); - -void rfc3984_uninit(Rfc3984Context *ctx); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/linphone/mediastreamer2/include/mediastreamer2/waveheader.h b/linphone/mediastreamer2/include/mediastreamer2/waveheader.h deleted file mode 100644 index d929f5c6d..000000000 --- a/linphone/mediastreamer2/include/mediastreamer2/waveheader.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -/* the following code was taken from a free software utility that I don't remember the name. */ -/* sorry */ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#ifndef waveheader_h -#define waveheader_h - -#ifdef swap16 -#else -/* all integer in wav header must be read in least endian order */ -static inline uint16_t swap16(uint16_t a) -{ - return ((a & 0xFF) << 8) | ((a & 0xFF00) >> 8); -} -#endif - -#ifdef swap32 -#else -static inline uint32_t swap32(uint32_t a) -{ - return ((a & 0xFF) << 24) | ((a & 0xFF00) << 8) | - ((a & 0xFF0000) >> 8) | ((a & 0xFF000000) >> 24); -} -#endif - -#ifdef WORDS_BIGENDIAN -#define le_uint32(a) (swap32((a))) -#define le_uint16(a) (swap16((a))) -#define le_int16(a) ( (int16_t) swap16((uint16_t)((a))) ) -#else -#define le_uint32(a) (a) -#define le_uint16(a) (a) -#define le_int16(a) (a) -#endif - -typedef struct _riff_t { - char riff[4] ; /* "RIFF" (ASCII characters) */ - uint32_t len ; /* Length of package (binary, little endian) */ - char wave[4] ; /* "WAVE" (ASCII characters) */ -} riff_t; - -/* The FORMAT chunk */ - -typedef struct _format_t { - char fmt[4] ; /* "fmt_" (ASCII characters) */ - uint32_t len ; /* length of FORMAT chunk (always 0x10) */ - uint16_t type; /* codec type*/ - uint16_t channel ; /* Channel numbers (0x01 = mono, 0x02 = stereo) */ - uint32_t rate ; /* Sample rate (binary, in Hz) */ - uint32_t bps ; /* Average Bytes Per Second */ - uint16_t blockalign ; /*number of bytes per sample */ - uint16_t bitpspl ; /* bits per sample */ -} format_t; - -/* The DATA chunk */ - -typedef struct _data_t { - char data[4] ; /* "data" (ASCII characters) */ - int len ; /* length of data */ -} data_t; - -typedef struct _wave_header_t -{ - riff_t riff_chunk; - format_t format_chunk; - data_t data_chunk; -} wave_header_t; - - -#define wave_header_get_rate(header) le_uint32((header)->format_chunk.rate) -#define wave_header_get_channel(header) le_uint16((header)->format_chunk.channel) -#define wave_header_get_bpsmpl(header) \ - le_uint16((header)->format_chunk.blockalign) -#endif diff --git a/linphone/mediastreamer2/mediastreamer.pc.in b/linphone/mediastreamer2/mediastreamer.pc.in deleted file mode 100644 index 55a763e69..000000000 --- a/linphone/mediastreamer2/mediastreamer.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -# This is a comment -prefix=@prefix@ -exec_prefix=@exec_prefix@ -includedir=@includedir@ - -Name: mediastreamer -Description: A mediastreaming library for telephony applications -Requires: ortp -Version: @MEDIASTREAMER_VERSION@ -Libs: -L@libdir@ -lmediastreamer -Cflags: -I@includedir@ @MS_PUBLIC_CFLAGS@ diff --git a/linphone/mediastreamer2/mediastreamer2.spec.in b/linphone/mediastreamer2/mediastreamer2.spec.in deleted file mode 100644 index ff1e4492e..000000000 --- a/linphone/mediastreamer2/mediastreamer2.spec.in +++ /dev/null @@ -1,81 +0,0 @@ -# -*- rpm-spec -*- -# -# mediastreamer2 -- A mediastreaming library for telephony applications -# - -%ifarch %ix86 -%define mediastreamer2_cpu pentium4 -%endif - -Summary: Audio/Video real-time streaming -Name: mediastreamer2 -Version: @MEDIASTREAMER2_PKGCONFIG_VERSION@ -Release: 1 -License: LGPL -Group: Applications/Communications -URL: http://linphone.org/mediastreamer2/ -Source0: %{name}-@MEDIASTREAMER2_PKGCONFIG_VERSION@.tar.gz -BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot -%ifarch %ix86 -BuildArch: i686 -%endif - -%description -Mediastreamer2 is a GPL licensed library to make audio and video -real-time streaming and processing. Written in pure C, it is based -upon the oRTP library. - -%package devel -Summary: Headers, libraries and docs for the mediastreamer2 library -Group: Development/Libraries -Requires: %{name} = %{version}-%{release} - -%description devel -Mediastreamer2 is a GPL licensed library to make audio and video -real-time streaming and processing. Written in pure C, it is based -upon the ortp library. - -This package contains header files and development libraries needed to -develop programs using the mediastreamer2 library. - -%ifarch %ix86 -%define mediastreamer2_arch_cflags -malign-double -march=i686 -mcpu=%{mediastreamer2_cpu} -%else -# Must be non-empty -%define mediastreamer2_arch_cflags -Wall -%endif -%define mediastreamer2_cflags %mediastreamer2_arch_cflags -Wall -g -pipe -pthread -O3 -fomit-frame-pointer -fno-schedule-insns -fschedule-insns2 -fstrict-aliasing - -%prep -%setup -q - -%build -%configure \ ---enable-gtk-doc=no \ ---enable-shared --enable-static -make -j$RPM_BUILD_NCPUS CFLAGS="%mediastreamer2_cflags" CXXFLAGS="%mediastreamer2_cflags" - -%install -rm -rf $RPM_BUILD_ROOT -%makeinstall - -%clean -rm -rf $RPM_BUILD_ROOT - -%files -%defattr(-,root,root,-) -%doc AUTHORS COPYING ChangeLog INSTALL NEWS README TODO -%{_libdir}/*.so.* - -%files devel -%defattr(-,root,root,-) -%doc docs/html -%{_libdir}/*.la -%{_libdir}/*.a -%{_libdir}/*.so -%{_libdir}/pkgconfig/*.pc -%{_includedir} - -%changelog -* Tue Oct 25 2005 Francois-Xavier Kowalski -- Add to mediastreamer2 distribution with "make rpm" target diff --git a/linphone/mediastreamer2/pkg.list b/linphone/mediastreamer2/pkg.list deleted file mode 100644 index cee1171f7..000000000 --- a/linphone/mediastreamer2/pkg.list +++ /dev/null @@ -1,43 +0,0 @@ -# -*- rpm-spec -*- ############################################################ -# -# EPM list file. See epm(1) and epm.list(5) for details -# -############################################################################### - -%product ${SUMMARY} -%version ${VERSION} -%release ${RELEASE} -%description ${SUMMARY} -%vendor ${VENDOR} -%copyright ${LICENSE} -%license ${LICENSE} -%readme ${srcdir}/README -%packager ${PACKAGER} - -%system linux - -# Compress man pages -%define __spec_install_post /usr/lib/rpm/brp-compress || : - -# Package all-in one: should be split later on... -%provides ortp-devel - -%postinstall << EOF -ldconfig 2>&1 | logger -i -s -t ${PACKAGE} -makewhatis -u -w 2>&1 | logger -i -s -t ${PACKAGE} -EOF - -%postremove << EOF -ldconfig 2>&1 | logger -i -s -t ${PACKAGE} -makewhatis -u -w 2>&1 | logger -i -s -t ${PACKAGE} -EOF - -%system hpux - -%system all - -%include files.list - -%provides mediastreamer2 -%replaces mediastreamer2 - diff --git a/linphone/mediastreamer2/plugins/.gitignore b/linphone/mediastreamer2/plugins/.gitignore deleted file mode 100644 index 6cecb663c..000000000 --- a/linphone/mediastreamer2/plugins/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -Makefile -Makefile.in -plugins.mk diff --git a/linphone/mediastreamer2/plugins/msilbc/AUTHORS b/linphone/mediastreamer2/plugins/msilbc/AUTHORS deleted file mode 100644 index e69de29bb..000000000 diff --git a/linphone/mediastreamer2/plugins/msilbc/COPYING b/linphone/mediastreamer2/plugins/msilbc/COPYING deleted file mode 100644 index 623b6258a..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE 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. - - 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 -convey 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision 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, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This 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 Library General -Public License instead of this License. diff --git a/linphone/mediastreamer2/plugins/msilbc/ChangeLog b/linphone/mediastreamer2/plugins/msilbc/ChangeLog deleted file mode 100644 index e69de29bb..000000000 diff --git a/linphone/mediastreamer2/plugins/msilbc/INSTALL b/linphone/mediastreamer2/plugins/msilbc/INSTALL deleted file mode 100644 index 23e5f25d0..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/INSTALL +++ /dev/null @@ -1,236 +0,0 @@ -Installation Instructions -************************* - -Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005 Free -Software Foundation, Inc. - -This file is free documentation; the Free Software Foundation gives -unlimited permission to copy, distribute and modify it. - -Basic Installation -================== - -These are generic installation instructions. - - 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 only 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. If you're - using `csh' on an old version of System V, you might need to type - `sh ./configure' instead to prevent `csh' from trying to execute - `configure' itself. - - Running `configure' takes awhile. 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. - -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=c89 CFLAGS=-O2 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 must use a version of `make' that -supports the `VPATH' variable, such as 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 `..'. - - If you have to use a `make' that does not support the `VPATH' -variable, you have 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. - -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. - -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). Here is a another example: - - /bin/bash ./configure CONFIG_SHELL=/bin/bash - -Here the `CONFIG_SHELL=/bin/bash' operand causes subsequent -configuration-related scripts to be executed by `/bin/bash'. - -`configure' Invocation -====================== - -`configure' recognizes the following options to control how it operates. - -`--help' -`-h' - Print a summary of the options to `configure', and exit. - -`--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. - -`configure' also accepts some other, not widely useful, options. Run -`configure --help' for more details. - diff --git a/linphone/mediastreamer2/plugins/msilbc/Makefile.am b/linphone/mediastreamer2/plugins/msilbc/Makefile.am deleted file mode 100644 index 34b360d4c..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/Makefile.am +++ /dev/null @@ -1,11 +0,0 @@ -EXTRA_DIST=ilbc-rfc3951.tar.gz - -plugindir=$(PACKAGE_PLUGINS_DIR) - -plugin_LTLIBRARIES=libmsilbc.la - -libmsilbc_la_SOURCES=ilbc.c - -libmsilbc_la_LIBADD=$(ILBC_LIBS) - -AM_CFLAGS=$(ILBC_CFLAGS) \ No newline at end of file diff --git a/linphone/mediastreamer2/plugins/msilbc/NEWS b/linphone/mediastreamer2/plugins/msilbc/NEWS deleted file mode 100644 index e69de29bb..000000000 diff --git a/linphone/mediastreamer2/plugins/msilbc/README b/linphone/mediastreamer2/plugins/msilbc/README deleted file mode 100644 index e18f0b05a..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/README +++ /dev/null @@ -1,13 +0,0 @@ - - -* compile and install the ilbc source: - tar -xvzf ilbc-rfc3951.tar.gz - cd ilbc-rfc2951 - ./configure --prefix=/usr && make - make install (as root) - cd .. - -* compile and install the plugin: - ./configure --prefix= - make - make install diff --git a/linphone/mediastreamer2/plugins/msilbc/configure.ac b/linphone/mediastreamer2/plugins/msilbc/configure.ac deleted file mode 100644 index d8418f211..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/configure.ac +++ /dev/null @@ -1,152 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. -AC_INIT([msilbc],[2.0.0]) - -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=yes]], -[wall_werror=$enableval], -[wall_werror=yes] -) - - -AC_ARG_ENABLE(debug, - [ --enable-debug=[yes/no] enables the display of traces showing the execution of the library. [default=yes]], - [case "${enableval}" in - yes) debug_enabled=yes;; - no) debug_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-debug");; - esac], - [debug_enabled=no] ) - - -dnl Checks for programs. -AC_PROG_CC -AC_PROG_LIBTOOL -AC_ENABLE_SHARED(yes) -AC_ENABLE_STATIC(no) - -if test "$GCC" != "yes" ; then - case $host_os in - *hpux*) - dnl we are probably using HPUX cc compiler, so add a +O2 to CFLAGS - CFLAGS="$CFLAGS +O2 -g " - ;; - esac -else - CFLAGS="$CFLAGS -Wall" -fi - - - -if test $debug_enabled = "yes"; then - CFLAGS="$CFLAGS -DDEBUG" -fi - -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 - -PKG_CHECK_MODULES(MEDIASTREAMER, mediastreamer >= 2.0.0) - -AC_ARG_WITH( ilbc, - [ --with-ilbc Sets the installation prefix of ilbc codec, [default=/usr] ], - [ ilbcdir=${withval}],[ ilbcdir=/usr ]) - -if test "$ilbcdir" != "/usr" ; then - ILBC_CFLAGS="$ilbcdir/include" - ILBC_LIBS="$ilbcdir/lib" -fi -ILBC_LIBS="$ILBC_LIBS -lilbc" - -AC_SUBST(ILBC_CFLAGS) -AC_SUBST(ILBC_LIBS) - -CFLAGS="$CFLAGS \$(MEDIASTREAMER_CFLAGS) " -LIBS="$LIBS \$(MEDIASTREAMER_LIBS) " -LDFLAGS="$LDFLAGS -rdynamic " - -dnl define path of plugins: -PACKAGE_PLUGINS_DIR=`eval echo $prefix/lib/mediastreamer/plugins` -AC_DEFINE_UNQUOTED(PACKAGE_PLUGINS_DIR, "$PACKAGE_PLUGINS_DIR" ,[path of plugins]) -AC_SUBST(PACKAGE_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 mediastreamer plugin." -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 -) diff --git a/linphone/mediastreamer2/plugins/msilbc/ilbc-rfc3951.tar.gz b/linphone/mediastreamer2/plugins/msilbc/ilbc-rfc3951.tar.gz deleted file mode 100644 index e5160f402..000000000 Binary files a/linphone/mediastreamer2/plugins/msilbc/ilbc-rfc3951.tar.gz and /dev/null differ diff --git a/linphone/mediastreamer2/plugins/msilbc/ilbc.c b/linphone/mediastreamer2/plugins/msilbc/ilbc.c deleted file mode 100644 index 9a6b43e38..000000000 --- a/linphone/mediastreamer2/plugins/msilbc/ilbc.c +++ /dev/null @@ -1,283 +0,0 @@ -/* - NO LICENSE -*/ -#include -#include - -#include "mediastreamer2/msfilter.h" - -typedef struct EncState{ - int nsamples; - int nbytes; - int ms_per_frame; - int ptime; - uint32_t ts; - MSBufferizer bufferizer; - iLBC_Enc_Inst_t ilbc_enc; -}EncState; - -static void enc_init(MSFilter *f){ - EncState *s=ms_new(EncState,1); - s->nsamples=BLOCKL_20MS; - s->nbytes=NO_OF_BYTES_20MS; - s->ms_per_frame=20; - s->ptime=0; - s->ts=0; - ms_bufferizer_init(&s->bufferizer); - f->data=s; -} - -static void enc_uninit(MSFilter *f){ - EncState *s=(EncState*)f->data; - ms_bufferizer_uninit(&s->bufferizer); - ms_free(f->data); -} - -static void enc_preprocess(MSFilter *f){ - EncState *s=(EncState*)f->data; - initEncode(&s->ilbc_enc,s->ms_per_frame); -} - -static int enc_add_fmtp(MSFilter *f, void *arg){ - char buf[64]; - const char *fmtp=(const char *)arg; - EncState *s=(EncState*)f->data; - - memset(buf, '\0', sizeof(buf)); - fmtp_get_value(fmtp, "mode", buf, sizeof(buf)); - if (buf[0]=='\0'){ - ms_warning("unsupported fmtp parameter (%s)!", fmtp); - } - else if (strstr(buf,"20")!=NULL){ - s->nsamples=BLOCKL_20MS; - s->nbytes=NO_OF_BYTES_20MS; - s->ms_per_frame=20; - }else if (strstr(buf,"30")!=NULL){ - s->nsamples=BLOCKL_30MS; - s->nbytes=NO_OF_BYTES_30MS; - s->ms_per_frame=30; - } - return 0; -} - -static int enc_add_attr(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - EncState *s=(EncState*)f->data; - if (strstr(fmtp,"ptime:20")!=NULL){ - s->ptime=20; - }else if (strstr(fmtp,"ptime:30")!=NULL){ - s->ptime=30; - }else if (strstr(fmtp,"ptime:40")!=NULL){ - s->ptime=40; - }else if (strstr(fmtp,"ptime:60")!=NULL){ - s->ptime=60; - }else if (strstr(fmtp,"ptime:80")!=NULL){ - s->ptime=80; - }else if (strstr(fmtp,"ptime:90")!=NULL){ - s->ptime=90; - }else if (strstr(fmtp,"ptime:100")!=NULL){ - s->ptime=100; - }else if (strstr(fmtp,"ptime:120")!=NULL){ - s->ptime=120; - }else if (strstr(fmtp,"ptime:140")!=NULL){ - s->ptime=140; - } - return 0; -} - -static void enc_process(MSFilter *f){ - EncState *s=(EncState*)f->data; - mblk_t *im,*om; - int size=s->nsamples*2; - int16_t samples[1610]; /* BLOCKL_MAX * 7 is the largest size for ptime == 140 */ - float samples2[BLOCKL_MAX]; - int i; - int frame_per_packet=1; - - if (s->ptime>=20 && s->ms_per_frame>0 && s->ptime%s->ms_per_frame==0) - { - frame_per_packet = s->ptime/s->ms_per_frame; - } - - if (frame_per_packet<=0) - frame_per_packet=1; - if (frame_per_packet>7) /* 7*20 == 140 ms max */ - frame_per_packet=7; - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - ms_bufferizer_put(&s->bufferizer,im); - } - while(ms_bufferizer_read(&s->bufferizer,(uint8_t*)samples,size*frame_per_packet)==(size*frame_per_packet)){ - int k; - om=allocb(s->nbytes*frame_per_packet,0); - for (k=0;knsamples;i++){ - samples2[i]=samples[i+(s->nsamples*k)]; - } - iLBC_encode((uint8_t*)om->b_wptr,samples2,&s->ilbc_enc); - om->b_wptr+=s->nbytes; - s->ts+=s->nsamples; - } - mblk_set_timestamp_info(om,s->ts-s->nsamples); - ms_queue_put(f->outputs[0],om); - } -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_ADD_FMTP, enc_add_fmtp }, - { MS_FILTER_ADD_ATTR, enc_add_attr}, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_ilbc_enc_desc={ - MS_FILTER_PLUGIN_ID, - "MSIlbcEnc", - "iLBC encoder", - MS_FILTER_ENCODER, - "iLBC", - 1, - 1, - enc_init, - enc_preprocess, - enc_process, - NULL, - enc_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_ilbc_enc_desc={ - .id=MS_FILTER_PLUGIN_ID, - .name="MSIlbcEnc", - .text="iLBC encoder", - .category=MS_FILTER_ENCODER, - .enc_fmt="iLBC", - .ninputs=1, - .noutputs=1, - .init=enc_init, - .preprocess=enc_preprocess, - .process=enc_process, - .uninit=enc_uninit, - .methods=enc_methods -}; - -#endif - -typedef struct DecState{ - int nsamples; - int nbytes; - int ms_per_frame; - iLBC_Dec_Inst_t ilbc_dec; -}DecState; - - -static void dec_init(MSFilter *f){ - DecState *s=ms_new(DecState,1); - s->nsamples=0; - s->nbytes=0; - s->ms_per_frame=0; - f->data=s; -} - -static void dec_uninit(MSFilter *f){ - ms_free(f->data); -} - -static void dec_process(MSFilter *f){ - DecState *s=(DecState*)f->data; - mblk_t *im,*om; - int nbytes; - float samples[BLOCKL_MAX]; - int i; - - while ((im=ms_queue_get(f->inputs[0]))!=NULL){ - nbytes=msgdsize(im); - if (nbytes<=0) - return; - if (nbytes%38!=0 && nbytes%50!=0) - return; - if (nbytes%38==0 && s->nbytes!=NO_OF_BYTES_20MS) - { - /* not yet configured, or misconfigured */ - s->ms_per_frame=20; - s->nbytes=NO_OF_BYTES_20MS; - s->nsamples=BLOCKL_20MS; - initDecode(&s->ilbc_dec,s->ms_per_frame,0); - } - else if (nbytes%50==0 && s->nbytes!=NO_OF_BYTES_30MS) - { - /* not yet configured, or misconfigured */ - s->ms_per_frame=30; - s->nbytes=NO_OF_BYTES_30MS; - s->nsamples=BLOCKL_30MS; - initDecode(&s->ilbc_dec,s->ms_per_frame,0); - } - if (s->nbytes>0 && nbytes>=s->nbytes){ - int frame_per_packet = nbytes/s->nbytes; - int k; - - for (k=0;knsamples*2,0); - iLBC_decode(samples,(uint8_t*)im->b_rptr+(k*s->nbytes),&s->ilbc_dec,1); - for (i=0;insamples;i++,om->b_wptr+=2){ - *((int16_t*)om->b_wptr)=samples[i]; - } - ms_queue_put(f->outputs[0],om); - } - }else{ - ms_warning("bad iLBC frame !"); - } - freemsg(im); - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_ilbc_dec_desc={ - MS_FILTER_PLUGIN_ID, - "MSIlbcDec", - "iLBC decoder", - MS_FILTER_DECODER, - "iLBC", - 1, - 1, - dec_init, - NULL, - dec_process, - NULL, - dec_uninit, - NULL -}; - -#else - -MSFilterDesc ms_ilbc_dec_desc={ - .id=MS_FILTER_PLUGIN_ID, - .name="MSIlbcDec", - .text="iLBC decoder", - .category=MS_FILTER_DECODER, - .enc_fmt="iLBC", - .ninputs=1, - .noutputs=1, - .init=dec_init, - .process=dec_process, - .uninit=dec_uninit -}; - -#endif - -#ifdef _MSC_VER -#define MS_PLUGIN_DECLARE(type) __declspec(dllexport) type -#else -#define MS_PLUGIN_DECLARE(type) type -#endif - -MS_PLUGIN_DECLARE(void) libmsilbc_init(){ - ms_filter_register(&ms_ilbc_enc_desc); - ms_filter_register(&ms_ilbc_dec_desc); -} diff --git a/linphone/mediastreamer2/plugins/msx264/AUTHORS b/linphone/mediastreamer2/plugins/msx264/AUTHORS deleted file mode 100644 index 16d2ea646..000000000 --- a/linphone/mediastreamer2/plugins/msx264/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Simon Morlat \ No newline at end of file diff --git a/linphone/mediastreamer2/plugins/msx264/COPYING b/linphone/mediastreamer2/plugins/msx264/COPYING deleted file mode 100644 index 623b6258a..000000000 --- a/linphone/mediastreamer2/plugins/msx264/COPYING +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE 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. - - 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 -convey 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision 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, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This 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 Library General -Public License instead of this License. diff --git a/linphone/mediastreamer2/plugins/msx264/ChangeLog b/linphone/mediastreamer2/plugins/msx264/ChangeLog deleted file mode 100644 index e69de29bb..000000000 diff --git a/linphone/mediastreamer2/plugins/msx264/INSTALL b/linphone/mediastreamer2/plugins/msx264/INSTALL deleted file mode 100644 index 2550dab75..000000000 --- a/linphone/mediastreamer2/plugins/msx264/INSTALL +++ /dev/null @@ -1,302 +0,0 @@ -Installation Instructions -************************* - -Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, -2006, 2007, 2008, 2009 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 -D_XOPEN_SOURCE=500" - -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" - - On Solaris, don't put `/usr/ucb' early in your `PATH'. This -directory contains several dysfunctional programs; working variants of -these programs are available in `/usr/bin'. So, if you need `/usr/ucb' -in your `PATH', put it _after_ `/usr/bin'. - - On Haiku, software installed for all users goes in `/boot/common', -not `/usr/local'. It is recommended to use the following options: - - ./configure --prefix=/boot/common - -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/linphone/mediastreamer2/plugins/msx264/Makefile.am b/linphone/mediastreamer2/plugins/msx264/Makefile.am deleted file mode 100644 index 3ec7f9edc..000000000 --- a/linphone/mediastreamer2/plugins/msx264/Makefile.am +++ /dev/null @@ -1,48 +0,0 @@ -EXTRA_DIST=autogen.sh - -SUBDIRS=src - - - -INSTALLDIR=$(shell cd $(top_builddir) && pwd)/$(PACKAGE)-install -INSTALLDIR_WITH_PREFIX=$(INSTALLDIR)/$(prefix) -ZIPFILE=$(shell cd $(top_builddir) && pwd)/$(PACKAGE)-win32-$(VERSION).zip -ZIP_EXCLUDED=include - -ISS_SCRIPT=msx264.iss -ISS_SCRIPT_PATH=$(shell cd $(top_srcdir) && pwd)/$(ISS_SCRIPT) -#path to Inno Setup 5 compiler -ISCC=/c/Program\ Files/Inno\ Setup\ 5/ISCC.exe -PACKAGE_WIN32_FILELIST=$(PACKAGE)-win32.filelist - -setup.exe: zip - cd $(INSTALLDIR_WITH_PREFIX) && \ - rm -f $(PACKAGE_WIN32_FILELIST) && \ - for file in `find` ; do \ - if ! test -d $$file ; then \ - echo "Source: $$file; Destdir: {app}\\`dirname $$file`; Flags: ignoreversion" \ - >> $(PACKAGE_WIN32_FILELIST) ;\ - fi \ - done - cp $(ISS_SCRIPT) $(INSTALLDIR_WITH_PREFIX)/. - cd $(INSTALLDIR_WITH_PREFIX) && \ - $(ISCC) $(ISS_SCRIPT) - mv $(INSTALLDIR_WITH_PREFIX)/Output/setup.exe $(PACKAGE)-$(VERSION)-setup.exe - rm -rf $(INSTALLDIR_WITH_PREFIX)/Output - rm -f $(INSTALLDIR_WITH_PREFIX)/$(PACKAGE_WIN32_FILELIST) - rm -f $(INSTALLDIR_WITH_PREFIX)/$(ISS_SCRIPT) - -zip: - rm -f $(ZIPFILE) - rm -rf $(INSTALLDIR) - mkdir -p $(INSTALLDIR) - make install DESTDIR=$(INSTALLDIR) - cp -f $(top_srcdir)/README $(INSTALLDIR_WITH_PREFIX)/. - cp -f $(top_srcdir)/COPYING $(INSTALLDIR_WITH_PREFIX)/. - cd $(INSTALLDIR)/$(prefix) && rm -rf $(ZIP_EXCLUDED) && \ - zip -r $(ZIPFILE) * - -clean-local: - -rm -rf $(PACKAGE)-install - -rm -f $(PACKAGE)-win32-$(VERSION).zip - diff --git a/linphone/mediastreamer2/plugins/msx264/NEWS b/linphone/mediastreamer2/plugins/msx264/NEWS deleted file mode 100644 index a354cdff8..000000000 --- a/linphone/mediastreamer2/plugins/msx264/NEWS +++ /dev/null @@ -1,8 +0,0 @@ -Wednesday December 2, 2009: msx264-1.3.0 - - use new official x264 support of multislicing (forked version no more required) - -Friday July 4, 2009 : msx264-1.2.0 - - modified to compile against new multisliced version of x264 to allow packetization-mode=0 - -Wednesday August 20, 2008: msx264-1.1.0 - - compiled together with x264-snapshot-20080421-2245+multislicing-patch.tar.gz, allows packetization-mode=0 diff --git a/linphone/mediastreamer2/plugins/msx264/README b/linphone/mediastreamer2/plugins/msx264/README deleted file mode 100644 index 291cab2cb..000000000 --- a/linphone/mediastreamer2/plugins/msx264/README +++ /dev/null @@ -1,18 +0,0 @@ -msx264 - a GPL plugin to bring video H264 encoding/decoding capabilities to mediastreamer2 applications. -It is based on ffmpeg for decoding and x264 for encoding. - -It works with x264 version later to september 2009. -So: - -* compile msx264 with ./configure && make && make install - - -A bit of history -**************** - -The multislicing feature of x264 is something that has been contributed several time, but never merged (why ?). -The linphone.org version of x264 was inspired by a patch submitted on x264-devel mailing list: -http://mailman.videolan.org/pipermail/x264-devel/2008-April/004427.html -http://download.savannah.gnu.org/releases/linphone/plugins/sources/x264-snapshot-20090704-linphone-org.tar.gz -This version is no more required since in august 2009, x264 team introduces new parameters -controlling slicing. diff --git a/linphone/mediastreamer2/plugins/msx264/autogen.sh b/linphone/mediastreamer2/plugins/msx264/autogen.sh deleted file mode 100755 index 829a5a0b7..000000000 --- a/linphone/mediastreamer2/plugins/msx264/autogen.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -AM_VERSION=1.10 -if ! type aclocal-$AM_VERSION 1>/dev/null 2>&1; then - ACLOCAL=aclocal - AUTOMAKE=automake -else - ACLOCAL=aclocal-${AM_VERSION} - AUTOMAKE=automake-${AM_VERSION} -fi - -echo "Generating build scripts in this mediastreamer plugin" -set -x -libtoolize --copy --force -$ACLOCAL -$AUTOMAKE --force-missing --add-missing --copy -autoconf - - diff --git a/linphone/mediastreamer2/plugins/msx264/configure.ac b/linphone/mediastreamer2/plugins/msx264/configure.ac deleted file mode 100644 index 191383a13..000000000 --- a/linphone/mediastreamer2/plugins/msx264/configure.ac +++ /dev/null @@ -1,159 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. -AC_INIT([msx264],[1.3.0]) - -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=yes]], -[wall_werror=$enableval], -[wall_werror=yes] -) - - -dnl Checks for programs. -AC_PROG_CC - -AC_LIBTOOL_WIN32_DLL -AC_DISABLE_STATIC -AC_PROG_LIBTOOL - - -case $target_os in - *mingw*) - mingw_found=yes - ;; -esac - -AM_CONDITIONAL(BUILD_WIN32, test x$mingw_found = xyes) - -AC_CONFIG_COMMANDS([libtool-hacking],[ -if test "$mingw_found" = "yes" ; then - AC_MSG_NOTICE([Hacking libtool to work with mingw...]) - sed -e 's/\*\" \$a_deplib \"\*/\*/' < ./libtool > libtool.tmp - cp -f ./libtool.tmp ./libtool - rm -f ./libtool.tmp -fi -],[mingw_found=$mingw_found]) - - -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 - -PKG_CHECK_MODULES(MEDIASTREAMER, mediastreamer >= 2.1.0) - -PKG_CHECK_MODULES(X264, x264 >= 0.67.0) - - -dnl test for ffmpeg presence -PKG_CHECK_MODULES(LIBAVCODEC, [libavcodec >= 50.0.0 ],ffmpeg_found=yes , ffmpeg_found=no) -dnl workaround for debian... -PKG_CHECK_MODULES(LIBAVCODEC, [libavcodec >= 0d.50.0.0 ], ffmpeg_found=yes, ffmpeg_found=no) -if test x$ffmpeg_found = xno ; then - AC_MSG_ERROR([Could not find ffmpeg headers and library. This is mandatory for video support]) -fi - -PKG_CHECK_MODULES(LIBSWSCALE, [libswscale >= 0.7.0]) - - -dnl check for new/old ffmpeg header file layout -CPPFLAGS_save=$CPPFLAGS -CPPFLAGS=$LIBAVCODEC_CFLAGS -AC_CHECK_HEADERS(libavcodec/avcodec.h) -CPPFLAGS=$CPPFLAGS_save - -if test "$hacked_x264" = "yes" ; then - AC_MSG_NOTICE([Trying to compile with multislicing patched version of X264]) - CFLAGS="$CFLAGS -DHACKED_X264" -fi - -LDFLAGS="$LDFLAGS -rdynamic " - -dnl define path of plugins: -PACKAGE_PLUGINS_DIR="\$(libdir)/mediastreamer/plugins" -AC_SUBST(PACKAGE_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 H264 codec mediastreamer plugin" -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 -src/Makefile -msx264.iss -) diff --git a/linphone/mediastreamer2/plugins/msx264/msx264.iss.in b/linphone/mediastreamer2/plugins/msx264/msx264.iss.in deleted file mode 100644 index 94f282b8e..000000000 --- a/linphone/mediastreamer2/plugins/msx264/msx264.iss.in +++ /dev/null @@ -1,34 +0,0 @@ -; Script generated by the Inno Setup Script Wizard. -; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! - -[Setup] -AppName=msx264 -AppVerName=msx264 version @VERSION@ , an H.264 plugin for linphone. -AppPublisher=linphone.org -AppPublisherURL=http://www.linphone.org -AppSupportURL=http://www.linphone.org -AppUpdatesURL=http://www.linphone.org -DefaultDirName={pf}\Linphone -DefaultGroupName=Linphone -LicenseFile=COPYING -InfoBeforeFile=README -OutputBaseFilename=setup -Compression=lzma -SolidCompression=yes - -[Languages] -Name: "english"; MessagesFile: "compiler:Default.isl" - -[Tasks] -;Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked - -[Files] -#include "msx264-win32.filelist" - -[Icons] -;Name: "{group}\Linphone"; Filename: "{app}\linphone-wx.exe" ; WorkingDir: "{app}" -;Name: "{userdesktop}\Linphone"; Filename: "{app}\linphone-wx.exe"; WorkingDir: "{app}" ; Tasks: desktopicon - -[Run] -;Filename: "{app}\linphone-wx.exe"; Description: "{cm:LaunchProgram,Linphone}"; WorkingDir: "{app}" ; Flags: nowait postinstall skipifsilent - diff --git a/linphone/mediastreamer2/plugins/msx264/src/Makefile.am b/linphone/mediastreamer2/plugins/msx264/src/Makefile.am deleted file mode 100644 index c4c423605..000000000 --- a/linphone/mediastreamer2/plugins/msx264/src/Makefile.am +++ /dev/null @@ -1,27 +0,0 @@ -pluginsdir=$(PACKAGE_PLUGINS_DIR) - -plugins_LTLIBRARIES=libmsx264.la - -libmsx264_la_SOURCES=msx264.c - -libmsx264_la_LIBADD=\ - $(LIBAVCODEC_LIBS) \ - $(LIBSWSCALE_LIBS) \ - $(MEDIASTREAMER_LIBS) \ - $(X264_LIBS) - -libmsx264_la_LDFLAGS=-no-undefined - -AM_CFLAGS= $(LIBAVCODEC_CFLAGS) \ - $(LIBSWSCALE_CFLAGS) \ - $(MEDIASTREAMER_CFLAGS)\ - $(X264_CFLAGS) - -if BUILD_WIN32 -#hack for mingw to force plugins dll to be where we want them to be. -install-data-hook: - mv $(DESTDIR)$(pluginsdir)/../bin/*.dll \ - $(DESTDIR)$(pluginsdir)/. - rm -f $(DESTDIR)$(pluginsdir)/*.la - rm -f $(DESTDIR)$(pluginsdir)/*.dll.a -endif diff --git a/linphone/mediastreamer2/plugins/msx264/src/msx264.c b/linphone/mediastreamer2/plugins/msx264/src/msx264.c deleted file mode 100644 index 3ad35f217..000000000 --- a/linphone/mediastreamer2/plugins/msx264/src/msx264.c +++ /dev/null @@ -1,563 +0,0 @@ -/* -mediastreamer2 x264 plugin -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/rfc3984.h" - -#include "ortp/b64.h" - -#include - -#ifdef HAVE_LIBAVCODEC_AVCODEC_H -#include -#include -#else -#include -#include -#endif - -#define REMOVE_PREVENTING_BYTES 1 - -typedef struct _EncData{ - x264_t *enc; - MSVideoSize vsize; - int bitrate; - float fps; - int mode; - uint64_t framenum; - Rfc3984Context packer; - int keyframe_int; - bool_t generate_keyframe; -}EncData; - - -static void enc_init(MSFilter *f){ - EncData *d=ms_new(EncData,1); - d->enc=NULL; - d->bitrate=384000; - d->vsize=MS_VIDEO_SIZE_CIF; - d->fps=30; - d->keyframe_int=10; /*10 seconds */ - d->mode=0; - d->framenum=0; - d->generate_keyframe=FALSE; - f->data=d; -} - -static void enc_uninit(MSFilter *f){ - EncData *d=(EncData*)f->data; - ms_free(d); -} - -static void enc_preprocess(MSFilter *f){ - EncData *d=(EncData*)f->data; - x264_param_t params; - - rfc3984_init(&d->packer); - rfc3984_set_mode(&d->packer,d->mode); - rfc3984_enable_stap_a(&d->packer,FALSE); - - x264_param_default(¶ms); - params.i_threads=1; - params.i_sync_lookahead=0; - params.i_width=d->vsize.width; - params.i_height=d->vsize.height; - params.i_fps_num=(int)d->fps; - params.i_fps_den=1; - params.i_slice_max_size=ms_get_payload_max_size()-100; /*-100 security margin*/ - /*params.i_level_idc=30;*/ - - params.rc.i_rc_method = X264_RC_ABR; - params.rc.i_bitrate=(int)( ( ((float)d->bitrate)*0.8)/1000.0); - params.rc.f_rate_tolerance=0.1; - params.rc.i_vbv_max_bitrate=(int) (((float)d->bitrate)*0.9/1000.0); - params.rc.i_vbv_buffer_size=params.rc.i_vbv_max_bitrate; - params.rc.f_vbv_buffer_init=0.5; - params.rc.i_lookahead=0; - /*enable this by config ?*/ - /* - params.i_keyint_max = (int)d->fps*d->keyframe_int; - params.i_keyint_min = (int)d->fps; - */ - params.b_repeat_headers=1; - params.b_cabac=0;//disable cabac to be baseline - params.i_bframe=0;/*no B frames*/ - d->enc=x264_encoder_open(¶ms); - if (d->enc==NULL) ms_error("Fail to create x264 encoder."); - d->framenum=0; -} - -static void x264_nals_to_msgb(x264_nal_t *xnals, int num_nals, MSQueue * nalus){ - int i; - mblk_t *m; - /*int bytes;*/ - for (i=0;ib_wptr,xnals[i].p_payload+4,xnals[i].i_payload-4); - m->b_wptr+=xnals[i].i_payload-4; - if (xnals[i].i_type==7) { - ms_message("A SPS is being sent."); - }else if (xnals[i].i_type==8) { - ms_message("A PPS is being sent."); - } - ms_queue_put(nalus,m); - } -} - -static void enc_process(MSFilter *f){ - EncData *d=(EncData*)f->data; - uint32_t ts=f->ticker->time*90LL; - mblk_t *im; - MSPicture pic; - MSQueue nalus; - ms_queue_init(&nalus); - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - if (yuv_buf_init_from_mblk(&pic,im)==0){ - x264_picture_t xpic; - x264_picture_t oxpic; - x264_nal_t *xnals=NULL; - int num_nals=0; - - /*send I frame 2 seconds and 4 seconds after the beginning */ - if (d->framenum==(int)d->fps*2 || d->framenum==(int)d->fps*4) - d->generate_keyframe=TRUE; - - if (d->generate_keyframe){ - xpic.i_type=X264_TYPE_IDR; - d->generate_keyframe=FALSE; - }else xpic.i_type=X264_TYPE_AUTO; - xpic.i_qpplus1=0; - xpic.i_pts=d->framenum; - xpic.param=NULL; - xpic.img.i_csp=X264_CSP_I420; - xpic.img.i_plane=3; - xpic.img.i_stride[0]=pic.strides[0]; - xpic.img.i_stride[1]=pic.strides[1]; - xpic.img.i_stride[2]=pic.strides[2]; - xpic.img.i_stride[3]=0; - xpic.img.plane[0]=pic.planes[0]; - xpic.img.plane[1]=pic.planes[1]; - xpic.img.plane[2]=pic.planes[2]; - xpic.img.plane[3]=0; - if (x264_encoder_encode(d->enc,&xnals,&num_nals,&xpic,&oxpic)>=0){ - x264_nals_to_msgb(xnals,num_nals,&nalus); - rfc3984_pack(&d->packer,&nalus,f->outputs[0],ts); - d->framenum++; - }else{ - ms_error("x264_encoder_encode() error."); - } - } - freemsg(im); - } -} - -static void enc_postprocess(MSFilter *f){ - EncData *d=(EncData*)f->data; - rfc3984_uninit(&d->packer); - if (d->enc!=NULL){ - x264_encoder_close(d->enc); - d->enc=NULL; - } -} - -static int enc_set_br(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - d->bitrate=*(int*)arg; - - if (d->bitrate>=1024000){ - d->vsize=MS_VIDEO_SIZE_VGA; - d->fps=25; - }else if (d->bitrate>=512000){ - d->vsize=MS_VIDEO_SIZE_VGA; - d->fps=15; - }else if (d->bitrate>=384000){ - d->vsize=MS_VIDEO_SIZE_CIF; - d->fps=30; - }else if (d->bitrate>=256000){ - d->vsize=MS_VIDEO_SIZE_CIF; - d->fps=15; - }else if (d->bitrate>=128000){ - d->vsize=MS_VIDEO_SIZE_CIF; - d->fps=15; - }else if (d->bitrate>=64000){ - d->vsize=MS_VIDEO_SIZE_CIF; - d->fps=10; - }else if (d->bitrate>=32000){ - d->vsize=MS_VIDEO_SIZE_QCIF; - d->fps=10; - }else{ - d->vsize=MS_VIDEO_SIZE_QCIF; - d->fps=5; - } - ms_message("bitrate set to %i",d->bitrate); - return 0; -} - -static int enc_set_fps(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - d->fps=*(float*)arg; - return 0; -} - -static int enc_get_fps(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - *(float*)arg=d->fps; - return 0; -} - -static int enc_get_vsize(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - *(MSVideoSize*)arg=d->vsize; - return 0; -} - -static int enc_set_vsize(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - d->vsize=*(MSVideoSize*)arg; - return 0; -} - -static int enc_add_fmtp(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - const char *fmtp=(const char *)arg; - char value[12]; - if (fmtp_get_value(fmtp,"packetization-mode",value,sizeof(value))){ - d->mode=atoi(value); - ms_message("packetization-mode set to %i",d->mode); - } - return 0; -} - -static int enc_req_vfu(MSFilter *f, void *arg){ - EncData *d=(EncData*)f->data; - d->generate_keyframe=TRUE; - return 0; -} - - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_SET_FPS , enc_set_fps }, - { MS_FILTER_SET_BITRATE , enc_set_br }, - { MS_FILTER_GET_FPS , enc_get_fps }, - { MS_FILTER_GET_VIDEO_SIZE, enc_get_vsize }, - { MS_FILTER_SET_VIDEO_SIZE, enc_set_vsize }, - { MS_FILTER_ADD_FMTP , enc_add_fmtp }, - { MS_FILTER_REQ_VFU , enc_req_vfu }, - { 0 , NULL } -}; - -static MSFilterDesc x264_enc_desc={ - .id=MS_FILTER_PLUGIN_ID, - .name="MSX264Enc", - .text="A H264 encoder based on x264 project (with multislicing enabled)", - .category=MS_FILTER_ENCODER, - .enc_fmt="H264", - .ninputs=1, - .noutputs=1, - .init=enc_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=enc_methods -}; - -typedef struct _DecData{ - mblk_t *yuv_msg; - mblk_t *sps,*pps; - Rfc3984Context unpacker; - MSPicture outbuf; - struct SwsContext *sws_ctx; - AVCodecContext av_context; - unsigned int packet_num; - uint8_t *bitstream; - int bitstream_size; -}DecData; - -static void ffmpeg_init(){ - static bool_t done=FALSE; - if (!done){ - avcodec_init(); - avcodec_register_all(); - done=TRUE; - } -} - -static void dec_open(DecData *d){ - AVCodec *codec; - int error; - codec=avcodec_find_decoder(CODEC_ID_H264); - if (codec==NULL) ms_fatal("Could not find H264 decoder in ffmpeg."); - avcodec_get_context_defaults(&d->av_context); - error=avcodec_open(&d->av_context,codec); - if (error!=0){ - ms_fatal("avcodec_open() failed."); - } -} - -static void dec_init(MSFilter *f){ - DecData *d=(DecData*)ms_new(DecData,1); - ffmpeg_init(); - d->yuv_msg=NULL; - d->sps=NULL; - d->pps=NULL; - d->sws_ctx=NULL; - rfc3984_init(&d->unpacker); - d->packet_num=0; - dec_open(d); - d->outbuf.w=0; - d->outbuf.h=0; - d->bitstream_size=65536; - d->bitstream=ms_malloc0(d->bitstream_size); - f->data=d; -} - -static void dec_reinit(DecData *d){ - avcodec_close(&d->av_context); - dec_open(d); -} - -static void dec_uninit(MSFilter *f){ - DecData *d=(DecData*)f->data; - rfc3984_uninit(&d->unpacker); - avcodec_close(&d->av_context); - if (d->yuv_msg) freemsg(d->yuv_msg); - if (d->sps) freemsg(d->sps); - if (d->pps) freemsg(d->pps); - ms_free(d->bitstream); - ms_free(d); -} - -static mblk_t *get_as_yuvmsg(MSFilter *f, DecData *s, AVFrame *orig){ - AVCodecContext *ctx=&s->av_context; - - if (s->outbuf.w!=ctx->width || s->outbuf.h!=ctx->height){ - if (s->sws_ctx!=NULL){ - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - freemsg(s->yuv_msg); - s->yuv_msg=NULL; - } - ms_message("Getting yuv picture of %ix%i",ctx->width,ctx->height); - s->yuv_msg=yuv_buf_alloc(&s->outbuf,ctx->width,ctx->height); - s->outbuf.w=ctx->width; - s->outbuf.h=ctx->height; - s->sws_ctx=sws_getContext(ctx->width,ctx->height,ctx->pix_fmt, - ctx->width,ctx->height,PIX_FMT_YUV420P,SWS_FAST_BILINEAR, - NULL, NULL, NULL); - } - if (sws_scale(s->sws_ctx,orig->data,orig->linesize, 0, - ctx->height, s->outbuf.planes, s->outbuf.strides)<0){ - ms_error("%s: error in sws_scale().",f->desc->name); - } - return dupmsg(s->yuv_msg); -} - -static void update_sps(DecData *d, mblk_t *sps){ - if (d->sps) - freemsg(d->sps); - d->sps=dupb(sps); -} - -static void update_pps(DecData *d, mblk_t *pps){ - if (d->pps) - freemsg(d->pps); - if (pps) d->pps=dupb(pps); - else d->pps=NULL; -} - -static bool_t check_sps_pps_change(DecData *d, mblk_t *sps, mblk_t *pps){ - bool_t ret1=FALSE,ret2=FALSE; - if (d->sps){ - if (sps){ - ret1=(msgdsize(sps)!=msgdsize(d->sps)) || (memcmp(d->sps->b_rptr,sps->b_rptr,msgdsize(sps))!=0); - if (ret1) { - update_sps(d,sps); - ms_message("SPS changed !"); - update_pps(d,NULL); - } - } - }else if (sps) { - ms_message("Receiving first SPS"); - update_sps(d,sps); - } - if (d->pps){ - if (pps){ - ret2=(msgdsize(pps)!=msgdsize(d->pps)) || (memcmp(d->pps->b_rptr,pps->b_rptr,msgdsize(pps))!=0); - if (ret2) { - update_sps(d,pps); - ms_message("PPS changed ! %i,%i",msgdsize(pps),msgdsize(d->pps)); - } - } - }else if (pps) { - ms_message("Receiving first PPS"); - update_pps(d,pps); - } - return ret1 || ret2; -} - -static void enlarge_bitstream(DecData *d, int new_size){ - d->bitstream_size=new_size; - d->bitstream=ms_realloc(d->bitstream,d->bitstream_size); -} - -static int nalusToFrame(DecData *d, MSQueue *naluq, bool_t *new_sps_pps){ - mblk_t *im; - uint8_t *dst=d->bitstream,*src,*end; - int nal_len; - bool_t start_picture=TRUE; - uint8_t nalu_type; - *new_sps_pps=FALSE; - end=d->bitstream+d->bitstream_size; - while((im=ms_queue_get(naluq))!=NULL){ - src=im->b_rptr; - nal_len=im->b_wptr-src; - if (dst+nal_len+100>end){ - int pos=dst-d->bitstream; - enlarge_bitstream(d, d->bitstream_size+nal_len+100); - dst=d->bitstream+pos; - end=d->bitstream+d->bitstream_size; - } - nalu_type=(*src) & ((1<<5)-1); - if (nalu_type==7) - *new_sps_pps=check_sps_pps_change(d,im,NULL) || *new_sps_pps; - if (nalu_type==8) - *new_sps_pps=check_sps_pps_change(d,NULL,im) || *new_sps_pps; - if (start_picture || nalu_type==7/*SPS*/ || nalu_type==8/*PPS*/ ){ - *dst++=0; - start_picture=FALSE; - } - /*prepend nal marker*/ - *dst++=0; - *dst++=0; - *dst++=1; - *dst++=*src++; - while(src<(im->b_wptr-3)){ - if (src[0]==0 && src[1]==0 && src[2]<3){ - *dst++=0; - *dst++=0; - *dst++=3; - src+=2; - } - *dst++=*src++; - } - *dst++=*src++; - *dst++=*src++; - *dst++=*src++; - freemsg(im); - } - return dst-d->bitstream; -} - -static void dec_process(MSFilter *f){ - DecData *d=(DecData*)f->data; - mblk_t *im; - MSQueue nalus; - AVFrame orig; - ms_queue_init(&nalus); - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - /*push the sps/pps given in sprop-parameter-sets if any*/ - if (d->packet_num==0 && d->sps && d->pps){ - mblk_set_timestamp_info(d->sps,mblk_get_timestamp_info(im)); - mblk_set_timestamp_info(d->pps,mblk_get_timestamp_info(im)); - rfc3984_unpack(&d->unpacker,d->sps,&nalus); - rfc3984_unpack(&d->unpacker,d->pps,&nalus); - d->sps=NULL; - d->pps=NULL; - } - rfc3984_unpack(&d->unpacker,im,&nalus); - if (!ms_queue_empty(&nalus)){ - int size; - uint8_t *p,*end; - bool_t need_reinit=FALSE; - - size=nalusToFrame(d,&nalus,&need_reinit); - if (need_reinit) - dec_reinit(d); - p=d->bitstream; - end=d->bitstream+size; - while (end-p>0) { - int len; - int got_picture=0; - AVPacket pkt; - avcodec_get_frame_defaults(&orig); - av_init_packet(&pkt); - pkt.data = p; - pkt.size = end-p; - len=avcodec_decode_video2(&d->av_context,&orig,&got_picture,&pkt); - if (len<=0) { - ms_warning("ms_AVdecoder_process: error %i.",len); - break; - } - if (got_picture) { - ms_queue_put(f->outputs[0],get_as_yuvmsg(f,d,&orig)); - } - p+=len; - } - } - d->packet_num++; - } -} - -static int dec_add_fmtp(MSFilter *f, void *arg){ - DecData *d=(DecData*)f->data; - const char *fmtp=(const char *)arg; - char value[256]; - if (fmtp_get_value(fmtp,"sprop-parameter-sets",value,sizeof(value))){ - char * b64_sps=value; - char * b64_pps=strchr(value,','); - if (b64_pps){ - *b64_pps='\0'; - ++b64_pps; - ms_message("Got sprop-parameter-sets : sps=%s , pps=%s",b64_sps,b64_pps); - d->sps=allocb(sizeof(value),0); - d->sps->b_wptr+=b64_decode(b64_sps,strlen(b64_sps),d->sps->b_wptr,sizeof(value)); - d->pps=allocb(sizeof(value),0); - d->pps->b_wptr+=b64_decode(b64_pps,strlen(b64_pps),d->pps->b_wptr,sizeof(value)); - } - } - return 0; -} - -static MSFilterMethod h264_dec_methods[]={ - { MS_FILTER_ADD_FMTP , dec_add_fmtp }, - { 0 , NULL } -}; - -static MSFilterDesc h264_dec_desc={ - .id=MS_FILTER_PLUGIN_ID, - .name="MSH264Dec", - .text="A H264 decoder based on ffmpeg project.", - .category=MS_FILTER_DECODER, - .enc_fmt="H264", - .ninputs=1, - .noutputs=1, - .init=dec_init, - .process=dec_process, - .uninit=dec_uninit, - .methods=h264_dec_methods -}; - -void libmsx264_init(void){ - ms_filter_register(&x264_enc_desc); - ms_filter_register(&h264_dec_desc); -} diff --git a/linphone/mediastreamer2/src/.gitignore b/linphone/mediastreamer2/src/.gitignore deleted file mode 100644 index 9c4a34a80..000000000 --- a/linphone/mediastreamer2/src/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -Makefile.in -Makefile -.libs -.deps -*.la -*.lo -alldescs.h -filterdescs.txt diff --git a/linphone/mediastreamer2/src/Makefile.am b/linphone/mediastreamer2/src/Makefile.am deleted file mode 100644 index d5bf394ac..000000000 --- a/linphone/mediastreamer2/src/Makefile.am +++ /dev/null @@ -1,188 +0,0 @@ - -EXTRA_DIST= winsnd2.c winsnd.c winvideo.c \ - winvideods.c wincevideods.c dxfilter.h dxfilter.cpp \ - msfileplayer_win.c msfilerec_win.c winsndds.cpp nowebcamCIF.jpg winsnd3.c vfw-missing.h \ - winvideo2.c - -BUILT_SOURCES=alldescs.h - -CLEANFILES=alldescs.h filterdescs.txt - -INCLUDES=-I$(top_srcdir)/include/ - -lib_LTLIBRARIES=libmediastreamer.la - -libmediastreamer_la_SOURCES= mscommon.c \ - msfilter.c \ - msqueue.c \ - msticker.c \ - alaw.c \ - ulaw.c \ - mssndcard.c \ - msrtp.c \ - dtmfgen.c \ - ice.c \ - tee.c \ - msconf.c \ - msjoin.c \ - g711common.h \ - msvolume.c \ - mswebcam.c \ - mtu.c \ - void.c \ - dsptools.c \ - kiss_fft.c \ - _kiss_fft_guts.h \ - kiss_fft.h \ - kiss_fftr.c \ - kiss_fftr.h \ - equalizer.c - -#dummy c++ file to force libtool to use c++ linking (because of msdscap-mingw.cc) -nodist_EXTRA_libmediastreamer_la_SOURCES = dummy.cxx - -libmediastreamer_la_SOURCES+=audiostream.c - - -if BUILD_SPEEX -libmediastreamer_la_SOURCES+=msspeex.c speexec.c -endif - -if BUILD_GSM -libmediastreamer_la_SOURCES+=gsm.c -endif - -if BUILD_WIN32 -libmediastreamer_la_SOURCES+= winsnd3.c \ - msfileplayer_win.c msfilerec_win.c -else -libmediastreamer_la_SOURCES+= msfileplayer.c \ - msfilerec.c -endif - -if BUILD_RESAMPLE -libmediastreamer_la_SOURCES+=msresample.c -endif - -if BUILD_ALSA -libmediastreamer_la_SOURCES+=alsa.c -endif - -if BUILD_OSS -libmediastreamer_la_SOURCES+=oss.c -endif - -if BUILD_ARTS -libmediastreamer_la_SOURCES+=arts.c -endif - -if BUILD_PORTAUDIO -libmediastreamer_la_SOURCES+=pasnd.c -endif - -if BUILD_MACSND -libmediastreamer_la_SOURCES+=macsnd.c -endif - -if BUILD_MACAQSND -libmediastreamer_la_SOURCES+=aqsnd.c -endif - - -if BUILD_VIDEO - -if BUILD_MACOSX -libmediastreamer_la_SOURCES+=msv4m.m -endif - -if BUILD_V4L -libmediastreamer_la_SOURCES+=msv4l.c msv4l2.c -endif - -if BUILD_WIN32 -libmediastreamer_la_SOURCES+=msdscap-mingw.cc -endif - -if BUILD_THEORA -libmediastreamer_la_SOURCES+=theora.c -endif - - -libmediastreamer_la_SOURCES+= videoenc.c \ - videodec.c \ - pixconv.c \ - sizeconv.c \ - rfc2429.h \ - nowebcam.c nowebcam.h \ - videoout.c \ - msvideo.c \ - rfc3984.c \ - mire.c \ - swscale.h ffmpeg-priv.h - -libmediastreamer_la_SOURCES+=videostream.c - -endif - - - - -alldescs.h: Makefile.am $(libmediastreamer_la_SOURCES) - builddir=`pwd` && cd $(srcdir) && \ - awk 'BEGIN { FS="[()]" ; }; /^\t*MS_FILTER_DESC_EXPORT/{ printf("%s\n", $$2) } ' > $$builddir/filterdescs.txt $(libmediastreamer_la_SOURCES) && \ - awk 'BEGIN { print("#include \"mediastreamer2/msfilter.h\"\n") } { printf("extern MSFilterDesc %s;\n",$$1) } ' $$builddir/filterdescs.txt > $$builddir/$@ && \ - awk 'BEGIN { print("MSFilterDesc * ms_filter_descs[]={") } { printf("&%s,\n",$$1) } END{ print("NULL\n};\n") } ' $$builddir/filterdescs.txt >> $$builddir/$@ - - -libmediastreamer_la_LIBADD= $(ORTP_LIBS) \ - $(PORTAUDIO_LIBS) \ - $(ALSA_LIBS) \ - $(ARTS_LIBS) \ - $(SPEEX_LIBS) \ - $(GSM_LIBS) \ - $(LIBV4L1_LIBS) \ - $(LIBV4L2_LIBS) -if !BUILD_WIN32 -libmediastreamer_la_LDFLAGS=-rdynamic -else -libmediastreamer_la_LDFLAGS=-no-undefined -endif - -if BUILD_VIDEO -libmediastreamer_la_LIBADD+= $(VIDEO_LIBS) \ - $(THEORA_LIBS) - - -if BUILD_WIN32 -libmediastreamer_la_LIBADD+= -lole32 \ - -loleaut32\ - -lwinmm \ - -luuid - -endif - -endif -if BUILD_WIN32_WCE -libmediastreamer_la_LIBADD+= -lmmtimer -endif - -AM_CFLAGS= -I$(top_srcdir) \ - $(ORTP_CFLAGS) \ - $(SPEEX_CFLAGS) \ - $(GSM_CFLAGS) \ - $(STRICT_OPTIONS) - -AM_CXXFLAGS= -I$(top_srcdir) \ - $(ORTP_CFLAGS) \ - $(STRICT_OPTIONS) - -if BUILD_VIDEO -AM_CFLAGS+=$(VIDEO_CFLAGS) -endif - -AM_OBJCFLAGS=$(AM_CFLAGS) - -imgdir=$(datadir)/images/ - -img_DATA=nowebcamCIF.jpg - diff --git a/linphone/mediastreamer2/src/_kiss_fft_guts.h b/linphone/mediastreamer2/src/_kiss_fft_guts.h deleted file mode 100644 index 02ad5471f..000000000 --- a/linphone/mediastreamer2/src/_kiss_fft_guts.h +++ /dev/null @@ -1,205 +0,0 @@ -/* -Copyright (c) 2003-2004, Mark Borgerding - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. -*/ - -#undef MIN -#undef MAX - -#define MIN(a,b) ((a)<(b) ? (a):(b)) -#define MAX(a,b) ((a)>(b) ? (a):(b)) - -/* kiss_fft.h - defines kiss_fft_scalar as either short or a float type - and defines - typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */ -#include "kiss_fft.h" -//#include "math_approx.h" - -#define MAXFACTORS 32 -/* e.g. an fft of length 128 has 4 factors - as far as kissfft is concerned - 4*4*4*2 - */ - -struct kiss_fft_state{ - int nfft; - int inverse; - int factors[2*MAXFACTORS]; - kiss_fft_cpx twiddles[1]; -}; - -/* - Explanation of macros dealing with complex math: - - C_MUL(m,a,b) : m = a*b - C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise - C_SUB( res, a,b) : res = a - b - C_SUBFROM( res , a) : res -= a - C_ADDTO( res , a) : res += a - * */ -#ifdef MS_FIXED_POINT -# define FRACBITS 15 -# define SAMPPROD ms_int32_t -#define SAMP_MAX 32767 - -#define SAMP_MIN -SAMP_MAX - -#if defined(CHECK_OVERFLOW) -# define CHECK_OVERFLOW_OP(a,op,b) \ - if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ - fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } -#endif - - -# define smul(a,b) ( (SAMPPROD)(a)*(b) ) -# define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) - -# define S_MUL(a,b) sround( smul(a,b) ) - -# define C_MUL(m,a,b) \ - do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ - (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) - -# define C_MUL4(m,a,b) \ - do{ (m).r = PSHR32( smul((a).r,(b).r) - smul((a).i,(b).i),17 ); \ - (m).i = PSHR32( smul((a).r,(b).i) + smul((a).i,(b).r),17 ); }while(0) - -# define DIVSCALAR(x,k) \ - (x) = sround( smul( x, SAMP_MAX/k ) ) - -# define C_FIXDIV(c,div) \ - do { DIVSCALAR( (c).r , div); \ - DIVSCALAR( (c).i , div); }while (0) - -# define C_MULBYSCALAR( c, s ) \ - do{ (c).r = sround( smul( (c).r , s ) ) ;\ - (c).i = sround( smul( (c).i , s ) ) ; }while(0) - -#else /* not FIXED_POINT*/ - -# define S_MUL(a,b) ( (a)*(b) ) -#define C_MUL(m,a,b) \ - do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ - (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) - -#define C_MUL4(m,a,b) C_MUL(m,a,b) - -# define C_FIXDIV(c,div) /* NOOP */ -# define C_MULBYSCALAR( c, s ) \ - do{ (c).r *= (s);\ - (c).i *= (s); }while(0) -#endif - -#ifndef CHECK_OVERFLOW_OP -# define CHECK_OVERFLOW_OP(a,op,b) /* noop */ -#endif - -#define C_ADD( res, a,b)\ - do { \ - CHECK_OVERFLOW_OP((a).r,+,(b).r)\ - CHECK_OVERFLOW_OP((a).i,+,(b).i)\ - (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ - }while(0) -#define C_SUB( res, a,b)\ - do { \ - CHECK_OVERFLOW_OP((a).r,-,(b).r)\ - CHECK_OVERFLOW_OP((a).i,-,(b).i)\ - (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ - }while(0) -#define C_ADDTO( res , a)\ - do { \ - CHECK_OVERFLOW_OP((res).r,+,(a).r)\ - CHECK_OVERFLOW_OP((res).i,+,(a).i)\ - (res).r += (a).r; (res).i += (a).i;\ - }while(0) - -#define C_SUBFROM( res , a)\ - do {\ - CHECK_OVERFLOW_OP((res).r,-,(a).r)\ - CHECK_OVERFLOW_OP((res).i,-,(a).i)\ - (res).r -= (a).r; (res).i -= (a).i; \ - }while(0) - - -#ifdef MS_FIXED_POINT -# define KISS_FFT_COS(phase) floor(MIN(32767,MAX(-32767,.5+32768 * cos (phase)))) -# define KISS_FFT_SIN(phase) floor(MIN(32767,MAX(-32767,.5+32768 * sin (phase)))) -# define HALF_OF(x) ((x)>>1) -#elif defined(USE_SIMD) -# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) -# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) -# define HALF_OF(x) ((x)*_mm_set1_ps(.5)) -#else -# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) -# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) -# define HALF_OF(x) ((x)*.5) -#endif - -#define kf_cexp(x,phase) \ - do{ \ - (x)->r = KISS_FFT_COS(phase);\ - (x)->i = KISS_FFT_SIN(phase);\ - }while(0) - -#ifdef MS_FIXED_POINT - -#define L1 32767 -#define L2 -7651 -#define L3 8277 -#define L4 -626 - -static inline ms_word16_t _ms_cos_pi_2(ms_word16_t x) -{ - ms_word16_t x2; - - x2 = MULT16_16_P15(x,x); - return ADD16(1,MIN16(32766,ADD32(SUB16(L1,x2), MULT16_16_P15(x2, ADD32(L2, MULT16_16_P15(x2, ADD32(L3, MULT16_16_P15(L4, x2)))))))); -} - -static inline ms_word16_t ms_cos_norm(ms_word32_t x) -{ - x = x&0x0001ffff; - if (x>SHL32(EXTEND32(1), 16)) - x = SUB32(SHL32(EXTEND32(1), 17),x); - if (x&0x00007fff) - { - if (xr = ms_cos_norm((phase));\ - (x)->i = ms_cos_norm((phase)-32768);\ -}while(0) - - -/* a debugging function */ -#define pcpx(c)\ - fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) diff --git a/linphone/mediastreamer2/src/alaw.c b/linphone/mediastreamer2/src/alaw.c deleted file mode 100644 index 3ac08a200..000000000 --- a/linphone/mediastreamer2/src/alaw.c +++ /dev/null @@ -1,222 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "g711common.h" - -typedef struct _AlawEncData{ - MSBufferizer *bz; - int ptime; - uint32_t ts; -} AlawEncData; - -static AlawEncData * alaw_enc_data_new(){ - AlawEncData *obj=(AlawEncData *)ms_new(AlawEncData,1); - obj->bz=ms_bufferizer_new(); - obj->ptime=0; - obj->ts=0; - return obj; -} - -static void alaw_enc_data_destroy(AlawEncData *obj){ - ms_bufferizer_destroy(obj->bz); - ms_free(obj); -} - -static void alaw_enc_init(MSFilter *obj){ - obj->data=alaw_enc_data_new(); -} - -static void alaw_enc_uninit(MSFilter *obj){ - alaw_enc_data_destroy((AlawEncData*)obj->data); -} - -static void alaw_enc_process(MSFilter *obj){ - AlawEncData *dt=(AlawEncData*)obj->data; - MSBufferizer *bz=dt->bz; - uint8_t buffer[2240]; - int frame_per_packet=2; - int size_of_pcm=320; - - mblk_t *m; - - if (dt->ptime>=10) - { - frame_per_packet = dt->ptime/10; - } - - if (frame_per_packet<=0) - frame_per_packet=1; - if (frame_per_packet>14) /* 7*20 == 140 ms max */ - frame_per_packet=14; - - size_of_pcm = 160*frame_per_packet; /* ex: for 20ms -> 160*2==320 */ - - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - ms_bufferizer_put(bz,m); - } - while (ms_bufferizer_read(bz,buffer,size_of_pcm)==size_of_pcm){ - mblk_t *o=allocb(size_of_pcm/2,0); - int i; - for (i=0;ib_wptr=s16_to_alaw(((int16_t*)buffer)[i]); - o->b_wptr++; - } - mblk_set_timestamp_info(o,dt->ts); - dt->ts+=size_of_pcm/2; - ms_queue_put(obj->outputs[0],o); - } -} - -static int enc_add_fmtp(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - AlawEncData *s=(AlawEncData*)f->data; - char tmp[30]; - if (fmtp_get_value(fmtp,"ptime",tmp,sizeof(tmp))){ - s->ptime=atoi(tmp); - ms_message("MSAlawEnc: got ptime=%i",s->ptime); - } - return 0; -} - -static int enc_add_attr(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - AlawEncData *s=(AlawEncData*)f->data; - if (strstr(fmtp,"ptime:10")!=NULL){ - s->ptime=10; - }else if (strstr(fmtp,"ptime:20")!=NULL){ - s->ptime=20; - }else if (strstr(fmtp,"ptime:30")!=NULL){ - s->ptime=30; - }else if (strstr(fmtp,"ptime:40")!=NULL){ - s->ptime=40; - }else if (strstr(fmtp,"ptime:50")!=NULL){ - s->ptime=50; - }else if (strstr(fmtp,"ptime:60")!=NULL){ - s->ptime=60; - }else if (strstr(fmtp,"ptime:70")!=NULL){ - s->ptime=70; - }else if (strstr(fmtp,"ptime:80")!=NULL){ - s->ptime=80; - }else if (strstr(fmtp,"ptime:90")!=NULL){ - s->ptime=90; - }else if (strstr(fmtp,"ptime:100")!=NULL){ - s->ptime=100; - }else if (strstr(fmtp,"ptime:110")!=NULL){ - s->ptime=110; - }else if (strstr(fmtp,"ptime:120")!=NULL){ - s->ptime=120; - }else if (strstr(fmtp,"ptime:130")!=NULL){ - s->ptime=130; - }else if (strstr(fmtp,"ptime:140")!=NULL){ - s->ptime=140; - } - return 0; -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_ADD_ATTR , enc_add_attr}, - { MS_FILTER_ADD_FMTP , enc_add_fmtp}, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_alaw_enc_desc={ - MS_ALAW_ENC_ID, - "MSAlawEnc", - N_("ITU-G.711 alaw encoder"), - MS_FILTER_ENCODER, - "pcma", - 1, - 1, - alaw_enc_init, - NULL, - alaw_enc_process, - NULL, - alaw_enc_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_alaw_enc_desc={ - .id=MS_ALAW_ENC_ID, - .name="MSAlawEnc", - .text=N_("ITU-G.711 alaw encoder"), - .category=MS_FILTER_ENCODER, - .enc_fmt="pcma", - .ninputs=1, - .noutputs=1, - .init=alaw_enc_init, - .process=alaw_enc_process, - .uninit=alaw_enc_uninit, - .methods=enc_methods -}; - -#endif - -static void alaw_dec_process(MSFilter *obj){ - mblk_t *m; - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - mblk_t *o; - msgpullup(m,-1); - o=allocb((m->b_wptr-m->b_rptr)*2,0); - for(;m->b_rptrb_wptr;m->b_rptr++,o->b_wptr+=2){ - *((int16_t*)(o->b_wptr))=alaw_to_s16(*m->b_rptr); - } - freemsg(m); - ms_queue_put(obj->outputs[0],o); - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_alaw_dec_desc={ - MS_ALAW_DEC_ID, - "MSAlawDec", - N_("ITU-G.711 alaw decoder"), - MS_FILTER_DECODER, - "pcma", - 1, - 1, - NULL, - NULL, - alaw_dec_process, - NULL, - NULL -}; - -#else - -MSFilterDesc ms_alaw_dec_desc={ - .id=MS_ALAW_DEC_ID, - .name="MSAlawDec", - .text=N_("ITU-G.711 alaw decoder"), - .category=MS_FILTER_DECODER, - .enc_fmt="pcma", - .ninputs=1, - .noutputs=1, - .process=alaw_dec_process, -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_alaw_dec_desc) -MS_FILTER_DESC_EXPORT(ms_alaw_enc_desc) diff --git a/linphone/mediastreamer2/src/alsa.c b/linphone/mediastreamer2/src/alsa.c deleted file mode 100644 index 65f0df720..000000000 --- a/linphone/mediastreamer2/src/alsa.c +++ /dev/null @@ -1,1050 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 - - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/mssndcard.h" - -//#define THREADED_VERSION - -/*in case of troubles with a particular driver, try incrementing ALSA_PERIOD_SIZE -to 512, 1024, 2048, 4096... -then try incrementing the number of periods*/ -#define ALSA_PERIODS 8 -#define ALSA_PERIOD_SIZE 256 - -/*uncomment the following line if you have problems with an alsa driver -having sound quality trouble:*/ -/*#define EPIPE_BUGFIX 1*/ - -static MSSndCard * alsa_card_new(int id); -static MSSndCard *alsa_card_duplicate(MSSndCard *obj); -static MSFilter * ms_alsa_read_new(const char *dev); -static MSFilter * ms_alsa_write_new(const char *dev); - - -struct _AlsaData{ - char *pcmdev; - char *mixdev; -}; - -typedef struct _AlsaData AlsaData; - - -static int alsa_set_params(snd_pcm_t *pcm_handle, int rw, int bits, int stereo, int rate) -{ - snd_pcm_hw_params_t *hwparams=NULL; - snd_pcm_sw_params_t *swparams=NULL; - int dir; - uint exact_uvalue; - unsigned long exact_ulvalue; - int channels; - int periods=ALSA_PERIODS; - int periodsize=ALSA_PERIOD_SIZE; - int err; - int format; - - /* Allocate the snd_pcm_hw_params_t structure on the stack. */ - snd_pcm_hw_params_alloca(&hwparams); - - /* Init hwparams with full configuration space */ - if (snd_pcm_hw_params_any(pcm_handle, hwparams) < 0) { - ms_warning("alsa_set_params: Cannot configure this PCM device."); - return -1; - } - - if (snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) { - ms_warning("alsa_set_params: Error setting access."); - return -1; - } - /* Set sample format */ - format=SND_PCM_FORMAT_S16; - if (snd_pcm_hw_params_set_format(pcm_handle, hwparams, format) < 0) { - ms_warning("alsa_set_params: Error setting format."); - return -1; - } - /* Set number of channels */ - if (stereo) channels=2; - else channels=1; - if (snd_pcm_hw_params_set_channels(pcm_handle, hwparams, channels) < 0) { - ms_warning("alsa_set_params: Error setting channels."); - return -1; - } - /* Set sample rate. If the exact rate is not supported */ - /* by the hardware, use nearest possible rate. */ - exact_uvalue=rate; - dir=0; - if ((err=snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &exact_uvalue, &dir))<0){ - ms_warning("alsa_set_params: Error setting rate to %i:%s",rate,snd_strerror(err)); - return -1; - } - if (dir != 0) { - ms_warning("alsa_set_params: The rate %d Hz is not supported by your hardware.\n " - "==> Using %d Hz instead.", rate, exact_uvalue); - } - /* choose greater period size when rate is high */ - periodsize=periodsize*(rate/8000); - - /* Set buffer size (in frames). The resulting latency is given by */ - /* latency = periodsize * periods / (rate * bytes_per_frame) */ - /* set period size */ - exact_ulvalue=periodsize; - dir=0; - if (snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &exact_ulvalue, &dir) < 0) { - ms_warning("alsa_set_params: Error setting period size."); - return -1; - } - if (dir != 0) { - ms_warning("alsa_set_params: The period size %d is not supported by your hardware.\n " - "==> Using %d instead.", periodsize, (int)exact_ulvalue); - } - ms_warning("alsa_set_params: periodsize:%d Using %d", periodsize, (int)exact_ulvalue); - periodsize=exact_ulvalue; - /* Set number of periods. Periods used to be called fragments. */ - exact_uvalue=periods; - dir=0; - if (snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &exact_uvalue, &dir) < 0) { - ms_warning("alsa_set_params: Error setting periods."); - return -1; - } - ms_warning("alsa_set_params: period:%d Using %d", periods, exact_uvalue); - if (dir != 0) { - ms_warning("alsa_set_params: The number of periods %d is not supported by your hardware.\n " - "==> Using %d instead.", periods, exact_uvalue); - } - /* Apply HW parameter settings to */ - /* PCM device and prepare device */ - if ((err=snd_pcm_hw_params(pcm_handle, hwparams)) < 0) { - ms_warning("alsa_set_params: Error setting HW params:%s",snd_strerror(err)); - return -1; - } - /*prepare sw params */ - if (rw){ - snd_pcm_sw_params_alloca(&swparams); - snd_pcm_sw_params_current(pcm_handle, swparams); - if ((err=snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams,periodsize*2 ))<0){ - ms_warning("alsa_set_params: Error setting start threshold:%s",snd_strerror(err)); - } - if ((err=snd_pcm_sw_params_set_stop_threshold(pcm_handle, swparams,periodsize*periods ))<0){ - ms_warning("alsa_set_params: Error setting stop threshold:%s",snd_strerror(err)); - } - if ((err=snd_pcm_sw_params(pcm_handle, swparams))<0){ - ms_warning("alsa_set_params: Error setting SW params:%s",snd_strerror(err)); - return -1; - } - } - return 0; -} - -#ifdef EPIPE_BUGFIX -static void alsa_fill_w (snd_pcm_t *pcm_handle) -{ - snd_pcm_hw_params_t *hwparams=NULL; - int channels; - snd_pcm_uframes_t buffer_size; - int buffer_size_bytes; - void *buffer; - - /* Allocate the snd_pcm_hw_params_t structure on the stack. */ - snd_pcm_hw_params_alloca(&hwparams); - snd_pcm_hw_params_current(pcm_handle, hwparams); - - /* get channels */ - snd_pcm_hw_params_get_channels (hwparams, &channels); - - /* get buffer size */ - snd_pcm_hw_params_get_buffer_size (hwparams, &buffer_size); - - /* fill half */ - buffer_size /= 2; - - /* allocate buffer assuming 2 bytes per sample */ - buffer_size_bytes = buffer_size * channels * 2; - buffer = alloca (buffer_size_bytes); - memset (buffer, 0, buffer_size_bytes); - - /* write data */ - snd_pcm_writei(pcm_handle, buffer, buffer_size); -} -#endif - -static snd_pcm_t * alsa_open_r(const char *pcmdev,int bits,int stereo,int rate) -{ - snd_pcm_t *pcm_handle; - int err; - - ms_message("alsa_open_r: opening %s at %iHz, bits=%i, stereo=%i",pcmdev,rate,bits,stereo); - - -#ifndef THREADED_VERSION - if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_CAPTURE,SND_PCM_NONBLOCK) < 0) { - ms_warning("alsa_open_r: Error opening PCM device %s",pcmdev ); - return NULL; - } -#else - /* want blocking mode for threaded version */ - if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_CAPTURE,0) < 0) { - ms_warning("alsa_open_r: Error opening PCM device %s",pcmdev ); - return NULL; - } -#endif - - { - struct timeval tv1; - struct timeval tv2; - struct timezone tz; - int diff = 0; - err = gettimeofday(&tv1, &tz); - while (1) { - if (!(alsa_set_params(pcm_handle,0,bits,stereo,rate)<0)){ - ms_message("alsa_open_r: Audio params set"); - break; - } - if (!gettimeofday(&tv2, &tz) && !err) { - diff = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec); - } else { - diff = -1; - } - if ((diff < 0) || (diff > 3000000)) { /* 3 secondes */ - ms_error("alsa_open_r: Error setting params for more than 3 seconds"); - snd_pcm_close(pcm_handle); - return NULL; - } - ms_warning("alsa_open_r: Error setting params (for %d micros)", diff); - usleep(200000); - } - } - - err=snd_pcm_start(pcm_handle); - if (err<0){ - ms_warning("snd_pcm_start() failed: %s", snd_strerror(err)); - } - return pcm_handle; -} - -static snd_pcm_t * alsa_open_w(const char *pcmdev,int bits,int stereo,int rate) -{ - snd_pcm_t *pcm_handle; - - if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK) < 0) { - ms_warning("alsa_open_w: Error opening PCM device %s",pcmdev ); - return NULL; - } - - { - struct timeval tv1; - struct timeval tv2; - struct timezone tz; - int diff = 0; - int err; - err = gettimeofday(&tv1, &tz); - while (1) { - if (!(alsa_set_params(pcm_handle,1,bits,stereo,rate)<0)){ - ms_message("alsa_open_w: Audio params set"); - break; - } - if (!gettimeofday(&tv2, &tz) && !err) { - diff = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec); - } else { - diff = -1; - } - if ((diff < 0) || (diff > 3000000)) { /* 3 secondes */ - ms_error("alsa_open_w: Error setting params for more than 3 seconds"); - snd_pcm_close(pcm_handle); - return NULL; - } - ms_warning("alsa_open_w: Error setting params (for %d micros)", diff); - usleep(200000); - } - } - - return pcm_handle; -} - -static int alsa_can_read(snd_pcm_t *dev) -{ - snd_pcm_sframes_t avail; - int err; - - avail = snd_pcm_avail_update(dev); - /* A buggy driver does not return an error while being in Xrun */ - if (avail >= 0 && snd_pcm_state(dev) == SND_PCM_STATE_XRUN) avail=-EPIPE; - if (avail < 0) { - ms_error("snd_pcm_avail_update: %s", snd_strerror(avail)); // most probably -EPIPE - /* overrun occured, snd_pcm_state() would return SND_PCM_STATE_XRUN - FIXME: handle other error conditions*/ - ms_error("*** alsa_can_read fixup, trying to recover"); - snd_pcm_drain(dev); /* Ignore possible error, at least -EAGAIN.*/ - err = snd_pcm_recover(dev, avail, 0); - if (err){ - ms_error("snd_pcm_recover() failed with err %d: %s", err, snd_strerror(err)); - return -1; - } - err = snd_pcm_start(dev); - if (err){ - ms_error("snd_pcm_start() failed with err %d: %s", err, snd_strerror(err)); - return -1; - } - ms_message("Recovery done"); - } - return avail; -} - -static int alsa_read(snd_pcm_t *handle,unsigned char *buf,int nsamples) -{ - int err; - err=snd_pcm_readi(handle,buf,nsamples); - if (err<0) { - ms_warning("alsa_read: snd_pcm_readi() returned %i",err); - if (err==-EPIPE){ - snd_pcm_prepare(handle); - err=snd_pcm_readi(handle,buf,nsamples); - if (err<0) ms_warning("alsa_read: snd_pcm_readi() failed:%s.",snd_strerror(err)); - }else if (err!=-EWOULDBLOCK){ - ms_warning("alsa_read: snd_pcm_readi() failed:%s.",snd_strerror(err)); - } - }else if (err==0){ - ms_warning("alsa_read: snd_pcm_readi() returned 0"); - } - return err; -} - - -static int alsa_write(snd_pcm_t *handle,unsigned char *buf,int nsamples) -{ - int err; - if ((err=snd_pcm_writei(handle,buf,nsamples))<0){ - if (err==-EPIPE){ - snd_pcm_prepare(handle); -#ifdef EPIPE_BUGFIX - alsa_fill_w (handle); -#endif - err=snd_pcm_writei(handle,buf,nsamples); - if (err<0) ms_warning("alsa_card_write: Error writing sound buffer (nsamples=%i):%s",nsamples,snd_strerror(err)); - }else if (err!=-EWOULDBLOCK){ - ms_warning("alsa_card_write: snd_pcm_writei() failed:%s.",snd_strerror(err)); - } - }else if (err!=nsamples) { - ms_debug("Only %i samples written instead of %i",err,nsamples); - } - return err; -} - - -static snd_mixer_t *alsa_mixer_open(const char *mixdev){ - snd_mixer_t *mixer=NULL; - int err; - err=snd_mixer_open(&mixer,0); - if (err<0){ - ms_warning("Could not open alsa mixer: %s",snd_strerror(err)); - return NULL; - } - if ((err = snd_mixer_attach (mixer, mixdev)) < 0){ - ms_warning("Could not attach mixer to card: %s",snd_strerror(err)); - snd_mixer_close(mixer); - return NULL; - } - if ((err = snd_mixer_selem_register (mixer, NULL, NULL)) < 0){ - ms_warning("snd_mixer_selem_register: %s",snd_strerror(err)); - snd_mixer_close(mixer); - return NULL; - } - if ((err = snd_mixer_load (mixer)) < 0){ - ms_warning("snd_mixer_load: %s",snd_strerror(err)); - snd_mixer_close(mixer); - return NULL; - } - return mixer; -} - -static void alsa_mixer_close(snd_mixer_t *mix){ - snd_mixer_close(mix); -} - -typedef enum {CAPTURE, PLAYBACK, CAPTURE_SWITCH, PLAYBACK_SWITCH} MixerAction; - -static int get_mixer_element(snd_mixer_t *mixer,const char *name, MixerAction action){ - long value=0; - const char *elemname; - snd_mixer_elem_t *elem; - int err; - long sndMixerPMin=0; - long sndMixerPMax=0; - long newvol=0; - elem=snd_mixer_first_elem(mixer); - while (elem!=NULL){ - elemname=snd_mixer_selem_get_name(elem); - //ms_message("Found alsa mixer element %s.",elemname); - if (strcmp(elemname,name)==0){ - switch (action){ - case CAPTURE: - if (snd_mixer_selem_has_capture_volume(elem)){ - snd_mixer_selem_get_capture_volume_range(elem, &sndMixerPMin, &sndMixerPMax); - err=snd_mixer_selem_get_capture_volume(elem,SND_MIXER_SCHN_UNKNOWN,&newvol); - newvol-=sndMixerPMin; - value=(100*newvol)/(sndMixerPMax-sndMixerPMin); - if (err<0) ms_warning("Could not get capture volume for %s:%s",name,snd_strerror(err)); - //else ms_message("Successfully get capture level for %s.",elemname); - break; - } - break; - case PLAYBACK: - if (snd_mixer_selem_has_playback_volume(elem)){ - snd_mixer_selem_get_playback_volume_range(elem, &sndMixerPMin, &sndMixerPMax); - err=snd_mixer_selem_get_playback_volume(elem,SND_MIXER_SCHN_FRONT_LEFT,&newvol); - newvol-=sndMixerPMin; - value=(100*newvol)/(sndMixerPMax-sndMixerPMin); - if (err<0) ms_warning("Could not get playback volume for %s:%s",name,snd_strerror(err)); - //else ms_message("Successfully get playback level for %s.",elemname); - break; - } - break; - case CAPTURE_SWITCH: - - break; - case PLAYBACK_SWITCH: - - break; - } - } - elem=snd_mixer_elem_next(elem); - } - - return value; -} - - -static void set_mixer_element(snd_mixer_t *mixer,const char *name, int level,MixerAction action){ - const char *elemname; - snd_mixer_elem_t *elem; - long sndMixerPMin=0; - long sndMixerPMax=0; - long newvol=0; - - elem=snd_mixer_first_elem(mixer); - - while (elem!=NULL){ - elemname=snd_mixer_selem_get_name(elem); - //ms_message("Found alsa mixer element %s.",elemname); - if (strcmp(elemname,name)==0){ - switch(action){ - case CAPTURE: - if (snd_mixer_selem_has_capture_volume(elem)){ - snd_mixer_selem_get_capture_volume_range(elem, &sndMixerPMin, &sndMixerPMax); - newvol=(((sndMixerPMax-sndMixerPMin)*level)/100)+sndMixerPMin; - snd_mixer_selem_set_capture_volume_all(elem,newvol); - //ms_message("Successfully set capture level for %s.",elemname); - return; - } - break; - case PLAYBACK: - if (snd_mixer_selem_has_playback_volume(elem)){ - snd_mixer_selem_get_playback_volume_range(elem, &sndMixerPMin, &sndMixerPMax); - newvol=(((sndMixerPMax-sndMixerPMin)*level)/100)+sndMixerPMin; - snd_mixer_selem_set_playback_volume_all(elem,newvol); - //ms_message("Successfully set playback level for %s.",elemname); - return; - } - break; - case CAPTURE_SWITCH: - if (snd_mixer_selem_has_capture_switch(elem)){ - snd_mixer_selem_set_capture_switch_all(elem,level); - //ms_message("Successfully set capture switch for %s.",elemname); - } - break; - case PLAYBACK_SWITCH: - if (snd_mixer_selem_has_playback_switch(elem)){ - snd_mixer_selem_set_playback_switch_all(elem,level); - //ms_message("Successfully set capture switch for %s.",elemname); - } - break; - - } - } - elem=snd_mixer_elem_next(elem); - } - - return ; -} - - -static void alsa_card_set_level(MSSndCard *obj,MSSndCardMixerElem e,int a) -{ - snd_mixer_t *mixer; - AlsaData *ad=(AlsaData*)obj->data; - mixer=alsa_mixer_open(ad->mixdev); - if (mixer==NULL) return ; - switch(e){ - case MS_SND_CARD_MASTER: - set_mixer_element(mixer,"Master",a,PLAYBACK); - break; - case MS_SND_CARD_CAPTURE: - set_mixer_element(mixer,"Capture",a,CAPTURE); - break; - case MS_SND_CARD_PLAYBACK: - set_mixer_element(mixer,"PCM",a,PLAYBACK); - break; - default: - ms_warning("alsa_card_set_level: unsupported command."); - } - alsa_mixer_close(mixer); -} - -static int alsa_card_get_level(MSSndCard *obj, MSSndCardMixerElem e) -{ - snd_mixer_t *mixer; - AlsaData *ad=(AlsaData*)obj->data; - int value = -1; - mixer=alsa_mixer_open(ad->mixdev); - if (mixer==NULL) return 0; - switch(e){ - case MS_SND_CARD_MASTER: - value=get_mixer_element(mixer,"Master",PLAYBACK); - break; - case MS_SND_CARD_CAPTURE: - value=get_mixer_element(mixer,"Capture",CAPTURE); - break; - case MS_SND_CARD_PLAYBACK: - value=get_mixer_element(mixer,"PCM",PLAYBACK); - break; - default: - ms_warning("alsa_card_set_level: unsupported command."); - } - alsa_mixer_close(mixer); - return value; -} - -static void alsa_card_set_source(MSSndCard *obj,MSSndCardCapture source) -{ - snd_mixer_t *mixer; - AlsaData *ad=(AlsaData*)obj->data; - mixer=alsa_mixer_open(ad->mixdev); - if (mixer==NULL) return; - switch (source){ - case MS_SND_CARD_MIC: - set_mixer_element(mixer,"Mic",1,CAPTURE_SWITCH); - set_mixer_element(mixer,"Capture",1,CAPTURE_SWITCH); - break; - case MS_SND_CARD_LINE: - set_mixer_element(mixer,"Line",1,CAPTURE_SWITCH); - set_mixer_element(mixer,"Capture",1,CAPTURE_SWITCH); - break; - } - alsa_mixer_close(mixer); -} - -static MSFilter *alsa_card_create_reader(MSSndCard *card) -{ - AlsaData *ad=(AlsaData*)card->data; - MSFilter *f=ms_alsa_read_new(ad->pcmdev); - return f; -} - -static MSFilter *alsa_card_create_writer(MSSndCard *card) -{ - AlsaData *ad=(AlsaData*)card->data; - MSFilter *f=ms_alsa_write_new(ad->pcmdev); - return f; -} - - -static void alsa_card_init(MSSndCard *obj){ - AlsaData *ad=ms_new0(AlsaData,1); - obj->data=ad; -} - -static void alsa_card_uninit(MSSndCard *obj){ - AlsaData *ad=(AlsaData*)obj->data; - if (ad->pcmdev!=NULL) ms_free(ad->pcmdev); - if (ad->mixdev!=NULL) ms_free(ad->mixdev); - ms_free(ad); -} - -static void alsa_card_detect(MSSndCardManager *m){ - int i; - for (i=-1;i<10;i++){ - MSSndCard *card=alsa_card_new(i); - if (card!=NULL) - ms_snd_card_manager_add_card(m,card); - } -} - -MSSndCardDesc alsa_card_desc={ - .driver_type="ALSA", - .detect=alsa_card_detect, - .init=alsa_card_init, - .set_level=alsa_card_set_level, - .get_level=alsa_card_get_level, - .set_capture=alsa_card_set_source, - .set_control=NULL, - .get_control=NULL, - .create_reader=alsa_card_create_reader, - .create_writer=alsa_card_create_writer, - .uninit=alsa_card_uninit, - .duplicate=alsa_card_duplicate -}; - -static MSSndCard *alsa_card_duplicate(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&alsa_card_desc); - AlsaData* dcard=(AlsaData*)card->data; - AlsaData* dobj=(AlsaData*)obj->data; - card->name=ms_strdup(obj->name); - card->id=ms_strdup(obj->id); - dcard->pcmdev=ms_strdup(dobj->pcmdev); - dcard->mixdev=ms_strdup(dobj->mixdev); - return card; -} - -MSSndCard * ms_alsa_card_new_custom(const char *pcmdev, const char *mixdev){ - MSSndCard * obj; - AlsaData *ad; - obj=ms_snd_card_new(&alsa_card_desc); - ad=(AlsaData*)obj->data; - obj->name=ms_strdup(pcmdev); - ad->pcmdev=ms_strdup(pcmdev); - ad->mixdev=ms_strdup(mixdev); - return obj; -} - -static unsigned int get_card_capabilities(const char *devname){ - snd_pcm_t *pcm_handle; - unsigned int ret=0; - if (snd_pcm_open(&pcm_handle,devname,SND_PCM_STREAM_CAPTURE,SND_PCM_NONBLOCK)==0) { - ret|=MS_SND_CARD_CAP_CAPTURE; - snd_pcm_close(pcm_handle); - } - if (snd_pcm_open(&pcm_handle,devname,SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK)==0) { - ret|=MS_SND_CARD_CAP_PLAYBACK; - snd_pcm_close(pcm_handle); - } - return ret; -} - -static MSSndCard * alsa_card_new(int id) -{ - MSSndCard * obj; - char *name=NULL; - AlsaData *ad; - int err; - - if (id!=-1){ - err=snd_card_get_name(id,&name); - if (err<0) { - return NULL; - } - } - obj=ms_snd_card_new(&alsa_card_desc); - ad=(AlsaData*)obj->data; - if (id==-1) { - /* the default pcm device */ - obj->name=ms_strdup("default device"); - ad->pcmdev=ms_strdup("default"); - ad->mixdev=ms_strdup("default"); - }else{ - /* remove trailing spaces from card name */ - char *pos1, *pos2; - pos1=ms_strdup(name); - pos2=pos1+strlen(pos1)-1; - for (; pos2>pos1 && *pos2==' '; pos2--) *pos2='\0'; - obj->name=pos1; - ad->pcmdev=ms_strdup_printf("default:%i",id); - ad->mixdev=ms_strdup_printf("default:%i",id); - { - snd_mixer_t *mixer; - mixer = alsa_mixer_open(ad->mixdev); - if (mixer==NULL) { - ms_free(ad->mixdev); - ad->mixdev=ms_strdup_printf("hw:%i",id); - } else { - alsa_mixer_close(mixer); - } - } - } - /*check card capabilities: */ - obj->capabilities=get_card_capabilities(ad->pcmdev); - if (obj->capabilities==0){ - ms_warning("Strange, sound card %s does not seems to be capable of anything, retrying with plughw...",obj->name); - /*retry with plughw: this workarounds an alsa bug*/ - ms_free(ad->pcmdev); - ad->pcmdev=ms_strdup_printf("plughw:%i",id); - obj->capabilities=get_card_capabilities(ad->pcmdev); - if (obj->capabilities==0){ - ms_warning("Strange, sound card %s seems totally unusable.",obj->name); - } - } - free(name); - /*ms_message("alsa device %s found",obj->name);*/ - return obj; -} - -struct _AlsaReadData{ - char *pcmdev; - snd_pcm_t *handle; - int rate; - int nchannels; - -#ifdef THREADED_VERSION - ms_thread_t thread; - ms_mutex_t mutex; - MSBufferizer * bufferizer; - bool_t read_started; - bool_t write_started; -#endif -}; - -typedef struct _AlsaReadData AlsaReadData; - -void alsa_read_init(MSFilter *obj){ - AlsaReadData *ad=ms_new(AlsaReadData,1); - ad->pcmdev=NULL; - ad->handle=NULL; - ad->rate=8000; - ad->nchannels=1; - obj->data=ad; - -#ifdef THREADED_VERSION - ad->read_started=FALSE; - ad->write_started=FALSE; - ad->bufferizer=ms_bufferizer_new(); - ms_mutex_init(&ad->mutex,NULL); - ad->thread=0; -#endif -} - -#ifdef THREADED_VERSION - -static void * alsa_write_thread(void *p){ - AlsaReadData *ad=(AlsaReadData*)p; - int samples=(160*ad->rate)/8000; - int err; - int count=0; - mblk_t *om=NULL; - struct timeval timeout; - if (ad->handle==NULL && ad->pcmdev!=NULL){ - ad->handle=alsa_open_r(ad->pcmdev,16,ad->nchannels==2,ad->rate); - } - if (ad->handle==NULL) return NULL; - - while (ad->read_started) - { - count = alsa_can_read(ad->handle,samples); - if (count==24) - { /* keep this value for this driver */ } - else if (count<=0) - { - count = samples; - } - else if (count>0) - { - //ms_warning("%i count", count); - //count = samples; - } - - int size=count*2; - om=allocb(size,0); - - if ((err=alsa_read(ad->handle,om->b_wptr,count))<=0) - { - ms_warning("nothing to read"); - //ms_warning("Fail to read samples %i", count); - freemsg(om); /* leak fixed */ - continue; - } - //ms_warning(" read %i", err); - - size=err*2; - om->b_wptr+=size; - - ms_mutex_lock(&ad->mutex); - ms_bufferizer_put(ad->bufferizer,om); - ms_mutex_unlock(&ad->mutex); - - if (count==24) - { - timeout.tv_sec = 0; - timeout.tv_usec = 2000; - select(0, 0, NULL, NULL, &timeout ); - } - else - { - /* select will be less active than locking on "read" */ - timeout.tv_sec = 0; - timeout.tv_usec = 5000; - select(0, 0, NULL, NULL, &timeout ); - } - } - - if (ad->handle!=NULL) snd_pcm_close(ad->handle); - ad->handle=NULL; - return NULL; -} - -static void alsa_start_r(AlsaReadData *d){ - if (d->read_started==FALSE){ - d->read_started=TRUE; - ms_thread_create(&d->thread,NULL,alsa_write_thread,d); - }else d->read_started=TRUE; -} - -static void alsa_stop_r(AlsaReadData *d){ - d->read_started=FALSE; - if (d->thread!=0) - { - ms_thread_join(d->thread,NULL); - d->thread=0; - } -} -#endif - -#ifdef THREADED_VERSION -void alsa_read_preprocess(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - alsa_start_r(ad); -} -#endif - -void alsa_read_postprocess(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; -#ifdef THREADED_VERSION - alsa_stop_r(ad); -#endif - if (ad->handle!=NULL) snd_pcm_close(ad->handle); - ad->handle=NULL; -} - -void alsa_read_uninit(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; -#ifdef THREADED_VERSION - alsa_stop_r(ad); -#endif - if (ad->pcmdev!=NULL) ms_free(ad->pcmdev); - if (ad->handle!=NULL) snd_pcm_close(ad->handle); -#ifdef THREADED_VERSION - ms_bufferizer_destroy(ad->bufferizer); - ms_mutex_destroy(&ad->mutex); -#endif - ms_free(ad); -} - -#ifndef THREADED_VERSION -void alsa_read_process(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - int samples=(128*ad->rate)/8000; - int err; - mblk_t *om=NULL; - if (ad->handle==NULL && ad->pcmdev!=NULL){ - ad->handle=alsa_open_r(ad->pcmdev,16,ad->nchannels==2,ad->rate); - } - if (ad->handle==NULL) return; - while (alsa_can_read(ad->handle)>=samples){ - - int size=samples*2; - om=allocb(size,0); - if ((err=alsa_read(ad->handle,om->b_wptr,samples))<=0) { - ms_warning("Fail to read samples"); - freemsg(om); - return; - } - size=err*2; - om->b_wptr+=size; - /*ms_message("alsa_read_process: Outputing %i bytes",size);*/ - ms_queue_put(obj->outputs[0],om); - } -} -#endif - -#ifdef THREADED_VERSION -void alsa_read_process(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - mblk_t *om=NULL; - int samples=(160*ad->rate)/8000; - - ms_mutex_lock(&ad->mutex); - while (ms_bufferizer_get_avail(ad->bufferizer)>=samples*2){ - - om=allocb(samples*2,0); - ms_bufferizer_read(ad->bufferizer,om->b_wptr,samples*2); - om->b_wptr+=samples*2; - /*ms_message("alsa_read_process: Outputing %i bytes",size);*/ - ms_queue_put(obj->outputs[0],om); - } - ms_mutex_unlock(&ad->mutex); -} -#endif - -static int alsa_read_get_sample_rate(MSFilter *obj, void *param){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - *((int*)param)=ad->rate; - return 0; -} - -static int alsa_read_set_sample_rate(MSFilter *obj, void *param){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - ad->rate=*((int*)param); - return 0; -} - -static int alsa_read_set_nchannels(MSFilter *obj, void *param){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - ad->nchannels=*((int*)param); - return 0; -} - -MSFilterMethod alsa_read_methods[]={ - {MS_FILTER_GET_SAMPLE_RATE, alsa_read_get_sample_rate}, - {MS_FILTER_SET_SAMPLE_RATE, alsa_read_set_sample_rate}, - {MS_FILTER_SET_NCHANNELS, alsa_read_set_nchannels}, - {0,NULL} -}; - -MSFilterDesc alsa_read_desc={ - .id=MS_ALSA_READ_ID, - .name="MSAlsaRead", - .text=N_("Alsa sound source"), - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .init=alsa_read_init, -#ifdef THREADED_VERSION - .preprocess=alsa_read_preprocess, -#endif - .process=alsa_read_process, - .postprocess=alsa_read_postprocess, - .uninit=alsa_read_uninit, - .methods=alsa_read_methods -}; - -static MSFilter * ms_alsa_read_new(const char *dev){ - MSFilter *f=ms_filter_new_from_desc(&alsa_read_desc); - AlsaReadData *ad=(AlsaReadData*)f->data; - ad->pcmdev=ms_strdup(dev); - return f; -} - -typedef struct _AlsaReadData AlsaWriteData; - -void alsa_write_init(MSFilter *obj){ - AlsaWriteData *ad=ms_new(AlsaWriteData,1); - ad->pcmdev=NULL; - ad->handle=NULL; - ad->rate=8000; - ad->nchannels=1; - obj->data=ad; -} - -void alsa_write_postprocess(MSFilter *obj){ - AlsaReadData *ad=(AlsaReadData*)obj->data; - if (ad->handle!=NULL) snd_pcm_close(ad->handle); - ad->handle=NULL; -} - -void alsa_write_uninit(MSFilter *obj){ - AlsaWriteData *ad=(AlsaWriteData*)obj->data; - if (ad->pcmdev!=NULL) ms_free(ad->pcmdev); - if (ad->handle!=NULL) snd_pcm_close(ad->handle); - ms_free(ad); -} - -static int alsa_write_get_sample_rate(MSFilter *obj, void *data){ - AlsaWriteData *ad=(AlsaWriteData*)obj->data; - *((int*)data)=ad->rate; - return 0; -} - -int alsa_write_set_sample_rate(MSFilter *obj, void *data){ - int *rate=(int*)data; - AlsaWriteData *ad=(AlsaWriteData*)obj->data; - ad->rate=*rate; - return 0; -} - -int alsa_write_set_nchannels(MSFilter *obj, void *data){ - int *n=(int*)data; - AlsaWriteData *ad=(AlsaWriteData*)obj->data; - ad->nchannels=*n; - return 0; -} - -void alsa_write_process(MSFilter *obj){ - AlsaWriteData *ad=(AlsaWriteData*)obj->data; - mblk_t *im=NULL; - int size; - int samples; - int err; - if (ad->handle==NULL && ad->pcmdev!=NULL){ - ad->handle=alsa_open_w(ad->pcmdev,16,ad->nchannels==2,ad->rate); -#ifdef EPIPE_BUGFIX - alsa_fill_w (ad->pcmdev); -#endif - } - if (ad->handle==NULL) { - ms_queue_flush(obj->inputs[0]); - return; - } - while ((im=ms_queue_get(obj->inputs[0]))!=NULL){ - while((size=im->b_wptr-im->b_rptr)>0){ - samples=size/(2*ad->nchannels); - err=alsa_write(ad->handle,im->b_rptr,samples); - if (err>0) { - im->b_rptr+=err*(2*ad->nchannels); - } - else break; - } - freemsg(im); - } -} - -MSFilterMethod alsa_write_methods[]={ - {MS_FILTER_GET_SAMPLE_RATE, alsa_write_get_sample_rate}, - {MS_FILTER_SET_SAMPLE_RATE, alsa_write_set_sample_rate}, - {MS_FILTER_SET_NCHANNELS, alsa_write_set_nchannels}, - {0,NULL} -}; - -MSFilterDesc alsa_write_desc={ - .id=MS_ALSA_WRITE_ID, - .name="MSAlsaWrite", - .text=N_("Alsa sound output"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .init=alsa_write_init, - .process=alsa_write_process, - .postprocess=alsa_write_postprocess, - .uninit=alsa_write_uninit, - .methods=alsa_write_methods -}; - - -static MSFilter * ms_alsa_write_new(const char *dev){ - MSFilter *f=ms_filter_new_from_desc(&alsa_write_desc); - AlsaWriteData *ad=(AlsaWriteData*)f->data; - ad->pcmdev=ms_strdup(dev); - return f; -} - - -MS_FILTER_DESC_EXPORT(alsa_write_desc) - -MS_FILTER_DESC_EXPORT(alsa_read_desc) - diff --git a/linphone/mediastreamer2/src/aqsnd.c b/linphone/mediastreamer2/src/aqsnd.c deleted file mode 100644 index 0c7f06bd8..000000000 --- a/linphone/mediastreamer2/src/aqsnd.c +++ /dev/null @@ -1,955 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -/* this file is specifically distributed under a BSD license */ - -/** -* Copyright (C) 2008 Hiroki Mori (himori@users.sourceforge.net) -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * Neither the name of the nor the -* names of its contributors may be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY ``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 BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (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 is MacOS X Audio Queue Service support code for mediastreamer2. - Audio Queue Support MacOS X 10.5 or later. - http://developer.apple.com/documentation/MusicAudio/Conceptual/AudioQueueProgrammingGuide/ - */ - -#include -#if (!defined(__AudioHardware_h__) & !defined(__IPHONE_3_0)) -#include "AudioHardware.h" -#endif - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" - -MSFilter *ms_aq_read_new(MSSndCard * card); -MSFilter *ms_aq_write_new(MSSndCard * card); - -#define kSecondsPerBuffer 0.02 /*0.04 */ -#define kNumberAudioOutDataBuffers 4 -#define kNumberAudioInDataBuffers 4 - -float gain_volume_in=1.0; -float gain_volume_out=1.0; -bool gain_changed_in = true; -bool gain_changed_out = true; - -typedef struct AQData { - CFStringRef uidname; - AudioStreamBasicDescription devicereadFormat; - AudioStreamBasicDescription devicewriteFormat; - - int rate; - int bits; - bool_t stereo; - - ms_mutex_t mutex; - queue_t rq; - bool_t read_started; - bool_t write_started; - - AudioConverterRef readAudioConverter; - AudioQueueRef readQueue; - AudioStreamBasicDescription readAudioFormat; - UInt32 readBufferByteSize; - - AudioConverterRef writeAudioConverter; - AudioQueueRef writeQueue; - AudioStreamBasicDescription writeAudioFormat; - UInt32 writeBufferByteSize; - AudioQueueBufferRef writeBuffers[kNumberAudioOutDataBuffers]; - int curWriteBuffer; - MSBufferizer *bufferizer; -} AQData; - - - -/* - mediastreamer2 function - */ - -typedef struct AqSndDsCard { - CFStringRef uidname; - AudioStreamBasicDescription devicereadFormat; - AudioStreamBasicDescription devicewriteFormat; - int removed; -} AqSndDsCard; - -static void aqcard_set_level(MSSndCard * card, MSSndCardMixerElem e, - int percent) -{ - switch(e){ - case MS_SND_CARD_PLAYBACK: - case MS_SND_CARD_MASTER: - gain_volume_out =((float)percent)/100.0f; - gain_changed_out = true; - return; - case MS_SND_CARD_CAPTURE: - gain_volume_in =((float)percent)/100.0f; - gain_changed_in = true; - return; - default: - ms_warning("aqcard_set_level: unsupported command."); - } -} - -static int aqcard_get_level(MSSndCard * card, MSSndCardMixerElem e) -{ - switch(e){ - case MS_SND_CARD_PLAYBACK: - case MS_SND_CARD_MASTER: - { - } - return (int)(gain_volume_out*100.0f); - case MS_SND_CARD_CAPTURE: - return (int)(gain_volume_in*100.0f); - default: - ms_warning("aqcard_get_level: unsupported command."); - } - return -1; -} - -static void aqcard_set_source(MSSndCard * card, MSSndCardCapture source) -{ -} - -static void aqcard_init(MSSndCard * card) -{ - AqSndDsCard *c = (AqSndDsCard *) ms_new(AqSndDsCard, 1); - c->removed = 0; - card->data = c; -} - -static void aqcard_uninit(MSSndCard * card) -{ - AqSndDsCard *d = (AqSndDsCard *) card->data; - if (d->uidname != NULL) - CFRelease(d->uidname); - ms_free(d); -} - -static void aqcard_detect(MSSndCardManager * m); -static MSSndCard *aqcard_duplicate(MSSndCard * obj); - -MSSndCardDesc aq_card_desc = { - .driver_type = "AQ", - .detect = aqcard_detect, - .init = aqcard_init, - .set_level = aqcard_set_level, - .get_level = aqcard_get_level, - .set_capture = aqcard_set_source, - .set_control = NULL, - .get_control = NULL, - .create_reader = ms_aq_read_new, - .create_writer = ms_aq_write_new, - .uninit = aqcard_uninit, - .duplicate = aqcard_duplicate -}; - -static MSSndCard *aqcard_duplicate(MSSndCard * obj) -{ - MSSndCard *card = ms_snd_card_new(&aq_card_desc); - card->name = ms_strdup(obj->name); - card->data = ms_new(AqSndDsCard, 1); - memcpy(card->data, obj->data, sizeof(AqSndDsCard)); - return card; -} - -static MSSndCard *aq_card_new(const char *name, CFStringRef uidname, - AudioStreamBasicDescription * - devicereadFormat, - AudioStreamBasicDescription * - devicewriteFormat, unsigned cap) -{ - MSSndCard *card = ms_snd_card_new(&aq_card_desc); - AqSndDsCard *d = (AqSndDsCard *) card->data; - d->uidname = uidname; - memcpy(&d->devicereadFormat, devicereadFormat, - sizeof(AudioStreamBasicDescription)); - memcpy(&d->devicewriteFormat, devicewriteFormat, - sizeof(AudioStreamBasicDescription)); - card->name = ms_strdup(name); - card->capabilities = cap; - return card; -} - -static void show_format(char *name, - AudioStreamBasicDescription * deviceFormat) -{ - ms_debug("Format for %s", name); - ms_debug("mSampleRate = %g", deviceFormat->mSampleRate); - char *the4CCString = (char *) &deviceFormat->mFormatID; - char outName[5]; - outName[0] = the4CCString[0]; - outName[1] = the4CCString[1]; - outName[2] = the4CCString[2]; - outName[3] = the4CCString[3]; - outName[4] = 0; - ms_debug("mFormatID = %s", outName); - ms_debug("mFormatFlags = %08lX", deviceFormat->mFormatFlags); - ms_debug("mBytesPerPacket = %ld", deviceFormat->mBytesPerPacket); - ms_debug("mFramesPerPacket = %ld", deviceFormat->mFramesPerPacket); - ms_debug("mChannelsPerFrame = %ld", deviceFormat->mChannelsPerFrame); - ms_debug("mBytesPerFrame = %ld", deviceFormat->mBytesPerFrame); - ms_debug("mBitsPerChannel = %ld", deviceFormat->mBitsPerChannel); -} - -static void aqcard_detect(MSSndCardManager * m) -{ - OSStatus err; - UInt32 slen; - int count; - Boolean writable; - int i; - writable = 0; - slen = 0; - err = - AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &slen, - &writable); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioHardwarePropertyDevices error %ld", err); - return; - } - AudioDeviceID V[slen / sizeof(AudioDeviceID)]; - err = - AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &slen, V); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioHardwarePropertyDevices error %ld", err); - return; - } - count = slen / sizeof(AudioDeviceID); - for (i = 0; i < count; i++) { - char devname[256]; - char uidname[256]; - int cap = 0; - slen = 256; - err = - AudioDeviceGetProperty(V[i], 0, FALSE, - kAudioDevicePropertyDeviceName, &slen, - devname); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioDevicePropertyDeviceName error %ld", err); - continue; - } - slen = strlen(devname); - /* trim whitespace */ - while ((slen > 0) && (devname[slen - 1] == ' ')) { - slen--; - } - devname[slen] = '\0'; - - err = - AudioDeviceGetPropertyInfo(V[i], 0, FALSE, - kAudioDevicePropertyStreamConfiguration, - &slen, &writable); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioDevicePropertyDeviceName error %ld", err); - continue; - } - AudioBufferList *buflist = ms_new(slen, 1); - if (buflist == NULL) { - ms_error("alloc AudioBufferList %ld", err); - continue; - } - - err = - AudioDeviceGetProperty(V[i], 0, FALSE, - kAudioDevicePropertyStreamConfiguration, - &slen, buflist); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioDevicePropertyDeviceName error %ld", err); - ms_free(buflist); - continue; - } - - UInt32 j; - for (j = 0; j < buflist->mNumberBuffers; j++) { - if (buflist->mBuffers[j].mNumberChannels > 0) { - cap = MS_SND_CARD_CAP_PLAYBACK; - break; - } - } - - ms_free(buflist); - - err = - AudioDeviceGetPropertyInfo(V[i], 0, TRUE, - kAudioDevicePropertyStreamConfiguration, - &slen, &writable); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioDevicePropertyDeviceName error %ld", err); - continue; - } - buflist = ms_new(slen, 1); - if (buflist == NULL) { - ms_error("alloc error %ld", err); - continue; - } - - err = - AudioDeviceGetProperty(V[i], 0, TRUE, - kAudioDevicePropertyStreamConfiguration, - &slen, buflist); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioDevicePropertyDeviceName error %ld", err); - ms_free(buflist); - continue; - } - - for (j = 0; j < buflist->mNumberBuffers; j++) { - if (buflist->mBuffers[j].mNumberChannels > 0) { - cap |= MS_SND_CARD_CAP_CAPTURE; - break; - } - } - - ms_free(buflist); - - CFStringRef dUID; - dUID = NULL; - slen = sizeof(CFStringRef); - err = - AudioDeviceGetProperty(V[i], 0, false, - kAudioDevicePropertyDeviceUID, &slen, - &dUID); - if (err != kAudioHardwareNoError) { - ms_error("get kAudioHardwarePropertyDevices error %ld", err); - continue; - } - CFStringGetCString(dUID, uidname, 256, - CFStringGetSystemEncoding()); - ms_message("AQ: devname:%s uidname:%s", devname, uidname); - - AudioStreamBasicDescription devicereadFormat; - AudioStreamBasicDescription devicewriteFormat; - slen = sizeof(devicewriteFormat); - err = AudioDeviceGetProperty(V[i], 0, false, - kAudioDevicePropertyStreamFormat, - &slen, &devicewriteFormat); - if (err == kAudioHardwareNoError) { - show_format("output device", &devicewriteFormat); - } - slen = sizeof(devicereadFormat); - err = AudioDeviceGetProperty(V[i], 0, true, - kAudioDevicePropertyStreamFormat, - &slen, &devicereadFormat); - if (err == kAudioHardwareNoError) { - show_format("input device", &devicereadFormat); - } - - MSSndCard *card = aq_card_new(devname, dUID, &devicereadFormat, - &devicewriteFormat, cap); - ms_snd_card_manager_add_card(m, card); - } -} - - -/* - Audio Queue recode callback - */ - -static void readCallback(void *aqData, - AudioQueueRef inAQ, - AudioQueueBufferRef inBuffer, - const AudioTimeStamp * inStartTime, - UInt32 inNumPackets, - const AudioStreamPacketDescription * inPacketDesc) -{ - AQData *d = (AQData *) aqData; - OSStatus err; - mblk_t *rm = NULL; - - UInt32 len = - (inBuffer->mAudioDataByteSize * d->readAudioFormat.mSampleRate / - 1) / d->devicereadFormat.mSampleRate / - d->devicereadFormat.mChannelsPerFrame; - - ms_mutex_lock(&d->mutex); - if (d->read_started == FALSE) { - ms_mutex_unlock(&d->mutex); - return; - } - - rm = allocb(len, 0); - - err = AudioConverterConvertBuffer(d->readAudioConverter, - inBuffer->mAudioDataByteSize, - inBuffer->mAudioData, - &len, rm->b_wptr); - if (err != noErr) { - ms_error("readCallback: AudioConverterConvertBuffer %d", err); - ms_warning("readCallback: inBuffer->mAudioDataByteSize = %d", - inBuffer->mAudioDataByteSize); - ms_warning("readCallback: outlen = %d", len); - ms_warning("readCallback: origlen = %i", - (inBuffer->mAudioDataByteSize * - d->readAudioFormat.mSampleRate / 1) / - d->devicereadFormat.mSampleRate / - d->devicereadFormat.mChannelsPerFrame); - freeb(rm); - } else { - - rm->b_wptr += len; - if (gain_volume_in != 1.0f) - { - int16_t *ptr=(int16_t *)rm->b_rptr; - for (;ptr<(int16_t *)rm->b_wptr;ptr++) - { - *ptr=(int16_t)(((float)(*ptr))*gain_volume_in); - } - } - putq(&d->rq, rm); - } - - err = AudioQueueEnqueueBuffer(d->readQueue, inBuffer, 0, NULL); - if (err != noErr) { - ms_error("readCallback:AudioQueueEnqueueBuffer %d", err); - } - ms_mutex_unlock(&d->mutex); -} - -/* - Audio Queue play callback - */ - -static void writeCallback(void *aqData, - AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) -{ - AQData *d = (AQData *) aqData; - OSStatus err; - - int len = - (d->writeBufferByteSize * d->writeAudioFormat.mSampleRate / 1) / - d->devicewriteFormat.mSampleRate / - d->devicewriteFormat.mChannelsPerFrame; - - ms_mutex_lock(&d->mutex); - if (d->write_started == FALSE) { - ms_mutex_unlock(&d->mutex); - return; - } - if (d->bufferizer->size >= len) { - UInt32 bsize = d->writeBufferByteSize; - uint8_t *pData = ms_malloc(len); - - ms_bufferizer_read(d->bufferizer, pData, len); - err = AudioConverterConvertBuffer(d->writeAudioConverter, - len, - pData, - &bsize, inBuffer->mAudioData); - if (err != noErr) { - ms_error("writeCallback: AudioConverterConvertBuffer %d", err); - } - ms_free(pData); - - if (bsize != d->writeBufferByteSize) - ms_warning("d->writeBufferByteSize = %i len = %i bsize = %i", - d->writeBufferByteSize, len, bsize); - } else { - memset(inBuffer->mAudioData, 0, d->writeBufferByteSize); - } - inBuffer->mAudioDataByteSize = d->writeBufferByteSize; - - if (gain_changed_out == true) - { - AudioQueueSetParameter (d->writeQueue, - kAudioQueueParam_Volume, - gain_volume_out); - gain_changed_out = false; - } - - err = AudioQueueEnqueueBuffer(d->writeQueue, inBuffer, 0, NULL); - if (err != noErr) { - ms_error("AudioQueueEnqueueBuffer %d", err); - } - ms_mutex_unlock(&d->mutex); -} - -void putWriteAQ(void *aqData, int queuenum) -{ - AQData *d = (AQData *) aqData; - OSStatus err; - err = AudioQueueEnqueueBuffer(d->writeQueue, - d->writeBuffers[queuenum], 0, NULL); - if (err != noErr) { - ms_error("AudioQueueEnqueueBuffer %d", err); - } -} - -/* - play buffer setup function - */ - -void setupWrite(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - OSStatus err; - - int bufferIndex; - - for (bufferIndex = 0; bufferIndex < kNumberAudioOutDataBuffers; - ++bufferIndex) { - - err = AudioQueueAllocateBuffer(d->writeQueue, - d->writeBufferByteSize, - &d->writeBuffers[bufferIndex] - ); - if (err != noErr) { - ms_error("setupWrite:AudioQueueAllocateBuffer %d", err); - } - } -} - -/* - recode buffer setup function - */ - -void setupRead(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - OSStatus err; - - // allocate and enqueue buffers - int bufferIndex; - - for (bufferIndex = 0; bufferIndex < kNumberAudioInDataBuffers; - ++bufferIndex) { - - AudioQueueBufferRef buffer; - - err = AudioQueueAllocateBuffer(d->readQueue, - d->readBufferByteSize, &buffer); - if (err != noErr) { - ms_error("setupRead:AudioQueueAllocateBuffer %d", err); - } - - err = AudioQueueEnqueueBuffer(d->readQueue, buffer, 0, NULL); - if (err != noErr) { - ms_error("AudioQueueEnqueueBuffer %d", err); - } - } -} - - -static void aq_start_r(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - if (d->read_started == FALSE) { - OSStatus aqresult; - - d->readAudioFormat.mSampleRate = d->rate; - d->readAudioFormat.mFormatID = kAudioFormatLinearPCM; - d->readAudioFormat.mFormatFlags = - kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; - d->readAudioFormat.mFramesPerPacket = 1; - d->readAudioFormat.mChannelsPerFrame = 1; - d->readAudioFormat.mBitsPerChannel = d->bits; - d->readAudioFormat.mBytesPerPacket = d->bits / 8; - d->readAudioFormat.mBytesPerFrame = d->bits / 8; - - //show_format("input device", &d->devicereadFormat); - //show_format("data from input filter", &d->readAudioFormat); - - memcpy(&d->devicereadFormat, &d->readAudioFormat, - sizeof(d->readAudioFormat)); - d->readBufferByteSize = - kSecondsPerBuffer * d->devicereadFormat.mSampleRate * - (d->devicereadFormat.mBitsPerChannel / 8) * - d->devicereadFormat.mChannelsPerFrame; - - aqresult = AudioConverterNew(&d->devicereadFormat, - &d->readAudioFormat, - &d->readAudioConverter); - if (aqresult != noErr) { - ms_error("d->readAudioConverter = %d", aqresult); - d->readAudioConverter = NULL; - } - - aqresult = AudioQueueNewInput(&d->devicereadFormat, readCallback, d, // userData - NULL, // run loop - NULL, // run loop mode - 0, // flags - &d->readQueue); - if (aqresult != noErr) { - ms_error("AudioQueueNewInput = %d", aqresult); - } - - char uidname[256]; - CFStringGetCString(d->uidname, uidname, 256, - CFStringGetSystemEncoding()); - ms_message("AQ: using uidname:%s", uidname); - aqresult = - AudioQueueSetProperty(d->readQueue, - kAudioQueueProperty_CurrentDevice, - &d->uidname, sizeof(CFStringRef)); - if (aqresult != noErr) { - ms_error - ("AudioQueueSetProperty on kAudioQueueProperty_CurrentDevice %d", - aqresult); - } - - setupRead(f); - AudioQueueStart(d->readQueue, NULL // start time. NULL means ASAP. - ); - if (aqresult != noErr) { - ms_error("AudioQueueStart %d", aqresult); - } - d->read_started = TRUE; - } -} - -static void aq_stop_r(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - - if (d->read_started == TRUE) { - ms_mutex_lock(&d->mutex); - d->read_started = FALSE; /* avoid a deadlock related to buffer conversion in callback */ - ms_mutex_unlock(&d->mutex); - AudioConverterDispose(d->readAudioConverter); - AudioQueueStop(d->readQueue, true); - AudioQueueDispose(d->readQueue, true); - } -} - -static void aq_start_w(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - if (d->write_started == FALSE) { - OSStatus aqresult; - - d->writeAudioFormat.mSampleRate = d->rate; - d->writeAudioFormat.mFormatID = kAudioFormatLinearPCM; - d->writeAudioFormat.mFormatFlags = - kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; - d->writeAudioFormat.mFramesPerPacket = 1; - d->writeAudioFormat.mChannelsPerFrame = 1; - d->writeAudioFormat.mBitsPerChannel = d->bits; - d->writeAudioFormat.mBytesPerPacket = d->bits / 8; - d->writeAudioFormat.mBytesPerFrame = d->bits / 8; - - //show_format("data provided to output filter", &d->writeAudioFormat); - //show_format("output device", &d->devicewriteFormat); - - memcpy(&d->devicewriteFormat, &d->writeAudioFormat, - sizeof(d->writeAudioFormat)); - d->writeBufferByteSize = - kSecondsPerBuffer * d->devicewriteFormat.mSampleRate * - (d->devicewriteFormat.mBitsPerChannel / 8) * - d->devicewriteFormat.mChannelsPerFrame; - - aqresult = AudioConverterNew(&d->writeAudioFormat, - &d->devicewriteFormat, - &d->writeAudioConverter); - if (aqresult != noErr) { - ms_error("d->writeAudioConverter = %d", aqresult); - d->writeAudioConverter = NULL; - } - // create the playback audio queue object - aqresult = AudioQueueNewOutput(&d->devicewriteFormat, writeCallback, d, NULL, /*CFRunLoopGetCurrent () */ - NULL, /*kCFRunLoopCommonModes */ - 0, // run loop flags - &d->writeQueue); - if (aqresult != noErr) { - ms_error("AudioQueueNewOutput = %d", aqresult); - } - - AudioQueueSetParameter (d->writeQueue, - kAudioQueueParam_Volume, - gain_volume_out); - - char uidname[256]; - CFStringGetCString(d->uidname, uidname, 256, - CFStringGetSystemEncoding()); - ms_message("AQ: using uidname:%s", uidname); - aqresult = - AudioQueueSetProperty(d->writeQueue, - kAudioQueueProperty_CurrentDevice, - &d->uidname, sizeof(CFStringRef)); - if (aqresult != noErr) { - ms_error - ("AudioQueueSetProperty on kAudioQueueProperty_CurrentDevice %d", - aqresult); - } - setupWrite(f); - d->curWriteBuffer = 0; - } -} - -static void aq_stop_w(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - if (d->write_started == TRUE) { - ms_mutex_lock(&d->mutex); - d->write_started = FALSE; /* avoid a deadlock related to buffer conversion in callback */ - ms_mutex_unlock(&d->mutex); - AudioConverterDispose(d->writeAudioConverter); - AudioQueueStop(d->writeQueue, true); - - AudioQueueDispose(d->writeQueue, true); - } -} - -static mblk_t *aq_get(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - mblk_t *m; - ms_mutex_lock(&d->mutex); - m = getq(&d->rq); - ms_mutex_unlock(&d->mutex); - return m; -} - -static void aq_put(MSFilter * f, mblk_t * m) -{ - AQData *d = (AQData *) f->data; - ms_mutex_lock(&d->mutex); - ms_bufferizer_put(d->bufferizer, m); - ms_mutex_unlock(&d->mutex); - - int len = - (d->writeBufferByteSize * d->writeAudioFormat.mSampleRate / 1) / - d->devicewriteFormat.mSampleRate / - d->devicewriteFormat.mChannelsPerFrame; - if (d->write_started == FALSE && d->bufferizer->size >= len) { - AudioQueueBufferRef curbuf = d->writeBuffers[d->curWriteBuffer]; - OSStatus err; - UInt32 bsize = d->writeBufferByteSize; - uint8_t *pData = ms_malloc(len); - - ms_bufferizer_read(d->bufferizer, pData, len); - err = AudioConverterConvertBuffer(d->writeAudioConverter, - len, - pData, - &bsize, curbuf->mAudioData); - if (err != noErr) { - ms_error("writeCallback: AudioConverterConvertBuffer %d", err); - } - ms_free(pData); - - if (bsize != d->writeBufferByteSize) - ms_warning("d->writeBufferByteSize = %i len = %i bsize = %i", - d->writeBufferByteSize, len, bsize); - - curbuf->mAudioDataByteSize = d->writeBufferByteSize; - putWriteAQ(d, d->curWriteBuffer); - ++d->curWriteBuffer; - } - if (d->write_started == FALSE - && d->curWriteBuffer == kNumberAudioOutDataBuffers - 1) { - OSStatus err; - err = AudioQueueStart(d->writeQueue, NULL // start time. NULL means ASAP. - ); - if (err != noErr) { - ms_error("AudioQueueStart %d", err); - } - d->write_started = TRUE; - } -} - -static void aq_init(MSFilter * f) -{ - AQData *d = ms_new(AQData, 1); - d->bits = 16; - d->rate = 8000; - d->stereo = FALSE; - - d->read_started = FALSE; - d->write_started = FALSE; - qinit(&d->rq); - d->bufferizer = ms_bufferizer_new(); - ms_mutex_init(&d->mutex, NULL); - f->data = d; -} - -static void aq_uninit(MSFilter * f) -{ - AQData *d = (AQData *) f->data; - flushq(&d->rq, 0); - ms_bufferizer_destroy(d->bufferizer); - ms_mutex_destroy(&d->mutex); - if (d->uidname != NULL) - CFRelease(d->uidname); - ms_free(d); -} - -static void aq_read_preprocess(MSFilter * f) -{ - aq_start_r(f); -} - -static void aq_read_postprocess(MSFilter * f) -{ - aq_stop_r(f); -} - -static void aq_read_process(MSFilter * f) -{ - mblk_t *m; - while ((m = aq_get(f)) != NULL) { - ms_queue_put(f->outputs[0], m); - } -} - -static void aq_write_preprocess(MSFilter * f) -{ - aq_start_w(f); -} - -static void aq_write_postprocess(MSFilter * f) -{ - aq_stop_w(f); -} - -static void aq_write_process(MSFilter * f) -{ - mblk_t *m; - while ((m = ms_queue_get(f->inputs[0])) != NULL) { - aq_put(f, m); - } -} - -static int set_rate(MSFilter * f, void *arg) -{ - AQData *d = (AQData *) f->data; - d->rate = *((int *) arg); - return 0; -} - -static int read_get_rate(MSFilter * f, void *arg) -{ - AQData *d = (AQData *) f->data; - *((int *) arg) = d->rate; - return 0; -} - -static int write_get_rate(MSFilter * f, void *arg) -{ - AQData *d = (AQData *) f->data; - *((int *) arg) = d->rate; - return 0; -} - -/* -static int set_nchannels(MSFilter *f, void *arg){ - AQData *d=(AQData*)f->data; - d->stereo=(*((int*)arg)==2); - return 0; -} -*/ - -static MSFilterMethod aq_read_methods[] = { - {MS_FILTER_SET_SAMPLE_RATE, set_rate}, - {MS_FILTER_GET_SAMPLE_RATE, read_get_rate}, -/* not support yet - { MS_FILTER_SET_NCHANNELS , set_nchannels }, -*/ - {0, NULL} -}; - -MSFilterDesc aq_read_desc = { - .id = MS_AQ_READ_ID, - .name = "MSAQRead", - .text = N_("Sound capture filter for MacOS X Audio Queue Service"), - .category = MS_FILTER_OTHER, - .ninputs = 0, - .noutputs = 1, - .init = aq_init, - .preprocess = aq_read_preprocess, - .process = aq_read_process, - .postprocess = aq_read_postprocess, - .uninit = aq_uninit, - .methods = aq_read_methods -}; - -static MSFilterMethod aq_write_methods[] = { - {MS_FILTER_SET_SAMPLE_RATE, set_rate}, - {MS_FILTER_GET_SAMPLE_RATE, write_get_rate}, -/* not support yet - { MS_FILTER_SET_NCHANNELS , set_nchannels }, -*/ - {0, NULL} -}; - -MSFilterDesc aq_write_desc = { - .id = MS_AQ_WRITE_ID, - .name = "MSAQWrite", - .text = N_("Sound playback filter for MacOS X Audio Queue Service"), - .category = MS_FILTER_OTHER, - .ninputs = 1, - .noutputs = 0, - .init = aq_init, - .preprocess = aq_write_preprocess, - .process = aq_write_process, - .postprocess = aq_write_postprocess, - .uninit = aq_uninit, - .methods = aq_write_methods -}; - -MSFilter *ms_aq_read_new(MSSndCard * card) -{ - MSFilter *f = ms_filter_new_from_desc(&aq_read_desc); - AqSndDsCard *wc = (AqSndDsCard *) card->data; - AQData *d = (AQData *) f->data; - d->uidname = CFStringCreateCopy(NULL, wc->uidname); - memcpy(&d->devicereadFormat, &wc->devicereadFormat, - sizeof(AudioStreamBasicDescription)); - memcpy(&d->devicewriteFormat, &wc->devicewriteFormat, - sizeof(AudioStreamBasicDescription)); - return f; -} - - -MSFilter *ms_aq_write_new(MSSndCard * card) -{ - MSFilter *f = ms_filter_new_from_desc(&aq_write_desc); - AqSndDsCard *wc = (AqSndDsCard *) card->data; - AQData *d = (AQData *) f->data; - d->uidname = CFStringCreateCopy(NULL, wc->uidname); - memcpy(&d->devicereadFormat, &wc->devicereadFormat, - sizeof(AudioStreamBasicDescription)); - memcpy(&d->devicewriteFormat, &wc->devicewriteFormat, - sizeof(AudioStreamBasicDescription)); - return f; -} - -MS_FILTER_DESC_EXPORT(aq_read_desc) -MS_FILTER_DESC_EXPORT(aq_write_desc) diff --git a/linphone/mediastreamer2/src/arts.c b/linphone/mediastreamer2/src/arts.c deleted file mode 100644 index e6fcec820..000000000 --- a/linphone/mediastreamer2/src/arts.c +++ /dev/null @@ -1,207 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" - -extern MSSndCardDesc arts_card_desc; - -static int arts_users=0; -static void check_arts_init(){ - if (arts_users==0){ - arts_init(); - } - arts_users++; -} - -static void check_arts_uninit(){ - arts_users--; - if (arts_users==0){ - arts_free(); - } -} - - -typedef struct ArtsState{ - int rate; - int nchannels; - int bits; - int bsize; - arts_stream_t stream; - mblk_t *msg; -} ArtsState; - -static void reader_init(MSFilter *f){ - ArtsState *s=ms_new(ArtsState,1); - s->rate=8000; - s->nchannels=1; - s->bits=16; - s->bsize=512; - s->stream=NULL; - s->msg=NULL; - f->data=s; -} - -static void reader_uninit(MSFilter *f){ - ArtsState *s=(ArtsState *)f->data; - ms_free(s); -} - -static void configure(arts_stream_t stream){ - int ret; - int latency=50; - ret=arts_stream_set(stream,ARTS_P_BUFFER_TIME,latency); - if (ret!=latency) ms_message("Arts set latency to %i",ret); - arts_stream_set(stream,ARTS_P_BLOCKING,0); -} - -static void reader_preprocess(MSFilter *f){ - ArtsState *s=(ArtsState *)f->data; - check_arts_init(); - s->stream=arts_record_stream(s->rate,s->bits,s->nchannels, "linphone"); - s->bsize=512*s->rate/8000; - if (s->stream!=NULL) configure(s->stream); -} - -static void reader_process(MSFilter *f){ - int err; - ArtsState *s=(ArtsState *)f->data; - if (s->stream!=NULL){ - mblk_t *om=s->msg; - if (om==NULL) om=allocb(s->bsize,0); - err=arts_read(s->stream,om->b_wptr,s->bsize); - if (err>0){ - om->b_wptr+=err; - ms_queue_put(f->outputs[0],om); - om=NULL; - } - s->msg=om; - } -} - -static void reader_postprocess(MSFilter *f){ - ArtsState *s=(ArtsState *)f->data; - if (s->stream) arts_close_stream(s->stream); - s->stream=NULL; - check_arts_uninit(); -} - -static void writer_preprocess(MSFilter *f){ - ArtsState *s=(ArtsState *)f->data; - check_arts_init(); - s->stream=arts_play_stream(s->rate,s->bits,s->nchannels, "linphone"); - s->bsize=512*s->rate/8000; - if (s->stream!=NULL) configure(s->stream); -} - -static void writer_process(MSFilter *f){ - ArtsState *s=(ArtsState *)f->data; - int err; - mblk_t *im; - - if (s->stream==NULL){ - ms_queue_flush(f->inputs[0]); - return; - } - while ((im=ms_queue_get(f->inputs[0]))!=NULL){ - err=arts_write(s->stream,im->b_rptr,im->b_wptr-im->b_rptr); - if (err<0){ - ms_warning("arts_write error"); - } - freemsg(im); - } -} - -static int reader_set_sr(MSFilter *f, void *arg){ - ArtsState *s=(ArtsState *)f->data; - s->rate=*(int*)arg; - return 0; -} - -static int reader_set_nchannels(MSFilter *f, void *arg){ - ArtsState *s=(ArtsState *)f->data; - s->nchannels=*(int*)arg; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , reader_set_sr }, - { MS_FILTER_SET_NCHANNELS , reader_set_nchannels }, - { 0 , NULL } -}; - -MSFilterDesc ms_arts_read_desc={ - .id=MS_ARTS_READ_ID, - .name="MSArtsRead", - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .init=reader_init, - .preprocess=reader_preprocess, - .process=reader_process, - .postprocess=reader_postprocess, - .uninit=reader_uninit, - .methods=methods -}; - -MSFilterDesc ms_arts_write_desc={ - .id=MS_ARTS_WRITE_ID, - .name="MSArtsWrite", - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .init=reader_init, /*the read and the write method do the same*/ - .preprocess=writer_preprocess, - .process=writer_process, - .postprocess=reader_postprocess,/*the read and the write method do the same*/ - .uninit=reader_uninit,/*the read and the write method do the same*/ - .methods=methods /*the read and the write method do the same*/ -}; - -static void arts_card_detect(MSSndCardManager *m){ - if (arts_init()==0){ - MSSndCard *card=ms_snd_card_new(&arts_card_desc); - card->name=ms_strdup("arts driver"); - ms_snd_card_manager_add_card(ms_snd_card_manager_get(),card); - arts_free(); - } -} - -static MSFilter * arts_card_create_reader(MSSndCard *card){ - return ms_filter_new(MS_ARTS_READ_ID); -} - -static MSFilter * arts_card_create_writer(MSSndCard *card){ - return ms_filter_new(MS_ARTS_WRITE_ID); -} - -MSSndCardDesc arts_card_desc={ - .driver_type="aRts", - .detect=arts_card_detect, - .set_control=NULL, - .get_control=NULL, - .create_reader=arts_card_create_reader, - .create_writer=arts_card_create_writer, - .duplicate=NULL -}; - -MS_FILTER_DESC_EXPORT(ms_arts_read_desc) -MS_FILTER_DESC_EXPORT(ms_arts_write_desc) diff --git a/linphone/mediastreamer2/src/audiostream.c b/linphone/mediastreamer2/src/audiostream.c deleted file mode 100644 index ac9222d60..000000000 --- a/linphone/mediastreamer2/src/audiostream.c +++ /dev/null @@ -1,604 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/mediastream.h" - -#include "mediastreamer2/dtmfgen.h" -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msrtp.h" -#include "mediastreamer2/msfileplayer.h" -#include "mediastreamer2/msfilerec.h" -#include "mediastreamer2/msvolume.h" -#include "mediastreamer2/msequalizer.h" -#include "mediastreamer2/msspeexec.h" - -#ifdef INET6 - #include -#ifndef WIN32 - #include - #include -#endif -#endif - - -#define MAX_RTP_SIZE 1500 - - -/* this code is not part of the library itself, it is part of the mediastream program */ -void audio_stream_free(AudioStream *stream) -{ - if (stream->session!=NULL) rtp_session_destroy(stream->session); - if (stream->rtpsend!=NULL) ms_filter_destroy(stream->rtpsend); - if (stream->rtprecv!=NULL) ms_filter_destroy(stream->rtprecv); - if (stream->soundread!=NULL) ms_filter_destroy(stream->soundread); - if (stream->soundwrite!=NULL) ms_filter_destroy(stream->soundwrite); - if (stream->encoder!=NULL) ms_filter_destroy(stream->encoder); - if (stream->decoder!=NULL) ms_filter_destroy(stream->decoder); - if (stream->dtmfgen!=NULL) ms_filter_destroy(stream->dtmfgen); - if (stream->ec!=NULL) ms_filter_destroy(stream->ec); - if (stream->volrecv!=NULL) ms_filter_destroy(stream->volrecv); - if (stream->volsend!=NULL) ms_filter_destroy(stream->volsend); - if (stream->equalizer!=NULL) ms_filter_destroy(stream->equalizer); - if (stream->ticker!=NULL) ms_ticker_destroy(stream->ticker); - if (stream->read_resampler!=NULL) ms_filter_destroy(stream->read_resampler); - if (stream->write_resampler!=NULL) ms_filter_destroy(stream->write_resampler); - ms_free(stream); -} - -static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; - -static void on_dtmf_received(RtpSession *s, int dtmf, void * user_data) -{ - AudioStream *stream=(AudioStream*)user_data; - if (dtmf>15){ - ms_warning("Unsupported telephone-event type."); - return; - } - ms_message("Receiving dtmf %c.",dtmf_tab[dtmf]); - if (stream->dtmfgen!=NULL && stream->play_dtmfs){ - ms_filter_call_method(stream->dtmfgen,MS_DTMF_GEN_PUT,&dtmf_tab[dtmf]); - } -} - -#if 0 - -static void on_timestamp_jump(RtpSession *s,uint32_t* ts, void * user_data) -{ - ms_warning("The remote sip-phone has send data with a future timestamp: %u," - "resynchronising session.",*ts); - rtp_session_reset(s); -} - -#endif - - -bool_t ms_is_ipv6(const char *remote){ - bool_t ret=FALSE; -#ifdef INET6 - struct addrinfo hints, *res0; - - int err; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - err = getaddrinfo(remote,"8000", &hints, &res0); - if (err!=0) { - ms_warning ("get_local_addr_for: %s", gai_strerror(err)); - return FALSE; - } - ret=(res0->ai_addr->sa_family==AF_INET6); - freeaddrinfo(res0); -#endif - return ret; -} - -static void audio_stream_configure_resampler(MSFilter *resampler,MSFilter *from,MSFilter *to) { - int from_rate=0, to_rate=0; - ms_filter_call_method(from,MS_FILTER_GET_SAMPLE_RATE,&from_rate); - ms_filter_call_method(to,MS_FILTER_GET_SAMPLE_RATE,&to_rate); - ms_filter_call_method(resampler,MS_FILTER_SET_SAMPLE_RATE,&from_rate); - ms_filter_call_method(resampler,MS_FILTER_SET_OUTPUT_SAMPLE_RATE,&to_rate); - ms_debug("configuring from rate[%i] to rate [%i]",from_rate,to_rate); -} - -RtpSession * create_duplex_rtpsession( int locport, bool_t ipv6){ - RtpSession *rtpr; - rtpr=rtp_session_new(RTP_SESSION_SENDRECV); - rtp_session_set_recv_buf_size(rtpr,MAX_RTP_SIZE); - rtp_session_set_scheduling_mode(rtpr,0); - rtp_session_set_blocking_mode(rtpr,0); - rtp_session_enable_adaptive_jitter_compensation(rtpr,TRUE); - rtp_session_set_symmetric_rtp(rtpr,TRUE); - rtp_session_set_local_addr(rtpr,ipv6 ? "::" : "0.0.0.0",locport); - rtp_session_signal_connect(rtpr,"timestamp_jump",(RtpCallback)rtp_session_resync,(long)NULL); - rtp_session_signal_connect(rtpr,"ssrc_changed",(RtpCallback)rtp_session_resync,(long)NULL); - return rtpr; -} - -#if defined(_WIN32_WCE) -time_t -ms_time (time_t *t) -{ - DWORD timemillis = GetTickCount(); - if (timemillis>0) - { - if (t!=NULL) - *t = timemillis/1000; - } - return timemillis/1000; -} -#endif - -bool_t audio_stream_alive(AudioStream * stream, int timeout){ - RtpSession *session=stream->session; - const rtp_stats_t *stats=rtp_session_get_stats(session); - if (stats->recv!=0){ - if (stats->recv!=stream->last_packet_count){ - stream->last_packet_count=stats->recv; - stream->last_packet_time=ms_time(NULL); - }else{ - if (ms_time(NULL)-stream->last_packet_time>timeout){ - /* more than timeout seconds of inactivity*/ - return FALSE; - } - } - } - return TRUE; -} - -/*this function must be called from the MSTicker thread: -it replaces one filter by another one. -This is a dirty hack that works anyway. -It would be interesting to have something that does the job -simplier within the MSTicker api -*/ -void audio_stream_change_decoder(AudioStream *stream, int payload){ - RtpSession *session=stream->session; - RtpProfile *prof=rtp_session_get_profile(session); - PayloadType *pt=rtp_profile_get_payload(prof,payload); - if (pt!=NULL){ - MSFilter *dec=ms_filter_create_decoder(pt->mime_type); - if (dec!=NULL){ - ms_filter_unlink(stream->rtprecv, 0, stream->decoder, 0); - ms_filter_unlink(stream->decoder,0,stream->dtmfgen,0); - ms_filter_postprocess(stream->decoder); - ms_filter_destroy(stream->decoder); - stream->decoder=dec; - if (pt->recv_fmtp!=NULL) - ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)pt->recv_fmtp); - ms_filter_link (stream->rtprecv, 0, stream->decoder, 0); - ms_filter_link (stream->decoder,0 , stream->dtmfgen, 0); - ms_filter_preprocess(stream->decoder,stream->ticker); - - }else{ - ms_warning("No decoder found for %s",pt->mime_type); - } - }else{ - ms_warning("No payload defined with number %i",payload); - } -} - -static void payload_type_changed(RtpSession *session, unsigned long data){ - AudioStream *stream=(AudioStream*)data; - int pt=rtp_session_get_recv_payload_type(stream->session); - audio_stream_change_decoder(stream,pt); -} - - -int audio_stream_start_full(AudioStream *stream, RtpProfile *profile, const char *remip,int remport, - int rem_rtcp_port, int payload,int jitt_comp, const char *infile, const char *outfile, - MSSndCard *playcard, MSSndCard *captcard, bool_t use_ec) -{ - RtpSession *rtps=stream->session; - PayloadType *pt; - int tmp; - MSConnectionHelper h; - - rtp_session_set_profile(rtps,profile); - if (remport>0) rtp_session_set_remote_addr_full(rtps,remip,remport,rem_rtcp_port); - rtp_session_set_payload_type(rtps,payload); - rtp_session_set_jitter_compensation(rtps,jitt_comp); - - if (remport>0) - ms_filter_call_method(stream->rtpsend,MS_RTP_SEND_SET_SESSION,rtps); - stream->rtprecv=ms_filter_new(MS_RTP_RECV_ID); - ms_filter_call_method(stream->rtprecv,MS_RTP_RECV_SET_SESSION,rtps); - stream->session=rtps; - - stream->dtmfgen=ms_filter_new(MS_DTMF_GEN_ID); - rtp_session_signal_connect(rtps,"telephone-event",(RtpCallback)on_dtmf_received,(unsigned long)stream); - rtp_session_signal_connect(rtps,"payload_type_changed",(RtpCallback)payload_type_changed,(unsigned long)stream); - - /* creates the local part */ - if (captcard!=NULL) stream->soundread=ms_snd_card_create_reader(captcard); - else { - stream->soundread=ms_filter_new(MS_FILE_PLAYER_ID); - stream->read_resampler=ms_filter_new(MS_RESAMPLE_ID); - if (infile!=NULL) audio_stream_play(stream,infile); - } - if (playcard!=NULL) stream->soundwrite=ms_snd_card_create_writer(playcard); - else { - stream->soundwrite=ms_filter_new(MS_FILE_REC_ID); - if (outfile!=NULL) audio_stream_record(stream,outfile); - } - - /* creates the couple of encoder/decoder */ - pt=rtp_profile_get_payload(profile,payload); - if (pt==NULL){ - ms_error("audiostream.c: undefined payload type."); - return -1; - } - stream->encoder=ms_filter_create_encoder(pt->mime_type); - stream->decoder=ms_filter_create_decoder(pt->mime_type); - if ((stream->encoder==NULL) || (stream->decoder==NULL)){ - /* big problem: we have not a registered codec for this payload...*/ - ms_error("mediastream.c: No decoder available for payload %i.",payload); - return -1; - } - - if (use_ec) { - stream->ec=ms_filter_new(MS_SPEEX_EC_ID); - ms_filter_call_method(stream->ec,MS_FILTER_SET_SAMPLE_RATE,&pt->clock_rate); - if (stream->ec_tail_len!=0) - ms_filter_call_method(stream->ec,MS_SPEEX_EC_SET_TAIL_LENGTH,&stream->ec_tail_len); - if (stream->ec_delay!=0) - ms_filter_call_method(stream->ec,MS_SPEEX_EC_SET_DELAY,&stream->ec_delay); - if (stream->ec_framesize!=0) - ms_filter_call_method(stream->ec,MS_SPEEX_EC_SET_FRAME_SIZE,&stream->ec_framesize); - } - - if (stream->el_type!=ELInactive || stream->use_gc || stream->use_ng){ - stream->volsend=ms_filter_new(MS_VOLUME_ID); - stream->volrecv=ms_filter_new(MS_VOLUME_ID); - if (stream->el_type!=ELInactive){ - if (stream->el_type==ELControlSpeaker) - ms_filter_call_method(stream->volrecv,MS_VOLUME_SET_PEER,stream->volsend); - else ms_filter_call_method(stream->volsend,MS_VOLUME_SET_PEER,stream->volrecv); - } - if (stream->use_ng){ - int tmp=1; - ms_filter_call_method(stream->volsend,MS_VOLUME_ENABLE_NOISE_GATE,&tmp); - } - } - - if (stream->use_agc){ - int tmp=1; - if (stream->volsend==NULL) - stream->volsend=ms_filter_new(MS_VOLUME_ID); - ms_filter_call_method(stream->volsend,MS_VOLUME_ENABLE_AGC,&tmp); - } - - /* give the sound filters some properties */ - if (ms_filter_call_method(stream->soundread,MS_FILTER_SET_SAMPLE_RATE,&pt->clock_rate) != 0) { - /* need to add resampler*/ - if (stream->read_resampler == NULL) stream->read_resampler=ms_filter_new(MS_RESAMPLE_ID); - } - - if (ms_filter_call_method(stream->soundwrite,MS_FILTER_SET_SAMPLE_RATE,&pt->clock_rate) != 0) { - /* need to add resampler*/ - if (stream->write_resampler == NULL) stream->write_resampler=ms_filter_new(MS_RESAMPLE_ID); - } - - - tmp=1; - ms_filter_call_method(stream->soundwrite,MS_FILTER_SET_NCHANNELS, &tmp); - - /* give the encoder/decoder some parameters*/ - ms_filter_call_method(stream->encoder,MS_FILTER_SET_SAMPLE_RATE,&pt->clock_rate); - ms_message("Payload's bitrate is %i",pt->normal_bitrate); - if (pt->normal_bitrate>0){ - ms_message("Setting audio encoder network bitrate to %i",pt->normal_bitrate); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_BITRATE,&pt->normal_bitrate); - } - ms_filter_call_method(stream->decoder,MS_FILTER_SET_SAMPLE_RATE,&pt->clock_rate); - - if (pt->send_fmtp!=NULL) ms_filter_call_method(stream->encoder,MS_FILTER_ADD_FMTP, (void*)pt->send_fmtp); - if (pt->recv_fmtp!=NULL) ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)pt->recv_fmtp); - - /*create the equalizer*/ - stream->equalizer=ms_filter_new(MS_EQUALIZER_ID); - tmp=stream->eq_active; - ms_filter_call_method(stream->equalizer,MS_EQUALIZER_SET_ACTIVE,&tmp); - /*configure resampler if needed*/ - if (stream->read_resampler){ - audio_stream_configure_resampler(stream->read_resampler,stream->soundread,stream->rtpsend); - } - - if (stream->write_resampler){ - audio_stream_configure_resampler(stream->write_resampler,stream->rtprecv,stream->soundwrite); - } - /* and then connect all */ - /* tip: draw yourself the picture if you don't understand */ - - /*sending graph*/ - ms_connection_helper_start(&h); - ms_connection_helper_link(&h,stream->soundread,-1,0); - if (stream->read_resampler) - ms_connection_helper_link(&h,stream->read_resampler,0,0); - if (stream->ec) - ms_connection_helper_link(&h,stream->ec,1,1); - if (stream->volsend) - ms_connection_helper_link(&h,stream->volsend,0,0); - ms_connection_helper_link(&h,stream->encoder,0,0); - ms_connection_helper_link(&h,stream->rtpsend,0,-1); - - /*receiving graph*/ - ms_connection_helper_start(&h); - ms_connection_helper_link(&h,stream->rtprecv,-1,0); - ms_connection_helper_link(&h,stream->decoder,0,0); - ms_connection_helper_link(&h,stream->dtmfgen,0,0); - if (stream->equalizer) - ms_connection_helper_link(&h,stream->equalizer,0,0); - if (stream->volrecv) - ms_connection_helper_link(&h,stream->volrecv,0,0); - if (stream->ec) - ms_connection_helper_link(&h,stream->ec,0,0); - if (stream->write_resampler) - ms_connection_helper_link(&h,stream->write_resampler,0,0); - ms_connection_helper_link(&h,stream->soundwrite,0,-1); - - /* create ticker */ - stream->ticker=ms_ticker_new(); - ms_ticker_set_name(stream->ticker,"Audio MSTicker"); - ms_ticker_attach(stream->ticker,stream->soundread); - ms_ticker_attach(stream->ticker,stream->rtprecv); - - return 0; -} - - -int audio_stream_start_with_files(AudioStream *stream, RtpProfile *prof,const char *remip, int remport, - int rem_rtcp_port, int pt,int jitt_comp, const char *infile, const char * outfile) -{ - return audio_stream_start_full(stream,prof,remip,remport,rem_rtcp_port,pt,jitt_comp,infile,outfile,NULL,NULL,FALSE); -} - -AudioStream * audio_stream_start(RtpProfile *prof,int locport,const char *remip,int remport,int profile,int jitt_comp,bool_t use_ec) -{ - MSSndCard *sndcard_playback; - MSSndCard *sndcard_capture; - AudioStream *stream; - sndcard_capture=ms_snd_card_manager_get_default_capture_card(ms_snd_card_manager_get()); - sndcard_playback=ms_snd_card_manager_get_default_playback_card(ms_snd_card_manager_get()); - if (sndcard_capture==NULL || sndcard_playback==NULL) - return NULL; - stream=audio_stream_new(locport, ms_is_ipv6(remip)); - if (audio_stream_start_full(stream,prof,remip,remport,remport+1,profile,jitt_comp,NULL,NULL,sndcard_playback,sndcard_capture,use_ec)==0) return stream; - audio_stream_free(stream); - return NULL; -} - -AudioStream *audio_stream_start_with_sndcards(RtpProfile *prof,int locport,const char *remip,int remport,int profile,int jitt_comp,MSSndCard *playcard, MSSndCard *captcard, bool_t use_ec) -{ - AudioStream *stream; - if (playcard==NULL) { - ms_error("No playback card."); - return NULL; - } - if (captcard==NULL) { - ms_error("No capture card."); - return NULL; - } - stream=audio_stream_new(locport, ms_is_ipv6(remip)); - if (audio_stream_start_full(stream,prof,remip,remport,remport+1,profile,jitt_comp,NULL,NULL,playcard,captcard,use_ec)==0) return stream; - audio_stream_free(stream); - return NULL; -} - -void audio_stream_set_rtcp_information(AudioStream *st, const char *cname, const char *tool){ - if (st->session!=NULL){ - rtp_session_set_source_description(st->session,cname,NULL,NULL,NULL,NULL,tool , "This is free software (GPL) !"); - } -} - -void audio_stream_play(AudioStream *st, const char *name){ - if (ms_filter_get_id(st->soundread)==MS_FILE_PLAYER_ID){ - ms_filter_call_method_noarg(st->soundread,MS_FILE_PLAYER_CLOSE); - ms_filter_call_method(st->soundread,MS_FILE_PLAYER_OPEN,(void*)name); - if (st->read_resampler){ - audio_stream_configure_resampler(st,st->soundread,st->rtpsend); - } - ms_filter_call_method_noarg(st->soundread,MS_FILE_PLAYER_START); - }else{ - ms_error("Cannot play file: the stream hasn't been started with" - " audio_stream_start_with_files"); - } -} - -void audio_stream_record(AudioStream *st, const char *name){ - if (ms_filter_get_id(st->soundwrite)==MS_FILE_REC_ID){ - ms_filter_call_method_noarg(st->soundwrite,MS_FILE_REC_CLOSE); - ms_filter_call_method(st->soundwrite,MS_FILE_REC_OPEN,(void*)name); - ms_filter_call_method_noarg(st->soundwrite,MS_FILE_REC_START); - }else{ - ms_error("Cannot record file: the stream hasn't been started with" - " audio_stream_start_with_files"); - } -} - - -AudioStream *audio_stream_new(int locport, bool_t ipv6){ - AudioStream *stream=(AudioStream *)ms_new0(AudioStream,1); - stream->session=create_duplex_rtpsession(locport,ipv6); - stream->rtpsend=ms_filter_new(MS_RTP_SEND_ID); - stream->play_dtmfs=TRUE; - stream->use_gc=FALSE; - stream->use_agc=FALSE; - stream->use_ng=FALSE; - return stream; -} - -void audio_stream_play_received_dtmfs(AudioStream *st, bool_t yesno){ - st->play_dtmfs=yesno; -} - -int audio_stream_start_now(AudioStream *stream, RtpProfile * prof, const char *remip, int remport, int rem_rtcp_port, int payload_type, int jitt_comp, MSSndCard *playcard, MSSndCard *captcard, bool_t use_ec){ - return audio_stream_start_full(stream,prof,remip,remport,rem_rtcp_port, - payload_type,jitt_comp,NULL,NULL,playcard,captcard,use_ec); -} - -void audio_stream_set_relay_session_id(AudioStream *stream, const char *id){ - ms_filter_call_method(stream->rtpsend, MS_RTP_SEND_SET_RELAY_SESSION_ID,(void*)id); -} - -void audio_stream_set_echo_canceller_params(AudioStream *st, int tail_len_ms, int delay_ms, int framesize){ - st->ec_tail_len=tail_len_ms; - st->ec_delay=delay_ms; - st->ec_framesize=framesize; -} - -void audio_stream_enable_echo_limiter(AudioStream *stream, EchoLimiterType type){ - stream->el_type=type; -} - -void audio_stream_enable_gain_control(AudioStream *stream, bool_t val){ - stream->use_gc=val; -} - -void audio_stream_enable_automatic_gain_control(AudioStream *stream, bool_t val){ - stream->use_agc=val; -} - -void audio_stream_enable_noise_gate(AudioStream *stream, bool_t val){ - stream->use_ng=val; -} - -void audio_stream_set_mic_gain(AudioStream *stream, float gain){ - if (stream->volsend){ - ms_filter_call_method(stream->volsend,MS_VOLUME_SET_GAIN,&gain); - }else ms_warning("Could not apply gain: gain control wasn't activated. " - "Use audio_stream_enable_gain_control() before starting the stream."); -} - -void audio_stream_enable_equalizer(AudioStream *stream, bool_t enabled){ - stream->eq_active=enabled; - if (stream->equalizer){ - int tmp=enabled; - ms_filter_call_method(stream->equalizer,MS_EQUALIZER_SET_ACTIVE,&tmp); - } -} - -void audio_stream_equalizer_set_gain(AudioStream *stream, int frequency, float gain, int freq_width){ - if (stream->equalizer){ - MSEqualizerGain d; - d.frequency=frequency; - d.gain=gain; - d.width=freq_width; - ms_filter_call_method(stream->equalizer,MS_EQUALIZER_SET_GAIN,&d); - } -} - -void audio_stream_stop(AudioStream * stream) -{ - if (stream->ticker){ - MSConnectionHelper h; - ms_ticker_detach(stream->ticker,stream->soundread); - ms_ticker_detach(stream->ticker,stream->rtprecv); - - rtp_stats_display(rtp_session_get_stats(stream->session),"Audio session's RTP statistics"); - - /*dismantle the outgoing graph*/ - ms_connection_helper_start(&h); - ms_connection_helper_unlink(&h,stream->soundread,-1,0); - if (stream->read_resampler!=NULL) - ms_connection_helper_unlink(&h,stream->read_resampler,0,0); - if (stream->ec!=NULL) - ms_connection_helper_unlink(&h,stream->ec,1,1); - if (stream->volsend!=NULL) - ms_connection_helper_unlink(&h,stream->volsend,0,0); - ms_connection_helper_unlink(&h,stream->encoder,0,0); - ms_connection_helper_unlink(&h,stream->rtpsend,0,-1); - - /*dismantle the receiving graph*/ - ms_connection_helper_start(&h); - ms_connection_helper_unlink(&h,stream->rtprecv,-1,0); - ms_connection_helper_unlink(&h,stream->decoder,0,0); - ms_connection_helper_unlink(&h,stream->dtmfgen,0,0); - if (stream->equalizer) - ms_connection_helper_unlink(&h,stream->equalizer,0,0); - if (stream->volrecv!=NULL) - ms_connection_helper_unlink(&h,stream->volrecv,0,0); - if (stream->ec!=NULL) - ms_connection_helper_unlink(&h,stream->ec,0,0); - if (stream->write_resampler!=NULL) - ms_connection_helper_unlink(&h,stream->write_resampler,0,0); - ms_connection_helper_unlink(&h,stream->soundwrite,0,-1); - - } - audio_stream_free(stream); -} - -RingStream * ring_start(const char *file, int interval, MSSndCard *sndcard){ - return ring_start_with_cb(file,interval,sndcard,NULL,NULL); -} - -RingStream * ring_start_with_cb(const char *file,int interval,MSSndCard *sndcard, MSFilterNotifyFunc func,void * user_data) -{ - RingStream *stream; - int tmp; - stream=(RingStream *)ms_new0(RingStream,1); - stream->source=ms_filter_new(MS_FILE_PLAYER_ID); - if (ms_filter_call_method(stream->source,MS_FILE_PLAYER_OPEN,(void*)file)<0){ - ms_filter_destroy(stream->source); - ms_free(stream); - return NULL; - } - ms_filter_call_method(stream->source,MS_FILE_PLAYER_LOOP,&interval); - ms_filter_call_method_noarg(stream->source,MS_FILE_PLAYER_START); - if (func!=NULL) - ms_filter_set_notify_callback(stream->source,func,user_data); - stream->sndwrite=ms_snd_card_create_writer(sndcard); - ms_filter_call_method(stream->source,MS_FILTER_GET_SAMPLE_RATE,&tmp); - ms_filter_call_method(stream->sndwrite,MS_FILTER_SET_SAMPLE_RATE,&tmp); - ms_filter_call_method(stream->source,MS_FILTER_GET_NCHANNELS,&tmp); - ms_filter_call_method(stream->sndwrite,MS_FILTER_SET_NCHANNELS,&tmp); - stream->ticker=ms_ticker_new(); - ms_ticker_set_name(stream->ticker,"Audio (ring) MSTicker"); - ms_filter_link(stream->source,0,stream->sndwrite,0); - ms_ticker_attach(stream->ticker,stream->source); - return stream; -} - -void ring_stop(RingStream *stream){ - ms_ticker_detach(stream->ticker,stream->source); - ms_filter_unlink(stream->source,0,stream->sndwrite,0); - ms_ticker_destroy(stream->ticker); - ms_filter_destroy(stream->source); - ms_filter_destroy(stream->sndwrite); - ms_free(stream); -#ifdef _WIN32_WCE - ms_warning("Sleeping a bit after closing the audio device..."); - ms_sleep(1); -#endif -} - - -int audio_stream_send_dtmf(AudioStream *stream, char dtmf) -{ - if (stream->rtpsend) - ms_filter_call_method(stream->rtpsend,MS_RTP_SEND_SEND_DTMF,&dtmf); - if (stream->dtmfgen) - ms_filter_call_method(stream->dtmfgen,MS_DTMF_GEN_PUT,&dtmf); - return 0; -} diff --git a/linphone/mediastreamer2/src/dsptools.c b/linphone/mediastreamer2/src/dsptools.c deleted file mode 100644 index 71ea227a3..000000000 --- a/linphone/mediastreamer2/src/dsptools.c +++ /dev/null @@ -1,386 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2009 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. -*/ - -/* This file contains useful DSP routines from the speex project. -*/ - -/* Copyright (C) 2002-2006 Jean-Marc Valin - File: filters.c - Various analysis/synthesis filters - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - Neither the name of the Xiph.org Foundation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 FOUNDATION 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. -*/ - -#include - -#ifdef HAVE_ALLOCA_H -#include -#else -#if !defined(__APPLE__) -#include -#endif -#endif - -#define ALLOC(var,size,type) var = alloca(sizeof(type)*(size)) - -#if 0 -//#ifdef ARCH_BFIN - -static void filter_mem16(const ms_word16_t *_x, const ms_coef_t *num, const ms_coef_t *den, ms_word16_t *_y, int N, int ord, ms_mem_t *mem) -{ - VARDECL(ms_word32_t *xy2); - VARDECL(ms_word32_t *numden_a); - ms_word32_t *xy; - ms_word16_t *numden; - int i; - - ALLOC(xy2, (N+1), ms_word32_t); - ALLOC(numden_a, (2*ord+2), ms_word32_t); - xy = xy2+1; - numden = (ms_word16_t*) numden_a; - - for (i=0;i=0;--j){ - acc+=num[j]*mem[j]; - mem[j+1]=mem[j]; - } - y[i]=acc; - } -} - -#else - -void ms_fir_mem16(const ms_word16_t *x, const ms_coef_t *num, ms_word16_t *y, int N, int ord, ms_mem_t *mem){ - int i,j; - ms_word16_t xi; - ms_word32_t acc; - int shift=0; /* REVISIT: empiric value...*/ - - for(i=0;i>shift; - for(j=ord-2;j>=0;--j){ - acc+=(((ms_word32_t)num[j])*mem[j])>>shift; - mem[j+1]=mem[j]; - } - y[i]=(ms_word16_t)SATURATE16(acc>>14,32767); - } -} - - -#endif - -#endif - -#endif - -#ifdef MS_FIXED_POINT -static int maximize_range(ms_word16_t *in, ms_word16_t *out, ms_word16_t bound, int len) -{ - int i, shift; - ms_word16_t max_val = 0; - for (i=0;imax_val) - max_val = in[i]; - if (-in[i]>max_val) - max_val = -in[i]; - } - shift=0; - while (max_val <= (bound>>1) && max_val != 0) - { - max_val <<= 1; - shift++; - } - for (i=0;iforward = kiss_fftr_alloc(size,0,NULL,NULL); - table->backward = kiss_fftr_alloc(size,1,NULL,NULL); - table->N = size; - return table; -} - -void ms_fft_destroy(void *table) -{ - struct kiss_config *t = (struct kiss_config *)table; - kiss_fftr_free(t->forward); - kiss_fftr_free(t->backward); - ms_free(table); -} - -#ifdef MS_FIXED_POINT - -void ms_fft(void *table, ms_word16_t *in, ms_word16_t *out) -{ - int shift; - struct kiss_config *t = (struct kiss_config *)table; - shift = maximize_range(in, in, 32000, t->N); - kiss_fftr2(t->forward, in, out); - renorm_range(in, in, shift, t->N); - renorm_range(out, out, shift, t->N); -} - -#else - -void ms_fft(void *table, ms_word16_t *in, ms_word16_t *out) -{ - int i; - float scale; - struct kiss_config *t = (struct kiss_config *)table; - scale = 1./t->N; - kiss_fftr2(t->forward, in, out); - for (i=0;iN;i++) - out[i] *= scale; -} -#endif - -void ms_ifft(void *table, ms_word16_t *in, ms_word16_t *out) -{ - struct kiss_config *t = (struct kiss_config *)table; - kiss_fftri2(t->backward, in, out); -} diff --git a/linphone/mediastreamer2/src/dtmfgen.c b/linphone/mediastreamer2/src/dtmfgen.c deleted file mode 100644 index 74cbeb17e..000000000 --- a/linphone/mediastreamer2/src/dtmfgen.c +++ /dev/null @@ -1,204 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/dtmfgen.h" - - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -struct DtmfGenState{ - int rate; - int dur; - int pos; - float highfreq; - float lowfreq; - char dtmf; -}; - -typedef struct DtmfGenState DtmfGenState; - -static void dtmfgen_init(MSFilter *f){ - DtmfGenState *s=(DtmfGenState *)ms_new(DtmfGenState,1); - s->rate=8000; - s->dur=s->rate/10; - s->pos=0; - s->dtmf=0; - f->data=s; -} - -static void dtmfgen_uninit(MSFilter *f){ - ms_free(f->data); -} - -static int dtmfgen_put(MSFilter *f, void *arg){ - DtmfGenState *s=(DtmfGenState*)f->data; - const char *dtmf=(char*)arg; - s->pos=0; - switch(dtmf[0]){ - case '0': - s->lowfreq=941; - s->highfreq=1336; - break; - case '1': - s->lowfreq=697; - s->highfreq=1209; - break; - case '2': - s->lowfreq=697; - s->highfreq=1336; - break; - case '3': - s->lowfreq=697; - s->highfreq=1477; - break; - case '4': - s->lowfreq=770; - s->highfreq=1209; - break; - case '5': - s->lowfreq=770; - s->highfreq=1336; - break; - case '6': - s->lowfreq=770; - s->highfreq=1477; - break; - case '7': - s->lowfreq=852; - s->highfreq=1209; - break; - case '8': - s->lowfreq=852; - s->highfreq=1336; - break; - case '9': - s->lowfreq=852; - s->highfreq=1477; - break; - case '*': - s->lowfreq=941; - s->highfreq=1209; - break; - case '#': - s->lowfreq=941; - s->highfreq=1477; - break; - case 'A': - s->lowfreq=697; - s->highfreq=1633; - break; - case 'B': - s->lowfreq=770; - s->highfreq=1633; - break; - case 'C': - s->lowfreq=852; - s->highfreq=1633; - break; - case 'D': - s->lowfreq=941; - s->highfreq=1633; - break; - default: - ms_warning("Not a dtmf key."); - return -1; - } - s->lowfreq=s->lowfreq/s->rate; - s->highfreq=s->highfreq/s->rate; - - s->dtmf=dtmf[0]; - return 0; -} - -static int dtmfgen_set_rate(MSFilter *f, void *arg){ - DtmfGenState *s=(DtmfGenState*)f->data; - s->rate=*((int*)arg); - s->dur=s->rate/10; - return 0; -} - -static void dtmfgen_process(MSFilter *f){ - mblk_t *m; - DtmfGenState *s=(DtmfGenState*)f->data; - - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - if (s->dtmf!=0){ - int nsamples=(m->b_wptr-m->b_rptr)/2; - int i; - int16_t *sample=(int16_t*)m->b_rptr; - for (i=0;iposdur;i++,s->pos++){ - sample[i]=(int16_t)(10000.0*sin(2*M_PI*(float)s->pos*s->lowfreq)); - sample[i]+=(int16_t)(10000.0*sin(2*M_PI*(float)s->pos*s->highfreq)); - } - if (s->pos==s->dur){ - s->pos=0; - s->dtmf=0; - } - } - ms_queue_put(f->outputs[0],m); - } -} - -MSFilterMethod dtmfgen_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , dtmfgen_set_rate }, - { MS_DTMF_GEN_PUT , dtmfgen_put }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_dtmf_gen_desc={ - MS_DTMF_GEN_ID, - "MSDtmfGen", - N_("DTMF generator"), - MS_FILTER_OTHER, - NULL, - 1, - 1, - dtmfgen_init, - NULL, - dtmfgen_process, - NULL, - dtmfgen_uninit, - dtmfgen_methods -}; - -#else - -MSFilterDesc ms_dtmf_gen_desc={ - .id=MS_DTMF_GEN_ID, - .name="MSDtmfGen", - .text=N_("DTMF generator"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=1, - .init=dtmfgen_init, - .process=dtmfgen_process, - .uninit=dtmfgen_uninit, - .methods=dtmfgen_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_dtmf_gen_desc) - diff --git a/linphone/mediastreamer2/src/dxfilter.cpp b/linphone/mediastreamer2/src/dxfilter.cpp deleted file mode 100644 index 262d5fe53..000000000 --- a/linphone/mediastreamer2/src/dxfilter.cpp +++ /dev/null @@ -1,884 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef VIDEO_ENABLED - -#if !defined(_WIN32_WCE) //Allready defined for wince -#define UNICODE -#endif - -#include -#include - -#if !defined(_WIN32_WCE) -EXTERN_C const CLSID CLSID_NullRenderer; -#endif -#include "dxfilter.h" - -#pragma warning(disable: 4800) - - -const AMOVIESETUP_PIN psudDXFilterPins[] = -{ { L"Input" // strName - , FALSE // bRendered - , FALSE // bOutput - , FALSE // bZero - , FALSE // bMany - , &CLSID_NULL // clsConnectsToFilter - , L"" // strConnectsToPin - , 0 // nTypes - , NULL // lpTypes - } -, { L"Output" // strName - , FALSE // bRendered - , TRUE // bOutput - , FALSE // bZero - , FALSE // bMany - , &CLSID_NULL // clsConnectsToFilter - , L"" // strConnectsToPin - , 0 // nTypes - , NULL // lpTypes - } -}; - -const AMOVIESETUP_FILTER sudDXFilter = -{ &CLSID_DXFilter // clsID -, L"DXFilter for mediastreamer2" // strName -, MERIT_DO_NOT_USE // dwMerit -, 2 // nPins -, psudDXFilterPins }; // lpPin - - -// Needed for the CreateInstance mechanism -CFactoryTemplate g_Templates[]= -{ - { L"DirectX Filter for mediastreamer2" - , &CLSID_DXFilter - , CDXFilter::CreateInstance - , NULL - , &sudDXFilter } - -}; - -int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]); - - -//////////////////////////////////////////////////////////////////////// -// -// Exported entry points for registration and unregistration -// (in this case they only call through to default implementations). -// -//////////////////////////////////////////////////////////////////////// - -STDAPI DllRegisterServer() -{ - return AMovieDllRegisterServer2(TRUE); -} - -STDAPI DllUnregisterServer() -{ - return AMovieDllRegisterServer2(FALSE); -} - -// -// DllEntryPoint -// -extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); - -BOOL APIENTRY DllMain(HANDLE hModule, - DWORD dwReason, - LPVOID lpReserved) -{ - return DllEntryPoint((HINSTANCE)(hModule), dwReason, lpReserved); -} - -// -// CreateInstance -// -// Provide the way for COM to create a CDXFilter object -// -CUnknown * WINAPI CDXFilter::CreateInstance(LPUNKNOWN punk, HRESULT *phr) -{ - /* ASSERT(phr); */ - - // assuming we don't want to modify the data - CDXFilter *pNewObject = new CDXFilter(punk, phr, FALSE); - - if(pNewObject == NULL) { - if (phr) - *phr = E_OUTOFMEMORY; - } - - return pNewObject; - -} // CreateInstance - - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -CDXFilter::CDXFilter( IUnknown * pOuter, HRESULT * phr, BOOL ModifiesData ) - : CTransInPlaceFilter( TEXT("DXFilter"), (IUnknown*) pOuter, - CLSID_DXFilter, phr -#if !defined(_WIN32_WCE) - ,(BOOL)ModifiesData -#endif - ) - , m_callback( NULL ) -{ - // this is used to override the input pin with our own - m_pInput = (CTransInPlaceInputPin*) new CDXFilterInPin( this, phr ); - if( !m_pInput ) - { - if (phr) - *phr = E_OUTOFMEMORY; - } - - // Ensure that the output pin gets created. This is necessary because our - // SetDeliveryBuffer() method assumes that the input/output pins are created, but - // the output pin isn't created until GetPin() is called. The - // CTransInPlaceFilter::GetPin() method will create the output pin, since we - // have not already created one. - IPin *pOutput = GetPin(1); - // The pointer is not AddRef'ed by GetPin(), so don't release it -} - -STDMETHODIMP CDXFilter::NonDelegatingQueryInterface( REFIID riid, void ** ppv) -{ - CheckPointer(ppv,E_POINTER); - - if(riid == IID_IDXFilter) { - return GetInterface((IDXFilter *) this, ppv); - } - else { - return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv); - } -} - - -//---------------------------------------------------------------------------- -// This is where you force the sample grabber to connect with one type -// or the other. What you do here is crucial to what type of data your -// app will be dealing with in the sample grabber's callback. For instance, -// if you don't enforce right-side-up video in this call, you may not get -// right-side-up video in your callback. It all depends on what you do here. -//---------------------------------------------------------------------------- - -HRESULT CDXFilter::CheckInputType( const CMediaType * pmt ) -{ - CheckPointer(pmt,E_POINTER); - CAutoLock lock( &m_Lock ); - - // if the major type is not set, then accept anything - - GUID g = *m_mtAccept.Type( ); - if( g == GUID_NULL ) - { - return NOERROR; - } - - // if the major type is set, don't accept anything else - - if( g != *pmt->Type( ) ) - { - return VFW_E_INVALID_MEDIA_TYPE; - } - - // subtypes must match, if set. if not set, accept anything - VIDEOINFO *pvi = (VIDEOINFO *)pmt->Format(); - - g = *m_mtAccept.Subtype( ); - if( g == GUID_NULL ) - { - return NOERROR; - } -#if 0 - if( MEDIASUBTYPE_RGB24 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_YVU9 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Y411 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Y41P == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_YUY2 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_YVYU == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_UYVY == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Y211 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_YV12 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_CLJR == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_IF09 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_CPLA == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MJPG == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_TVMJ == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_WAKE == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_CFCC == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_IJPG == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Plum == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB1 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB1 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB1 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB4 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB8 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB565 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB555 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB24 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_RGB32 == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Overlay == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1Packet == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1Payload == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1AudioPayload == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIATYPE_MPEG1SystemStream == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1System == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1VideoCD == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_MPEG1Video == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Avi == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_Asf == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_QTMovie == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_QTRpza == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_QTSmc == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_QTRle == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_QTJpeg == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_PCM == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_WAVE == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_AU == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_AIFF == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_DssVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVBI == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; - if( MEDIASUBTYPE_VPVideo == *pmt->Subtype( ) ) - return VFW_E_INVALID_MEDIA_TYPE; -#endif - - if( g != *pmt->Subtype( ) ) - { - return VFW_E_INVALID_MEDIA_TYPE; - } - - // format types must match, if one is set - - g = *m_mtAccept.FormatType( ); - if( g == GUID_NULL ) - { - return NOERROR; - } - if( g != *pmt->FormatType( ) ) - { - return VFW_E_INVALID_MEDIA_TYPE; - } - - // at this point, for this sample code, this is good enough, - // but you may want to make it more strict - - //compare sizes - //VIDEOINFO *pvi = (VIDEOINFO *)pmt->Format(); - VIDEOINFO *pvi2 = (VIDEOINFO *)m_mtAccept.Format(); - if (pvi2==NULL) - return NOERROR; - - if (pvi==NULL) - return VFW_E_INVALID_MEDIA_TYPE; -#if !defined(_WIN32_WCE) - if (pvi->bmiHeader.biCompression!=pvi2->bmiHeader.biCompression) - return VFW_E_INVALID_MEDIA_TYPE; -#endif - if (pvi->bmiHeader.biBitCount!=pvi2->bmiHeader.biBitCount) - return VFW_E_INVALID_MEDIA_TYPE; - if (pvi->bmiHeader.biWidth!=pvi2->bmiHeader.biWidth) - return VFW_E_INVALID_MEDIA_TYPE; - if (pvi->bmiHeader.biHeight!=pvi2->bmiHeader.biHeight) - return VFW_E_INVALID_MEDIA_TYPE; - if (pvi->bmiHeader.biSizeImage!=pvi2->bmiHeader.biSizeImage) - return VFW_E_INVALID_MEDIA_TYPE; - - return NOERROR; -} - - -//---------------------------------------------------------------------------- -// This bit is almost straight out of the base classes. -// We override this so we can handle Transform( )'s error -// result differently. -//---------------------------------------------------------------------------- - -HRESULT CDXFilter::Receive( IMediaSample * pms ) -{ - CheckPointer(pms,E_POINTER); - - HRESULT hr; - AM_SAMPLE2_PROPERTIES * const pProps = m_pInput->SampleProps(); - - if (pProps->dwStreamId != AM_STREAM_MEDIA) - { - if( m_pOutput->IsConnected() ) - return m_pOutput->Deliver(pms); - else - return NOERROR; - } - -#if !defined(_WIN32_WCE) - if (UsingDifferentAllocators()) - { - // We have to copy the data. - - pms = Copy(pms); - - if (pms == NULL) - { - return E_UNEXPECTED; - } - } -#endif - - // have the derived class transform the data - hr = Transform(pms); - - if (FAILED(hr)) - { - //DbgLog((LOG_TRACE, 1, TEXT("Error from TransInPlace"))); -#if !defined(_WIN32_WCE) - if (UsingDifferentAllocators()) - { - pms->Release(); - } -#endif - return hr; - } - - if (hr == NOERROR) - { - hr = m_pOutput->Deliver(pms); - } - - // release the output buffer. If the connected pin still needs it, - // it will have addrefed it itself. -#if !defined(_WIN32_WCE) - if (UsingDifferentAllocators()) - { - pms->Release(); - } -#endif - return hr; -} - - -//---------------------------------------------------------------------------- -// Transform -//---------------------------------------------------------------------------- - -HRESULT CDXFilter::Transform ( IMediaSample * pms ) -{ - CheckPointer(pms,E_POINTER); - CAutoLock lock( &m_Lock ); - - if( m_callback ) - { - REFERENCE_TIME StartTime, StopTime; - pms->GetTime( &StartTime, &StopTime); - - StartTime += m_pInput->CurrentStartTime( ); - StopTime += m_pInput->CurrentStartTime( ); - - BOOL * pTypeChanged = &((CDXFilterInPin*) m_pInput)->m_bMediaTypeChanged; - - HRESULT hr = m_callback( pms, &StartTime, &StopTime, *pTypeChanged ); - - *pTypeChanged = FALSE; // now that we notified user, we can clear it - - return hr; - } - - return NOERROR; -} - - -//---------------------------------------------------------------------------- -// SetAcceptedMediaType -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilter::SetAcceptedMediaType( const CMediaType * pmt ) -{ - CAutoLock lock( &m_Lock ); - - if( !pmt ) - { - m_mtAccept = CMediaType( ); - return NOERROR; - } - - HRESULT hr; -#if !defined(_WIN32_WCE) - hr = CopyMediaType( &m_mtAccept, pmt ); -#else - hr=S_OK; - CopyMediaType( &m_mtAccept, pmt ); -#endif - return hr; -} - -//---------------------------------------------------------------------------- -// GetAcceptedMediaType -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilter::GetConnectedMediaType( CMediaType * pmt ) -{ - if( !m_pInput || !m_pInput->IsConnected( ) ) - { - return VFW_E_NOT_CONNECTED; - } - - return m_pInput->ConnectionMediaType( pmt ); -} - - -//---------------------------------------------------------------------------- -// SetCallback -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilter::SetCallback( SAMPLECALLBACK Callback ) -{ - CAutoLock lock( &m_Lock ); - - m_callback = Callback; - - return NOERROR; -} - - -//---------------------------------------------------------------------------- -// inform the input pin of the allocator buffer we wish to use. See the -// input pin's SetDeliverBuffer method for comments. -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilter::SetDeliveryBuffer( ALLOCATOR_PROPERTIES props, BYTE * m_pBuffer ) -{ - // have the input/output pins been created? - if( !InputPin( ) || !OutputPin( ) ) - { - return E_POINTER; - } - - // they can't be connected if we're going to be changing delivery buffers - // - if( InputPin( )->IsConnected( ) || OutputPin( )->IsConnected( ) ) - { - return E_INVALIDARG; - } - - return ((CDXFilterInPin*)m_pInput)->SetDeliveryBuffer( props, m_pBuffer ); -} - - -//---------------------------------------------------------------------------- -// used to help speed input pin connection times. We return a partially -// specified media type - only the main type is specified. If we return -// anything BUT a major type, some codecs written improperly will crash -//---------------------------------------------------------------------------- - -HRESULT CDXFilterInPin::GetMediaType( int iPosition, CMediaType * pMediaType ) -{ - CheckPointer(pMediaType,E_POINTER); - - if (iPosition < 0) { - return E_INVALIDARG; - } - if (iPosition > 0) { - return VFW_S_NO_MORE_ITEMS; - } - - *pMediaType = CMediaType( ); - pMediaType->SetType( ((CDXFilter*)m_pFilter)->m_mtAccept.Type( ) ); - - return S_OK; -} - - -//---------------------------------------------------------------------------- -// override the CTransInPlaceInputPin's method, and return a new enumerator -// if the input pin is disconnected. This will allow GetMediaType to be -// called. If we didn't do this, EnumMediaTypes returns a failure code -// and GetMediaType is never called. -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilterInPin::EnumMediaTypes( IEnumMediaTypes **ppEnum ) -{ - CheckPointer(ppEnum,E_POINTER); - ValidateReadWritePtr(ppEnum,sizeof(IEnumMediaTypes *)); - - // if the output pin isn't connected yet, offer the possibly - // partially specified media type that has been set by the user - - if( !((CDXFilter*)m_pTIPFilter)->OutputPin( )->IsConnected() ) - { - // Create a new reference counted enumerator - - *ppEnum = new CEnumMediaTypes( this, NULL ); - - return (*ppEnum) ? NOERROR : E_OUTOFMEMORY; - } - - // if the output pin is connected, offer it's fully qualified media type - - return ((CDXFilter*)m_pTIPFilter)->OutputPin( )->GetConnected()->EnumMediaTypes( ppEnum ); -} - - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilterInPin::NotifyAllocator( IMemAllocator *pAllocator, BOOL bReadOnly ) -{ - if( m_pPrivateAllocator ) - { - if( pAllocator != m_pPrivateAllocator ) - { - return E_FAIL; - } - else - { -#if !defined(_WIN32_WCE) - // if the upstream guy wants to be read only and we don't, then that's bad - // if the upstream guy doesn't request read only, but we do, that's okay - if( bReadOnly && !DXFilter( )->IsReadOnly( ) ) - { - return E_FAIL; - } -#endif - } - } - - return CTransInPlaceInputPin::NotifyAllocator( pAllocator, bReadOnly ); -} - - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -STDMETHODIMP CDXFilterInPin::GetAllocator( IMemAllocator **ppAllocator ) -{ - if( m_pPrivateAllocator ) - { - CheckPointer(ppAllocator,E_POINTER); - - *ppAllocator = m_pPrivateAllocator; - m_pPrivateAllocator->AddRef( ); - return NOERROR; - } - else - { - return CTransInPlaceInputPin::GetAllocator( ppAllocator ); - } -} - -//---------------------------------------------------------------------------- -// GetAllocatorRequirements: The upstream filter calls this to get our -// filter's allocator requirements. If the app has set the buffer, then -// we return those props. Otherwise, we use the default TransInPlace behavior. -//---------------------------------------------------------------------------- - -HRESULT CDXFilterInPin::GetAllocatorRequirements( ALLOCATOR_PROPERTIES *pProps ) -{ - CheckPointer(pProps,E_POINTER); - - if (m_pPrivateAllocator) - { - *pProps = m_allocprops; - return S_OK; - } - else - { - return CTransInPlaceInputPin::GetAllocatorRequirements(pProps); - } -} - - - - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -HRESULT CDXFilterInPin::SetDeliveryBuffer( ALLOCATOR_PROPERTIES props, BYTE * pBuffer ) -{ - // don't allow more than one buffer - - if( props.cBuffers != 1 ) - { - return E_INVALIDARG; - } - if( !pBuffer ) - { - return E_POINTER; - } - - m_allocprops = props; - m_pBuffer = pBuffer; - - // If there is an existing allocator, make sure that it is released - // to prevent a memory leak - if (m_pPrivateAllocator) - { - m_pPrivateAllocator->Release(); - m_pPrivateAllocator = NULL; - } - - HRESULT hr = S_OK; - - m_pPrivateAllocator = new CDXFilterAllocator( this, &hr ); - if( !m_pPrivateAllocator ) - { - return E_OUTOFMEMORY; - } - - m_pPrivateAllocator->AddRef( ); - return hr; -} - - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -HRESULT CDXFilterInPin::SetMediaType( const CMediaType *pmt ) -{ - m_bMediaTypeChanged = TRUE; - - return CTransInPlaceInputPin::SetMediaType( pmt ); -} - - -//---------------------------------------------------------------------------- -// don't allocate the memory, just use the buffer the app provided -//---------------------------------------------------------------------------- - -HRESULT CDXFilterAllocator::Alloc( ) -{ - // look at the base class code to see where this came from! - - CAutoLock lck(this); - - // Check he has called SetProperties - HRESULT hr = CBaseAllocator::Alloc(); - if (FAILED(hr)) { - return hr; - } - - // If the requirements haven't changed then don't reallocate - if (hr == S_FALSE) { - /* ASSERT(m_pBuffer); */ - return NOERROR; - } - /* ASSERT(hr == S_OK); we use this fact in the loop below */ - - // Free the old resources - if (m_pBuffer) { - ReallyFree(); - } - - // Compute the aligned size - LONG lAlignedSize = m_lSize + m_lPrefix; - if (m_lAlignment > 1) - { - LONG lRemainder = lAlignedSize % m_lAlignment; - if (lRemainder != 0) - { - lAlignedSize += (m_lAlignment - lRemainder); - } - } - - // Create the contiguous memory block for the samples - // making sure it's properly aligned (64K should be enough!) - /* ASSERT(lAlignedSize % m_lAlignment == 0); */ - - // don't create the buffer - use what was passed to us - // - m_pBuffer = m_pPin->m_pBuffer; - - if (m_pBuffer == NULL) { - return E_OUTOFMEMORY; - } - - LPBYTE pNext = m_pBuffer; - CMediaSample *pSample; - - /* ASSERT(m_lAllocated == 0); */ - - // Create the new samples - we have allocated m_lSize bytes for each sample - // plus m_lPrefix bytes per sample as a prefix. We set the pointer to - // the memory after the prefix - so that GetPointer() will return a pointer - // to m_lSize bytes. - for (; m_lAllocated < m_lCount; m_lAllocated++, pNext += lAlignedSize) - { - pSample = new CMediaSample( - NAME("Sample Grabber memory media sample"), - this, - &hr, - pNext + m_lPrefix, // GetPointer() value - m_lSize); // not including prefix - - /* ASSERT(SUCCEEDED(hr)); */ - if (pSample == NULL) - return E_OUTOFMEMORY; - - // This CANNOT fail - m_lFree.Add(pSample); - } - - m_bChanged = FALSE; - return NOERROR; -} - - -//---------------------------------------------------------------------------- -// don't really free the memory -//---------------------------------------------------------------------------- - -void CDXFilterAllocator::ReallyFree() -{ - // look at the base class code to see where this came from! - - // Should never be deleting this unless all buffers are freed - - /* ASSERT(m_lAllocated == m_lFree.GetCount()); */ - - // Free up all the CMediaSamples - - CMediaSample *pSample; - for (;;) - { - pSample = m_lFree.RemoveHead(); - if (pSample != NULL) - { - delete pSample; - } - else - { - break; - } - } - - m_lAllocated = 0; - - // don't free the buffer - let the app do it -} - - -//---------------------------------------------------------------------------- -// SetProperties: Called by the upstream filter to set the allocator -// properties. The application has already allocated the buffer, so we reject -// anything that is not compatible with that, and return the actual props. -//---------------------------------------------------------------------------- - -HRESULT CDXFilterAllocator::SetProperties( - ALLOCATOR_PROPERTIES *pRequest, - ALLOCATOR_PROPERTIES *pActual -) -{ - HRESULT hr = CMemAllocator::SetProperties(pRequest, pActual); - - if (FAILED(hr)) - { - return hr; - } - - ALLOCATOR_PROPERTIES *pRequired = &(m_pPin->m_allocprops); - if (pRequest->cbAlign != pRequired->cbAlign) - { - return VFW_E_BADALIGN; - } - if (pRequest->cbPrefix != pRequired->cbPrefix) - { - return E_FAIL; - } - if (pRequest->cbBuffer > pRequired->cbBuffer) - { - return E_FAIL; - } - if (pRequest->cBuffers > pRequired->cBuffers) - { - return E_FAIL; - } - - *pActual = *pRequired; - - m_lCount = pRequired->cBuffers; - m_lSize = pRequired->cbBuffer; - m_lAlignment = pRequired->cbAlign; - m_lPrefix = pRequired->cbPrefix; - - return S_OK; -} - -#endif diff --git a/linphone/mediastreamer2/src/dxfilter.h b/linphone/mediastreamer2/src/dxfilter.h deleted file mode 100644 index cc63f0de9..000000000 --- a/linphone/mediastreamer2/src/dxfilter.h +++ /dev/null @@ -1,231 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -// {4D6410BE-7643-4f43-B55F-8821A6FFB50A} -DEFINE_GUID(CLSID_DXFilter, -0x4d6410be, 0x7643, 0x4f43, 0xb5, 0x5f, 0x88, 0x21, 0xa6, 0xff, 0xb5, 0xa); - -// {52A7F345-CD92-442c-89C1-632C16AD5003} -DEFINE_GUID(IID_IDXFilter, -0x52a7f345, 0xcd92, 0x442c, 0x89, 0xc1, 0x63, 0x2c, 0x16, 0xad, 0x50, 0x3); - - -// We define a callback typedef for this example. -// Normally, you would make the DXFilter support a COM interface, -// and in one of its methods you would pass in a pointer to a COM interface -// used for calling back. See the DirectX documentation for the DXFilter -// for more information. - -typedef HRESULT (*SAMPLECALLBACK) ( - IMediaSample * pSample, - REFERENCE_TIME * StartTime, - REFERENCE_TIME * StopTime, - BOOL TypeChanged ); - - -// We define the interface the app can use to program us -MIDL_INTERFACE("6B652FFF-11FE-4FCE-92AD-0266B5D7C78F") -IDXFilter : public IUnknown -{ - public: - - virtual HRESULT STDMETHODCALLTYPE SetAcceptedMediaType( - const CMediaType *pType) = 0; - - virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType( - CMediaType *pType) = 0; - - virtual HRESULT STDMETHODCALLTYPE SetCallback( - SAMPLECALLBACK Callback) = 0; - - virtual HRESULT STDMETHODCALLTYPE SetDeliveryBuffer( - ALLOCATOR_PROPERTIES props, - BYTE *pBuffer) = 0; -}; - - -class CDXFilterInPin; -class CDXFilter; - -//---------------------------------------------------------------------------- -// This is a special allocator that KNOWS that the person who is creating it -// will only create one of them. It allocates CMediaSamples that only -// reference the buffer location that is set in the pin's renderer's -// data variable -//---------------------------------------------------------------------------- - -class CDXFilterAllocator : public CMemAllocator -{ - friend class CDXFilterInPin; - friend class CDXFilter; - -protected: - - // our pin who created us - // - CDXFilterInPin * m_pPin; - -public: - - CDXFilterAllocator( CDXFilterInPin * pParent, HRESULT *phr ) - : CMemAllocator( TEXT("DXFilterAllocator\0"), NULL, phr ) - , m_pPin( pParent ) - { - }; - - ~CDXFilterAllocator( ) - { - // wipe out m_pBuffer before we try to delete it. It's not an allocated - // buffer, and the default destructor will try to free it! - m_pBuffer = NULL; - } - - HRESULT Alloc( ); - - void ReallyFree(); - - // Override this to reject anything that does not match the actual buffer - // that was created by the application - STDMETHODIMP SetProperties(ALLOCATOR_PROPERTIES *pRequest, ALLOCATOR_PROPERTIES *pActual); - -}; - -//---------------------------------------------------------------------------- -// we override the input pin class so we can provide a media type -// to speed up connection times. When you try to connect a filesourceasync -// to a transform filter, DirectShow will insert a splitter and then -// start trying codecs, both audio and video, video codecs first. If -// your sample grabber's set to connect to audio, unless we do this, it -// will try all the video codecs first. Connection times are sped up x10 -// for audio with just this minor modification! -//---------------------------------------------------------------------------- - -class CDXFilterInPin : public CTransInPlaceInputPin -{ - friend class CDXFilterAllocator; - friend class CDXFilter; - - CDXFilterAllocator * m_pPrivateAllocator; - ALLOCATOR_PROPERTIES m_allocprops; - BYTE * m_pBuffer; - BOOL m_bMediaTypeChanged; - -protected: - - CDXFilter * DXFilter( ) { return (CDXFilter*) m_pFilter; } - HRESULT SetDeliveryBuffer( ALLOCATOR_PROPERTIES props, BYTE * m_pBuffer ); - -public: - - CDXFilterInPin( CTransInPlaceFilter * pFilter, HRESULT * pHr ) - : CTransInPlaceInputPin( TEXT("DXFilterInputPin\0"), pFilter, pHr, L"Input\0" ) - , m_pPrivateAllocator( NULL ) - , m_pBuffer( NULL ) - , m_bMediaTypeChanged( FALSE ) - { - memset( &m_allocprops, 0, sizeof( m_allocprops ) ); - } - - ~CDXFilterInPin( ) - { - if( m_pPrivateAllocator ) delete m_pPrivateAllocator; - } - - // override to provide major media type for fast connects - - HRESULT GetMediaType( int iPosition, CMediaType *pMediaType ); - - // override this or GetMediaType is never called - - STDMETHODIMP EnumMediaTypes( IEnumMediaTypes **ppEnum ); - - // override this to refuse any allocators besides - // the one the user wants, if this is set - - STDMETHODIMP NotifyAllocator( IMemAllocator *pAllocator, BOOL bReadOnly ); - - // override this so we always return the special allocator, if necessary - - STDMETHODIMP GetAllocator( IMemAllocator **ppAllocator ); - - HRESULT SetMediaType( const CMediaType *pmt ); - - // we override this to tell whoever's upstream of us what kind of - // properties we're going to demand to have - // - STDMETHODIMP GetAllocatorRequirements( ALLOCATOR_PROPERTIES *pProps ); - - - -}; - -//---------------------------------------------------------------------------- -// -//---------------------------------------------------------------------------- - -class CDXFilter : public CTransInPlaceFilter, - public IDXFilter -{ - friend class CDXFilterInPin; - friend class CDXFilterAllocator; - -protected: - - CMediaType m_mtAccept; - SAMPLECALLBACK m_callback; - CCritSec m_Lock; // serialize access to our data - -#if !defined(_WIN32_WCE) - BOOL IsReadOnly( ) { return !m_bModifiesData; } -#endif - - // PURE, override this to ensure we get - // connected with the right media type - HRESULT CheckInputType( const CMediaType * pmt ); - - // PURE, override this to callback - // the user when a sample is received - HRESULT Transform( IMediaSample * pms ); - - // override this so we can return S_FALSE directly. - // The base class CTransInPlace - // Transform( ) method is called by it's - // Receive( ) method. There is no way - // to get Transform( ) to return an S_FALSE value - // (which means "stop giving me data"), - // to Receive( ) and get Receive( ) to return S_FALSE as well. - - HRESULT Receive( IMediaSample * pms ); - -public: - - static CUnknown *WINAPI CreateInstance(LPUNKNOWN punk, HRESULT *phr); - - // Expose IDXFilter - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv); - DECLARE_IUNKNOWN; - - CDXFilter( IUnknown * pOuter, HRESULT * pHr, BOOL ModifiesData ); - - // IDXFilter - STDMETHODIMP SetAcceptedMediaType( const CMediaType * pmt ); - STDMETHODIMP GetConnectedMediaType( CMediaType * pmt ); - STDMETHODIMP SetCallback( SAMPLECALLBACK Callback ); - STDMETHODIMP SetDeliveryBuffer( ALLOCATOR_PROPERTIES props, BYTE * m_pBuffer ); -}; diff --git a/linphone/mediastreamer2/src/equalizer.c b/linphone/mediastreamer2/src/equalizer.c deleted file mode 100644 index 95a60649f..000000000 --- a/linphone/mediastreamer2/src/equalizer.c +++ /dev/null @@ -1,368 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2009 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 -#include - -#include - -#ifdef _MSC_VER -#include -#define alloca _alloca -#endif - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -#ifdef MS_FIXED_POINT -#define GAIN_ZERODB 20000 -#else -#define GAIN_ZERODB 1.0 -#endif - -#define TAPS 128 - -typedef struct _EqualizerState{ - int rate; - int nfft; /*number of fft points in time*/ - ms_word16_t *fft_cpx; - int fir_len; - ms_word16_t *fir; - ms_mem_t *mem; /*memories for filtering computations*/ - bool_t needs_update; - bool_t active; -} EqualizerState; - -static void equalizer_state_flatten(EqualizerState *s){ - int i; - ms_word16_t val=GAIN_ZERODB/s->nfft; - s->fft_cpx[0]=val; - for(i=1;infft;i+=2) - s->fft_cpx[i]=val; -} - -/* TODO: rate also beyond 8000 */ -static EqualizerState * equalizer_state_new(int nfft){ - EqualizerState *s=(EqualizerState *)ms_new0(EqualizerState,1); - s->rate=8000; - s->nfft=nfft; - s->fft_cpx=(ms_word16_t*)ms_new0(ms_word16_t,s->nfft); - equalizer_state_flatten(s); - s->fir_len=s->nfft; - s->fir=(ms_word16_t*)ms_new(ms_word16_t,s->fir_len); - s->mem=(ms_mem_t*)ms_new0(ms_mem_t,s->fir_len); - s->needs_update=TRUE; - s->active=TRUE; - return s; -} - -static void equalizer_state_destroy(EqualizerState *s){ - ms_free(s->fft_cpx); - ms_free(s->fir); - ms_free(s->mem); - ms_free(s); -} - -static int equalizer_state_hz_to_index(EqualizerState *s, int hz){ - int ret; - if (hz<0){ - ms_error("Bad frequency value %i",hz); - return -1; - } - if (hz>(s->rate/2)){ - hz=(s->rate/2); - } - /*round to nearest integer*/ - ret=((hz*s->nfft)+(s->rate/2))/s->rate; - if (ret==s->nfft/2) ret=(s->nfft/2)-1; - return ret; -} - -static int equalizer_state_index2hz(EqualizerState *s, int index){ - return (index * s->rate + s->nfft/2) / s->nfft; -} - -static float gain_float(ms_word16_t val){ - return (float)val/GAIN_ZERODB; -} - -static float equalizer_state_get(EqualizerState *s, int freqhz){ - int idx=equalizer_state_hz_to_index(s,freqhz); - if (idx>=0) return gain_float(s->fft_cpx[idx*2])*s->nfft; - return 0; -} - -/* The natural peaking equalizer amplitude transfer function is multiplied to the discrete f-points. - * Note that for PEQ no sqrt is needed for the overall calculation, applying it to gain yields the - * same response. - */ -static float equalizer_compute_gainpoint(int f, int freq_0, float sqrt_gain, int freq_bw) -{ - float k1, k2; - k1 = ((float)(f*f)-(float)(freq_0*freq_0)); - k1*= k1; - k2 = (float)(f*freq_bw); - k2*= k2; - return (k1+k2*sqrt_gain)/(k1+k2/sqrt_gain); -} - -static void equalizer_point_set(EqualizerState *s, int i, int f, float gain){ - ms_message("Setting gain %f for freq_index %i (%i Hz)\n",gain,i,f); - s->fft_cpx[1+((i-1)*2)] = (s->fft_cpx[1+((i-1)*2)]*(int)(gain*32768))/32768; -} - -static void equalizer_state_set(EqualizerState *s, int freq_0, float gain, int freq_bw){ - //int low,high; - int i, f; - int delta_f = equalizer_state_index2hz(s, 1); - float sqrt_gain = sqrt(gain); - int mid = equalizer_state_hz_to_index(s, freq_0); - freq_bw-= delta_f/2; /* subtract a constant - compensates for limited fft steepness at low f */ - if (freq_bw < delta_f/2) - freq_bw = delta_f/2; - i = mid; - f = equalizer_state_index2hz(s, i); - equalizer_point_set(s, i, f, gain); /* gain according to argument */ - do { /* note: to better accomodate limited fft steepness, -delta is applied in f-calc ... */ - i++; - f = equalizer_state_index2hz(s, i); - gain = equalizer_compute_gainpoint(f-delta_f, freq_0, sqrt_gain, freq_bw); - equalizer_point_set(s, i, f, gain); - } - while (i < s->nfft/2 && (gain>1.1 || gain<0.9)); - i = mid; - do { /* ... and here +delta, as to */ - i--; - f = equalizer_state_index2hz(s, i); - gain = equalizer_compute_gainpoint(f+delta_f, freq_0, sqrt_gain, freq_bw); - equalizer_point_set(s, i, f, gain); - } - while (i>=0 && (gain>1.1 || gain<0.9)); - s->needs_update=TRUE; -} - -static void dump_table(ms_word16_t *t, int len){ - int i; - for(i=0;infft); - ms_message("Spectral domain:"); - dump_table(s->fft_cpx,s->nfft); - ms_ifft(fft_handle,s->fft_cpx,s->fir); - ms_fft_destroy(fft_handle); - /* - ms_message("Inverse fft result:"); - dump_table(s->fir,s->fir_len); - */ - time_shift(s->fir,s->fir_len); - /* - ms_message("Time shifted:"); - dump_table(s->fir,s->fir_len); - */ - norm_and_apodize(s->fir,s->fir_len); - ms_message("Apodized impulse response:"); - dump_table(s->fir,s->fir_len); - s->needs_update=FALSE; -} - - - -#ifdef MS_FIXED_POINT -#define INT16_TO_WORD16(i,w,l) w=(i) -#define WORD16_TO_INT16(i,w,l) i=(w) -#else - -static void int16_to_word16(const int16_t *is, ms_word16_t *w, int l){ - int i; - for(i=0;ineeds_update) - equalizer_state_compute_impulse_response(s); - ms_word16_t *w; - INT16_TO_WORD16(samples,w,nsamples); - ms_fir_mem16(w,s->fir,w,nsamples,s->fir_len,s->mem); - WORD16_TO_INT16(w,samples,nsamples); -} - - -static void equalizer_init(MSFilter *f){ - f->data=equalizer_state_new(TAPS); -} - -static void equalizer_uninit(MSFilter *f){ - equalizer_state_destroy((EqualizerState*)f->data); -} - -static void equalizer_process(MSFilter *f){ - mblk_t *m; - EqualizerState *s=(EqualizerState*)f->data; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - if (s->active){ - equalizer_state_run(s,(int16_t*)m->b_rptr,(m->b_wptr-m->b_rptr)/2); - } - ms_queue_put(f->outputs[0],m); - } -} - -static int equalizer_set_gain(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - MSEqualizerGain *d=(MSEqualizerGain*)data; - equalizer_state_set(s,d->frequency,d->gain,d->width); - return 0; -} - -static int equalizer_get_gain(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - MSEqualizerGain *d=(MSEqualizerGain*)data; - d->gain=equalizer_state_get(s,d->frequency); - d->width=0; - return 0; -} - -static int equalizer_set_rate(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - s->rate=*(int*)data; - s->needs_update=TRUE; - return 0; -} - -static int equalizer_set_active(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - s->active=*(int*)data; - return 0; -} - -static int equalizer_dump(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - float *t=(float*)data; - int i; - *t=s->fft_cpx[0]; - t++; - for (i=1;infft;i+=2){ - *t=((float)s->fft_cpx[i]*(float)s->nfft)/(float)GAIN_ZERODB; - t++; - } - return 0; -} - -static int equalizer_get_nfreqs(MSFilter *f, void *data){ - EqualizerState *s=(EqualizerState*)f->data; - *(int*)data=s->nfft/2; - return 0; -} - -static MSFilterMethod equalizer_methods[]={ - { MS_EQUALIZER_SET_GAIN , equalizer_set_gain }, - { MS_EQUALIZER_GET_GAIN , equalizer_get_gain }, - { MS_EQUALIZER_SET_ACTIVE , equalizer_set_active }, - { MS_FILTER_SET_SAMPLE_RATE , equalizer_set_rate }, - { MS_EQUALIZER_DUMP_STATE , equalizer_dump }, - { MS_EQUALIZER_GET_NUM_FREQUENCIES, equalizer_get_nfreqs }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_equalizer_desc={ - MS_EQUALIZER_ID, - "MSEqualizer", - N_("Parametric sound equalizer."), - MS_FILTER_OTHER, - NULL, - 1, - 1, - equalizer_init, - NULL, - equalizer_process, - NULL, - equalizer_uninit, - equalizer_methods -}; - -#else - -MSFilterDesc ms_equalizer_desc={ - .id= MS_EQUALIZER_ID, - .name="MSEqualizer", - .text=N_("Parametric sound equalizer."), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=1, - .init=equalizer_init, - .process=equalizer_process, - .uninit=equalizer_uninit, - .methods=equalizer_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_equalizer_desc) diff --git a/linphone/mediastreamer2/src/ffmpeg-priv.h b/linphone/mediastreamer2/src/ffmpeg-priv.h deleted file mode 100644 index 5aefaf656..000000000 --- a/linphone/mediastreamer2/src/ffmpeg-priv.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef FFMPEG_PRIV_H -#define FFMPEG_PRIV_H - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#if defined(HAVE_LIBAVCODEC_AVCODEC_H) -/* new layout */ -# include -# include -#else -/* old layout */ -# include -# include -#endif - -#if defined(HAVE_LIBSWSCALE_SWSCALE_H) -/* new layout */ -# include -# elif !defined(HAVE_LIBAVCODEC_AVCODEC_H) -/* old layout */ -# include -#else -/* swscale.h not delivered: use linphone private version */ -# include "swscale.h" -#endif - - -#if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(52,24,0) -/*should work as long as nobody uses avformat.h*/ -typedef struct AVPacket{ - uint8_t *data; - int size; -}AVPacket; - -static inline void av_init_packet(AVPacket *pkt){ - -} -static inline int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, - int *got_picture_ptr, - AVPacket *avpkt){ - return avcodec_decode_video(avctx,picture, got_picture_ptr,avpkt->data,avpkt->size); -} -#endif - -#endif /* FFMPEG_PRIV_H */ diff --git a/linphone/mediastreamer2/src/g711common.h b/linphone/mediastreamer2/src/g711common.h deleted file mode 100644 index 3f2c9e330..000000000 --- a/linphone/mediastreamer2/src/g711common.h +++ /dev/null @@ -1,171 +0,0 @@ -/* - * PCM - A-Law conversion - * Copyright (c) 2000 by Abramo Bagnara - * - * Wrapper for linphone Codec class by Simon Morlat - */ - -static inline int val_seg(int val) -{ - int r = 0; - val >>= 7; - if (val & 0xf0) { - val >>= 4; - r += 4; - } - if (val & 0x0c) { - val >>= 2; - r += 2; - } - if (val & 0x02) - r += 1; - return r; -} - -/* - * s16_to_alaw() - Convert a 16-bit linear PCM value to 8-bit A-law - * - * s16_to_alaw() accepts an 16-bit integer and encodes it as A-law data. - * - * Linear Input Code Compressed Code - * ------------------------ --------------- - * 0000000wxyza 000wxyz - * 0000001wxyza 001wxyz - * 000001wxyzab 010wxyz - * 00001wxyzabc 011wxyz - * 0001wxyzabcd 100wxyz - * 001wxyzabcde 101wxyz - * 01wxyzabcdef 110wxyz - * 1wxyzabcdefg 111wxyz - * - * For further information see John C. Bellamy's Digital Telephony, 1982, - * John Wiley & Sons, pps 98-111 and 472-476. - */ - -static inline unsigned char s16_to_alaw(int pcm_val) -{ - int mask; - int seg; - unsigned char aval; - - if (pcm_val >= 0) { - mask = 0xD5; - } else { - mask = 0x55; - pcm_val = -pcm_val; - if (pcm_val > 0x7fff) - pcm_val = 0x7fff; - } - - if (pcm_val < 256) - aval = pcm_val >> 4; - else { - /* Convert the scaled magnitude to segment number. */ - seg = val_seg(pcm_val); - aval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0x0f); - } - return aval ^ mask; -} - -/* - * alaw_to_s16() - Convert an A-law value to 16-bit linear PCM - * - */ -static inline int alaw_to_s16(unsigned char a_val) -{ - int t; - int seg; - - a_val ^= 0x55; - t = a_val & 0x7f; - if (t < 16) - t = (t << 4) + 8; - else { - seg = (t >> 4) & 0x07; - t = ((t & 0x0f) << 4) + 0x108; - t <<= seg -1; - } - return ((a_val & 0x80) ? t : -t); -} -/* - * s16_to_ulaw() - Convert a linear PCM value to u-law - * - * In order to simplify the encoding process, the original linear magnitude - * is biased by adding 33 which shifts the encoding range from (0 - 8158) to - * (33 - 8191). The result can be seen in the following encoding table: - * - * Biased Linear Input Code Compressed Code - * ------------------------ --------------- - * 00000001wxyza 000wxyz - * 0000001wxyzab 001wxyz - * 000001wxyzabc 010wxyz - * 00001wxyzabcd 011wxyz - * 0001wxyzabcde 100wxyz - * 001wxyzabcdef 101wxyz - * 01wxyzabcdefg 110wxyz - * 1wxyzabcdefgh 111wxyz - * - * Each biased linear code has a leading 1 which identifies the segment - * number. The value of the segment number is equal to 7 minus the number - * of leading 0's. The quantization interval is directly available as the - * four bits wxyz. * The trailing bits (a - h) are ignored. - * - * Ordinarily the complement of the resulting code word is used for - * transmission, and so the code word is complemented before it is returned. - * - * For further information see John C. Bellamy's Digital Telephony, 1982, - * John Wiley & Sons, pps 98-111 and 472-476. - */ - -static inline unsigned char s16_to_ulaw(int pcm_val) /* 2's complement (16-bit range) */ -{ - int mask; - int seg; - unsigned char uval; - - if (pcm_val < 0) { - pcm_val = 0x84 - pcm_val; - mask = 0x7f; - } else { - pcm_val += 0x84; - mask = 0xff; - } - if (pcm_val > 0x7fff) - pcm_val = 0x7fff; - - /* Convert the scaled magnitude to segment number. */ - seg = val_seg(pcm_val); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0x0f); - return uval ^ mask; -} - -/* - * ulaw_to_s16() - Convert a u-law value to 16-bit linear PCM - * - * First, a biased linear code is derived from the code word. An unbiased - * output can then be obtained by subtracting 33 from the biased code. - * - * Note that this function expects to be passed the complement of the - * original code word. This is in keeping with ISDN conventions. - */ -static inline int ulaw_to_s16(unsigned char u_val) -{ - int t; - - /* Complement to obtain normal u-law value. */ - u_val = ~u_val; - - /* - * Extract and bias the quantization bits. Then - * shift up by the segment number and subtract out the bias. - */ - t = ((u_val & 0x0f) << 3) + 0x84; - t <<= (u_val & 0x70) >> 4; - - return ((u_val & 0x80) ? (0x84 - t) : (t - 0x84)); -} diff --git a/linphone/mediastreamer2/src/gsm.c b/linphone/mediastreamer2/src/gsm.c deleted file mode 100644 index 6cc62ec7d..000000000 --- a/linphone/mediastreamer2/src/gsm.c +++ /dev/null @@ -1,165 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" - -#include - -typedef struct EncState{ - gsm state; - uint32_t ts; - MSBufferizer *bufferizer; -} EncState; - -static void enc_init(MSFilter *f){ - EncState *s=(EncState *)ms_new(EncState,1); - s->state=gsm_create(); - s->ts=0; - s->bufferizer=ms_bufferizer_new(); - f->data=s; -} - -static void enc_uninit(MSFilter *f){ - EncState *s=(EncState*)f->data; - gsm_destroy(s->state); - ms_bufferizer_destroy(s->bufferizer); - ms_free(s); -} - - - -static void enc_process(MSFilter *f){ - EncState *s=(EncState*)f->data; - mblk_t *im; - int16_t buf[160]; - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - ms_bufferizer_put(s->bufferizer,im); - } - while(ms_bufferizer_read(s->bufferizer,(uint8_t*)buf,sizeof(buf))==sizeof(buf)) { - mblk_t *om=allocb(33,0); - gsm_encode(s->state,(gsm_signal*)buf,(gsm_byte*)om->b_wptr); - om->b_wptr+=33; - mblk_set_timestamp_info(om,s->ts); - ms_queue_put(f->outputs[0],om); - s->ts+=sizeof(buf)/2; - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_gsm_enc_desc={ - MS_GSM_ENC_ID, - "MSGsmEnc", - N_("The GSM full-rate codec"), - MS_FILTER_ENCODER, - "gsm", - 1, - 1, - enc_init, - NULL, - enc_process, - NULL, - enc_uninit, - NULL -}; - -#else - -MSFilterDesc ms_gsm_enc_desc={ - .id=MS_GSM_ENC_ID, - .name="MSGsmEnc", - .text=N_("The GSM full-rate codec"), - .category=MS_FILTER_ENCODER, - .enc_fmt="gsm", - .ninputs=1, - .noutputs=1, - .init=enc_init, - .process=enc_process, - .uninit=enc_uninit, -}; - -#endif - -static void dec_init(MSFilter *f){ - f->data=gsm_create(); -} - -static void dec_uninit(MSFilter *f){ - gsm s=(gsm)f->data; - gsm_destroy(s); -} - - -static void dec_process(MSFilter *f){ - gsm s=(gsm)f->data; - mblk_t *im; - mblk_t *om; - const int frsz=160*2; - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - om=allocb(frsz,0); - if (gsm_decode(s,(gsm_byte*)im->b_rptr,(gsm_signal*)om->b_wptr)<0){ - ms_warning("gsm_decode error!"); - freemsg(om); - }else{ - om->b_wptr+=frsz; - ms_queue_put(f->outputs[0],om); - } - freemsg(im); - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_gsm_dec_desc={ - MS_GSM_DEC_ID, - "MSGsmDec", - N_("The GSM codec"), - MS_FILTER_DECODER, - "gsm", - 1, - 1, - dec_init, - NULL, - dec_process, - NULL, - dec_uninit, - NULL -}; - -#else - -MSFilterDesc ms_gsm_dec_desc={ - .id=MS_GSM_DEC_ID, - .name="MSGsmDec", - .text=N_("The GSM codec"), - .category=MS_FILTER_DECODER, - .enc_fmt="gsm", - .ninputs=1, - .noutputs=1, - .init=dec_init, - .process=dec_process, - .uninit=dec_uninit -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_gsm_dec_desc) -MS_FILTER_DESC_EXPORT(ms_gsm_enc_desc) diff --git a/linphone/mediastreamer2/src/ice.c b/linphone/mediastreamer2/src/ice.c deleted file mode 100644 index 4f26c4215..000000000 --- a/linphone/mediastreamer2/src/ice.c +++ /dev/null @@ -1,1381 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#if !defined(WIN32) && !defined(_WIN32_WCE) -#ifdef __APPLE__ -#include -#endif -#include -#include -#endif - -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/ice.h" -#include "mediastreamer2/mscommon.h" - -static void -ice_sendtest( struct IceCheckList *checklist, struct CandidatePair *remote_candidate, Socket myFd, StunAddress4 *dest, - const StunAtrString *username, const StunAtrString *password, - UInt96 *tid) -{ - StunMessage req; - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = STUN_MAX_MESSAGE_SIZE; - - memset(&req, 0, sizeof(StunMessage)); - - stunBuildReqSimple( &req, username, FALSE, FALSE, 1); - req.hasMessageIntegrity=TRUE; - - /* 7.1.1.1 - The attribute MUST be set equal to the priority that would be - assigned, based on the algorithm in Section 4.1.2, to a peer - reflexive candidate, should one be learned as a consequence of this - check */ - req.hasPriority = TRUE; - - req.priority.priority = (110 << 24) | (255 << 16) | (255 << 8) - | (256 - remote_candidate->remote_candidate.component_id); - - /* TODO: put this parameter only for the candidate selected */ - if (remote_candidate->nominated_pair==1) - req.hasUseCandidate = TRUE; - - if (remote_candidate->rem_controlling==1) - { - req.hasIceControlled = TRUE; - req.iceControlled.value = checklist->tiebreak_value; - } - else - { - req.hasIceControlling = TRUE; - req.iceControlling.value = checklist->tiebreak_value; - } - - /* TODO: not yet implemented? */ - req.hasFingerprint = TRUE; - - len = stunEncodeMessage( &req, buf, len, password ); - - memcpy(tid , &(req.msgHdr.tr_id), sizeof(req.msgHdr.tr_id)); - - sendMessage( myFd, buf, len, dest->addr, dest->port ); -} - -static int ice_restart(struct IceCheckList *checklist) -{ - struct CandidatePair *remote_candidates = NULL; - int pos; - - int count_waiting=0; - int count=0; - - if (checklist==NULL) - return 0; - remote_candidates = checklist->cand_pairs; - if (remote_candidates==NULL) - return 0; - - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (strcasecmp(remote_candidates[pos].local_candidate.cand_type, "srflx")==0) - { - /* search for a highest priority "equivalent" pair */ - int pos2; - for (pos2=0;pos2 remove the one with lowest priority */ - if (strcasecmp(remote_candidates[pos].remote_candidate.conn_addr, - remote_candidates[pos2].remote_candidate.conn_addr)==0) - { - /* useless cpair */ - ms_message("ice.c: Removing useless pair (idx=%i)", pos); - remote_candidates[pos].connectivity_check = ICE_PRUNED; - - } - - } - - } - } - } - - /* no currently nominated pair */ - checklist->nominated_pair_index = -1; - - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (remote_candidates[pos].connectivity_check == ICE_PRUNED) - continue; - if (remote_candidates[pos].connectivity_check == ICE_FROZEN) - remote_candidates[pos].connectivity_check = ICE_WAITING; - } - - checklist->Ta = 40; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (remote_candidates[pos].connectivity_check == ICE_PRUNED) - continue; - if (remote_candidates[pos].connectivity_check == ICE_WAITING) - count_waiting++; - count++; - } - checklist->RTO = MAX(200, count*checklist->Ta*count_waiting); - return 0; -} - -static int ice_sound_send_stun_request(RtpSession *session, struct IceCheckList *checklist, uint64_t ctime) -{ - struct CandidatePair *remote_candidates = NULL; - - if (checklist==NULL) - return 0; - remote_candidates = checklist->cand_pairs; - if (remote_candidates==NULL) - return 0; - - { - struct CandidatePair *cand_pair; - int media_socket = rtp_session_get_rtp_socket(session); - StunAddress4 stunServerAddr; - StunAtrString username; - StunAtrString password; - bool_t res; - int pos; - - /* prepare ONCE tie-break value */ - if (checklist->tiebreak_value==0) { - checklist->tiebreak_value = random() * (0x7fffffffffffffffLL /0x7fff); - } - - cand_pair=NULL; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - if (cand_pair->connectivity_check == ICE_PRUNED) - { - cand_pair=NULL; - continue; - } - if (cand_pair->connectivity_check == ICE_WAITING) - break; - if (cand_pair->connectivity_check == ICE_IN_PROGRESS) - break; - if (cand_pair->connectivity_check == ICE_SUCCEEDED) - break; - cand_pair=NULL; - } - - if (cand_pair==NULL) - return 0; /* nothing to do: every pair is FAILED, FROZEN or PRUNED */ - - /* start first WAITING pair */ - cand_pair=NULL; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - if (cand_pair->connectivity_check == ICE_PRUNED) - { - cand_pair=NULL; - continue; - } - if (cand_pair->connectivity_check == ICE_WAITING) - break; - cand_pair=NULL; - } - - if (cand_pair!=NULL) - { - cand_pair->connectivity_check = ICE_IN_PROGRESS; - cand_pair->retransmission_number=0; - cand_pair->retransmission_time=ctime+checklist->RTO; - /* keep same rem_controlling for retransmission */ - cand_pair->rem_controlling = checklist->rem_controlling; - } - - /* try no nominate a pair if we are ready */ - if (cand_pair==NULL && checklist->nominated_pair_index<0) - { - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - if (cand_pair->connectivity_check == ICE_PRUNED) - { - cand_pair=NULL; - continue; - } - if (cand_pair->connectivity_check == ICE_SUCCEEDED) - { - break; - } - cand_pair=NULL; - } - - /* ALWAYS accept "host" candidate that have succeeded */ - if (cand_pair!=NULL - && (strcasecmp(cand_pair->remote_candidate.cand_type, "host")==0)) - { - checklist->nominated_pair_index = pos; - cand_pair->nominated_pair = 1; - cand_pair->connectivity_check = ICE_IN_PROGRESS; - cand_pair->retransmission_number=0; - cand_pair->retransmission_time=ctime+checklist->RTO; - /* keep same rem_controlling for retransmission */ - cand_pair->rem_controlling = checklist->rem_controlling; - /* send a new STUN with USE-CANDIDATE */ - ms_message("ice.c: nominating pair -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - checklist->keepalive_time=ctime+15*1000; - } - else if (cand_pair!=NULL) - { - struct CandidatePair *cand_pair2=NULL; - int pos2; - for (pos2=0;pos2connectivity_check == ICE_PRUNED) - { - cand_pair2=NULL; - continue; - } - if (cand_pair2->connectivity_check == ICE_IN_PROGRESS - ||cand_pair2->connectivity_check == ICE_WAITING) - { - break; - } - cand_pair2=NULL; - } - - if (cand_pair2!=NULL) - { - /* a better candidate is still tested */ - cand_pair=NULL; - } - else - { - checklist->nominated_pair_index = pos; - cand_pair->nominated_pair = 1; - cand_pair->connectivity_check = ICE_IN_PROGRESS; - cand_pair->retransmission_number=0; - cand_pair->retransmission_time=ctime+checklist->RTO; - /* keep same rem_controlling for retransmission */ - cand_pair->rem_controlling = checklist->rem_controlling; - /* send a new STUN with USE-CANDIDATE */ - ms_message("ice.c: nominating pair -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - checklist->keepalive_time=ctime+15*1000; - } - } - } - - if (cand_pair==NULL) - { - /* no WAITING pair: retransmit after RTO */ - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - if (cand_pair->connectivity_check == ICE_PRUNED) - { - cand_pair=NULL; - continue; - } - if (cand_pair->connectivity_check == ICE_IN_PROGRESS - && ctime > cand_pair->retransmission_time) - { - if (cand_pair->retransmission_number>7) - { - ms_message("ice.c: ICE_FAILED for candidate pair! %s:%i -> %s:%i", - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port); - - cand_pair->connectivity_check = ICE_FAILED; - cand_pair=NULL; - continue; - } - - cand_pair->retransmission_number++; - cand_pair->retransmission_time=ctime+checklist->RTO; - break; - } - cand_pair=NULL; - } - } - - if (cand_pair==NULL) - { - if (checklist->nominated_pair_index<0) - return 0; - - /* send STUN indication each 15 seconds: keepalive */ - if (ctime>checklist->keepalive_time) - { - checklist->keepalive_time=ctime+15*1000; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - if (cand_pair->connectivity_check == ICE_SUCCEEDED) - { - res = stunParseServerName(cand_pair->remote_candidate.conn_addr, - &stunServerAddr); - if ( res == TRUE ) - { - StunMessage req; - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = STUN_MAX_MESSAGE_SIZE; - stunServerAddr.port = cand_pair->remote_candidate.conn_port; - memset(&req, 0, sizeof(StunMessage)); - stunBuildReqSimple( &req, NULL, FALSE, FALSE, 1); - req.msgHdr.msgType = (STUN_METHOD_BINDING|STUN_INDICATION); - req.hasFingerprint = TRUE; - len = stunEncodeMessage( &req, buf, len, NULL); - sendMessage( media_socket, buf, len, stunServerAddr.addr, stunServerAddr.port ); - } - } - } - } - - return 0; - } - - username.sizeValue = 0; - password.sizeValue = 0; - - /* username comes from "ice-ufrag" (rfrag:lfrag) */ - /* ufrag and pwd are in first row only */ - snprintf(username.value, sizeof(username.value), "%s:%s", - checklist->rem_ice_ufrag, - checklist->loc_ice_ufrag); - username.sizeValue = (uint16_t)strlen(username.value); - - - snprintf(password.value, sizeof(password.value), "%s", - checklist->rem_ice_pwd); - password.sizeValue = (uint16_t)strlen(password.value); - - - res = stunParseServerName(cand_pair->remote_candidate.conn_addr, - &stunServerAddr); - if ( res == TRUE ) - { - ms_message("ice.c: STUN REQ (%s) -> %i (%s:%i:%s -> %s:%i:%s) nominated=%s", - cand_pair->nominated_pair==0?"":"USE-CANDIDATE", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - stunServerAddr.port = cand_pair->remote_candidate.conn_port; - ice_sendtest(checklist, cand_pair, media_socket, &stunServerAddr, &username, &password, - &(cand_pair->tid)); - } - } - - return 0; -} - -#if 0 -static int -_ice_get_localip_for (struct sockaddr_storage *saddr, size_t saddr_len, char *loc, int size) -{ - int err, tmp; - int sock; - struct sockaddr_storage addr; - socklen_t addr_len; - - strcpy (loc, "127.0.0.1"); /* always fallback to local loopback */ - - sock = socket (saddr->ss_family, SOCK_DGRAM, 0); - tmp = 1; - err = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &tmp, sizeof (int)); - if (err < 0) - { - ms_error("ice.c: Error in setsockopt"); - closesocket (sock); - return -1; - } - err = connect (sock, (struct sockaddr*)saddr, saddr_len); - if (err < 0) - { - ms_error("ice.c: Error in connect"); - closesocket (sock); - return -1; - } - addr_len = sizeof (addr); - err = getsockname (sock, (struct sockaddr *) &addr, (socklen_t*)&addr_len); - if (err != 0) - { - ms_error("ice.c: Error in getsockname"); - closesocket (sock); - return -1; - } - - err = getnameinfo ((struct sockaddr *) &addr, addr_len, loc, size, NULL, 0, NI_NUMERICHOST); - if (err != 0) - { - ms_error("ice.c: Error in getnameinfo"); - closesocket (sock); - return -1; - } - closesocket (sock); - /* ms_message("ice.c: Outgoing interface for sending STUN answer is %s", loc); */ - return 0; -} - -#endif - -static void -_ice_createErrorResponse(StunMessage *response, int cl, int number, const char* msg) -{ - response->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_ERR_RESP); - response->hasErrorCode = TRUE; - response->errorCode.errorClass = cl; - response->errorCode.number = number; - strcpy(response->errorCode.reason, msg); - response->errorCode.sizeReason = strlen(msg); - response->hasFingerprint = TRUE; -} - -static int ice_process_stun_message(RtpSession *session, struct IceCheckList *checklist, OrtpEvent *evt) -{ - struct CandidatePair *remote_candidates = NULL; - StunMessage msg; - bool_t res; - int highest_priority_success=-1; - OrtpEventData *evt_data = ortp_event_get_data(evt); - mblk_t *mp = evt_data->packet; - struct sockaddr_in *udp_remote; - char src6host[NI_MAXHOST]; - int recvport = 0; - int i; - - udp_remote = (struct sockaddr_in*)&evt_data->ep->addr; - - memset( &msg, 0 , sizeof(msg) ); - res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr, &msg); - if (!res) - { - ms_error("ice.c: Malformed STUN packet."); - return -1; - } - - if (checklist==NULL) - { - ms_error("ice.c: dropping STUN packet: ice is not configured"); - return -1; - } - - remote_candidates = checklist->cand_pairs; - if (remote_candidates==NULL) - { - ms_error("ice.c: dropping STUN packet: ice is not configured"); - return -1; - } - - /* prepare ONCE tie-break value */ - if (checklist->tiebreak_value==0) { - checklist->tiebreak_value = random() * (0x7fffffffffffffffLL/0x7fff); - } - - memset (src6host, 0, sizeof (src6host)); - - { - struct sockaddr_storage *aaddr = (struct sockaddr_storage *)&evt_data->ep->addr; - if (aaddr->ss_family==AF_INET) - recvport = ntohs (((struct sockaddr_in *) udp_remote)->sin_port); - else - recvport = ntohs (((struct sockaddr_in6 *) &evt_data->ep->addr)->sin6_port); - } - i = getnameinfo ((struct sockaddr*)&evt_data->ep->addr, evt_data->ep->addrlen, - src6host, NI_MAXHOST, - NULL, 0, NI_NUMERICHOST); - if (i != 0) - { - ms_error("ice.c: Error with getnameinfo"); - return -1; - } - - if (STUN_IS_REQUEST(msg.msgHdr.msgType)) - ms_message("ice.c: STUN_CONNECTIVITYCHECK: Request received from: %s:%i", - src6host, recvport); - else if (STUN_IS_INDICATION(msg.msgHdr.msgType)) - ms_message("ice.c: SUN_INDICATION: Request Indication received from: %s:%i", - src6host, recvport); - else - ms_message("ice.c: STUN_ANSWER: Answer received from: %s:%i", - src6host, recvport); - - { - int pos; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - struct CandidatePair *cand_pair = &remote_candidates[pos]; - - if (cand_pair->connectivity_check == ICE_SUCCEEDED) - { - highest_priority_success=pos; - break; - } - } - } - - if (STUN_IS_INDICATION(msg.msgHdr.msgType)) - { - ms_message("ice.c: STUN INDICATION <- (?:?:? <- %s:%i:?)", src6host, recvport); - return 0; - } - else if (STUN_IS_REQUEST(msg.msgHdr.msgType)) - { - StunMessage resp; - StunAtrString hmacPassword; - StunAddress4 remote_addr; - int rtp_socket; - - memset( &resp, 0 , sizeof(resp)); - remote_addr.addr = ntohl(udp_remote->sin_addr.s_addr); - remote_addr.port = ntohs(udp_remote->sin_port); - - rtp_socket = rtp_session_get_rtp_socket(session); - - resp.msgHdr.magic_cookie = ntohl(msg.msgHdr.magic_cookie); - for (i=0; i<12; i++ ) - { - resp.msgHdr.tr_id.octet[i] = msg.msgHdr.tr_id.octet[i]; - } - - /* check mandatory params */ - - if (!msg.hasUsername) - { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- Missing USERNAME attribute in connectivity check"); - _ice_createErrorResponse(&resp, 4, 32, "Missing USERNAME attribute"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - if (!msg.hasMessageIntegrity) - { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- Missing MESSAGEINTEGRITY attribute in connectivity check"); - _ice_createErrorResponse(&resp, 4, 1, "Missing MESSAGEINTEGRITY attribute"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - - /* - The password associated with that transport address ID is used to verify - the MESSAGE-INTEGRITY attribute, if one was present in the request. - */ - { - char hmac[20]; - /* remove length of fingerprint if present */ - if (msg.hasFingerprint==TRUE) - { - char *lenpos = (char *)mp->b_rptr + sizeof(uint16_t); - uint16_t newlen = htons(msg.msgHdr.msgLength-8); /* remove fingerprint size */ - memcpy(lenpos, &newlen, sizeof(uint16_t)); - stunCalculateIntegrity_shortterm(hmac, (char*)mp->b_rptr, mp->b_wptr-mp->b_rptr-24-8, checklist->loc_ice_pwd); - } - else - stunCalculateIntegrity_shortterm(hmac, (char*)mp->b_rptr, mp->b_wptr-mp->b_rptr-24, checklist->loc_ice_pwd); - if (memcmp(msg.messageIntegrity.hash, hmac, 20)!=0) - { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- Wrong MESSAGEINTEGRITY attribute in connectivity check"); - _ice_createErrorResponse(&resp, 4, 1, "Wrong MESSAGEINTEGRITY attribute"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - if (msg.hasFingerprint==TRUE) - { - char *lenpos = (char *)mp->b_rptr + sizeof(uint16_t); - uint16_t newlen = htons(msg.msgHdr.msgLength); /* add back fingerprint size */ - memcpy(lenpos, &newlen, sizeof(uint16_t)); - } - } - - - /* 7.2.1.1. Detecting and Repairing Role Conflicts */ - /* TODO */ - if (!msg.hasIceControlling && !msg.hasIceControlled) - { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- Missing either ICE-CONTROLLING or ICE-CONTROLLED attribute"); - _ice_createErrorResponse(&resp, 4, 87, "Missing either ICE-CONTROLLING or ICE-CONTROLLED attribute"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - - if (checklist->rem_controlling==0 && msg.hasIceControlling) { - /* If the agent's tie-breaker is larger than or equal - to the contents of the ICE-CONTROLLING attribute - -> send 487, and do not change ROLE */ - if (checklist->tiebreak_value >= msg.iceControlling.value) { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- 487 Role Conflict"); - _ice_createErrorResponse(&resp, 4, 87, "Role Conflict"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - else { - int pos; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - /* controller agent */ - uint64_t G = remote_candidates[pos].remote_candidate.priority; - /* controlled agent */ - uint64_t D = remote_candidates[pos].local_candidate.priority; - remote_candidates[pos].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - checklist->rem_controlling = 1; - /* reset all to initial WAITING state? */ - ms_message("ice.c: STUN REQ <- tiebreaker -> reset all to ICE_WAITING state"); - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (remote_candidates[pos].connectivity_check == ICE_PRUNED) - continue; - remote_candidates[pos].connectivity_check = ICE_WAITING; - memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid)); - remote_candidates[pos].retransmission_time = 0; - remote_candidates[pos].retransmission_number = 0; - } - } - } - - if (checklist->rem_controlling==1 && msg.hasIceControlled) { - - /* If the agent's tie-breaker is larger than or equal - to the contents of the ICE-CONTROLLED attribute - -> change ROLE */ - if (checklist->tiebreak_value >= msg.iceControlled.value) { - int pos; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - /* controller agent */ - uint64_t G = remote_candidates[pos].local_candidate.priority; - /* controlled agent */ - uint64_t D = remote_candidates[pos].remote_candidate.priority; - remote_candidates[pos].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - checklist->rem_controlling = 0; - /* reset all to initial WAITING state? */ - ms_message("ice.c: STUN REQ <- tiebreaker -> reset all to ICE_WAITING state"); - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (remote_candidates[pos].connectivity_check == ICE_PRUNED) - continue; - remote_candidates[pos].connectivity_check = ICE_WAITING; - memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid)); - remote_candidates[pos].retransmission_time = 0; - remote_candidates[pos].retransmission_number = 0; - } - } - else { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - ms_error("ice.c: STUN REQ <- 487 Role Conflict"); - _ice_createErrorResponse(&resp, 4, 87, "Role Conflict"); - len = stunEncodeMessage(&resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - return -1; - } - } - - { - struct CandidatePair *cand_pair; - int pos; - cand_pair=NULL; - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - /* connectivity check is coming from a known remote candidate? - we should also check the port... - */ - if (strcmp(cand_pair->remote_candidate.conn_addr, src6host)==0 - && cand_pair->remote_candidate.conn_port==recvport) - { - ms_message("ice.c: STUN REQ (%s) <- %i (%s:%i:%s <- %s:%i:%s) from known peer", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type); - if (cand_pair->connectivity_check==ICE_FROZEN - || cand_pair->connectivity_check==ICE_IN_PROGRESS - || cand_pair->connectivity_check==ICE_FAILED) - { - cand_pair->connectivity_check = ICE_WAITING; - if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0) - cand_pair->nominated_pair = 1; - } - else if (cand_pair->connectivity_check==ICE_SUCCEEDED) - { - if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0) - { - cand_pair->nominated_pair = 1; - - /* USE-CANDIDATE is in STUN request and we already succeeded on that link */ - ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen); - session->rtp.rem_addrlen=evt_data->ep->addrlen; - } - } - break; - } - cand_pair=NULL; - } - if (cand_pair==NULL) - { - struct CandidatePair new_pair; - memset(&new_pair, 0, sizeof(struct CandidatePair)); - - ms_message("ice.c: STUN REQ <- connectivity check received from an unknow candidate (%s:%i)", src6host, recvport); - /* TODO: add the peer-reflexive candidate */ - - memcpy(&new_pair.local_candidate, &remote_candidates[0].local_candidate, sizeof(new_pair.local_candidate)); - - new_pair.remote_candidate.foundation = 6; - new_pair.remote_candidate.component_id = remote_candidates[0].remote_candidate.component_id; - - /* -> no known base address for peer */ - - new_pair.remote_candidate.conn_port = recvport; - snprintf(new_pair.remote_candidate.conn_addr, sizeof(new_pair.remote_candidate.conn_addr), - "%s", src6host); - - /* take it from PRIORITY STUN attr */ - new_pair.remote_candidate.priority = msg.priority.priority; - if (new_pair.remote_candidate.priority==0) - { - uint32_t type_preference = 110; - uint32_t interface_preference = 255; - uint32_t stun_priority=255; - new_pair.remote_candidate.priority = (type_preference << 24) | (interface_preference << 16) | (stun_priority << 8) - | (256 - new_pair.remote_candidate.component_id); - } - - snprintf(new_pair.remote_candidate.cand_type, sizeof(cand_pair->remote_candidate.cand_type), - "prflx"); - snprintf (new_pair.remote_candidate.transport, - sizeof (new_pair.remote_candidate.transport), - "UDP"); - - if (checklist->rem_controlling==0) - { - uint64_t G = new_pair.local_candidate.priority; - /* controlled agent */ - uint64_t D = new_pair.remote_candidate.priority; - new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - else - { - uint64_t G = new_pair.remote_candidate.priority; - /* controlled agent */ - uint64_t D = new_pair.local_candidate.priority; - new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - new_pair.connectivity_check = ICE_WAITING; - /* insert new pair candidate */ - if (msg.hasUseCandidate==TRUE && checklist->rem_controlling==0) - { - new_pair.nominated_pair = 1; - } - - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (pos==9) - { - ms_message("ice.c: STUN REQ (%s) <- X (%s:%i:%s <- %s:%i:%s) no room for new remote reflexive candidate", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - new_pair.local_candidate.conn_addr, - new_pair.local_candidate.conn_port, - new_pair.local_candidate.cand_type, - new_pair.remote_candidate.conn_addr, - new_pair.remote_candidate.conn_port, - new_pair.remote_candidate.cand_type); - break; - } - if (new_pair.pair_priority > remote_candidates[pos].pair_priority) - { - /* move upper data */ - memmove(&remote_candidates[pos+1], &remote_candidates[pos], sizeof(struct CandidatePair)*(10-pos-1)); - memcpy(&remote_candidates[pos], &new_pair, sizeof(struct CandidatePair)); - - if (checklist->nominated_pair_index>=pos) - checklist->nominated_pair_index++; - ms_message("ice.c: STUN REQ (%s) <- %i (%s:%i:%s <- %s:%i:%s) new learned remote reflexive candidate", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos, - new_pair.local_candidate.conn_addr, - new_pair.local_candidate.conn_port, - new_pair.local_candidate.cand_type, - new_pair.remote_candidate.conn_addr, - new_pair.remote_candidate.conn_port, - new_pair.remote_candidate.cand_type); - break; - } - } - } - } - - { - uint32_t cookie = 0x2112A442; - resp.hasXorMappedAddress = TRUE; - resp.xorMappedAddress.ipv4.port = remote_addr.port^(cookie>>16); - resp.xorMappedAddress.ipv4.addr = remote_addr.addr^cookie; - } - - resp.msgHdr.msgType = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP); - - resp.hasUsername = TRUE; - memcpy(resp.username.value, msg.username.value, msg.username.sizeValue ); - resp.username.sizeValue = msg.username.sizeValue; - - /* ? any messageintegrity in response? */ - resp.hasMessageIntegrity = TRUE; - - { - const char serverName[] = "mediastreamer2 " STUN_VERSION; - resp.hasSoftware = TRUE; - memcpy( resp.softwareName.value, serverName, sizeof(serverName)); - resp.softwareName.sizeValue = sizeof(serverName); - } - - resp.hasFingerprint = TRUE; - - { - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = sizeof(buf); - len = stunEncodeMessage( &resp, buf, len, &hmacPassword ); - if (len) - sendMessage( rtp_socket, buf, len, remote_addr.addr, remote_addr.port); - } - } - else if (STUN_IS_SUCCESS_RESP(msg.msgHdr.msgType)) - { - /* set state to RECV-VALID or VALID */ - StunMessage resp; - StunAddress4 mappedAddr; - memset(&resp, 0, sizeof(StunMessage)); - res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr, - &resp ); - if (!res) - { - ms_error("ice.c: STUN RESP <- Bad format for STUN answer."); - return -1; - } - - if (resp.hasXorMappedAddress!=TRUE) - { - ms_error("ice.c: STUN RESP <- Missing XOR-MAPPED-ADDRESS in STUN answer."); - return -1; - } - - { - uint32_t cookie = 0x2112A442; - uint16_t cookie16 = 0x2112A442 >> 16; - mappedAddr.port = resp.xorMappedAddress.ipv4.port^cookie16; - mappedAddr.addr = resp.xorMappedAddress.ipv4.addr^cookie; - } - - { - struct in_addr inaddr; - char mapped_addr[64]; - struct CandidatePair *cand_pair=NULL; - int pos; - inaddr.s_addr = htonl (mappedAddr.addr); - snprintf(mapped_addr, sizeof(mapped_addr), - "%s", inet_ntoa (inaddr)); - - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - cand_pair = &remote_candidates[pos]; - - if (memcmp(&(cand_pair->tid), &(resp.msgHdr.tr_id), sizeof(resp.msgHdr.tr_id))==0) - { - break; - } - cand_pair = NULL; - } - - if (cand_pair==NULL) - { - ms_message("ice.c: STUN RESP (%s) <- no transaction for STUN answer?", - msg.hasUseCandidate==0?"":"USE-CANDIDATE"); - } - else if (strcmp(src6host, cand_pair->remote_candidate.conn_addr)!=0 - || recvport!=cand_pair->remote_candidate.conn_port) - { - /* 7.1.2.2. Success Cases - -> must be a security issue: refuse non-symmetric answer */ - ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s nominated=%s) refused because non-symmetric", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - cand_pair->connectivity_check = ICE_FAILED; - } - else - { - /* Youhouhouhou */ - ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s nominated=%s)", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - if (cand_pair->connectivity_check != ICE_SUCCEEDED) - { - if (checklist->rem_controlling==1 && cand_pair->nominated_pair>0) - { - /* USE-CANDIDATE was in previous STUN request sent */ - ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen); - session->rtp.rem_addrlen=evt_data->ep->addrlen; - } - - if (cand_pair->nominated_pair>0 && checklist->rem_controlling==0) - { - /* USE-CANDIDATE is in STUN request and we already succeeded on that link */ - ms_message("ice.c: ICE CONCLUDED == %i (%s:%i:%s <- %s:%i:%s nominated=%s)", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type, - cand_pair->nominated_pair==0?"FALSE":"TRUE"); - memcpy(&session->rtp.rem_addr, &evt_data->ep->addr, evt_data->ep->addrlen); - session->rtp.rem_addrlen=evt_data->ep->addrlen; - } - - cand_pair->connectivity_check = ICE_FAILED; - if (mappedAddr.port == cand_pair->local_candidate.conn_port - && strcmp(mapped_addr, cand_pair->local_candidate.conn_addr)==0) - { - /* no peer-reflexive candidate was discovered */ - cand_pair->connectivity_check = ICE_SUCCEEDED; - } - else - { - int pos2; - for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++) - { - if (mappedAddr.port == remote_candidates[pos2].local_candidate.conn_port - && strcmp(mapped_addr, remote_candidates[pos2].local_candidate.conn_addr)==0 - && cand_pair->remote_candidate.conn_port == remote_candidates[pos2].remote_candidate.conn_port - && strcmp(cand_pair->remote_candidate.conn_addr, remote_candidates[pos2].remote_candidate.conn_addr)==0) - { - if (remote_candidates[pos2].connectivity_check==ICE_PRUNED - ||remote_candidates[pos2].connectivity_check==ICE_FROZEN - ||remote_candidates[pos2].connectivity_check==ICE_FAILED - || remote_candidates[pos2].connectivity_check==ICE_IN_PROGRESS) - remote_candidates[pos2].connectivity_check = ICE_WAITING; /* trigger check */ - /* - ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) found candidate pair matching XOR-MAPPED-ADDRESS", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos, - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->local_candidate.cand_type, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port, - cand_pair->remote_candidate.cand_type); - */ - break; - } - } - if (pos2==10 || remote_candidates[pos2].remote_candidate.conn_addr[0]=='\0') - { - struct CandidatePair new_pair; - memset(&new_pair, 0, sizeof(struct CandidatePair)); - - /* 7.1.2.2.1. Discovering Peer Reflexive Candidates */ - /* If IP & port were different than mappedAddr, there was A NAT - between me and remote destination. */ - memcpy(&new_pair.remote_candidate, &cand_pair->remote_candidate, sizeof(new_pair.remote_candidate)); - - new_pair.local_candidate.foundation = 6; - new_pair.local_candidate.component_id = cand_pair->local_candidate.component_id; - - /* what is my base address? */ - new_pair.local_candidate.rel_port = cand_pair->local_candidate.conn_port; - snprintf(new_pair.local_candidate.rel_addr, sizeof(new_pair.local_candidate.rel_addr), - "%s", cand_pair->local_candidate.conn_addr); - - new_pair.local_candidate.conn_port = mappedAddr.port; - snprintf(new_pair.local_candidate.conn_addr, sizeof(new_pair.local_candidate.conn_addr), - "%s", mapped_addr); - - new_pair.remote_candidate.priority = (110 << 24) | (255 << 16) | (255 << 8) - | (256 - new_pair.remote_candidate.component_id); - - snprintf(new_pair.local_candidate.cand_type, sizeof(cand_pair->local_candidate.cand_type), - "prflx"); - snprintf (new_pair.local_candidate.transport, - sizeof (new_pair.local_candidate.transport), - "UDP"); - - if (checklist->rem_controlling==0) - { - uint64_t G = new_pair.local_candidate.priority; - /* controlled agent */ - uint64_t D = new_pair.remote_candidate.priority; - new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - else - { - uint64_t G = new_pair.remote_candidate.priority; - /* controlled agent */ - uint64_t D = new_pair.local_candidate.priority; - new_pair.pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - new_pair.connectivity_check = ICE_WAITING; - /* insert new pair candidate */ - for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++) - { - if (pos2==9) - { - ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) no room for new local peer-reflexive candidate", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos2, - new_pair.local_candidate.conn_addr, - new_pair.local_candidate.conn_port, - new_pair.local_candidate.cand_type, - new_pair.remote_candidate.conn_addr, - new_pair.remote_candidate.conn_port, - new_pair.remote_candidate.cand_type); - break; - } - if (new_pair.pair_priority > remote_candidates[pos2].pair_priority) - { - /* move upper data */ - memmove(&remote_candidates[pos2+1], &remote_candidates[pos2], sizeof(struct CandidatePair)*(10-pos2-1)); - memcpy(&remote_candidates[pos2], &new_pair, sizeof(struct CandidatePair)); - - if (checklist->nominated_pair_index>=pos2) - checklist->nominated_pair_index++; - ms_message("ice.c: STUN RESP (%s) <- %i (%s:%i:%s <- %s:%i:%s) new discovered local peer-reflexive candidate", - msg.hasUseCandidate==0?"":"USE-CANDIDATE", - pos2, - new_pair.local_candidate.conn_addr, - new_pair.local_candidate.conn_port, - new_pair.local_candidate.cand_type, - new_pair.remote_candidate.conn_addr, - new_pair.remote_candidate.conn_port, - new_pair.remote_candidate.cand_type); - break; - } - } - } - } - } - } - } - } - else if (STUN_IS_ERR_RESP(msg.msgHdr.msgType)) - { - int pos; - StunMessage resp; - memset(&resp, 0, sizeof(StunMessage)); - res = stunParseMessage((char*)mp->b_rptr, mp->b_wptr-mp->b_rptr, - &resp ); - if (!res) - { - ms_error("ice.c: ERROR_RESPONSE: Bad format for STUN answer."); - return -1; - } - - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - struct CandidatePair *cand_pair = &remote_candidates[pos]; - - if (memcmp(&(cand_pair->tid), &(resp.msgHdr.tr_id), sizeof(resp.msgHdr.tr_id))==0) - { - cand_pair->connectivity_check = ICE_FAILED; - ms_message("ice.c: ERROR_RESPONSE: ICE_FAILED for candidate pair! %s:%i -> %s:%i", - cand_pair->local_candidate.conn_addr, - cand_pair->local_candidate.conn_port, - cand_pair->remote_candidate.conn_addr, - cand_pair->remote_candidate.conn_port); - if (resp.hasErrorCode==TRUE && resp.errorCode.errorClass==4 && resp.errorCode.number==87) - { - if (remote_candidates[pos].rem_controlling==1) - { - int pos2; - for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++) - { - /* controller agent */ - uint64_t G = remote_candidates[pos2].local_candidate.priority; - /* controlled agent */ - uint64_t D = remote_candidates[pos2].remote_candidate.priority; - remote_candidates[pos2].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - checklist->rem_controlling=0; - } - else - { - int pos2; - for (pos2=0;pos2<10 && remote_candidates[pos2].remote_candidate.conn_addr[0]!='\0';pos2++) - { - /* controller agent */ - uint64_t G = remote_candidates[pos2].remote_candidate.priority; - /* controlled agent */ - uint64_t D = remote_candidates[pos2].local_candidate.priority; - remote_candidates[pos2].pair_priority = (MIN(G, D))<<32 | (MAX(G, D))<<1 | (G>D?1:0); - } - checklist->rem_controlling=1; - } - /* reset all to initial WAITING state? */ - ms_message("ice.c: ERROR_RESPONSE: 487 -> reset all to ICE_WAITING state"); - for (pos=0;pos<10 && remote_candidates[pos].remote_candidate.conn_addr[0]!='\0';pos++) - { - if (remote_candidates[pos].connectivity_check == ICE_PRUNED) - continue; - remote_candidates[pos].connectivity_check = ICE_WAITING; - memset(&remote_candidates[pos].tid , 0, sizeof(remote_candidates[pos].tid)); - remote_candidates[pos].retransmission_time = 0; - remote_candidates[pos].retransmission_number = 0; - } - } - } - } - } - - return 0; -} - - - - -struct IceData { - RtpSession *session; - OrtpEvQueue *ortp_event; - struct IceCheckList *check_lists; /* table of 10 cpair */ - int rate; -}; - -typedef struct IceData IceData; - -static void ice_init(MSFilter * f) -{ - IceData *d = (IceData *)ms_new(IceData, 1); - - d->ortp_event = ortp_ev_queue_new(); - d->session = NULL; - d->check_lists = NULL; - d->rate = 8000; - f->data = d; -} - -static void ice_postprocess(MSFilter * f) -{ - IceData *d = (IceData *) f->data; - if (d->session!=NULL && d->ortp_event!=NULL) - rtp_session_unregister_event_queue(d->session, d->ortp_event); -} - -static void ice_uninit(MSFilter * f) -{ - IceData *d = (IceData *) f->data; - if (d->ortp_event!=NULL) - ortp_ev_queue_destroy(d->ortp_event); - ms_free(f->data); -} - -static int ice_set_session(MSFilter * f, void *arg) -{ - IceData *d = (IceData *) f->data; - RtpSession *s = (RtpSession *) arg; - PayloadType *pt = rtp_profile_get_payload(rtp_session_get_profile(s), - rtp_session_get_recv_payload_type - (s)); - if (pt != NULL) { - if (strcasecmp("g722", pt->mime_type)==0 ) - d->rate=8000; - else d->rate = pt->clock_rate; - } else { - ms_warning("Receiving undefined payload type ?"); - } - d->session = s; - - return 0; -} - -static int ice_set_sdpcandidates(MSFilter * f, void *arg) -{ - IceData *d = (IceData *) f->data; - struct IceCheckList *scs = NULL; - - if (d == NULL) - return -1; - - scs = (struct IceCheckList *) arg; - d->check_lists = scs; - ice_restart(d->check_lists); - return 0; -} - -static void ice_preprocess(MSFilter * f){ - IceData *d = (IceData *) f->data; - if (d->session!=NULL && d->ortp_event!=NULL) - rtp_session_register_event_queue(d->session, d->ortp_event); -} - -static void ice_process(MSFilter * f) -{ - IceData *d = (IceData *) f->data; - - if (d->session == NULL) - return; - - /* check received STUN request */ - if (d->ortp_event!=NULL) - { - OrtpEvent *evt = ortp_ev_queue_get(d->ortp_event); - - while (evt != NULL) { - if (ortp_event_get_type(evt) == - ORTP_EVENT_STUN_PACKET_RECEIVED) { - ice_process_stun_message(d->session, d->check_lists, evt); - } - if (ortp_event_get_type(evt) == - ORTP_EVENT_TELEPHONE_EVENT) { - } - - ortp_event_destroy(evt); - evt = ortp_ev_queue_get(d->ortp_event); - } - } - - ice_sound_send_stun_request(d->session, d->check_lists, f->ticker->time); -} - -static MSFilterMethod ice_methods[] = { - {MS_ICE_SET_SESSION, ice_set_session}, - {MS_ICE_SET_CANDIDATEPAIRS, ice_set_sdpcandidates}, - {0, NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_ice_desc = { - MS_ICE_ID, - "MSIce", - N_("ICE filter"), - MS_FILTER_OTHER, - NULL, - 0, - 0, - ice_init, - ice_preprocess, - ice_process, - ice_postprocess, - ice_uninit, - ice_methods -}; - -#else - -MSFilterDesc ms_ice_desc = { - .id = MS_ICE_ID, - .name = "MSIce", - .text = N_("ICE filter"), - .category = MS_FILTER_OTHER, - .ninputs = 0, - .noutputs = 0, - .init = ice_init, - .preprocess = ice_preprocess, - .process = ice_process, - .postprocess=ice_postprocess, - .uninit = ice_uninit, - .methods = ice_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_ice_desc) diff --git a/linphone/mediastreamer2/src/kiss_fft.c b/linphone/mediastreamer2/src/kiss_fft.c deleted file mode 100644 index 27c16085d..000000000 --- a/linphone/mediastreamer2/src/kiss_fft.c +++ /dev/null @@ -1,519 +0,0 @@ -/* -Copyright (c) 2003-2004, Mark Borgerding -Copyright (c) 2005-2007, Jean-Marc Valin - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. -*/ - - - -#include "_kiss_fft_guts.h" - - -/* The guts header contains all the multiplication and addition macros that are defined for - fixed or floating point complex numbers. It also delares the kf_ internal functions. - */ - -static void kf_bfly2( - kiss_fft_cpx * Fout, - const size_t fstride, - const kiss_fft_cfg st, - int m, - int N, - int mm - ) -{ - kiss_fft_cpx * Fout2; - kiss_fft_cpx * tw1; - kiss_fft_cpx t; - if (!st->inverse) { - int i,j; - kiss_fft_cpx * Fout_beg = Fout; - for (i=0;itwiddles; - for(j=0;jr , tw1->r),MULT16_16(Fout2->i , tw1->i)), 1); - ti = SHR32(ADD32(MULT16_16(Fout2->i , tw1->r),MULT16_16(Fout2->r , tw1->i)), 1); - tw1 += fstride; - Fout2->r = PSHR32(SUB32(SHL32(EXTEND32(Fout->r), 14), tr), 15); - Fout2->i = PSHR32(SUB32(SHL32(EXTEND32(Fout->i), 14), ti), 15); - Fout->r = PSHR32(ADD32(SHL32(EXTEND32(Fout->r), 14), tr), 15); - Fout->i = PSHR32(ADD32(SHL32(EXTEND32(Fout->i), 14), ti), 15); - ++Fout2; - ++Fout; - } - } - } else { - int i,j; - kiss_fft_cpx * Fout_beg = Fout; - for (i=0;itwiddles; - for(j=0;jinverse) - { - kiss_fft_cpx * Fout_beg = Fout; - for (i=0;itwiddles; - for (j=0;jtwiddles; - for (j=0;jr = PSHR16(Fout->r, 2); - Fout->i = PSHR16(Fout->i, 2); - C_SUB( scratch[5] , *Fout, scratch[1] ); - C_ADDTO(*Fout, scratch[1]); - C_ADD( scratch[3] , scratch[0] , scratch[2] ); - C_SUB( scratch[4] , scratch[0] , scratch[2] ); - Fout[m2].r = PSHR16(Fout[m2].r, 2); - Fout[m2].i = PSHR16(Fout[m2].i, 2); - C_SUB( Fout[m2], *Fout, scratch[3] ); - tw1 += fstride; - tw2 += fstride*2; - tw3 += fstride*3; - C_ADDTO( *Fout , scratch[3] ); - - Fout[m].r = scratch[5].r + scratch[4].i; - Fout[m].i = scratch[5].i - scratch[4].r; - Fout[m3].r = scratch[5].r - scratch[4].i; - Fout[m3].i = scratch[5].i + scratch[4].r; - ++Fout; - } - } - } -} - -static void kf_bfly3( - kiss_fft_cpx * Fout, - const size_t fstride, - const kiss_fft_cfg st, - size_t m - ) -{ - size_t k=m; - const size_t m2 = 2*m; - kiss_fft_cpx *tw1,*tw2; - kiss_fft_cpx scratch[5]; - kiss_fft_cpx epi3; - epi3 = st->twiddles[fstride*m]; - - tw1=tw2=st->twiddles; - - do{ - if (!st->inverse) { - C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); - } - - C_MUL(scratch[1],Fout[m] , *tw1); - C_MUL(scratch[2],Fout[m2] , *tw2); - - C_ADD(scratch[3],scratch[1],scratch[2]); - C_SUB(scratch[0],scratch[1],scratch[2]); - tw1 += fstride; - tw2 += fstride*2; - - Fout[m].r = Fout->r - HALF_OF(scratch[3].r); - Fout[m].i = Fout->i - HALF_OF(scratch[3].i); - - C_MULBYSCALAR( scratch[0] , epi3.i ); - - C_ADDTO(*Fout,scratch[3]); - - Fout[m2].r = Fout[m].r + scratch[0].i; - Fout[m2].i = Fout[m].i - scratch[0].r; - - Fout[m].r -= scratch[0].i; - Fout[m].i += scratch[0].r; - - ++Fout; - }while(--k); -} - -static void kf_bfly5( - kiss_fft_cpx * Fout, - const size_t fstride, - const kiss_fft_cfg st, - int m - ) -{ - kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; - int u; - kiss_fft_cpx scratch[13]; - kiss_fft_cpx * twiddles = st->twiddles; - kiss_fft_cpx *tw; - kiss_fft_cpx ya,yb; - ya = twiddles[fstride*m]; - yb = twiddles[fstride*2*m]; - - Fout0=Fout; - Fout1=Fout0+m; - Fout2=Fout0+2*m; - Fout3=Fout0+3*m; - Fout4=Fout0+4*m; - - tw=st->twiddles; - for ( u=0; uinverse) { - C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5); - } - scratch[0] = *Fout0; - - C_MUL(scratch[1] ,*Fout1, tw[u*fstride]); - C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]); - C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]); - C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]); - - C_ADD( scratch[7],scratch[1],scratch[4]); - C_SUB( scratch[10],scratch[1],scratch[4]); - C_ADD( scratch[8],scratch[2],scratch[3]); - C_SUB( scratch[9],scratch[2],scratch[3]); - - Fout0->r += scratch[7].r + scratch[8].r; - Fout0->i += scratch[7].i + scratch[8].i; - - scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); - scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); - - scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); - scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); - - C_SUB(*Fout1,scratch[5],scratch[6]); - C_ADD(*Fout4,scratch[5],scratch[6]); - - scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); - scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); - scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); - scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); - - C_ADD(*Fout2,scratch[11],scratch[12]); - C_SUB(*Fout3,scratch[11],scratch[12]); - - ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; - } -} - -/* perform the butterfly for one stage of a mixed radix FFT */ -static void kf_bfly_generic( - kiss_fft_cpx * Fout, - const size_t fstride, - const kiss_fft_cfg st, - int m, - int p - ) -{ - int u,k,q1,q; - kiss_fft_cpx * twiddles = st->twiddles; - kiss_fft_cpx t; - kiss_fft_cpx scratchbuf[17]; - int Norig = st->nfft; - - /*CHECKBUF(scratchbuf,nscratchbuf,p);*/ - if (p>17) - ms_fatal("KissFFT: max radix supported is 17"); - - for ( u=0; uinverse) { - C_FIXDIV(scratchbuf[q1],p); - } - k += m; - } - - k=u; - for ( q1=0 ; q1

=Norig) twidx-=Norig; - C_MUL(t,scratchbuf[q] , twiddles[twidx] ); - C_ADDTO( Fout[ k ] ,t); - } - k += m; - } - } -} - -static -void kf_shuffle( - kiss_fft_cpx * Fout, - const kiss_fft_cpx * f, - const size_t fstride, - int in_stride, - int * factors, - const kiss_fft_cfg st - ) -{ - const int p=*factors++; /* the radix */ - const int m=*factors++; /* stage's fft length/p */ - - /*printf ("fft %d %d %d %d %d %d\n", p*m, m, p, s2, fstride*in_stride, N);*/ - if (m==1) - { - int j; - for (j=0;j32000 || (int32_t)p*(int32_t)p > n) - p = n; /* no more factors, skip to end */ - } - n /= p; - *facbuf++ = p; - *facbuf++ = n; - } while (n > 1); -} -/* - * - * User-callable function to allocate all necessary storage space for the fft. - * - * The return value is a contiguous block of memory, allocated with malloc. As such, - * It can be freed with free(), rather than a kiss_fft-specific function. - * */ -kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) -{ - kiss_fft_cfg st=NULL; - size_t memneeded = sizeof(struct kiss_fft_state) - + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ - - if ( lenmem==NULL ) { - st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); - }else{ - if (mem != NULL && *lenmem >= memneeded) - st = (kiss_fft_cfg)mem; - *lenmem = memneeded; - } - if (st) { - int i; - st->nfft=nfft; - st->inverse = inverse_fft; -#ifdef MS_FIXED_POINT - for (i=0;iinverse) - phase = -phase; - kf_cexp2(st->twiddles+i, DIV32(SHL32(phase,17),nfft)); - } -#else - for (i=0;iinverse) - phase *= -1; - kf_cexp(st->twiddles+i, phase ); - } -#endif - kf_factor(nfft,st->factors); - } - return st; -} - - - - -void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) -{ - if (fin == fout) - { - ms_fatal("In-place FFT not supported"); - /*CHECKBUF(tmpbuf,ntmpbuf,st->nfft); - kf_work(tmpbuf,fin,1,in_stride, st->factors,st); - SPEEX_MOVE(fout,tmpbuf,st->nfft);*/ - } else { - kf_shuffle( fout, fin, 1,in_stride, st->factors,st); - kf_work( fout, fin, 1,in_stride, st->factors,st, 1, in_stride, 1); - } -} - -void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) -{ - kiss_fft_stride(cfg,fin,fout,1); -} - diff --git a/linphone/mediastreamer2/src/kiss_fft.h b/linphone/mediastreamer2/src/kiss_fft.h deleted file mode 100644 index 9db74941d..000000000 --- a/linphone/mediastreamer2/src/kiss_fft.h +++ /dev/null @@ -1,114 +0,0 @@ -#ifndef KISS_FFT_H -#define KISS_FFT_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - ATTENTION! - If you would like a : - -- a utility that will handle the caching of fft objects - -- real-only (no imaginary time component ) FFT - -- a multi-dimensional FFT - -- a command-line utility to perform ffts - -- a command-line utility to perform fast-convolution filtering - - Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c - in the tools/ directory. -*/ - -#ifdef USE_SIMD -# include -# define kiss_fft_scalar __m128 -#define KISS_FFT_MALLOC(nbytes) memalign(16,nbytes) -#else -#define KISS_FFT_MALLOC ms_malloc -#endif - - -#ifdef MS_FIXED_POINT -# define kiss_fft_scalar short -#else -# ifndef kiss_fft_scalar -/* default is float */ -# define kiss_fft_scalar float -# endif -#endif - -typedef struct { - kiss_fft_scalar r; - kiss_fft_scalar i; -}kiss_fft_cpx; - -typedef struct kiss_fft_state* kiss_fft_cfg; - -/* add a prefix to these function to avoid collision with the ones defined in speex*/ -#define kiss_fft_alloc ms_kiss_fft_alloc -#define kiss_fft ms_kiss_fft -#define kiss_fft_stride ms_kiss_fft_stride -#define kiss_fft_cleanup ms_kiss_fft_cleanup - - -/* - * kiss_fft_alloc - * - * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. - * - * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); - * - * The return value from fft_alloc is a cfg buffer used internally - * by the fft routine or NULL. - * - * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. - * The returned value should be free()d when done to avoid memory leaks. - * - * The state can be placed in a user supplied buffer 'mem': - * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, - * then the function places the cfg in mem and the size used in *lenmem - * and returns mem. - * - * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), - * then the function returns NULL and places the minimum cfg - * buffer size in *lenmem. - * */ - -kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); - -/* - * kiss_fft(cfg,in_out_buf) - * - * Perform an FFT on a complex input bufferb. - * for a forward FFT, - * fin should be f[0] , f[1] , ... ,f[nfft-1] - * fout will be F[0] , F[1] , ... ,F[nfft-1] - * Note that each element is complex and can be accessed like - f[k].r and f[k].i - * */ -void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); - -/* - A more generic version of the above function. It reads its input from every Nth sample. - * */ -void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); - -/* If kiss_fft_alloc allocated a buffer, it is one contiguous - buffer and can be simply free()d when no longer needed*/ -#define kiss_fft_free ms_free - -/* - Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up - your compiler output to call this before you exit. -*/ -void kiss_fft_cleanup(void); - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/mediastreamer2/src/kiss_fftr.c b/linphone/mediastreamer2/src/kiss_fftr.c deleted file mode 100644 index a8ab42a64..000000000 --- a/linphone/mediastreamer2/src/kiss_fftr.c +++ /dev/null @@ -1,294 +0,0 @@ -/* -Copyright (c) 2003-2004, Mark Borgerding - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. -*/ - - - -#include "kiss_fftr.h" -#include "_kiss_fft_guts.h" - -struct kiss_fftr_state{ - kiss_fft_cfg substate; - kiss_fft_cpx * tmpbuf; - kiss_fft_cpx * super_twiddles; -#ifdef USE_SIMD - long pad; -#endif -}; - -kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem) -{ - int i; - kiss_fftr_cfg st = NULL; - size_t subsize, memneeded; - - if (nfft & 1) { - ms_warning("Real FFT optimization must be even"); - return NULL; - } - nfft >>= 1; - - kiss_fft_alloc (nfft, inverse_fft, NULL, &subsize); - memneeded = sizeof(struct kiss_fftr_state) + subsize + sizeof(kiss_fft_cpx) * ( nfft * 2); - - if (lenmem == NULL) { - st = (kiss_fftr_cfg) KISS_FFT_MALLOC (memneeded); - } else { - if (*lenmem >= memneeded) - st = (kiss_fftr_cfg) mem; - *lenmem = memneeded; - } - if (!st) - return NULL; - - st->substate = (kiss_fft_cfg) (st + 1); /*just beyond kiss_fftr_state struct */ - st->tmpbuf = (kiss_fft_cpx *) (((char *) st->substate) + subsize); - st->super_twiddles = st->tmpbuf + nfft; - kiss_fft_alloc(nfft, inverse_fft, st->substate, &subsize); - -#ifdef MS_FIXED_POINT - for (i=0;i>1); - if (!inverse_fft) - phase = -phase; - kf_cexp2(st->super_twiddles+i, DIV32(SHL32(phase,16),nfft)); - } -#else - for (i=0;isuper_twiddles+i, phase ); - } -#endif - return st; -} - -void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata) -{ - /* input buffer timedata is stored row-wise */ - int k,ncfft; - kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc; - - if ( st->substate->inverse) { - ms_fatal("kiss fft usage error: improper alloc\n"); - } - - ncfft = st->substate->nfft; - - /*perform the parallel fft of two real signals packed in real,imag*/ - kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf ); - /* The real part of the DC element of the frequency spectrum in st->tmpbuf - * contains the sum of the even-numbered elements of the input time sequence - * The imag part is the sum of the odd-numbered elements - * - * The sum of tdc.r and tdc.i is the sum of the input time sequence. - * yielding DC of input time sequence - * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... - * yielding Nyquist bin of input time sequence - */ - - tdc.r = st->tmpbuf[0].r; - tdc.i = st->tmpbuf[0].i; - C_FIXDIV(tdc,2); - CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i); - CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i); - freqdata[0].r = tdc.r + tdc.i; - freqdata[ncfft].r = tdc.r - tdc.i; -#ifdef USE_SIMD - freqdata[ncfft].i = freqdata[0].i = _mm_set1_ps(0); -#else - freqdata[ncfft].i = freqdata[0].i = 0; -#endif - - for ( k=1;k <= ncfft/2 ; ++k ) { - fpk = st->tmpbuf[k]; - fpnk.r = st->tmpbuf[ncfft-k].r; - fpnk.i = - st->tmpbuf[ncfft-k].i; - C_FIXDIV(fpk,2); - C_FIXDIV(fpnk,2); - - C_ADD( f1k, fpk , fpnk ); - C_SUB( f2k, fpk , fpnk ); - C_MUL( tw , f2k , st->super_twiddles[k]); - - freqdata[k].r = HALF_OF(f1k.r + tw.r); - freqdata[k].i = HALF_OF(f1k.i + tw.i); - freqdata[ncfft-k].r = HALF_OF(f1k.r - tw.r); - freqdata[ncfft-k].i = HALF_OF(tw.i - f1k.i); - } -} - -void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata, kiss_fft_scalar *timedata) -{ - /* input buffer timedata is stored row-wise */ - int k, ncfft; - - if (st->substate->inverse == 0) { - ms_fatal("kiss fft usage error: improper alloc\n"); - } - - ncfft = st->substate->nfft; - - st->tmpbuf[0].r = freqdata[0].r + freqdata[ncfft].r; - st->tmpbuf[0].i = freqdata[0].r - freqdata[ncfft].r; - /*C_FIXDIV(st->tmpbuf[0],2);*/ - - for (k = 1; k <= ncfft / 2; ++k) { - kiss_fft_cpx fk, fnkc, fek, fok, tmp; - fk = freqdata[k]; - fnkc.r = freqdata[ncfft - k].r; - fnkc.i = -freqdata[ncfft - k].i; - /*C_FIXDIV( fk , 2 ); - C_FIXDIV( fnkc , 2 );*/ - - C_ADD (fek, fk, fnkc); - C_SUB (tmp, fk, fnkc); - C_MUL (fok, tmp, st->super_twiddles[k]); - C_ADD (st->tmpbuf[k], fek, fok); - C_SUB (st->tmpbuf[ncfft - k], fek, fok); -#ifdef USE_SIMD - st->tmpbuf[ncfft - k].i *= _mm_set1_ps(-1.0); -#else - st->tmpbuf[ncfft - k].i *= -1; -#endif - } - kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata); -} - -void kiss_fftr2(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_scalar *freqdata) -{ - /* input buffer timedata is stored row-wise */ - int k,ncfft; - kiss_fft_cpx f2k,tdc; - ms_word32_t f1kr, f1ki, twr, twi; - - if ( st->substate->inverse) { - ms_fatal("kiss fft usage error: improper alloc\n"); - } - - ncfft = st->substate->nfft; - - /*perform the parallel fft of two real signals packed in real,imag*/ - kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf ); - /* The real part of the DC element of the frequency spectrum in st->tmpbuf - * contains the sum of the even-numbered elements of the input time sequence - * The imag part is the sum of the odd-numbered elements - * - * The sum of tdc.r and tdc.i is the sum of the input time sequence. - * yielding DC of input time sequence - * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... - * yielding Nyquist bin of input time sequence - */ - - tdc.r = st->tmpbuf[0].r; - tdc.i = st->tmpbuf[0].i; - C_FIXDIV(tdc,2); - CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i); - CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i); - freqdata[0] = tdc.r + tdc.i; - freqdata[2*ncfft-1] = tdc.r - tdc.i; - - for ( k=1;k <= ncfft/2 ; ++k ) - { - /*fpk = st->tmpbuf[k]; - fpnk.r = st->tmpbuf[ncfft-k].r; - fpnk.i = - st->tmpbuf[ncfft-k].i; - C_FIXDIV(fpk,2); - C_FIXDIV(fpnk,2); - - C_ADD( f1k, fpk , fpnk ); - C_SUB( f2k, fpk , fpnk ); - - C_MUL( tw , f2k , st->super_twiddles[k]); - - freqdata[2*k-1] = HALF_OF(f1k.r + tw.r); - freqdata[2*k] = HALF_OF(f1k.i + tw.i); - freqdata[2*(ncfft-k)-1] = HALF_OF(f1k.r - tw.r); - freqdata[2*(ncfft-k)] = HALF_OF(tw.i - f1k.i); - */ - - /*f1k.r = PSHR32(ADD32(EXTEND32(st->tmpbuf[k].r), EXTEND32(st->tmpbuf[ncfft-k].r)),1); - f1k.i = PSHR32(SUB32(EXTEND32(st->tmpbuf[k].i), EXTEND32(st->tmpbuf[ncfft-k].i)),1); - f2k.r = PSHR32(SUB32(EXTEND32(st->tmpbuf[k].r), EXTEND32(st->tmpbuf[ncfft-k].r)),1); - f2k.i = SHR32(ADD32(EXTEND32(st->tmpbuf[k].i), EXTEND32(st->tmpbuf[ncfft-k].i)),1); - - C_MUL( tw , f2k , st->super_twiddles[k]); - - freqdata[2*k-1] = HALF_OF(f1k.r + tw.r); - freqdata[2*k] = HALF_OF(f1k.i + tw.i); - freqdata[2*(ncfft-k)-1] = HALF_OF(f1k.r - tw.r); - freqdata[2*(ncfft-k)] = HALF_OF(tw.i - f1k.i); - */ - f2k.r = SHR32(SUB32(EXTEND32(st->tmpbuf[k].r), EXTEND32(st->tmpbuf[ncfft-k].r)),1); - f2k.i = PSHR32(ADD32(EXTEND32(st->tmpbuf[k].i), EXTEND32(st->tmpbuf[ncfft-k].i)),1); - - f1kr = SHL32(ADD32(EXTEND32(st->tmpbuf[k].r), EXTEND32(st->tmpbuf[ncfft-k].r)),13); - f1ki = SHL32(SUB32(EXTEND32(st->tmpbuf[k].i), EXTEND32(st->tmpbuf[ncfft-k].i)),13); - - twr = SHR32(SUB32(MULT16_16(f2k.r,st->super_twiddles[k].r),MULT16_16(f2k.i,st->super_twiddles[k].i)), 1); - twi = SHR32(ADD32(MULT16_16(f2k.i,st->super_twiddles[k].r),MULT16_16(f2k.r,st->super_twiddles[k].i)), 1); - -#ifdef MS_FIXED_POINT - freqdata[2*k-1] = PSHR32(f1kr + twr, 15); - freqdata[2*k] = PSHR32(f1ki + twi, 15); - freqdata[2*(ncfft-k)-1] = PSHR32(f1kr - twr, 15); - freqdata[2*(ncfft-k)] = PSHR32(twi - f1ki, 15); -#else - freqdata[2*k-1] = .5f*(f1kr + twr); - freqdata[2*k] = .5f*(f1ki + twi); - freqdata[2*(ncfft-k)-1] = .5f*(f1kr - twr); - freqdata[2*(ncfft-k)] = .5f*(twi - f1ki); - -#endif - } -} - -void kiss_fftri2(kiss_fftr_cfg st,const kiss_fft_scalar *freqdata,kiss_fft_scalar *timedata) -{ - /* input buffer timedata is stored row-wise */ - int k, ncfft; - - if (st->substate->inverse == 0) { - ms_fatal ("kiss fft usage error: improper alloc\n"); - } - - ncfft = st->substate->nfft; - - st->tmpbuf[0].r = freqdata[0] + freqdata[2*ncfft-1]; - st->tmpbuf[0].i = freqdata[0] - freqdata[2*ncfft-1]; - /*C_FIXDIV(st->tmpbuf[0],2);*/ - - for (k = 1; k <= ncfft / 2; ++k) { - kiss_fft_cpx fk, fnkc, fek, fok, tmp; - fk.r = freqdata[2*k-1]; - fk.i = freqdata[2*k]; - fnkc.r = freqdata[2*(ncfft - k)-1]; - fnkc.i = -freqdata[2*(ncfft - k)]; - /*C_FIXDIV( fk , 2 ); - C_FIXDIV( fnkc , 2 );*/ - - C_ADD (fek, fk, fnkc); - C_SUB (tmp, fk, fnkc); - C_MUL (fok, tmp, st->super_twiddles[k]); - C_ADD (st->tmpbuf[k], fek, fok); - C_SUB (st->tmpbuf[ncfft - k], fek, fok); -#ifdef USE_SIMD - st->tmpbuf[ncfft - k].i *= _mm_set1_ps(-1.0); -#else - st->tmpbuf[ncfft - k].i *= -1; -#endif - } - kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata); -} diff --git a/linphone/mediastreamer2/src/kiss_fftr.h b/linphone/mediastreamer2/src/kiss_fftr.h deleted file mode 100644 index 5f1650cfe..000000000 --- a/linphone/mediastreamer2/src/kiss_fftr.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef KISS_FTR_H -#define KISS_FTR_H - -#include "kiss_fft.h" -#ifdef __cplusplus -extern "C" { -#endif - -#define kiss_fftr_alloc ms_kiss_fftr_alloc -#define kiss_fftr ms_kiss_fftr -#define kiss_fftr2 ms_kiss_fftr2 -#define kiss_fftri ms_kiss_fftri -#define kiss_fftri2 ms_kiss_fftri2 - - -/* - - Real optimized version can save about 45% cpu time vs. complex fft of a real seq. - - - - */ - -typedef struct kiss_fftr_state *kiss_fftr_cfg; - - -kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); -/* - nfft must be even - - If you don't care to allocate space, use mem = lenmem = NULL -*/ - - -void kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); -/* - input timedata has nfft scalar points - output freqdata has nfft/2+1 complex points -*/ - -void kiss_fftr2(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_scalar *freqdata); - -void kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); - -void kiss_fftri2(kiss_fftr_cfg st,const kiss_fft_scalar *freqdata, kiss_fft_scalar *timedata); - -/* - input freqdata has nfft/2+1 complex points - output timedata has nfft scalar points -*/ - -#define kiss_fftr_free ms_free - -#ifdef __cplusplus -} -#endif -#endif diff --git a/linphone/mediastreamer2/src/macsnd.c b/linphone/mediastreamer2/src/macsnd.c deleted file mode 100644 index 102a9f4a7..000000000 --- a/linphone/mediastreamer2/src/macsnd.c +++ /dev/null @@ -1,710 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -/* this file is specifically distributed under a BSD license */ - -/** -* Copyright (C) 2007 Hiroki Mori (himori@users.sourceforge.net) -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * Neither the name of the nor the -* names of its contributors may be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY ``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 BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -**/ -#include -#include -#include - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" - -MSFilter *ms_ca_read_new(MSSndCard *card); -MSFilter *ms_ca_write_new(MSSndCard *card); - -typedef struct CAData{ - char *pcmdev; - char *mixdev; - AudioUnit caOutAudioUnit; - AudioUnit caInAudioUnit; - AudioStreamBasicDescription caOutASBD; - AudioStreamBasicDescription caInASBD; - AURenderCallbackStruct caOutRenderCallback; - AURenderCallbackStruct caInRenderCallback; - AudioConverterRef caOutConverter; - AudioConverterRef caInConverter; - int pcmfd; - int rate; - int bits; - ms_mutex_t mutex; - queue_t rq; - MSBufferizer * bufferizer; - bool_t read_started; - bool_t write_started; - bool_t stereo; - void *caSourceBuffer; - AudioBufferList *fAudioBuffer, *fMSBuffer; -} CAData; - -// Convenience function to dispose of our audio buffers -void DestroyAudioBufferList(AudioBufferList* list) -{ - UInt32 i; - - if(list) { - for(i = 0; i < list->mNumberBuffers; i++) { - if(list->mBuffers[i].mData) - free(list->mBuffers[i].mData); - } - free(list); - } -} - -// Convenience function to allocate our audio buffers -AudioBufferList *AllocateAudioBufferList(UInt32 numChannels, UInt32 size) -{ - AudioBufferList* list; - UInt32 i; - - list = (AudioBufferList*)calloc(1, sizeof(AudioBufferList) + numChannels * sizeof(AudioBuffer)); - if(list == NULL) - return NULL; - - list->mNumberBuffers = numChannels; - for(i = 0; i < numChannels; ++i) { - list->mBuffers[i].mNumberChannels = 1; - list->mBuffers[i].mDataByteSize = size; - list->mBuffers[i].mData = malloc(size); - if(list->mBuffers[i].mData == NULL) { - DestroyAudioBufferList(list); - return NULL; - } - } - return list; -} - -OSStatus writeACInputProc ( - AudioConverterRef inAudioConverter, - UInt32 *ioNumberDataPackets, - AudioBufferList *ioData, - AudioStreamPacketDescription **outDataPacketDescription, - void* inUserData) -{ - OSStatus err = noErr; - CAData *d=(CAData*)inUserData; - UInt32 packetSize = (d->bits / 8) * (d->stereo ? 2 : 1); -// ms_error("writeACInputProc %d", *ioNumberDataPackets); - - if(*ioNumberDataPackets) { - if(d->caSourceBuffer != NULL) { - free(d->caSourceBuffer); - d->caSourceBuffer = NULL; - } - - d->caSourceBuffer = (void *) calloc (1, *ioNumberDataPackets * packetSize); - - ioData->mBuffers[0].mData = d->caSourceBuffer; // tell the Audio Converter where it's source data is - - ms_mutex_lock(&d->mutex); - int readsize = ms_bufferizer_read(d->bufferizer,d->caSourceBuffer,*ioNumberDataPackets * packetSize); - ms_mutex_unlock(&d->mutex); - if(readsize != *ioNumberDataPackets * packetSize) { - /* ms_error("ms_bufferizer_read error request = %d result = %d", *ioNumberDataPackets * packetSize, readsize); */ - memset(d->caSourceBuffer, 0, *ioNumberDataPackets * packetSize); - ioData->mBuffers[0].mDataByteSize = *ioNumberDataPackets * packetSize; // tell the Audio Converter how much source data there is - } else { - ioData->mBuffers[0].mDataByteSize = readsize; // tell the Audio Converter how much source data there is - } - } - - return err; -} - -OSStatus readACInputProc (AudioConverterRef inAudioConverter, - UInt32* ioNumberDataPackets, - AudioBufferList* ioData, - AudioStreamPacketDescription** ioASPD, - void* inUserData) -{ - CAData *d=(CAData*)inUserData; - AudioBufferList* l_inputABL = d->fAudioBuffer; - UInt32 totalInputBufferSizeBytes = ((*ioNumberDataPackets) * sizeof (float)); - int counter = d->caInASBD.mChannelsPerFrame; - ioData->mNumberBuffers = d->caInASBD.mChannelsPerFrame; - - while (--counter >= 0) { - AudioBuffer* l_ioD_AB = &(ioData->mBuffers[counter]); - l_ioD_AB->mNumberChannels = 1; - l_ioD_AB->mData = (float*)(l_inputABL->mBuffers[counter].mData); - l_ioD_AB->mDataByteSize = totalInputBufferSizeBytes; - } - - return (noErr); -} - -OSStatus readRenderProc(void *inRefCon, - AudioUnitRenderActionFlags *inActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumFrames, - AudioBufferList *ioData) -{ - CAData *d=(CAData*)inRefCon; - OSStatus err = noErr; - - // Render into audio buffer - err = AudioUnitRender(d->caInAudioUnit, inActionFlags, inTimeStamp, inBusNumber, - inNumFrames, d->fAudioBuffer); - if(err != noErr) - ms_error("AudioUnitRender %d size = %d", err, d->fAudioBuffer->mBuffers[0].mDataByteSize); - - UInt32 AvailableOutputBytes = inNumFrames * sizeof (float); - UInt32 propertySize = sizeof (AvailableOutputBytes); - err = AudioConverterGetProperty (d->caInConverter, - kAudioConverterPropertyCalculateOutputBufferSize, - &propertySize, - &AvailableOutputBytes); - - if(err != noErr) - ms_error("AudioConverterGetProperty %d", err); - - UInt32 ActualOutputFrames = AvailableOutputBytes / sizeof (short); - err = AudioConverterFillComplexBuffer (d->caInConverter, - (AudioConverterComplexInputDataProc)(readACInputProc), - inRefCon, - &ActualOutputFrames, - d->fMSBuffer, - NULL); - if(err != noErr) - ms_error("readRenderProc:AudioConverterFillComplexBuffer %08x mNumberBuffers = %d", err, ioData->mNumberBuffers); - - mblk_t *rm=NULL; - rm=allocb(d->fMSBuffer->mBuffers[0].mDataByteSize,0); - memcpy(rm->b_wptr, d->fMSBuffer->mBuffers[0].mData, d->fMSBuffer->mBuffers[0].mDataByteSize); -// memset(rm->b_wptr, 0, d->fMSBuffer->mBuffers[0].mDataByteSize); - rm->b_wptr+=d->fMSBuffer->mBuffers[0].mDataByteSize; - ms_mutex_lock(&d->mutex); - putq(&d->rq,rm); - ms_mutex_unlock(&d->mutex); - rm=NULL; - - return err; -} - -OSStatus writeRenderProc(void *inRefCon, - AudioUnitRenderActionFlags *inActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumFrames, - AudioBufferList *ioData) -{ - OSStatus err= noErr; - void *inInputDataProcUserData=NULL; - CAData *d=(CAData*)inRefCon; - if(d->write_started != FALSE) { - AudioStreamPacketDescription* outPacketDescription = NULL; - err = AudioConverterFillComplexBuffer(d->caOutConverter, writeACInputProc, inRefCon, - &inNumFrames, ioData, outPacketDescription); - if(err != noErr) - ms_error("writeRenderProc:AudioConverterFillComplexBuffer err %08x %d", err, ioData->mNumberBuffers); - } - return err; -} - -static void ca_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent) -{ - CAData *d=(CAData*)card->data; -} - -static int ca_get_level(MSSndCard *card, MSSndCardMixerElem e) -{ - CAData *d=(CAData*)card->data; - return 0; -} - -static void ca_set_source(MSSndCard *card, MSSndCardCapture source) -{ - CAData *d=(CAData*)card->data; -} - -static void ca_init(MSSndCard *card){ - ms_debug("ca_init"); - OSStatus result; - UInt32 param; - AudioDeviceID fInputDeviceID; - CAData *d=ms_new(CAData,1); - - ComponentDescription desc; - - // Get Default Output audio unit - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_DefaultOutput; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - Component comp = FindNextComponent(NULL, &desc); - if (comp == NULL) return; - - result = OpenAComponent(comp, &d->caOutAudioUnit); - if(result != noErr) return; - - // Get Default Input audio unit - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_HALOutput; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - comp = FindNextComponent(NULL, &desc); - if (comp == NULL) return; - - result = OpenAComponent(comp, &d->caInAudioUnit); - if(result != noErr) return; - - AudioUnitInitialize(d->caOutAudioUnit); - AudioUnitInitialize(d->caInAudioUnit); - - UInt32 asbdsize = sizeof(AudioStreamBasicDescription); - memset((char *)&d->caOutASBD, 0, asbdsize); - memset((char *)&d->caInASBD, 0, asbdsize); - - // Setup Output audio unit - result = AudioUnitGetProperty (d->caOutAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - 0, - &d->caOutASBD, - &asbdsize); - ms_message("AudioUnitGetProperty %i %x", result, result); - result = AudioUnitSetProperty (d->caOutAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &d->caOutASBD, - asbdsize); - ms_message("AudioUnitSetProperty %i %x", result, result); - - // Setup Input audio unit - // Enable input on the AUHAL - param = 1; - result = AudioUnitSetProperty(d->caInAudioUnit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Input, - 1, - ¶m, - sizeof(UInt32)); - ms_message("AudioUnitSetProperty %i %x", result, result); - -// Select the default input device - param = sizeof(AudioDeviceID); - result = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, - ¶m, - &fInputDeviceID); - ms_message("AudioHardwareGetProperty %i %x", result, result); - - // Set the current device to the default input unit. - result = AudioUnitSetProperty(d->caInAudioUnit, - kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, - 0, - &fInputDeviceID, - sizeof(AudioDeviceID)); - ms_message("AudioUnitSetProperty %i %x", result, result); - - AudioStreamBasicDescription tmpASBD; - result = AudioUnitGetProperty (d->caInAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &tmpASBD, - &asbdsize); - ms_message("AudioUnitGetProperty %i %x", result, result); - - int fAudioChannels = 1; - d->caInASBD.mChannelsPerFrame = fAudioChannels; - d->caInASBD.mSampleRate = tmpASBD.mSampleRate; - d->caInASBD.mFormatID = kAudioFormatLinearPCM; - d->caInASBD.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | - kAudioFormatFlagIsNonInterleaved; - if (d->caInASBD.mFormatID == kAudioFormatLinearPCM && fAudioChannels == 1) - d->caInASBD.mFormatFlags &= ~kLinearPCMFormatFlagIsNonInterleaved; - d->caInASBD.mFormatFlags = kAudioFormatFlagIsFloat; - if (htonl(0x1234) == 0x1234) - d->caInASBD.mFormatFlags |= kAudioFormatFlagIsBigEndian; - d->caInASBD.mBitsPerChannel = sizeof(Float32) * 8; - d->caInASBD.mBytesPerFrame = d->caInASBD.mBitsPerChannel / 8; - d->caInASBD.mFramesPerPacket = 1; - d->caInASBD.mBytesPerPacket = d->caInASBD.mBytesPerFrame; - - result = AudioUnitSetProperty(d->caInAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - 1, - &d->caInASBD, - sizeof(AudioStreamBasicDescription)); - ms_message("AudioUnitGetProperty %i %x", result, result); - - d->caSourceBuffer=NULL; - - // Get the number of frames in the IO buffer(s) - param = sizeof(UInt32); - UInt32 fAudioSamples; - result = AudioUnitGetProperty(d->caInAudioUnit, - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Global, - 0, - &fAudioSamples, - ¶m); - if(result != noErr) - { - fprintf(stderr, "failed to get audio sample size\n"); - return; - } - // Allocate our low device audio buffers - d->fAudioBuffer = AllocateAudioBufferList(d->caInASBD.mChannelsPerFrame, - fAudioSamples * d->caInASBD.mBytesPerFrame); - if(d->fAudioBuffer == NULL) - { - fprintf(stderr, "failed to allocate buffers\n"); - return; - } - // Allocate our low device audio buffers - d->fMSBuffer = AllocateAudioBufferList(d->caInASBD.mChannelsPerFrame, - fAudioSamples * d->caInASBD.mBytesPerFrame); - if(d->fMSBuffer == NULL) - { - fprintf(stderr, "failed to allocate buffers\n"); - return; - } - - d->pcmdev=NULL; - d->mixdev=NULL; - d->pcmfd=-1; - d->read_started=FALSE; - d->write_started=FALSE; - d->bits=16; - d->rate=8000; - d->stereo=FALSE; - qinit(&d->rq); - d->bufferizer=ms_bufferizer_new(); - ms_mutex_init(&d->mutex,NULL); - card->data=d; -} - -static void ca_uninit(MSSndCard *card){ - CAData *d=(CAData*)card->data; - if (d->pcmdev!=NULL) ms_free(d->pcmdev); - if (d->mixdev!=NULL) ms_free(d->mixdev); - ms_bufferizer_destroy(d->bufferizer); - flushq(&d->rq,0); - ms_mutex_destroy(&d->mutex); - ms_free(d); -} - -static void ca_detect(MSSndCardManager *m); -static MSSndCard *ca_duplicate(MSSndCard *obj); - -MSSndCardDesc ca_card_desc={ - .driver_type="CA", - .detect=ca_detect, - .init=ca_init, - .set_level=ca_set_level, - .get_level=ca_get_level, - .set_capture=ca_set_source, - .set_control=NULL, - .get_control=NULL, - .create_reader=ms_ca_read_new, - .create_writer=ms_ca_write_new, - .uninit=ca_uninit, - .duplicate=ca_duplicate -}; - -static MSSndCard *ca_duplicate(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&ca_card_desc); - CAData *dcard=(CAData*)card->data; - CAData *dobj=(CAData*)obj->data; - dcard->pcmdev=ms_strdup(dobj->pcmdev); - dcard->mixdev=ms_strdup(dobj->mixdev); - card->name=ms_strdup(obj->name); - return card; -} - -static MSSndCard *ca_card_new(){ - MSSndCard *card=ms_snd_card_new(&ca_card_desc); - card->name=ms_strdup("Core Audio"); - return card; -} - -static void ca_detect(MSSndCardManager *m){ - ms_debug("ca_detect"); - MSSndCard *card=ca_card_new(); - ms_snd_card_manager_add_card(m,card); -} - -static void ca_start_r(MSSndCard *card){ - OSStatus err= noErr; - CAData *d=(CAData*)card->data; - ms_debug("ca_start_r"); - - if (d->read_started==FALSE){ - AudioStreamBasicDescription outASBD; - outASBD = d->caInASBD; - outASBD.mSampleRate = d->rate; - outASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; - if (htonl(0x1234) == 0x1234) - outASBD.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; - outASBD.mBytesPerPacket = (d->bits / 8) * outASBD.mChannelsPerFrame; - outASBD.mBytesPerFrame = (d->bits / 8) * outASBD.mChannelsPerFrame; - outASBD.mFramesPerPacket = 1; - outASBD.mBitsPerChannel = d->bits; - - err = AudioConverterNew( &d->caInASBD, &outASBD, &d->caInConverter); - if(err != noErr) - ms_error("AudioConverterNew %x %d", err, outASBD.mBytesPerFrame); - else - CAShow(d->caInConverter); - - d->caInRenderCallback.inputProc = readRenderProc; - d->caInRenderCallback.inputProcRefCon = d; - err = AudioUnitSetProperty(d->caInAudioUnit, - kAudioOutputUnitProperty_SetInputCallback, - kAudioUnitScope_Global, - 0, - &d->caInRenderCallback, - sizeof(AURenderCallbackStruct)); - - if(AudioOutputUnitStart(d->caInAudioUnit) == noErr) - d->read_started = TRUE; - } -} - -static void ca_stop_r(MSSndCard *card){ - CAData *d=(CAData*)card->data; - OSErr err; - if(d->read_started == TRUE) { - if(AudioOutputUnitStop(d->caInAudioUnit) == noErr) - d->read_started=FALSE; - } -} - -static void ca_start_w(MSSndCard *card){ - OSStatus err= noErr; - ms_debug("ca_start_w"); - CAData *d=(CAData*)card->data; - if (d->write_started==FALSE){ - AudioStreamBasicDescription inASBD; - inASBD = d->caOutASBD; - inASBD.mSampleRate = d->rate; - inASBD.mFormatID = kAudioFormatLinearPCM; - // http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/Reference/reference.html - inASBD.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; - if (htonl(0x1234) == 0x1234) - inASBD.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; - inASBD.mChannelsPerFrame = d->stereo ? 2 : 1; - inASBD.mBytesPerPacket = (d->bits / 8) * inASBD.mChannelsPerFrame; - inASBD.mBytesPerFrame = (d->bits / 8) * inASBD.mChannelsPerFrame; - inASBD.mFramesPerPacket = 1; - inASBD.mBitsPerChannel = d->bits; - - - err = AudioConverterNew( &inASBD, &d->caOutASBD, &d->caOutConverter); - if(err != noErr) - ms_error("AudioConverterNew %x %d", err, inASBD.mBytesPerFrame); - else - CAShow(d->caOutConverter); - - if (inASBD.mChannelsPerFrame == 1 && d->caOutASBD.mChannelsPerFrame == 2) - { - if (d->caOutConverter) - { - // This should be as large as the number of output channels, - // each element specifies which input channel's data is routed to that output channel - SInt32 channelMap[] = { 0, 0 }; - err = AudioConverterSetProperty(d->caOutConverter, kAudioConverterChannelMap, 2*sizeof(SInt32), channelMap); - } - } - - memset((char*)&d->caOutRenderCallback, 0, sizeof(AURenderCallbackStruct)); - d->caOutRenderCallback.inputProc = writeRenderProc; - d->caOutRenderCallback.inputProcRefCon = d; - err = AudioUnitSetProperty (d->caOutAudioUnit, - kAudioUnitProperty_SetRenderCallback, - kAudioUnitScope_Input, - 0, - &d->caOutRenderCallback, - sizeof(AURenderCallbackStruct)); - if(err != noErr) - ms_error("AudioUnitSetProperty %x", err); - - if(err == noErr) { - if(AudioOutputUnitStart(d->caOutAudioUnit) == noErr) - d->write_started=TRUE; - } - } -} - -static void ca_stop_w(MSSndCard *card){ - CAData *d=(CAData*)card->data; - OSErr err; - if(d->write_started == TRUE) { - if(AudioOutputUnitStop(d->caOutAudioUnit) == noErr) - d->write_started=FALSE; - } -} - -static mblk_t *ca_get(MSSndCard *card){ - CAData *d=(CAData*)card->data; - mblk_t *m; - ms_mutex_lock(&d->mutex); - m=getq(&d->rq); - ms_mutex_unlock(&d->mutex); - return m; -} - -static void ca_put(MSSndCard *card, mblk_t *m){ - CAData *d=(CAData*)card->data; - ms_mutex_lock(&d->mutex); - ms_bufferizer_put(d->bufferizer,m); - ms_mutex_unlock(&d->mutex); -} - - -static void ca_read_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - ca_start_r(card); -} - -static void ca_read_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - ca_stop_r(card); -} - -static void ca_read_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=ca_get(card))!=NULL){ - ms_queue_put(f->outputs[0],m); - } -} - -static void ca_write_preprocess(MSFilter *f){ - ms_debug("ca_write_preprocess"); - MSSndCard *card=(MSSndCard*)f->data; - ca_start_w(card); -} - -static void ca_write_postprocess(MSFilter *f){ - ms_debug("ca_write_postprocess"); - MSSndCard *card=(MSSndCard*)f->data; - ca_stop_w(card); -} - -static void ca_write_process(MSFilter *f){ -// ms_debug("ca_write_process"); - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - ca_put(card,m); - } -} - -static int set_rate(MSFilter *f, void *arg){ - ms_debug("set_rate %d", *((int*)arg)); - MSSndCard *card=(MSSndCard*)f->data; - CAData *d=(CAData*)card->data; - d->rate=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - ms_debug("set_nchannels %d", *((int*)arg)); - MSSndCard *card=(MSSndCard*)f->data; - CAData *d=(CAData*)card->data; - d->stereo=(*((int*)arg)==2); - return 0; -} - -static MSFilterMethod ca_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { 0 , NULL } -}; - -MSFilterDesc ca_read_desc={ - .id=MS_CA_READ_ID, - .name="MSCARead", - .text=N_("Sound capture filter for MacOS X Core Audio drivers"), - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .preprocess=ca_read_preprocess, - .process=ca_read_process, - .postprocess=ca_read_postprocess, - .methods=ca_methods -}; - - -MSFilterDesc ca_write_desc={ - .id=MS_CA_WRITE_ID, - .name="MSCAWrite", - .text=N_("Sound playback filter for MacOS X Core Audio drivers"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .preprocess=ca_write_preprocess, - .process=ca_write_process, - .postprocess=ca_write_postprocess, - .methods=ca_methods -}; - -MSFilter *ms_ca_read_new(MSSndCard *card){ - ms_debug("ms_ca_read_new"); - MSFilter *f=ms_filter_new_from_desc(&ca_read_desc); - f->data=card; - return f; -} - - -MSFilter *ms_ca_write_new(MSSndCard *card){ - ms_debug("ms_ca_write_new"); - MSFilter *f=ms_filter_new_from_desc(&ca_write_desc); - f->data=card; - return f; -} - -MS_FILTER_DESC_EXPORT(ca_read_desc) -MS_FILTER_DESC_EXPORT(ca_write_desc) diff --git a/linphone/mediastreamer2/src/mire.c b/linphone/mediastreamer2/src/mire.c deleted file mode 100644 index 27363ec20..000000000 --- a/linphone/mediastreamer2/src/mire.c +++ /dev/null @@ -1,164 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/mscommon.h" -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/mswebcam.h" - - -typedef struct _MireData{ - MSVideoSize vsize; - MSPicture pict; - int index; - uint64_t starttime; - float fps; - mblk_t *pic; -}MireData; - -void mire_init(MSFilter *f){ - MireData *d=(MireData*)ms_new(MireData,1); - d->vsize.width=MS_VIDEO_SIZE_CIF_W; - d->vsize.height=MS_VIDEO_SIZE_CIF_H; - d->fps=15; - d->index=0; - d->starttime=0; - d->pic=NULL; - f->data=d; -} - -void mire_uninit(MSFilter *f){ - ms_free(f->data); -} - -void mire_preprocess(MSFilter *f){ - MireData *d=(MireData*)f->data; - d->pic=yuv_buf_alloc(&d->pict,d->vsize.width,d->vsize.height); - memset(d->pic->b_rptr,0,d->pic->b_wptr-d->pic->b_rptr); - d->starttime=f->ticker->time; -} - -void plane_draw(uint8_t *p, int w, int h, int lsz, int index){ - int i,j; - for(i=0;ipict.planes[0],d->pict.w,d->pict.h,d->pict.strides[0],d->index*2); - plane_draw(d->pict.planes[1],d->pict.w/2,d->pict.h/2,d->pict.strides[1],d->index); - plane_draw(d->pict.planes[2],d->pict.w/2,d->pict.h/2,d->pict.strides[2],d->index); -} - -void mire_process(MSFilter *f){ - MireData *d=(MireData*)f->data; - float elapsed=(float)(f->ticker->time-d->starttime); - if ((elapsed*d->fps/1000.0)>d->index){ - mire_draw(d); - ms_queue_put(f->outputs[0],dupb(d->pic)); - d->index++; - } -} - -void mire_postprocess(MSFilter *f){ - MireData *d=(MireData*)f->data; - if (d->pic) { - freemsg(d->pic); - d->pic=NULL; - } -} - -int mire_set_vsize(MSFilter *f, void* data){ - MireData *d=(MireData*)f->data; - d->vsize=*(MSVideoSize*)data; - return 0; -} - -int mire_set_fps(MSFilter *f, void* data){ - MireData *d=(MireData*)f->data; - d->fps=*(float*)data; - return 0; -} - -int mire_get_fmt(MSFilter *f, void* data){ - *(MSPixFmt*)data=MS_YUV420P; - return 0; -} - -MSFilterMethod mire_methods[]={ - { MS_FILTER_SET_VIDEO_SIZE, mire_set_vsize }, - { MS_FILTER_SET_FPS , mire_set_fps }, - { MS_FILTER_GET_PIX_FMT , mire_get_fmt }, - { 0,0 } -}; - -MSFilterDesc ms_mire_desc={ - MS_MIRE_ID, - "MSMire", - "A filter that outputs synthetic moving picture", - MS_FILTER_OTHER, - NULL, - 0, - 1, - mire_init, - mire_preprocess, - mire_process, - mire_postprocess, - mire_uninit, - mire_methods -}; - -MS_FILTER_DESC_EXPORT(ms_mire_desc) - -static void mire_detect(MSWebCamManager *obj); - -static void mire_cam_init(MSWebCam *cam){ - cam->name=ms_strdup("Mire (synthetic moving picture)"); -} - - -static MSFilter *mire_create_reader(MSWebCam *obj){ - return ms_filter_new_from_desc(&ms_mire_desc); -} - -MSWebCamDesc mire_desc={ - "Mire", - &mire_detect, - &mire_cam_init, - &mire_create_reader, - NULL -}; - -static void mire_detect(MSWebCamManager *obj){ - char *debug=getenv("DEBUG"); - if (debug && atoi(debug)==1){ - MSWebCam *cam=ms_web_cam_new(&mire_desc); - ms_web_cam_manager_add_cam(obj,cam); - } -} - diff --git a/linphone/mediastreamer2/src/mscommon.c b/linphone/mediastreamer2/src/mscommon.c deleted file mode 100644 index 3138c3539..000000000 --- a/linphone/mediastreamer2/src/mscommon.c +++ /dev/null @@ -1,589 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -extern void __register_ffmpeg_encoders_if_possible(void); - -#include "mediastreamer2/mscommon.h" -#include "mediastreamer2/msfilter.h" - -#include "alldescs.h" -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/mswebcam.h" - -#if !defined(_WIN32_WCE) -#include -#endif -#ifndef WIN32 -#include -#else -#ifndef PACKAGE_PLUGINS_DIR -#if defined(WIN32) || defined(_WIN32_WCE) -#define PACKAGE_PLUGINS_DIR "plugins\\" -#else -#define PACKAGE_PLUGINS_DIR "." -#endif -#endif -#endif -#ifdef HAVE_DLOPEN -#include -#endif - -#if defined(__APPLE__) && !defined(__GNUC__) -#import -#include -#endif - -MSList *ms_list_new(void *data){ - MSList *new_elem=(MSList *)ms_new(MSList,1); - new_elem->prev=new_elem->next=NULL; - new_elem->data=data; - return new_elem; -} - -MSList * ms_list_append(MSList *elem, void * data){ - MSList *new_elem=ms_list_new(data); - MSList *it=elem; - if (elem==NULL) return new_elem; - while (it->next!=NULL) it=ms_list_next(it); - it->next=new_elem; - new_elem->prev=it; - return elem; -} - -MSList * ms_list_prepend(MSList *elem, void *data){ - MSList *new_elem=ms_list_new(data); - if (elem!=NULL) { - new_elem->next=elem; - elem->prev=new_elem; - } - return new_elem; -} - - -MSList * ms_list_concat(MSList *first, MSList *second){ - MSList *it=first; - if (it==NULL) return second; - while(it->next!=NULL) it=ms_list_next(it); - it->next=second; - second->prev=it; - return first; -} - -MSList * ms_list_free(MSList *list){ - MSList *elem = list; - MSList *tmp; - if (list==NULL) return NULL; - while(elem->next!=NULL) { - tmp = elem; - elem = elem->next; - ms_free(tmp); - } - ms_free(elem); - return NULL; -} - -MSList * ms_list_remove(MSList *first, void *data){ - MSList *it; - it=ms_list_find(first,data); - if (it) return ms_list_remove_link(first,it); - else { - ms_warning("ms_list_remove: no element with %p data was in the list", data); - return first; - } -} - -int ms_list_size(const MSList *first){ - int n=0; - while(first!=NULL){ - ++n; - first=first->next; - } - return n; -} - -void ms_list_for_each(const MSList *list, void (*func)(void *)){ - for(;list!=NULL;list=list->next){ - func(list->data); - } -} - -void ms_list_for_each2(const MSList *list, void (*func)(void *, void *), void *user_data){ - for(;list!=NULL;list=list->next){ - func(list->data,user_data); - } -} - -MSList *ms_list_remove_link(MSList *list, MSList *elem){ - MSList *ret; - if (elem==list){ - ret=elem->next; - elem->prev=NULL; - elem->next=NULL; - if (ret!=NULL) ret->prev=NULL; - ms_free(elem); - return ret; - } - elem->prev->next=elem->next; - if (elem->next!=NULL) elem->next->prev=elem->prev; - elem->next=NULL; - elem->prev=NULL; - ms_free(elem); - return list; -} - -MSList *ms_list_find(MSList *list, void *data){ - for(;list!=NULL;list=list->next){ - if (list->data==data) return list; - } - return NULL; -} - -MSList *ms_list_find_custom(MSList *list, int (*compare_func)(const void *, const void*), void *user_data){ - for(;list!=NULL;list=list->next){ - if (compare_func(list->data,user_data)==0) return list; - } - return NULL; -} - -void * ms_list_nth_data(const MSList *list, int index){ - int i; - for(i=0;list!=NULL;list=list->next,++i){ - if (i==index) return list->data; - } - ms_error("ms_list_nth_data: no such index in list."); - return NULL; -} - -int ms_list_position(const MSList *list, MSList *elem){ - int i; - for(i=0;list!=NULL;list=list->next,++i){ - if (elem==list) return i; - } - ms_error("ms_list_position: no such element in list."); - return -1; -} - -int ms_list_index(const MSList *list, void *data){ - int i; - for(i=0;list!=NULL;list=list->next,++i){ - if (data==list->data) return i; - } - ms_error("ms_list_index: no such element in list."); - return -1; -} - -MSList *ms_list_insert_sorted(MSList *list, void *data, int (*compare_func)(const void *, const void*)){ - MSList *it,*previt=NULL; - MSList *nelem; - MSList *ret=list; - if (list==NULL) return ms_list_append(list,data); - else{ - nelem=ms_list_new(data); - for(it=list;it!=NULL;it=it->next){ - previt=it; - if (compare_func(data,it->data)<=0){ - nelem->prev=it->prev; - nelem->next=it; - if (it->prev!=NULL) - it->prev->next=nelem; - else{ - ret=nelem; - } - it->prev=nelem; - return ret; - } - } - previt->next=nelem; - nelem->prev=previt; - } - return ret; -} - -MSList *ms_list_insert(MSList *list, MSList *before, void *data){ - MSList *elem; - if (list==NULL || before==NULL) return ms_list_append(list,data); - for(elem=list;elem!=NULL;elem=ms_list_next(elem)){ - if (elem==before){ - if (elem->prev==NULL) - return ms_list_prepend(list,data); - else{ - MSList *nelem=ms_list_new(data); - nelem->prev=elem->prev; - nelem->next=elem; - elem->prev->next=nelem; - elem->prev=nelem; - } - } - } - return list; -} - -MSList *ms_list_copy(const MSList *list){ - MSList *copy=NULL; - const MSList *iter; - for(iter=list;iter!=NULL;iter=ms_list_next(iter)){ - copy=ms_list_append(copy,iter->data); - } - return copy; -} - - -#ifdef __APPLE__ -#define PLUGINS_EXT ".dylib" -#else -#define PLUGINS_EXT ".so" -#endif - -typedef void (*init_func_t)(void); - -int ms_load_plugins(const char *dir){ - int num=0; -#if defined(WIN32) && !defined(_WIN32_WCE) - WIN32_FIND_DATA FileData; - HANDLE hSearch; - char szDirPath[1024]; - char szPluginFile[1024]; - BOOL fFinished = FALSE; - const char *tmp=getenv("DEBUG"); - BOOL debug=(tmp!=NULL && atoi(tmp)==1); - snprintf(szDirPath, sizeof(szDirPath), "%s", dir); - - // Start searching for .dll files in the current directory. - - snprintf(szDirPath, sizeof(szDirPath), "%s\\*.dll", dir); - hSearch = FindFirstFile(szDirPath, &FileData); - if (hSearch == INVALID_HANDLE_VALUE) - { - ms_message("no plugin (*.dll) found in %s.", szDirPath); - return 0; - } - snprintf(szDirPath, sizeof(szDirPath), "%s", dir); - - while (!fFinished) - { - /* load library */ - HINSTANCE os_handle; - UINT em; - if (!debug) em = SetErrorMode (SEM_FAILCRITICALERRORS); - - snprintf(szPluginFile, sizeof(szPluginFile), "%s\\%s", szDirPath, FileData.cFileName); - os_handle = LoadLibraryEx (szPluginFile, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); - if (os_handle==NULL) - { - ms_message("Fail to load plugin %s with altered search path: error %i",szPluginFile,GetLastError()); - os_handle = LoadLibraryEx (szPluginFile, NULL, 0); - } - if (!debug) SetErrorMode (em); - if (os_handle==NULL) - ms_error("Fail to load plugin %s", szPluginFile); - else{ - init_func_t initroutine; - char szPluginName[256]; - char szMethodName[256]; - char *minus; - snprintf(szPluginName, 256, "%s", FileData.cFileName); - /*on mingw, dll names might be libsomething-3.dll. We must skip the -X.dll stuff*/ - minus=strchr(szPluginName,'-'); - if (minus) *minus='\0'; - else szPluginName[strlen(szPluginName)-4]='\0'; /*remove .dll*/ - snprintf(szMethodName, 256, "%s_init", szPluginName); - initroutine = (init_func_t) GetProcAddress (os_handle, szMethodName); - if (initroutine!=NULL){ - initroutine(); - ms_message("Plugin loaded (%s)", szPluginFile); - num++; - }else{ - ms_warning("Could not locate init routine of plugin %s. Should be %s", - szPluginFile, szMethodName); - } - } - if (!FindNextFile(hSearch, &FileData)) { - if (GetLastError() == ERROR_NO_MORE_FILES){ - fFinished = TRUE; - } - else - { - ms_error("couldn't find next plugin dll."); - fFinished = TRUE; - } - } - } - /* Close the search handle. */ - FindClose(hSearch); - -#elif HAVE_DLOPEN - DIR *ds; - struct dirent *de; - char *fullpath; - ds=opendir(dir); - if (ds==NULL){ - ms_message("Cannot open directory %s: %s",dir,strerror(errno)); - return -1; - } - while( (de=readdir(ds))!=NULL){ - if ((de->d_type==DT_REG && strstr(de->d_name,PLUGINS_EXT)!=NULL) - || (de->d_type==DT_UNKNOWN && strstr(de->d_name,PLUGINS_EXT)==de->d_name+strlen(de->d_name)-strlen(PLUGINS_EXT))) { - void *handle; - fullpath=ms_strdup_printf("%s/%s",dir,de->d_name); - ms_message("Loading plugin %s...",fullpath); - - if ( (handle=dlopen(fullpath,RTLD_NOW))==NULL){ - ms_warning("Fail to load plugin %s : %s",fullpath,dlerror()); - }else { - char *initroutine_name=ms_malloc0(strlen(de->d_name)+10); - char *p; - void *initroutine=NULL; - strcpy(initroutine_name,de->d_name); - p=strstr(initroutine_name,PLUGINS_EXT); - if (p!=NULL){ - strcpy(p,"_init"); - initroutine=dlsym(handle,initroutine_name); - } - -#ifdef __APPLE__ - if (initroutine==NULL){ - /* on macosx: library name are libxxxx.1.2.3.dylib */ - /* -> MUST remove the .1.2.3 */ - p=strstr(initroutine_name,"."); - if (p!=NULL) - { - strcpy(p,"_init"); - initroutine=dlsym(handle,initroutine_name); - } - } -#endif - - if (initroutine!=NULL){ - init_func_t func=(init_func_t)initroutine; - func(); - ms_message("Plugin loaded (%s)", fullpath); - num++; - }else{ - ms_warning("Could not locate init routine of plugin %s",de->d_name); - } - ms_free(initroutine_name); - } - ms_free(fullpath); - } - } - closedir(ds); -#else - ms_warning("no loadable plugin support: plugins cannot be loaded."); - num=-1; -#endif - return num; -} - - -#ifdef __ALSA_ENABLED__ -extern MSSndCardDesc alsa_card_desc; -#endif - -#ifdef HAVE_SYS_SOUNDCARD_H -extern MSSndCardDesc oss_card_desc; -#endif - -#ifdef __ARTS_ENABLED__ -extern MSSndCardDesc arts_card_desc; -#endif - -#ifdef WIN32 -extern MSSndCardDesc winsnd_card_desc; -#endif - -#ifdef __DIRECTSOUND_ENABLED__ -extern MSSndCardDesc winsndds_card_desc; -#endif - -#ifdef __MACSND_ENABLED__ -extern MSSndCardDesc ca_card_desc; -#endif - -#ifdef __PORTAUDIO_ENABLED__ -extern MSSndCardDesc pasnd_card_desc; -#endif - -#ifdef __MAC_AQ_ENABLED__ -extern MSSndCardDesc aq_card_desc; -#endif - -static MSSndCardDesc * ms_snd_card_descs[]={ -#ifdef __ALSA_ENABLED__ - &alsa_card_desc, -#endif -#ifdef HAVE_SYS_SOUNDCARD_H - &oss_card_desc, -#endif -#ifdef __ARTS_ENABLED__ - &arts_card_desc, -#endif -#ifdef WIN32 - &winsnd_card_desc, -#endif -#ifdef __DIRECTSOUND_ENABLED__ - &winsndds_card_desc, -#endif -#ifdef __PORTAUDIO_ENABLED__ - &pasnd_card_desc, -#endif -#ifdef __MACSND_ENABLED__ - &ca_card_desc, -#endif -#ifdef __MAC_AQ_ENABLED__ - &aq_card_desc, -#endif - NULL -}; - -#ifdef VIDEO_ENABLED - -#ifdef __linux -extern MSWebCamDesc v4l_desc; -#endif - -#ifdef HAVE_LINUX_VIDEODEV2_H -extern MSWebCamDesc v4l2_card_desc; -#endif - -#ifdef WIN32 -extern MSWebCamDesc ms_vfw_cam_desc; -#endif -#if defined(WIN32) && defined(HAVE_DIRECTSHOW) -extern MSWebCamDesc ms_directx_cam_desc; -#endif - -#ifdef __MINGW32__ -extern MSWebCamDesc ms_dshow_cam_desc; -#endif - -#ifdef __APPLE__ -extern MSWebCamDesc ms_v4m_cam_desc; -#endif - -#if !defined(NO_FFMPEG) -extern MSWebCamDesc static_image_desc; -extern MSWebCamDesc mire_desc; -#endif - -static MSWebCamDesc * ms_web_cam_descs[]={ -#ifdef HAVE_LINUX_VIDEODEV2_H - &v4l2_card_desc, -#endif -#ifdef __linux - &v4l_desc, -#endif -#if defined(WIN32) && defined(HAVE_DIRECTSHOW) - &ms_directx_cam_desc, -#endif -#if defined(WIN32) && defined(HAVE_VFW) - &ms_vfw_cam_desc, -#endif -#ifdef __MINGW32__ - &ms_dshow_cam_desc, -#endif -#ifdef __APPLE__ - &ms_v4m_cam_desc, -#endif - -#if !defined(NO_FFMPEG) - &mire_desc, - &static_image_desc, -#endif - NULL -}; - -#endif - -void ms_init(){ - int i; - MSSndCardManager *cm; - -#if !defined(_WIN32_WCE) - if (getenv("MEDIASTREAMER_DEBUG")!=NULL){ - ortp_set_log_level_mask(ORTP_DEBUG|ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - } -#endif - ms_message("Registering all filters..."); - /* register builtin MSFilter's */ - for (i=0;ms_filter_descs[i]!=NULL;i++){ - ms_filter_register(ms_filter_descs[i]); - } - ms_message("Registering all soundcard handlers"); - cm=ms_snd_card_manager_get(); - for (i=0;ms_snd_card_descs[i]!=NULL;i++){ - ms_snd_card_manager_register_desc(cm,ms_snd_card_descs[i]); - } - -#ifdef VIDEO_ENABLED - ms_message("Registering all webcam handlers"); - { - MSWebCamManager *wm; - wm=ms_web_cam_manager_get(); - for (i=0;ms_web_cam_descs[i]!=NULL;i++){ - ms_web_cam_manager_register_desc(wm,ms_web_cam_descs[i]); - } - } -#if !defined(NO_FFMPEG) - __register_ffmpeg_encoders_if_possible(); -#endif -#endif - ms_message("Loading plugins"); - ms_load_plugins(PACKAGE_PLUGINS_DIR); - ms_message("ms_init() done"); -} - -void ms_exit(){ - ms_filter_unregister_all(); - ms_snd_card_manager_destroy(); -#ifdef VIDEO_ENABLED - ms_web_cam_manager_destroy(); -#endif -} - -void ms_sleep(int seconds){ -#ifdef WIN32 - Sleep(seconds*1000); -#else - struct timespec ts,rem; - int err; - ts.tv_sec=seconds; - ts.tv_nsec=0; - do { - err=nanosleep(&ts,&rem); - ts=rem; - }while(err==-1 && errno==EINTR); -#endif -} - -#define DEFAULT_MAX_PAYLOAD_SIZE 1440 - -static int max_payload_size=DEFAULT_MAX_PAYLOAD_SIZE; - -int ms_get_payload_max_size(){ - return max_payload_size; -} - -void ms_set_payload_max_size(int size){ - if (size<=0) size=DEFAULT_MAX_PAYLOAD_SIZE; - max_payload_size=size; -} diff --git a/linphone/mediastreamer2/src/msconf.c b/linphone/mediastreamer2/src/msconf.c deleted file mode 100644 index 46541fd98..000000000 --- a/linphone/mediastreamer2/src/msconf.c +++ /dev/null @@ -1,820 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msfilter.h" -#include - -#if defined(_WIN32_WCE) -#define DISABLE_SPEEX -#endif - -#ifndef HAVE_SPEEXDSP -#define DISABLE_SPEEX -#endif - -#ifndef DISABLE_SPEEX -#include -#endif - -#define CONF_NSAMPLES 160*4*4 /* (CONF_GRAN/2) */ -#ifndef CONF_MAX_PINS -#define CONF_MAX_PINS 128 -#endif - -static const float max_e=(float)32767*32767; -static const float coef=(float)0.01; - -typedef struct Channel{ - MSBufferizer buff; - int16_t input[CONF_NSAMPLES]; - bool_t has_contributed; - bool_t is_used; - - int is_speaking; - int count_speaking; - - int count; - int missed; - - int stat_discarded; - int stat_missed; - int stat_processed; - -#ifndef DISABLE_SPEEX - SpeexPreprocessState *speex_pp; -#endif - - float energy; - double average_psd; - -} Channel; - -typedef struct ConfState{ - Channel channels[CONF_MAX_PINS]; - int sum[CONF_NSAMPLES]; - int enable_directmode; - int enable_vad; - - int enable_halfduplex; - int vad_prob_start; - int vad_prob_continue; - - int agc_level; - int max_gain; - int mix_mode; - int samplerate; - - int adaptative_msconf_buf; - int conf_gran; - int conf_nsamples; -} ConfState; - - -static void channel_init(ConfState *s, Channel *chan, int pos){ -#ifndef DISABLE_SPEEX - float f; - int val; -#endif - memset(chan, 0, sizeof(Channel)); - ms_bufferizer_init(&chan->buff); -#ifndef DISABLE_SPEEX - chan->speex_pp = speex_preprocess_state_init(s->conf_gran/2, s->samplerate); - if (chan->speex_pp==NULL) - return; - - /* configure sound card input on pin 0 */ - val=0; - if (pos==0) - val=1; - - if (s->enable_halfduplex>0 && pos%2==1) - val=1; - - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_DENOISE, &val); - val = -30; - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &val); - - /* enable VAD only on incoming RTP stream */ - val=0; - if (pos%2==1 || (pos==0 && s->enable_halfduplex>0)) - { - val=1; - } - - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_VAD, &val); - if (s->vad_prob_start>0 && s->vad_prob_continue>0) - { - val = s->vad_prob_start; // xx% - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_PROB_START, &val); - val = s->vad_prob_continue; // xx% - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_PROB_CONTINUE, &val); - } - - /* enable AGC only on local soundcard */ - val=0; - f=12000; - if (s->agc_level>0 && pos==0) - val=1; - else if (pos==0 && s->enable_halfduplex>0) - val=1; - else if ( pos%2==1 && s->enable_halfduplex>0) - val=1; //1; should not do that - if (s->agc_level>0) - f=(float)s->agc_level; - - - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_AGC, &val); - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); - - val=s->max_gain; - if ( pos%2==1 && s->enable_halfduplex>0) - val=1; - - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &val); - - val=0; -#if 0 - val=1; // do more testing -#endif - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_DEREVERB, &val); - f=(float).4; - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=(float).3; - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - -#endif -} - -static void channel_uninit(Channel *chan){ - ms_bufferizer_uninit(&chan->buff); - chan->is_speaking=0; - chan->energy=0; - chan->average_psd=0; -#ifndef DISABLE_SPEEX - if (chan->speex_pp!=NULL) - speex_preprocess_state_destroy(chan->speex_pp); - chan->speex_pp=NULL; -#endif -} - -static void conf_init(MSFilter *f){ - ConfState *s=(ConfState *)ms_new0(ConfState,1); - int i; - s->samplerate=8000; - s->conf_gran=((16 * s->samplerate) / 800) *2; - s->conf_nsamples=s->conf_gran/2; - for (i=0;ichannels[i], i); - s->enable_directmode=FALSE; - s->enable_vad=TRUE; - s->agc_level=0; - s->max_gain=30; - s->mix_mode=TRUE; - s->adaptative_msconf_buf=2; - f->data=s; -} - -static void conf_uninit(MSFilter *f){ - ConfState *s=(ConfState*)f->data; - int i; - for (i=0;ichannels[i]); - ms_free(f->data); -} - -static void conf_preprocess(MSFilter *f){ - ConfState *s=(ConfState*)f->data; - int i; - for (i=0;ichannels[i].is_used=FALSE; - s->channels[i].missed=0; - s->channels[i].stat_discarded=0; - s->channels[i].stat_missed=0; - s->channels[i].stat_processed=0; - } -} - -static bool_t should_process(MSFilter *f, ConfState *s){ - Channel *chan; - int active_channel=0; - int i; - - if (ms_bufferizer_get_avail(&(&s->channels[0])->buff)>s->conf_gran - && s->channels[0].is_used==FALSE) - { - /* soundread has just started */ - s->channels[0].is_used=TRUE; - } - else if (s->channels[0].is_used==FALSE) - { - return FALSE; - } - - /* count active channel */ - for (i=1;ichannels[i]; - if (chan->is_used == TRUE) - { - active_channel++; - } - } - - if (active_channel<=1) /* disable mix mode when it's not needed */ - s->mix_mode = FALSE; - else - s->mix_mode = TRUE; - - if (s->enable_directmode==FALSE) - { - s->mix_mode = TRUE; - } - - if (s->mix_mode == FALSE) - return FALSE; - - if (ms_bufferizer_get_avail(&(&s->channels[0])->buff)>=s->conf_gran) - { - return TRUE; - } - return FALSE; -} - -#ifndef DISABLE_SPEEX -static double powerspectrum_stat_beyond8K(struct Channel *chan){ - spx_int32_t ps_size = 0; - spx_int32_t *ps = NULL; - double mystat = 0; - float fftmul = 1.0 / (32768.0); - int i; - - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_GET_PSD_SIZE, &ps_size); - ps = (spx_int32_t*)ortp_malloc(sizeof(spx_int32_t)*ps_size); - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_GET_PSD, ps); - - mystat = 0; - for (i=ps_size/2;i < ps_size; i++) { - double yp; -#if defined(__cplusplus) - yp = sqrtf(sqrtf(static_cast(ps[i]))) - 1.0f; -#else - yp = sqrtf(sqrtf((float)(ps[i]))) - 1.0f; -#endif - yp = yp * fftmul; - yp = MIN(yp * 3000.0, 1.0); - yp = (1 - yp) * (100 - 1.0f); - mystat = yp + mystat; - } - - mystat = (mystat*2)/ps_size; - - ortp_free(ps); - - /* values: - Maximum: 108,064 low volume on high frequency. - Decrease when volume increase. */ - - /* return value between 0 and 108,064? */ - mystat = 108.064-mystat; - - chan->average_psd=(mystat*mystat*coef) + (1.0-coef)*chan->average_psd; - //ms_message("average power spectrum on half highest values ONLY: stat=%.3lf", chan->average_psd); - - return mystat; -} -#endif - -static void conf_sum(MSFilter *f, ConfState *s){ - int i,j; - Channel *chan; - memset(s->sum,0,s->conf_nsamples*sizeof(int)); - - chan=&s->channels[0]; - if (s->adaptative_msconf_buf*s->conf_granbuff)) - { - i = ms_bufferizer_get_avail(&chan->buff)/s->conf_gran; - if (i>5) - ms_message("Increasing buffer because sound card is late. (nb_buf=%i /old=%i)", i, s->adaptative_msconf_buf); - s->adaptative_msconf_buf=i; - if (s->adaptative_msconf_buf>10) - { - while (ms_bufferizer_get_avail(&chan->buff)> s->conf_gran*6) - { - ms_bufferizer_read(&chan->buff,(uint8_t*)chan->input,s->conf_gran); - ms_message("Deleting extra sound card data %i", ms_bufferizer_get_avail(&chan->buff)); - } - } - } - else if (s->adaptative_msconf_buf*s->conf_gran>ms_bufferizer_get_avail(&chan->buff)) - { - if (s->adaptative_msconf_buf>3) - { - s->adaptative_msconf_buf--; - s->adaptative_msconf_buf=ms_bufferizer_get_avail(&chan->buff)/s->conf_gran; - //ms_message("decreasing buffer because sound card is in advance. (nb_buf=%i)", s->adaptative_msconf_buf); - } - } - - if (s->adaptative_msconf_buf>6) - s->adaptative_msconf_buf=6; - - for (i=0;ichannels[i]; - - /* skip soundread and short buffer entry */ - if (i>0 - && ms_bufferizer_get_avail(&chan->buff)> s->conf_gran - && ms_bufferizer_get_avail(&chan->buff)> (ms_bufferizer_get_avail(&s->channels[0].buff)+s->conf_gran*6) ) - { -#if 0 - int loudness; -#endif - while (ms_bufferizer_get_avail(&chan->buff)> s->conf_gran - && ms_bufferizer_get_avail(&chan->buff)> (ms_bufferizer_get_avail(&s->channels[0].buff)) ) - { - ms_bufferizer_read(&chan->buff,(uint8_t*)chan->input,s->conf_gran); -#if 0 - speex_preprocess_ctl(chan->speex_pp, SPEEX_PREPROCESS_GET_AGC_LOUDNESS, &loudness); -#endif - /* we want to remove 4 packets (40ms) in a near future: */ -#ifndef DISABLE_SPEEX - if (chan->speex_pp!=NULL && s->enable_vad==TRUE) - { - int vad=0; - vad = speex_preprocess(chan->speex_pp, (short*)chan->input, NULL); - if (vad==1) - break; /* voice detected: process as usual */ - if (ms_bufferizer_get_avail(&chan->buff)conf_gran) - break; /* no more data to remove */ - ms_message("No voice detected: discarding sample. (idx=%i - bufsize=%i sncardbufsize=%i)", - i, ms_bufferizer_get_avail(&chan->buff), ms_bufferizer_get_avail(&s->channels[0].buff)); - } - if (ms_bufferizer_get_avail(&chan->buff) == (ms_bufferizer_get_avail(&s->channels[0].buff))) - ms_message("same data in soundcard and incoming rtp. (idx=%i - bufsize=%i sncardbufsize=%i)", - i, ms_bufferizer_get_avail(&chan->buff), ms_bufferizer_get_avail(&s->channels[0].buff)); -#endif - chan->stat_discarded++; - } - - for(j=0;jconf_nsamples;++j){ - s->sum[j]+=chan->input[j]; - } - chan->has_contributed=TRUE; - - chan->stat_processed++; - } - else if (ms_bufferizer_get_avail(&chan->buff)>=s->conf_gran) - { - struct channel_volume { - float energy; - int channel; - }; - struct channel_volume vol; - float en; - - ms_bufferizer_read(&chan->buff,(uint8_t*)chan->input,s->conf_gran); - - en=chan->energy; - for(j=0;jconf_nsamples;++j){ - float s=chan->input[j]; - en=(s*s*coef) + ((float)1.0-coef)*en; - } - chan->energy=en; - vol.energy = chan->energy; //10*log10f(chan->energy/max_e); - vol.channel = i; - ms_filter_notify(f, MS_CONF_CHANNEL_VOLUME, (void*)&vol); - - if (i>0) /* not for MIC */ - { - if (chan->energy>65) - chan->count_speaking++; - else - chan->count_speaking=0; - } - -#ifndef DISABLE_SPEEX - if (chan->speex_pp!=NULL && s->enable_vad==TRUE && i==0) - { - int vad; - vad = speex_preprocess(chan->speex_pp, (short*)chan->input, NULL); - ms_filter_notify(f, MS_CONF_SPEEX_PREPROCESS_MIC, (void*)chan->speex_pp); - - if (s->enable_halfduplex>0) - { - powerspectrum_stat_beyond8K(chan); - if (chan->average_psd>s->vad_prob_start) - { - if (s->channels[0].is_speaking<0) - ms_message("MIC is turned on"); - //ms_message("is_speaking (chan=%i) -> on/stat=%.3lf", i, chan->average_psd); - s->channels[0].is_speaking=20; /* keep RTP unmuted for the next few ms */ - } - else if (chan->average_psdvad_prob_continue) - { - if (s->channels[0].is_speaking==0) - { - ms_message("MIC is turned off"); - s->channels[0].count_speaking=0; - } - s->channels[0].is_speaking--; - } - if (s->channels[0].is_speaking>0) - { - s->channels[0].count_speaking++; - } - } - } - else if (chan->speex_pp!=NULL && s->enable_vad==TRUE) - { - int vad; - - if (s->enable_halfduplex>0) - { - vad = speex_preprocess(chan->speex_pp, (short*)chan->input, NULL); - } - else - { - vad = speex_preprocess(chan->speex_pp, (short*)chan->input, NULL); - //speex_preprocess_estimate_update(chan->speex_pp, (short*)chan->input); - } - } -#endif - - for(j=0;jconf_nsamples;++j){ - s->sum[j]+=chan->input[j]; - } - chan->has_contributed=TRUE; - - chan->stat_processed++; - } else { - chan->stat_missed++; - if (i>0 && chan->is_used == TRUE) - { - chan->missed++; - /* delete stream if data is missing since a long time */ - if (chan->missed>15) - { - chan->is_used=FALSE; - ms_message("msconf: deleted contributing stream (pin=%i)", i); - } - /* couldn't we add confort noise for those outputs? */ - } - chan->has_contributed=FALSE; - } - } - return; -} - -static inline int16_t saturate(int sample){ - if (sample>32000) - sample=32000; - else if (sample<-32000) - sample=-32000; - return (int16_t)sample; -} - -static mblk_t * conf_output(ConfState *s, Channel *chan, int16_t attenuation){ - mblk_t *m=allocb(s->conf_gran,0); - int i; - int tmp; - if (chan->has_contributed==TRUE){ - for (i=0;iconf_nsamples;++i){ - tmp=s->sum[i]-(int)chan->input[i]; - *((int16_t*)m->b_wptr)=saturate(tmp)/attenuation; - m->b_wptr+=2; - } - }else{ - for (i=0;iconf_nsamples;++i){ - tmp=s->sum[i]; - *((int16_t*)m->b_wptr)=saturate(tmp)/attenuation; - m->b_wptr+=2; - } - } - return m; -} - -static void conf_dispatch(MSFilter *f, ConfState *s){ - int i; - Channel *chan; - mblk_t *m; - - for (i=0;ioutputs[i]!=NULL){ - chan=&s->channels[i]; - if (s->channels[0].is_speaking>0 // if MIC is speaking - && s->channels[0].count_speaking<75 // if MIC was silence a few time ago - && chan->count_speaking>0 // if RTP has started to talk - && chan->count_speaking<75 // if RTP was silence a few ms ago - && i%2==1) // false detection of MIC speaking - { - ms_message("false detection of MIC speaking: turned off"); - m=conf_output(s,chan, 32000); - } - else if (s->channels[0].is_speaking<0 && i%2==1) // MIC is NOT speaking -> send silence on RTP - m=conf_output(s,chan, 32000); - else - m=conf_output(s,chan, 1); - ms_queue_put(f->outputs[i],m); - } - } -} - -static void conf_process(MSFilter *f){ - int i; - ConfState *s=(ConfState*)f->data; - Channel *chan; - Channel *chan0; - /*read from all inputs and put into bufferizers*/ - for (i=0;iinputs[i]!=NULL){ - chan=&s->channels[i]; - ms_bufferizer_put_from_queue(&chan->buff,f->inputs[i]); - if (ms_bufferizer_get_avail(&chan->buff)>0) - { - chan->missed=0; /* reset counter of missed packet */ - if (i>0 && chan->is_used==FALSE) - { - chan->is_used=TRUE; - ms_message("msconf: new contributing stream (chan=%i) %i", ms_bufferizer_get_avail(&chan->buff), i); - } - } - } - } - - /*do the job */ - while(should_process(f,s)==TRUE){ - conf_sum(f, s); - conf_dispatch(f,s); - } - - /* mixer is disabled! -> copy A->B and B->A*/ - if (s->mix_mode == FALSE) - { - /* get the soundread data and copy it to pinX */ - for (i=1;iinputs[i]!=NULL){ - chan0=&s->channels[0]; - chan=&s->channels[i]; - if (chan->is_used==TRUE) - { - while (ms_bufferizer_read(&chan->buff,(uint8_t*)chan->input,s->conf_gran)==s->conf_gran) - { - if (f->outputs[0]!=NULL) - { - /* send in pin0 */ - mblk_t *m=allocb(s->conf_gran,0); - memcpy(m->b_wptr, chan->input, s->conf_gran); - m->b_wptr+=s->conf_gran; - ms_queue_put(f->outputs[0],m); - } - } - } - - if (chan0->is_used==TRUE) - { - while (ms_bufferizer_read(&chan0->buff,(uint8_t*)chan0->input,s->conf_gran)==s->conf_gran) - { - if (f->outputs[i]!=NULL) - { - /* send in pinI */ - mblk_t *m=allocb(s->conf_gran,0); - memcpy(m->b_wptr, chan0->input, s->conf_gran); - m->b_wptr+=s->conf_gran; - ms_queue_put(f->outputs[i],m); - } - } - } - break; - } - } - } - -} - -static void conf_postprocess(MSFilter *f){ - int i; - ConfState *s=(ConfState*)f->data; - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); -} - -static int msconf_set_sr(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - - s->samplerate = *(int*)arg; - s->conf_gran = ((16 * s->samplerate) / 800) *2; - s->conf_nsamples=s->conf_gran/2; - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_enable_directmode(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - s->enable_directmode = *(int*)arg; - return 0; -} - -static int msconf_enable_agc(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->agc_level = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_set_max_gain(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->max_gain = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - - -static int msconf_enable_halfduplex(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->enable_halfduplex = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_set_vad_prob_start(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->vad_prob_start = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_set_vad_prob_continue(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->vad_prob_continue = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_enable_vad(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - int i; - s->enable_vad = *(int*)arg; - - for (i=0;ichannels[i]); - for (i=0;ichannels[i], i); - return 0; -} - -static int msconf_get_stat_discarded(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - Channel *chan; - int i; - i = *(int*)arg; - /*read from all inputs and put into bufferizers*/ - if (i<0 || i>CONF_MAX_PINS) - return -1; - - if (f->inputs[i]!=NULL){ - chan=&s->channels[i]; - return chan->stat_discarded; - } - return -1; -} - -static int msconf_get_stat_missed(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - Channel *chan; - int i; - i = *(int*)arg; - /*read from all inputs and put into bufferizers*/ - if (i<0 || i>CONF_MAX_PINS) - return -1; - - if (f->inputs[i]!=NULL){ - chan=&s->channels[i]; - return chan->stat_missed; - } - return -1; -} - -static int msconf_get_stat_processed(MSFilter *f, void *arg){ - ConfState *s=(ConfState*)f->data; - Channel *chan; - int i; - i = *(int*)arg; - /*read from all inputs and put into bufferizers*/ - if (i<0 || i>CONF_MAX_PINS) - return -1; - - if (f->inputs[i]!=NULL){ - chan=&s->channels[i]; - return chan->stat_processed; - } - return -1; -} - -static MSFilterMethod msconf_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE, msconf_set_sr }, - { MS_FILTER_ENABLE_DIRECTMODE, msconf_enable_directmode }, - { MS_FILTER_ENABLE_VAD, msconf_enable_vad }, - { MS_FILTER_ENABLE_AGC, msconf_enable_agc }, - { MS_FILTER_SET_MAX_GAIN, msconf_set_max_gain }, - - { MS_FILTER_GET_STAT_DISCARDED, msconf_get_stat_discarded }, - { MS_FILTER_GET_STAT_MISSED, msconf_get_stat_missed }, - { MS_FILTER_GET_STAT_OUTPUT, msconf_get_stat_processed }, - - { MS_FILTER_ENABLE_HALFDUPLEX, msconf_enable_halfduplex }, - { MS_FILTER_SET_VAD_PROB_START, msconf_set_vad_prob_start }, - { MS_FILTER_SET_VAD_PROB_CONTINUE, msconf_set_vad_prob_continue }, - { 0 , NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_conf_desc={ - MS_CONF_ID, - "MSConf", - N_("A filter to make conferencing"), - MS_FILTER_OTHER, - NULL, - CONF_MAX_PINS, - CONF_MAX_PINS, - conf_init, - conf_preprocess, - conf_process, - conf_postprocess, - conf_uninit, - msconf_methods -}; - -#else - -MSFilterDesc ms_conf_desc={ - .id=MS_CONF_ID, - .name="MSConf", - .text=N_("A filter to make conferencing"), - .category=MS_FILTER_OTHER, - .ninputs=CONF_MAX_PINS, - .noutputs=CONF_MAX_PINS, - .init=conf_init, - .preprocess=conf_preprocess, - .process=conf_process, - .postprocess=conf_postprocess, - .uninit=conf_uninit, - .methods=msconf_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_conf_desc) - diff --git a/linphone/mediastreamer2/src/msdscap-mingw.cc b/linphone/mediastreamer2/src/msdscap-mingw.cc deleted file mode 100755 index 67449097b..000000000 --- a/linphone/mediastreamer2/src/msdscap-mingw.cc +++ /dev/null @@ -1,1071 +0,0 @@ -/* msdscap-mingw - mediastreamer2 plugin for video capture using directshow - Unlike winvideods.c filter, the following source code compiles with mingw. - winvideods.c requires visual studio to build. - - Copyright (C) 2009 Simon Morlat - - 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 . -*/ -/* -This plugin has been written by Simon Morlat based on the work made by -Jan Wedekind, posted on mingw tracker here: -http://sourceforge.net/tracker/index.php?func=detail&aid=1819367&group_id=2435&atid=302435 -He wrote all the declarations missing to get directshow capture working -with mingw, and provided a demo code that worked great with minimal code. -*/ - - -#include -#include -#include -#include -#include - - -#include -#include -#include -#include - -template -class ComPtr{ - private: - _ComT *mPtr; - public: - int coCreateInstance(REFCLSID clsid, REFIID iid){ - HRESULT res; - res=::CoCreateInstance(clsid,NULL,CLSCTX_INPROC,iid, - (void**)&mPtr); - return (res==S_OK) ? 0 : -1; - } - ComPtr() : mPtr(0){ - } - ~ComPtr(){ - reset(); - } - ComPtr(const ComPtr<_ComT>& other) : mPtr(other.mPtr){ - if (mPtr) mPtr->AddRef(); - } - ComPtr<_ComT> & operator=(const ComPtr<_ComT> &other){ - if (other.mPtr) - other.mPtr->AddRef(); - if (mPtr) - mPtr->Release(); - mPtr=other.mPtr; - return *this; - } - bool operator==(const ComPtr<_ComT> &other){ - return other.mPtr==mPtr; - } - bool operator!=(const ComPtr<_ComT> &other){ - return other.mPtr!=mPtr; - } - _ComT *get(){ - return mPtr; - } - _ComT **operator&(){ - return &mPtr; - } - _ComT * operator->(){ - return mPtr; - } - void reset(){ - if (mPtr){ - mPtr->Release(); - mPtr=0; - } - } -}; - - -DEFINE_GUID( CLSID_VideoInputDeviceCategory, 0x860BB310, 0x5D01, - 0x11d0, 0xBD, 0x3B, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86); -DEFINE_GUID( CLSID_SystemDeviceEnum, 0x62BE5D10, 0x60EB, 0x11d0, - 0xBD, 0x3B, 0x00, 0xA0, 0xC9, 0x11, 0xCE, 0x86 ); -DEFINE_GUID( CLSID_FilterGraph, 0xe436ebb3, 0x524f, 0x11ce, - 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70); -DEFINE_GUID( CLSID_SampleGrabber, 0xc1f400a0, 0x3f08, 0x11d3, - 0x9f, 0x0b, 0x00, 0x60, 0x08, 0x03, 0x9e, 0x37 ); -DEFINE_GUID( CLSID_NullRenderer,0xc1f400a4, 0x3f08, 0x11d3, - 0x9f, 0x0b, 0x00, 0x60, 0x08, 0x03, 0x9e, 0x37 ); -DEFINE_GUID( CLSID_VfwCapture, 0x1b544c22, 0xfd0b, 0x11ce, - 0x8c, 0x63, 0x0, 0xaa, 0x00, 0x44, 0xb5, 0x1e); -DEFINE_GUID( IID_IGraphBuilder, 0x56a868a9, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70); -DEFINE_GUID( IID_IBaseFilter, 0x56a86895, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_ICreateDevEnum, 0x29840822, 0x5b84, 0x11d0, - 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86 ); -DEFINE_GUID( IID_IEnumFilters, 0x56a86893, 0xad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IEnumPins, 0x56a86892, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IMediaSample, 0x56a8689a, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IMediaFilter, 0x56a86899, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IPin, 0x56a86891, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_ISampleGrabber, 0x6b652fff, 0x11fe, 0x4fce, - 0x92, 0xad, 0x02, 0x66, 0xb5, 0xd7, 0xc7, 0x8f ); -DEFINE_GUID( IID_ISampleGrabberCB, 0x0579154a, 0x2b53, 0x4994, - 0xb0, 0xd0, 0xe7, 0x73, 0x14, 0x8e, 0xff, 0x85 ); -DEFINE_GUID( IID_IMediaEvent, 0x56a868b6, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IMediaControl, 0x56a868b1, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IMemInputPin, 0x56a8689d, 0x0ad4, 0x11ce, - 0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); -DEFINE_GUID( IID_IAMStreamConfig, 0xc6e13340, 0x30ac, 0x11d0, - 0xa1, 0x8c, 0x00, 0xa0, 0xc9, 0x11, 0x89, 0x56 ); -DEFINE_GUID( IID_IVideoProcAmp, 0x4050560e, 0x42a7, 0x413a, - 0x85, 0xc2, 0x09, 0x26, 0x9a, 0x2d, 0x0f, 0x44 ); -DEFINE_GUID( MEDIATYPE_Video, 0x73646976, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_I420, 0x30323449, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); -DEFINE_GUID( MEDIASUBTYPE_YV12, 0x32315659, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_IYUV, 0x56555949, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_YUYV, 0x56595559, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_YUY2, 0x32595559, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_UYVY, 0x59565955, 0x0000, 0x0010, - 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 ); -DEFINE_GUID( MEDIASUBTYPE_RGB24, 0xe436eb7d, 0x524f, 0x11ce, - 0x9f, 0x53, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70 ); - -using namespace std; - -typedef LONGLONG REFERENCE_TIME; - -typedef struct tagVIDEOINFOHEADER { - RECT rcSource; - RECT rcTarget; - DWORD dwBitRate; - DWORD dwBitErrorRate; - REFERENCE_TIME AvgTimePerFrame; - BITMAPINFOHEADER bmiHeader; -} VIDEOINFOHEADER; - -typedef struct _AMMediaType { - GUID majortype; - GUID subtype; - BOOL bFixedSizeSamples; - BOOL bTemporalCompression; - ULONG lSampleSize; - GUID formattype; - IUnknown *pUnk; - ULONG cbFormat; - BYTE *pbFormat; -} AM_MEDIA_TYPE; - -DECLARE_ENUMERATOR_(IEnumMediaTypes,AM_MEDIA_TYPE*); - -typedef struct _VIDEO_STREAM_CONFIG_CAPS -{ - GUID guid; - ULONG VideoStandard; - SIZE InputSize; - SIZE MinCroppingSize; - SIZE MaxCroppingSize; - int CropGranularityX; - int CropGranularityY; - int CropAlignX; - int CropAlignY; - SIZE MinOutputSize; - SIZE MaxOutputSize; - int OutputGranularityX; - int OutputGranularityY; - int StretchTapsX; - int StretchTapsY; - int ShrinkTapsX; - int ShrinkTapsY; - LONGLONG MinFrameInterval; - LONGLONG MaxFrameInterval; - LONG MinBitsPerSecond; - LONG MaxBitsPerSecond; -} VIDEO_STREAM_CONFIG_CAPS; - -typedef LONGLONG REFERENCE_TIME; - -typedef interface IBaseFilter IBaseFilter; -typedef interface IReferenceClock IReferenceClock; -typedef interface IFilterGraph IFilterGraph; - -typedef enum _FilterState { - State_Stopped, - State_Paused, - State_Running -} FILTER_STATE; - -#define MAX_FILTER_NAME 128 -typedef struct _FilterInfo { - WCHAR achName[MAX_FILTER_NAME]; - IFilterGraph *pGraph; -} FILTER_INFO; - -typedef enum _PinDirection { - PINDIR_INPUT, - PINDIR_OUTPUT -} PIN_DIRECTION; - -#define MAX_PIN_NAME 128 -typedef struct _PinInfo { - IBaseFilter *pFilter; - PIN_DIRECTION dir; - WCHAR achName[MAX_PIN_NAME]; -} PIN_INFO; - -#define INTERFACE IPin -DECLARE_INTERFACE_(IPin,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Connect)(THIS_ IPin*,const AM_MEDIA_TYPE*) PURE; - STDMETHOD(ReceiveConnection)(THIS_ IPin*,const AM_MEDIA_TYPE*) PURE; - STDMETHOD(Disconnect)(THIS) PURE; - STDMETHOD(ConnectedTo)(THIS_ IPin**) PURE; - STDMETHOD(ConnectionMediaType)(THIS_ AM_MEDIA_TYPE*) PURE; - STDMETHOD(QueryPinInfo)(THIS_ PIN_INFO*) PURE; - STDMETHOD(QueryDirection)(THIS_ PIN_DIRECTION*) PURE; -}; -#undef INTERFACE - -DECLARE_ENUMERATOR_(IEnumPins,IPin*); - -typedef struct _AllocatorProperties { - long cBuffers; - long cbBuffer; - long cbAlign; - long cbPrefix; -} ALLOCATOR_PROPERTIES; - -typedef LONG_PTR OAEVENT; - -#define INTERFACE IMediaEvent -DECLARE_INTERFACE_(IMediaEvent,IDispatch) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetEventHandle)(THIS_ OAEVENT*) PURE; - STDMETHOD(GetEvent)(THIS_ long*,LONG_PTR,LONG_PTR,long) PURE; - STDMETHOD(WaitForCompletion)(THIS_ long,long*) PURE; - STDMETHOD(CancelDefaultHandling)(THIS_ long) PURE; - STDMETHOD(RestoreDefaultHandling)(THIS_ long) PURE; - STDMETHOD(FreeEventParams)(THIS_ long,LONG_PTR,LONG_PTR) PURE; -}; -#undef INTERFACE - -typedef long OAFilterState; - -#define INTERFACE IMediaControl -DECLARE_INTERFACE_(IMediaControl,IDispatch) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Run)(THIS) PURE; - STDMETHOD(Pause)(THIS) PURE; - STDMETHOD(Stop)(THIS) PURE; - STDMETHOD(GetState)(THIS_ LONG,OAFilterState*) PURE; - STDMETHOD(RenderFile)(THIS_ BSTR) PURE; - STDMETHOD(AddSourceFilter)(THIS_ BSTR,IDispatch**) PURE; - STDMETHOD(get_FilterCollection)(THIS_ IDispatch**) PURE; - STDMETHOD(get_RegFilterCollection)(THIS_ IDispatch**) PURE; - STDMETHOD(StopWhenReady)(THIS) PURE; -}; -#undef INTERFACE - -#define INTERFACE IVideoProcAmp -DECLARE_INTERFACE_(IVideoProcAmp,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; -}; -#undef INTERFACE - -#define INTERFACE IAMStreamConfig -DECLARE_INTERFACE_(IAMStreamConfig,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(SetFormat)(THIS_ AM_MEDIA_TYPE*) PURE; - STDMETHOD(GetFormat)(THIS_ AM_MEDIA_TYPE**) PURE; - STDMETHOD(GetNumberOfCapabilities)(THIS_ int*,int*) PURE; - STDMETHOD(GetStreamCaps)(THIS_ int,AM_MEDIA_TYPE**,BYTE*) PURE; -}; -#undef INTERFACE - -#define INTERFACE IMediaFilter -DECLARE_INTERFACE_(IMediaFilter,IPersist) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Stop)(THIS) PURE; - STDMETHOD(Pause)(THIS) PURE; - STDMETHOD(Run)(THIS_ REFERENCE_TIME) PURE; - STDMETHOD(GetState)(THIS_ DWORD,FILTER_STATE*) PURE; - STDMETHOD(SetSyncSource)(THIS_ IReferenceClock*) PURE; - STDMETHOD(GetSyncSource)(THIS_ IReferenceClock**) PURE; -}; -#undef INTERFACE - -#define INTERFACE IBaseFilter -DECLARE_INTERFACE_(IBaseFilter,IMediaFilter) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(EnumPins)(THIS_ IEnumPins**) PURE; - STDMETHOD(FindPin)(THIS_ LPCWSTR,IPin**) PURE; - STDMETHOD(QueryFilterInfo)(THIS_ FILTER_INFO*) PURE; - STDMETHOD(JoinFilterGraph)(THIS_ IFilterGraph*,LPCWSTR) PURE; - STDMETHOD(QueryVendorInfo)(THIS_ LPWSTR*) PURE; -}; -#undef INTERFACE - -DECLARE_ENUMERATOR_(IEnumFilters,IBaseFilter*); - -// #define INTERFACE IEnumFilters -// DECLARE_INTERFACE_(IEnumFilters,IUnknown) -// { -// STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; -// STDMETHOD_(ULONG,AddRef)(THIS) PURE; -// STDMETHOD_(ULONG,Release)(THIS) PURE; -// STDMETHOD(Next)(THIS_ ULONG,IBaseFilter**,ULONG*) PURE; -// STDMETHOD(Skip)(THIS_ ULONG) PURE; -// STDMETHOD(Reset)(THIS) PURE; -// STDMETHOD(Clone)(THIS_ IEnumFilters**) PURE; -// }; -// #undef INTERFACE - -#define INTERFACE IFilterGraph -DECLARE_INTERFACE_(IFilterGraph,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddFilter)(THIS_ IBaseFilter*,LPCWSTR) PURE; - STDMETHOD(RemoveFilter)(THIS_ IBaseFilter*) PURE; - STDMETHOD(EnumFilters)(THIS_ IEnumFilters**) PURE; - STDMETHOD(FindFilterByName)(THIS_ LPCWSTR,IBaseFilter**) PURE; - STDMETHOD(ConnectDirect)(THIS_ IPin*,IPin*,const AM_MEDIA_TYPE*) PURE; - STDMETHOD(Reconnect)(THIS_ IPin*) PURE; - STDMETHOD(Disconnect)(THIS_ IPin*) PURE; - STDMETHOD(SetDefaultSyncSource)(THIS) PURE; -}; -#undef INTERFACE - -#define INTERFACE IGraphBuilder -DECLARE_INTERFACE_(IGraphBuilder,IFilterGraph) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Connect)(THIS_ IPin*,IPin*) PURE; - STDMETHOD(Render)(THIS_ IPin*) PURE; - STDMETHOD(RenderFile)(THIS_ LPCWSTR,LPCWSTR) PURE; - STDMETHOD(AddSourceFilter)(THIS_ LPCWSTR,LPCWSTR,IBaseFilter**) PURE; - STDMETHOD(SetLogFile)(THIS_ DWORD_PTR) PURE; - STDMETHOD(Abort)(THIS) PURE; - STDMETHOD(ShouldOperationContinue)(THIS) PURE; -}; -#undef INTERFACE - -#define INTERFACE ICreateDevEnum -DECLARE_INTERFACE_(ICreateDevEnum,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(CreateClassEnumerator)(THIS_ REFIID,IEnumMoniker**,DWORD) PURE; -}; -#undef INTERFACE - -#define INTERFACE IMediaSample -DECLARE_INTERFACE_(IMediaSample,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetPointer)(THIS_ BYTE **) PURE; - STDMETHOD_(long, GetSize)(THIS) PURE; -}; -/* -#define INTERFACE IMediaSample -DECLARE_INTERFACE_(IMediaSample, IUnknown) -{ - STDMETHOD(GetPointer)(THIS_ BYTE **) PURE; - STDMETHOD_(long, GetSize)(THIS) PURE; - STDMETHOD(GetTime)(THIS_ REFERENCE_TIME *, REFERENCE_TIME *) PURE; - STDMETHOD(SetTime)(THIS_ REFERENCE_TIME *, REFERENCE_TIME *) PURE; - STDMETHOD(IsSyncPoint)(THIS) PURE; - STDMETHOD(SetSyncPoint)(THIS_ BOOL) PURE; - STDMETHOD(IsPreroll)(THIS) PURE; - STDMETHOD(SetPreroll)(THIS_ BOOL) PURE; - STDMETHOD_(long, GetActualDataLength)(THIS) PURE; - STDMETHOD(SetActualDataLength)(THIS_ long) PURE; - STDMETHOD(GetMediaType)(THIS_ AM_MEDIA_TYPE **) PURE; - STDMETHOD(SetMediaType)(THIS_ AM_MEDIA_TYPE *) PURE; - STDMETHOD(IsDiscontinuity)(THIS) PURE; - STDMETHOD(SetDiscontinuity)(THIS_ BOOL) PURE; - STDMETHOD(GetMediaTime)(THIS_ LONGLONG *, LONGLONG *) PURE; - STDMETHOD(SetMediaTime)(THIS_ LONGLONG *, LONGLONG *) PURE; -}; -*/ - - -#undef INTERFACE - -#define INTERFACE IMemAllocator -DECLARE_INTERFACE_(IMemAllocator,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(SetProperties)(THIS_ ALLOCATOR_PROPERTIES*,ALLOCATOR_PROPERTIES*) PURE; - STDMETHOD(GetProperties)(THIS_ ALLOCATOR_PROPERTIES*) PURE; - STDMETHOD(Commit)(THIS) PURE; - STDMETHOD(Decommit)(THIS) PURE; - STDMETHOD(GetBuffer)(THIS_ IMediaSample **,REFERENCE_TIME*,REFERENCE_TIME*,DWORD) PURE; - STDMETHOD(ReleaseBuffer)(THIS_ IMediaSample*) PURE; -}; -#undef INTERFACE - -#define INTERFACE IMemInputPin -DECLARE_INTERFACE_(IMemInputPin,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetAllocator)(THIS_ IMemAllocator**) PURE; - STDMETHOD(NotifyAllocator)(THIS_ IMemAllocator*,BOOL) PURE; - STDMETHOD(GetAllocatorRequirements)(THIS_ ALLOCATOR_PROPERTIES*) PURE; - STDMETHOD(Receive)(THIS_ IMediaSample*) PURE; - STDMETHOD(ReceiveMultiple)(THIS_ IMediaSample**,LONG,LONG*) PURE; - STDMETHOD(ReceiveCanBlock)(THIS) PURE; -}; -#undef INTERFACE - -#define INTERFACE ISampleGrabberCB -DECLARE_INTERFACE_(ISampleGrabberCB,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(SampleCB)(THIS_ double,IMediaSample*) PURE; - STDMETHOD(BufferCB)(THIS_ double,BYTE*,long) PURE; -}; -#undef INTERFACE - -#define INTERFACE ISampleGrabber -DECLARE_INTERFACE_(ISampleGrabber,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(SetOneShot)(THIS_ BOOL) PURE; - STDMETHOD(SetMediaType)(THIS_ const AM_MEDIA_TYPE*) PURE; - STDMETHOD(GetConnectedMediaType)(THIS_ AM_MEDIA_TYPE*) PURE; - STDMETHOD(SetBufferSamples)(THIS_ BOOL) PURE; - STDMETHOD(GetCurrentBuffer)(THIS_ long*,long*) PURE; - STDMETHOD(GetCurrentSample)(THIS_ IMediaSample**) PURE; - STDMETHOD(SetCallBack)(THIS_ ISampleGrabberCB *,long) PURE; -}; -#undef INTERFACE - -ComPtr< IPin > getPin( IBaseFilter *filter, PIN_DIRECTION direction, int num ) -{ - ComPtr< IPin > retVal; - ComPtr< IEnumPins > enumPins; - if (filter->EnumPins( &enumPins )!=S_OK){ - ms_error("Error getting pin enumerator" ); - return retVal; - } - ULONG found; - ComPtr< IPin > pin; - while ( enumPins->Next( 1, &pin, &found ) == S_OK ) { - PIN_DIRECTION pinDirection = (PIN_DIRECTION)( -1 ); - pin->QueryDirection( &pinDirection ); - if ( pinDirection == direction ) { - if ( num == 0 ) { - retVal = pin; - break; - }; - num--; - }; - }; - return retVal; -} - - - -class DSCapture : public ISampleGrabberCB{ -public: - DSCapture(){ - qinit(&_rq); - ms_mutex_init(&_mutex,NULL); - _vsize=MS_VIDEO_SIZE_CIF; - _fps=15; - _start_time=0; - _frame_count=0; - _pixfmt=MS_YUV420P; - _ready=false; - m_refCount=1; - } - virtual ~DSCapture(){ - if (_ready) stopAndClean(); - flushq(&_rq,0); - ms_mutex_destroy(&_mutex); - } - STDMETHODIMP QueryInterface( REFIID riid, void **ppv ); - STDMETHODIMP_(ULONG) AddRef(void); - STDMETHODIMP_(ULONG) Release(void); - STDMETHODIMP SampleCB(double,IMediaSample*); - STDMETHODIMP BufferCB(double,BYTE*,long); - int startDshowGraph(); - void stopAndClean(); - mblk_t *readFrame(){ - mblk_t *ret=NULL; - ms_mutex_lock(&_mutex); - ret=getq(&_rq); - ms_mutex_unlock(&_mutex); - return ret; - } - bool isTimeToSend(uint64_t ticker_time); - MSVideoSize getVSize()const{ - return _vsize; - } - void setVSize(MSVideoSize vsize){ - _vsize=vsize; - } - void setFps(float fps){ - _fps=fps; - } - MSPixFmt getPixFmt(){ - if (!_ready) createDshowGraph(); /* so that _pixfmt is updated*/ - return _pixfmt; - } - void setDeviceIndex(int index){ - _devid=index; - } -protected: - long m_refCount; -private: - int createDshowGraph(); - int selectBestFormat(ComPtr streamConfig, int count); - int _devid; - MSVideoSize _vsize; - queue_t _rq; - ms_mutex_t _mutex; - float _fps; - float _start_time; - int _frame_count; - MSPixFmt _pixfmt; - ComPtr< IGraphBuilder > _graphBuilder; - ComPtr< IBaseFilter > _source; - ComPtr< IBaseFilter > _nullRenderer; - ComPtr< IBaseFilter > _grabberBase; - ComPtr< IMediaControl > _mediaControl; - ComPtr< IMediaEvent > _mediaEvent; - bool _ready; -}; - - -STDMETHODIMP DSCapture::QueryInterface(REFIID riid, void **ppv) -{ - HRESULT retval; - if ( ppv == NULL ) return E_POINTER; - /* - if ( riid == IID_IUnknown ) { - *ppv = static_cast< IUnknown * >( this ); - AddRef(); - retval = S_OK; - } else if ( riid == IID_ISampleGrabberCB ) { - *ppv = static_cast< ISampleGrabberCB * >( this ); - AddRef(); - retval = S_OK; - } else */ { - retval = E_NOINTERFACE; - }; - return retval; -}; - -STDMETHODIMP_(ULONG) DSCapture::AddRef(){ - m_refCount++; - return m_refCount; -} - -STDMETHODIMP_(ULONG) DSCapture::Release() -{ - ms_message("DSCapture::Release"); - if ( !InterlockedDecrement( &m_refCount ) ) { - int refcnt=m_refCount; - delete this; - return refcnt; - } - return m_refCount; -} - -static void dummy(void*p){ -} - -STDMETHODIMP DSCapture::SampleCB( double par1 , IMediaSample * sample) -{ - uint8_t *p; - unsigned int size; - if (sample->GetPointer(&p)!=S_OK){ - ms_error("error in GetPointer()"); - return S_OK; - } - size=sample->GetSize(); - //ms_message( "DSCapture::SampleCB pointer=%p, size=%i",p,size); - mblk_t *m=esballoc(p,size,0,dummy); - m->b_wptr+=size; - ms_mutex_lock(&_mutex); - putq(&_rq,m); - ms_mutex_unlock(&_mutex); - return S_OK; -} - - - -STDMETHODIMP DSCapture::BufferCB( double, BYTE *b, long len) -{ - ms_message("DSCapture::BufferCB"); - return S_OK; -} - -static void dscap_init(MSFilter *f){ - DSCapture *s=new DSCapture(); - f->data=s; -} - - - -static void dscap_uninit(MSFilter *f){ - DSCapture *s=(DSCapture*)f->data; - s->Release(); -} - -static char * fourcc_to_char(char *str, uint32_t fcc){ - memcpy(str,&fcc,4); - str[4]='\0'; - return str; -} - -static int find_best_format(ComPtr streamConfig, int count, MSVideoSize *requested_size, MSPixFmt requested_fmt ){ - int i; - MSVideoSize best_found=(MSVideoSize){32768,32768}; - int best_index=-1; - char fccstr[5]; - char selected_fcc[5]; - for (i=0; iGetStreamCaps( i, &mediaType, - (BYTE *)&videoConfig )!=S_OK){ - ms_error( "Error getting stream capabilities"); - return -1; - } - if ( mediaType->majortype == MEDIATYPE_Video && - mediaType->cbFormat != 0 ) { - VIDEOINFOHEADER *infoHeader = (VIDEOINFOHEADER*)mediaType->pbFormat; - ms_message("Seeing format %ix%i %s",infoHeader->bmiHeader.biWidth,infoHeader->bmiHeader.biHeight, - fourcc_to_char(fccstr,infoHeader->bmiHeader.biCompression)); - if (ms_fourcc_to_pix_fmt(infoHeader->bmiHeader.biCompression)==requested_fmt){ - MSVideoSize cur; - cur.width=infoHeader->bmiHeader.biWidth; - cur.height=infoHeader->bmiHeader.biHeight; - if (ms_video_size_greater_than(cur,*requested_size)){ - if (ms_video_size_greater_than(best_found,cur)){ - best_found=cur; - best_index=i; - fourcc_to_char(selected_fcc,infoHeader->bmiHeader.biCompression); - } - } - } - }; - if ( mediaType->cbFormat != 0 ) - CoTaskMemFree( (PVOID)mediaType->pbFormat ); - if ( mediaType->pUnk != NULL ) mediaType->pUnk->Release(); - CoTaskMemFree( (PVOID)mediaType ); - } - if (best_index!=-1) { - *requested_size=best_found; - ms_message("Best camera format is %s %ix%i",selected_fcc,best_found.width,best_found.height); - } - return best_index; -} - -int DSCapture::selectBestFormat(ComPtr streamConfig, int count){ - int index; - _pixfmt=MS_YUV420P; - index=find_best_format(streamConfig, count, &_vsize, _pixfmt); - if (index!=-1) goto success; - _pixfmt=MS_YUY2; - index=find_best_format(streamConfig, count, &_vsize,_pixfmt); - if (index!=-1) goto success; - _pixfmt=MS_YUYV; - index=find_best_format(streamConfig, count, &_vsize, _pixfmt); - if (index!=-1) goto success; - _pixfmt=MS_RGB24; - index=find_best_format(streamConfig, count, &_vsize, _pixfmt); - if (index!=-1) { - _pixfmt=MS_RGB24_REV; - goto success; - } - ms_error("This camera does not support any of our pixel formats."); - return -1; - - success: - VIDEO_STREAM_CONFIG_CAPS videoConfig; - AM_MEDIA_TYPE *mediaType; - if (streamConfig->GetStreamCaps( index, &mediaType, - (BYTE *)&videoConfig )!=S_OK){ - ms_error( "Error getting stream capabilities" ); - } - streamConfig->SetFormat( mediaType ); - return 0; -} - -int DSCapture::createDshowGraph(){ - ComPtr< ICreateDevEnum > createDevEnum; - - CoInitialize(NULL); - if (createDevEnum.coCreateInstance( CLSID_SystemDeviceEnum, - IID_ICreateDevEnum )==-1){ - ms_error("Could not create device enumerator"); - return -1; - } - ComPtr< IEnumMoniker > enumMoniker; - if (createDevEnum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory, &enumMoniker, 0 )!=S_OK){ - ms_error("Fail to create class enumerator."); - return -1; - } - createDevEnum.reset(); - enumMoniker->Reset(); - - ULONG fetched = 0; - if (_graphBuilder.coCreateInstance( CLSID_FilterGraph, IID_IGraphBuilder )!=0){ - ms_error("Could not create graph builder."); - return -1; - } - ComPtr< IMoniker > moniker; - for ( int i=0;enumMoniker->Next( 1, &moniker, &fetched )==S_OK;++i ) { - if (i==_devid){ - if (moniker->BindToObject( 0, 0, IID_IBaseFilter, (void **)&_source )!=S_OK){ - ms_error("Error binding moniker to base filter" ); - return -1; - } - } - } - if (_source.get()==0){ - ms_error("Could not interface with webcam devid=%i",_devid); - return -1; - } - moniker.reset(); - enumMoniker.reset(); - if (_graphBuilder->AddFilter( _source.get(), L"Source" )!=S_OK){ - ms_error("Error adding camera source to filter graph" ); - return -1; - } - ComPtr< IPin > sourceOut = getPin( _source.get(), PINDIR_OUTPUT, 0 ); - if (sourceOut.get()==NULL){ - ms_error("Error getting output pin of camera source" ); - return -1; - } - ComPtr< IAMStreamConfig > streamConfig; - if (sourceOut->QueryInterface( IID_IAMStreamConfig, - (void **)&streamConfig )!=S_OK){ - ms_error("Error requesting stream configuration API" ); - return -1; - } - int count, size; - if (streamConfig->GetNumberOfCapabilities( &count, &size )!=S_OK){ - ms_error("Error getting number of capabilities" ); - return -1; - } - if (selectBestFormat(streamConfig,count)!=0){ - return -1; - } - streamConfig.reset(); - - if (CoCreateInstance( CLSID_SampleGrabber, NULL, - CLSCTX_INPROC, IID_IBaseFilter, - (void **)&_grabberBase )!=S_OK){ - ms_error("Error creating sample grabber" ); - return -1; - } - if (_graphBuilder->AddFilter( _grabberBase.get(), L"Grabber" )!=S_OK){ - ms_error("Error adding sample grabber to filter graph"); - return -1; - } - ComPtr< ISampleGrabber > sampleGrabber; - if (_grabberBase->QueryInterface( IID_ISampleGrabber, - (void **)&sampleGrabber )!=S_OK){ - ms_error("Error requesting sample grabber interface"); - return -1; - } - if (sampleGrabber->SetOneShot( FALSE )!=S_OK){ - ms_error("Error disabling one-shot mode" ); - return -1; - } - if (sampleGrabber->SetBufferSamples( TRUE )!=S_OK){ - ms_error("Error enabling buffer sampling" ); - return -1; - } - if (sampleGrabber->SetCallBack(this, 0 )!=S_OK){ - ms_error("Error setting callback interface for grabbing" ); - return -1; - } - ComPtr< IPin > grabberIn = getPin( _grabberBase.get(), PINDIR_INPUT, 0 ); - if (grabberIn.get() == NULL){ - ms_error("Error getting input of sample grabber"); - return -1; - } - ComPtr< IPin > grabberOut = getPin( _grabberBase.get(), PINDIR_OUTPUT, 0 ); - if (grabberOut.get()==NULL){ - ms_error("Error getting output of sample grabber" ); - return -1; - } - if (CoCreateInstance( CLSID_NullRenderer, NULL, - CLSCTX_INPROC, IID_IBaseFilter, - (void **)&_nullRenderer )!=S_OK){ - ms_error("Error creating Null Renderer" ); - return -1; - } - if (_graphBuilder->AddFilter( _nullRenderer.get(), L"Sink" )!=S_OK){ - ms_error("Error adding null renderer to filter graph" ); - return -1; - } - ComPtr< IPin > nullIn = getPin( _nullRenderer.get(), PINDIR_INPUT, 0 ); - if (_graphBuilder->Connect( sourceOut.get(), grabberIn.get() )!=S_OK){ - ms_error("Error connecting source to sample grabber" ); - return -1; - } - if (_graphBuilder->Connect( grabberOut.get(), nullIn.get() )!=S_OK){ - ms_error("Error connecting sample grabber to sink" ); - return -1; - } - ms_message("Directshow graph is now ready to run."); - - if (_graphBuilder->QueryInterface( IID_IMediaControl, - (void **)&_mediaControl )!=S_OK){ - ms_error("Error requesting media control interface" ); - return -1; - } - if (_graphBuilder->QueryInterface( IID_IMediaEvent, - (void **)&_mediaEvent )!=S_OK){ - ms_error("Error requesting event interface" ); - return -1; - } - _ready=true; - return 0; -} - -int DSCapture::startDshowGraph(){ - if (!_ready) { - if (createDshowGraph()!=0) return -1; - } - HRESULT r=_mediaControl->Run(); - if (r!=S_OK && r!=S_FALSE){ - ms_error("Error starting graph (%i)",r); - return -1; - } - ms_message("Graph started"); - return 0; -} - -void DSCapture::stopAndClean(){ - if (_mediaControl.get()!=NULL){ - HRESULT r; - r=_mediaControl->Stop(); - if (r!=S_OK){ - ms_error("msdscap: Could not stop graph !"); - fflush(NULL); - } - _graphBuilder->RemoveFilter(_source.get()); - _graphBuilder->RemoveFilter(_grabberBase.get()); - _graphBuilder->RemoveFilter(_nullRenderer.get()); - } - _source.reset(); - _grabberBase.reset(); - _nullRenderer.reset(); - _mediaControl.reset(); - _mediaEvent.reset(); - _graphBuilder.reset(); - CoUninitialize(); - ms_mutex_lock(&_mutex); - flushq(&_rq,0); - ms_mutex_unlock(&_mutex); - _ready=false; -} - -bool DSCapture::isTimeToSend(uint64_t ticker_time){ - if (_frame_count==-1){ - _start_time=(float)ticker_time; - _frame_count=0; - } - int cur_frame=(int)(((float)ticker_time-_start_time)*_fps/1000.0); - if (cur_frame>_frame_count){ - _frame_count++; - return true; - } - return false; -} - -static void dscap_preprocess(MSFilter * obj){ - DSCapture *s=(DSCapture*)obj->data; - s->startDshowGraph(); -} - -static void dscap_postprocess(MSFilter * obj){ - DSCapture *s=(DSCapture*)obj->data; - s->stopAndClean(); -} - -static void dscap_process(MSFilter * obj){ - DSCapture *s=(DSCapture*)obj->data; - mblk_t *m; - uint32_t timestamp; - - if (s->isTimeToSend(obj->ticker->time)){ - mblk_t *om=NULL; - /*keep the most recent frame if several frames have been captured */ - while((m=s->readFrame())!=NULL){ - if (om!=NULL) freemsg(om); - om=m; - } - if (om!=NULL){ - timestamp=(uint32_t)(obj->ticker->time*90);/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - ms_queue_put(obj->outputs[0],om); - } - } -} - -static int dscap_set_fps(MSFilter *f, void *arg){ - DSCapture *s=(DSCapture*)f->data; - s->setFps(*(float*)arg); - return 0; -} - -static int dscap_get_pix_fmt(MSFilter *f,void *arg){ - DSCapture *s=(DSCapture*)f->data; - *((MSPixFmt*)arg)=s->getPixFmt(); - return 0; -} - -static int dscap_set_vsize(MSFilter *f, void *arg){ - DSCapture *s=(DSCapture*)f->data; - s->setVSize(*((MSVideoSize*)arg)); - return 0; -} - -static int dscap_get_vsize(MSFilter *f, void *arg){ - DSCapture *s=(DSCapture*)f->data; - MSVideoSize *vs=(MSVideoSize*)arg; - *vs=s->getVSize(); - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , dscap_set_fps }, - { MS_FILTER_GET_PIX_FMT , dscap_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, dscap_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, dscap_get_vsize }, - { 0 , NULL } -}; - -MSFilterDesc ms_dscap_desc={ - MS_DSCAP_ID, - "MSDsCap", - N_("A webcam grabber based on directshow."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - dscap_init, - dscap_preprocess, - dscap_process, - dscap_postprocess, - dscap_uninit, - methods -}; - - -static void ms_dshow_detect(MSWebCamManager *obj); -static MSFilter * ms_dshow_create_reader(MSWebCam *obj){ - MSFilter *f=ms_filter_new_from_desc(&ms_dscap_desc); - DSCapture *s=(DSCapture*)f->data; - s->setDeviceIndex((int)obj->data); - return f; -} - -MSWebCamDesc ms_dshow_cam_desc={ - "Directshow capture", - &ms_dshow_detect, - NULL, - &ms_dshow_create_reader, - NULL -}; - -static void ms_dshow_detect(MSWebCamManager *obj){ - ComPtr pBag; - - CoInitialize(NULL); - - ComPtr< ICreateDevEnum > createDevEnum; - if (createDevEnum.coCreateInstance( CLSID_SystemDeviceEnum, - IID_ICreateDevEnum)!=0){ - ms_error( "Could not create device enumerator" ); - return ; - } - ComPtr< IEnumMoniker > enumMoniker; - if (createDevEnum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory, &enumMoniker, 0 )!=S_OK){ - ms_error("Fail to create class enumerator."); - return; - } - createDevEnum.reset(); - enumMoniker->Reset(); - - ULONG fetched = 0; - ComPtr< IMoniker > moniker; - for ( int i=0;enumMoniker->Next( 1, &moniker, &fetched )==S_OK;++i ) { - VARIANT var; - if (moniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag )!=S_OK) - continue; - VariantInit(&var); - if (pBag->Read( L"FriendlyName", &var, NULL )!=S_OK) - continue; - char szName[256]; - WideCharToMultiByte(CP_ACP,0,var.bstrVal,-1,szName,256,0,0); - MSWebCam *cam=ms_web_cam_new(&ms_dshow_cam_desc); - cam->name=ms_strdup(szName); - cam->data=(void*)i; - ms_web_cam_manager_prepend_cam(obj,cam); - VariantClear(&var); - } - enumMoniker.reset(); -} - diff --git a/linphone/mediastreamer2/src/msfileplayer.c b/linphone/mediastreamer2/src/msfileplayer.c deleted file mode 100644 index 3ae467617..000000000 --- a/linphone/mediastreamer2/src/msfileplayer.c +++ /dev/null @@ -1,325 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfileplayer.h" -#include "mediastreamer2/waveheader.h" -#include "mediastreamer2/msticker.h" - - -static int player_close(MSFilter *f, void *arg); - -typedef enum { - CLOSED, - STARTED, - STOPPED -} PlayerState; - -struct _PlayerData{ - int fd; - PlayerState state; - int rate; - int nchannels; - int hsize; - int loop_after; - int pause_time; - int count; - bool_t swap; -}; - -typedef struct _PlayerData PlayerData; - -static void player_init(MSFilter *f){ - PlayerData *d=ms_new(PlayerData,1); - d->fd=-1; - d->state=CLOSED; - d->swap=FALSE; - d->rate=8000; - d->nchannels=1; - d->hsize=0; - d->loop_after=-1; /*by default, don't loop*/ - d->pause_time=0; - d->count=0; - f->data=d; -} - -static int read_wav_header(PlayerData *d){ - char header1[sizeof(riff_t)]; - char header2[sizeof(format_t)]; - char header3[sizeof(data_t)]; - int count; - - riff_t *riff_chunk=(riff_t*)header1; - format_t *format_chunk=(format_t*)header2; - data_t *data_chunk=(data_t*)header3; - - unsigned long len=0; - - len = read(d->fd, header1, sizeof(header1)) ; - if (len != sizeof(header1)){ - goto not_a_wav; - } - - if (0!=strncmp(riff_chunk->riff, "RIFF", 4) || 0!=strncmp(riff_chunk->wave, "WAVE", 4)){ - goto not_a_wav; - } - - len = read(d->fd, header2, sizeof(header2)) ; - if (len != sizeof(header2)){ - ms_warning("Wrong wav header: cannot read file"); - goto not_a_wav; - } - - d->rate=le_uint32(format_chunk->rate); - d->nchannels=le_uint16(format_chunk->channel); - - if (format_chunk->len-0x10>0) - { - lseek(d->fd,(format_chunk->len-0x10),SEEK_CUR); - } - - d->hsize=sizeof(wave_header_t)-0x10+format_chunk->len; - - len = read(d->fd, header3, sizeof(header3)) ; - if (len != sizeof(header3)){ - ms_warning("Wrong wav header: cannot read file"); - goto not_a_wav; - } - count=0; - while (strncmp(data_chunk->data, "data", 4)!=0 && count<30) - { - ms_warning("skipping chunk=%s len=%i", data_chunk->data, data_chunk->len); - lseek(d->fd,data_chunk->len,SEEK_CUR); - count++; - d->hsize=d->hsize+len+data_chunk->len; - - len = read(d->fd, header3, sizeof(header3)) ; - if (len != sizeof(header3)){ - ms_warning("Wrong wav header: cannot read file"); - goto not_a_wav; - } - } - #ifdef WORDS_BIGENDIAN - if (le_uint16(format_chunk->blockalign)==le_uint16(format_chunk->channel) * 2) - d->swap=TRUE; - #endif - return 0; - - not_a_wav: - /*rewind*/ - lseek(d->fd,0,SEEK_SET); - d->hsize=0; - return -1; -} - -static int player_open(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - int fd; - const char *file=(const char*)arg; - - if (d->fd>=0){ - player_close(f,NULL); - } - if ((fd=open(file,O_RDONLY))==-1){ - ms_warning("Failed to open %s",file); - return -1; - } - d->state=STOPPED; - d->fd=fd; - if (read_wav_header(d)!=0 && strstr(file,".wav")){ - ms_warning("File %s has .wav extension but wav header could be found.",file); - } - ms_message("%s opened: rate=%i,channel=%i",file,d->rate,d->nchannels); - return 0; -} - -static int player_start(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->state==STOPPED) - d->state=STARTED; - return 0; -} - -static int player_stop(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - ms_filter_lock(f); - if (d->state==STARTED){ - d->state=STOPPED; - lseek(d->fd,d->hsize,SEEK_SET); - } - ms_filter_unlock(f); - return 0; -} - -static int player_close(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - player_stop(f,NULL); - if (d->fd>=0) close(d->fd); - d->fd=-1; - d->state=CLOSED; - return 0; -} - -static void player_uninit(MSFilter *f){ - PlayerData *d=(PlayerData*)f->data; - if (d->fd>=0) player_close(f,NULL); - ms_free(d); -} - -static void swap_bytes(unsigned char *bytes, int len){ - int i; - unsigned char tmp; - for(i=0;idata; - int nsamples=(f->ticker->interval*d->rate*d->nchannels)/1000; - int bytes; - /*send an even number of samples each tick. At 22050Hz the number of samples per 10 ms chunk is odd. - Odd size buffer of samples cause troubles to alsa. Fixing in alsa is difficult, so workaround here. - */ - if (nsamples & 0x1 ) { //odd number of samples - if (d->count & 0x1 ) - nsamples++; - else - nsamples--; - } - bytes=2*nsamples; - d->count++; - ms_filter_lock(f); - if (d->state==STARTED){ - int err; - mblk_t *om=allocb(bytes,0); - if (d->pause_time>0){ - err=bytes; - memset(om->b_wptr,0,bytes); - d->pause_time-=f->ticker->interval; - }else{ - err=read(d->fd,om->b_wptr,bytes); - if (d->swap) swap_bytes(om->b_wptr,bytes); - } - if (err>=0){ - if (err!=0){ - if (errb_wptr+err,0,bytes-err); - om->b_wptr+=bytes; - ms_queue_put(f->outputs[0],om); - }else freemsg(om); - if (errfd,d->hsize,SEEK_SET); - - /* special value for playing file only once */ - if (d->loop_after==-2) - { - d->state=STOPPED; - ms_filter_unlock(f); - return; - } - - if (d->loop_after>=0){ - d->pause_time=d->loop_after; - } - } - }else{ - ms_warning("Fail to read %i bytes: %s",bytes,strerror(errno)); - } - } - ms_filter_unlock(f); -} - -static int player_get_sr(MSFilter *f, void*arg){ - PlayerData *d=(PlayerData*)f->data; - *((int*)arg)=d->rate; - return 0; -} - -static int player_loop(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - d->loop_after=*((int*)arg); - return 0; -} - -static int player_eof(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->fd<0 && d->state==CLOSED) - *((int*)arg) = TRUE; /* 1 */ - else - *((int*)arg) = FALSE; /* 0 */ - return 0; -} - -static int player_get_nch(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - *((int*)arg)=d->nchannels; - return 0; -} - -static MSFilterMethod player_methods[]={ - { MS_FILE_PLAYER_OPEN, player_open }, - { MS_FILE_PLAYER_START, player_start }, - { MS_FILE_PLAYER_STOP, player_stop }, - { MS_FILE_PLAYER_CLOSE, player_close }, - { MS_FILTER_GET_SAMPLE_RATE, player_get_sr}, - { MS_FILTER_GET_NCHANNELS, player_get_nch }, - { MS_FILE_PLAYER_LOOP, player_loop }, - { MS_FILE_PLAYER_DONE, player_eof }, - { 0, NULL } -}; - -#ifdef WIN32 - -MSFilterDesc ms_file_player_desc={ - MS_FILE_PLAYER_ID, - "MSFilePlayer", - N_("Raw files and wav reader"), - MS_FILTER_OTHER, - NULL, - 0, - 1, - player_init, - NULL, - player_process, - NULL, - player_uninit, - player_methods -}; - -#else - -MSFilterDesc ms_file_player_desc={ - .id=MS_FILE_PLAYER_ID, - .name="MSFilePlayer", - .text=N_("Raw files and wav reader"), - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .init=player_init, - .process=player_process, - .uninit=player_uninit, - .methods=player_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_file_player_desc) diff --git a/linphone/mediastreamer2/src/msfileplayer_win.c b/linphone/mediastreamer2/src/msfileplayer_win.c deleted file mode 100644 index 0007b7a2a..000000000 --- a/linphone/mediastreamer2/src/msfileplayer_win.c +++ /dev/null @@ -1,369 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#define UNICODE - -#include "mediastreamer2/msfileplayer.h" -#include "mediastreamer2/waveheader.h" -#include "mediastreamer2/msticker.h" - -typedef enum { - CLOSED, - STARTED, - STOPPED -} PlayerState; - -struct _PlayerData{ - HANDLE fd; - PlayerState state; - int rate; - int nchannels; - int hsize; - int loop_after; - int pause_time; - bool_t swap; - - int stat; - int big_buffer; /* ouput less & bigger buffer. (default => no change) */ -}; - -typedef struct _PlayerData PlayerData; - -static void player_init(MSFilter *f){ - PlayerData *d=(PlayerData *)ms_new(PlayerData,1); - d->fd=INVALID_HANDLE_VALUE; - d->state=CLOSED; - d->swap=FALSE; - d->rate=8000; - d->nchannels=1; - d->hsize=0; - d->loop_after=-1; - d->pause_time=0; - d->stat=-1; - d->big_buffer=1; - f->data=d; -} - -static int read_wav_header(PlayerData *d){ - - char header1[sizeof(riff_t)]; - char header2[sizeof(format_t)]; - char header3[sizeof(data_t)]; - int count; - - riff_t *riff_chunk=(riff_t*)header1; - format_t *format_chunk=(format_t*)header2; - data_t *data_chunk=(data_t*)header3; - - unsigned long len=0; - BOOL res; - - res = ReadFile(d->fd, header1, sizeof(header1), &len, NULL) ; - if (!res || len != sizeof(header1)){ - ms_warning("Wrong wav header: cannot read file"); - return -1; - } - - if (0!=strncmp(riff_chunk->riff, "RIFF", 4) || 0!=strncmp(riff_chunk->wave, "WAVE", 4)){ - ms_warning("Wrong wav header (not RIFF/WAV)"); - return -1; - } - - res = ReadFile(d->fd, header2, sizeof(header2), &len, NULL) ; - if (!res || len != sizeof(header2)){ - ms_warning("Wrong wav header: cannot read file"); - return -1; - } - - d->rate=le_uint32(format_chunk->rate); - d->nchannels=le_uint16(format_chunk->channel); - - if (format_chunk->len-0x10>0) - { - SetFilePointer(d->fd, (format_chunk->len-0x10), NULL, FILE_CURRENT); - } - - d->hsize=sizeof(wave_header_t)-0x10+format_chunk->len; - - res = ReadFile(d->fd, header3, sizeof(header3), &len, NULL) ; - if (!res || len != sizeof(header3)){ - ms_warning("Wrong wav header: cannot read file"); - return -1; - } - count=0; - while (strncmp(data_chunk->data, "data", 4)!=0 && count<30) - { - SetFilePointer(d->fd, data_chunk->len, NULL, FILE_CURRENT); - count++; - d->hsize=d->hsize+len+data_chunk->len; - - res = ReadFile(d->fd, header3, sizeof(header3), &len, NULL) ; - if (!res || len != sizeof(header3)){ - ms_warning("Wrong wav header: cannot read file"); - return -1; - } - } -#ifdef WORDS_BIGENDIAN - d->swap=TRUE; -#endif - return 0; -} - -static int player_open(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - HANDLE fd; - const char *file=(const char*)arg; - WCHAR wUnicode[1024]; - MultiByteToWideChar(CP_UTF8, 0, file, -1, wUnicode, 1024); - fd = CreateFile(wUnicode, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, 0, NULL); - if (fd==INVALID_HANDLE_VALUE){ - ms_warning("Failed to open %s",file); - return -1; - } - d->state=STOPPED; - d->fd=fd; - if (strstr(file,".wav")!=NULL) read_wav_header(d); - return 0; -} - -static int player_close(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->fd!=INVALID_HANDLE_VALUE) CloseHandle(d->fd); - d->fd=NULL; - d->state=CLOSED; - d->stat=-1; - return 0; -} - -static int player_start(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->state==STOPPED) - d->state=STARTED; - return 0; -} - -static int player_stop(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->state==STARTED){ - d->state=STOPPED; - d->stat=-1; - SetFilePointer(d->fd, d->hsize, NULL, FILE_BEGIN); - //read_wav_header(d); - } - return 0; -} - -static void player_uninit(MSFilter *f){ - PlayerData *d=(PlayerData*)f->data; - if (d->fd!=INVALID_HANDLE_VALUE) player_close(f,NULL); - ms_free(d); -} - -static void player_process(MSFilter *f){ - PlayerData *d=(PlayerData*)f->data; - int bytes =d->big_buffer * 2*(f->ticker->interval*d->rate*d->nchannels)/1000; - - if (d->big_buffer>1) - { - /* when starting reading a file: prepare more data - so that sound card buffer will never remain empty. - */ - d->stat++; - if (d->stat>3) - { - if (d->stat%(d->big_buffer)!=0) - return; - } - } - - if (d->state==STARTED){ - unsigned long err; - mblk_t *om=allocb(bytes,0); - if (d->pause_time>0){ - err=bytes; - memset(om->b_wptr,0,bytes); - d->pause_time-=f->ticker->interval; - }else{ - BOOL res; - err=0; - res = ReadFile(d->fd, om->b_wptr, bytes, &err, NULL) ; - } - if (err>=0){ - if (err==bytes){ - om->b_wptr+=err; - ms_queue_put(f->outputs[0],om); - } - else if (err>0){ - BOOL res; - - om->b_wptr+=err; - - ms_filter_notify_no_arg(f,MS_FILE_PLAYER_EOF); - SetFilePointer(d->fd, d->hsize, NULL, FILE_BEGIN); - //read_wav_header(d); - - /* special value for playing file only once */ - if (d->loop_after==-2) - { - freemsg(om); - player_close(f,NULL); - return; - } - - if (d->loop_after>0) - { - d->stat=-1; - d->pause_time=d->loop_after; - } - else - { - bytes=bytes-err; - err=0; - res = ReadFile(d->fd, om->b_wptr, bytes, &err, NULL); - if (err>0){ - om->b_wptr+=err; - } - } - - ms_queue_put(f->outputs[0],om); - } - else if (err==0){ - BOOL res; - ms_filter_notify_no_arg(f,MS_FILE_PLAYER_EOF); - SetFilePointer(d->fd, d->hsize, NULL, FILE_BEGIN); - - if (d->loop_after==-2) - { - freemsg(om); - player_close(f,NULL); - return; - } - - if (d->loop_after>0) - { - d->stat=-1; - d->pause_time=d->loop_after; - } - else - { - bytes=bytes-err; - err=0; - res = ReadFile(d->fd, om->b_wptr, bytes, &err, NULL); - if (err>0){ - om->b_wptr+=err; - ms_queue_put(f->outputs[0],om); - return; - } - } - freemsg(om); - - }else freemsg(om); - }else{ -#if !defined(_WIN32_WCE) - ms_warning("Fail to read %i bytes: %s",bytes,strerror(errno)); -#else - ms_warning("Fail to read %i bytes: %i",bytes,WSAGetLastError()); -#endif - } - } -} - -static int player_get_sr(MSFilter *f, void*arg){ - PlayerData *d=(PlayerData*)f->data; - *((int*)arg)=d->rate; - return 0; -} - -static int player_loop(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - d->loop_after=*((int*)arg); - return 0; -} - -static int player_set_big_buffer(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - d->big_buffer=*((int*)arg); - return 0; -} - -static int player_eof(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - if (d->fd==NULL && d->state==CLOSED) - *((int*)arg) = TRUE; /* 1 */ - else - *((int*)arg) = FALSE; /* 0 */ - return 0; -} - -static int player_get_nch(MSFilter *f, void *arg){ - PlayerData *d=(PlayerData*)f->data; - *((int*)arg)=d->nchannels; - return 0; -} - -static MSFilterMethod player_methods[]={ - { MS_FILE_PLAYER_OPEN, player_open }, - { MS_FILE_PLAYER_START, player_start }, - { MS_FILE_PLAYER_STOP, player_stop }, - { MS_FILE_PLAYER_CLOSE, player_close }, - { MS_FILTER_GET_SAMPLE_RATE, player_get_sr}, - { MS_FILTER_GET_NCHANNELS, player_get_nch }, - { MS_FILE_PLAYER_LOOP, player_loop }, - { MS_FILE_PLAYER_DONE, player_eof }, - { MS_FILE_PLAYER_BIG_BUFFER, player_set_big_buffer }, - { 0, NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_file_player_desc={ - MS_FILE_PLAYER_ID, - "MSFilePlayer", - "Raw files and wav reader", - MS_FILTER_OTHER, - NULL, - 0, - 1, - player_init, - NULL, - player_process, - NULL, - player_uninit, - player_methods -}; - -#else - -MSFilterDesc ms_file_player_desc={ - .id=MS_FILE_PLAYER_ID, - .name="MSFilePlayer", - .text="Raw files and wav reader", - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .init=player_init, - .process=player_process, - .uninit=player_uninit, - .methods=player_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_file_player_desc) diff --git a/linphone/mediastreamer2/src/msfilerec.c b/linphone/mediastreamer2/src/msfilerec.c deleted file mode 100644 index 78035492b..000000000 --- a/linphone/mediastreamer2/src/msfilerec.c +++ /dev/null @@ -1,200 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilerec.h" -#include "mediastreamer2/waveheader.h" - -#include -#include -#include - -static int rec_close(MSFilter *f, void *arg); - -typedef enum{ - Closed, - Stopped, - Started -} State; - -typedef struct RecState{ - int fd; - int rate; - int size; - State state; -} RecState; - -static void rec_init(MSFilter *f){ - RecState *s=ms_new(RecState,1); - s->fd=-1; - s->rate=8000; - s->size=0; - s->state=Closed; - f->data=s; -} - -static void rec_process(MSFilter *f){ - RecState *s=(RecState*)f->data; - mblk_t *m; - int err; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - mblk_t *it=m; - ms_mutex_lock(&f->lock); - if (s->state==Started){ - while(it!=NULL){ - int len=it->b_wptr-it->b_rptr; - if ((err=write(s->fd,it->b_rptr,len))!=len){ - if (err<0) - ms_warning("MSFileRec: fail to write %i bytes: %s",len,strerror(errno)); - } - it=it->b_cont; - s->size+=len; - } - } - ms_mutex_unlock(&f->lock); - freemsg(m); - } -} - -static int rec_open(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - const char *filename=(const char*)arg; - if (s->fd>=0) rec_close(f,NULL); - ms_mutex_lock(&f->lock); - s->fd=open(filename,O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR); - if (s->fd<0){ - ms_warning("Cannot open %s: %s",filename,strerror(errno)); - ms_mutex_unlock(&f->lock); - return -1; - } - s->state=Stopped; - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_start(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Started; - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_stop(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Stopped; - ms_mutex_unlock(&f->lock); - return 0; -} - -static void write_wav_header(int fd, int rate,int size){ - wave_header_t header; - memcpy(&header.riff_chunk.riff,"RIFF",4); - header.riff_chunk.len=le_uint32(size+32); - memcpy(&header.riff_chunk.wave,"WAVE",4); - - memcpy(&header.format_chunk.fmt,"fmt ",4); - header.format_chunk.len=le_uint32(0x10); - header.format_chunk.type=le_uint16(0x1); - header.format_chunk.channel=le_uint16(0x1); - header.format_chunk.rate=le_uint32(rate); - header.format_chunk.bps=le_uint32(rate*2); - header.format_chunk.blockalign=le_uint16(2); - header.format_chunk.bitpspl=le_uint16(16); - - memcpy(&header.data_chunk.data,"data",4); - header.data_chunk.len=le_uint32(size); - lseek(fd,0,SEEK_SET); - if (write(fd,&header,sizeof(header))!=sizeof(header)){ - ms_warning("Fail to write wav header."); - } -} - -static int rec_close(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Closed; - if (s->fd>=0) { - write_wav_header(s->fd,s->rate, s->size); - close(s->fd); - s->fd=-1; - } - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_set_sr(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->rate=*((int*)arg); - ms_mutex_unlock(&f->lock); - return 0; -} - -static void rec_uninit(MSFilter *f){ - RecState *s=(RecState*)f->data; - if (s->fd>=0) rec_close(f,NULL); - ms_free(s); -} - -static MSFilterMethod rec_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE, rec_set_sr }, - { MS_FILE_REC_OPEN , rec_open }, - { MS_FILE_REC_START , rec_start }, - { MS_FILE_REC_STOP , rec_stop }, - { MS_FILE_REC_CLOSE , rec_close }, - { 0 , NULL } -}; - -#ifdef WIN32 - -MSFilterDesc ms_file_rec_desc={ - MS_FILE_REC_ID, - "MSFileRec", - N_("Wav file recorder"), - MS_FILTER_OTHER, - NULL, - 1, - 0, - rec_init, - NULL, - rec_process, - NULL, - rec_uninit, - rec_methods -}; - -#else - -MSFilterDesc ms_file_rec_desc={ - .id=MS_FILE_REC_ID, - .name="MSFileRec", - .text=N_("Wav file recorder"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .init=rec_init, - .process=rec_process, - .uninit=rec_uninit, - .methods=rec_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_file_rec_desc) diff --git a/linphone/mediastreamer2/src/msfilerec_win.c b/linphone/mediastreamer2/src/msfilerec_win.c deleted file mode 100644 index b485d451b..000000000 --- a/linphone/mediastreamer2/src/msfilerec_win.c +++ /dev/null @@ -1,246 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#define UNICODE - -#include "mediastreamer2/msfilerec.h" -#include "mediastreamer2/waveheader.h" - -#if !defined(_WIN32_WCE) -#include -#include -#include -#endif - - -typedef enum{ - Closed, - Stopped, - Started -} State; - -typedef struct RecState{ - HANDLE fd; - int rate; - int size; - State state; - char filename[256]; -} RecState; - -static void rec_init(MSFilter *f){ - RecState *s=(RecState *)ms_new(RecState,1); - s->fd=INVALID_HANDLE_VALUE; - s->rate=8000; - s->size=0; - s->state=Closed; - f->data=s; -} - -static void rec_process(MSFilter *f){ - RecState *s=(RecState*)f->data; - mblk_t *m; - int err; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - mblk_t *it=m; - ms_mutex_lock(&f->lock); - if (s->state==Started){ - while(it!=NULL){ - int len=it->b_wptr-it->b_rptr; - DWORD byte_written=0; - if ((err=WriteFile(s->fd,it->b_rptr,len, &byte_written, NULL))!=len){ - if (err<0) - { -#if !defined(_WIN32_WCE) - ms_warning("MSFileRec: fail to write %i bytes: %s",len,strerror(errno)); -#else - ms_warning("MSFileRec: fail to write %i bytes: %i",len,WSAGetLastError()); -#endif - } - } - it=it->b_cont; - s->size+=len; - } - } - ms_mutex_unlock(&f->lock); - freemsg(m); - } -} - -static void write_wav_header(int rate,int size, char *filename){ - wave_header_t header; - DWORD bytes_written=0; - HANDLE fd; - WCHAR wUnicode[1024]; - MultiByteToWideChar(CP_UTF8, 0, filename, -1, wUnicode, 1024); - - memcpy(&header.riff_chunk.riff,"RIFF",4); - header.riff_chunk.len=le_uint32(size+32); - memcpy(&header.riff_chunk.wave,"WAVE",4); - - memcpy(&header.format_chunk.fmt,"fmt ",4); - header.format_chunk.len=le_uint32(0x10); - header.format_chunk.type=le_uint16(0x1); - header.format_chunk.channel=le_uint16(0x1); - header.format_chunk.rate=le_uint32(rate); - header.format_chunk.bps=le_uint32(rate*2); - header.format_chunk.blockalign=le_uint16(2); - header.format_chunk.bitpspl=le_uint16(16); - - memcpy(&header.data_chunk.data,"data",4); - header.data_chunk.len=le_uint32(size); - - /* TODO: replace with "lseek" equivalent for windows */ - fd=CreateFile(wUnicode, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - if (fd==INVALID_HANDLE_VALUE){ -#if !defined(_WIN32_WCE) - ms_warning("Cannot open %s: %s",filename,strerror(errno)); -#else - ms_warning("Cannot open %s: %i",filename,WSAGetLastError()); -#endif - return; - } - WriteFile(fd,&header,sizeof(header), &bytes_written, NULL); - if (bytes_written!=sizeof(header)){ - ms_warning("Fail to write wav header."); - } - CloseHandle(fd); -} - -static int rec_open(MSFilter *f, void *arg){ - wave_header_t header; - DWORD bytes_written=0; - - RecState *s=(RecState*)f->data; - const char *filename=(const char*)arg; - WCHAR wUnicode[1024]; - MultiByteToWideChar(CP_UTF8, 0, filename, -1, wUnicode, 1024); - - ms_mutex_lock(&f->lock); - snprintf(s->filename, sizeof(s->filename), "%s", filename); - s->fd=CreateFile(wUnicode, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); - if (s->fd==INVALID_HANDLE_VALUE){ -#if !defined(_WIN32_WCE) - ms_warning("Cannot open %s: %s",filename,strerror(errno)); -#else - ms_warning("Cannot open %s: %i",filename,WSAGetLastError()); -#endif - ms_mutex_unlock(&f->lock); - return -1; - } - - memset(&header ,0,sizeof(header)); - WriteFile(s->fd,&header,sizeof(header), &bytes_written, NULL); - if (bytes_written!=sizeof(header)){ - ms_warning("Fail to write wav header."); - } - - s->state=Stopped; - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_start(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Started; - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_stop(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Stopped; - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_close(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->state=Closed; - if (s->fd!=INVALID_HANDLE_VALUE) { - CloseHandle(s->fd); - write_wav_header(s->rate, s->size, s->filename); - s->fd=INVALID_HANDLE_VALUE; - s->size=0; - } - ms_mutex_unlock(&f->lock); - return 0; -} - -static int rec_set_sr(MSFilter *f, void *arg){ - RecState *s=(RecState*)f->data; - ms_mutex_lock(&f->lock); - s->rate=*((int*)arg); - ms_mutex_unlock(&f->lock); - return 0; -} - -static void rec_uninit(MSFilter *f){ - RecState *s=(RecState*)f->data; - if (s->fd!=INVALID_HANDLE_VALUE) rec_close(f,NULL); - ms_free(s); -} - -static MSFilterMethod rec_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE, rec_set_sr }, - { MS_FILE_REC_OPEN , rec_open }, - { MS_FILE_REC_START , rec_start }, - { MS_FILE_REC_STOP , rec_stop }, - { MS_FILE_REC_CLOSE , rec_close }, - { 0 , NULL } -}; - -#ifdef WIN32 - -MSFilterDesc ms_file_rec_desc={ - MS_FILE_REC_ID, - "MSFileRec", - N_("Wav file recorder"), - MS_FILTER_OTHER, - NULL, - 1, - 0, - rec_init, - NULL, - rec_process, - NULL, - rec_uninit, - rec_methods -}; - -#else - -MSFilterDesc ms_file_rec_desc={ - .id=MS_FILE_REC_ID, - .name="MSFileRec", - .text=N_("Wav file recorder"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .init=rec_init, - .process=rec_process, - .uninit=rec_uninit, - .methods=rec_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_file_rec_desc) diff --git a/linphone/mediastreamer2/src/msfilter.c b/linphone/mediastreamer2/src/msfilter.c deleted file mode 100644 index 4bbfaa5f0..000000000 --- a/linphone/mediastreamer2/src/msfilter.c +++ /dev/null @@ -1,309 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "mediastreamer2/mscommon.h" - -static MSList *desc_list=NULL; - -void ms_filter_register(MSFilterDesc *desc){ - if (desc->id==MS_FILTER_NOT_SET_ID){ - ms_fatal("MSFilterId for %s not set !",desc->name); - } - /*lastly registered encoder/decoders may replace older ones*/ - desc_list=ms_list_prepend(desc_list,desc); -} - -void ms_filter_unregister_all(){ - if (desc_list!=NULL) ms_list_free(desc_list); -} - -bool_t ms_filter_codec_supported(const char *mime){ - if (ms_filter_get_encoder(mime)!=NULL - && ms_filter_get_decoder(mime)!=NULL) return TRUE; - return FALSE; -} - -MSFilterDesc * ms_filter_get_encoder(const char *mime){ - MSList *elem; - for (elem=desc_list;elem!=NULL;elem=ms_list_next(elem)){ - MSFilterDesc *desc=(MSFilterDesc*)elem->data; - if (desc->category==MS_FILTER_ENCODER && - strcasecmp(desc->enc_fmt,mime)==0){ - return desc; - } - } - return NULL; -} - -MSFilterDesc * ms_filter_get_decoder(const char *mime){ - MSList *elem; - for (elem=desc_list;elem!=NULL;elem=ms_list_next(elem)){ - MSFilterDesc *desc=(MSFilterDesc*)elem->data; - if (desc->category==MS_FILTER_DECODER && - strcasecmp(desc->enc_fmt,mime)==0){ - return desc; - } - } - return NULL; -} - -MSFilter * ms_filter_create_encoder(const char *mime){ - MSFilterDesc *desc=ms_filter_get_encoder(mime); - if (desc!=NULL) return ms_filter_new_from_desc(desc); - return NULL; -} - -MSFilter * ms_filter_create_decoder(const char *mime){ - MSFilterDesc *desc=ms_filter_get_decoder(mime); - if (desc!=NULL) return ms_filter_new_from_desc(desc); - return NULL; -} - -MSFilter *ms_filter_new_from_desc(MSFilterDesc *desc){ - MSFilter *obj; - obj=(MSFilter *)ms_new0(MSFilter,1); - ms_mutex_init(&obj->lock,NULL); - obj->desc=desc; - if (desc->ninputs>0) obj->inputs=(MSQueue**)ms_new0(MSQueue*,desc->ninputs); - if (desc->noutputs>0) obj->outputs=(MSQueue**)ms_new0(MSQueue*,desc->noutputs); - if (obj->desc->init!=NULL) - obj->desc->init(obj); - return obj; -} - -MSFilter *ms_filter_new(MSFilterId id){ - MSList *elem; - if (id==MS_FILTER_PLUGIN_ID){ - ms_warning("cannot create plugin filters with ms_filter_new_from_id()"); - return NULL; - } - for (elem=desc_list;elem!=NULL;elem=ms_list_next(elem)){ - MSFilterDesc *desc=(MSFilterDesc*)elem->data; - if (desc->id==id){ - return ms_filter_new_from_desc(desc); - } - } - ms_error("No such filter with id %i",id); - return NULL; -} - -MSFilter *ms_filter_new_from_name(const char *filter_name){ - MSList *elem; - for (elem=desc_list;elem!=NULL;elem=ms_list_next(elem)){ - MSFilterDesc *desc=(MSFilterDesc*)elem->data; - if (strcmp(desc->name,filter_name)==0){ - return ms_filter_new_from_desc(desc); - } - } - ms_error("No such filter with name %s",filter_name); - return NULL; -} - - -MSFilterId ms_filter_get_id(MSFilter *f){ - return f->desc->id; -} - -int ms_filter_link(MSFilter *f1, int pin1, MSFilter *f2, int pin2){ - MSQueue *q; - ms_return_val_if_fail(pin1desc->noutputs, -1); - ms_return_val_if_fail(pin2desc->ninputs, -1); - ms_return_val_if_fail(f1->outputs[pin1]==NULL,-1); - ms_return_val_if_fail(f2->inputs[pin2]==NULL,-1); - q=ms_queue_new(f1,pin1,f2,pin2); - f1->outputs[pin1]=q; - f2->inputs[pin2]=q; - ms_message("ms_filter_link: %s:%p,%i-->%s:%p,%i",f1->desc->name,f1,pin1,f2->desc->name,f2,pin2); - return 0; -} - -int ms_filter_unlink(MSFilter *f1, int pin1, MSFilter *f2, int pin2){ - MSQueue *q; - ms_return_val_if_fail(f1, -1); - ms_return_val_if_fail(f2, -1); - ms_return_val_if_fail(pin1desc->noutputs, -1); - ms_return_val_if_fail(pin2desc->ninputs, -1); - ms_return_val_if_fail(f1->outputs[pin1]!=NULL,-1); - ms_return_val_if_fail(f2->inputs[pin2]!=NULL,-1); - ms_return_val_if_fail(f1->outputs[pin1]==f2->inputs[pin2],-1); - q=f1->outputs[pin1]; - f1->outputs[pin1]=f2->inputs[pin2]=0; - ms_queue_destroy(q); - ms_message("ms_filter_unlink: %s:%p,%i-->%s:%p,%i",f1->desc->name,f1,pin1,f2->desc->name,f2,pin2); - return 0; -} - -#define MS_FILTER_METHOD_GET_FID(id) (((id)>>16) & 0xFFFF) - -int ms_filter_call_method(MSFilter *f, unsigned int id, void *arg){ - MSFilterMethod *methods=f->desc->methods; - int i; - unsigned int magic=MS_FILTER_METHOD_GET_FID(id); - if (magic!=MS_FILTER_BASE_ID && magic!=f->desc->id) { - ms_fatal("Method type checking failed when calling %u on filter %s",id,f->desc->name); - return -1; - } - for(i=0;methods!=NULL && methods[i].method!=NULL; i++){ - unsigned int mm=MS_FILTER_METHOD_GET_FID(methods[i].id); - if (mm!=f->desc->id && mm!=MS_FILTER_BASE_ID) { - ms_fatal("Bad method definition on filter %s. fid=%u , mm=%u",f->desc->name,f->desc->id,mm); - return -1; - } - if (methods[i].id==id){ - return methods[i].method(f,arg); - } - } - if (magic!=MS_FILTER_BASE_ID) ms_error("no such method on filter %s",f->desc->name); - return -1; -} - -int ms_filter_call_method_noarg(MSFilter *f, unsigned int id){ - return ms_filter_call_method(f,id,NULL); -} - -void ms_filter_set_notify_callback(MSFilter *f, MSFilterNotifyFunc fn, void *ud){ - f->notify=fn; - f->notify_ud=ud; -} - -void ms_filter_destroy(MSFilter *f){ - if (f->desc->uninit!=NULL) - f->desc->uninit(f); - if (f->inputs!=NULL) ms_free(f->inputs); - if (f->outputs!=NULL) ms_free(f->outputs); - ms_mutex_destroy(&f->lock); - ms_free(f); -} - - -void ms_filter_process(MSFilter *f){ - ms_debug("Executing process of filter %s:%p",f->desc->name,f); - f->desc->process(f); -} - -void ms_filter_preprocess(MSFilter *f, struct _MSTicker *t){ - f->last_tick=0; - f->ticker=t; - if (f->desc->preprocess!=NULL) - f->desc->preprocess(f); -} - -void ms_filter_postprocess(MSFilter *f){ - if (f->desc->postprocess!=NULL) - f->desc->postprocess(f); - f->ticker=NULL; -} - -bool_t ms_filter_inputs_have_data(MSFilter *f){ - int i; - for(i=0;idesc->ninputs;i++){ - MSQueue *q=f->inputs[i]; - if (q!=NULL && q->q.q_mcount>0) return TRUE; - } - return FALSE; -} - -void ms_filter_notify(MSFilter *f, unsigned int id, void *arg){ - if (f->notify!=NULL) - f->notify(f->notify_ud,id,arg); -} - -void ms_filter_notify_no_arg(MSFilter *f, unsigned int id){ - if (f->notify!=NULL) - f->notify(f->notify_ud,id,NULL); -} - - -static void find_filters(MSList **filters, MSFilter *f ){ - int i,found; - MSQueue *link; - if (f==NULL) ms_fatal("Bad graph."); - /*ms_message("seeing %s, seen=%i",f->desc->name,f->seen);*/ - if (f->seen){ - return; - } - f->seen=TRUE; - *filters=ms_list_append(*filters,f); - /* go upstream */ - for(i=0;idesc->ninputs;i++){ - link=f->inputs[i]; - if (link!=NULL) find_filters(filters,link->prev.filter); - } - /* go downstream */ - for(i=0,found=0;idesc->noutputs;i++){ - link=f->outputs[i]; - if (link!=NULL) { - found++; - find_filters(filters,link->next.filter); - } - } - if (f->desc->noutputs>=1 && found==0){ - ms_fatal("Bad graph: filter %s has %i outputs, none is connected.",f->desc->name,f->desc->noutputs); - } -} - -MSList * ms_filter_find_neighbours(MSFilter *me){ - MSList *l=NULL; - MSList *it; - find_filters(&l,me); - /*reset seen boolean for further lookups to succeed !*/ - for(it=l;it!=NULL;it=it->next){ - MSFilter *f=(MSFilter*)it->data; - f->seen=FALSE; - } - return l; -} - -void ms_connection_helper_start(MSConnectionHelper *h){ - h->last.filter=0; - h->last.pin=-1; -} - -int ms_connection_helper_link(MSConnectionHelper *h, MSFilter *f, int inpin, int outpin){ - int err=0; - if (h->last.filter==NULL){ - h->last.filter=f; - h->last.pin=outpin; - }else{ - err=ms_filter_link(h->last.filter,h->last.pin,f,inpin); - if (err==0){ - h->last.filter=f; - h->last.pin=outpin; - } - } - return err; -} - -int ms_connection_helper_unlink(MSConnectionHelper *h, MSFilter *f, int inpin, int outpin){ - int err=0; - if (h->last.filter==NULL){ - h->last.filter=f; - h->last.pin=outpin; - }else{ - err=ms_filter_unlink(h->last.filter,h->last.pin,f,inpin); - if (err==0){ - h->last.filter=f; - h->last.pin=outpin; - } - } - return err; -} - - diff --git a/linphone/mediastreamer2/src/msjoin.c b/linphone/mediastreamer2/src/msjoin.c deleted file mode 100644 index 9d04b0c1b..000000000 --- a/linphone/mediastreamer2/src/msjoin.c +++ /dev/null @@ -1,72 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" - -static void join_process(MSFilter *f){ - mblk_t *im; - if (f->inputs[0]!=NULL) - { - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - ms_queue_put(f->outputs[0],im); - } - } - if (f->inputs[1]!=NULL) - { - while((im=ms_queue_get(f->inputs[1]))!=NULL){ - int payload; - payload=mblk_set_payload_type(im, 123); - ms_queue_put(f->outputs[0],im); - } - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_join_desc={ - MS_JOIN_ID, - "MSJoin", - N_("A filter that send several inputs to one output."), - MS_FILTER_OTHER, - NULL, - 2, - 1, - NULL, - NULL, - join_process, - NULL, - NULL, - NULL -}; - -#else - -MSFilterDesc ms_join_desc={ - .id=MS_JOIN_ID, - .name="MSJoin", - .text=N_("A filter that send several inputs to one output."), - .category=MS_FILTER_OTHER, - .ninputs=2, - .noutputs=1, - .process=join_process -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_join_desc) diff --git a/linphone/mediastreamer2/src/msqueue.c b/linphone/mediastreamer2/src/msqueue.c deleted file mode 100644 index 66172a517..000000000 --- a/linphone/mediastreamer2/src/msqueue.c +++ /dev/null @@ -1,117 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msqueue.h" -#include "mediastreamer2/mscommon.h" -#include "mediastreamer2/msvideo.h" -#include - -MSQueue * ms_queue_new(struct _MSFilter *f1, int pin1, struct _MSFilter *f2, int pin2 ){ - MSQueue *q=(MSQueue*)ms_new(MSQueue,1); - qinit(&q->q); - q->prev.filter=f1; - q->prev.pin=pin1; - q->next.filter=f2; - q->next.pin=pin2; - return q; -} - -void ms_queue_init(MSQueue *q){ - q->prev.filter=0; - q->prev.pin=0; - q->next.filter=0; - q->next.pin=0; - qinit(&q->q); -} - -void ms_queue_destroy(MSQueue *q){ - flushq(&q->q,0); - ms_free(q); -} - -void ms_queue_flush(MSQueue *q){ - flushq(&q->q,0); -} - - -void ms_bufferizer_init(MSBufferizer *obj){ - qinit(&obj->q); - obj->size=0; -} - -MSBufferizer * ms_bufferizer_new(){ - MSBufferizer *obj=(MSBufferizer *)ms_new(MSBufferizer,1); - ms_bufferizer_init(obj); - return obj; -} - -void ms_bufferizer_put(MSBufferizer *obj, mblk_t *m){ - obj->size+=msgdsize(m); - putq(&obj->q,m); -} - -void ms_bufferizer_put_from_queue(MSBufferizer *obj, MSQueue *q){ - mblk_t *m; - while((m=ms_queue_get(q))!=NULL){ - ms_bufferizer_put(obj,m); - } -} - -int ms_bufferizer_read(MSBufferizer *obj, uint8_t *data, int datalen){ - if (obj->size>=datalen){ - int sz=0; - int cplen; - mblk_t *m=peekq(&obj->q); - /*we can return something */ - while(szb_wptr-m->b_rptr,datalen-sz); - memcpy(data+sz,m->b_rptr,cplen); - sz+=cplen; - m->b_rptr+=cplen; - if (m->b_rptr==m->b_wptr){ - /* check cont */ - if (m->b_cont!=NULL) { - m=m->b_cont; - } - else{ - mblk_t *remove=getq(&obj->q); - freemsg(remove); - m=peekq(&obj->q); - } - } - } - obj->size-=datalen; - return datalen; - } - return 0; -} - -void ms_bufferizer_flush(MSBufferizer *obj){ - obj->size=0; - flushq(&obj->q,0); -} - -void ms_bufferizer_uninit(MSBufferizer *obj){ - flushq(&obj->q,0); -} - -void ms_bufferizer_destroy(MSBufferizer *obj){ - ms_bufferizer_uninit(obj); - ms_free(obj); -} diff --git a/linphone/mediastreamer2/src/msresample.c b/linphone/mediastreamer2/src/msresample.c deleted file mode 100644 index 6347faa31..000000000 --- a/linphone/mediastreamer2/src/msresample.c +++ /dev/null @@ -1,252 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" - -#ifdef _MSC_VER -#include -#endif - -#include -#include - -typedef struct _ResampleData{ - MSBufferizer *bz; - uint32_t ts; - uint32_t input_rate; - uint32_t output_rate; - - SpeexResamplerState *handle; - int nb_unprocessed; -} ResampleData; - -static ResampleData * resample_data_new(){ - ResampleData *obj=(ResampleData *)ms_new(ResampleData,1); - obj->bz=ms_bufferizer_new(); - obj->ts=0; - obj->input_rate=8000; - obj->output_rate=16000; - obj->handle=NULL; - - obj->nb_unprocessed=0; - return obj; -} - -static void resample_data_destroy(ResampleData *obj){ - if (obj->handle!=NULL) - speex_resampler_destroy(obj->handle); - ms_bufferizer_destroy(obj->bz); - ms_free(obj); -} - -static void resample_init(MSFilter *obj){ - obj->data=resample_data_new(); -} - -static void resample_uninit(MSFilter *obj){ - resample_data_destroy((ResampleData*)obj->data); - -} - -#if 0 -static void resample_process_ms2(MSFilter *obj){ - ResampleData *dt=(ResampleData*)obj->data; - MSBufferizer *bz=dt->bz; - uint8_t buffer[2240]; - int size_of_input; - int size_of_output; - - mblk_t *m; - - if (dt->output_rate==dt->input_rate) - { - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - ms_queue_put(obj->outputs[0],m); - } - return; - } - if (dt->handle!=NULL){ - unsigned int inrate=0, outrate=0; - speex_resampler_get_rate(dt->handle,&inrate,&outrate); - if (inrate!=dt->input_rate || outrate!=dt->output_rate){ - speex_resampler_destroy(dt->handle); - dt->handle=0; - } - } - if (dt->handle==NULL){ - int err=0; - dt->handle=speex_resampler_init(1, dt->input_rate, dt->output_rate, SPEEX_RESAMPLER_QUALITY_VOIP, &err); - } - - - if (dt->input_rateoutput_rate) - size_of_input=320*dt->input_rate/8000; - else - size_of_input=320*dt->input_rate/8000; - size_of_output = (size_of_input * dt->output_rate)/dt->input_rate; - - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - ms_bufferizer_put(bz,m); - } - while (ms_bufferizer_read(bz,buffer,size_of_input)==size_of_input){ - mblk_t *obl=allocb(size_of_output,0); - - float *in; - float *out; - spx_uint32_t in_len; - spx_uint32_t out_len; - int err; - - short *data = (short*)buffer; - short *data_out = (short*)obl->b_wptr; - - int i; - spx_uint32_t idx; - - in = (float*) alloca((size_of_input/2)*sizeof(float)); - out = (float*) alloca((size_of_output/2)*sizeof(float)); - - /* Convert the samples to floats */ - for (i = 0; i < size_of_input/2; i++) - in[i] = (float) data[i]; - - in_len = size_of_input/2; - out_len = size_of_output/2; - err = speex_resampler_process_float(dt->handle, 0, in, &in_len, out, &out_len); - - /* ms_message("resampling info: err=%i in_len=%i, out_len=%i", err, in_len, out_len); */ - - for (idx=0;idxb_wptr=obl->b_wptr+(out_len*2); /* size_of_output; */ - - mblk_set_timestamp_info(obl,dt->ts); - dt->ts+=160; - ms_queue_put(obj->outputs[0],obl); - } -} - -#else -static void resample_process_ms2(MSFilter *obj){ - ResampleData *dt=(ResampleData*)obj->data; - mblk_t *m; - - if (dt->output_rate==dt->input_rate){ - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - ms_queue_put(obj->outputs[0],m); - } - return; - } - - if (dt->handle!=NULL){ - unsigned int inrate=0, outrate=0; - speex_resampler_get_rate(dt->handle,&inrate,&outrate); - if (inrate!=dt->input_rate || outrate!=dt->output_rate){ - speex_resampler_destroy(dt->handle); - dt->handle=0; - } - } - if (dt->handle==NULL){ - int err=0; - dt->handle=speex_resampler_init(1, dt->input_rate, dt->output_rate, SPEEX_RESAMPLER_QUALITY_VOIP, &err); - } - - - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - unsigned int inlen=(m->b_wptr-m->b_rptr)/2; - unsigned int outlen=((inlen*dt->output_rate)/dt->input_rate)+1; - unsigned int inlen_orig=inlen; - mblk_t *om=allocb(outlen*2,0); - speex_resampler_process_int(dt->handle, - 0, - (int16_t*)m->b_rptr, - &inlen, - (int16_t*)om->b_wptr, - &outlen); - if (inlen_orig!=inlen){ - ms_error("Bug in resampler ! only %u samples consumed instead of %u, out=%u", - inlen,inlen_orig,outlen); - } - om->b_wptr+=outlen*2; - mblk_set_timestamp_info(om,dt->ts); - dt->ts+=outlen; - ms_queue_put(obj->outputs[0],om); - freemsg(m); - } -} - -#endif - - - -int ms_resample_set_sr(MSFilter *obj, void *arg){ - ResampleData *dt=(ResampleData*)obj->data; - dt->input_rate=((int*)arg)[0]; - return 0; -} - -int ms_resample_set_output_sr(MSFilter *obj, void *arg){ - ResampleData *dt=(ResampleData*)obj->data; - dt->output_rate=((int*)arg)[0]; - return 0; -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , ms_resample_set_sr }, - { MS_FILTER_SET_OUTPUT_SAMPLE_RATE , ms_resample_set_output_sr }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_resample_desc={ - MS_RESAMPLE_ID, - "MSResample", - N_("frequency resampler"), - MS_FILTER_OTHER, - NULL, - 1, - 1, - resample_init, - NULL, - resample_process_ms2, - NULL, - resample_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_resample_desc={ - .id=MS_RESAMPLE_ID, - .name="MSResample", - .text=N_("frequency resampler"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=1, - .init=resample_init, - .process=resample_process_ms2, - .uninit=resample_uninit, - .methods=enc_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_resample_desc) - diff --git a/linphone/mediastreamer2/src/msrtp.c b/linphone/mediastreamer2/src/msrtp.c deleted file mode 100644 index 79a4a3fad..000000000 --- a/linphone/mediastreamer2/src/msrtp.c +++ /dev/null @@ -1,525 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msrtp.h" -#include "mediastreamer2/msticker.h" - -#include "ortp/telephonyevents.h" -#if defined(__cplusplus) -#define B64_NO_NAMESPACE -#endif -#include "ortp/b64.h" - - -struct SenderData { - RtpSession *session; - uint32_t tsoff; - uint32_t skip_until; - int rate; - char dtmf; - bool_t dtmf_start; - int dtmf_duration; - char relay_session_id[64]; - int relay_session_id_size; - uint64_t last_rsi_time; - bool_t skip; - bool_t mute_mic; -}; - -typedef struct SenderData SenderData; - -static void sender_init(MSFilter * f) -{ - SenderData *d = (SenderData *)ms_new(SenderData, 1); - - d->session = NULL; - d->tsoff = 0; - d->skip_until = 0; - d->skip = FALSE; - d->rate = 8000; - d->dtmf = 0; - d->dtmf_start = FALSE; - d->dtmf_duration = 800; - d->mute_mic=FALSE; - d->relay_session_id_size=0; - d->last_rsi_time=0; - f->data = d; -} - -static void sender_uninit(MSFilter * f) -{ - SenderData *d = (SenderData *) f->data; - - ms_free(d); -} - -static int sender_send_dtmf(MSFilter * f, void *arg) -{ - const char *dtmf = (const char *) arg; - SenderData *d = (SenderData *) f->data; - - ms_filter_lock(f); - if (d->skip==TRUE) - { - ms_filter_unlock(f); - return -1; - } - d->dtmf = dtmf[0]; - ms_filter_unlock(f); - return 0; -} - -static int sender_set_dtmf_duration(MSFilter * f, void *arg) -{ - SenderData *d = (SenderData *) f->data; - d->dtmf_duration = *((int*)arg); - return 0; -} - -static int sender_set_session(MSFilter * f, void *arg) -{ - SenderData *d = (SenderData *) f->data; - RtpSession *s = (RtpSession *) arg; - PayloadType *pt = - rtp_profile_get_payload(rtp_session_get_profile(s), - rtp_session_get_send_payload_type(s)); - if (pt != NULL) { - if (strcasecmp("g722", pt->mime_type)==0 ) - d->rate=8000; - else d->rate = pt->clock_rate; - } else { - ms_warning("Sending undefined payload type ?"); - } - d->session = s; - return 0; -} - -static int sender_mute_mic(MSFilter * f, void *arg) -{ - SenderData *d = (SenderData *) f->data; - ms_filter_lock(f); - d->mute_mic=TRUE; - ms_filter_unlock(f); - return 0; -} - -static int sender_unmute_mic(MSFilter * f, void *arg) -{ - SenderData *d = (SenderData *) f->data; - ms_filter_lock(f); - d->mute_mic=FALSE; - ms_filter_unlock(f); - return 0; -} - -static int sender_set_relay_session_id(MSFilter *f, void*arg){ - SenderData *d = (SenderData *) f->data; - const char *tmp=(const char *)arg; - d->relay_session_id_size=b64_decode(tmp, strlen(tmp), (void*)d->relay_session_id, (unsigned int)sizeof(d->relay_session_id)); - return 0; -} - -static int sender_get_sr(MSFilter *f, void *arg){ - SenderData *d = (SenderData *) f->data; - *(int*)arg=d->rate; - return 0; -} - -/* the goal of that function is to return a absolute timestamp closest to real time, with respect of given packet_ts, which is a relative to an undefined origin*/ -static uint32_t get_cur_timestamp(MSFilter * f, uint32_t packet_ts) -{ - SenderData *d = (SenderData *) f->data; - uint32_t curts = (uint32_t)( (f->ticker->time*(uint64_t)d->rate)/(uint64_t)1000) ; - int diff; - int delta = d->rate / 50; /*20 ms at 8000Hz */ - uint32_t netts; - - netts = packet_ts + d->tsoff; - diff = curts - netts; - -#ifdef AMD_HACK - if (diff > delta) { - d->tsoff = curts - packet_ts; - netts = packet_ts + d->tsoff; - ms_message("synchronizing timestamp, diff=%i", diff); - } - else if (diff < -delta) { - /* d->tsoff = curts - packet_ts; */ - /* hardware clock is going slower than sound card on my PDA... */ - } -#else - if ((diff > delta) || (diff < -(delta * 5))) { - d->tsoff = curts - packet_ts; - netts = packet_ts + d->tsoff; - ms_message("synchronizing timestamp, diff=%i", diff); - } -#endif - - /*ms_message("returned ts=%u, orig_ts=%u",netts,packet_ts); */ - return netts; -} - -static int send_dtmf(MSFilter * f, uint32_t timestamp_start, uint32_t current_timestamp) -{ - SenderData *d = (SenderData *) f->data; - mblk_t *m1; - int tev_type; - - /* create the first telephony event packet */ - switch (d->dtmf){ - case '1': - tev_type=TEV_DTMF_1; - break; - case '2': - tev_type=TEV_DTMF_2; - break; - case '3': - tev_type=TEV_DTMF_3; - break; - case '4': - tev_type=TEV_DTMF_4; - break; - case '5': - tev_type=TEV_DTMF_5; - break; - case '6': - tev_type=TEV_DTMF_6; - break; - case '7': - tev_type=TEV_DTMF_7; - break; - case '8': - tev_type=TEV_DTMF_8; - break; - case '9': - tev_type=TEV_DTMF_9; - break; - case '*': - tev_type=TEV_DTMF_STAR; - break; - case '0': - tev_type=TEV_DTMF_0; - break; - case '#': - tev_type=TEV_DTMF_POUND; - break; - - case 'A': - case 'a': - tev_type=TEV_DTMF_A; - break; - - - case 'B': - case 'b': - tev_type=TEV_DTMF_B; - break; - - case 'C': - case 'c': - tev_type=TEV_DTMF_C; - break; - - case 'D': - case 'd': - tev_type=TEV_DTMF_D; - break; - - case '!': - tev_type=TEV_FLASH; - break; - - - default: - ms_warning("Bad dtmf: %c.",d->dtmf); - return -1; - } - - - if (d->dtmf_start == TRUE) - m1=rtp_session_create_telephone_event_packet(d->session,1); - else - m1=rtp_session_create_telephone_event_packet(d->session,0); - if (m1==NULL) return -1; - - - if (RTP_TIMESTAMP_IS_NEWER_THAN(current_timestamp, d->skip_until)) { - //retransmit end of rtp dtmf event - mblk_t *tmp; - rtp_session_add_telephone_event(d->session,m1,tev_type,1,10, (current_timestamp-timestamp_start)); - tmp=copymsg(m1); - rtp_session_sendm_with_ts(d->session,tmp,timestamp_start); - d->session->rtp.snd_seq--; - tmp=copymsg(m1); - rtp_session_sendm_with_ts(d->session,tmp,timestamp_start); - d->session->rtp.snd_seq--; - rtp_session_sendm_with_ts(d->session,m1,timestamp_start); - } - else { - rtp_session_add_telephone_event(d->session,m1,tev_type,0,10, (current_timestamp-timestamp_start)); - rtp_session_sendm_with_ts(d->session,m1,timestamp_start); - } - return 0; -} - -static void sender_process(MSFilter * f) -{ - SenderData *d = (SenderData *) f->data; - RtpSession *s = d->session; - - mblk_t *im; - uint32_t timestamp; - - if (s == NULL){ - ms_queue_flush(f->inputs[0]); - return; - } - - if (d->relay_session_id_size>0 && - ( (f->ticker->time-d->last_rsi_time)>5000 || d->last_rsi_time==0) ) { - ms_message("relay session id sent in RTCP APP"); - rtp_session_send_rtcp_APP(s,0,"RSID",(const uint8_t *)d->relay_session_id,d->relay_session_id_size); - d->last_rsi_time=f->ticker->time; - } - - while ((im = ms_queue_get(f->inputs[0])) != NULL) { - mblk_t *header; - - timestamp = get_cur_timestamp(f, mblk_get_timestamp_info(im)); - ms_filter_lock(f); - if (d->skip) { - ms_debug("skipping.."); - send_dtmf(f, d->skip_until-d->dtmf_duration, timestamp); - d->dtmf_start = FALSE; - if (!RTP_TIMESTAMP_IS_NEWER_THAN(timestamp, d->skip_until)) { - freemsg(im); - ms_filter_unlock(f); - continue; - } - d->skip = FALSE; - d->dtmf = 0; - } - - if (d->skip == FALSE && d->mute_mic==FALSE){ - int pt = mblk_get_payload_type(im); - header = rtp_session_create_packet(s, 12, NULL, 0); - if (pt>0) - rtp_set_payload_type(header, pt); - rtp_set_markbit(header, mblk_get_marker_info(im)); - header->b_cont = im; - rtp_session_sendm_with_ts(s, header, timestamp); - } - else{ - freemsg(im); - } - - if (d->dtmf != 0) { - ms_debug("prepare to send RFC2833 dtmf."); - d->skip_until = timestamp + d->dtmf_duration; - d->skip = TRUE; - d->dtmf_start = TRUE; - } - ms_filter_unlock(f); - } -} - -static MSFilterMethod sender_methods[] = { - {MS_RTP_SEND_MUTE_MIC, sender_mute_mic}, - {MS_RTP_SEND_UNMUTE_MIC, sender_unmute_mic}, - {MS_RTP_SEND_SET_SESSION, sender_set_session}, - {MS_RTP_SEND_SEND_DTMF, sender_send_dtmf}, - {MS_RTP_SEND_SET_RELAY_SESSION_ID, sender_set_relay_session_id}, - {MS_FILTER_GET_SAMPLE_RATE, sender_get_sr }, - {MS_RTP_SEND_SET_DTMF_DURATION, sender_set_dtmf_duration }, - {0, NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_rtp_send_desc = { - MS_RTP_SEND_ID, - "MSRtpSend", - N_("RTP output filter"), - MS_FILTER_OTHER, - NULL, - 1, - 0, - sender_init, - NULL, - sender_process, - NULL, - sender_uninit, - sender_methods -}; - -#else - -MSFilterDesc ms_rtp_send_desc = { - .id = MS_RTP_SEND_ID, - .name = "MSRtpSend", - .text = N_("RTP output filter"), - .category = MS_FILTER_OTHER, - .ninputs = 1, - .noutputs = 0, - .init = sender_init, - .process = sender_process, - .uninit = sender_uninit, - .methods = sender_methods -}; - -#endif - -struct ReceiverData { - RtpSession *session; - int rate; -}; - -typedef struct ReceiverData ReceiverData; - -static void receiver_init(MSFilter * f) -{ - ReceiverData *d = (ReceiverData *)ms_new(ReceiverData, 1); - d->session = NULL; - d->rate = 8000; - f->data = d; -} - -static void receiver_postprocess(MSFilter * f){ - /*ReceiverData *d = (ReceiverData *) f->data;*/ -} - -static void receiver_uninit(MSFilter * f){ - ReceiverData *d = (ReceiverData *) f->data; - ms_free(d); -} - -static int receiver_set_session(MSFilter * f, void *arg) -{ - ReceiverData *d = (ReceiverData *) f->data; - RtpSession *s = (RtpSession *) arg; - PayloadType *pt = rtp_profile_get_payload(rtp_session_get_profile(s), - rtp_session_get_recv_payload_type - (s)); - if (pt != NULL) { - if (strcasecmp("g722", pt->mime_type)==0 ) - d->rate=8000; - else d->rate = pt->clock_rate; - } else { - ms_warning("Receiving undefined payload type ?"); - } - d->session = s; - - return 0; -} - -static int receiver_get_sr(MSFilter *f, void *arg){ - ReceiverData *d = (ReceiverData *) f->data; - PayloadType *pt; - if (d->session==NULL) { - ms_warning("Could not obtain sample rate, session is not set."); - return -1; - } - pt=rtp_profile_get_payload(rtp_session_get_profile(d->session), - rtp_session_get_recv_payload_type(d->session)); - if (pt != NULL) { - *(int*)arg=pt->clock_rate; - }else{ - ms_warning("Could not obtain sample rate, payload type is unknown."); - return -1; - } - return 0; -} - -static void receiver_preprocess(MSFilter * f){ - ReceiverData *d = (ReceiverData *) f->data; - if (d->session){ - PayloadType *pt=rtp_profile_get_payload( - rtp_session_get_profile(d->session), - rtp_session_get_recv_payload_type(d->session)); - if (pt){ - if (pt->type!=PAYLOAD_VIDEO) - rtp_session_flush_sockets(d->session); - } - } -} - -static void receiver_process(MSFilter * f) -{ - ReceiverData *d = (ReceiverData *) f->data; - mblk_t *m; - uint32_t timestamp; - - if (d->session == NULL) - return; - - timestamp = (uint32_t) (f->ticker->time * (d->rate/1000)); - while ((m = rtp_session_recvm_with_ts(d->session, timestamp)) != NULL) { - mblk_set_timestamp_info(m, rtp_get_timestamp(m)); - mblk_set_marker_info(m, rtp_get_markbit(m)); - mblk_set_payload_type(m, rtp_get_payload_type(m)); - rtp_get_payload(m,&m->b_rptr); - ms_queue_put(f->outputs[0], m); - } -} - -static MSFilterMethod receiver_methods[] = { - { MS_RTP_RECV_SET_SESSION , receiver_set_session }, - { MS_FILTER_GET_SAMPLE_RATE , receiver_get_sr }, - { 0, NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_rtp_recv_desc = { - MS_RTP_RECV_ID, - "MSRtpRecv", - N_("RTP input filter"), - MS_FILTER_OTHER, - NULL, - 0, - 1, - receiver_init, - receiver_preprocess, - receiver_process, - receiver_postprocess, - receiver_uninit, - receiver_methods -}; - -#else - -MSFilterDesc ms_rtp_recv_desc = { - .id = MS_RTP_RECV_ID, - .name = "MSRtpRecv", - .text = N_("RTP input filter"), - .category = MS_FILTER_OTHER, - .ninputs = 0, - .noutputs = 1, - .init = receiver_init, - .preprocess = receiver_preprocess, - .process = receiver_process, - .postprocess=receiver_postprocess, - .uninit = receiver_uninit, - .methods = receiver_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_rtp_send_desc) -MS_FILTER_DESC_EXPORT(ms_rtp_recv_desc) diff --git a/linphone/mediastreamer2/src/mssndcard.c b/linphone/mediastreamer2/src/mssndcard.c deleted file mode 100644 index 593e3ec8f..000000000 --- a/linphone/mediastreamer2/src/mssndcard.c +++ /dev/null @@ -1,231 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mssndcard.h" -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -static MSSndCardManager *scm=NULL; - -static MSSndCardManager * create_manager(){ - MSSndCardManager *obj=(MSSndCardManager *)ms_new(MSSndCardManager,1); - obj->cards=NULL; - obj->descs=NULL; - return obj; -} - -void ms_snd_card_manager_destroy(void){ - if (scm!=NULL){ - MSList *elem; - for(elem=scm->descs;elem!=NULL;elem=elem->next){ - MSSndCardDesc *desc = (MSSndCardDesc*)elem->data; - if (desc->unload!=NULL) - desc->unload(scm); - } - ms_list_for_each(scm->cards,(void (*)(void*))ms_snd_card_destroy); - ms_list_free(scm->cards); - ms_list_free(scm->descs); - } - ms_free(scm); - scm=NULL; -} - -MSSndCardManager * ms_snd_card_manager_get(void){ - if (scm==NULL) scm=create_manager(); - return scm; -} - -MSSndCard * ms_snd_card_manager_get_card(MSSndCardManager *m, const char *id){ - MSList *elem; - for (elem=m->cards;elem!=NULL;elem=elem->next){ - MSSndCard *card=(MSSndCard*)elem->data; - if (id==NULL) return card; - if (strcmp(ms_snd_card_get_string_id(card),id)==0) return card; - } - if (id!=NULL) ms_warning("no card with id %s",id); - return NULL; -} - -MSSndCard * ms_snd_card_manager_get_default_card(MSSndCardManager *m){ - /*return the first card that has the capture+playback capability */ - MSList *elem; - for (elem=m->cards;elem!=NULL;elem=elem->next){ - MSSndCard *card=(MSSndCard*)elem->data; - if ((card->capabilities & MS_SND_CARD_CAP_CAPTURE ) - && (card->capabilities & MS_SND_CARD_CAP_PLAYBACK)) - return card; - } - return NULL; -} - -MSSndCard * ms_snd_card_manager_get_default_capture_card(MSSndCardManager *m){ - MSList *elem; - for (elem=m->cards;elem!=NULL;elem=elem->next){ - MSSndCard *card=(MSSndCard*)elem->data; - if (card->capabilities & MS_SND_CARD_CAP_CAPTURE) - return card; - } - return NULL; -} - -MSSndCard * ms_snd_card_manager_get_default_playback_card(MSSndCardManager *m){ - MSList *elem; - for (elem=m->cards;elem!=NULL;elem=elem->next){ - MSSndCard *card=(MSSndCard*)elem->data; - if (card->capabilities & MS_SND_CARD_CAP_PLAYBACK) - return card; - } - return NULL; -} - -const MSList * ms_snd_card_manager_get_list(MSSndCardManager *m){ - return m->cards; -} - -void ms_snd_card_manager_add_card(MSSndCardManager *m, MSSndCard *c){ - ms_message("Card %s added",ms_snd_card_get_string_id(c)); - m->cards=ms_list_append(m->cards,c); -} - -static void card_detect(MSSndCardManager *m, MSSndCardDesc *desc){ - if (desc->detect!=NULL) - desc->detect(m); -} - -void ms_snd_card_manager_register_desc(MSSndCardManager *m, MSSndCardDesc *desc){ - m->descs=ms_list_append(m->descs,desc); - card_detect(m,desc); -} - -void ms_snd_card_manager_reload(MSSndCardManager *m){ - MSList *elem; - ms_list_for_each(m->cards,(void (*)(void*))ms_snd_card_destroy); - ms_list_free(m->cards); - m->cards=NULL; - for(elem=m->descs;elem!=NULL;elem=elem->next) - card_detect(m,(MSSndCardDesc*)elem->data); -} - -MSSndCard * ms_snd_card_dup(MSSndCard *card){ - MSSndCard *obj=NULL; - if (card->desc->duplicate!=NULL) - obj=card->desc->duplicate(card); - return obj; -} - -MSSndCard * ms_snd_card_new(MSSndCardDesc *desc){ - MSSndCard *obj=(MSSndCard *)ms_new(MSSndCard,1); - obj->desc=desc; - obj->name=NULL; - obj->data=NULL; - obj->id=NULL; - obj->capabilities=MS_SND_CARD_CAP_CAPTURE|MS_SND_CARD_CAP_PLAYBACK; - if (desc->init!=NULL) - desc->init(obj); - return obj; -} - -const char *ms_snd_card_get_driver_type(const MSSndCard *obj){ - return obj->desc->driver_type; -} - -const char *ms_snd_card_get_name(const MSSndCard *obj){ - return obj->name; -} - -unsigned int ms_snd_card_get_capabilities(const MSSndCard *obj){ - return obj->capabilities; -} - -const char *ms_snd_card_get_string_id(MSSndCard *obj){ - if (obj->id==NULL) obj->id=ms_strdup_printf("%s: %s",obj->desc->driver_type,obj->name); - return obj->id; -} - -void ms_snd_card_set_level(MSSndCard *obj, MSSndCardMixerElem e, int percent){ - if (obj->desc->set_level!=NULL) - obj->desc->set_level(obj,e,percent); - else ms_warning("ms_snd_card_set_level: unimplemented by %s wrapper",obj->desc->driver_type); -} - -int ms_snd_card_get_level(MSSndCard *obj, MSSndCardMixerElem e){ - if (obj->desc->get_level!=NULL) - return obj->desc->get_level(obj,e); - else { - ms_warning("ms_snd_card_get_level: unimplemented by %s wrapper",obj->desc->driver_type); - return -1; - } -} - -void ms_snd_card_set_capture(MSSndCard *obj, MSSndCardCapture c){ - if (obj->desc->set_capture!=NULL) - obj->desc->set_capture(obj,c); - else ms_warning("ms_snd_card_set_capture: unimplemented by %s wrapper",obj->desc->driver_type); -} - -int ms_snd_card_set_control(MSSndCard *obj, MSSndCardControlElem e, int val) -{ - if (obj->desc->set_control!=NULL) - return obj->desc->set_control(obj,e,val); - else { - ms_warning("ms_snd_card_set_control: unimplemented by %s wrapper",obj->desc->driver_type); - return -1; - } -} - -int ms_snd_card_get_control(MSSndCard *obj, MSSndCardControlElem e) -{ - if (obj->desc->get_control!=NULL) - return obj->desc->get_control(obj,e); - else { - ms_warning("ms_snd_card_get_control: unimplemented by %s wrapper",obj->desc->driver_type); - return -1; - } -} - -struct _MSFilter * ms_snd_card_create_reader(MSSndCard *obj){ - if (obj->desc->create_reader!=NULL) - return obj->desc->create_reader(obj); - else ms_warning("ms_snd_card_create_reader: unimplemented by %s wrapper",obj->desc->driver_type); - return NULL; -} - -struct _MSFilter * ms_snd_card_create_writer(MSSndCard *obj){ - if (obj->desc->create_writer!=NULL) - return obj->desc->create_writer(obj); - else ms_warning("ms_snd_card_create_writer: unimplemented by %s wrapper",obj->desc->driver_type); - return NULL; -} - -void ms_snd_card_destroy(MSSndCard *obj){ - if (obj->desc->uninit!=NULL) obj->desc->uninit(obj); - if (obj->name!=NULL) ms_free(obj->name); - if (obj->id!=NULL) ms_free(obj->id); - ms_free(obj); -} - -#ifdef __linux -#ifndef __ALSA_ENABLED__ -MSSndCard * ms_alsa_card_new_custom(const char *pcmdev, const char *mixdev){ - ms_warning("Alsa support not available in this build of mediastreamer2"); - return NULL; -} -#endif -#endif diff --git a/linphone/mediastreamer2/src/msspeex.c b/linphone/mediastreamer2/src/msspeex.c deleted file mode 100644 index 871db5409..000000000 --- a/linphone/mediastreamer2/src/msspeex.c +++ /dev/null @@ -1,538 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" - -#include - -#ifdef WIN32 -#include /* for alloca */ -#endif - -typedef struct SpeexEncState{ - int rate; - int bitrate; - int maxbitrate; - int ptime; - int vbr; - int cng; - int mode; - int frame_size; - void *state; - uint32_t ts; - MSBufferizer *bufferizer; -} SpeexEncState; - -static void enc_init(MSFilter *f){ - SpeexEncState *s=(SpeexEncState *)ms_new(SpeexEncState,1); - s->rate=8000; - s->bitrate=-1; - s->maxbitrate=-1; - s->ptime=0; - s->mode=-1; - s->vbr=0; - s->cng=0; - s->frame_size=0; - s->state=0; - s->ts=0; - s->bufferizer=ms_bufferizer_new(); - f->data=s; -} - -static void enc_uninit(MSFilter *f){ - SpeexEncState *s=(SpeexEncState*)f->data; - if (s==NULL) - return; - ms_bufferizer_destroy(s->bufferizer); - if (s->state!=NULL) - speex_encoder_destroy(s->state); - ms_free(s); -} - -static void enc_preprocess(MSFilter *f){ - SpeexEncState *s=(SpeexEncState*)f->data; - const SpeexMode *mode=NULL; - int _mode=0; - - switch(s->rate){ - case 8000: - _mode = SPEEX_MODEID_NB; /* rate = 8000Hz */ - break; - case 16000: - _mode = SPEEX_MODEID_WB; /* rate = 16000Hz */ - break; - /* should be supported in the future */ - case 32000: - _mode = SPEEX_MODEID_UWB; /* rate = 32000Hz */ - break; - default: - ms_error("Unsupported rate for speex encoder (back to default rate=8000)."); - s->rate=8000; - } - /* warning: speex_lib_get_mode() is not available on speex<1.1.12 */ - mode = speex_lib_get_mode(_mode); - - if (mode==NULL) - return; - s->state=speex_encoder_init(mode); - - if (s->vbr==1) - { - if (speex_encoder_ctl(s->state,SPEEX_SET_VBR,&s->vbr)!=0){ - ms_error("Could not set vbr mode to speex encoder."); - } - /* implicit VAD */ - speex_encoder_ctl (s->state, SPEEX_SET_DTX, &s->vbr); - } - else if (s->vbr==2) - { - int vad=1; - /* VAD */ - speex_encoder_ctl (s->state, SPEEX_SET_VAD, &vad); - speex_encoder_ctl (s->state, SPEEX_SET_DTX, &vad); - } - else if (s->cng==1) - { - speex_encoder_ctl (s->state, SPEEX_SET_VAD, &s->cng); - } - - if (s->rate==8000){ - //+------+---------------+-------------+ - //| mode | Speex quality | bit-rate | - //+------+---------------+-------------+ - //| 1 | 0 | 2.15 kbit/s | - //| 2 | 2 | 5.95 kbit/s | - //| 3 | 3 or 4 | 8.00 kbit/s | - //| 4 | 5 or 6 | 11.0 kbit/s | - //| 5 | 7 or 8 | 15.0 kbit/s | - //| 6 | 9 | 18.2 kbit/s | - //| 7 | 10 | 24.6 kbit/s | - //| 8 | 1 | 3.95 kbit/s | - //+------+---------------+-------------+ - if (s->mode<=0 || s->mode>8) - s->mode = 3; /* default mode */ - - if (s->mode==1) - s->bitrate = 2150; - else if (s->mode==2) - s->bitrate = 5950; - else if (s->mode==3) - s->bitrate = 8000; - else if (s->mode==4) - s->bitrate = 11000; - else if (s->mode==5) - s->bitrate = 15000; - else if (s->mode==6) - s->bitrate = 18200; - else if (s->mode==7) - s->bitrate = 24600; - else if (s->mode==8) - s->bitrate = 3950; - - if (s->bitrate!=-1){ - if (speex_encoder_ctl(s->state,SPEEX_SET_BITRATE,&s->bitrate)!=0){ - ms_error("Could not set bitrate %i to speex encoder.",s->bitrate); - } - } - } - else if (s->rate==16000 || s->rate==32000){ - //+------+---------------+-------------------+------------------------+ - //| mode | Speex quality | wideband bit-rate | ultra wideband | - //| | | | bit-rate | - //+------+---------------+-------------------+------------------------+ - //| 0 | 0 | 3.95 kbit/s | 5.75 kbit/s | - //| 1 | 1 | 5.75 kbit/s | 7.55 kbit/s | - //| 2 | 2 | 7.75 kbit/s | 9.55 kbit/s | - //| 3 | 3 | 9.80 kbit/s | 11.6 kbit/s | - //| 4 | 4 | 12.8 kbit/s | 14.6 kbit/s | - //| 5 | 5 | 16.8 kbit/s | 18.6 kbit/s | - //| 6 | 6 | 20.6 kbit/s | 22.4 kbit/s | - //| 7 | 7 | 23.8 kbit/s | 25.6 kbit/s | - //| 8 | 8 | 27.8 kbit/s | 29.6 kbit/s | - //| 9 | 9 | 34.2 kbit/s | 36.0 kbit/s | - //| 10 | 10 | 42.2 kbit/s | 44.0 kbit/s | - //+------+---------------+-------------------+------------------------+ - int q=0; - if (s->mode<0 || s->mode>10) - s->mode = 8; /* default mode */ - q=s->mode; - if (speex_encoder_ctl(s->state,SPEEX_SET_QUALITY,&q)!=0){ - ms_error("Could not set quality %i to speex encoder.",q); - } - } - - if (s->maxbitrate>0){ - /* convert from network bitrate to codec bitrate:*/ - /* ((nbr/(50*8)) -20-12-8)*50*8*/ - int cbr=(int)( ((((float)s->maxbitrate)/(50.0*8))-20-12-8)*50*8); - ms_message("Setting maxbitrate=%i to speex encoder.",cbr); - if (speex_encoder_ctl(s->state,SPEEX_SET_BITRATE,&cbr)!=0){ - ms_error("Could not set maxbitrate %i to speex encoder.",s->bitrate); - } - } - if (speex_encoder_ctl(s->state,SPEEX_GET_BITRATE,&s->bitrate)!=0){ - ms_error("Could not get bitrate %i to speex encoder.",s->bitrate); - } - else ms_message("Using bitrate %i for speex encoder.",s->bitrate); - - speex_mode_query(mode,SPEEX_MODE_FRAME_SIZE,&s->frame_size); -} - -static void enc_process(MSFilter *f){ - SpeexEncState *s=(SpeexEncState*)f->data; - mblk_t *im; - int nbytes; - uint8_t *buf; - int frame_per_packet=1; - - if (s->frame_size<=0) - return; - - if (s->ptime>=20) - { - frame_per_packet = s->ptime/20; - } - - if (frame_per_packet<=0) - frame_per_packet=1; - if (frame_per_packet>7) /* 7*20 == 140 ms max */ - frame_per_packet=7; - - nbytes=s->frame_size*2; - buf=(uint8_t*)alloca(nbytes*frame_per_packet); - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - ms_bufferizer_put(s->bufferizer,im); - } - while(ms_bufferizer_read(s->bufferizer,buf,nbytes*frame_per_packet)==nbytes*frame_per_packet){ - mblk_t *om=allocb(nbytes*frame_per_packet,0);//too large... - int k; - SpeexBits bits; - speex_bits_init(&bits); - for (k=0;kstate,(int16_t*)(buf + (k*s->frame_size*2)),&bits); - s->ts+=s->frame_size; - } - speex_bits_insert_terminator(&bits); - k=speex_bits_write(&bits, (char*)om->b_wptr, nbytes*frame_per_packet); - om->b_wptr+=k; - - mblk_set_timestamp_info(om,s->ts-s->frame_size); - ms_queue_put(f->outputs[0],om); - speex_bits_destroy(&bits); - } -} - -static void enc_postprocess(MSFilter *f){ - SpeexEncState *s=(SpeexEncState*)f->data; - speex_encoder_destroy(s->state); - s->state=NULL; -} - -static int enc_set_sr(MSFilter *f, void *arg){ - SpeexEncState *s=(SpeexEncState*)f->data; - /* TODO: should be done with fmtp parameter */ - s->rate=((int*)arg)[0]; - return 0; -} - -static int enc_set_br(MSFilter *f, void *arg){ - SpeexEncState *s=(SpeexEncState*)f->data; - s->maxbitrate=((int*)arg)[0]; - return 0; -} - -static int enc_add_fmtp(MSFilter *f, void *arg){ - char buf[64]; - const char *fmtp=(const char *)arg; - SpeexEncState *s=(SpeexEncState*)f->data; - - memset(buf, '\0', sizeof(buf)); - fmtp_get_value(fmtp, "vbr", buf, sizeof(buf)); - if (buf[0]=='\0'){ - } - else if (strstr(buf,"off")!=NULL){ - s->vbr=0; - } - else if (strstr(buf,"on")!=NULL){ - s->vbr=1; - } - else if (strstr(buf,"vad")!=NULL){ - s->vbr=2; - } - - memset(buf, '\0', sizeof(buf)); - fmtp_get_value(fmtp, "cng", buf, sizeof(buf)); - if (buf[0]=='\0'){ - } - else if (strstr(buf,"off")!=NULL){ - s->cng=0; - } - else if (strstr(buf,"on")!=NULL){ - s->cng=1; - } - - memset(buf, '\0', sizeof(buf)); - fmtp_get_value(fmtp, "mode", buf, sizeof(buf)); - if (buf[0]=='\0' || buf[1]=='\0'){ - } - else if (buf[0]=='0' || (buf[0]=='"' && buf[1]=='0')){ - s->mode=0; - } - else if (buf[0]=='"' && atoi(buf+1)>=0){ - s->mode=atoi(buf+1); - } - else if (buf[0]!='"' && atoi(buf)>=0){ - s->mode=atoi(buf); - } - else { - s->mode = -1; /* deault mode */ - } - return 0; -} - -static int enc_add_attr(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - SpeexEncState *s=(SpeexEncState*)f->data; - if (strstr(fmtp,"ptime:10")!=NULL){ - s->ptime=20; - }else if (strstr(fmtp,"ptime:20")!=NULL){ - s->ptime=20; - }else if (strstr(fmtp,"ptime:30")!=NULL){ - s->ptime=40; - }else if (strstr(fmtp,"ptime:40")!=NULL){ - s->ptime=40; - }else if (strstr(fmtp,"ptime:50")!=NULL){ - s->ptime=60; - }else if (strstr(fmtp,"ptime:60")!=NULL){ - s->ptime=60; - }else if (strstr(fmtp,"ptime:70")!=NULL){ - s->ptime=80; - }else if (strstr(fmtp,"ptime:80")!=NULL){ - s->ptime=80; - }else if (strstr(fmtp,"ptime:90")!=NULL){ - s->ptime=100; /* not allowed */ - }else if (strstr(fmtp,"ptime:100")!=NULL){ - s->ptime=100; - }else if (strstr(fmtp,"ptime:110")!=NULL){ - s->ptime=120; - }else if (strstr(fmtp,"ptime:120")!=NULL){ - s->ptime=120; - }else if (strstr(fmtp,"ptime:130")!=NULL){ - s->ptime=140; - }else if (strstr(fmtp,"ptime:140")!=NULL){ - s->ptime=140; - } - return 0; -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , enc_set_sr }, - { MS_FILTER_SET_BITRATE , enc_set_br }, - { MS_FILTER_ADD_FMTP , enc_add_fmtp }, - { MS_FILTER_ADD_ATTR , enc_add_attr}, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_speex_enc_desc={ - MS_SPEEX_ENC_ID, - "MSSpeexEnc", - N_("The free and wonderful speex codec"), - MS_FILTER_ENCODER, - "speex", - 1, - 1, - enc_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_speex_enc_desc={ - .id=MS_SPEEX_ENC_ID, - .name="MSSpeexEnc", - .text=N_("The free and wonderful speex codec"), - .category=MS_FILTER_ENCODER, - .enc_fmt="speex", - .ninputs=1, - .noutputs=1, - .init=enc_init, - .preprocess=enc_preprocess, - .postprocess=enc_postprocess, - .process=enc_process, - .uninit=enc_uninit, - .methods=enc_methods -}; - -#endif - -typedef struct DecState{ - int rate; - int penh; - int frsz; - void *state; -} DecState; - -static void dec_init(MSFilter *f){ - DecState *s=(DecState *)ms_new(DecState,1); - s->rate=8000; - s->frsz=0; - s->state=NULL; - s->penh=1; - f->data=s; -} - -static void dec_uninit(MSFilter *f){ - DecState *s=(DecState*)f->data; - if (s==NULL) - return; - if (s->state!=NULL) - speex_decoder_destroy(s->state); - ms_free(s); -} - -static void dec_preprocess(MSFilter *f){ - DecState *s=(DecState*)f->data; - const SpeexMode *mode=NULL; - int modeid; - switch(s->rate){ - case 8000: - modeid = SPEEX_MODEID_NB; /* rate = 8000Hz */ - break; - case 16000: - modeid = SPEEX_MODEID_WB; /* rate = 16000Hz */ - break; - /* should be supported in the future */ - case 32000: - modeid = SPEEX_MODEID_UWB; /* rate = 32000Hz */ - break; - default: - ms_error("Unsupported rate for speex decoder (back to default rate=8000)."); - modeid=SPEEX_MODEID_NB; - } - /* warning: speex_lib_get_mode() is not available on speex<1.1.12 */ - mode = speex_lib_get_mode(modeid); - s->state=speex_decoder_init(mode); - speex_mode_query(mode,SPEEX_MODE_FRAME_SIZE,&s->frsz); - if (s->penh==1) - speex_decoder_ctl (s->state, SPEEX_SET_ENH, &s->penh); -} - -static void dec_postprocess(MSFilter *f){ - DecState *s=(DecState*)f->data; - speex_decoder_destroy(s->state); - s->state=NULL; -} - -static int dec_set_sr(MSFilter *f, void *arg){ - DecState *s=(DecState*)f->data; - s->rate=((int*)arg)[0]; - return 0; -} - -static void dec_process(MSFilter *f){ - DecState *s=(DecState*)f->data; - mblk_t *im; - mblk_t *om; - int err; - int frame_per_packet; - SpeexBits bits; - int bytes=s->frsz*2; - speex_bits_init(&bits); - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - speex_bits_reset(&bits); - speex_bits_read_from(&bits,(char*)im->b_rptr,im->b_wptr-im->b_rptr); - om=allocb(bytes*7,0); - /* support for multiple frame (max=7 frames???) in one RTP packet */ - for (frame_per_packet=0;frame_per_packet<7;frame_per_packet++) - { - int i; - err=speex_decode_int(s->state,&bits,(int16_t*)(om->b_wptr+(frame_per_packet*320))); - - i = speex_bits_remaining(&bits); - if (i<10) /* this seems to work: don't know why. */ - break; - } - if (err==0){ - om->b_wptr+=bytes*(frame_per_packet+1); - ms_queue_put(f->outputs[0],om); - }else { - if (err==-1) - ms_warning("speex end of stream"); - else if (err==-2) - ms_warning("speex corrupted stream"); - freemsg(om); - } - freemsg(im); - } - speex_bits_destroy(&bits); -} - -static MSFilterMethod dec_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , dec_set_sr }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_speex_dec_desc={ - MS_SPEEX_DEC_ID, - "MSSpeexDec", - N_("The free and wonderful speex codec"), - MS_FILTER_DECODER, - "speex", - 1, - 1, - dec_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - dec_methods -}; - -#else - -MSFilterDesc ms_speex_dec_desc={ - .id=MS_SPEEX_DEC_ID, - .name="MSSpeexDec", - .text=N_("The free and wonderful speex codec"), - .category=MS_FILTER_DECODER, - .enc_fmt="speex", - .ninputs=1, - .noutputs=1, - .init=dec_init, - .preprocess=dec_preprocess, - .postprocess=dec_postprocess, - .process=dec_process, - .uninit=dec_uninit, - .methods=dec_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_speex_dec_desc) -MS_FILTER_DESC_EXPORT(ms_speex_enc_desc) diff --git a/linphone/mediastreamer2/src/msticker.c b/linphone/mediastreamer2/src/msticker.c deleted file mode 100644 index 6e52656d0..000000000 --- a/linphone/mediastreamer2/src/msticker.c +++ /dev/null @@ -1,468 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msticker.h" - - -void * ms_ticker_run(void *s); -static uint64_t get_cur_time(void *); - -void ms_ticker_start(MSTicker *s){ - s->run=TRUE; - ms_thread_create(&s->thread,NULL,ms_ticker_run,s); -} - - -void ms_ticker_init(MSTicker *ticker) -{ - ms_mutex_init(&ticker->lock,NULL); - ticker->execution_list=NULL; - ticker->ticks=1; - ticker->time=0; - ticker->interval=10; - ticker->run=FALSE; - ticker->exec_id=0; - ticker->get_cur_time_ptr=&get_cur_time; - ticker->get_cur_time_data=NULL; -#ifdef WIN32_TIMERS - ticker->TimeEvent=NULL; -#endif - ticker->name=ms_strdup("MSTicker"); - ms_ticker_start(ticker); -} - -MSTicker *ms_ticker_new(){ - MSTicker *obj=(MSTicker *)ms_new(MSTicker,1); - ms_ticker_init(obj); - return obj; -} - -void ms_ticker_stop(MSTicker *s){ - ms_mutex_lock(&s->lock); - s->run=FALSE; - ms_mutex_unlock(&s->lock); - ms_thread_join(s->thread,NULL); -} - -void ms_ticker_set_name(MSTicker *s, const char *name){ - if (s->name) ms_free(s->name); - s->name=ms_strdup(name); -} - -void ms_ticker_uninit(MSTicker *ticker) -{ - ms_ticker_stop(ticker); - ms_free(ticker->name); - ms_mutex_destroy(&ticker->lock); -} - -void ms_ticker_destroy(MSTicker *ticker){ - ms_ticker_uninit(ticker); - ms_free(ticker); -} - - -static MSList *get_sources(MSList *filters){ - MSList *sources=NULL; - MSFilter *f; - for(;filters!=NULL;filters=filters->next){ - f=(MSFilter*)filters->data; - if (f->desc->ninputs==0){ - sources=ms_list_append(sources,f); - } - } - return sources; -} - -int ms_ticker_attach(MSTicker *ticker,MSFilter *f) -{ - MSList *sources=NULL; - MSList *filters=NULL; - MSList *it; - - if (f->ticker!=NULL) { - ms_message("Filter %s is already being scheduled; nothing to do.",f->desc->name); - return 0; - } - - filters=ms_filter_find_neighbours(f); - sources=get_sources(filters); - if (sources==NULL){ - ms_fatal("No sources found around filter %s",f->desc->name); - ms_list_free(filters); - return -1; - } - /*run preprocess on each filter: */ - for(it=filters;it!=NULL;it=it->next) - ms_filter_preprocess((MSFilter*)it->data,ticker); - ms_mutex_lock(&ticker->lock); - ticker->execution_list=ms_list_concat(ticker->execution_list,sources); - ms_mutex_unlock(&ticker->lock); - ms_list_free(filters); - return 0; -} - - - -int ms_ticker_detach(MSTicker *ticker,MSFilter *f){ - MSList *sources=NULL; - MSList *filters=NULL; - MSList *it; - - if (f->ticker==NULL) { - ms_message("Filter %s is not scheduled; nothing to do.",f->desc->name); - return 0; - } - - ms_mutex_lock(&ticker->lock); - - filters=ms_filter_find_neighbours(f); - sources=get_sources(filters); - if (sources==NULL){ - ms_fatal("No sources found around filter %s",f->desc->name); - ms_list_free(filters); - ms_mutex_unlock(&ticker->lock); - return -1; - } - - for(it=sources;it!=NULL;it=ms_list_next(it)){ - ticker->execution_list=ms_list_remove(ticker->execution_list,it->data); - } - ms_mutex_unlock(&ticker->lock); - ms_list_for_each(filters,(void (*)(void*))ms_filter_postprocess); - ms_list_free(filters); - ms_list_free(sources); - return 0; -} - - -static bool_t filter_can_process(MSFilter *f, int tick){ - /* look if filters before this one have run */ - int i; - MSQueue *l; - for(i=0;idesc->ninputs;i++){ - l=f->inputs[i]; - if (l!=NULL){ - if (l->prev.filter->last_tick!=tick) return FALSE; - } - } - return TRUE; -} - -static void call_process(MSFilter *f){ - bool_t process_done=FALSE; - if (f->desc->ninputs==0 || f->desc->flags & MS_FILTER_IS_PUMP){ - ms_filter_process(f); - }else{ - while (ms_filter_inputs_have_data(f)) { - if (process_done){ - ms_warning("Re-scheduling filter %s: all data should be consumed in one process call, so fix it.",f->desc->name); - } - ms_filter_process(f); - process_done=TRUE; - } - } -} - -static void run_graph(MSFilter *f, MSTicker *s, MSList **unschedulable, bool_t force_schedule){ - int i; - MSQueue *l; - if (f->last_tick!=s->ticks ){ - if (filter_can_process(f,s->ticks) || force_schedule) { - /* this is a candidate */ - f->last_tick=s->ticks; - call_process(f); - /* now recurse to next filters */ - for(i=0;idesc->noutputs;i++){ - l=f->outputs[i]; - if (l!=NULL){ - run_graph(l->next.filter,s,unschedulable, force_schedule); - } - } - }else{ - /* this filter has not all inputs that have been filled by filters before it. */ - *unschedulable=ms_list_prepend(*unschedulable,f); - } - } -} - -static void run_graphs(MSTicker *s, MSList *execution_list, bool_t force_schedule){ - MSList *it; - MSList *unschedulable=NULL; - for(it=execution_list;it!=NULL;it=it->next){ - run_graph((MSFilter*)it->data,s,&unschedulable,force_schedule); - } - /* filters that are part of a loop haven't been called in process() because one of their input refers to a filter that could not be scheduled (because they could not be scheduled themselves)... Do you understand ?*/ - /* we resolve this by simply assuming that they must be called anyway - for the loop to run correctly*/ - /* we just recall run_graphs on them, as if they were source filters */ - if (unschedulable!=NULL) { - run_graphs(s,unschedulable,TRUE); - ms_list_free(unschedulable); - } -} - -#ifdef __MACH__ -#include -#include -#endif - -static uint64_t get_cur_time(void *unused){ -#if defined(_WIN32_WCE) - DWORD timemillis = GetTickCount(); - return timemillis; -#elif defined(WIN32) - return timeGetTime() ; -#elif defined(__MACH__) && defined(__GNUC__) && (__GNUC__ >= 3) - struct timeval tv; - gettimeofday(&tv, NULL); - return (tv.tv_sec*1000LL) + (tv.tv_usec/1000LL); -#elif defined(__MACH__) - struct timespec ts; - struct timeb time_val; - - ftime (&time_val); - ts.tv_sec = time_val.time; - ts.tv_nsec = time_val.millitm * 1000000; - return (ts.tv_sec*1000LL) + (ts.tv_nsec/1000000LL); -#else - struct timespec ts; - if (clock_gettime(CLOCK_MONOTONIC,&ts)<0){ - ms_fatal("clock_gettime() doesn't work: %s",strerror(errno)); - } - return (ts.tv_sec*1000LL) + (ts.tv_nsec/1000000LL); -#endif -} - -static void sleepMs(int ms){ -#ifdef WIN32 - Sleep(ms); -#else - struct timespec ts; - ts.tv_sec=0; - ts.tv_nsec=ms*1000000LL; - nanosleep(&ts,NULL); -#endif -} - -static int set_high_prio(void){ - int precision=2; - int result=0; -#ifdef WIN32 - MMRESULT mm; - TIMECAPS ptc; - mm=timeGetDevCaps(&ptc,sizeof(ptc)); - if (mm==0){ - if (ptc.wPeriodMin<(UINT)precision) - ptc.wPeriodMin=precision; - else - precision = ptc.wPeriodMin; - mm=timeBeginPeriod(ptc.wPeriodMin); - if (mm!=TIMERR_NOERROR){ - ms_warning("timeBeginPeriod failed."); - } - ms_message("win32 timer resolution set to %i ms",ptc.wPeriodMin); - }else{ - ms_warning("timeGetDevCaps failed."); - } - - if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)){ - ms_warning("SetThreadPriority() failed (%d)\n", GetLastError()); - } -#else - struct sched_param param; - memset(¶m,0,sizeof(param)); -#ifdef TARGET_OS_MAC - int policy=SCHED_RR; -#else - int policy=SCHED_OTHER; -#endif - param.sched_priority=sched_get_priority_max(policy); - if((result=pthread_setschedparam(pthread_self(),policy, ¶m))) { - ms_warning("Set sched param failed with error code(%i)\n",result); - } else { - ms_message("MS ticker priority set to max"); - } -#endif - return precision; -} - -static void unset_high_prio(int precision){ -#ifdef WIN32 - MMRESULT mm; - - if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL)){ - ms_warning("SetThreadPriority() failed (%d)\n", GetLastError()); - } - - mm=timeEndPeriod(precision); -#endif -} - -#ifndef WIN32_TIMERS - -void * ms_ticker_run(void *arg) -{ - uint64_t realtime; - int64_t diff; - MSTicker *s=(MSTicker*)arg; - int lastlate=0; - int precision=2; - int late; - - precision = set_high_prio(); - - - s->ticks=1; - ms_mutex_lock(&s->lock); - s->orig=s->get_cur_time_ptr(s->get_cur_time_data); - - while(s->run){ - s->ticks++; - run_graphs(s,s->execution_list,FALSE); - s->time+=s->interval; - while(1){ - realtime=s->get_cur_time_ptr(s->get_cur_time_data)-s->orig; - ms_mutex_unlock(&s->lock); - diff=s->time-realtime; - if (diff>0){ - /* sleep until next tick */ - sleepMs((int)diff); - }else{ - late=(int)-diff; - if (late>s->interval*5 && late>lastlate){ - ms_warning("%s: We are late of %d miliseconds.",s->name,late); - } - lastlate=late; - break; /*exit the while loop */ - } - ms_mutex_lock(&s->lock); - } - ms_mutex_lock(&s->lock); - } - ms_mutex_unlock(&s->lock); - unset_high_prio(precision); - ms_message("%s thread exiting",s->name); - - ms_thread_exit(NULL); - return NULL; -} - -#else - -void * ms_ticker_run(void *arg) -{ - MSTicker *s=(MSTicker*)arg; - uint64_t realtime; - int precision=2; - UINT timerId; - - precision = set_high_prio(); - - s->TimeEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - - s->ticks=1; - ms_mutex_lock(&s->lock); - s->orig=s->get_cur_time_ptr(s->get_cur_time_data); - - timerId = timeSetEvent (s->interval, precision, (LPTIMECALLBACK)s->TimeEvent, 0, - TIME_PERIODIC | TIME_CALLBACK_EVENT_SET); - while(s->run){ - DWORD err; - - s->ticks++; - run_graphs(s,s->execution_list,FALSE); - - /* elapsed time since origin */ - s->time = s->get_cur_time_ptr(s->get_cur_time_data)- s->orig; - - ms_mutex_unlock(&s->lock); - err = WaitForSingleObject (s->TimeEvent, s->interval*1000 ); /* wake up each diff */ - if (err==WAIT_FAILED) - ms_message("WaitForSingleObject is failing"); - - ms_mutex_lock(&s->lock); - } - ms_mutex_unlock(&s->lock); - timeKillEvent (timerId); - CloseHandle (s->TimeEvent); - s->TimeEvent=NULL; - unset_high_prio(precision); - ms_message("MSTicker thread exiting"); - ms_thread_exit(NULL); - return NULL; -} - -#endif - -void ms_ticker_set_time_func(MSTicker *ticker, MSTickerTimeFunc func, void *user_data){ - if (func==NULL) func=get_cur_time; - /*ms_mutex_lock(&ticker->lock);*/ - ticker->get_cur_time_ptr=func; - ticker->get_cur_time_data=user_data; - /*re-set the origin to take in account that previous function ptr and the - new one may return different times*/ - ticker->orig=func(user_data)-ticker->time; - /*ms_mutex_unlock(&ticker->lock);*/ - ms_message("ms_ticker_set_time_func: ticker updated."); -} - -static void print_graph(MSFilter *f, MSTicker *s, MSList **unschedulable, bool_t force_schedule){ - int i; - MSQueue *l; - if (f->last_tick!=s->ticks ){ - if (filter_can_process(f,s->ticks) || force_schedule) { - /* this is a candidate */ - f->last_tick=s->ticks; - ms_message("print_graphs: %s", f->desc->name); - /* now recurse to next filters */ - for(i=0;idesc->noutputs;i++){ - l=f->outputs[i]; - if (l!=NULL){ - print_graph(l->next.filter,s,unschedulable, force_schedule); - } - } - }else{ - /* this filter has not all inputs that have been filled by filters before it. */ - *unschedulable=ms_list_prepend(*unschedulable,f); - } - } -} - -static void print_graphs(MSTicker *s, MSList *execution_list, bool_t force_schedule){ - MSList *it; - MSList *unschedulable=NULL; - for(it=execution_list;it!=NULL;it=it->next){ - print_graph((MSFilter*)it->data,s,&unschedulable,force_schedule); - } - /* filters that are part of a loop haven't been called in process() because one of their input refers to a filter that could not be scheduled (because they could not be scheduled themselves)... Do you understand ?*/ - /* we resolve this by simply assuming that they must be called anyway - for the loop to run correctly*/ - /* we just recall run_graphs on them, as if they were source filters */ - if (unschedulable!=NULL) { - print_graphs(s,unschedulable,TRUE); - ms_list_free(unschedulable); - } -} - -void ms_ticker_print_graphs(MSTicker *ticker){ - print_graphs(ticker,ticker->execution_list,FALSE); -} diff --git a/linphone/mediastreamer2/src/msv4l.c b/linphone/mediastreamer2/src/msv4l.c deleted file mode 100644 index 635f789b5..000000000 --- a/linphone/mediastreamer2/src/msv4l.c +++ /dev/null @@ -1,1072 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef __linux - -#include "mediastreamer-config.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#ifdef HAVE_LINUX_VIDEODEV2_H -#include -#endif - -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" -#include "mediastreamer2/mswebcam.h" -#include "nowebcam.h" - -/* From: Logitech QuickCam USB driver */ -#define QC_IOCTLBASE 220 -/* Get enable workaround for bugs, bitfield */ -#define VIDIOCQCGCOMPATIBLE _IOR ('v',QC_IOCTLBASE+10,int) -/* Set enable workaround for bugs, bitfield */ -#define VIDIOCQCSCOMPATIBLE _IOWR('v',QC_IOCTLBASE+10,int) - -#ifndef VIDIOSFPS -#define VIDIOSFPS _IOW('v',BASE_VIDIOCPRIVATE+20, int) -#endif - -typedef struct V4lState{ - int fd; - ms_thread_t thread; - char *dev; - char *mmapdbuf; - int msize;/*mmapped size*/ - MSVideoSize vsize; - MSVideoSize got_vsize; - int pix_fmt; - int int_pix_fmt; /*internal pixel format */ - mblk_t *frames[VIDEO_MAX_FRAME]; - mblk_t *mire; - queue_t rq; - ms_mutex_t mutex; - int frame_ind; - int frame_max; - float fps; - float start_time; - int frame_count; - int queued; - bool_t run; - bool_t usemire; - bool_t v4lv2; /*we interface with a V4Lv2 driver */ - bool_t force_v1; - bool_t auto_started; -}V4lState; - -static void *v4l_thread(void *s); -static int v4l_configure(V4lState *s); - -#ifdef HAVE_LINUX_VIDEODEV2_H - -static bool_t v4lv2_try_format(V4lState *s, int fmtid){ - struct v4l2_format fmt; - - memset(&fmt,0,sizeof(fmt)); - - fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - fmt.fmt.pix.width = s->vsize.width; - fmt.fmt.pix.height = s->vsize.height; - fmt.fmt.pix.pixelformat = fmtid; - fmt.fmt.pix.field = V4L2_FIELD_ANY; - - if (ioctl (s->fd, VIDIOC_S_FMT, &fmt)<0){ - return FALSE; - } - s->got_vsize.width=s->vsize.width; - s->got_vsize.height=s->vsize.height; - return TRUE; -} - -static int v4lv2_configure(V4lState *s) -{ - struct v4l2_capability cap; - - if (ioctl (s->fd, VIDIOC_QUERYCAP, &cap)<0) { - ms_message("Not a v4lv2 driver."); - return -1; - } - - if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { - ms_error("%s is not a video capture device\n",s->dev); - return -1; - } - - if (!(cap.capabilities & V4L2_CAP_STREAMING)) { - ms_error("%s does not support streaming i/o\n",s->dev); - return -1; - } - - if (v4lv2_try_format(s,V4L2_PIX_FMT_YUV420)){ - s->pix_fmt=MS_YUV420P; - s->int_pix_fmt=V4L2_PIX_FMT_YUV420; - ms_message("v4lv2: YUV420P choosen"); - }else if (v4lv2_try_format(s,V4L2_PIX_FMT_NV12)){ - s->pix_fmt=MS_YUV420P; - s->int_pix_fmt=V4L2_PIX_FMT_NV12; - ms_message("v4lv2: V4L2_PIX_FMT_NV12 choosen"); - }else if (v4lv2_try_format(s,V4L2_PIX_FMT_MJPEG)){ - s->pix_fmt=MS_MJPEG; - s->int_pix_fmt=V4L2_PIX_FMT_MJPEG; - ms_message("v4lv2: MJPEG choosen"); - }else if (v4lv2_try_format(s,V4L2_PIX_FMT_YUYV)){ - s->pix_fmt=MS_YUYV; - s->int_pix_fmt=V4L2_PIX_FMT_YUYV; - ms_message("v4lv2: V4L2_PIX_FMT_YUYV choosen"); - }else if (v4lv2_try_format(s,V4L2_PIX_FMT_RGB24)){ - s->pix_fmt=MS_RGB24; - s->int_pix_fmt=V4L2_PIX_FMT_RGB24; - ms_message("v4lv2: RGB24 choosen"); - }else{ - ms_error("Could not find supported pixel format."); - return -1; - } - return 0; -} - -static int v4lv2_do_mmap(V4lState *s){ - struct v4l2_requestbuffers req; - int i; - enum v4l2_buf_type type; - - memset(&req,0,sizeof(req)); - - req.count = 4; - req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - req.memory = V4L2_MEMORY_MMAP; - - if (ioctl (s->fd, VIDIOC_REQBUFS, &req)<0) { - ms_error("Error requesting info on mmap'd buffers: %s",strerror(errno)); - return -1; - } - - for (i=0; ifd, VIDIOC_QUERYBUF, &buf)<0){ - ms_error("Could not VIDIOC_QUERYBUF : %s",strerror(errno)); - return -1; - } - - start=mmap (NULL /* start anywhere */, - buf.length, - PROT_READ | PROT_WRITE /* required */, - MAP_SHARED /* recommended */, - s->fd, buf.m.offset); - - if (start==NULL){ - ms_error("Could not mmap: %s",strerror(errno)); - } - msg=esballoc(start,buf.length,0,NULL); - /* adjust to real size of picture*/ - if (s->pix_fmt==MS_RGB24) - msg->b_wptr+=s->vsize.width*s->vsize.height*3; - else - msg->b_wptr+=(s->vsize.width*s->vsize.height*3)/2; - - s->frames[i]=msg; - } - s->frame_max=req.count; - /* - for (i = 0; i < s->frame_max; ++i) { - struct v4l2_buffer buf; - - memset(&buf,0,sizeof(buf)); - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - buf.index = i; - if (-1==ioctl (s->fd, VIDIOC_QBUF, &buf)){ - ms_error("VIDIOC_QBUF failed: %s",strerror(errno)); - } - } - */ - /*start capture immediately*/ - type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (-1 ==ioctl (s->fd, VIDIOC_STREAMON, &type)){ - ms_error("VIDIOC_STREAMON failed: %s",strerror(errno)); - return -1; - } - return 0; -} - -static mblk_t * v4lv2_grab_image(V4lState *s){ - struct v4l2_buffer buf; - unsigned int k; - memset(&buf,0,sizeof(buf)); - mblk_t *ret=NULL; - - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - if (s->queued){ - if (ioctl(s->fd, VIDIOC_DQBUF, &buf)<0) { - switch (errno) { - case EAGAIN: - case EIO: - /* Could ignore EIO, see spec. */ - break; - default: - ms_warning("VIDIOC_DQBUF failed: %s",strerror(errno)); - } - }else{ - if (buf.index >= s->frame_max){ - ms_error("buf.index>=s->max_frames !"); - return NULL; - } - s->queued--; - /*decrement ref count of dequeued buffer */ - ret=s->frames[buf.index]; - ret->b_datap->db_ref--; - if (buf.bytesused<=30){ - ms_warning("Ignoring empty buffer..."); - return NULL; - } - } - } - - /*queue buffers whose ref count has dropped to 1, because they are not - still used anywhere in the filter chain */ - for(k=0;kframe_max;++k){ - if (s->frames[k]->b_datap->db_ref==1){ - buf.index=k; - if (-1==ioctl (s->fd, VIDIOC_QBUF, &buf)) - ms_warning("VIDIOC_QBUF %i failed: %s",k, strerror(errno)); - else { - /*increment ref count of queued buffer*/ - s->frames[k]->b_datap->db_ref++; - s->queued++; - } - } - } - return ret; -} - -#endif - -static void v4l_init(MSFilter *f){ - V4lState *s=ms_new0(V4lState,1); - s->fd=-1; - s->run=FALSE; - s->v4lv2=FALSE; - s->mmapdbuf=NULL; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->pix_fmt=MS_RGB24; - s->dev=ms_strdup("/dev/video0"); - qinit(&s->rq); - s->mire=NULL; - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - s->usemire=(getenv("DEBUG")!=NULL); - s->queued=0; - s->force_v1=FALSE; - s->auto_started=FALSE; - f->data=s; -} - -/* we try not to close the /dev/videoX device to workaround a bug of linux kernel. -The bug is this one: -One thread opens /dev/videoX, and mmap()s some pages to get data from the camera. -Then several threads are created (using clone) and automatically get a reference to the mmap'd page, thus a reference to the file_struct of the opened file descriptor. -Then when the first thread closes and unmap() the file descriptor, the .release method of the driver is not called because there are still some threads owning the reference to the mmap'd pages. -As far as I understand. -If all threads are correctly pthread_join()ed, then the file descriptor is closed correctly. -But unfortunately when using alsa dmix/asym plugins, some threads are started by those plugins and are kept alive (or zombie) for some time after the mmap()/close(). -*/ - -static int v4l_fd=-1; -static bool_t reuse_fd=FALSE; -static char *v4l_devname=NULL; - -static int v4l_start(MSFilter *f, void *arg) -{ - V4lState *s=(V4lState*)f->data; - int err=0; - if (v4l_fd>=0 && reuse_fd){ - if (strcmp(v4l_devname,s->dev)==0 ){ - /*use this one!*/ - ms_message("v4l_start: reusing previous file descriptor."); - s->fd=v4l_fd; - }else{ - ms_message("closing cached fd"); - close(v4l_fd); - v4l_fd=-1; - ms_free(v4l_devname); - v4l_devname=NULL; - } - } - if (s->fd==-1){ - s->fd=open(s->dev,O_RDWR); - ms_message("v4l_start: open, fd=%i",s->fd); - if (s->fd>=0){ - v4l_fd=s->fd; - v4l_devname=ms_strdup(s->dev); - } - } - if (s->fd<0){ - ms_error("MSV4l: cannot open video device (%s): %s.",s->dev,strerror(errno)); - if (!s->usemire){ - s->pix_fmt=MS_YUV420P; - s->fps=1; - } - return -1; - }else{ -#ifdef HAVE_LINUX_VIDEODEV2_H - if (s->force_v1 || v4lv2_configure(s)<0) {/*might not be V4LV2 */ -#else - if (1){ -#endif - struct video_capability vidcap; - err=v4l_configure(s); - if (err<0) - { - ms_error("MSV4l: could not get configuration of video device"); - close(s->fd); - s->fd=-1; - return -1; - } - if (!s->force_v1) reuse_fd=TRUE; - - err=ioctl(s->fd, VIDIOCGCAP, &vidcap); - if (err==0) - { - ms_message("MSV4l: Webcam is %s.", vidcap.name); - if (strcasecmp(vidcap.name, "Logitech QuickCam USB")==0) - { - int comp_arg=0; - err=ioctl(s->fd, VIDIOCQCSCOMPATIBLE, &comp_arg); - if (err==0) - { - ms_message("MSV4l: compatibility mode disabled for %s.", vidcap.name); - } - } - } - }else{ - ms_message("Device is a video4linux V2 one."); - s->v4lv2=TRUE; - reuse_fd=FALSE; - } - } - return 0; -} - -static void v4l_start_capture(V4lState *s){ - if (s->fd>=0){ - s->run=TRUE; - ms_thread_create(&s->thread,NULL,v4l_thread,s); - } -} - -static int v4l_stop(MSFilter *f, void *arg){ - V4lState *s=(V4lState*)f->data; - if (s->fd>=0){ - if (!reuse_fd){ - if (close(s->fd)<0){ - ms_warning("MSV4l: Could not close(): %s",strerror(errno)); - } - ms_message("v4l fd %i closed",s->fd); - } - s->fd=-1; - s->frame_count=-1; - } - return 0; -} - -static void v4l_stop_capture(V4lState *s){ - if (s->run){ - s->run=FALSE; - ms_thread_join(s->thread,NULL); - ms_message("v4l thread has joined."); - flushq(&s->rq,0); - } -} - - -static void v4l_uninit(MSFilter *f){ - V4lState *s=(V4lState*)f->data; - if (s->fd>=0) v4l_stop(f,NULL); - ms_free(s->dev); - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - freemsg(s->mire); - ms_free(s); -} - -static bool_t try_format(int fd, struct video_picture *pict, int palette, int depth){ - int err; - pict->palette=palette; - pict->depth=depth; - err=ioctl(fd,VIDIOCSPICT,pict); - if (err<0){ - ms_warning("Could not set picture properties: %s",strerror(errno)); - return FALSE; - } - return TRUE; -} - -static int v4l_do_mmap(V4lState *s){ - struct video_mbuf vmbuf; - int err,i; - memset(&vmbuf,0,sizeof(vmbuf)); - /* try to get mmap properties */ - err=ioctl(s->fd,VIDIOCGMBUF,&vmbuf); - if (err<0){ - ms_error("Could not get mmap properties: %s",strerror(errno)); - return -1; - }else { - if (vmbuf.size>0){ - /* do the mmap */ - s->msize=vmbuf.size; - s->frame_max=vmbuf.frames; - } else { - ms_error("This device cannot support mmap."); - return -1; - } - } - s->mmapdbuf=mmap(NULL,s->msize,PROT_READ,MAP_SHARED,s->fd,0); - if (s->mmapdbuf==(void*)-1) { - /* for non-mmu arch */ - s->mmapdbuf=mmap(NULL,s->msize,PROT_READ,MAP_PRIVATE,s->fd,0); - if (s->mmapdbuf==(void*)-1) { - ms_error("Could not mmap: %s",strerror(errno)); - s->mmapdbuf=NULL; - return -1; - } - } - /* initialize the mediastreamer buffers */ - ms_message("Using %i-frames mmap'd buffer at %p, len %i", - s->frame_max, s->mmapdbuf,s->msize); - for(i=0;iframe_max;i++){ - mblk_t *buf=esballoc((uint8_t*)s->mmapdbuf+vmbuf.offsets[i],vmbuf.offsets[1],0,NULL); - /* adjust to real size of picture*/ - if (s->pix_fmt==MS_RGB24) - buf->b_wptr+=s->vsize.width*s->vsize.height*3; - else - buf->b_wptr+=(s->vsize.width*s->vsize.height*3)/2; - s->frames[i]=buf; - } - s->frame_ind=0; - return 0; -} - -static bool_t try_size(V4lState *s, MSVideoSize vsize){ - struct video_window win; - int err; - memset(&win,0,sizeof(win)); - /*set picture size */ - win.x=win.y=0; - win.width=vsize.width; - win.height=vsize.height; - win.flags=0; - win.clips=NULL; - win.clipcount=0; - - ms_message("Trying to set capture size to %ix%i", vsize.width,vsize.height); - err=ioctl(s->fd,VIDIOCSWIN,&win); - if (err<0){ - ms_warning("Could not set window size: %s",strerror(errno)); - return FALSE; - } - - err=ioctl(s->fd, VIDIOCGWIN, &win); - if (err<0){ - ms_warning("Could not get window size: %s",strerror(errno)); - return FALSE; - } - s->vsize.width=vsize.width; - s->vsize.height=vsize.height; - - if (s->vsize.width!=win.width || s->vsize.height!=win.height){ - ms_warning("Capture size is not what we expected: asked for %ix%i and get %ix%i",s->vsize.width,s->vsize.height, win.width, win.height); - } - s->got_vsize.width=win.width; - s->got_vsize.height=win.height; - ms_message("Capture size set to %ix%i", s->got_vsize.width,s->got_vsize.height); - return TRUE; -} - -static int v4l_configure(V4lState *s) -{ - struct video_channel chan; - struct video_picture pict; - struct video_capability cap; - int err; - int i; - int fps = 0; - int found=0; - - memset(&chan,0,sizeof(chan)); - memset(&pict,0,sizeof(pict)); - memset(&cap,0,sizeof(cap)); - - err=ioctl(s->fd,VIDIOCGCAP,&cap); - if (err!=0) - { - ms_warning("MSV4l: cannot get device capabilities: %s.",strerror(errno)); - return -1; - } - - ms_message("Found %s device. (maxsize=%ix%i, minsize=%ix%i)",cap.name, cap.maxwidth, cap.maxheight, - cap.minwidth, cap.minheight); - for (i=0;ifd,VIDIOCGCHAN,&chan); - if (err==0) - { - ms_message("Getting video channel %s",chan.name); - switch(chan.type){ - case VIDEO_TYPE_TV: - ms_message("Channel is a TV."); - break; - case VIDEO_TYPE_CAMERA: - ms_message("Channel is a camera"); - break; - default: - ms_warning("unknown video channel type."); - } - found=1; - break; /* find the first channel */ - } - } - if (found) ms_message("A valid video channel was found."); - /* select this channel */ - ioctl(s->fd,VIDIOCSCHAN,&chan); - - /* get picture properties */ - err=ioctl(s->fd,VIDIOCGPICT,&pict); - if (err<0){ - ms_warning("Could not get picture properties: %s",strerror(errno)); - return -1; - } - ms_message("Default picture properties: brightness=%i,hue=%i,colour=%i,contrast=%i,depth=%i, palette=%i.", - pict.brightness,pict.hue,pict.colour, pict.contrast,pict.depth, pict.palette); - - /* trying color format */ - if (try_format(s->fd,&pict,VIDEO_PALETTE_YUV420P,16)){ - ms_message("Driver supports YUV420P, using that format."); - s->pix_fmt=MS_YUV420P; - }else if (try_format(s->fd, &pict,VIDEO_PALETTE_RGB24,24)){ - ms_message("Driver supports RGB24, using that format."); - s->pix_fmt=MS_RGB24; - }else if (try_format(s->fd, &pict,VIDEO_PALETTE_YUV422, 16)){ - ms_message("Driver supports YUV422, using that format."); - s->pix_fmt=MS_YUYV; - }else if (try_format(s->fd, &pict,VIDEO_PALETTE_UYVY, 16)){ - ms_message("Driver supports UYVY, using that format."); - s->pix_fmt=MS_UYVY; - }else{ - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->pix_fmt=MS_YUV420P; - ms_fatal("Unsupported video pixel format."); - return -1; - } - - if (!try_size(s,s->vsize)) { - if (!try_size(s,MS_VIDEO_SIZE_NS1)){ - if (!try_size(s,MS_VIDEO_SIZE_VGA)){ - if (!try_size(s,MS_VIDEO_SIZE_CIF)) { - if (!try_size(s,MS_VIDEO_SIZE_QCIF)) { - if (!try_size(s,MS_VIDEO_SIZE_QVGA)) { - if (!try_size(s,MS_VIDEO_SIZE_4CIF)) { - if (!try_size(s,MS_VIDEO_SIZE_1024)) { - return -1; - } - } - } - } - } - } - } - } - - /* Try HW frame rate control */ - fps = s->fps; - if (ioctl(s->fd, VIDIOSFPS, &fps) < 0 ) - ms_message("v4l_configure: cannot set HW frame rate control"); - else - ms_message("v4l_configure: set HW fps to be : %d", fps); - - return 0; -} - - -int ms_to_v4l_pix_fmt(MSPixFmt p){ - switch(p){ - case MS_YUV420P: - return VIDEO_PALETTE_YUV420P; - case MS_RGB24: - return VIDEO_PALETTE_RGB24; - case MS_YUYV: - return VIDEO_PALETTE_YUV422; - case MS_UYVY: - return VIDEO_PALETTE_UYVY; - default: - ms_fatal("unsupported pix fmt"); - return -1; - } -} - -static void plane_copy(uint8_t *dest, int dw, int dh, uint8_t *src, int sw, int sh, int bpp){ - int diffw=dw-sw; - int diffh=dh-sh; - int dlsize=dw*bpp; - int slsize=sw*bpp; - int i; - int dstartx=(diffw>0) ? diffw/2 : 0; - int dstarty=(diffh>0) ? diffh/2 : 0; - int sstartx=(diffw<0) ? diffw/2 : 0; - int sstarty=(diffh<0) ? diffh/2 : 0; - uint8_t *tmp1=dest; - uint8_t *tmp2=src; - - /* copy orig into dest */ - tmp2+=sstarty*slsize; - tmp1+=dstarty*dlsize; - for(i=dstarty;ivsize.width*s->vsize.height; - mblk_t *newpic; - if (s->pix_fmt==MS_YUV420P) size=size*3/2; - else if (s->pix_fmt==MS_YUYV) size=size*2; - else if (s->pix_fmt==MS_UYVY) size=size*2; - else if (s->pix_fmt==MS_RGB24) size=size*3; - else ms_fatal("crop_or_pad: unsupported pixel format."); - newpic=allocb(size,0); - memset(newpic->b_wptr,0,size); - pic_copy(newpic->b_wptr, s->vsize.width, s->vsize.height, - pic->b_rptr,s->got_vsize.width,s->got_vsize.height,s->pix_fmt); - newpic->b_wptr+=size; - return newpic; -} - -static mblk_t * v4l_grab_image_mmap(V4lState *s){ - struct video_mmap vmap; - int err; - int syncframe; - int jitter=s->frame_max-1; - int query_frame; - mblk_t *ret; - vmap.width=s->got_vsize.width; - vmap.height=s->got_vsize.height; - vmap.format=ms_to_v4l_pix_fmt(s->pix_fmt); - - query_frame=(s->frame_ind) % s->frame_max; - /*ms_message("v4l_mmap_process: query_frame=%i", - obj->query_frame);*/ - vmap.frame=query_frame; - err=ioctl(s->fd,VIDIOCMCAPTURE,&vmap); - if (err<0) { - ms_warning("v4l_grab_image_mmap: error in VIDIOCMCAPTURE: %s.",strerror(errno)); - usleep(10000); - return NULL; - } - /*g_message("v4l_mmap_process: query_frame=%i done", - obj->query_frame);*/ - syncframe=(s->frame_ind-jitter); - s->frame_ind++; - if (syncframe>=0){ - syncframe=syncframe%s->frame_max; - /*ms_message("Syncing on frame %i",syncframe);*/ - err=ioctl(s->fd,VIDIOCSYNC,&syncframe); - if (err<0) { - ms_warning("v4l_grab_image_mmap: error in VIDIOCSYNC: %s.",strerror(errno)); - return NULL; - } - /*g_message("got frame %i",syncframe);*/ - }else { - return NULL; - } - ret=s->frames[syncframe]; - /* crop or pad picture if obtained size is not what we want */ - if (s->vsize.width!=s->got_vsize.width){ - ret=crop_or_pad(s,ret); - } - return ret; -} - -static mblk_t * v4l_make_mire(V4lState *s){ - unsigned char *data; - int i,j,line,pos; - int patternw=s->vsize.width/6; - int patternh=s->vsize.height/6; - int red,green=0,blue=0; - if (s->mire==NULL){ - s->mire=allocb(s->vsize.width*s->vsize.height*3,0); - s->mire->b_wptr=s->mire->b_datap->db_lim; - } - data=s->mire->b_rptr; - for (i=0;ivsize.height;++i){ - line=i*s->vsize.width*3; - if ( ((i+s->frame_ind)/patternh) & 0x1) red=255; - else red= 0; - for (j=0;jvsize.width;++j){ - pos=line+(j*3); - - if ( ((j+s->frame_ind)/patternw) & 0x1) blue=255; - else blue= 0; - - data[pos]=red; - data[pos+1]=green; - data[pos+2]=blue; - } - } - s->frame_ind++; - return s->mire; -} - -static mblk_t * v4l_make_nowebcam(V4lState *s){ - if (s->mire==NULL && s->frame_ind==0){ - s->mire=ms_load_nowebcam(&s->vsize, -1); - } - s->frame_ind++; - return s->mire; -} - -static void v4l_purge(V4lState *s){ - int i; - int err; - int jitter=s->frame_max-1; - for (i=s->frame_ind-jitter;iframe_ind;++i){ - int syncframe=i%s->frame_max; - ms_message("syncing last frame"); - err=ioctl(s->fd,VIDIOCSYNC,&syncframe); - if (err<0) { - ms_warning("v4l_mmap_process: error in VIDIOCSYNC: %s.",strerror(errno)); - } - } -} - -#ifdef HAVE_LINUX_VIDEODEV2_H -static void v4lv2_purge(V4lState *s){ - struct v4l2_buffer buf; - memset(&buf,0,sizeof(buf)); - - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - - for(;s->queued>0;s->queued--){ - if (ioctl(s->fd, VIDIOC_DQBUF, &buf)==-1){ - ms_warning("v4lv2_purge: Could not DQ buffer: %s",strerror(errno)); - } - } -} -#endif - -static void v4l_do_munmap(V4lState *s){ - int i; -#ifdef HAVE_LINUX_VIDEODEV2_H - enum v4l2_buf_type type; - if (s->v4lv2){ - v4lv2_purge(s); - /*stop capture immediately*/ - type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (-1 ==ioctl (s->fd, VIDIOC_STREAMOFF, &type)){ - ms_error("VIDIOC_STREAMOFF failed: %s",strerror(errno)); - } - } -#endif - if (!s->v4lv2){ - v4l_purge(s); - } - if (s->mmapdbuf!=NULL){ - if (munmap(s->mmapdbuf,s->msize)<0){ - ms_warning("MSV4l: Fail to unmap: %s",strerror(errno)); - } - ms_message("munmap() done (%p,%i)",s->mmapdbuf,s->msize); - s->mmapdbuf=NULL; - } - s->msize=0; - for(i=0;iframe_max;++i){ - if (s->v4lv2){ - mblk_t *msg=s->frames[i]; - int len=msg->b_datap->db_lim-msg->b_datap->db_base; - if (munmap(msg->b_datap->db_base,len)<0){ - ms_warning("MSV4l: Fail to unmap: %s",strerror(errno)); - } - } - freemsg(s->frames[i]); - s->frames[i]=NULL; - } -} - - -static void *v4l_thread(void *ptr){ - V4lState *s=(V4lState*)ptr; - int err=-1; - ms_message("v4l_thread starting"); - if (s->v4lv2){ -#ifdef HAVE_LINUX_VIDEODEV2_H - err=v4lv2_do_mmap(s); -#endif - }else{ - err=v4l_do_mmap(s); - } - if (err<0){ - ms_thread_exit(NULL); - } - while(s->run){ - mblk_t *m; -#ifdef HAVE_LINUX_VIDEODEV2_H - if (s->v4lv2) - m=v4lv2_grab_image(s); - else -#endif - m=v4l_grab_image_mmap(s); - - if (s->vsize.width!=s->got_vsize.width){ - if (m){ - /* mblock was allocated by crop or pad! */ - ms_mutex_lock(&s->mutex); - putq(&s->rq,m); - ms_mutex_unlock(&s->mutex); - }else{ - ms_error("grabbing failed !"); - } - } else if (m!=NULL) { - mblk_t *dm=dupmsg(m); - ms_mutex_lock(&s->mutex); - putq(&s->rq,dm); - ms_mutex_unlock(&s->mutex); - } - } - v4l_do_munmap(s); - ms_message("v4l_thread exited."); - ms_thread_exit(NULL); -} - - -static void v4l_process(MSFilter * obj){ - V4lState *s=(V4lState*)obj->data; - uint32_t timestamp; - int cur_frame; - if (s->frame_count==-1){ - s->start_time=obj->ticker->time; - s->frame_count=0; - } - cur_frame=((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>=s->frame_count){ - mblk_t *om=NULL; - ms_mutex_lock(&s->mutex); - /*keep the most recent frame if several frames have been captured */ - if (s->fd!=-1){ - om=getq(&s->rq); - }else{ - if (s->usemire){ - om=dupmsg(v4l_make_mire(s)); - }else { - mblk_t *tmpm=v4l_make_nowebcam(s); - if (tmpm) { - om=dupmsg(tmpm); - mblk_set_precious_flag(om,1); - } - } - } - ms_mutex_unlock(&s->mutex); - if (om!=NULL){ - timestamp=obj->ticker->time*90;/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - mblk_set_marker_info(om,TRUE); - ms_queue_put(obj->outputs[0],om); - /*ms_message("picture sent");*/ - s->frame_count++; - } - }else flushq(&s->rq,0); -} - -static void v4l_preprocess(MSFilter *f){ - V4lState *s=(V4lState*)f->data; - if (s->fd==-1){ - s->auto_started=TRUE; - v4l_start(f,NULL); - v4l_start_capture(s); - } - else - { - v4l_start_capture(s); - } -} - -static void v4l_postprocess(MSFilter *f){ - V4lState *s=(V4lState*)f->data; - if (s->auto_started){ - v4l_stop_capture(s); - v4l_stop(f,NULL); - } - else - { - v4l_stop_capture(s); - } -} - -static int v4l_set_fps(MSFilter *f, void *arg){ - V4lState *s=(V4lState*)f->data; - s->fps=*((float*)arg); - s->frame_count=-1; - return 0; -} - -static int v4l_get_pix_fmt(MSFilter *f,void *arg){ - V4lState *s=(V4lState*)f->data; - MSPixFmt res; - if (s->fd==-1){ - v4l_start(f,NULL); - res=s->pix_fmt; - v4l_stop(f,NULL); - }else res=s->pix_fmt; - *((MSPixFmt*)arg)=res; - return 0; -} - -static int v4l_set_vsize(MSFilter *f, void *arg){ - V4lState *s=(V4lState*)f->data; - s->vsize=*((MSVideoSize*)arg); - return 0; -} - -static int v4l_get_vsize(MSFilter *f, void *arg){ - V4lState *s=(V4lState*)f->data; - *(MSVideoSize*)arg=s->vsize; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , v4l_set_fps }, - { MS_FILTER_GET_PIX_FMT , v4l_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, v4l_set_vsize }, - { MS_V4L_START , v4l_start }, - { MS_V4L_STOP , v4l_stop }, - { MS_FILTER_GET_VIDEO_SIZE, v4l_get_vsize }, - { 0 , NULL } -}; - -static int v4l_set_devfile(MSFilter *f, void *arg){ - V4lState *s=(V4lState*)f->data; - if (s->dev) ms_free(s->dev); - s->dev=ms_strdup((char*)arg); - return 0; -} - -MSFilterDesc ms_v4l_desc={ - .id=MS_V4L_ID, - .name="MSV4l", - .text=N_("A video4linux compatible source filter to stream pictures."), - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=v4l_init, - .preprocess=v4l_preprocess, - .process=v4l_process, - .postprocess=v4l_postprocess, - .uninit=v4l_uninit, - .methods=methods -}; - -MS_FILTER_DESC_EXPORT(ms_v4l_desc) - -static MSFilter *v4l_create_reader(MSWebCam *obj){ - MSFilter *f=ms_filter_new_from_desc(&ms_v4l_desc); - V4lState *s=(V4lState*)f->data; - v4l_set_devfile(f,obj->name); - s->force_v1=TRUE; - return f; -} - -static void v4l_detect(MSWebCamManager *obj); - -static void v4l_cam_init(MSWebCam *cam){ - -} - -MSWebCamDesc v4l_desc={ - "V4L", - &v4l_detect, - &v4l_cam_init, - &v4l_create_reader, - NULL -}; - -static void v4l_detect(MSWebCamManager *obj){ - struct video_capability cap; - const char *devname="/dev/video0"; - int fd=open(devname,O_RDWR); - if (fd!=-1){ - if (ioctl (fd, VIDIOCGCAP, &cap)==0) { - /* is a V4Lv1 */ - MSWebCam *cam=ms_web_cam_new(&v4l_desc); - cam->name=ms_strdup(devname); - ms_web_cam_manager_add_cam(obj,cam); - } - close(fd); - } - devname="/dev/video1"; - fd=open(devname,O_RDWR); - if (fd!=-1){ - if (ioctl (fd, VIDIOCGCAP, &cap)==0) { - /* is a V4Lv1 */ - MSWebCam *cam=ms_web_cam_new(&v4l_desc); - cam->name=ms_strdup(devname); - ms_web_cam_manager_add_cam(obj,cam); - } - close(fd); - } -} - - -#endif diff --git a/linphone/mediastreamer2/src/msv4l2.c b/linphone/mediastreamer2/src/msv4l2.c deleted file mode 100644 index 377131926..000000000 --- a/linphone/mediastreamer2/src/msv4l2.c +++ /dev/null @@ -1,524 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#ifdef HAVE_LINUX_VIDEODEV2_H - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/mswebcam.h" - -#ifdef HAVE_LIBV4L2 -#include -#else - -#define v4l2_open open -#define v4l2_close close -#define v4l2_mmap mmap -#define v4l2_munmap munmap -#define v4l2_ioctl ioctl - -#endif - -typedef struct V4l2State{ - int fd; - char *dev; - char *mmapdbuf; - int msize;/*mmapped size*/ - MSVideoSize vsize; - MSVideoSize got_vsize; - int pix_fmt; - int int_pix_fmt; /*internal pixel format */ - int picture_size; - mblk_t *frames[VIDEO_MAX_FRAME]; - int frame_ind; - int frame_max; - float fps; - float start_time; - int frame_count; - int queued; - bool_t configured; -}V4l2State; - -static int msv4l2_open(V4l2State *s){ - int fd=v4l2_open(s->dev,O_RDWR|O_NONBLOCK); - if (fd==-1){ - ms_error("Could not open %s: %s",s->dev,strerror(errno)); - return -1; - } - s->fd=fd; - return 0; -} - -static int msv4l2_close(V4l2State *s){ - if (s->fd!=-1){ - v4l2_close(s->fd); - s->fd=-1; - s->configured=FALSE; - } - return 0; -} - -static bool_t v4lv2_try_format( V4l2State *s, struct v4l2_format *fmt, int fmtid){ - - fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - fmt->fmt.pix.pixelformat = fmtid; - fmt->fmt.pix.field = V4L2_FIELD_ANY; - - if (v4l2_ioctl (s->fd, VIDIOC_TRY_FMT, fmt)<0){ - ms_message("VIDIOC_TRY_FMT: %s",strerror(errno)); - return FALSE; - } - if (v4l2_ioctl (s->fd, VIDIOC_S_FMT, fmt)<0){ - ms_message("VIDIOC_S_FMT: %s",strerror(errno)); - return FALSE; - } - return TRUE; -} - -static int get_picture_buffer_size(MSPixFmt pix_fmt, int w, int h){ - switch(pix_fmt){ - case MS_YUV420P: - return (w*h*3)/2; - break; - case MS_RGB24: - return w*h*3; - break; - case MS_YUYV: - return w*h*2; - break; - default: - return 0; - } - return 0; -} - -static int msv4l2_configure(V4l2State *s){ - struct v4l2_capability cap; - struct v4l2_format fmt; - MSVideoSize vsize; - - if (v4l2_ioctl (s->fd, VIDIOC_QUERYCAP, &cap)<0) { - ms_message("Not a v4lv2 driver."); - return -1; - } - - if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { - ms_error("%s is not a video capture device\n",s->dev); - return -1; - } - - if (!(cap.capabilities & V4L2_CAP_STREAMING)) { - ms_error("%s does not support streaming i/o\n",s->dev); - return -1; - } - - ms_message("Driver is %s",cap.driver); - memset(&fmt,0,sizeof(fmt)); - - fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (v4l2_ioctl (s->fd, VIDIOC_G_FMT, &fmt)<0){ - ms_error("VIDIOC_G_FMT failed: %s",strerror(errno)); - } - vsize=s->vsize; - do{ - fmt.fmt.pix.width = s->vsize.width; - fmt.fmt.pix.height = s->vsize.height; - if (v4lv2_try_format(s,&fmt,V4L2_PIX_FMT_YUV420)){ - s->pix_fmt=MS_YUV420P; - s->int_pix_fmt=V4L2_PIX_FMT_YUV420; - ms_message("v4lv2: YUV420P choosen"); - break; - }else if (v4lv2_try_format(s,&fmt,V4L2_PIX_FMT_MJPEG)){ - s->pix_fmt=MS_MJPEG; - s->int_pix_fmt=V4L2_PIX_FMT_MJPEG; - ms_message("v4lv2: MJPEG choosen"); - break; - }else if (v4lv2_try_format(s,&fmt,V4L2_PIX_FMT_YUYV)){ - s->pix_fmt=MS_YUYV; - s->int_pix_fmt=V4L2_PIX_FMT_YUYV; - ms_message("v4lv2: V4L2_PIX_FMT_YUYV choosen"); - break; - }else if (v4lv2_try_format(s,&fmt,V4L2_PIX_FMT_RGB24)){ - s->pix_fmt=MS_RGB24; - s->int_pix_fmt=V4L2_PIX_FMT_RGB24; - ms_message("v4lv2: RGB24 choosen"); - break; - }else{ - ms_error("Could not find supported pixel format for %ix%i", s->vsize.width, s->vsize.height); - } - s->vsize=ms_video_size_get_just_lower_than(s->vsize); - }while(s->vsize.width!=0); - if (s->vsize.width==0){ - ms_message("Could not find any combination of resolution/pixel-format that works !"); - s->vsize=vsize; - return -1; - } - memset(&fmt,0,sizeof(fmt)); - - fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - - if (v4l2_ioctl (s->fd, VIDIOC_G_FMT, &fmt)<0){ - ms_error("VIDIOC_G_FMT failed: %s",strerror(errno)); - }else{ - ms_message("Size of webcam delivered pictures is %ix%i",fmt.fmt.pix.width,fmt.fmt.pix.height); - s->vsize.width=fmt.fmt.pix.width; - s->vsize.height=fmt.fmt.pix.height; - } - s->picture_size=get_picture_buffer_size(s->pix_fmt,s->vsize.width,s->vsize.height); - s->configured=TRUE; - return 0; -} - -static int msv4l2_do_mmap(V4l2State *s){ - struct v4l2_requestbuffers req; - int i; - enum v4l2_buf_type type; - - memset(&req,0,sizeof(req)); - - req.count = 4; - req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - req.memory = V4L2_MEMORY_MMAP; - - if (v4l2_ioctl (s->fd, VIDIOC_REQBUFS, &req)<0) { - ms_error("Error requesting info on mmap'd buffers: %s",strerror(errno)); - return -1; - } - - for (i=0; ifd, VIDIOC_QUERYBUF, &buf)<0){ - ms_error("Could not VIDIOC_QUERYBUF : %s",strerror(errno)); - return -1; - } - - start=v4l2_mmap (NULL /* start anywhere */, - buf.length, - PROT_READ | PROT_WRITE /* required */, - MAP_SHARED /* recommended */, - s->fd, buf.m.offset); - - if (start==NULL){ - ms_error("Could not v4l2_mmap: %s",strerror(errno)); - } - msg=esballoc(start,buf.length,0,NULL); - msg->b_wptr+=buf.length; - s->frames[i]=msg; - } - s->frame_max=req.count; - for (i = 0; i < s->frame_max; ++i) { - struct v4l2_buffer buf; - - memset(&buf,0,sizeof(buf)); - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - buf.index = i; - if (-1==v4l2_ioctl (s->fd, VIDIOC_QBUF, &buf)){ - ms_error("VIDIOC_QBUF failed: %s",strerror(errno)); - }else { - s->frames[i]->b_datap->db_ref++; - s->queued++; - } - } - /*start capture immediately*/ - type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (-1 ==v4l2_ioctl (s->fd, VIDIOC_STREAMON, &type)){ - ms_error("VIDIOC_STREAMON failed: %s",strerror(errno)); - return -1; - } - return 0; -} - -static mblk_t * v4lv2_grab_image(V4l2State *s){ - struct v4l2_buffer buf; - unsigned int k; - memset(&buf,0,sizeof(buf)); - mblk_t *ret=NULL; - - buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - buf.memory = V4L2_MEMORY_MMAP; - - /*queue buffers whose ref count is 1, because they are not - still used anywhere in the filter chain */ - for(k=0;kframe_max;++k){ - if (s->frames[k]->b_datap->db_ref==1){ - buf.index=k; - if (-1==v4l2_ioctl (s->fd, VIDIOC_QBUF, &buf)) - ms_warning("VIDIOC_QBUF %i failed: %s",k, strerror(errno)); - else { - ms_debug("v4l2: queue buf %i",k); - /*increment ref count of queued buffer*/ - s->frames[k]->b_datap->db_ref++; - s->queued++; - } - } - } - - if (s->queued){ - struct pollfd fds; - memset(&fds,0,sizeof(fds)); - fds.events=POLLIN; - fds.fd=s->fd; - /*check with poll if there is something to read */ - if (poll(&fds,1,0)==1 && fds.revents==POLLIN){ - if (v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)<0) { - switch (errno) { - case EAGAIN: - case EIO: - /* Could ignore EIO, see spec. */ - break; - default: - ms_warning("VIDIOC_DQBUF failed: %s",strerror(errno)); - } - }else{ - s->queued--; - ms_debug("v4l2: de-queue buf %i",buf.index); - /*decrement ref count of dequeued buffer */ - ret=s->frames[buf.index]; - ret->b_datap->db_ref--; - if (buf.index >= s->frame_max){ - ms_error("buf.index>=s->max_frames !"); - return NULL; - } - if (buf.bytesused<=30){ - ms_warning("Ignoring empty buffer..."); - return NULL; - } - /*normally buf.bytesused should contain the right buffer size; however we have found a buggy - driver that puts a random value inside */ - if (s->picture_size!=0) - ret->b_wptr=ret->b_rptr+s->picture_size; - else ret->b_wptr=ret->b_rptr+buf.bytesused; - } - } - } - return ret; -} - -static void msv4l2_do_munmap(V4l2State *s){ - int i; - enum v4l2_buf_type type; - /*stop capture immediately*/ - type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (-1 ==v4l2_ioctl (s->fd, VIDIOC_STREAMOFF, &type)){ - ms_error("VIDIOC_STREAMOFF failed: %s",strerror(errno)); - } - - for(i=0;iframe_max;++i){ - mblk_t *msg=s->frames[i]; - int len=msg->b_datap->db_lim-msg->b_datap->db_base; - if (v4l2_munmap(msg->b_datap->db_base,len)<0){ - ms_warning("MSV4l2: Fail to unmap: %s",strerror(errno)); - } - freemsg(s->frames[i]); - s->frames[i]=NULL; - } -} - - - -static void msv4l2_init(MSFilter *f){ - V4l2State *s=ms_new0(V4l2State,1); - s->dev=ms_strdup("/dev/video0"); - s->fd=-1; - s->vsize=MS_VIDEO_SIZE_CIF; - s->fps=15; - s->configured=FALSE; - f->data=s; -} - -static void msv4l2_uninit(MSFilter *f){ - V4l2State *s=(V4l2State*)f->data; - ms_free(s->dev); - ms_free(s); -} - -static void msv4l2_preprocess(MSFilter *f){ - V4l2State *s=(V4l2State*)f->data; - if (s->fd==-1 && msv4l2_open(s)!=0) { - return; - } - if (!s->configured && msv4l2_configure(s)!=0){ - return; - } - if (msv4l2_do_mmap(s)==0){ - ms_message("V4L2 video capture started."); - }else{ - msv4l2_close(s); - } - s->start_time=f->ticker->time; -} - -static void msv4l2_process(MSFilter *f){ - V4l2State *s=(V4l2State*)f->data; - uint32_t elapsed; - - if (s->fd!=-1){ - /*see it is necessary to output a frame:*/ - elapsed=f->ticker->time-s->start_time; - if (((float)elapsed*s->fps/1000.0)>s->frame_count){ - mblk_t *m; - m=v4lv2_grab_image(s); - if (m){ - mblk_t *om=dupb(m); - mblk_set_marker_info(om,(s->pix_fmt==MS_MJPEG)); - ms_queue_put(f->outputs[0],om); - s->frame_count++; - } - } - } -} - -static void msv4l2_postprocess(MSFilter *f){ - V4l2State *s=(V4l2State*)f->data; - if (s->fd!=-1){ - msv4l2_do_munmap(s); - msv4l2_close(s); - } -} - -static int msv4l2_set_fps(MSFilter *f, void *arg){ - V4l2State *s=(V4l2State*)f->data; - s->fps=*(float*)arg; - return 0; -} - -static int msv4l2_set_vsize(MSFilter *f, void *arg){ - V4l2State *s=(V4l2State*)f->data; - s->vsize=*(MSVideoSize*)arg; - return 0; -} - -static int msv4l2_get_vsize(MSFilter *f, void *arg){ - V4l2State *s=(V4l2State*)f->data; - *(MSVideoSize*)arg=s->vsize; - return 0; -} - -static int msv4l2_get_pixfmt(MSFilter *f, void *arg){ - V4l2State *s=(V4l2State*)f->data; - if (s->fd==-1){ - if (msv4l2_open(s)==0){ - msv4l2_configure(s); - *(MSPixFmt*)arg=s->pix_fmt; - return 0; - }else return -1; - } - *(MSPixFmt*)arg=s->pix_fmt; - return 0; -} - -static int msv4l2_set_devfile(MSFilter *f, void *arg){ - V4l2State *s=(V4l2State*)f->data; - if (s->dev) ms_free(s->dev); - s->dev=ms_strdup((char*)arg); - return 0; -} - -static MSFilterMethod msv4l2_methods[]={ - { MS_FILTER_SET_FPS , msv4l2_set_fps }, - { MS_FILTER_SET_VIDEO_SIZE, msv4l2_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, msv4l2_get_vsize }, - { MS_FILTER_GET_PIX_FMT , msv4l2_get_pixfmt }, - { 0 , NULL } -}; - -MSFilterDesc ms_v4l2_desc={ - .id=MS_V4L2_CAPTURE_ID, - .name="MSV4L2Capture", - .text=N_("A filter to grab pictures from Video4Linux2-powered cameras"), - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .init=msv4l2_init, - .preprocess=msv4l2_preprocess, - .process=msv4l2_process, - .postprocess=msv4l2_postprocess, - .uninit=msv4l2_uninit, - .methods=msv4l2_methods -}; - -MS_FILTER_DESC_EXPORT(ms_v4l2_desc) - -static MSFilter *msv4l2_create_reader(MSWebCam *obj){ - MSFilter *f=ms_filter_new(MS_V4L2_CAPTURE_ID); - msv4l2_set_devfile(f,obj->name); - return f; -} - -static void msv4l2_detect(MSWebCamManager *obj); - -static void msv4l2_cam_init(MSWebCam *cam){ -} - -MSWebCamDesc v4l2_card_desc={ - "V4L2", - &msv4l2_detect, - &msv4l2_cam_init, - &msv4l2_create_reader, - NULL -}; - -static void msv4l2_detect(MSWebCamManager *obj){ - struct v4l2_capability cap; - char devname[32]; - int i; - for(i=0;i<10;++i){ - int fd; - snprintf(devname,sizeof(devname),"/dev/video%i",i); - fd=open(devname,O_RDWR); - if (fd!=-1){ - if (v4l2_ioctl (fd, VIDIOC_QUERYCAP, &cap)==0) { - /* is a V4LV2 */ - MSWebCam *cam=ms_web_cam_new(&v4l2_card_desc); - cam->name=ms_strdup(devname); - ms_web_cam_manager_add_cam(obj,cam); - } - close(fd); - } - } -} - - -#endif diff --git a/linphone/mediastreamer2/src/msv4m.m b/linphone/mediastreamer2/src/msv4m.m deleted file mode 100644 index de52a465f..000000000 --- a/linphone/mediastreamer2/src/msv4m.m +++ /dev/null @@ -1,706 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef __APPLE__ - -#include "mediastreamer-config.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" -#include "nowebcam.h" -#include "mediastreamer2/mswebcam.h" - -// build for carbon -#define TARGET_API_MAC_CARBON 1 - -#if __APPLE_CC__ - #include - #include - #include -#else - #include - #include - #include - #include - #include -#endif - -typedef struct v4mState{ - char * name; - char * id; - SeqGrabComponent seqgrab; - SGChannel sgchanvideo; - GWorldPtr pgworld; - ImageSequence decomseq; - - char *mmapdbuf; - int msize;/*mmapped size*/ - MSVideoSize vsize; - MSVideoSize got_vsize; - int pix_fmt; - int int_pix_fmt; /*internal pixel format */ - mblk_t *mire; - queue_t rq; - ms_mutex_t mutex; - int frame_ind; - int frame_max; - float fps; - float start_time; - int frame_count; - int queued; - bool_t run; - bool_t usemire; -}v4mState; - -static void v4m_init(MSFilter *f){ - v4mState *s=ms_new0(v4mState,1); - s->seqgrab=NULL; - s->sgchanvideo=NULL; - s->pgworld=NULL; - s->decomseq=0; - - s->run=FALSE; - s->mmapdbuf=NULL; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->pix_fmt=MS_RGB24; - qinit(&s->rq); - s->mire=NULL; - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - s->usemire=(getenv("DEBUG")!=NULL); - s->queued=0; - f->data=s; -} - - -#define BailErr(x) {err = x; if(err != noErr) goto bail;} - -pascal OSErr sgdata_callback(SGChannel c, Ptr p, long len, long *offset, long chRefCon, TimeValue time, short writeType, long refCon); -pascal OSErr sgdata_callback(SGChannel c, Ptr p, long len, long *offset, long chRefCon, TimeValue time, short writeType, long refCon) -{ -#pragma unused(offset,chRefCon,time,writeType) - - CodecFlags ignore; - v4mState *s=(v4mState *)refCon; - ComponentResult err = noErr; - - if (!s) goto bail; - - Rect boundsRect = {0, 0, s->vsize.height, s->vsize.width}; /* 240 , 320*/ - if (s->pgworld) { - - if (s->decomseq == 0) { - Rect sourceRect = { 0, 0 }; - MatrixRecord scaleMatrix; - ImageDescriptionHandle imageDesc = (ImageDescriptionHandle)NewHandle(0); - - err = SGGetChannelSampleDescription(c,(Handle)imageDesc); - BailErr(err); - - // make a scaling matrix for the sequence - sourceRect.right = (**imageDesc).width; - sourceRect.bottom = (**imageDesc).height; - RectMatrix(&scaleMatrix, &sourceRect, &boundsRect); - - err = DecompressSequenceBegin(&s->decomseq, // pointer to field to receive unique ID for sequence - imageDesc, // handle to image description structure - s->pgworld, // port for the DESTINATION image - NULL, // graphics device handle, if port is set, set to NULL - NULL, // source rectangle defining the portion of the image to decompress - &scaleMatrix, // transformation matrix - srcCopy, // transfer mode specifier - NULL, // clipping region in dest. coordinate system to use as a mask - 0, // flags - codecNormalQuality, // accuracy in decompression - bestSpeedCodec); // compressor identifier or special identifiers ie. bestSpeedCodec - BailErr(err); - - DisposeHandle((Handle)imageDesc); - imageDesc = NULL; - } - - // decompress a frame into the GWorld - can queue a frame for async decompression when passed in a completion proc - // once the image is in the GWorld it can be manipulated at will - err = DecompressSequenceFrameS(s->decomseq, // sequence ID returned by DecompressSequenceBegin - p, // pointer to compressed image data - len, // size of the buffer - 0, // in flags - &ignore, // out flags - NULL); // async completion proc - BailErr(err); - - { - unsigned line; - mblk_t *buf; - int size = s->vsize.width * s->vsize.height * 3; - buf=allocb(size,0); - - PixMap * pixmap = *GetGWorldPixMap(s->pgworld); - uint8_t * data; - unsigned rowBytes = pixmap->rowBytes & (((unsigned short) 0xFFFF) >> 2); - unsigned pixelSize = pixmap->pixelSize / 8; // Pixel size in bytes - unsigned lineOffset = rowBytes - s->vsize.width * pixelSize; - - data = (uint8_t *) GetPixBaseAddr(GetGWorldPixMap(s->pgworld)); - - for (line = 0 ; line < s->vsize.height ; line++) { - unsigned offset = line * (s->vsize.width * pixelSize + lineOffset); - memcpy(buf->b_wptr + ((line * s->vsize.width) * pixelSize), data + offset, (rowBytes - lineOffset)); - } - - if (s->pix_fmt==MS_RGB24) - { - /* Conversion from top down bottom up (BGR to RGB and flip) */ - unsigned long Index,nPixels; - unsigned char *blue; - unsigned char tmp; - short iPixelSize; - - blue=buf->b_wptr; - - nPixels=s->vsize.width*s->vsize.height; - iPixelSize=24/8; - - for(Index=0;Index!=nPixels;Index++) // For each pixel - { - tmp=*blue; - *blue=*(blue+2); - *(blue+2)=tmp; - blue+=iPixelSize; - } - } - - buf->b_wptr+=size; - //ms_mutex_lock(&s->mutex); /* called during SGIdle? */ - putq(&s->rq, buf); - //ms_mutex_unlock(&s->mutex); - } - } - -bail: - return err; -} - -static int v4m_close(v4mState *s) -{ - if(s->seqgrab) - CloseComponent(s->seqgrab); - s->seqgrab=NULL; - if (s->decomseq) - CDSequenceEnd(s->decomseq); - s->decomseq=0; - if (s->pgworld!=NULL) - DisposeGWorld(s->pgworld); - s->pgworld=NULL; - return 0; -} -unsigned char *stdToPascalString(char *buffer, char * str) { - if (strlen(str) <= 255) { - buffer[0] = strlen(str); - - memcpy(buffer + 1, str, strlen(str)); - - return (unsigned char*)buffer; - } else { - return NULL; - } -} - -static int sequence_grabber_start(v4mState *s) -{ - OSErr err = noErr; - char *camName; - - ms_warning("Opening component"); - s->seqgrab = OpenDefaultComponent(SeqGrabComponentType, 0); - if (s->seqgrab == NULL) { - ms_warning("can't get default sequence grabber component"); - return -1; - } - - ms_warning("Initializing component"); - err = SGInitialize(s->seqgrab); - if (err != noErr) { - ms_warning("can't initialize sequence grabber component"); - return -1; - } - - ms_warning("SetDataRef"); - err = SGSetDataRef(s->seqgrab, 0, 0, seqGrabDontMakeMovie); - if (err != noErr) { - ms_warning("can't set the destination data reference"); - return -1; - } - - ms_warning("Creating new channel"); - err = SGNewChannel(s->seqgrab, VideoMediaType, &s->sgchanvideo); - if (err != noErr) { - ms_warning("can't create a video channel"); - return -1; - } - - - camName = alloca(strlen(s->name) + 1); - - err = SGSetChannelDevice(s->sgchanvideo, stdToPascalString(camName, s->name)); - if (err != noErr) { - ms_warning("can't set channel device"); - return -1; - } - - short input = atoi(s->id); - - err = SGSetChannelDeviceInput(s->sgchanvideo,input); - if (err != noErr) { - ms_warning("can't set channel device input"); - return -1; - } - - ms_warning("createGWorld"); - Rect theRect = {0, 0, s->vsize.height, s->vsize.width}; - - err = QTNewGWorld(&(s->pgworld), // returned GWorld - k24BGRPixelFormat, - &theRect, // bounding rectangle - 0, // color table - NULL, // graphic device handle - 0); // flags - if (err!=noErr) - { - return -1; - } - - if(!LockPixels(GetPortPixMap(s->pgworld))) - { - v4m_close(s); - return -1; - } - - err = SGSetGWorld(s->seqgrab, s->pgworld, GetMainDevice()); - if (err != noErr) { - ms_warning("can't set GWorld"); - return -1; - } - - ms_warning("SGSetDataProc"); - err = SGSetDataProc(s->seqgrab,NewSGDataUPP(sgdata_callback),(long)s); - if (err != noErr) { - ms_warning("can't set data proc"); - return -1; - } - - ms_warning("SGSetChannelUsage"); - err = SGSetChannelUsage(s->sgchanvideo, seqGrabRecord); - if (err != noErr) { - ms_warning("can't set channel usage"); - return -1; - } - - ms_warning("SGPrepare"); - err = SGPrepare(s->seqgrab, false, true); - if (err != noErr) { - ms_warning("can't prepare sequence grabber component"); - return -1; - } - - err = SGSetChannelBounds(s->sgchanvideo, &theRect); - if (err!=noErr) - { - v4m_close(s); - return -1; - } - - err = SGStartRecord(s->seqgrab); - if (err!=noErr) - { - v4m_close(s); - return -1; - } - - return 0; -} - -static int v4m_start(MSFilter *f, void *arg) -{ - v4mState *s=(v4mState*)f->data; - int err=0; - - err = sequence_grabber_start(s); - - if (err!=0) - { - s->pix_fmt=MS_YUV420P; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - return 0; - } - - ms_message("v4m video device opened."); - s->pix_fmt=MS_RGB24; - - return 0; -} - -static void v4m_start_capture(v4mState *s){ - if (s->seqgrab!=NULL){ - s->run=TRUE; - } -} - -static int v4m_stop(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - if (s->seqgrab!=NULL){ - ms_mutex_lock(&s->mutex); - SGStop(s->seqgrab); - v4m_close(s); - flushq(&s->rq,0); - ms_mutex_unlock(&s->mutex); - } - return 0; -} - -static void v4m_stop_capture(v4mState *s){ - if (s->run){ - s->run=FALSE; - ms_message("v4m capture stopped."); - } -} - - -static void v4m_uninit(MSFilter *f){ - v4mState *s=(v4mState*)f->data; - if (s->seqgrab!=NULL) v4m_stop(f,NULL); - //ms_free(s->dev); - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - freemsg(s->mire); - ms_free(s); -} - -static mblk_t * v4m_make_mire(v4mState *s){ - unsigned char *data; - int i,j,line,pos; - int patternw=s->vsize.width/6; - int patternh=s->vsize.height/6; - int red,green=0,blue=0; - if (s->mire==NULL){ - s->mire=allocb(s->vsize.width*s->vsize.height*3,0); - s->mire->b_wptr=s->mire->b_datap->db_lim; - } - data=s->mire->b_rptr; - for (i=0;ivsize.height;++i){ - line=i*s->vsize.width*3; - if ( ((i+s->frame_ind)/patternh) & 0x1) red=255; - else red= 0; - for (j=0;jvsize.width;++j){ - pos=line+(j*3); - - if ( ((j+s->frame_ind)/patternw) & 0x1) blue=255; - else blue= 0; - - data[pos]=red; - data[pos+1]=green; - data[pos+2]=blue; - } - } - s->frame_ind++; - return s->mire; -} - -static mblk_t * v4m_make_nowebcam(v4mState *s){ - if (s->mire==NULL && s->frame_ind==0){ - s->mire=ms_load_nowebcam(&s->vsize, -1); - } - s->frame_ind++; - return s->mire; -} - -static void v4m_process(MSFilter * obj){ - v4mState *s=(v4mState*)obj->data; - uint32_t timestamp; - int cur_frame; - if (s->frame_count==-1){ - s->start_time=obj->ticker->time; - s->frame_count=0; - } - - ms_mutex_lock(&s->mutex); - - if (s->seqgrab!=NULL) - { - SGIdle(s->seqgrab); - } - - cur_frame=((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>=s->frame_count){ - mblk_t *om=NULL; - /*keep the most recent frame if several frames have been captured */ - if (s->seqgrab!=NULL){ - om=getq(&s->rq); - }else{ - if (s->pix_fmt==MS_YUV420P - && s->vsize.width==MS_VIDEO_SIZE_CIF_W - && s->vsize.height==MS_VIDEO_SIZE_CIF_H) - { - if (s->usemire){ - om=dupmsg(v4m_make_mire(s)); - }else { - mblk_t *tmpm=v4m_make_nowebcam(s); - if (tmpm) om=dupmsg(tmpm); - } - } - } - if (om!=NULL){ - timestamp=obj->ticker->time*90;/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - mblk_set_marker_info(om,TRUE); - ms_queue_put(obj->outputs[0],om); - /*ms_message("picture sent");*/ - s->frame_count++; - } - }else flushq(&s->rq,0); - - ms_mutex_unlock(&s->mutex); -} - -static void v4m_preprocess(MSFilter *f){ - v4mState *s=(v4mState*)f->data; - - if(s->seqgrab == NULL) - v4m_start(f,NULL); - - v4m_start_capture(s); -} - -static void v4m_postprocess(MSFilter *f){ - v4mState *s=(v4mState*)f->data; - v4m_stop_capture(s); -} - -static int v4m_set_fps(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - s->fps=*((float*)arg); - s->frame_count=-1; - return 0; -} - -static int v4m_get_pix_fmt(MSFilter *f,void *arg){ - v4mState *s=(v4mState*)f->data; - *((MSPixFmt*)arg) = s->pix_fmt; - return 0; -} - -static int v4m_set_vsize(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - s->vsize=*((MSVideoSize*)arg); - return 0; -} - -static int v4m_get_vsize(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - *(MSVideoSize*)arg=s->vsize; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , v4m_set_fps }, - { MS_FILTER_GET_PIX_FMT , v4m_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, v4m_set_vsize }, - { MS_V4L_START , v4m_start }, - { MS_V4L_STOP , v4m_stop }, - { MS_FILTER_GET_VIDEO_SIZE, v4m_get_vsize }, - { 0 , NULL } -}; - -MSFilterDesc ms_v4m_desc={ - .id=MS_V4L_ID, - .name="MSV4m", - .text="A video for macosx compatible source filter to stream pictures.", - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=v4m_init, - .preprocess=v4m_preprocess, - .process=v4m_process, - .postprocess=v4m_postprocess, - .uninit=v4m_uninit, - .methods=methods -}; - -MS_FILTER_DESC_EXPORT(ms_v4m_desc) - -static void ms_v4m_detect(MSWebCamManager *obj); - -static void ms_v4m_cam_init(MSWebCam *cam) -{ - -} - -static int v4m_set_device(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - - s->id = (char*) malloc(sizeof(char)*strlen((char*)arg)); - strcpy(s->id,(char*)arg); - - return 0; -} - -static int v4m_set_name(MSFilter *f, void *arg){ - v4mState *s=(v4mState*)f->data; - - s->name = (char*) malloc(sizeof(char)*strlen((char*)arg)); - strcpy(s->name,(char*)arg); - - return 0; -} - -static MSFilter *ms_v4m_create_reader(MSWebCam *obj) -{ - MSFilter *f= ms_filter_new_from_desc(&ms_v4m_desc); - - v4m_set_device(f,obj->id); - v4m_set_name(f,obj->data); - - return f; -} - -MSWebCamDesc ms_v4m_cam_desc={ - "VideoForMac grabber", - &ms_v4m_detect, - &ms_v4m_cam_init, - &ms_v4m_create_reader, - NULL -}; - -char * genDeviceName(unsigned char * device,short inputIndex, unsigned char * input) -{ - static char buffer[32]; - snprintf(buffer,sizeof(buffer), "%s:%d:%s", device,inputIndex,input); - return buffer; -} - -/* - * convert pascal string to c string - */ -static char* pas2cstr(const char *pstr) -{ - char *cstr = ms_malloc(pstr[0] + 1); - memcpy(cstr, pstr+1, pstr[0]); - cstr[(int)pstr[0]] = 0; - - return cstr; - -} - -static void ms_v4m_detect(MSWebCamManager *obj){ - - - SGDeviceList sgDeviceList; - OSErr err = noErr; - SGChannel _SGChanVideo; - - SeqGrabComponent _seqGrab; - NSApplicationLoad(); - - if (_SGChanVideo) { - SGDisposeChannel(_seqGrab, _SGChanVideo); - } - - if (_seqGrab) { - CloseComponent(_seqGrab); - } - - _seqGrab = OpenDefaultComponent(SeqGrabComponentType, 0); - if (_seqGrab == NULL) { - ms_warning("can't get default sequence grabber component"); - return; - } - - err = SGInitialize(_seqGrab); - if (err != noErr) { - ms_warning("can't initialize sequence grabber component"); - return; - } - - err = SGSetDataRef(_seqGrab, 0, 0, seqGrabDontMakeMovie); - if (err != noErr) { - ms_warning("can't set the destination data reference"); - return; - } - - err = SGNewChannel(_seqGrab, VideoMediaType, &_SGChanVideo); - if (err != noErr) { - ms_warning("can't create a video channel"); - return; - } - - err = SGGetChannelDeviceList(_SGChanVideo, sgDeviceListIncludeInputs, &sgDeviceList); - if (err != noErr) - ms_warning("can't get device list"); - - register short i = 0; - for (; i < (*sgDeviceList)->count ; i++) - { - if (!((*sgDeviceList)->entry[i].flags & sgDeviceNameFlagDeviceUnavailable)) - { - SGDeviceInputList inputs = (*sgDeviceList)->entry[i].inputs; - - register short j = 0; - for (; j < (*inputs)->count ; j++) - { - if (!((*inputs)->entry[j].flags & sgDeviceInputNameFlagInputUnavailable)) - { - MSWebCam *cam=ms_web_cam_new(&ms_v4m_cam_desc); - char * buffer = (char*)malloc(sizeof(char)*32); - sprintf(buffer,"%d",(*inputs)->selectedIndex); - cam->name=pas2cstr((*inputs)->entry[j].name); - cam->id = buffer; - cam->data = pas2cstr((*sgDeviceList)->entry[i].name); - ms_web_cam_manager_add_cam(obj,cam); - ms_warning("web cam found : %s:%s:%s",cam->name,cam->id,cam->data); - } - } - } - } - - SGDisposeDeviceList(_seqGrab, sgDeviceList); - - - if (_SGChanVideo) { - SGDisposeChannel(_seqGrab, _SGChanVideo); - } - - if (_seqGrab) { - CloseComponent(_seqGrab); - } -} - -#endif diff --git a/linphone/mediastreamer2/src/msvideo.c b/linphone/mediastreamer2/src/msvideo.c deleted file mode 100644 index 7c1abeb25..000000000 --- a/linphone/mediastreamer2/src/msvideo.c +++ /dev/null @@ -1,252 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msvideo.h" - -static void yuv_buf_init(YuvBuf *buf, int w, int h, uint8_t *ptr){ - int ysize,usize; - ysize=w*h; - usize=ysize/4; - buf->w=w; - buf->h=h; - buf->planes[0]=ptr; - buf->planes[1]=buf->planes[0]+ysize; - buf->planes[2]=buf->planes[1]+usize; - buf->planes[3]=0; - buf->strides[0]=w; - buf->strides[1]=w/2; - buf->strides[2]=buf->strides[1]; - buf->strides[3]=0; -} - -int yuv_buf_init_from_mblk(YuvBuf *buf, mblk_t *m){ - int size=m->b_wptr-m->b_rptr; - int w,h; - if (size==(MS_VIDEO_SIZE_QCIF_W*MS_VIDEO_SIZE_QCIF_H*3)/2){ - w=MS_VIDEO_SIZE_QCIF_W; - h=MS_VIDEO_SIZE_QCIF_H; - }else if (size==(MS_VIDEO_SIZE_CIF_W*MS_VIDEO_SIZE_CIF_H*3)/2){ - w=MS_VIDEO_SIZE_CIF_W; - h=MS_VIDEO_SIZE_CIF_H; - }else if (size==(MS_VIDEO_SIZE_QVGA_W*MS_VIDEO_SIZE_QVGA_H*3)/2){ - w=MS_VIDEO_SIZE_QVGA_W; - h=MS_VIDEO_SIZE_QVGA_H; - }else if (size==(MS_VIDEO_SIZE_VGA_W*MS_VIDEO_SIZE_VGA_H*3)/2){ - w=MS_VIDEO_SIZE_VGA_W; - h=MS_VIDEO_SIZE_VGA_H; - }else if (size==(MS_VIDEO_SIZE_4CIF_W*MS_VIDEO_SIZE_4CIF_H*3)/2){ - w=MS_VIDEO_SIZE_4CIF_W; - h=MS_VIDEO_SIZE_4CIF_H; - }else if (size==(MS_VIDEO_SIZE_SVGA_W*MS_VIDEO_SIZE_SVGA_H*3)/2){ - w=MS_VIDEO_SIZE_SVGA_W; - h=MS_VIDEO_SIZE_SVGA_H; - }else if (size==(MS_VIDEO_SIZE_SQCIF_W*MS_VIDEO_SIZE_SQCIF_H*3)/2){ - w=MS_VIDEO_SIZE_SQCIF_W; - h=MS_VIDEO_SIZE_SQCIF_H; - }else if (size==(MS_VIDEO_SIZE_QQVGA_W*MS_VIDEO_SIZE_QQVGA_H*3)/2){ - w=MS_VIDEO_SIZE_QQVGA_W; - h=MS_VIDEO_SIZE_QQVGA_H; - }else if (size==(MS_VIDEO_SIZE_NS1_W*MS_VIDEO_SIZE_NS1_H*3)/2){ - w=MS_VIDEO_SIZE_NS1_W; - h=MS_VIDEO_SIZE_NS1_H; - }else if (size==(MS_VIDEO_SIZE_QSIF_W*MS_VIDEO_SIZE_QSIF_H*3)/2){ - w=MS_VIDEO_SIZE_QSIF_W; - h=MS_VIDEO_SIZE_QSIF_H; - }else if (size==(MS_VIDEO_SIZE_SIF_W*MS_VIDEO_SIZE_SIF_H*3)/2){ - w=MS_VIDEO_SIZE_SIF_W; - h=MS_VIDEO_SIZE_SIF_H; - }else if (size==(MS_VIDEO_SIZE_4SIF_W*MS_VIDEO_SIZE_4SIF_H*3)/2){ - w=MS_VIDEO_SIZE_4SIF_W; - h=MS_VIDEO_SIZE_4SIF_H; - }else if (size==(MS_VIDEO_SIZE_288P_W*MS_VIDEO_SIZE_288P_H*3)/2){ - w=MS_VIDEO_SIZE_288P_W; - h=MS_VIDEO_SIZE_288P_H; - }else if (size==(MS_VIDEO_SIZE_448P_W*MS_VIDEO_SIZE_448P_H*3)/2){ - w=MS_VIDEO_SIZE_448P_W; - h=MS_VIDEO_SIZE_448P_H; - }else if (size==(MS_VIDEO_SIZE_576P_W*MS_VIDEO_SIZE_576P_H*3)/2){ - w=MS_VIDEO_SIZE_576P_W; - h=MS_VIDEO_SIZE_576P_H; - }else if (size==(MS_VIDEO_SIZE_720P_W*MS_VIDEO_SIZE_720P_H*3)/2){ - w=MS_VIDEO_SIZE_720P_W; - h=MS_VIDEO_SIZE_720P_H; - }else if (size==(MS_VIDEO_SIZE_1080P_W*MS_VIDEO_SIZE_1080P_H*3)/2){ - w=MS_VIDEO_SIZE_1080P_W; - h=MS_VIDEO_SIZE_1080P_H; - }else if (size==(MS_VIDEO_SIZE_SDTV_W*MS_VIDEO_SIZE_SDTV_H*3)/2){ - w=MS_VIDEO_SIZE_SDTV_W; - h=MS_VIDEO_SIZE_SDTV_H; - }else if (size==(MS_VIDEO_SIZE_HDTVP_W*MS_VIDEO_SIZE_HDTVP_H*3)/2){ - w=MS_VIDEO_SIZE_HDTVP_W; - h=MS_VIDEO_SIZE_HDTVP_H; - }else if (size==(MS_VIDEO_SIZE_XGA_W*MS_VIDEO_SIZE_XGA_H*3)/2){ - w=MS_VIDEO_SIZE_XGA_W; - h=MS_VIDEO_SIZE_XGA_H; - }else if (size==(MS_VIDEO_SIZE_WXGA_W*MS_VIDEO_SIZE_WXGA_H*3)/2){ - w=MS_VIDEO_SIZE_WXGA_W; - h=MS_VIDEO_SIZE_WXGA_H; - }else if (size==(160*112*3)/2){/*format used by econf*/ - w=160; - h=112; - }else if (size==(320*200*3)/2){/*format used by gTalk */ - w=320; - h=200; - }else { - ms_error("Unsupported image size: size=%i (bug somewhere !)",size); - return -1; - } - yuv_buf_init(buf,w,h,m->b_rptr); - return 0; -} - -void yuv_buf_init_from_mblk_with_size(YuvBuf *buf, mblk_t *m, int w, int h){ - yuv_buf_init(buf,w,h,m->b_rptr); -} - -mblk_t * yuv_buf_alloc(YuvBuf *buf, int w, int h){ - int size=(w*h*3)/2; - mblk_t *msg=allocb(size,0); - yuv_buf_init(buf,w,h,msg->b_wptr); - msg->b_wptr+=size; - return msg; -} - -static void plane_copy(const uint8_t *src_plane, int src_stride, - uint8_t *dst_plane, int dst_stride, MSVideoSize roi){ - int i; - for(i=0;iplanes[0],buf->strides[0],buf->w,buf->h); - plane_mirror(buf->planes[1],buf->strides[1],buf->w/2,buf->h/2); - plane_mirror(buf->planes[2],buf->strides[2],buf->w/2,buf->h/2); -} - -#ifndef MAKEFOURCC -#define MAKEFOURCC(a,b,c,d) ((d)<<24 | (c)<<16 | (b)<<8 | (a)) -#endif - -MSPixFmt ms_fourcc_to_pix_fmt(uint32_t fourcc){ - MSPixFmt ret; - switch (fourcc){ - case MAKEFOURCC('I','4','2','0'): - ret=MS_YUV420P; - break; - case MAKEFOURCC('Y','U','Y','2'): - ret=MS_YUY2; - break; - case MAKEFOURCC('Y','U','Y','V'): - ret=MS_YUYV; - break; - case MAKEFOURCC('U','Y','V','Y'): - ret=MS_UYVY; - break; - case 0: /*BI_RGB on windows*/ - ret=MS_RGB24; - break; - default: - ret=MS_PIX_FMT_UNKNOWN; - } - return ret; -} - -void rgb24_revert(uint8_t *buf, int w, int h, int linesize){ - uint8_t *p,*pe; - int i,j; - uint8_t *end=buf+((h-1)*linesize); - uint8_t exch; - p=buf; - pe=end-1; - for(i=0;iwidth!=0;++p){ - if (ms_video_size_greater_than(vs,*p) && !ms_video_size_equal(vs,*p)){ - ret=*p; - }else return ret; - } - return ret; -}; diff --git a/linphone/mediastreamer2/src/msvolume.c b/linphone/mediastreamer2/src/msvolume.c deleted file mode 100644 index 8d1df08d6..000000000 --- a/linphone/mediastreamer2/src/msvolume.c +++ /dev/null @@ -1,431 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msvolume.h" -#include "mediastreamer2/msticker.h" -#include - -#ifdef HAVE_SPEEXDSP -#include -#endif - -static const float max_e=32767*32767; -static const float coef=0.1; -static const float gain_k=0.02; -static const float en_weight=4.0; -static const float noise_thres=0.1; - - -typedef struct Volume{ - float energy; - float norm_en; - float gain; /*the one really applied, smoothed by noise gate and echo limiter*/ - float static_gain; /*the one fixed by the user*/ - float gain_k; - float thres; - float force; - float target_gain; /*the target gain choosed by echo limiter and noise gate*/ - float last_peer_en; - int sustain_time; /* time in ms for which echo limiter remains active after resuming from speech to silence.*/ - uint64_t sustain_start; - MSFilter *peer; -#ifdef HAVE_SPEEXDSP - SpeexPreprocessState *speex_pp; -#endif - int sample_rate; - int nsamples; - int ng_cut_time; /*noise gate cut time, after last speech detected*/ - int ng_noise_dur; - float ng_threshold; - float ng_floorgain; - MSBufferizer *buffer; - bool_t ea_active; - bool_t agc_enabled; - bool_t noise_gate_enabled; -}Volume; - -static void volume_init(MSFilter *f){ - Volume *v=(Volume*)ms_new(Volume,1); - v->energy=0; - v->norm_en=0; - v->static_gain=v->gain=1; - v->ea_active=FALSE; - v->gain_k=gain_k; - v->thres=noise_thres; - v->force=en_weight; - v->peer=NULL; - v->last_peer_en=0; - v->sustain_time=200; - v->sustain_start=0; - v->agc_enabled=FALSE; - v->buffer=ms_bufferizer_new(); - v->sample_rate=8000; - v->nsamples=80; - v->noise_gate_enabled=FALSE; - v->ng_cut_time=100;/*milliseconds*/ - v->ng_noise_dur=0; - v->ng_threshold=noise_thres; - v->ng_floorgain=0; -#ifdef HAVE_SPEEXDSP - v->speex_pp=NULL; -#endif - f->data=v; -} - -static void volume_uninit(MSFilter *f){ - Volume *v=(Volume*)f->data; -#ifdef HAVE_SPEEXDSP - if (v->speex_pp) - speex_preprocess_state_destroy(v->speex_pp); -#endif - ms_bufferizer_destroy(v->buffer); - ms_free(f->data); -} - -static int volume_get(MSFilter *f, void *arg){ - float *farg=(float*)arg; - Volume *v=(Volume*)f->data; - *farg=10*ortp_log10f((v->energy+1)/max_e); - - return 0; -} - -static int volume_set_sample_rate(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->sample_rate=*(int*)arg; - return 0; -} - -static int volume_get_linear(MSFilter *f, void *arg){ - float *farg=(float*)arg; - Volume *v=(Volume*)f->data; - *farg=(v->energy+1)/max_e; - return 0; -} -#ifdef HAVE_SPEEXDSP -static void volume_agc_process(Volume *v, mblk_t *om){ - speex_preprocess_run(v->speex_pp,(int16_t*)om->b_rptr); -} -#else - -static void volume_agc_process(Volume *v, mblk_t *om){ -} - -#endif - - -static inline float compute_gain(float static_gain, float energy, float weight){ - float ret=static_gain*(1 - (energy*weight)); - if (ret<0) ret=0; - return ret; -} - -/* -The principle of this algorithm is that we apply a gain to the input signal which is opposite to the -energy measured by the peer MSVolume. -For example if some noise is played by the speaker, then the signal captured by the microphone will be lowered. -The gain changes smoothly when the peer energy is decreasing, but is immediately changed when the peer energy is -increasing. -*/ - -static void volume_echo_avoider_process(Volume *v, uint64_t curtime){ - float peer_e; - float gain; - ms_filter_call_method(v->peer,MS_VOLUME_GET_LINEAR,&peer_e); - peer_e=sqrt(peer_e); - if (v->ea_active){ - if (peer_e>v->thres){ - /*lower our output*/ - gain=compute_gain(v->static_gain,peer_e,v->force); - if (peer_e>v->last_peer_en) - v->gain=gain; - }else { - v->sustain_start=curtime; - v->ea_active=FALSE; - gain=v->gain; - } - }else{ - int peer_active=FALSE; - ms_filter_call_method(v->peer,MS_VOLUME_GET_EA_STATE,&peer_active); - if (peer_e>v->thres && ! peer_active){ - /*lower our output*/ - gain=compute_gain(v->static_gain,peer_e,v->force); - v->ea_active=TRUE; - v->gain=gain; - }else { - if (curtime!=0 && (curtime-v->sustain_start)sustain_time){ - gain=v->gain; - }else{/*restore normal gain*/ - gain=v->static_gain; - v->sustain_start=0; - } - } - } - v->last_peer_en=peer_e; - v->target_gain=gain; - ms_message("ea_active=%i, peer_e=%f gain=%f gain_k=%f force=%f",v->ea_active,peer_e,v->gain, v->gain_k,v->force); -} - -static void volume_noise_gate_process(Volume *v , float energy, mblk_t *om){ - int nsamples=((om->b_wptr-om->b_rptr)/2); - if ((energy/max_e)ng_threshold){ - v->ng_noise_dur+=(nsamples*1000)/v->sample_rate; - if (v->ng_noise_dur>v->ng_cut_time){ - v->target_gain=v->ng_floorgain; - } - }else{ - v->ng_noise_dur=0; - /*let the target gain unchanged, ie let the echo-limiter choose the gain*/ - } -} - -static int volume_set_gain(MSFilter *f, void *arg){ - float *farg=(float*)arg; - Volume *v=(Volume*)f->data; - v->gain=v->static_gain=v->target_gain=*farg; - return 0; -} - - -static int volume_get_ea_state(MSFilter *f, void *arg){ - int *barg=(int*)arg; - Volume *v=(Volume*)f->data; - *barg=v->ea_active; - return 0; -} - -static int volume_set_peer(MSFilter *f, void *arg){ - MSFilter *p=(MSFilter*)arg; - Volume *v=(Volume*)f->data; - v->peer=p; - return 0; -} - -static int volume_set_agc(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->agc_enabled=*(int*)arg; - return 0; -} - -static int volume_set_ea_threshold(MSFilter *f, void*arg){ - Volume *v=(Volume*)f->data; - float val=*(float*)arg; - if (val<0 || val>1) { - ms_error("Error: threshold must be in range [0..1]"); - return -1; - } - v->thres=val; - return 0; -} - -static int volume_set_ea_speed(MSFilter *f, void*arg){ - Volume *v=(Volume*)f->data; - float val=*(float*)arg; - if (val<0 || val>1) { - ms_error("Error: speed must be in range [0..1]"); - return -1; - } - v->gain_k=val; - return 0; -} - -static int volume_set_ea_force(MSFilter *f, void*arg){ - Volume *v=(Volume*)f->data; - float val=*(float*)arg; - v->force=val; - return 0; -} - -static int volume_set_ea_sustain(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->sustain_time=*(int*)arg; - return 0; -} - -static int volume_enable_noise_gate(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->noise_gate_enabled=*(int*)arg; - return 0; -} - -static int volume_set_noise_gate_threshold(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->ng_threshold=*(float*)arg; - return 0; -} - -static int volume_set_noise_gate_floorgain(MSFilter *f, void *arg){ - Volume *v=(Volume*)f->data; - v->ng_floorgain=*(float*)arg; - return 0; -} - -static inline int16_t saturate(float val){ - return (val>32767) ? 32767 : ( (val<-32767) ? -32767 : val); -} - -static float update_energy(int16_t *signal, int numsamples, float last_energy_value){ - int i; - float en=last_energy_value; - for (i=0;itarget_gain; - - if (gain==1 && v->gain==1) return; - v->gain=(v->gain*(1-v->gain_k)) + (v->gain_k*gain); - for ( sample=(int16_t*)m->b_rptr; - sample<(int16_t*)m->b_wptr; - ++sample){ - float s=*sample; - *sample=saturate(s*v->gain); - } -} - -static void volume_preprocess(MSFilter *f){ - Volume *v=(Volume*)f->data; - /*process agc by chunks of 10 ms*/ - v->nsamples=(int)(0.01*(float)v->sample_rate); - if (v->agc_enabled){ - ms_message("AGC is enabled."); -#ifdef HAVE_SPEEXDSP - if (v->speex_pp==NULL){ - int tmp=1; - v->speex_pp=speex_preprocess_state_init(v->nsamples,v->sample_rate); - if (speex_preprocess_ctl(v->speex_pp,SPEEX_PREPROCESS_SET_AGC,&tmp)==-1){ - ms_warning("Speex AGC is not available."); - } - tmp=0; - speex_preprocess_ctl(v->speex_pp,SPEEX_PREPROCESS_SET_VAD,&tmp); - speex_preprocess_ctl(v->speex_pp,SPEEX_PREPROCESS_SET_DENOISE,&tmp); - speex_preprocess_ctl(v->speex_pp,SPEEX_PREPROCESS_SET_DEREVERB,&tmp); - } -#else - ms_error("No AGC possible, mediastreamer2 was compiled without libspeexdsp."); -#endif - } -} - - - -static void volume_process(MSFilter *f){ - mblk_t *m; - Volume *v=(Volume*)f->data; - float en=v->energy; - - if (v->agc_enabled){ - mblk_t *om; - int nbytes=v->nsamples*2; - ms_bufferizer_put_from_queue(v->buffer,f->inputs[0]); - while(ms_bufferizer_get_avail(v->buffer)>=nbytes){ - om=allocb(nbytes,0); - ms_bufferizer_read(v->buffer,om->b_wptr,nbytes); - om->b_wptr+=nbytes; - en=update_energy((int16_t*)om->b_rptr,v->nsamples,en); - volume_agc_process(v,om); - - if (v->peer){ - volume_echo_avoider_process(v,f->ticker->time); - }else v->target_gain=v->static_gain; - - if (v->noise_gate_enabled) - volume_noise_gate_process(v,en,om); - apply_gain(v,om); - ms_queue_put(f->outputs[0],om); - } - }else{ - /*light processing: no agc. Work in place in the input buffer*/ - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - en=update_energy((int16_t*)m->b_rptr,(m->b_wptr-m->b_rptr)/2,en); - if (v->peer){ - volume_echo_avoider_process(v,f->ticker->time); - }else v->target_gain=v->static_gain; - - if (v->noise_gate_enabled) - volume_noise_gate_process(v,en,m); - apply_gain(v,m); - ms_queue_put(f->outputs[0],m); - } - } - v->energy=en; -} - -static MSFilterMethod methods[]={ - { MS_VOLUME_GET , volume_get }, - { MS_VOLUME_GET_LINEAR , volume_get_linear }, - { MS_VOLUME_SET_GAIN , volume_set_gain }, - { MS_VOLUME_GET_EA_STATE , volume_get_ea_state }, - { MS_VOLUME_SET_PEER , volume_set_peer }, - { MS_VOLUME_SET_EA_THRESHOLD , volume_set_ea_threshold }, - { MS_VOLUME_SET_EA_SPEED , volume_set_ea_speed }, - { MS_VOLUME_SET_EA_FORCE , volume_set_ea_force }, - { MS_VOLUME_SET_EA_SUSTAIN, volume_set_ea_sustain }, - { MS_FILTER_SET_SAMPLE_RATE, volume_set_sample_rate }, - { MS_VOLUME_ENABLE_AGC , volume_set_agc }, - { MS_VOLUME_ENABLE_NOISE_GATE, volume_enable_noise_gate}, - { MS_VOLUME_SET_NOISE_GATE_THRESHOLD, volume_set_noise_gate_threshold}, - { MS_VOLUME_SET_NOISE_GATE_FLOORGAIN, volume_set_noise_gate_floorgain}, - { 0 , NULL } -}; - -#ifndef _MSC_VER -MSFilterDesc ms_volume_desc={ - .name="MSVolume", - .text=N_("A filter that controls and measure sound volume"), - .id=MS_VOLUME_ID, - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=1, - .init=volume_init, - .uninit=volume_uninit, - .preprocess=volume_preprocess, - .process=volume_process, - .methods=methods -}; -#else -MSFilterDesc ms_volume_desc={ - MS_VOLUME_ID, - "MSVolume", - N_("A filter that controls and measure sound volume"), - MS_FILTER_OTHER, - NULL, - 1, - 1, - volume_init, - volume_preprocess, - volume_process, - NULL, - volume_uninit, - methods -}; -#endif - -MS_FILTER_DESC_EXPORT(ms_volume_desc) - - diff --git a/linphone/mediastreamer2/src/mswebcam.c b/linphone/mediastreamer2/src/mswebcam.c deleted file mode 100644 index fa360ec4e..000000000 --- a/linphone/mediastreamer2/src/mswebcam.c +++ /dev/null @@ -1,137 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mswebcam.h" -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msfilter.h" - -static MSWebCamManager *scm=NULL; - -static MSWebCamManager * create_manager(){ - MSWebCamManager *obj=(MSWebCamManager *)ms_new(MSWebCamManager,1); - obj->cams=NULL; - obj->descs=NULL; - return obj; -} - -void ms_web_cam_manager_destroy(void){ - if (scm!=NULL){ - ms_list_for_each(scm->cams,(void (*)(void*))ms_web_cam_destroy); - ms_list_free(scm->cams); - ms_list_free(scm->descs); - } - ms_free(scm); - scm=NULL; -} - -MSWebCamManager * ms_web_cam_manager_get(void){ - if (scm==NULL) scm=create_manager(); - return scm; -} - -MSWebCam * ms_web_cam_manager_get_cam(MSWebCamManager *m, const char *id){ - MSList *elem; - for (elem=m->cams;elem!=NULL;elem=elem->next){ - MSWebCam *cam=(MSWebCam*)elem->data; - if (id==NULL) return cam; - if (strcmp(ms_web_cam_get_string_id(cam),id)==0) return cam; - } - if (id!=NULL) ms_warning("no camera with id %s",id); - return NULL; -} - -MSWebCam * ms_web_cam_manager_get_default_cam(MSWebCamManager *m){ - if (m->cams!=NULL) - return (MSWebCam*)m->cams->data; - return NULL; -} - -const MSList * ms_web_cam_manager_get_list(MSWebCamManager *m){ - return m->cams; -} - -void ms_web_cam_manager_add_cam(MSWebCamManager *m, MSWebCam *c){ - ms_message("Webcam %s added",ms_web_cam_get_string_id(c)); - m->cams=ms_list_append(m->cams,c); -} - -void ms_web_cam_manager_prepend_cam(MSWebCamManager *m, MSWebCam *c){ - ms_message("Webcam %s prepended",ms_web_cam_get_string_id(c)); - m->cams=ms_list_prepend(m->cams,c); -} - -static void cam_detect(MSWebCamManager *m, MSWebCamDesc *desc){ - if (desc->detect!=NULL) - desc->detect(m); -} - -void ms_web_cam_manager_register_desc(MSWebCamManager *m, MSWebCamDesc *desc){ - m->descs=ms_list_append(m->descs,desc); - cam_detect(m,desc); -} - -void ms_web_cam_manager_reload(MSWebCamManager *m){ - MSList *elem; - ms_list_for_each(m->cams,(void (*)(void*))ms_web_cam_destroy); - ms_list_free(m->cams); - m->cams=NULL; - for(elem=m->descs;elem!=NULL;elem=elem->next) - cam_detect(m,(MSWebCamDesc*)elem->data); -} - -MSWebCam * ms_web_cam_new(MSWebCamDesc *desc){ - MSWebCam *obj=(MSWebCam *)ms_new(MSWebCam,1); - obj->desc=desc; - obj->name=NULL; - obj->data=NULL; - obj->id=NULL; - if (desc->init!=NULL) - desc->init(obj); - return obj; -} - -const char *ms_web_cam_get_driver_type(const MSWebCam *obj){ - return obj->desc->driver_type; -} - -const char *ms_web_cam_get_name(const MSWebCam *obj){ - return obj->name; -} - -const char *ms_web_cam_get_string_id(MSWebCam *obj){ - if (obj->id==NULL) obj->id=ms_strdup_printf("%s: %s",obj->desc->driver_type,obj->name); - return obj->id; -} - -struct _MSFilter * ms_web_cam_create_reader(MSWebCam *obj){ - if (obj->desc->create_reader!=NULL) - return obj->desc->create_reader(obj); - else ms_warning("ms_web_cam_create_reader: unimplemented by %s wrapper",obj->desc->driver_type); - return NULL; -} - -void ms_web_cam_destroy(MSWebCam *obj){ - if (obj->desc->uninit!=NULL) obj->desc->uninit(obj); - if (obj->name!=NULL) ms_free(obj->name); - if (obj->id!=NULL) ms_free(obj->id); - ms_free(obj); -} diff --git a/linphone/mediastreamer2/src/mtu.c b/linphone/mediastreamer2/src/mtu.c deleted file mode 100644 index baf242cfa..000000000 --- a/linphone/mediastreamer2/src/mtu.c +++ /dev/null @@ -1,249 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -/* mtu.c : discover the mtu automatically */ - -#include "mediastreamer2/mscommon.h" - - -#if defined(WIN32) && !defined(_WIN32_WCE) - -HINSTANCE m_IcmpInst = NULL; - -typedef struct ip_option_information { - UCHAR Ttl; - UCHAR Tos; - UCHAR Flags; - UCHAR OptionsSize; - PUCHAR OptionsData; -} IP_OPTION_INFORMATION, * PIP_OPTION_INFORMATION; - -typedef BOOL (WINAPI *ICMPCLOSEHANDLE)(HANDLE IcmpHandle); -typedef HANDLE (WINAPI *ICMPCREATEFILE)(VOID); -typedef DWORD (WINAPI *ICMPSENDECHO)(HANDLE IcmpHandle,ULONG DestinationAddress, LPVOID RequestData, WORD RequestSize, PIP_OPTION_INFORMATION RequestOptions, LPVOID ReplyBuffer, DWORD ReplySize, DWORD Timeout); - -ICMPCLOSEHANDLE pIcmpCloseHandle = NULL; -ICMPCREATEFILE pIcmpCreateFile = NULL; -ICMPSENDECHO pIcmpSendEcho = NULL; - -#define IP_FLAG_DF 0x2 // Don't fragment this packet. -#define IP_OPT_ROUTER_ALERT 0x94 // Router Alert Option - -#define IP_STATUS_BASE 11000 -#define IP_PACKET_TOO_BIG (IP_STATUS_BASE + 9) -#define IP_REQ_TIMED_OUT (IP_STATUS_BASE + 10) - -static int mtus[] = { - 1500, // Ethernet, Point-to-Point (default) - 1492, // IEEE 802.3 - 1006, // SLIP, ARPANET - 576, // X.25 Networks - 544, // DEC IP Portal - 512, // NETBIOS - 508, // IEEE 802/Source-Rt Bridge, ARCNET - 296, // Point-to-Point (low delay) - 68, // Official minimum - 0 -}; - -int ms_discover_mtu(const char *host) -{ - int i; - - struct addrinfo hints,*ai=NULL; - char port[10]; - char ipaddr[INET6_ADDRSTRLEN]; - int err; - - HANDLE hIcmp; - unsigned long target_addr; - - struct ip_option_information ip_opts; - unsigned char reply_buffer[10000]; - - if (!m_IcmpInst) - { - m_IcmpInst = LoadLibrary("icmp.dll"); - if (m_IcmpInst) - { - pIcmpCloseHandle = (ICMPCLOSEHANDLE)GetProcAddress(m_IcmpInst, "IcmpCloseHandle"); - pIcmpCreateFile = (ICMPCREATEFILE) GetProcAddress(m_IcmpInst, "IcmpCreateFile"); - pIcmpSendEcho = (ICMPSENDECHO) GetProcAddress(m_IcmpInst, "IcmpSendEcho"); - } - } - - hIcmp = pIcmpCreateFile(); - - memset(&hints,0,sizeof(hints)); - hints.ai_family = PF_INET; - hints.ai_socktype = SOCK_DGRAM; - - snprintf(port,sizeof(port),"0"); - err=getaddrinfo(host,port,&hints,&ai); - if (err!=0){ - pIcmpCloseHandle( hIcmp ); - ms_error("getaddrinfo(): error\n"); - return -1; - } - getnameinfo (ai->ai_addr, ai->ai_addrlen, ipaddr, sizeof (ipaddr), port, - sizeof (port), NI_NUMERICHOST | NI_NUMERICSERV); - freeaddrinfo(ai); - - target_addr=inet_addr(ipaddr); - - - /* Prepare the IP options */ - memset(&ip_opts,0,sizeof(ip_opts)); - ip_opts.Ttl=30; - ip_opts.Flags = IP_FLAG_DF | IP_OPT_ROUTER_ALERT; - - - // ignore icmpbuff data contents - for (i=0;mtus[i]!=0;i++) - { - char icmpbuff[2048]; - char *icmp_data = icmpbuff; - - int status = -1; - if (pIcmpSendEcho) - status=pIcmpSendEcho(hIcmp, - target_addr, - (LPVOID)icmp_data, - mtus[i]-60, /* icmp_data_size */ - &ip_opts, - reply_buffer, - sizeof(reply_buffer), - 3000L); // 3 seconds - if (status || GetLastError() == IP_REQ_TIMED_OUT) - { - pIcmpCloseHandle( hIcmp ); - return mtus[i]; - } - } - - pIcmpCloseHandle( hIcmp ); - - return -1; -} - -#elif defined(__linux) - -#include -#include -#include -#include -#include -#include -#include - -#ifndef IP_MTU -#define IP_MTU 14 -#endif - -int ms_discover_mtu(const char *host){ - int sock; - int err,mtu=0,new_mtu; - socklen_t optlen; - char buf[1500-28]={0}; - char port[10]; - struct addrinfo hints,*ai=NULL; - int rand_port; - int retry=0; - struct timeval tv; - - memset(&hints,0,sizeof(hints)); - hints.ai_family = PF_INET; - hints.ai_socktype = SOCK_DGRAM; - - gettimeofday(&tv,NULL); - srandom(tv.tv_usec); - rand_port=random() & 0xFFFF; - if (rand_port<1000) rand_port+=1000; - snprintf(port,sizeof(port),"%i",rand_port); - err=getaddrinfo(host,port,&hints,&ai); - if (err!=0){ - ms_error("getaddrinfo(): %s\n",gai_strerror(err)); - return -1; - } - sock=socket(PF_INET,SOCK_DGRAM,0); - - mtu=IP_PMTUDISC_DO; - optlen=sizeof(mtu); - err=setsockopt(sock,IPPROTO_IP,IP_MTU_DISCOVER,&mtu,optlen); - if (err!=0){ - ms_error("setsockopt(): %s",strerror(errno)); - err = close(sock); - if (err!=0) - ms_error("close(): %s", strerror(errno)); - return -1; - } - err=connect(sock,ai->ai_addr,ai->ai_addrlen); - freeaddrinfo(ai); - if (err!=0){ - ms_error("connect(): %s",strerror(errno)); - err = close(sock); - if (err !=0) - ms_error("close(): %s", strerror(errno)); - return -1; - } - mtu=sizeof(buf); - do{ - send(sock,buf,mtu,0); - usleep(500000);/*wait for an icmp message come back */ - err=getsockopt(sock,IPPROTO_IP,IP_MTU,&new_mtu,&optlen); - if (err!=0){ - ms_error("getsockopt(): %s",strerror(errno)); - err = close(sock); - if (err!=0) - ms_error("close(): %s", strerror(errno)); - return -1; - }else{ - ms_message("Partial MTU discovered : %i",new_mtu); - if (new_mtu==mtu) break; - else mtu=new_mtu; - } - retry++; - }while(retry<10); - - ms_message("mtu to %s is %i",host,mtu); - - err = close(sock); - if (err!=0) - ms_error("close() %s", strerror(errno)); - return mtu; -} - -#else - -int ms_discover_mtu(const char*host){ - ms_warning("mtu discovery not implemented."); - return -1; -} - -#endif - - -void ms_set_mtu(int mtu){ - /*60= IPv6+UDP+RTP overhead */ - if (mtu>60){ - if (mtu>1500) mtu=1500;/*limit to 1500, the mediastreamer2 buffer are not large enough anyway*/ - ms_set_payload_max_size(mtu-60); - }else ms_set_payload_max_size(0); -} diff --git a/linphone/mediastreamer2/src/nowebcam.c b/linphone/mediastreamer2/src/nowebcam.c deleted file mode 100644 index 4241dc1f9..000000000 --- a/linphone/mediastreamer2/src/nowebcam.c +++ /dev/null @@ -1,1827 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/mscommon.h" -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/mswebcam.h" - -#include "ffmpeg-priv.h" - -#include - -#ifdef WIN32 -#include -#include -#include -#include -#include -#endif - -static mblk_t *jpeg2yuv(uint8_t *jpgbuf, int bufsize, MSVideoSize *reqsize){ - AVCodecContext av_context; - int got_picture=0; - AVFrame orig; - AVPicture dest; - mblk_t *ret; - struct SwsContext *sws_ctx; - AVPacket pkt; - - avcodec_get_context_defaults(&av_context); - if (avcodec_open(&av_context,avcodec_find_decoder(CODEC_ID_MJPEG))<0){ - ms_error("jpeg2yuv: avcodec_open failed"); - return NULL; - } - av_init_packet(&pkt); - pkt.data=jpgbuf; - pkt.size=bufsize; - if (avcodec_decode_video2(&av_context,&orig,&got_picture,&pkt)<0){ - ms_error("jpeg2yuv: avcodec_decode_video failed"); - avcodec_close(&av_context); - return NULL; - } - ret=allocb(avpicture_get_size(PIX_FMT_YUV420P,reqsize->width,reqsize->height),0); - ret->b_wptr=ret->b_datap->db_lim; - avpicture_fill(&dest,ret->b_rptr,PIX_FMT_YUV420P,reqsize->width,reqsize->height); - - sws_ctx=sws_getContext(av_context.width,av_context.height,av_context.pix_fmt, - reqsize->width,reqsize->height,PIX_FMT_YUV420P,SWS_FAST_BILINEAR, - NULL, NULL, NULL); - if (sws_ctx==NULL) { - ms_error("jpeg2yuv: sws_getContext() failed."); - avcodec_close(&av_context); - freemsg(ret); - return NULL; - } - if (sws_scale(sws_ctx,orig.data,orig.linesize,0,av_context.height,dest.data,dest.linesize)<0){ - ms_error("jpeg2yuv: sws_scale() failed."); - sws_freeContext(sws_ctx); - avcodec_close(&av_context); - freemsg(ret); - return NULL; - } - sws_freeContext(sws_ctx); - avcodec_close(&av_context); - return ret; -} - -#ifndef MS2_MINIMAL_SIZE -unsigned char def_mire[] = /* 22092 */ -{0xFF,0xD8,0xFF,0xE0,0x00,0x10,0x4A,0x46,0x49,0x46,0x00,0x01,0x01,0x01,0x00 -,0x59,0x00,0x59,0x00,0x00,0xFF,0xDB,0x00,0x43,0x00,0x05,0x03,0x04,0x04,0x04 -,0x03,0x05,0x04,0x04,0x04,0x05,0x05,0x05,0x06,0x07,0x0C,0x08,0x07,0x07,0x07 -,0x07,0x0F,0x0B,0x0B,0x09,0x0C,0x11,0x0F,0x12,0x12,0x11,0x0F,0x11,0x11,0x13 -,0x16,0x1C,0x17,0x13,0x14,0x1A,0x15,0x11,0x11,0x18,0x21,0x18,0x1A,0x1D,0x1D -,0x1F,0x1F,0x1F,0x13,0x17,0x22,0x24,0x22,0x1E,0x24,0x1C,0x1E,0x1F,0x1E,0xFF -,0xDB,0x00,0x43,0x01,0x05,0x05,0x05,0x07,0x06,0x07,0x0E,0x08,0x08,0x0E,0x1E -,0x14,0x11,0x14,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E -,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E -,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E -,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0xFF,0xC0,0x00,0x11,0x08,0x01,0x20 -,0x01,0x60,0x03,0x01,0x22,0x00,0x02,0x11,0x01,0x03,0x11,0x01,0xFF,0xC4,0x00 -,0x1D,0x00,0x01,0x00,0x02,0x03,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00 -,0x00,0x00,0x00,0x00,0x06,0x07,0x04,0x05,0x08,0x03,0x02,0x01,0x09,0xFF,0xC4 -,0x00,0x4A,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x06,0x03,0x04,0x05 -,0x0A,0x06,0x03,0x00,0x01,0x02,0x03,0x04,0x05,0x11,0x00,0x06,0x12,0x21,0x31 -,0x07,0x13,0x22,0x41,0x14,0x51,0x61,0x08,0x23,0x32,0x52,0x71,0x81,0x15,0x42 -,0x91,0x16,0x33,0x62,0xA1,0x43,0x53,0x72,0x82,0xB1,0x24,0x34,0x44,0x63,0x73 -,0x83,0x92,0xA2,0xC1,0xC2,0x17,0x26,0x45,0xA3,0xD1,0xE1,0x54,0x93,0xA4,0xFF -,0xC4,0x00,0x19,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00 -,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0xFF,0xC4,0x00,0x22 -,0x11,0x01,0x00,0x03,0x00,0x02,0x01,0x04,0x03,0x01,0x00,0x00,0x00,0x00,0x00 -,0x00,0x00,0x00,0x01,0x02,0x11,0x21,0x31,0x03,0x04,0x05,0x12,0x41,0x13,0x51 -,0x71,0xA1,0xFF,0xDA,0x00,0x0C,0x03,0x01,0x00,0x02,0x11,0x03,0x11,0x00,0x3F -,0x00,0xE3,0x2D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D -,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34 -,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D -,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34 -,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3 -,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40 -,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3 -,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D -,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x4D,0x76,0xBF,0x87,0x17,0xDB,0xCC,0xC6 -,0x39,0x20,0xA9,0x86,0x40,0xE6,0x21,0x4B,0x0C,0x1E,0x75,0x49,0x93,0xD6,0x02 -,0x32,0x65,0x56,0x23,0xC9,0x14,0x15,0x95,0xD1,0x8A,0xB8,0x64,0x57,0xED,0xA0 -,0x85,0x69,0xAE,0xB3,0xD9,0x5F,0x65,0xBA,0xFB,0x95,0x3A,0xD6,0x6E,0x2A,0x2B -,0x3E,0xDA,0xB7,0x42,0xAE,0xEA,0x2A,0x66,0xA8,0xAB,0xAC,0x91,0x49,0x2C,0x0C -,0xC5,0x64,0x86,0x35,0xC0,0x20,0x65,0x55,0x0E,0x17,0xAA,0xE7,0x2C,0x6A,0x9D -,0xF5,0xE1,0x85,0xBA,0x1B,0xED,0x6D,0xB3,0x65,0x54,0x7F,0x69,0xBE,0xF0,0xB8 -,0xB9,0x50,0xCC,0x60,0xB7,0xD3,0xFA,0x8E,0x61,0x51,0x20,0x73,0x26,0x06,0x00 -,0x65,0x99,0xF1,0xEF,0x93,0x9D,0x05,0x45,0xA6,0xA7,0x56,0xEF,0x0D,0xAE,0x95 -,0xD7,0xC9,0xAD,0xD4,0xD2,0xC9,0x53,0xC3,0x80,0x54,0xA6,0xA7,0xE7,0x3F,0x27 -,0x56,0x2A,0x8E,0x85,0x82,0x46,0xC1,0x94,0x2B,0x2B,0xB8,0x27,0x3C,0xA3,0xF3 -,0x57,0x04,0xDC,0x16,0xEF,0xB2,0xAE,0xE4,0x9E,0xDF,0x15,0x6D,0x4D,0x9A,0xB6 -,0x01,0xE5,0xAB,0x4B,0x1F,0xF1,0x54,0x2D,0x8C,0x75,0x25,0x7E,0x1F,0xCC,0x5E -,0xB9,0xF4,0xF9,0x6C,0x7F,0xDA,0xD0,0x73,0x2E,0x9A,0xB9,0xF7,0x77,0x80,0x1B -,0x96,0xC9,0x4F,0x5D,0x50,0x12,0x5E,0x4B,0x21,0x34,0xB0,0x33,0x46,0xAB,0xE5 -,0x96,0xE8,0x1D,0xE7,0x68,0x25,0x24,0x2E,0x7A,0xAC,0x1D,0x48,0xEC,0xB9,0xE9 -,0xA8,0xDA,0x9E,0x0D,0xEE,0x3B,0xD7,0x04,0x16,0xCB,0xD4,0xB5,0x2B,0x52,0x04 -,0xA9,0x4F,0x42,0x5E,0x9F,0xC8,0xE9,0xEA,0xF3,0x50,0xBC,0x81,0x8F,0xA8,0x60 -,0x40,0xE0,0x60,0x1C,0x9C,0x90,0x02,0xAF,0xD3,0x5D,0xE7,0xE1,0x2F,0xD9,0x89 -,0x6D,0x96,0x23,0x25,0xD6,0xAE,0x4A,0x3A,0xCA,0x88,0x84,0x72,0xAC,0x66,0x48 -,0x54,0xA9,0x09,0xC8,0x37,0x95,0x22,0xCB,0x20,0x62,0x8A,0xD8,0x79,0x15,0x03 -,0x03,0xF7,0x23,0x52,0x4B,0x67,0xD9,0x73,0x69,0xDB,0x9E,0xA6,0x58,0xAB,0x26 -,0x92,0x49,0xA4,0x67,0x0F,0x14,0x92,0xD3,0xCA,0x80,0x9C,0xF1,0x59,0x43,0xB9 -,0x50,0x3E,0x8B,0x9F,0x99,0xD0,0x7F,0x3A,0x34,0xD7,0x73,0x6F,0xCF,0xB2,0xD5 -,0x75,0xC9,0x6B,0x27,0xA7,0xBC,0xC9,0x53,0x51,0x53,0xC3,0x9B,0xD4,0xD3,0xA5 -,0x64,0x8C,0xA9,0xC7,0x88,0x6A,0x99,0x9C,0x4E,0x30,0x11,0x57,0xEE,0xF1,0xE9 -,0x18,0xED,0xD3,0x55,0x65,0xF7,0xEC,0xED,0x57,0x6F,0x90,0xCF,0x74,0xA3,0xB4 -,0x22,0x45,0x10,0x48,0xA9,0xE8,0x6E,0x73,0x5A,0xBE,0x24,0x82,0x49,0x66,0x92 -,0xE3,0x1B,0x0E,0x67,0x38,0xC2,0x12,0xB8,0x51,0xD3,0x39,0x24,0x39,0xB3,0x4D -,0x5A,0x97,0x3F,0x03,0x37,0xD5,0xB2,0xCA,0xF5,0x55,0x7B,0x63,0x74,0xBD,0x56 -,0x14,0xC5,0xF0,0x56,0xA4,0xAC,0xA4,0x61,0xC8,0x72,0x2D,0x3C,0x13,0x39,0x00 -,0x0C,0x9C,0x84,0x6C,0x90,0x07,0x4C,0xE4,0x44,0xF7,0xB6,0xC3,0xDC,0x7B,0x41 -,0x61,0x7B,0xC5,0x05,0x4C,0x29,0x22,0xA9,0xE5,0x2D,0x1D,0x45,0x3F,0x16,0x39 -,0xF4,0x71,0x9E,0x34,0x66,0x20,0x00,0x4B,0x28,0x65,0x1C,0xD7,0xD5,0x93,0x8D -,0x04,0x5F,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD3,0x4D -,0x03,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03 -,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D -,0x34,0xD0,0x34,0xD6,0xCE,0xC3,0x61,0xBB,0xDF,0x65,0x68,0xED,0x74,0x4F,0x38 -,0x56,0x0A,0xF2,0x33,0x2C,0x71,0xAB,0x15,0x66,0x55,0x2E,0xC4,0x28,0x66,0x08 -,0xC1,0x54,0x9C,0xB1,0x18,0x50,0x4F,0x4D,0x5C,0x3E,0x1D,0x7D,0x9E,0xF7,0x25 -,0xE2,0xE6,0x45,0x5D,0x11,0xA9,0x58,0x64,0x19,0x8C,0xAB,0xC5,0x1F,0x42,0x8D -,0xF7,0x81,0xB8,0x48,0x32,0x39,0x83,0x1B,0xF9,0x0D,0x8C,0x32,0x39,0xED,0xA0 -,0xA4,0x68,0xE9,0x2A,0xAB,0x6A,0x05,0x3D,0x1D,0x34,0xD5,0x33,0x15,0x66,0x11 -,0xC4,0x85,0xDB,0x8A,0xA9,0x66,0x38,0x1D,0x70,0x14,0x12,0x7E,0x40,0x13,0xAB -,0x1F,0x65,0xF8,0x39,0xB8,0xEF,0xF7,0x1A,0x58,0x63,0x8D,0x6A,0xD6,0x41,0xCA -,0x48,0xE8,0x9C,0xBE,0x00,0x93,0x8E,0x3C,0xD0,0xAC,0x85,0x59,0x41,0x22,0x58 -,0x84,0xCA,0xB9,0x5E,0x58,0xEB,0x8E,0xA3,0xA0,0xF0,0x87,0xC3,0x8F,0x0E,0xE8 -,0x21,0xB9,0xF8,0x87,0x79,0xB7,0xC4,0x59,0x63,0x48,0xE8,0xE0,0x41,0x1A,0xCC -,0xD1,0x82,0x10,0x2A,0x22,0x87,0x99,0xC6,0x72,0x1C,0x2F,0x9B,0x92,0x72,0xED -,0x92,0x4E,0x45,0xCB,0xC5,0x4B,0x9B,0x52,0xB5,0xBB,0xC3,0xBD,0xB5,0x4D,0xB6 -,0xED,0xEC,0x72,0x6E,0x17,0x18,0x41,0x9E,0x43,0x8F,0xC6,0xB4,0xEA,0x7B,0x9F -,0xCD,0x2B,0x67,0xE6,0x9A,0x26,0xB4,0x3B,0x5F,0xC0,0x3D,0xB3,0xB3,0xEC,0x70 -,0xDE,0x37,0xED,0xCE,0xD5,0x63,0xA2,0xA6,0xF5,0x33,0xB1,0x44,0x90,0xB3,0x46 -,0x11,0xB9,0x48,0xC5,0x89,0x2C,0x01,0xCA,0x73,0x92,0x26,0xE4,0xD8,0x89,0x39 -,0x11,0xA9,0x0A,0x78,0x93,0x64,0xB2,0x53,0x0A,0x0F,0x0B,0x36,0x7C,0x7C,0x11 -,0x3C,0xB5,0xBA,0xDD,0x23,0x68,0x21,0x0B,0x9E,0xD1,0xC7,0xD2,0x57,0x5F,0x70 -,0xB8,0x89,0x3E,0x47,0x55,0xFD,0x54,0x51,0x55,0x5E,0x96,0xE3,0x7D,0xB9,0x55 -,0xDE,0xEF,0x03,0xAA,0xD5,0x57,0xC9,0xE6,0xBC,0x40,0xE7,0xAA,0x28,0x1C,0x21 -,0x5E,0xFF,0x00,0x85,0x54,0x6B,0x16,0xDF,0xB8,0x26,0xBB,0xD5,0x79,0x1B,0x7B -,0x6F,0xDD,0xEF,0x0A,0x7F,0x0C,0xF1,0x24,0x71,0x42,0xFD,0xFA,0xAB,0xCA,0xE8 -,0x18,0x74,0x3D,0x46,0x41,0xF6,0x3A,0xA3,0x6B,0xB9,0x2B,0x6E,0x7B,0x82,0x41 -,0x2E,0xF2,0xBE,0xD5,0x5E,0x8B,0x1E,0x49,0x46,0xC3,0x85,0x28,0x23,0xF2,0x53 -,0x27,0xA5,0xB1,0xF3,0x6E,0x6C,0x3E,0x7A,0xFC,0x8F,0xCE,0x70,0x15,0x63,0x14 -,0xF1,0x81,0x80,0x0E,0x0B,0x63,0xF4,0x1D,0x07,0xB7,0xCF,0xF4,0x1A,0xC3,0xB8 -,0xD6,0xD6,0xD9,0x6A,0x24,0xFE,0x37,0xB7,0x2E,0x36,0xE8,0x55,0x62,0x69,0xAA -,0xC9,0x8A,0x58,0x93,0xCC,0x62,0x89,0xCD,0x91,0xC9,0x1E,0xA0,0x47,0x6C,0x0E -,0x99,0xC0,0x23,0x59,0x95,0x43,0xD2,0x5A,0x6A,0x8F,0x26,0x11,0xDF,0x07,0x8E -,0x7D,0xBA,0xB7,0xB7,0xB7,0x6C,0x1F,0xAE,0x83,0x15,0xA9,0x8D,0x0D,0xC6,0x7B -,0x9D,0x8E,0xE3,0x5F,0x67,0xBE,0x4B,0x01,0x84,0xD6,0xDB,0xE5,0xE1,0x3B,0x21 -,0xC7,0xA5,0xBD,0x8A,0xE5,0x47,0xE2,0xE8,0x30,0x31,0x83,0x83,0xA9,0x7E,0xCC -,0xF1,0x2F,0xC4,0x8D,0xB7,0x6F,0x68,0x2A,0x2A,0x36,0xA5,0x64,0x5C,0x8B,0xC9 -,0x23,0xDB,0x24,0x8A,0x69,0x4F,0xE7,0x92,0x45,0x9B,0x05,0x88,0x03,0x2C,0x54 -,0x9F,0xA9,0xD4,0x5E,0x36,0x72,0x85,0x28,0xE9,0xC4,0x4A,0x72,0x7C,0xC9,0x14 -,0x81,0x9E,0xBD,0x78,0xF7,0x27,0x3D,0xF3,0x8C,0xFC,0xF5,0xAF,0xB8,0xDC,0x6D -,0x74,0x35,0x4B,0x0D,0x54,0xD2,0x57,0x57,0xFE,0x38,0xE9,0x62,0x43,0x2C,0x83 -,0xAF,0x42,0x23,0x5F,0xC2,0x3D,0xB9,0x9C,0x7D,0x5B,0x41,0x6F,0x51,0xF8,0xFD -,0xBC,0x0B,0xE2,0x4D,0x8F,0x63,0xAA,0x8F,0xFD,0x72,0x5E,0xA5,0x84,0x1F,0xD0 -,0x1A,0x76,0xFF,0x00,0x89,0x1F,0x5D,0x6B,0x77,0x87,0xDA,0x53,0x73,0xDA,0x95 -,0x63,0xA4,0xD9,0xB6,0x01,0x55,0x2E,0x7E,0x1E,0x9D,0xAF,0x33,0x4F,0x34,0xC7 -,0xFC,0x31,0xA5,0x3A,0x9F,0xDF,0x38,0x1E,0xE4,0x6A,0xB5,0x96,0x2B,0xBD,0xD6 -,0x03,0x1C,0x93,0xC9,0x64,0x8D,0xC7,0x41,0x09,0x59,0x2A,0x40,0x23,0x23,0x2D -,0x86,0x44,0xEC,0xC3,0xA7,0x2F,0x6C,0x30,0x3D,0x35,0xE1,0x6A,0xA6,0xA1,0xB4 -,0x5C,0x3F,0x86,0x5A,0x68,0x1E,0xE7,0x77,0xA8,0x19,0xF2,0x29,0x11,0xA7,0xAE -,0xA8,0x3E,0xC5,0xF2,0x49,0x23,0xFC,0x6E,0xC1,0x47,0xD3,0x4C,0x16,0xE6,0xCF -,0xF1,0xF7,0x7C,0x08,0x5E,0xA3,0x77,0xEC,0x7B,0x61,0x8D,0x90,0x32,0x43,0x6A -,0xAF,0x3F,0x10,0x87,0xF2,0x95,0x93,0xD0,0xDF,0xFF,0x00,0x60,0xFD,0xF5,0x38 -,0xDB,0x9F,0x68,0x6F,0x0A,0xEE,0x91,0xBC,0x77,0x0D,0xC0,0x36,0xE5,0x7C,0x47 -,0x13,0xD0,0xDE,0x93,0xE1,0xA5,0x88,0xFB,0x64,0xE4,0xA1,0x04,0x10,0x41,0x56 -,0x3D,0xF5,0x00,0xDA,0x7E,0x0E,0xEE,0x7B,0xD2,0xA5,0x4E,0xEF,0xB8,0xAD,0x82 -,0x8D,0xBA,0xFF,0x00,0x0E,0xB7,0x48,0x24,0xAA,0x61,0xF2,0x92,0x72,0x38,0xA7 -,0xD4,0x46,0x09,0xF9,0x3E,0xAD,0xED,0xB1,0xB2,0xB6,0xA6,0xDA,0xB3,0xC9,0x69 -,0xB2,0xD8,0x68,0xA9,0xA9,0x26,0xEB,0x50,0xA6,0x3E,0x6D,0x50,0x7D,0xDA,0x56 -,0x6C,0xB4,0x87,0xEA,0xC4,0x9D,0x43,0x5A,0xE9,0xBC,0x69,0xF0,0xD6,0xA2,0x75 -,0xA7,0xA1,0xF1,0x13,0x68,0xC2,0x0B,0x61,0xA7,0xA8,0xB8,0xC7,0xC7,0xB8,0xE8 -,0x17,0x90,0x07,0x23,0x23,0x25,0x86,0x0E,0x0E,0x1B,0x53,0x8B,0x05,0xC2,0xD9 -,0x74,0xB7,0xAD,0x4D,0xAE,0xEF,0x4F,0x77,0x81,0xBB,0xD4,0x43,0x3A,0x4A,0xAF -,0xFB,0xA7,0xA7,0xFA,0x63,0x5A,0xC8,0xAD,0x56,0xB8,0xAD,0xE6,0xDD,0x15,0xB6 -,0x8D,0x28,0x8F,0x43,0x4E,0xB0,0x28,0x8C,0xFF,0x00,0xBB,0x8C,0x6A,0x23,0x5D -,0xE1,0x2F,0x86,0xD2,0x55,0x49,0x71,0x4D,0xAD,0x43,0x6C,0xA9,0xC1,0x2F,0x53 -,0x6D,0x77,0xA0,0x71,0xEE,0x4F,0x28,0x19,0x0F,0xEF,0xA1,0xAD,0xE5,0xF2,0xD5 -,0xB3,0x85,0xC2,0x4A,0x7A,0x1D,0xB8,0xB5,0x37,0x92,0x73,0x27,0xF0,0x85,0xF8 -,0x69,0xD3,0x23,0x20,0xC9,0x3C,0x65,0x3C,0xBE,0x9D,0x47,0x27,0x04,0xFF,0x00 -,0x28,0x3A,0x8E,0x78,0x8D,0xE0,0xE5,0xAF,0x78,0xD8,0xA9,0x21,0xBC,0x6E,0x9B -,0xF5,0xB9,0x68,0xA5,0xF8,0x88,0x91,0xAB,0x52,0xB2,0x18,0xA4,0x2A,0xC8,0x43 -,0x35,0x4C,0x6C,0xF2,0x21,0x57,0x2A,0x55,0x9B,0x0C,0x0F,0x50,0x75,0x85,0x49 -,0x68,0xDE,0xBB,0x01,0xCD,0x46,0xC5,0xA9,0x6D,0xC7,0xB6,0x90,0x97,0x9A,0xC1 -,0x72,0x6C,0x54,0x82,0x58,0x97,0x7A,0x6A,0xA6,0xF5,0x3B,0x13,0xD7,0x8C,0xD9 -,0x0D,0x93,0x87,0x19,0xE9,0x62,0xED,0x3B,0xC5,0x97,0x75,0x59,0x69,0xF7,0x2D -,0x9F,0x35,0x7C,0xF9,0xAA,0x0A,0x80,0x52,0x4A,0x79,0x14,0x95,0x78,0xD9,0x48 -,0xCC,0x4E,0xA7,0x2A,0xC0,0x0C,0xF4,0xEB,0x9D,0x15,0xCB,0xD7,0xCF,0xB2,0x05 -,0x61,0x6A,0xD9,0xAD,0xB7,0x3D,0xB5,0x73,0x35,0x62,0x46,0xF3,0x6A,0xED,0xF5 -,0x34,0x73,0x42,0xCF,0x9E,0xB1,0xC7,0x0C,0xE2,0x10,0x41,0x39,0x55,0x28,0x10 -,0x60,0x0E,0x38,0xE9,0xAA,0xDF,0xC4,0x2F,0xB2,0xC6,0xE6,0xDB,0x56,0xF8,0xA5 -,0x85,0x84,0xDC,0x41,0x32,0xD5,0x43,0x50,0x6A,0xA3,0x20,0x95,0xEA,0xD1,0x2C -,0x4B,0x2A,0x04,0x51,0x23,0x1F,0x2C,0x54,0x13,0xE9,0xE8,0xA0,0x16,0xD7,0x74 -,0xBD,0x63,0xDC,0x04,0x91,0x53,0x2A,0xDD,0x58,0x16,0x46,0x8E,0x17,0xF2,0xE9 -,0x23,0x61,0xC8,0x15,0x92,0x5E,0xA5,0xF0,0x54,0xA3,0x05,0x0D,0x8E,0x99,0x41 -,0xAC,0xDB,0x52,0xAB,0xC2,0xD4,0xCF,0x34,0x15,0x11,0xA0,0xF2,0xC4,0x74,0xD0 -,0xF0,0x82,0x25,0x04,0x80,0xA3,0xBE,0x58,0x60,0x03,0xD7,0xD8,0x7A,0x57,0x41 -,0xFC,0x84,0xB9,0x50,0xD5,0x5B,0xAB,0xA5,0xA2,0xAC,0x8C,0x47,0x34,0x64,0x64 -,0x06,0x0C,0xA4,0x11,0x90,0xCA,0xCA,0x48,0x65,0x20,0x82,0x18,0x12,0x08,0x20 -,0x82,0x41,0x07,0x58,0xDA,0xEA,0xFF,0x00,0xB6,0xD7,0x86,0x62,0xC5,0x34,0x77 -,0xEA,0x4A,0x28,0x96,0x9A,0xB6,0x79,0x4A,0x4E,0x10,0x2F,0x09,0x95,0x5A,0x57 -,0x50,0x4B,0x80,0x16,0x54,0x2E,0xE4,0x10,0x4F,0x9B,0x03,0x94,0x55,0xF3,0xDB -,0x3C,0xA1,0xA0,0x69,0xA6,0x9A,0x06,0x9A,0x69,0xA0,0x69,0xA6,0x9A,0x06,0x9A -,0x69,0xA0,0x69,0xA6,0x9A,0x06,0x9A,0x69,0xA0,0x69,0xA6,0x9A,0x06,0x9A,0x69 -,0xA0,0x69,0xA6,0xBD,0xA8,0xE9,0xAA,0x6B,0x6B,0x21,0xA3,0xA3,0xA7,0x96,0xA6 -,0xA6,0x79,0x16,0x28,0x61,0x89,0x0B,0xBC,0x8E,0xC7,0x0A,0xAA,0xA3,0xA9,0x24 -,0x90,0x00,0x1D,0xF4,0x1E,0x3A,0x6A,0x6B,0xB3,0x3C,0x38,0xBE,0xEE,0x26,0x32 -,0x34,0x33,0x53,0x53,0x87,0x31,0x16,0x11,0x02,0xC2,0x4F,0x58,0x08,0x4B,0xB2 -,0x46,0x8D,0xC9,0x00,0x2A,0xEE,0xAF,0x86,0x05,0x55,0xFB,0x6B,0xA2,0x3C,0x2C -,0xFB,0x35,0x5D,0x12,0x68,0xEB,0xE7,0x0D,0x6B,0xF5,0x07,0x49,0xE4,0xCF,0x9F -,0x1F,0x54,0x60,0x51,0xDD,0x03,0xAB,0x2B,0xA6,0x41,0x58,0xA1,0x71,0x92,0x04 -,0xC4,0x1D,0x07,0x2F,0xED,0xFD,0xAD,0x72,0xBC,0x3C,0x25,0x4C,0x54,0x71,0x4E -,0x0F,0x91,0x24,0xE1,0xC9,0x9C,0xFA,0xF0,0x22,0x8D,0x15,0xA5,0x97,0x2D,0x19 -,0x42,0x63,0x46,0x0A,0xC4,0x72,0x2A,0x3A,0xEA,0xDF,0xF0,0xBB,0xEC,0xFF,0x00 -,0x7D,0xDC,0xD4,0xB9,0x36,0x67,0xE3,0x3A,0x71,0x7A,0xBA,0xC7,0x2A,0xB0,0x64 -,0x26,0x4A,0x24,0x6C,0x00,0x75,0x60,0xEA,0x4B,0xBB,0x1E,0x2D,0x93,0x00,0x23 -,0x5D,0x49,0x2E,0xCF,0xF0,0xB7,0xC2,0x6B,0x0C,0xB7,0xAD,0xC2,0x69,0xCF,0x9C -,0xDC,0x58,0xCC,0xA5,0x9A,0xB2,0x53,0xD7,0xCB,0x09,0x92,0xF3,0xB1,0x3D,0x40 -,0x91,0xA4,0x23,0xBE,0x40,0xEB,0xA8,0x6E,0xEB,0xF1,0x0B,0x75,0xEE,0x88,0xDA -,0x9E,0x9E,0x69,0xB6,0xBD,0xA0,0xFA,0x52,0x92,0x8E,0x40,0x2A,0x9D,0x3F,0xEB -,0x26,0x5F,0xC1,0x9E,0x9E,0x98,0xB0,0x47,0xE7,0x6D,0x13,0x5B,0x0B,0x36,0xDC -,0xF0,0xDB,0xC2,0x08,0x84,0x17,0xDB,0xEC,0x95,0xD7,0x99,0x23,0x25,0x6D,0xB4 -,0x20,0xBC,0xE5,0x59,0x8B,0x15,0x58,0xE2,0x00,0xA4,0x65,0x99,0xB2,0x14,0x45 -,0x13,0x67,0x2C,0xBE,0xFA,0xC3,0xBD,0xF8,0x9F,0xBB,0xAE,0x94,0xC2,0xDF,0xB6 -,0x6D,0xF4,0xBB,0x2E,0xD0,0xA3,0x8C,0x64,0x24,0x73,0x56,0xF1,0xFF,0x00,0x0A -,0x8C,0xC3,0x0F,0xFF,0x00,0x73,0xF5,0x1A,0x87,0xD0,0x50,0x51,0x5B,0xA2,0x75 -,0xA2,0xA6,0x8E,0x1E,0x67,0x9C,0x84,0x0F,0x54,0x8D,0xEE,0xCC,0xDD,0xD8,0xFD -,0x4E,0x4E,0xA3,0xD4,0xFB,0x86,0x6B,0xBA,0x2D,0x55,0x2C,0x96,0xAA,0x1B,0x6B -,0x4B,0xE5,0x25,0x4D,0xD6,0xE5,0xF0,0x68,0xE4,0xA0,0x90,0x11,0xC5,0x5D,0xB1 -,0xC4,0x83,0xEA,0x29,0xDF,0x04,0x6A,0x8D,0xDA,0x53,0xD2,0x43,0x71,0x96,0xB5 -,0xCD,0x45,0xC6,0xEB,0x28,0xC4,0xD5,0x55,0x12,0xB4,0xF5,0x2F,0xEF,0x86,0x91 -,0xC9,0x2A,0x3E,0x43,0x21,0x7E,0x43,0x59,0x5C,0x26,0x94,0x1F,0x35,0xFC,0xB5 -,0x3F,0xCB,0x19,0xEB,0xFB,0xB7,0x7F,0xE9,0x8C,0x7C,0xF5,0x1D,0xB9,0xEE,0x6A -,0x5B,0x2D,0x3C,0x32,0x2D,0xD7,0x68,0xDD,0x29,0x89,0x60,0xD1,0xDA,0x6F,0x0A -,0xF3,0x21,0x08,0xCF,0x85,0x8C,0xA8,0x0C,0x4F,0x1E,0x20,0x72,0x04,0xB1,0x03 -,0xDF,0x52,0x52,0x8B,0x28,0x0E,0xC1,0x88,0x23,0x3C,0x0F,0x41,0xFB,0x8F,0xFF -,0x00,0x3A,0x0C,0x77,0x4A,0x59,0x69,0xE5,0xA3,0x8E,0x01,0x2C,0x52,0x86,0x59 -,0x02,0x8C,0x29,0x0D,0x90,0xD9,0x6F,0x9F,0xCF,0x19,0x3A,0x86,0x5C,0x76,0x17 -,0x08,0x22,0xA6,0x8B,0x7A,0xEE,0x4A,0x5A,0x28,0xD3,0xCB,0x86,0x91,0x6A,0x89 -,0x55,0x51,0x92,0x15,0x14,0x01,0x9C,0x75,0xF6,0x27,0x53,0xB7,0x59,0x18,0x63 -,0xCC,0xF2,0x97,0xFC,0x23,0x27,0xFA,0x9E,0x9F,0xE5,0xAD,0x30,0xBC,0x51,0x99 -,0x25,0x86,0xC7,0x4E,0xD7,0x6A,0xA5,0x3C,0x64,0x30,0xB8,0x28,0xA4,0x7B,0x49 -,0x33,0x74,0xE9,0xF2,0x05,0x98,0x7E,0x5D,0x06,0x97,0x6D,0x6C,0x2B,0x75,0xAE -,0xAF,0xE2,0x92,0x5B,0x8D,0x4B,0xF3,0x57,0xE7,0x5F,0x52,0x5F,0x2C,0xA7,0xD2 -,0x7C,0xB5,0xC2,0x9C,0x67,0x20,0xB6,0x48,0x3D,0x71,0xAD,0xD5,0xD6,0xF5,0x68 -,0xB3,0xCE,0x23,0x9E,0x69,0x2A,0xEE,0x1C,0x72,0xB0,0x46,0x3C,0xC9,0xB0,0x7A -,0x67,0x1D,0xA3,0x53,0xF3,0x3C,0x57,0xEB,0xAF,0x19,0x2D,0xBB,0x8A,0xE6,0x71 -,0x72,0xBA,0x47,0x6F,0xA7,0x3D,0xE9,0xED,0xFC,0x83,0x11,0xF2,0x32,0x9C,0x31 -,0xFD,0x54,0x27,0xE8,0x75,0x91,0xB7,0xA8,0xAD,0xEB,0x5A,0xD6,0x7D,0x9D,0x60 -,0xAA,0xBE,0x5D,0x15,0xBE,0xF5,0x28,0x63,0x12,0x18,0xDC,0xF4,0x2D,0x2C,0xA7 -,0x11,0xC4,0x4F,0xB9,0x66,0x04,0xFD,0x74,0x1A,0xD9,0xE1,0xDD,0x97,0xF5,0x2A -,0xD3,0xFF,0x00,0x67,0xE8,0x98,0x75,0x48,0x4F,0x2A,0x96,0x18,0x3D,0xDC,0xF4 -,0x4C,0xE0,0x8E,0x80,0x75,0xEC,0xE7,0x59,0x56,0x68,0x2C,0x7B,0x65,0xD6,0xC5 -,0x67,0x82,0xAA,0xE5,0x75,0xA8,0x25,0xBE,0x16,0x99,0x1A,0xA6,0xB2,0xA5,0x8E -,0x7D,0x6C,0xAB,0xD7,0xAE,0x41,0xE4,0x70,0x01,0x1D,0xF5,0x6C,0x6D,0xAF,0x04 -,0xB7,0x25,0xE4,0xAD,0x46,0xF6,0xBF,0x2D,0xA2,0x95,0xBD,0x5F,0xC2,0xEC,0xAF -,0xF7,0x87,0x3D,0x71,0x25,0x4B,0x00,0x47,0x5C,0xE4,0x46,0xAB,0xDF,0xF1,0x6A -,0xE0,0xD9,0x9B,0x3B,0x6B,0xEC,0xDB,0x79,0xA1,0xDB,0x36,0x4A,0x4B,0x6C,0x4E -,0x73,0x23,0x44,0x99,0x92,0x53,0xF3,0x77,0x39,0x67,0x3F,0x56,0x24,0xE8,0x29 -,0x4D,0xAF,0xE1,0x0E,0xF0,0xDC,0xC1,0x6A,0x37,0x55,0x61,0xDA,0xB6,0xD7,0x24 -,0x9A,0x2A,0x29,0x16,0x4A,0xF9,0x41,0x24,0xFA,0xA5,0x19,0x48,0x73,0x9E,0xC9 -,0xCD,0xBF,0xC4,0x35,0x75,0x6C,0x9D,0x9B,0xB6,0x76,0x5D,0xB4,0xDB,0xF6,0xD5 -,0x9E,0x9E,0xDF,0x13,0x9E,0x52,0xBA,0x02,0xD2,0xCC,0xDF,0x9A,0x49,0x0E,0x59 -,0xDB,0xEA,0xC4,0xEB,0x7F,0xAF,0x0A,0xDA,0xB8,0x68,0xD1,0x64,0xA8,0xE4,0x91 -,0x13,0x83,0x27,0x12,0x55,0x3F,0xDA,0xC7,0x61,0xF5,0x3D,0x07,0xB9,0x1A,0x83 -,0xDF,0x5F,0x8C,0xC1,0x54,0xB3,0x10,0x14,0x0C,0x92,0x4F,0x41,0xAF,0xDD,0x63 -,0xD6,0xCB,0xE5,0x45,0x9E,0x50,0xC7,0xD4,0x00,0xF2,0x9F,0x48,0x27,0xA0,0xE9 -,0xEE,0x73,0x8E,0x9D,0x33,0xF3,0xD1,0x1E,0x33,0x56,0x4A,0xEA,0xDF,0x09,0x10 -,0x08,0xA0,0xF2,0xA8,0x9F,0xD1,0x1A,0x8F,0x72,0x07,0x76,0xF9,0xFB,0x29,0x1F -,0xCC,0x35,0xAF,0x8E,0xBA,0x39,0x97,0xE2,0x61,0x3F,0x1E,0xA9,0x87,0x35,0x93 -,0x37,0x95,0x48,0x83,0xA1,0xCA,0x1F,0xE6,0x18,0x62,0x43,0x28,0x6E,0xC4,0x17 -,0x1A,0xFB,0xF8,0x39,0x2B,0xA4,0x59,0xA4,0x89,0xA7,0xC1,0x0C,0x92,0x56,0xA9 -,0x08,0x87,0x21,0x94,0xA4,0x03,0x1D,0x41,0xCE,0x0B,0xE1,0xC7,0xCC,0xEB,0x32 -,0xA4,0x50,0x5B,0xE1,0x6B,0x85,0xCE,0xAD,0x15,0x61,0xF5,0x1A,0x9A,0xB9,0x15 -,0x56,0x3E,0xE3,0x23,0x38,0x55,0xEF,0x8C,0x80,0x33,0xEF,0x9D,0x06,0x2C,0x0D -,0x75,0x95,0x8F,0x90,0xE5,0xDC,0x90,0x1E,0xA6,0xA2,0x33,0x1C,0x4B,0xEC,0x44 -,0x71,0x03,0xC9,0xBA,0xAF,0x76,0x3D,0x9B,0x21,0x98,0x0C,0x6A,0x1F,0x12,0x43 -,0xB5,0x3C,0x6E,0xA3,0xB6,0xC8,0xCD,0x25,0x9F,0x7C,0x52,0xC9,0xE7,0x44,0xC7 -,0x8A,0x9B,0x95,0x2A,0x03,0xE6,0x10,0xB8,0x5F,0xBD,0x87,0x21,0x86,0x30,0xC6 -,0x25,0xE9,0xD7,0x52,0xE5,0xBA,0xD7,0xDC,0xBA,0x59,0x6D,0xEC,0xB0,0x9F,0xFA -,0x65,0x72,0x34,0x71,0xFE,0xA9,0x1F,0x47,0x7F,0xDF,0x82,0x91,0xD9,0x8E,0xA0 -,0x3E,0x36,0x59,0xDE,0x8A,0x1D,0xA1,0xBA,0xE7,0xB8,0xD5,0x54,0xD7,0x59,0xF7 -,0x55,0xB6,0x42,0xE5,0xB8,0x27,0x95,0x2C,0xEB,0x04,0x91,0xAC,0x6B,0xE9,0x00 -,0x89,0x7B,0x9C,0xB7,0x4C,0x16,0x3A,0x2A,0xDE,0xAE,0x82,0x94,0x85,0x82,0xB1 -,0xDA,0x48,0x88,0xC2,0x51,0xC4,0xA4,0x2B,0x0E,0xD8,0x2A,0x3A,0xB0,0xEB,0x83 -,0x9F,0x46,0x08,0xC8,0xF7,0xD7,0xA2,0xC1,0x55,0x53,0x12,0xA3,0x93,0x43,0x4F -,0x80,0x04,0x30,0x91,0xE6,0x63,0x1D,0x8B,0x0E,0x8B,0xF2,0xC2,0xF5,0x18,0x04 -,0x36,0xB3,0x95,0x55,0x49,0x21,0x40,0x27,0xB9,0xC7,0x7D,0x7E,0xE8,0xAA,0xAB -,0xED,0x47,0x40,0x5F,0xC1,0x4B,0x9D,0x6D,0x28,0x3F,0x15,0x63,0x68,0x2E,0xD4 -,0x6E,0x49,0x66,0x49,0x29,0x64,0x59,0x32,0x09,0xEA,0x4F,0x05,0x90,0x67,0xEA -,0x75,0xFC,0xC7,0xBC,0xDB,0xAB,0x2C,0xF7,0x8A,0xDB,0x45,0xC6,0x11,0x0D,0x6D -,0x0D,0x44,0x94,0xD5,0x11,0x87,0x57,0xE1,0x22,0x31,0x56,0x1C,0x94,0x90,0x70 -,0x41,0xEA,0x09,0x07,0xDB,0x5F,0xD6,0x3F,0x16,0xA9,0x05,0x77,0x87,0x57,0xDA -,0x52,0x03,0x09,0xAD,0xF5,0x30,0xF1,0x23,0x21,0x8C,0x90,0x3C,0x60,0x7E,0xE5 -,0xC6,0xBF,0x94,0xDB,0xBE,0x7A,0xAA,0xCD,0xD1,0x71,0xB8,0x56,0x53,0xCD,0x04 -,0xB5,0xF5,0x0D,0x5A,0x16,0x54,0x2A,0xC5,0x66,0x3E,0x6A,0x36,0x0F,0xB3,0x2B -,0xAB,0x03,0xEE,0x08,0x23,0xBE,0x83,0x55,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81 -,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6 -,0x9A,0xCD,0xB7,0x5A,0x6E,0x57,0x08,0x64,0x9E,0x92,0x8E,0x59,0x29,0xE2,0x92 -,0x38,0xA6,0xA8,0x23,0x8C,0x30,0xB4,0x84,0x84,0xF3,0x24,0x38,0x48,0xF3,0xC5 -,0xB0,0x58,0x81,0xE9,0x3F,0x23,0xA0,0xC2,0xD7,0xAD,0x35,0x3C,0xF5,0x32,0xF9 -,0x54,0xD0,0xC9,0x34,0x9C,0x59,0xF8,0xC6,0xA5,0x8F,0x15,0x05,0x98,0xE0,0x7B -,0x00,0x09,0x27,0xD8,0x02,0x75,0x6B,0x6C,0x6F,0x04,0x6F,0x5B,0x88,0xD3,0xA2 -,0xAD,0x6C,0xB3,0xC8,0x39,0xBC,0x10,0xD3,0x14,0x0A,0x8D,0x18,0x28,0x43,0x3F -,0xAB,0x21,0xC9,0x04,0x98,0xD6,0x13,0xC7,0xA4,0xDE,0xAC,0x8E,0x9D,0xF0,0xE7 -,0xEC,0xDB,0x6C,0xB7,0xA2,0x4B,0x7D,0x10,0x41,0x0F,0x20,0xFF,0x00,0x07,0x4E -,0xA1,0xC9,0x21,0x99,0x97,0x91,0x6E,0x4A,0x08,0xE6,0xC0,0x72,0xF3,0x64,0x5C -,0xFA,0x66,0x03,0x41,0xC9,0xDB,0x07,0xC2,0x8B,0xDE,0xE3,0xAC,0x8A,0x26,0xA6 -,0x99,0xD6,0x60,0x7C,0xB1,0x09,0xE8,0xE3,0xD6,0xBC,0x95,0x95,0x5C,0xC8,0xA1 -,0x82,0x1E,0x51,0x24,0x88,0x43,0x10,0x5E,0x3E,0xE3,0xAB,0x7C,0x3A,0xFB,0x3A -,0x52,0xD3,0x44,0x93,0x5E,0xA9,0xE8,0xE8,0x63,0xF2,0xDA,0x3F,0x86,0x86,0x04 -,0x2D,0xE5,0xB3,0xF3,0x28,0xC3,0x93,0x87,0x01,0x80,0xE9,0x3C,0x95,0x23,0x01 -,0x70,0x17,0x00,0x0B,0xEE,0xC3,0x62,0xB4,0x58,0xA9,0x9A,0x0B,0x4D,0x0C,0x54 -,0xCA,0xE4,0x19,0x5C,0x65,0xA4,0x95,0x80,0xC7,0x27,0x73,0x96,0x76,0xC7,0xBB -,0x12,0x75,0xB1,0xD1,0x35,0xA5,0xDB,0xBB,0x56,0xC3,0x60,0x58,0xCD,0xBA,0x82 -,0x35,0x96,0x34,0xF2,0xD6,0x79,0x3D,0x72,0x2A,0x7E,0x55,0x63,0xF8,0x57,0xFC -,0x0B,0x85,0x1E,0xC0,0x6B,0x6F,0x3C,0x86,0x28,0x24,0x94,0x21,0x72,0x8A,0x5B -,0x88,0xEE,0x70,0x3B,0x6B,0xEF,0x4D,0x11,0xC1,0xD7,0xCB,0x9D,0xF3,0xC4,0x7B -,0xEA,0x6E,0xDD,0xCF,0x53,0x1C,0x15,0x15,0x9E,0x45,0x45,0x91,0x38,0x16,0x86 -,0x91,0x51,0xF9,0x88,0x11,0x4E,0x0B,0x13,0x85,0xE4,0xDE,0x90,0xC5,0xBA,0x13 -,0x81,0x8D,0xE4,0x3B,0x8E,0xA6,0x96,0x95,0x64,0xDC,0x36,0x3A,0xEB,0x6B,0x01 -,0xEA,0x92,0x25,0xF8,0xA8,0x7F,0xAC,0x79,0x60,0x3E,0xAC,0xA0,0x7D,0x4E,0xAD -,0x6D,0xE9,0xE0,0xC5,0xE6,0xD1,0x72,0xAD,0xB8,0xEC,0x58,0xA8,0xEE,0x36,0xEA -,0xB9,0x1A,0x57,0xB4,0x54,0xCD,0xE4,0xC9,0x01,0x63,0x96,0x58,0x24,0x20,0xA9 -,0x42,0x49,0x22,0x36,0xE2,0x14,0x93,0x86,0xC1,0xC0,0x83,0x5D,0x96,0xF1,0x67 -,0x59,0x05,0xDF,0x6A,0x6E,0x3A,0x13,0x1A,0x72,0x25,0xAD,0xD2,0x49,0x19,0x20 -,0x67,0x88,0x96,0x30,0xD1,0xE7,0xDB,0xF1,0x7E,0x99,0xD5,0x56,0x99,0x77,0x7E -,0xD3,0x9E,0x3E,0x9B,0x96,0xD4,0x80,0xF7,0xCD,0x62,0x21,0xFF,0x00,0x32,0x08 -,0xD6,0x9E,0xB0,0x78,0x57,0x52,0x59,0xEA,0x24,0xDA,0x6E,0xCC,0x72,0xCC,0x24 -,0x80,0x31,0x3F,0x52,0x0E,0x4E,0xB7,0xB6,0x9B,0x8D,0x96,0x5A,0x00,0xB4,0xF5 -,0x74,0xD5,0x01,0x59,0xBC,0xC6,0x41,0x90,0x64,0x24,0x97,0x24,0x7B,0x12,0xC4 -,0x92,0x35,0x9B,0x4D,0x51,0x4D,0x33,0x71,0xA5,0xA5,0xA9,0x94,0xFF,0x00,0xD4 -,0xD1,0x48,0xDF,0xF0,0x5D,0x04,0x4E,0xD1,0x55,0xE1,0xE5,0x15,0x57,0x99,0x62 -,0xB7,0xD3,0x54,0xD4,0xC7,0xDA,0x4B,0x7D,0xBD,0xEA,0x19,0x7F,0xDF,0x45,0x38 -,0xFE,0xA3,0x5B,0xB7,0xBA,0xDF,0x2A,0x63,0x73,0x6E,0xDB,0xB2,0x46,0x40,0xCA -,0xB5,0xC2,0xA5,0x21,0x56,0xFD,0x02,0x73,0x6F,0xD9,0x82,0xEB,0x6D,0x47,0x4B -,0x7D,0x96,0x6A,0x91,0x47,0xB4,0xF7,0x45,0x61,0x69,0x01,0x45,0x8E,0xCD,0x51 -,0x1A,0xFE,0x15,0x18,0xE7,0x22,0xAA,0x77,0x07,0xAF,0x2C,0x6A,0x4F,0x41,0xE1 -,0xA7,0x89,0xB7,0x54,0x46,0x8E,0xD7,0x68,0xB1,0x46,0xE0,0x12,0xD7,0x3A,0xC3 -,0x2C,0xA9,0xFF,0x00,0x75,0x00,0x65,0x27,0xFE,0xF0,0x68,0x20,0x8B,0x68,0x86 -,0xE3,0x1F,0x9B,0x79,0xAB,0x6B,0x88,0xEC,0xD0,0x11,0xE5,0xD3,0x29,0xF7,0x06 -,0x2C,0xFA,0x87,0xD2,0x42,0xD8,0xFA,0x6B,0x61,0xB7,0x7E,0x37,0x71,0x54,0x9B -,0x66,0xC9,0xB3,0x4D,0x7B,0x78,0x4F,0x96,0xF2,0x53,0xE2,0x3A,0x3A,0x7F,0xA3 -,0xCE,0x7D,0x03,0x1F,0x95,0x79,0x37,0xF8,0x75,0x6D,0x6D,0xEF,0x00,0x6C,0x7E -,0x62,0xD4,0xEF,0x4B,0xCD,0x76,0xE8,0x90,0x1C,0xFC,0x21,0x1F,0x0B,0x42,0x0F -,0xB6,0x61,0x43,0x97,0xFF,0x00,0xBC,0x76,0x1F,0x4D,0x5B,0x96,0xEA,0x1A,0x2B -,0x6D,0x0C,0x54,0x36,0xEA,0x4A,0x7A,0x3A,0x48,0x57,0x8C,0x50,0x41,0x18,0x48 -,0xD1,0x7E,0x41,0x47,0x40,0x3F,0x4D,0x34,0x54,0x1B,0x5B,0xC0,0xF4,0x99,0x56 -,0xA7,0x7E,0x5D,0xDA,0xE4,0xC7,0xA9,0xB6,0x5B,0xD9,0xA0,0xA4,0x5F,0xA3,0xBF -,0x49,0x25,0xFD,0xCA,0xA9,0xF7,0x4D,0x5B,0x76,0x5B,0x55,0xB2,0xCB,0x6E,0x8A -,0xDB,0x67,0xB7,0x52,0x5B,0xE8,0xA2,0x18,0x8E,0x9E,0x9A,0x15,0x8E,0x35,0xFD -,0x15,0x40,0x1A,0xCC,0xD7,0x9D,0x44,0xF1,0x40,0x9C,0xA5,0x7C,0x67,0xB0,0x03 -,0x25,0x8E,0x33,0x80,0x07,0x52,0x7E,0x83,0x51,0x1E,0x9A,0xF2,0xA8,0xA8,0x86 -,0x9C,0x2F,0x9B,0x20,0x52,0xC7,0x08,0xA3,0xAB,0x31,0xC6,0x70,0x00,0xEA,0x4E -,0x01,0xE8,0x35,0x85,0x59,0x3D,0x5B,0xC3,0x24,0x86,0x58,0xED,0x74,0x8A,0x0F -,0x3A,0x89,0x8A,0x99,0x00,0xEA,0x32,0x01,0xF4,0xA7,0xF2,0x90,0x5B,0x97,0xB8 -,0x2A,0x35,0x8D,0xE6,0xAD,0x34,0x13,0xD5,0x52,0xC6,0x94,0xD1,0xAA,0x96,0x9E -,0xE3,0x71,0x24,0x00,0xA3,0x91,0xCE,0x18,0x86,0x2A,0x0E,0x7A,0x12,0x8A,0x03 -,0x65,0x4E,0x3A,0x68,0x36,0xB3,0x54,0xC5,0x04,0x0D,0x3D,0x4B,0xA5,0x3C,0x4B -,0xDD,0xA5,0x70,0xA0,0x75,0xC0,0xC9,0xED,0xF2,0xD7,0xEC,0x12,0xC7,0x53,0x4E -,0x24,0x54,0x7E,0x0E,0x3F,0x0C,0x91,0xB2,0x1C,0x7D,0x55,0x80,0x23,0xF7,0x1A -,0x8D,0xC7,0x2D,0x6D,0x6D,0x4F,0x99,0x67,0xA3,0x7A,0x99,0x47,0x20,0x2E,0xB7 -,0x45,0x2B,0x14,0x5F,0x88,0x66,0x28,0x87,0x16,0x7F,0x6F,0xC2,0x23,0x57,0x52 -,0x0F,0x98,0xC4,0x6A,0x41,0x45,0x0C,0x94,0x94,0xA4,0x55,0x56,0xC9,0x54,0xF9 -,0x67,0x79,0xA5,0x0A,0xBD,0xFA,0xE0,0x05,0x00,0x05,0x03,0xA0,0xFA,0x0E,0xA4 -,0x9C,0x92,0x1F,0xB6,0xF6,0x0D,0x4A,0x02,0xE7,0x08,0xEF,0x18,0xC9,0x24,0xE1 -,0x58,0xAF,0x73,0xDF,0xB6,0xBE,0x6E,0x15,0x16,0xFB,0x75,0x3C,0x97,0x1B,0x85 -,0x45,0x3D,0x2C,0x31,0x2E,0x5E,0xA2,0x77,0x0A,0xA8,0x0E,0x3F,0x98,0xF4,0x03 -,0xB6,0xBC,0xAC,0x42,0x43,0x66,0x82,0x56,0x8E,0x48,0x25,0x9C,0x1A,0x86,0x8E -,0x61,0xEA,0x89,0xA4,0x25,0xCA,0x9C,0x7E,0x52,0xD8,0xFD,0xB5,0xF0,0x96,0x6A -,0x46,0xAE,0x4A,0xFA,0xD0,0xD5,0xB5,0x71,0x9E,0x51,0x49,0x3F,0x51,0x09,0xFF -,0x00,0xAB,0x5F,0xC2,0x87,0xDB,0x20,0x72,0x23,0xB9,0x3A,0x0D,0x68,0xBB,0xDE -,0xAF,0x3E,0x9D,0xBF,0x6F,0xF8,0x4A,0x53,0xFF,0x00,0xD4,0x6E,0x71,0x32,0x02 -,0x3E,0x71,0xC1,0xD1,0xDF,0xF5,0x73,0x18,0xEC,0x41,0x61,0xAC,0xAB,0x76,0xDB -,0xA2,0x82,0xAA,0x3A,0xFA,0xE9,0xAA,0x2E,0xD7,0x04,0x39,0x4A,0xAA,0xD6,0x0E -,0x63,0x3F,0xF5,0x68,0x00,0x48,0xFA,0x74,0xF4,0x28,0x27,0xDC,0x9D,0x6E,0xB4 -,0xD0,0x35,0x5C,0xF8,0xBA,0x7F,0x8D,0x6E,0x9D,0x89,0xB2,0x60,0x1C,0xE6,0xAE -,0xBE,0x45,0x73,0xAA,0x5F,0x64,0xA4,0xA2,0xFB,0xE7,0x63,0xF2,0xCC,0x82,0x14 -,0x1F,0x32,0xDA,0x9C,0xDF,0x6E,0xB6,0xFB,0x1D,0x9A,0xB2,0xF1,0x75,0xAA,0x8E -,0x96,0x86,0x8A,0x16,0x9E,0xA2,0x67,0x3D,0x11,0x14,0x64,0x9F,0xFF,0x00,0x5E -,0xFA,0x88,0x78,0x21,0x6A,0xB9,0x5E,0x6E,0x37,0x2F,0x15,0x37,0x1D,0x24,0x94 -,0x95,0xF7,0xD8,0x96,0x0B,0x4D,0x14,0xC3,0x0F,0x41,0x6C,0x53,0xCA,0x34,0x61 -,0xEC,0xF2,0x13,0xE6,0xB8,0xFA,0xA8,0xF6,0xD1,0x61,0x6A,0x69,0xA6,0x9A,0x2B -,0x02,0xFF,0x00,0x0A,0xCF,0x6D,0x28,0xF8,0xE0,0xB2,0xC5,0x23,0xE7,0xB7,0x15 -,0x91,0x58,0xFF,0x00,0x90,0x3A,0xFE,0x4D,0xF8,0x93,0x04,0x90,0xEE,0x45,0xFB -,0xB9,0x84,0x1F,0x05,0x4D,0x14,0x12,0x48,0xA4,0x09,0x56,0x18,0x56,0x06,0x2A -,0x4F,0xE2,0x01,0xE2,0x74,0xC8,0xE9,0x94,0x23,0xD8,0xEB,0xFA,0xBB,0xBC,0xFC -,0xDF,0xEC,0x7D,0xEB,0xC8,0x24,0x4B,0xFC,0x3E,0x7E,0x18,0xEF,0xCB,0xCB,0x6C -,0x7F,0x9E,0xB8,0x3F,0xED,0x6D,0xE1,0x45,0x16,0xC6,0xBE,0x05,0xB6,0x45,0x51 -,0x73,0x86,0xED,0x1D,0x65,0x75,0x23,0xC4,0x84,0xCB,0x4B,0x32,0x4F,0xE7,0x4D -,0x1B,0x63,0x39,0x85,0x69,0xE4,0x0D,0x83,0x8C,0x18,0xF9,0x82,0xA0,0xB8,0x70 -,0xE6,0xDD,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34 -,0x0D,0x34,0xD4,0xBB,0x62,0x78,0x7D,0xB8,0x77,0x6D,0xD2,0x2A,0x2A,0x1A,0x1A -,0xB6,0x2F,0xC5,0x8C,0x70,0x40,0x65,0x9C,0xA1,0xE0,0x79,0x08,0xC1,0x18,0x05 -,0x1F,0x92,0xBC,0x8D,0x1C,0x6D,0xC4,0x8E,0x60,0xE8,0x22,0x3A,0x92,0xED,0x1D -,0x8F,0xB8,0x77,0x3C,0xF0,0xC7,0x6F,0xA4,0x75,0x59,0xD4,0xB4,0x2C,0xF1,0xBB -,0x34,0xC3,0xD6,0x33,0x1C,0x71,0xAB,0x49,0x20,0xE4,0x85,0x0B,0x22,0xB2,0xAB -,0x11,0xCC,0xA8,0xEB,0xAE,0xAD,0xF0,0xCF,0xEC,0x9D,0x44,0x20,0xA5,0xA8,0xDE -,0x22,0x3A,0x5E,0x1E,0xA7,0x82,0x29,0xBE,0x22,0xA6,0x52,0xD1,0x85,0x65,0x77 -,0x23,0xC9,0x8D,0x33,0xC9,0x82,0xA2,0x3B,0xA9,0x6F,0xEF,0x8E,0x01,0x1D,0x2D -,0xB5,0x76,0xBD,0x83,0x6B,0xD2,0x3D,0x35,0x8A,0xD7,0x05,0x1A,0xCA,0xDC,0xE6 -,0x90,0x65,0xA5,0x9D,0xBF,0x34,0x92,0x36,0x5E,0x46,0xFF,0x00,0x13,0x12,0x74 -,0x4D,0x71,0xBF,0x87,0x3F,0x65,0x1D,0xCB,0x71,0xA1,0x13,0x6E,0x4A,0x78,0x2D -,0x9E,0x7C,0x78,0x26,0xAA,0x52,0xF3,0x45,0x90,0x87,0x29,0x14,0x4E,0x15,0x58 -,0x10,0xE3,0x9B,0xC8,0xD9,0x56,0xEB,0x08,0x23,0x5D,0x11,0xB2,0x3C,0x09,0xDA -,0x1B,0x78,0xD3,0x4D,0x50,0x92,0xD7,0xD4,0xD3,0xF2,0x30,0xBC,0x84,0x0F,0x27 -,0x93,0x17,0x22,0x3E,0x20,0x08,0x47,0x22,0x4F,0xDC,0xAC,0x40,0xE4,0xE4,0x1C -,0xEA,0xD8,0xD3,0x41,0x8F,0x6E,0xA0,0xA2,0xB7,0x53,0x0A,0x6B,0x7D,0x24,0x14 -,0xB0,0x82,0x5B,0x84,0x31,0x84,0x5C,0x9E,0xE7,0x03,0xDC,0xFC,0xF5,0x91,0xA6 -,0xBC,0xEA,0x6A,0x20,0xA6,0x88,0xCB,0x51,0x2A,0x44,0x99,0x03,0x93,0x9C,0x0C -,0x93,0x80,0x3F,0x52,0x7A,0x63,0x44,0x7A,0x69,0xAC,0x44,0xB8,0x53,0x3C,0x51 -,0x38,0xF3,0x43,0xCC,0xA1,0xD2,0x16,0x89,0x84,0xA5,0x49,0xC0,0x25,0x08,0xE4 -,0xA3,0xA8,0xCE,0x40,0xC6,0x7A,0xE3,0x58,0x93,0xDC,0x1D,0x99,0x97,0xAA,0x70 -,0xEB,0x24,0x71,0x90,0x5A,0x31,0xE9,0x27,0xCC,0x73,0xE8,0x8F,0x00,0x9C,0x8C -,0x92,0x47,0x55,0x3A,0x0D,0xB6,0xB1,0xE5,0xAC,0x86,0x36,0x64,0x0C,0x64,0x74 -,0xFC,0x41,0x3A,0xF1,0xE9,0x9F,0x51,0xEC,0xBD,0x3A,0xF5,0x23,0x58,0xD4,0xA9 -,0x2C,0xD4,0x2B,0x2C,0x52,0xC6,0xC1,0x86,0x51,0x55,0x9B,0xCB,0x3D,0xBA,0x96 -,0xFC,0x4F,0xEF,0xD7,0xA0,0x60,0x7B,0x7B,0xEB,0x14,0xED,0xBA,0x4A,0xA6,0x56 -,0xBC,0xB9,0xB9,0x05,0xFC,0x14,0xEE,0xBC,0x69,0x63,0xFD,0x21,0x1E,0x93,0x83 -,0xD4,0x17,0xE4,0x47,0xB1,0x1A,0x0F,0x1F,0xED,0x3A,0xD7,0x66,0x3D,0xBB,0x43 -,0x25,0xE1,0xBB,0x7C,0x42,0x3F,0x97,0x46,0xBF,0xAC,0xE4,0x61,0x87,0xB1,0xF2 -,0xC4,0x84,0x1E,0xE0,0x6B,0xC1,0x6D,0x97,0x8B,0x9C,0xA4,0xDE,0x2A,0xBC,0xE8 -,0xBF,0xFE,0x3C,0x6A,0x61,0xA5,0x1D,0xFB,0xAE,0x7C,0xC9,0x88,0x3D,0x08,0x72 -,0xA8,0xC0,0xE4,0x2E,0xA5,0x00,0x00,0x00,0x00,0x00,0x3B,0x01,0xA6,0x83,0x1E -,0x96,0x92,0x28,0x23,0x8D,0x10,0x61,0x63,0x1C,0x51,0x10,0x71,0x45,0x1F,0x20 -,0xA3,0xA6,0x07,0xB6,0xB2,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x35,0xE7,0x51 -,0x3C,0x34,0xF1,0xF9,0x93,0xC8,0xB1,0xAE,0x40,0x05,0x8F,0x72,0x7A,0x00,0x3E -,0x64,0x9E,0xC3,0x5A,0xFA,0x9A,0xAA,0xB9,0xE9,0xDE,0x55,0x75,0xB5,0xD1,0xAA -,0x96,0x7A,0x9A,0x80,0x04,0x9C,0x71,0xDC,0x2B,0x74,0x4E,0xF9,0xCB,0xF6,0x20 -,0x82,0x9E,0xFA,0x0D,0x85,0x45,0x44,0x14,0xE8,0x1E,0x79,0x52,0x35,0x66,0x0A -,0xBC,0x8E,0x39,0x31,0xEC,0x07,0xCC,0x9F,0x96,0xB0,0xC4,0xB5,0x33,0x92,0xF4 -,0x74,0xCB,0x4E,0xAC,0x06,0x67,0xA9,0x53,0x92,0x3A,0x11,0x84,0xE8,0xDE,0xE4 -,0x7A,0x8A,0x91,0xF2,0x3A,0xF8,0xA2,0x8E,0x33,0x29,0x96,0x92,0x9D,0xD9,0xC8 -,0x2A,0x6A,0xEA,0x72,0x58,0x8C,0x9C,0x85,0xCF,0xA8,0xAE,0x40,0x38,0x1C,0x57 -,0x07,0x2B,0xAD,0x80,0x0A,0x8A,0x5D,0xDF,0x38,0xEA,0x59,0x8F,0x61,0xFF,0x00 -,0x01,0xA0,0xC5,0x8A,0x82,0x35,0x91,0x66,0x91,0x9E,0xA6,0xA1,0x7A,0xAC,0xD5 -,0x1E,0xAE,0x07,0x04,0x65,0x54,0x60,0x2F,0x43,0x83,0xC4,0x0C,0x8E,0xF9,0xD7 -,0xDB,0x50,0xD3,0x3C,0xCB,0x51,0x52,0xBE,0x7C,0x91,0xB7,0x24,0x69,0x7A,0x88 -,0xC8,0xCF,0x55,0x1D,0x94,0xE0,0x91,0x90,0x33,0x8E,0xE4,0xEB,0xD1,0x67,0x32 -,0xFF,0x00,0xCD,0xD7,0x92,0xFF,0x00,0xAC,0x6E,0x8B,0xFB,0x7C,0xFF,0x00,0x6E -,0x87,0xE7,0xAF,0xB5,0x8F,0xB1,0x73,0xCD,0xBB,0xF5,0xEC,0x3F,0x41,0xA0,0xF9 -,0x32,0x3B,0x74,0x85,0x39,0x0F,0xCC,0xC7,0x03,0xF6,0xF9,0xFF,0x00,0xC3,0xEB -,0xAF,0xA9,0xE2,0x8E,0x78,0x5E,0x19,0x90,0x3C,0x72,0x29,0x57,0x52,0x32,0x18 -,0x1E,0x84,0x1D,0x7D,0xE9,0xA0,0x69,0xA6,0xBC,0x6A,0x2A,0x62,0x85,0x84,0x67 -,0x93,0xCA,0x46,0x44,0x68,0x32,0xC7,0xEB,0x8F,0x61,0x9E,0x99,0x38,0x1F,0x5D -,0x07,0xB6,0xBE,0x65,0x74,0x8A,0x36,0x92,0x47,0x54,0x44,0x05,0x99,0x98,0xE0 -,0x28,0x1D,0xC9,0x3A,0x8F,0xCD,0xBA,0xA9,0xD6,0x9A,0x69,0xA1,0x8A,0x29,0x96 -,0x22,0x79,0xCD,0xF1,0x0A,0xB4,0xD0,0x8E,0xDF,0x7B,0x39,0xF4,0x02,0x0F,0x42 -,0xA8,0x5C,0x8F,0x91,0xD5,0x4F,0x4D,0xBA,0xAE,0x5E,0x2E,0xF8,0xC5,0x49,0xB3 -,0xF6,0xE5,0xE2,0x1A,0xBD,0x9D,0x66,0x41,0x57,0xB9,0xEA,0x28,0x94,0x1A,0x5A -,0xB2,0x7F,0xBB,0xA4,0x59,0x0E,0x4C,0x8A,0xC4,0x10,0xC4,0x10,0xAE,0xBC,0x86 -,0x3A,0x1C,0x95,0x3A,0xB5,0xD2,0x0F,0x16,0xE5,0xA4,0xB9,0x56,0xD1,0xCF,0x0E -,0xC7,0xA4,0xA8,0x13,0xD2,0xC1,0x50,0xBC,0x4D,0xEE,0x44,0x39,0x8E,0x56,0x5F -,0x6A,0x65,0x23,0x92,0xAB,0x75,0x90,0xF1,0x62,0x02,0x80,0x1A,0xD8,0xD7,0xE2 -,0xAA,0xA2,0x85,0x55,0x0A,0xA0,0x60,0x00,0x30,0x00,0xD7,0xEE,0x8A,0x69,0xA6 -,0x9A,0x0F,0x2A,0xC8,0x84,0xD4,0x73,0x42,0x46,0x44,0x91,0xB2,0x9F,0xDC,0x63 -,0x5C,0xB5,0xF6,0xC9,0xA9,0x32,0x6D,0x8B,0x55,0xC4,0x60,0x03,0x4F,0x71,0x99 -,0x5F,0xDF,0x8C,0xB6,0xF8,0xA1,0xC7,0xE8,0x7C,0xE3,0xFD,0x35,0xD5,0x5A,0xE4 -,0x9F,0xB6,0x2B,0x2A,0x78,0x4D,0x67,0x03,0xF9,0x6C,0x88,0x7E,0x7F,0x8D,0xA9 -,0x97,0xFF,0x00,0x6E,0x83,0x87,0x74,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD6 -,0x55,0xB6,0xDF,0x59,0x71,0xA8,0xF2,0x68,0xE1,0xE6,0x46,0x0B,0xB1,0x60,0xA9 -,0x12,0x96,0x0B,0xC9,0xDD,0x88,0x54,0x5C,0xB2,0x82,0xCC,0x40,0x19,0x19,0x23 -,0x57,0x27,0x87,0x9F,0x67,0x5D,0xD5,0xBA,0xA1,0xA5,0x9F,0x84,0xD1,0x45,0x30 -,0xE4,0xF2,0x4B,0x13,0x41,0x0A,0xA3,0x20,0xE2,0x55,0xDC,0x19,0x24,0x60,0xE4 -,0x83,0xC6,0x23,0x11,0x0B,0xD2,0x5F,0x56,0x40,0x52,0xB4,0xD0,0x4D,0x53,0x51 -,0x15,0x35,0x34,0x32,0x4D,0x3C,0xAE,0x12,0x38,0xE3,0x52,0xCC,0xEC,0x4E,0x02 -,0x80,0x3A,0x92,0x4F,0x4C,0x6A,0xC0,0xD8,0x9E,0x12,0x6E,0x2D,0xD9,0x01,0x7A -,0x44,0x94,0xBC,0x8A,0x44,0x0B,0x4F,0x10,0x95,0x79,0xF1,0x56,0x02,0x49,0x0B -,0x2C,0x6B,0xE9,0x2F,0x94,0x56,0x79,0x95,0x90,0x83,0x17,0x5C,0xEB,0xB3,0x7C -,0x3E,0xFB,0x3C,0x6D,0x9B,0x1D,0x0F,0x93,0x75,0xE3,0x59,0x13,0x90,0xEF,0x46 -,0x91,0x84,0xA6,0x62,0x18,0xB2,0xF3,0x8B,0x2D,0xE6,0xF1,0x2E,0xE0,0x79,0xED -,0x39,0x01,0xB0,0xA5,0x47,0x4D,0x5C,0x96,0xCB,0x65,0x05,0xB2,0x05,0x86,0x82 -,0x92,0x28,0x11,0x50,0x20,0xE2,0x3A,0xF1,0x1D,0x97,0x3D,0xF0,0x33,0xD0,0x7B -,0x7B,0x68,0x9A,0xE6,0xEF,0x0A,0x3E,0xCC,0xB1,0x59,0xCA,0x55,0xDD,0xAA,0x7E -,0x1D,0xFA,0xE4,0x53,0xBB,0x2C,0x8C,0x0F,0x21,0x83,0x30,0xE3,0x29,0x05,0x24 -,0x74,0x6F,0x2C,0xD3,0xE4,0x01,0xCD,0x1B,0x5D,0x13,0xB6,0xB6,0xFD,0x8F,0x6D -,0x5A,0xD2,0xD9,0xB7,0xED,0x34,0x76,0xCA,0x34,0xEA,0x21,0xA6,0x88,0x22,0x93 -,0xF3,0x38,0xEE,0x7E,0xA7,0xA9,0xD6,0xCF,0x5F,0x8C,0x42,0xA9,0x66,0x20,0x00 -,0x32,0x49,0xEC,0x34,0x1F,0xBA,0x6B,0x0A,0x6B,0x8C,0x2B,0x18,0x91,0x0A,0x98 -,0xD8,0x80,0x25,0x76,0xE2,0x8C,0x4E,0x30,0x14,0xF7,0x62,0x73,0xD3,0x88,0x20 -,0xF6,0xCE,0xB1,0x9E,0x7A,0xA9,0x42,0x30,0xA7,0x94,0xAB,0x90,0x14,0xC9,0x11 -,0xC1,0xE8,0x0F,0x48,0xFD,0x87,0x43,0xD6,0x42,0xA4,0x1F,0x6E,0xBA,0x23,0x69 -,0x23,0xA4,0x68,0x64,0x91,0xD5,0x10,0x75,0x2C,0xC7,0x00,0x6B,0x0A,0xB6,0xE1 -,0xE5,0x28,0x11,0xA8,0x52,0xD9,0x0A,0xD2,0x82,0x0B,0x63,0x39,0xE2,0x83,0xD4 -,0xE4,0x63,0x38,0x00,0x64,0x76,0x3A,0xF7,0x14,0x80,0x61,0x8C,0xB2,0x3C,0xA3 -,0xFD,0x2B,0xE0,0xB0,0xFD,0x06,0x38,0xAF,0xEC,0x3A,0xE9,0x15,0x15,0x3C,0x65 -,0xD9,0x14,0x86,0x7C,0x73,0x7E,0x47,0x9B,0x63,0xB6,0x5B,0xF1,0x1C,0x64,0xE3 -,0xAE,0x83,0x01,0xEE,0x15,0x6D,0x88,0x12,0x31,0xE7,0x28,0x1C,0xC2,0x27,0x29 -,0x18,0xF7,0xE8,0x9C,0xB1,0x18,0x60,0x0F,0x12,0xED,0xDF,0xA1,0x1A,0xFD,0x86 -,0xDD,0x55,0x2C,0xA2,0x5A,0x99,0xBC,0xA2,0x06,0x32,0xA7,0x9C,0xAC,0x3D,0xFD -,0x64,0x00,0x81,0x80,0x19,0x54,0x51,0x82,0x32,0x1B,0x5B,0x48,0xA3,0x8E,0x24 -,0x11,0xC5,0x1A,0xC6,0x83,0xB2,0xA8,0xC0,0x1F,0xB6,0xBE,0xB4,0x1E,0x10,0x52 -,0x53,0xC1,0x11,0x8A,0x28,0xF8,0x2B,0x1E,0x4C,0x41,0x3C,0x9C,0xF4,0xEA,0xC7 -,0xBB,0x1E,0x83,0x24,0xE7,0x3E,0xFA,0xF5,0x8A,0x38,0xE2,0x89,0x62,0x8A,0x34 -,0x48,0xD4,0x61,0x55,0x46,0x00,0x1F,0x41,0xAF,0xAD,0x34,0x0D,0x34,0xD3,0x40 -,0xD3,0x4D,0x62,0x8A,0xCF,0x38,0xA0,0xA3,0x88,0xD4,0x2B,0x11,0x99,0x41,0xC4 -,0x60,0x7C,0xF9,0x7F,0x37,0x4C,0xFE,0x10,0x7A,0x8C,0x1C,0x68,0x32,0xB4,0xD3 -,0x58,0xF5,0x49,0x51,0x27,0xA6,0x3A,0x81,0x4F,0x1F,0xBB,0xAA,0x86,0x7F,0xDB -,0x3D,0x07,0xEE,0x0E,0x7E,0x9A,0x0F,0x49,0xE7,0x86,0x00,0xA6,0x59,0x15,0x79 -,0x1C,0x28,0xF7,0x63,0x8C,0xE0,0x0E,0xE4,0xFD,0x06,0xBC,0x2A,0x2A,0x59,0x20 -,0x79,0xE4,0x68,0xE8,0xE9,0xD0,0x72,0x79,0xA7,0x20,0x61,0x47,0x73,0x8C,0xF4 -,0x18,0xCF,0x52,0x7A,0x7B,0x8D,0x7E,0x43,0x4A,0x90,0x17,0x34,0x90,0xAA,0xC8 -,0xE3,0x0D,0x3C,0xC4,0xBB,0x1E,0xF8,0xC9,0x27,0x93,0x00,0x4F,0x62,0x40,0x00 -,0xF4,0xD7,0xEF,0xC1,0x53,0xAC,0xA2,0xAA,0xA5,0x8C,0xF2,0xC6,0x79,0x2C,0x93 -,0x10,0x44,0x7D,0xFA,0xA8,0xEC,0xA7,0x04,0x8C,0x81,0x92,0x3B,0x93,0xA0,0xD7 -,0xA3,0xD4,0xCF,0x21,0x6B,0x65,0x29,0x69,0x30,0x54,0xD7,0xD7,0xA9,0x00,0x77 -,0x07,0x82,0x74,0x66,0x19,0x55,0x38,0x1C,0x10,0x83,0x90,0xDA,0xCB,0x86,0xDB -,0x0C,0x72,0x0A,0xBA,0xE9,0xDE,0xB2,0x74,0x3C,0xD6,0x49,0xC8,0xE3,0x17,0x7F -,0xC0,0xA3,0xD2,0xB8,0x0C,0x47,0x2C,0x72,0xC7,0x42,0xC7,0x5E,0xC9,0x54,0x6A -,0x30,0x68,0xD3,0xCC,0x43,0xFE,0x99,0xBA,0x26,0x3A,0x75,0x1E,0xED,0xD0,0xE4 -,0x63,0xA1,0xF9,0xEB,0xD1,0x69,0xC1,0x60,0xF3,0x31,0x99,0xC1,0xC8,0xCF,0xE1 -,0x53,0xF4,0x1F,0xFA,0xF5,0x3F,0x5D,0x07,0xC9,0x9E,0x49,0x7A,0x52,0xC7,0xC8 -,0x7F,0xAC,0x7E,0x89,0xFB,0x7B,0xB7,0xCF,0xA7,0x43,0xF3,0xD1,0x29,0x14,0xB8 -,0x92,0xA5,0xCC,0xF2,0x03,0x91,0xCB,0xA2,0x29,0xFA,0x2F,0x6E,0x87,0xB1,0x39 -,0x3F,0x5D,0x64,0x6B,0xC2,0xBA,0xB2,0x92,0x86,0x9C,0xD4,0x56,0x54,0xC5,0x4F -,0x10,0x20,0x73,0x91,0xC2,0x8C,0x9E,0xC3,0xAF,0xB9,0xF9,0x68,0x3D,0xF4,0xD4 -,0x6E,0xE9,0xBA,0xE9,0xA9,0x64,0x8E,0x10,0x92,0x47,0x2C,0xC3,0x94,0x31,0x3C -,0x2E,0xF5,0x13,0x0F,0x9A,0x53,0xAF,0xDE,0x10,0x0F,0x42,0x58,0x20,0x1D,0xF3 -,0x8D,0x6B,0x9E,0xE1,0x7E,0xAD,0x32,0x16,0x63,0x68,0x82,0x3C,0x99,0x70,0xD1 -,0xCD,0x56,0x80,0x63,0x25,0xD8,0xFF,0x00,0xC9,0xE9,0xF0,0x08,0x24,0x7D,0xE1 -,0x2B,0xD4,0x60,0xE8,0xA9,0x45,0xC6,0xE5,0x05,0x0C,0xB1,0xAD,0x47,0xA1,0x64 -,0xCF,0x16,0x24,0x12,0xC7,0xF2,0xAA,0x8C,0xB3,0xB7,0xD0,0x0F,0xFF,0x00,0x1A -,0xD7,0xCB,0x78,0xAA,0x96,0x57,0x58,0x69,0xC5,0x3A,0x46,0x39,0x37,0x99,0x86 -,0x98,0x8C,0x13,0xD5,0x01,0x0B,0x18,0x23,0xA8,0x69,0x18,0x76,0xC1,0x5D,0x47 -,0xAD,0x6B,0x51,0x56,0x59,0xAC,0x54,0x6F,0x52,0x65,0x00,0x49,0x5C,0xF3,0xC8 -,0x90,0xB0,0xE8,0x7A,0xD4,0xB7,0xDF,0x54,0x00,0x7A,0xAF,0x96,0x16,0x32,0x09 -,0x52,0x46,0xB7,0x54,0x9B,0x4A,0x96,0x44,0x43,0x7C,0x98,0x5D,0x78,0x1E,0x49 -,0x4B,0xE5,0x08,0xA8,0xA3,0x39,0xCF,0xA6,0x01,0x95,0x3D,0x7A,0x83,0x21,0x76 -,0x07,0xB1,0x1A,0x0C,0x2A,0xDD,0xD8,0x27,0xA6,0x79,0xAD,0xC6,0x2A,0x8A,0x54 -,0xE8,0xD5,0x86,0x71,0x05,0x18,0xEA,0x40,0xCD,0x4B,0x0F,0x56,0x7B,0x62,0x15 -,0x62,0x18,0x63,0x23,0x58,0x30,0xD0,0xDE,0x6F,0xAA,0x43,0x45,0xE6,0xD3,0x31 -,0xCB,0x49,0x5B,0x03,0xD3,0xD1,0x9F,0x99,0x14,0xB9,0xF3,0x67,0x3D,0x3A,0xF9 -,0xCC,0xAA,0x7A,0x32,0xFC,0xB5,0x38,0xA9,0x4A,0x38,0xF1,0x59,0x52,0x90,0x27 -,0xC3,0xA9,0x61,0x34,0x80,0x0F,0x29,0x71,0xD4,0xF2,0x3F,0x84,0x63,0x39,0xD7 -,0x25,0x78,0xE1,0xE3,0x75,0xDF,0xC4,0x5D,0xCF,0x17,0x86,0x1E,0x13,0xD2,0xD7 -,0xDC,0x68,0xEA,0x65,0x30,0xD7,0x55,0xD0,0xFA,0x65,0xAE,0x51,0xD5,0xE3,0x89 -,0xFF,0x00,0x92,0x2C,0x67,0x94,0x87,0xB8,0xC9,0xFC,0x23,0xD4,0x12,0xFD,0xDF -,0x51,0x2F,0x88,0x37,0xD8,0xF6,0x86,0xCE,0x77,0xBC,0xC6,0x8E,0xD0,0xCD,0x73 -,0x9D,0xF1,0x1C,0xA5,0x3D,0x32,0x2C,0x01,0x00,0x58,0x29,0xA3,0xCF,0x19,0x26 -,0x8C,0x07,0x90,0xE2,0x24,0x62,0x4B,0x30,0xBE,0x7C,0x2A,0xD8,0x56,0x6F,0x0E -,0xF6,0xA4,0x76,0x3B,0x42,0x07,0x76,0x73,0x35,0x65,0x51,0x8D,0x51,0xAA,0x66 -,0x3F,0x89,0xC8,0x1D,0x14,0x74,0x01,0x54,0x74,0x55,0x00,0x0E,0xDA,0xC7,0xF0 -,0x7B,0x61,0xD1,0xEC,0x2D,0xA7,0x4F,0x6F,0x55,0x81,0xEE,0x32,0x44,0x9F,0x1B -,0x3C,0x49,0xC5,0x0B,0x28,0xC2,0xC7,0x18,0x3D,0x56,0x24,0xC9,0x0A,0xBF,0xAB -,0x1C,0xB3,0x33,0x19,0xA6,0x8A,0x69,0xAC,0x2A,0xDB,0xA5,0x15,0x25,0x42,0xD2 -,0xC9,0x37,0x3A,0xA7,0x5E,0x49,0x4F,0x10,0xE7,0x2B,0x0E,0xD9,0xE2,0x3A,0x85 -,0xCF,0x4E,0x47,0x00,0x7B,0x91,0xAC,0x8A,0x77,0x9A,0x45,0xE7,0x2C,0x5E,0x4E -,0x7B,0x21,0x60,0x58,0x7E,0xB8,0xE9,0xFD,0x33,0xFA,0xE8,0x3D,0x74,0xD3,0x4D -,0x03,0x5C,0x7B,0xF6,0xD7,0x91,0xA9,0x7C,0x3B,0xB3,0xC2,0xE4,0x65,0xEC,0xF4 -,0x90,0x9F,0xD7,0x91,0x6E,0xFF,0x00,0xF7,0x7A,0xEC,0x2D,0x71,0xC7,0xDB,0xCD -,0xA0,0x5D,0x93,0x64,0x88,0xC8,0x03,0xFC,0x2D,0x1F,0x10,0x48,0xF5,0x7F,0x7B -,0xFF,0x00,0xA6,0x7F,0xA6,0x83,0x8B,0xB4,0xD4,0xAB,0x60,0xEC,0x3D,0xC3,0xBC -,0x6B,0xA9,0xA3,0xB5,0xDB,0xAA,0xE6,0xA6,0x9A,0xA7,0xE1,0xDA,0x48,0x22,0x12 -,0x48,0x48,0x5E,0x4F,0xE5,0xA1,0x65,0xE6,0x55,0x4A,0xE7,0xA8,0x55,0x2F,0x1F -,0x36,0x40,0xE0,0xEA,0xF3,0xB6,0xFD,0x94,0xFC,0x41,0x48,0x92,0xAA,0x96,0x2D -,0xB5,0x42,0xC6,0x34,0x0E,0x97,0x6A,0xE3,0x51,0x37,0x2E,0x05,0x64,0xE2,0xA9 -,0x03,0x42,0xA1,0xB9,0x12,0x01,0xF3,0x0A,0x10,0xB8,0x72,0x47,0x22,0x1C,0xEF -,0x65,0xB0,0x5C,0x6E,0xB3,0x53,0xAC,0x51,0x88,0x61,0x9D,0xC2,0x24,0xF3,0x06 -,0x08,0xC7,0x92,0xA9,0xE0,0x00,0x2D,0x23,0x0E,0x60,0x94,0x8C,0x33,0xE3,0x24 -,0x29,0xC6,0xAF,0xAF,0x0C,0x3E,0xCC,0x37,0xDB,0xED,0x42,0x54,0xDD,0x83,0xD1 -,0xD1,0x14,0x5E,0x7F,0x1B,0x09,0x49,0x43,0x94,0x22,0x45,0x10,0xA3,0xF2,0xE8 -,0xCC,0xA5,0x5A,0x49,0x22,0x6F,0x4E,0x5A,0x32,0x09,0x51,0xD0,0x7B,0x17,0x6E -,0x0D,0x87,0xCE,0xAE,0xE9,0xE1,0x4D,0xCA,0xAE,0xE5,0x2F,0xFC,0xF2,0xF7,0x45 -,0x73,0x4B,0xB5,0x45,0x41,0xC6,0x09,0x91,0xA5,0xF2,0xE6,0x20,0xFB,0xAA,0xA1 -,0x1F,0x4D,0x4E,0xEC,0xFE,0x26,0xEC,0x1A,0xBA,0xA4,0xB6,0x0B,0xFD,0x35,0xAE -,0xB4,0x00,0xAB,0x41,0x73,0x8D,0xA8,0x27,0x1E,0xD8,0x11,0x4E,0x11,0x8F,0xEC -,0x0E,0x88,0xD6,0xEC,0x8F,0x07,0xF6,0x96,0xDA,0x14,0xB3,0x35,0x20,0xB8,0x56 -,0x52,0xF2,0x30,0x4D,0x52,0xAA,0xC2,0x9C,0xB3,0x16,0x6F,0x22,0x35,0x55,0x8A -,0x00,0x58,0x96,0xC4,0x48,0x9D,0x49,0xC9,0x3D,0xF5,0x61,0xC7,0x1A,0x46,0x08 -,0x45,0x0A,0x09,0xC9,0xC7,0xB9,0xF9,0x9F,0x99,0xD7,0xEA,0x32,0xBA,0x86,0x46 -,0x0C,0xA4,0x64,0x10,0x72,0x08,0xD7,0xEE,0x88,0x6B,0xF2,0x47,0x48,0xD0,0xBC -,0x8C,0xA8,0xAA,0x32,0x59,0x8E,0x00,0xD7,0xC4,0xC2,0x63,0x81,0x13,0x22,0x7C -,0xD9,0x86,0x7F,0x60,0x3A,0x7F,0x5F,0xF2,0x3A,0xF8,0x86,0x99,0x11,0x83,0xBB -,0x3C,0xD2,0x8F,0xE7,0x90,0xE4,0xE7,0x18,0xC8,0x1D,0x97,0xF6,0x03,0x41,0xF1 -,0x24,0xF3,0xC9,0x95,0xA5,0x87,0xA7,0x6F,0x36,0x50,0x42,0x8E,0xFD,0x97,0xBB -,0x7B,0x7C,0x81,0x1D,0x8E,0xB1,0x9E,0x86,0xA2,0x79,0x03,0x4B,0x2F,0x22,0x0E -,0x79,0xC8,0x01,0x0B,0xD7,0xF9,0x23,0xFC,0x20,0x8E,0xE1,0x9B,0x93,0x0E,0xC7 -,0x3A,0xD9,0xE9,0xA0,0xC6,0xA6,0xA2,0x82,0x09,0x3C,0xEC,0x34,0xB3,0x91,0x83 -,0x34,0x87,0x93,0x90,0x71,0x90,0x0F,0xB0,0x24,0x67,0x88,0xC0,0xFA,0x6B,0x27 -,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x35,0xE5,0x53,0x51,0x05 -,0x34,0x62,0x4A,0x89,0x92,0x25,0x2C,0x15,0x4B,0x1C,0x72,0x63,0xD8,0x0F,0x99 -,0x3E,0xC0,0x75,0x3A,0xC6,0x15,0x35,0xB5,0x43,0xFE,0x49,0x4F,0xE4,0x21,0x19 -,0x13,0x55,0x29,0x07,0xB0,0x20,0x88,0xFA,0x37,0xD0,0x86,0x28,0x47,0xD7,0x41 -,0x9D,0xA6,0xB5,0xEF,0x34,0x14,0xB3,0x14,0x69,0x26,0xAD,0xAB,0xC6,0x44,0x6B -,0x86,0x71,0x9E,0x58,0xE8,0x30,0xA8,0x0F,0x51,0xC8,0xE0,0x1C,0x75,0x3A,0xFA -,0x61,0x57,0x22,0xB4,0x95,0x53,0x47,0x45,0x02,0xE4,0x95,0x8D,0xB2,0xD8,0x1F -,0x99,0xCF,0x40,0x31,0xDC,0x01,0xD3,0xD9,0xB4,0x1F,0x35,0x31,0x52,0x1A,0x94 -,0x5A,0xE9,0xFC,0xF9,0x1F,0xAC,0x74,0xED,0xD5,0x7A,0x15,0xEA,0x10,0x7E,0x20 -,0x0E,0x0E,0x4E,0x78,0xE7,0xB8,0xD6,0xC3,0x58,0x96,0xE8,0xA9,0x62,0x0F,0xF0 -,0xB0,0x14,0x0D,0x82,0xD2,0x90,0x73,0x29,0x1D,0x32,0x49,0xF5,0x31,0xC0,0x1E -,0xA3,0xDF,0xA7,0x53,0xAC,0xBD,0x03,0x43,0xA6,0x9A,0x0F,0x09,0x26,0x91,0x88 -,0x5A,0x68,0xBC,0xCF,0x9B,0xB1,0xE2,0x83,0xB7,0xBF,0x73,0xD0,0xFB,0x0C,0x74 -,0xC6,0x46,0xBC,0xD6,0x85,0x64,0x65,0x92,0xB6,0x4F,0x8A,0x90,0x10,0x40,0x61 -,0x88,0xD4,0x8C,0x1C,0xAA,0x76,0xEE,0x32,0x09,0xC9,0x1F,0x3D,0x65,0xEB,0x1A -,0xB2,0xBE,0x9A,0x95,0x84,0x72,0x33,0x3C,0xCC,0x32,0xB0,0xC6,0xA5,0xE4,0x61 -,0xF3,0x0A,0x3A,0xE3,0xEB,0xD8,0x7B,0x9D,0x06,0x4E,0xB0,0xAE,0xF7,0x6B,0x75 -,0xA6,0x34,0x7A,0xFA,0xA4,0x88,0xC8,0x4A,0xC5,0x18,0x05,0xA4,0x94,0xFE,0x54 -,0x45,0xCB,0x39,0xFA,0x28,0x27,0x58,0x15,0x52,0x5E,0xEB,0x3D,0x28,0x1A,0xDB -,0x11,0xEC,0x90,0x84,0x96,0xA4,0xFE,0xAC,0xDF,0x75,0x1F,0xFE,0x7C,0x8E,0xC4 -,0x1D,0x78,0x50,0xED,0xA0,0x92,0x49,0x2C,0x92,0x9A,0x66,0x94,0x71,0x95,0xA0 -,0x95,0x9E,0xA2,0x51,0xF2,0x7A,0x96,0xFB,0xC2,0x3E,0x41,0x78,0xF1,0xEC,0x0E -,0x34,0x56,0x15,0xC7,0x72,0xDC,0x27,0x9C,0x52,0x52,0x53,0x35,0x03,0xBA,0x86 -,0x58,0x9A,0x3F,0x3E,0xB9,0xD4,0xF6,0x61,0x02,0x9E,0x31,0x29,0xF6,0x92,0x56 -,0x00,0x1E,0x8C,0xBA,0xF0,0xA5,0xB1,0x5E,0x2A,0xAB,0xE3,0x9A,0xAD,0xEA,0x28 -,0x4B,0x83,0xCA,0x75,0x74,0x9E,0xB0,0x29,0x1D,0x41,0x95,0xBD,0x10,0x86,0xEC -,0x63,0x81,0x0E,0x0E,0x08,0x61,0xDF,0x52,0xEB,0x75,0x05,0x15,0xBA,0x03,0x05 -,0x0D,0x2C,0x54,0xF1,0x96,0x2C,0xC1,0x17,0x1C,0x98,0xF7,0x66,0x3D,0xCB,0x1F -,0x72,0x7A,0x9D,0x64,0xE8,0x8D,0x4D,0xBF,0x6F,0x5B,0x2D,0xB0,0x49,0x15,0xBE -,0x9C,0x40,0x65,0x21,0xA6,0x7E,0x6C,0xD2,0x4E,0xC3,0xB3,0x4B,0x21,0x3C,0xE4 -,0x3F,0xED,0x37,0x51,0xD0,0xF4,0xD7,0xE2,0x58,0x28,0x9D,0xA2,0x6A,0xE5,0x15 -,0x82,0x12,0x0C,0x30,0xBA,0x81,0x04,0x38,0xED,0xC2,0x21,0xE9,0xC8,0xF6,0x27 -,0x2C,0x3E,0x7A,0xDB,0xE9,0xA0,0x6B,0x5B,0xB9,0xAF,0xD6,0x7D,0xB5,0x65,0xA8 -,0xBC,0xDF,0x6E,0x10,0x50,0x50,0x53,0x8C,0xC9,0x34,0xA7,0x03,0xE8,0x00,0xEE -,0xCC,0x4F,0x40,0xA3,0x24,0x9E,0x80,0x6A,0x3D,0xBF,0x7C,0x43,0xB5,0xED,0xAA -,0x9F,0xE1,0x14,0x91,0x7F,0x17,0xDC,0x0F,0x1F,0x98,0x96,0xE8,0xA6,0x58,0xC4 -,0x49,0xDB,0xCD,0xA8,0x95,0xBD,0x10,0x45,0x92,0x3D,0x6E,0x7A,0xF6,0x50,0xC7 -,0xA6,0xAA,0x6F,0x10,0xE2,0x6B,0x2D,0xA5,0xBC,0x55,0xF1,0x2A,0xA6,0x5B,0xE5 -,0x55,0xB7,0xD7,0x6B,0xA2,0x33,0x4B,0x43,0x6B,0xA6,0x9C,0x8C,0x22,0x53,0x45 -,0x8F,0x3E,0xA6,0x42,0x4F,0xF7,0x8E,0x15,0x4A,0xE4,0xE4,0x01,0xD0,0xAD,0x1F -,0xDA,0x03,0xC5,0x01,0x35,0xB8,0x45,0x7E,0x49,0x29,0x92,0xA8,0xA8,0xB3,0xED -,0x0E,0xF5,0x55,0x8C,0x7F,0x05,0x4D,0xC5,0x57,0xAC,0x70,0x8E,0x8C,0xB4,0xDF -,0x89,0xCE,0x39,0x74,0xC8,0x16,0xD7,0xD9,0x93,0xC2,0x95,0xD9,0x16,0x56,0xDC -,0x17,0x8A,0x31,0x16,0xE0,0xB9,0x47,0xEA,0x47,0xC1,0x92,0x96,0x26,0x3C,0x8A -,0xB9,0x1D,0xE5,0x76,0xC3,0x48,0x47,0x4C,0x85,0x41,0xE9,0x8D,0x75,0x52,0x7D -,0x98,0xB6,0xF7,0xF6,0xC7,0x75,0x4F,0xE3,0x16,0xF1,0xB4,0x41,0x5D,0x76,0x92 -,0x76,0x7B,0x25,0xA2,0xDD,0x4C,0x04,0x74,0x8B,0xED,0x23,0x64,0xF0,0x89,0x40 -,0xCF,0x96,0x1D,0x94,0x9F,0x53,0xFA,0x98,0xA9,0xD7,0x49,0xC3,0x72,0x37,0x84 -,0x96,0x5A,0xEB,0xD4,0x34,0x96,0xF8,0xCE,0x25,0xFE,0x1F,0x29,0x11,0x03,0x9C -,0x71,0x6A,0xB2,0x06,0x4E,0x7A,0x62,0x3E,0x2C,0xA7,0xA1,0x27,0x45,0x6E,0x6E -,0xB7,0xFB,0x7D,0x05,0x4F,0xC1,0x83,0x2D,0x65,0xC0,0xA8,0x65,0xA2,0xA5,0x4F -,0x32,0x62,0x0F,0x62,0x40,0xE8,0x8A,0x4F,0x4E,0x4E,0x55,0x7E,0xBA,0xC4,0x14 -,0xDB,0x86,0xEF,0xD6,0xBA,0xA4,0x59,0x68,0xCF,0xFD,0x1A,0x91,0xC3,0xD4,0xB8 -,0xF9,0x3C,0xA4,0x61,0x32,0x3A,0x11,0x18,0x24,0x1E,0xA2,0x4D,0x6C,0xAC,0xF4 -,0xB6,0xDA,0x1A,0x45,0x8A,0xDD,0x4D,0x1D,0x2C,0x52,0x31,0x70,0xA2,0x3E,0x05 -,0xDB,0xDD,0x8E,0x7A,0x96,0x3E,0xE4,0xF5,0x3A,0xCC,0x57,0x46,0x66,0x55,0x75 -,0x62,0x87,0x8B,0x00,0x73,0xC4,0xE0,0x1C,0x1F,0x97,0x42,0x0F,0xEF,0xA0,0xC5 -,0xB4,0xDA,0xED,0xF6,0xA8,0x1A,0x1B,0x7D,0x2A,0x40,0x1D,0xB9,0xC8,0xC3,0x25 -,0xE5,0x6F,0xCC,0xEC,0x72,0xCE,0xDF,0xE2,0x62,0x49,0xF9,0xEB,0x33,0x42,0x40 -,0x19,0x24,0x01,0xF5,0xD6,0x3D,0x5D,0x4A,0xC2,0xA3,0xD4,0xAA,0xCD,0x90,0xB9 -,0x04,0x92,0x71,0xEC,0xA3,0xAB,0x1F,0xA0,0xD0,0x64,0x12,0x07,0x73,0x8D,0x35 -,0xA5,0x49,0x25,0x92,0xEA,0x8A,0x30,0xF2,0x23,0x8E,0x61,0xC7,0x98,0xE8,0x3A -,0xFB,0x29,0x09,0x17,0x46,0x04,0x31,0x25,0x98,0x64,0x60,0x9D,0x6E,0xB4,0x0D -,0x71,0x7F,0xDB,0xE2,0x82,0xBA,0x74,0xDA,0xB0,0x2C,0x58,0xA6,0x96,0xDC,0x65 -,0x8D,0x81,0xEA,0x5A,0x9A,0x29,0xE4,0x90,0x63,0xE8,0xAE,0x9F,0xD7,0x5D,0x9E -,0xEC,0x15,0x0B,0x1E,0xC0,0x64,0xEB,0xF9,0xD1,0xF6,0xB2,0xF1,0x06,0xF5,0x71 -,0xDF,0xB7,0x2B,0x54,0xD5,0x55,0x51,0xB5,0xBE,0x6A,0x8B,0x6D,0xBC,0xC2,0xFC -,0x22,0x8A,0x8D,0x59,0xE1,0x9C,0x63,0xA9,0x32,0x4A,0xE8,0x51,0x98,0x70,0xFB -,0xB8,0xF8,0x9E,0x62,0x42,0x14,0x2D,0x9F,0x0A,0x21,0xB3,0xF8,0x51,0xE0,0x7D -,0xCF,0x7F,0x59,0x2D,0xD0,0x9B,0xB5,0xF2,0xB9,0xAD,0xB6,0x38,0xEA,0x5C,0x1C -,0xAF,0x9E,0xD0,0xC3,0xE6,0x3F,0x4C,0x96,0x2A,0xD3,0x48,0xC3,0x88,0x20,0x00 -,0x02,0xAA,0xAA,0xAE,0xCE,0xD3,0xE1,0x3C,0x7B,0x9A,0x35,0xB8,0xEF,0x59,0xAE -,0x5B,0xAE,0xEB,0x27,0xAA,0x4A,0xFB,0xDC,0xB2,0xC7,0x4D,0x13,0x1E,0xE2,0x9E -,0x8D,0x59,0x48,0x41,0xDB,0x0F,0xC3,0xE6,0x3A,0x74,0xD7,0xCE,0xCF,0x99,0x9B -,0xC3,0x5F,0x01,0xE0,0x1D,0x10,0xDC,0xE5,0x32,0x63,0xB7,0x34,0xA5,0xAA,0x1F -,0xF1,0x2D,0xAB,0xBA,0xA2,0x68,0x69,0xE0,0x79,0xEA,0x25,0x8E,0x18,0x90,0x65 -,0x9D,0xD8,0x2A,0xA8,0xF9,0x92,0x7B,0x6A,0xC2,0x2B,0x9B,0x4F,0x84,0x34,0x16 -,0x1A,0x74,0x1B,0x5F,0x77,0x6E,0xDB,0x0C,0xEB,0x92,0x5A,0x92,0xE1,0x98,0x5C -,0xE7,0x3D,0x60,0x75,0x31,0x60,0x76,0xC0,0x51,0xD3,0x59,0x57,0x8A,0x5F,0x10 -,0x69,0xED,0x72,0xC1,0x7D,0x93,0x65,0xEF,0xBB,0x54,0x6A,0x5E,0x48,0xEF,0x54 -,0x5F,0x03,0x27,0x10,0x3A,0xE5,0xD4,0x49,0x11,0xE9,0xEF,0xE5,0xA8,0xD6,0xFA -,0xE9,0xB8,0xCC,0x71,0x2B,0x52,0x44,0x91,0x44,0xED,0xC1,0x2A,0xAB,0x32,0x88 -,0xED,0xF2,0x8A,0x31,0xF7,0x93,0x37,0xB8,0x00,0x00,0xC3,0xB3,0x6B,0x4B,0x50 -,0x95,0xB5,0x93,0x24,0xB5,0x34,0xD5,0x75,0xF3,0x02,0x1A,0x21,0x53,0x00,0x3C -,0x4F,0x70,0x63,0xA6,0x04,0x24,0x7F,0x35,0x79,0xDB,0x9A,0x9E,0x9D,0x74,0x15 -,0xED,0xBE,0xEB,0xB3,0x2D,0xCE,0x95,0x95,0x3B,0x4F,0x7C,0xF8,0x63,0x45,0x2B -,0x94,0x4B,0xA5,0x8A,0xBE,0x59,0x68,0x24,0x7C,0xE1,0x42,0xC5,0x18,0x64,0x65 -,0x6C,0xFA,0x5B,0xC9,0xE2,0x7F,0xA6,0xA6,0x76,0xCD,0xE1,0x7D,0x37,0x2B,0x6D -,0xBB,0x67,0x78,0xA9,0xB6,0x77,0x7C,0xD5,0x75,0x0D,0x4E,0x68,0x2F,0x54,0xAB -,0x05,0x64,0x78,0x86,0x49,0x46,0x4C,0x1C,0x0A,0x93,0xE5,0xF1,0xF5,0x45,0xDD -,0x86,0xB7,0xF4,0xDB,0x7A,0xE3,0x59,0x3F,0xC5,0x57,0x55,0xB5,0x13,0xB0,0x2A -,0x64,0x8D,0xC4,0xB5,0x6C,0xA7,0xBA,0xF9,0xA4,0x05,0x88,0x11,0xDD,0x62,0x51 -,0x83,0xD4,0x36,0xBD,0x2E,0xFE,0x1E,0xEC,0x8B,0xBD,0xBD,0x68,0x2E,0x7B,0x5E -,0xD9,0x59,0x0A,0x92,0xC1,0xA5,0x80,0x34,0x9C,0x8F,0x76,0xF3,0x3F,0x1F,0x23 -,0xEE,0xD9,0xC9,0xF7,0x3A,0x60,0xC1,0x87,0xC5,0xEB,0xBD,0xB6,0x38,0x5F,0x75 -,0xF8,0x7B,0x74,0xA5,0x86,0x5A,0x68,0xEA,0x16,0xAE,0xD3,0x55,0x15,0x74,0x3C -,0x1E,0x17,0x9B,0x24,0x13,0x1C,0x83,0x09,0x14,0x84,0xFA,0x0E,0x38,0x1E,0xFD -,0x09,0x91,0x5B,0x7C,0x5A,0xF0,0xF6,0xB2,0xB0,0xD0,0xCD,0xB9,0x20,0xB5,0x57 -,0x2B,0xF0,0x6A,0x4B,0xBC,0x6F,0x41,0x32,0xBE,0x01,0xE3,0xC2,0x75,0x43,0x9E -,0xA3,0xA0,0xF9,0x8D,0x42,0xAA,0x7C,0x20,0xB5,0x45,0x0F,0x95,0x61,0xDC,0xDB -,0xA6,0xC9,0x1A,0xA1,0x48,0xE1,0x8A,0xE0,0x6A,0x61,0x45,0xF2,0xE4,0x8B,0x88 -,0x4A,0x81,0x26,0x17,0x84,0xB2,0x28,0x00,0x8C,0x07,0x38,0xD6,0x9B,0xC4,0x1B -,0x4E,0xEA,0xB3,0xD8,0xAE,0xF5,0xFB,0x83,0x77,0xED,0x0B,0xBD,0x15,0x5A,0xCC -,0x66,0x7B,0xF5,0x01,0xA5,0x3C,0xE4,0xA6,0x8A,0x05,0xF5,0x46,0x59,0x58,0x8F -,0x22,0x26,0x00,0x47,0x92,0x41,0x1F,0xCD,0xD2,0x60,0xE8,0x38,0x26,0x86,0xA2 -,0x15,0x9A,0x09,0x52,0x58,0x9C,0x65,0x5D,0x18,0x32,0xB0,0xF9,0x82,0x3B,0xEB -,0xEF,0x5C,0x8B,0x60,0xDF,0xFE,0x10,0x54,0xFC,0x45,0x49,0xDA,0x35,0xBB,0x12 -,0xA2,0x19,0x9E,0x39,0x26,0xB1,0x6E,0x48,0x28,0x59,0x19,0x4E,0x09,0x34,0xFE -,0x74,0x32,0x11,0xD3,0xB1,0x84,0x9F,0xA6,0xA5,0x34,0x7E,0x20,0xD6,0x43,0xB8 -,0xAD,0xB4,0x3B,0x67,0xC6,0x15,0x36,0xFA,0xF8,0xA1,0x7A,0x64,0xDE,0x16,0x80 -,0xA5,0xF9,0xA4,0xEF,0x91,0x27,0x18,0x19,0x93,0xEE,0xE2,0x00,0xE5,0xB3,0xE6 -,0xAE,0x09,0xC8,0xD0,0xC7,0x48,0xE9,0xAA,0xEE,0x2B,0xF7,0x8A,0xF4,0x11,0xAB -,0xD6,0xEC,0xBB,0x06,0xE2,0x81,0x87,0x25,0x9E,0xC9,0x78,0xF2,0x9D,0x87,0xD2 -,0x3A,0x84,0x0B,0xFF,0x00,0xDC,0x3A,0xF9,0x9B,0xC6,0x0D,0xBF,0x6C,0x60,0xBB -,0xB6,0xC9,0xB9,0xF6,0xA6,0x4E,0x0C,0xB7,0x3B,0x5B,0x9A,0x70,0x7F,0xED,0xE1 -,0xF3,0x23,0xC7,0xD4,0xB0,0xD0,0x58,0xDA,0x6B,0x12,0xCF,0x74,0xB6,0xDE,0x6D -,0xF1,0x5C,0x6D,0x17,0x0A,0x5B,0x85,0x1C,0xA3,0x31,0xCF,0x4D,0x32,0xC9,0x1B -,0x8F,0xA3,0x29,0x20,0xEB,0x2F,0x44,0x35,0x8D,0x52,0x2B,0x24,0x6F,0x2E,0x06 -,0x48,0x13,0xF9,0xA5,0x61,0xC9,0xBF,0xDD,0x5E,0xDF,0x3E,0xA7,0xB1,0x1F,0x84 -,0xEB,0xF2,0xA2,0xBE,0x18,0xE5,0x30,0x44,0xB2,0x54,0xD4,0x2F,0x78,0xA1,0x00 -,0x95,0xF7,0xF5,0x13,0x80,0xBD,0x3A,0x8E,0x44,0x67,0xDB,0x3A,0xC1,0xB8,0xD0 -,0x56,0x5C,0x22,0x22,0xBE,0xE9,0x2D,0x05,0x28,0xEB,0x24,0x54,0x52,0x79,0x6C -,0xEB,0x82,0x08,0x69,0x88,0x0E,0x07,0x50,0x41,0x8F,0xCB,0x60,0x47,0xE2,0x23 -,0x41,0xFA,0x24,0xB7,0x51,0x56,0xB4,0x71,0xF9,0xB7,0x0B,0xA0,0x4F,0x58,0x52 -,0x24,0x98,0x02,0x33,0xD4,0x9C,0x2C,0x4A,0xDC,0x49,0x00,0xF1,0x52,0x41,0xC7 -,0x5D,0x64,0x48,0x95,0x12,0x44,0xF2,0xD7,0xD4,0xA5,0x2C,0x0A,0x09,0x64,0x86 -,0x42,0x30,0x3A,0xF5,0x69,0x0E,0x0F,0x6C,0x1F,0x4F,0x1C,0x1C,0xF5,0x23,0x5F -,0x94,0x50,0x45,0x49,0x4D,0xF0,0xB6,0x9A,0x28,0x69,0x61,0x05,0x9B,0x91,0x4E -,0x2B,0xC8,0x92,0x4B,0x71,0x18,0x2C,0x4B,0x75,0x24,0xE3,0x39,0xCE,0x4E,0xBD -,0x5A,0x9E,0x08,0xB3,0x55,0x59,0x2F,0x98,0x63,0xCB,0xF9,0x93,0x10,0x16,0x3C -,0x64,0xE4,0x0E,0xCB,0x80,0x4F,0x5E,0xF8,0xEE,0x4E,0x83,0xCE,0x27,0x6E,0x06 -,0x1B,0x65,0x22,0x45,0x1E,0x49,0xF3,0x5D,0x38,0x26,0x49,0x39,0x21,0x7B,0xB9 -,0xCE,0x0F,0xB0,0x39,0xCF,0x2D,0x7B,0x25,0x22,0x06,0x13,0x54,0xC8,0xD3,0xC8 -,0xA7,0x90,0x67,0xFC,0x29,0xDF,0xF0,0xAF,0x61,0x8C,0x9E,0xBD,0xF1,0xDC,0x9D -,0x79,0x2D,0x74,0x95,0x5D,0x2D,0xF0,0xF3,0x43,0xFF,0x00,0x48,0x93,0x2B,0x1F -,0xEA,0xBE,0xEF,0xEC,0x46,0x30,0xA4,0x7F,0x36,0xBD,0xA1,0xA6,0xC1,0x12,0x54 -,0x4A,0xD3,0xC9,0xDF,0x2C,0x30,0xAA,0x7F,0xC2,0xBD,0x87,0xD0,0x9C,0x9F,0xA9 -,0xD0,0x7B,0xAB,0x06,0x19,0x1D,0x47,0xCF,0x5F,0xBA,0x69,0xA0,0x69,0xA6,0x9A -,0x0F,0x39,0x51,0xA4,0xE9,0xE6,0x32,0x2F,0xBF,0x1E,0x84,0xFE,0xFE,0xDF,0xB7 -,0x5F,0xAE,0x94,0xF0,0x43,0x02,0x91,0x0C,0x6A,0x9C,0x8E,0x58,0x8E,0xEC,0x7E -,0x64,0xF7,0x27,0xEA,0x75,0xE9,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x68,0x48,0x00 -,0x92,0x40,0x03,0xB9,0x3A,0xAA,0xF7,0x37,0x8D,0x36,0x51,0x7D,0x6D,0xAB,0xB0 -,0xE8,0xE4,0xDE,0x7B,0x97,0xB3,0x41,0x40,0x4B,0x53,0x53,0x7B,0x72,0x9A,0x65 -,0x0C,0x00,0x1E,0xE1,0x43,0x1E,0x98,0x20,0x68,0xAB,0x2E,0xEB,0x71,0xA0,0xB4 -,0xDB,0xA7,0xB8,0xDD,0x2B,0x69,0xE8,0xA8,0xE9,0xD0,0xBC,0xD3,0xCF,0x20,0x48 -,0xE3,0x5F,0x99,0x63,0xD0,0x6A,0xAE,0xAE,0xDE,0xD7,0x8D,0xEB,0x17,0x0D,0xAF -,0x59,0x2E,0xD6,0xDB,0x73,0xE5,0x22,0xBF,0xD4,0xD1,0x99,0x2B,0x2E,0x27,0xDD -,0x6D,0xF4,0x84,0x73,0x71,0x8F,0xF4,0xAC,0xA7,0xFC,0x2A,0x71,0x91,0xAE,0x8B -,0x6A,0x5C,0xB7,0x15,0xE1,0x6B,0xF7,0xED,0xC5,0xB7,0x05,0xD6,0x8D,0xFC,0xC5 -,0xB5,0x51,0x47,0x1B,0xD2,0x5B,0x1C,0x0C,0xF5,0x46,0x26,0x9E,0x27,0x5F,0xCD -,0x3B,0x4A,0xEC,0xBD,0x55,0x54,0xF4,0xD4,0xB2,0x1F,0x22,0x2A,0x79,0x2B,0xD2 -,0x68,0x44,0x53,0x62,0x39,0x2A,0x21,0xAD,0x78,0xA1,0x9B,0xF2,0xA3,0xD7,0xB8 -,0xF3,0xEA,0x3B,0x7A,0x56,0x05,0x00,0x1F,0x49,0x18,0xD0,0xC4,0x6B,0x69,0x6D -,0x3D,0xB9,0xB2,0x25,0xAC,0x9E,0xD5,0x41,0x57,0x1D,0xC3,0x26,0xAE,0xBA,0xE3 -,0x73,0x95,0x6E,0x17,0x87,0x3C,0x49,0x33,0x3F,0x23,0xE4,0x52,0x65,0x72,0x44 -,0x92,0x11,0x91,0x90,0x50,0x1D,0x52,0xD4,0x94,0x75,0xFF,0x00,0x68,0x1F,0x16 -,0xA0,0xDC,0x97,0x1B,0x1C,0xA9,0xB1,0xB6,0xEA,0xF2,0x90,0xD7,0xD6,0xAA,0x07 -,0x24,0x07,0x02,0xA2,0x77,0xC9,0x1E,0x66,0x03,0x15,0x45,0x21,0x10,0xA8,0x00 -,0x72,0x2D,0xAD,0xDF,0x8A,0xFB,0x9E,0xA7,0x7A,0x6E,0x6A,0x4F,0x0B,0xF6,0x9D -,0x7D,0x54,0x70,0x25,0x53,0xC3,0x5B,0x14,0x14,0x4F,0x47,0x46,0xF2,0x85,0xCB -,0xC7,0xF0,0xE9,0x99,0x24,0x8D,0x01,0xE7,0x28,0x93,0x93,0x33,0xF0,0x45,0x55 -,0xE4,0x4E,0xAF,0x1F,0x0B,0xFC,0x34,0x7D,0xB3,0xB6,0xE8,0x6D,0x14,0x86,0x60 -,0x94,0xCE,0xD3,0x1B,0x85,0xD1,0x52,0x5A,0x97,0x99,0x98,0xB3,0xCB,0x1D,0x3A -,0xFD,0xDC,0x4E,0x49,0x24,0x48,0xE5,0xDC,0x0F,0x4B,0x02,0x00,0xD1,0x5F,0xB5 -,0xBE,0x40,0xB5,0xD3,0x53,0xB8,0xA3,0x86,0xD0,0xB8,0x8A,0x96,0x29,0x29,0x5A -,0x9A,0xDA,0x7E,0x49,0x05,0x1A,0x7D,0xED,0x61,0xFF,0x00,0x0B,0x10,0x8D,0xD1 -,0x93,0xE5,0xAD,0xB5,0xB2,0xD9,0x5F,0x51,0x55,0x15,0x49,0x8E,0xA9,0x27,0x8D -,0x7E,0xEA,0xA2,0xB5,0x23,0x92,0xB1,0x57,0x07,0x1E,0x4C,0x03,0x10,0xD2,0x29 -,0x03,0x01,0x98,0x72,0x20,0x61,0x97,0x3D,0x75,0x26,0xA0,0xDB,0x54,0x94,0x75 -,0xAD,0x5A,0x92,0xCD,0x35,0x53,0xA7,0x19,0x2A,0x66,0x6E,0x55,0x12,0x83,0xDD -,0x4C,0x87,0x25,0x53,0x38,0x21,0x23,0xE0,0xA0,0xE7,0x03,0xAE,0x35,0xF5,0x74 -,0xA4,0x81,0x61,0xE1,0x55,0x34,0x6E,0xB2,0x72,0x09,0x4E,0x63,0x26,0x36,0x38 -,0x62,0x7E,0xE9,0x7D,0x52,0x92,0x0E,0x48,0x24,0xF6,0xC8,0x03,0x41,0xAE,0x88 -,0xD2,0xC5,0x4D,0x34,0xBF,0x15,0x98,0x87,0x49,0xEA,0x45,0x51,0x54,0xEE,0x47 -,0xAE,0xA9,0xBA,0x9E,0xA3,0xF0,0xC7,0x8E,0x27,0xA1,0xE9,0xAC,0xDA,0x39,0xA3 -,0xA7,0x82,0x38,0x69,0x69,0xE3,0xA5,0x85,0x99,0x8C,0x7C,0xA9,0xCC,0x41,0xDB -,0x24,0xB7,0x08,0x07,0xAD,0x8E,0x72,0x4F,0x2C,0x7E,0x61,0x91,0xAC,0x49,0x69 -,0xCF,0xC6,0x07,0x3E,0x7C,0x95,0xA8,0x09,0x8C,0xB0,0x49,0xAA,0x63,0x04,0x38 -,0x1C,0x17,0xFB,0x98,0x32,0x06,0x03,0x1F,0xC4,0x3A,0x37,0x5D,0x6C,0x28,0xED -,0x12,0x73,0x91,0xE6,0x7F,0x87,0x12,0x74,0x71,0x0C,0xAC,0xD2,0xC8,0x32,0xD8 -,0x0F,0x31,0xF5,0x63,0xD5,0x90,0x17,0x8F,0x13,0x90,0x09,0x1A,0x04,0xB3,0xD4 -,0x34,0xC6,0x14,0x69,0x16,0x50,0x3A,0x85,0xE3,0x24,0xE3,0x20,0xE3,0xA7,0xF7 -,0x71,0x76,0xE8,0x4E,0x43,0x76,0xC6,0x75,0x91,0x05,0xBD,0x89,0x66,0x95,0xCC -,0x41,0xBF,0x12,0xC5,0x23,0x17,0x6E,0xA7,0x1C,0xA4,0x3E,0xA2,0x3A,0xE4,0x01 -,0x8C,0x75,0x1D,0x46,0xB3,0xA9,0xE1,0x86,0x9E,0x21,0x14,0x11,0x24,0x48,0x09 -,0x3C,0x51,0x70,0x32,0x4E,0x49,0xFE,0xBA,0xFB,0xD0,0x7C,0x43,0x14,0x50,0x44 -,0x22,0x86,0x34,0x8E,0x35,0xEC,0xA8,0xA0,0x01,0xFB,0x0D,0x7D,0xE9,0xA6,0x83 -,0xCA,0xB7,0xAD,0x1C,0xC0,0xFF,0x00,0xAB,0x6F,0xF8,0x6B,0xF9,0x59,0xE3,0xBD -,0xD2,0x86,0xED,0xBD,0x5E,0xA2,0x96,0x7F,0x36,0x71,0x2D,0x79,0xAC,0x1C,0x18 -,0x70,0x95,0xEE,0x55,0x92,0x81,0x92,0x30,0x73,0x1C,0x91,0xB6,0x46,0x47,0xAB -,0x1D,0xC1,0x03,0xFA,0x97,0x7C,0xAA,0x8E,0x8E,0xD9,0x24,0xF3,0x7F,0x74,0x0A -,0x2B,0xFD,0x15,0x98,0x29,0x3F,0xD0,0xEB,0xF9,0x27,0xBF,0xE2,0x78,0xB7,0x21 -,0x79,0x57,0x0F,0x53,0x45,0x47,0x56,0xDF,0xAC,0xD4,0xB1,0x4B,0xFF,0x00,0xBF -,0x41,0xD7,0x3B,0x5A,0xAD,0x6B,0xBC,0x20,0xD8,0x95,0x7B,0x7E,0xBA,0x98,0x2D -,0xB7,0x7E,0x54,0xD3,0x51,0xD5,0xD4,0x53,0xBB,0x46,0x62,0x9D,0xAA,0xC4,0x4C -,0x63,0xCA,0x36,0x08,0x9E,0x3C,0x02,0x54,0xF5,0x19,0xC6,0xAF,0x0A,0x1B,0x3C -,0x71,0x32,0x4F,0x5D,0x53,0x35,0xCA,0xB1,0x7A,0x89,0xEA,0x31,0xE8,0x3F,0x34 -,0x40,0x02,0xA7,0xEA,0x06,0x7E,0x64,0xEB,0x93,0xFC,0x32,0xBE,0x54,0xD5,0xF8 -,0x15,0x7C,0xF2,0x56,0xE3,0x4C,0x96,0x49,0xED,0x97,0xC8,0x29,0x62,0xA5,0xF8 -,0x88,0x99,0x69,0xCC,0x71,0xC9,0x29,0x75,0x4E,0x51,0x96,0x6A,0x39,0x5B,0xA9 -,0xE2,0x01,0xC7,0xF8,0x8F,0x61,0x46,0xE9,0x24,0x6B,0x24,0x6C,0x19,0x18,0x06 -,0x56,0x07,0xA1,0x07,0xB1,0xD5,0x84,0x96,0x35,0x3D,0xBA,0x8E,0x0A,0xA7,0xAB -,0x48,0x15,0xAA,0x9C,0x71,0x69,0xDF,0xD5,0x21,0x1D,0xF8,0xF2,0x3D,0x42,0xE7 -,0xF9,0x47,0x4F,0xA6,0xB2,0xB4,0xD6,0xA7,0x72,0xEE,0x4B,0x1E,0xDC,0xA6,0x49 -,0xEF,0x57,0x28,0x69,0x3C,0xD6,0xE3,0x0C,0x67,0x2D,0x2C,0xCD,0xF9,0x63,0x8D -,0x72,0xCE,0xDF,0x45,0x04,0xEA,0xA3,0x6D,0xAD,0x5E,0xE7,0xDC,0x56,0x2D,0xB3 -,0x6D,0x6B,0x8D,0xFE,0xEB,0x4B,0x6E,0xA5,0x5E,0x81,0xE7,0x90,0x2F,0x23,0xF9 -,0x54,0x77,0x66,0xFA,0x00,0x4E,0xB9,0xCF,0xC4,0xAF,0xB4,0xDD,0x33,0x43,0x53 -,0x4D,0xB4,0xAA,0x63,0xA2,0x44,0xF4,0xAC,0xED,0x00,0xA8,0xAA,0x98,0xB4,0x65 -,0x95,0x91,0x7F,0xB9,0x8D,0x33,0xC5,0x4B,0x3B,0x3B,0xA9,0x6F,0xEE,0x89,0x04 -,0x0E,0x6C,0xDE,0x1B,0xE2,0xF5,0xB8,0xEE,0x53,0x55,0xCF,0x55,0x55,0xCA,0x4E -,0x4A,0x65,0x9A,0xA0,0xCD,0x52,0xE8,0x79,0x8E,0x2D,0x29,0xC6,0x01,0x47,0xE2 -,0xC9,0x18,0x8E,0x36,0xC0,0x3C,0x01,0xD4,0xD5,0xC7,0x4A,0x78,0xB3,0xF6,0x9D -,0x6A,0x43,0x3D,0xBB,0x67,0xD2,0x0A,0x49,0x17,0x92,0x1A,0xAA,0xC8,0xB9,0xCF -,0xC8,0x73,0x1D,0x20,0xCE,0x23,0xC3,0xA0,0x07,0xCD,0x21,0x80,0x60,0x7C,0xB2 -,0x35,0xCE,0xDB,0xAF,0xC4,0x9D,0xC9,0xB8,0x2A,0x26,0x9A,0xA6,0xB2,0x67,0x9A -,0x50,0xC8,0x6A,0xAA,0x24,0xF3,0xAA,0x42,0x12,0x0F,0x15,0x72,0x00,0x84,0x74 -,0xC7,0xDC,0xAC,0x7C,0x95,0x88,0x6E,0x40,0xEA,0x19,0xA6,0xA2,0x9A,0xCC,0xB5 -,0xDD,0x2E,0x76,0xB7,0x99,0xED,0x97,0x1A,0xBA,0x16,0x9E,0x23,0x0C,0xCD,0x4F -,0x33,0x46,0x64,0x8C,0x90,0x4A,0x37,0x12,0x32,0xA4,0xA8,0x38,0x3D,0x3A,0x0F -,0x96,0xBE,0xAD,0x76,0xAA,0xEB,0x9F,0x33,0x4B,0x12,0xF9,0x51,0xF4,0x92,0x69 -,0xA5,0x58,0x61,0x8C,0xF1,0x66,0x01,0xA4,0x72,0x11,0x49,0x08,0xDC,0x41,0x39 -,0x62,0x30,0x32,0x7A,0x6A,0x43,0x41,0xB2,0xA5,0xA9,0xA7,0x9C,0x7C,0x45,0x64 -,0xD5,0x6B,0x49,0x15,0x54,0x69,0x4D,0x42,0x7C,0xA5,0x57,0x04,0x91,0x2C,0x93 -,0x34,0x5C,0x71,0x8C,0x02,0x82,0x45,0x6C,0x36,0x0E,0x00,0x24,0x3A,0x87,0xEC -,0x9D,0xB2,0xA8,0x77,0x33,0x4D,0x71,0xB8,0xD5,0x5D,0x68,0x1E,0xB6,0x29,0x67 -,0x41,0x68,0xB8,0x4D,0x6F,0x44,0x61,0x0D,0x0B,0x16,0x58,0xE0,0x64,0x40,0x0B -,0xCF,0x37,0xA7,0x8F,0x1F,0x90,0xC0,0x1A,0xF7,0xDF,0xDB,0xC3,0x7D,0xEC,0xDF -,0x15,0x2E,0xDB,0x73,0x6A,0x6F,0xCB,0x85,0x75,0x9E,0xD6,0x90,0x47,0x32,0x5E -,0xE9,0xA1,0xAD,0xE7,0x50,0xE9,0xE6,0x3A,0x07,0x55,0x47,0xE2,0xA8,0xD1,0x8E -,0xAC,0x4E,0x49,0xEB,0xF2,0x84,0xF8,0x47,0xE2,0xB6,0xFA,0xD9,0x16,0xAF,0x80 -,0xB5,0x6C,0x8A,0x5A,0x1A,0x34,0x76,0xF8,0x5A,0xBB,0xAD,0x2D,0x55,0x54,0xD1 -,0xC0,0x52,0x24,0xF2,0xC8,0x80,0x27,0x23,0xF7,0x2A,0xC5,0x8A,0xA8,0xEF,0x80 -,0x3B,0x6B,0x41,0x59,0x45,0x79,0xDC,0xF7,0x9B,0xE5,0xE6,0xA6,0xE3,0x43,0x7C -,0xA7,0xB9,0xD6,0x4B,0x55,0x55,0x4F,0x6A,0xAB,0x34,0xB2,0x24,0xB2,0x31,0x2C -,0x84,0x30,0x27,0x00,0x61,0x42,0xB3,0xAF,0x41,0xD7,0x3A,0x0B,0x23,0x63,0xF8 -,0x99,0x63,0xBA,0x6E,0xF1,0x44,0x86,0x93,0xC3,0xFD,0xD2,0xF5,0x1E,0x5A,0x5D -,0x6D,0x71,0x73,0xB3,0x5D,0x25,0x20,0x7D,0xCD,0x54,0x24,0x80,0x1F,0xA8,0x19 -,0xE5,0xC9,0x4F,0x69,0x07,0x63,0xD1,0xDB,0x23,0x76,0x25,0xF6,0xA2,0xE3,0x65 -,0xB9,0x53,0x2D,0xBB,0x71,0x5A,0x5D,0x63,0xB8,0xD0,0x89,0x39,0x28,0x0C,0x32 -,0x93,0x44,0xD8,0x05,0xE2,0x71,0xD5,0x5B,0x00,0xF7,0x04,0x02,0x08,0xD7,0x21 -,0x59,0xD3,0x6C,0xCF,0x47,0xFD,0x99,0x9A,0x8E,0x4B,0x7C,0x6D,0x1F,0x94,0xB6 -,0xCA,0xD8,0xCC,0x6F,0x22,0x8E,0xBD,0x1C,0x93,0xE6,0xE0,0x8C,0xE5,0x18,0x81 -,0xAB,0x22,0xC5,0xB8,0x2A,0x68,0x36,0xBA,0x6F,0x19,0x1E,0x4A,0x9D,0xC5,0xB0 -,0x26,0x8A,0x96,0xE3,0x39,0x39,0x96,0xE5,0x62,0x98,0xFF,0x00,0xA4,0xFC,0xC5 -,0x07,0x26,0xC9,0xFE,0x7A,0x76,0x3F,0xCC,0x74,0x47,0x48,0x29,0x9C,0x01,0x05 -,0x05,0x2C,0x54,0xF0,0xAE,0x7E,0xF2,0x45,0xC2,0x8F,0xF6,0x50,0x60,0x9E,0xB9 -,0xCE,0x4A,0xFC,0xC6,0x75,0xEE,0xB0,0xC7,0x18,0xF3,0x66,0x90,0xC8,0x57,0xAF -,0x39,0x08,0xF4,0xF7,0xEB,0xEC,0x07,0x43,0xDC,0x0F,0xD7,0x5E,0x91,0xBA,0xC9 -,0x1A,0xC9,0x1B,0x2B,0x23,0x00,0x55,0x81,0xC8,0x20,0xFB,0xEB,0xE5,0xA1,0x47 -,0x60,0xD2,0x8F,0x30,0x83,0x90,0x1B,0xB0,0x3F,0x30,0x3E,0x7F,0x5E,0xFA,0x23 -,0x19,0xAA,0xA6,0x9F,0xD3,0x41,0x08,0x70,0x7F,0xD3,0xCB,0x95,0x8C,0x7D,0x47 -,0xBB,0xF7,0xC8,0xC6,0x01,0xFC,0xC3,0x5F,0x31,0xDB,0x23,0x79,0x92,0xA2,0xBE -,0x46,0xAD,0x99,0x08,0x64,0xF3,0x07,0xDD,0xC6,0x47,0x50,0x51,0x3B,0x02,0x0E -,0x70,0xC7,0x2C,0x33,0x8E,0x47,0x59,0xFA,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A -,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x8A,0x6F,0x6F,0x10,0x36,0xDE,0xD4,0xA8 -,0x86,0xDF,0x59,0x3C,0xF5,0xD7,0x9A,0x81,0xFF,0x00,0x25,0xB4,0x5B,0xA2,0x35 -,0x15,0xB5,0x1F,0xEC,0xC4,0xBD,0x40,0xFF,0x00,0x13,0x61,0x7E,0xBA,0x09,0x5E -,0xA0,0x5B,0xCB,0xC5,0x0B,0x3D,0x9A,0xEC,0x76,0xDD,0x86,0x8A,0xB3,0x76,0x6E -,0x92,0x3D,0x36,0x7B,0x50,0x0E,0xF1,0xFD,0x67,0x93,0xF0,0x40,0xBD,0xB2,0x5C -,0xE7,0xAF,0x63,0xAC,0x48,0xF6,0xCF,0x88,0xFE,0x20,0x7A,0xF7,0x55,0xC2,0x4D -,0x8D,0xB7,0x9F,0xFF,0x00,0xA4,0x5A,0xAA,0x03,0xDC,0x6A,0x17,0xE5,0x3D,0x48 -,0xF4,0xC4,0x0F,0xBA,0x45,0x93,0x82,0x41,0x7D,0x58,0x7B,0x3F,0x67,0xED,0x9D -,0xA1,0x65,0x16,0x7D,0xB5,0x65,0xA5,0xB6,0x51,0x67,0x2E,0x90,0xAE,0x1A,0x53 -,0xF9,0x9D,0x8F,0xA9,0xDB,0xE6,0x58,0x92,0x74,0x5C,0x52,0xF5,0xFB,0x0F,0x7B -,0x6F,0xE9,0x59,0xFC,0x4C,0xBE,0x4C,0x68,0x7B,0xFF,0x00,0x65,0x36,0xDC,0xE6 -,0x1A,0x54,0x1F,0x96,0xB2,0xB0,0xE0,0xBE,0x3A,0x72,0x55,0xEB,0xEE,0xA0,0xEA -,0x57,0x66,0xDB,0xD4,0x56,0x3B,0x28,0xB5,0xD8,0xED,0x54,0x54,0x16,0xA5,0xEF -,0x4B,0x6D,0xE5,0x49,0x40,0x4F,0xB7,0x39,0x80,0xF3,0xEB,0x1C,0xF5,0x1E,0x80 -,0x15,0xFB,0x30,0x07,0x56,0x25,0xDA,0xE7,0x6B,0xA0,0x31,0xD1,0x3C,0x66,0xA6 -,0xA4,0xA8,0x31,0x50,0xD3,0xC5,0xE6,0x48,0xC3,0xB0,0x3C,0x07,0x45,0x5C,0xF4 -,0xE4,0xD8,0x51,0xEE,0x46,0xB1,0xC5,0x25,0xEE,0xEC,0x43,0xDC,0x26,0xFE,0x11 -,0x4A,0x7B,0x53,0x52,0xBF,0x2A,0x86,0x07,0xD9,0xE6,0xEC,0x99,0x1D,0xC4,0x7D -,0x41,0x19,0x12,0x1D,0x15,0x03,0x96,0x9A,0x69,0x9E,0x1B,0x6C,0x90,0x8C,0x46 -,0xA1,0xA9,0xE8,0x85,0x1A,0xFA,0x57,0x3D,0x1A,0x1A,0x05,0x3C,0x22,0x5C,0xF5 -,0x59,0x6A,0x98,0x95,0x6E,0xE0,0x67,0x55,0xF7,0xDA,0x77,0x75,0xDD,0x36,0x3E -,0xD1,0x14,0xB6,0xEA,0xA9,0xE1,0xDD,0xB7,0xA8,0xDA,0x3A,0x4F,0x2A,0x61,0x3D -,0x7C,0x70,0x92,0x03,0xCA,0xD2,0x91,0x88,0x81,0x2C,0x11,0x62,0x85,0x54,0x79 -,0x8C,0x38,0xB1,0x00,0x8D,0x5F,0x1B,0x8E,0xE9,0xB6,0xBC,0x3B,0xD9,0x97,0x2B -,0xFD,0x70,0x8A,0xDF,0x6B,0xA1,0x89,0xAA,0x2A,0x19,0x47,0xAA,0x46,0xED,0xDC -,0xF5,0x79,0x18,0xE0,0x64,0x9C,0xB1,0x23,0xAE,0xB9,0xD3,0xEC,0xD1,0xB7,0x6F -,0x1E,0x2E,0x78,0x91,0x71,0xF1,0xDF,0x7C,0xD2,0x81,0x46,0x2A,0x4A,0x6D,0xEA -,0x39,0x17,0x92,0xA7,0x97,0x95,0x56,0x04,0x8F,0xC3,0x1E,0x48,0x18,0xE8,0xD2 -,0x16,0x6E,0xEA,0x34,0x16,0x57,0xD9,0x67,0xC2,0x6F,0xFE,0x1D,0x6C,0xF5,0xB8 -,0xDE,0xA2,0x56,0xDD,0x17,0x38,0x94,0xD5,0x92,0x79,0x1A,0x58,0xB3,0xC9,0x69 -,0xD4,0xFD,0x09,0x2C,0xE7,0xF9,0x9C,0x93,0xD7,0x03,0x57,0x26,0x9A,0x68,0x3C -,0xEA,0x18,0x84,0x21,0x4B,0x86,0x23,0xA7,0x00,0x0B,0x7E,0xD9,0xE9,0xFD,0x7A -,0x6B,0x0D,0x2D,0xE5,0xDD,0xD9,0xDD,0xA1,0x0E,0x30,0xFE,0x5B,0x9F,0x31,0xC7 -,0x5E,0x8D,0x27,0x70,0x3A,0xE4,0x05,0xC6,0x0F,0x63,0x8D,0x6C,0x34,0xD0,0x79 -,0xD3,0xC1,0x0D,0x3C,0x7E,0x5C,0x11,0x24,0x69,0x92,0xD8,0x51,0x80,0x49,0x39 -,0x27,0xF5,0x27,0xAE,0x75,0xE9,0xA6,0x9A,0x06,0x9A,0x69,0xA0,0x69,0xAF,0x99 -,0xA4,0x8E,0x18,0xDA,0x59,0x64,0x58,0xD1,0x7A,0xB3,0x31,0xC0,0x1F,0xBE,0xB4 -,0x97,0x4B,0xBB,0x07,0x4A,0x68,0x5A,0x58,0x1E,0x60,0x7C,0xA4,0x58,0xF9,0x55 -,0x4A,0x31,0xDD,0x23,0x3D,0x10,0x02,0x46,0x5E,0x4C,0x00,0x47,0x51,0x82,0x0E -,0x83,0x55,0xE3,0x75,0xCE,0x1B,0x47,0x84,0x7B,0xAE,0xE7,0x2C,0xAA,0x8D,0x49 -,0x6A,0x9A,0x64,0xC9,0xEF,0x20,0x52,0x63,0x1F,0xBB,0x00,0x35,0xFC,0xB0,0xDE -,0x94,0xF3,0xD1,0x6E,0xCB,0xA5,0xBA,0xA2,0xA2,0x4A,0x86,0xA1,0xAA,0x7A,0x35 -,0x77,0x90,0xB9,0xE1,0x09,0xF2,0xD1,0x41,0x3E,0xC1,0x51,0x40,0x1D,0x80,0x00 -,0x0E,0x9A,0xEC,0x5F,0xB6,0x8F,0x88,0x14,0x56,0xD8,0xAD,0xFB,0x16,0xDF,0x2D -,0x14,0x13,0x89,0x3F,0x8B,0xDE,0x7C,0xE6,0x69,0xC3,0xF9,0x68,0xC6,0x9E,0x96 -,0x66,0x53,0xC9,0xDA,0x56,0x00,0x10,0x0F,0xA5,0x42,0x9C,0x84,0xEA,0x38,0x8F -,0x41,0x36,0xD8,0x7B,0xC2,0x3B,0x60,0x86,0xDD,0x5C,0xAA,0x91,0xC9,0x1B,0xD0 -,0x3D,0x5C,0x87,0x9A,0xC7,0x45,0x31,0x63,0x24,0x25,0x4A,0x48,0x54,0x73,0x6E -,0x62,0x48,0xD7,0x9A,0xF3,0x97,0x2B,0x2E,0x55,0x47,0x4C,0x78,0x55,0xE3,0xFD -,0x82,0xC3,0xB1,0x6D,0x96,0x7D,0xED,0x52,0xBF,0x1D,0x49,0x4E,0x91,0xC1,0x51 -,0x45,0x53,0x15,0x52,0xD4,0xC2,0x17,0xEE,0xD9,0xB8,0xBF,0x28,0xE4,0xE3,0x80 -,0xCB,0x20,0x52,0x08,0xEA,0x01,0x24,0x0E,0x31,0xD3,0x41,0xD6,0x3E,0x24,0x7D -,0xA6,0x65,0x9C,0xD4,0xD2,0x6D,0xC9,0x92,0xCF,0x4F,0x1F,0xA4,0x3A,0x2A,0x55 -,0xD6,0xCE,0x4C,0x65,0x94,0xA1,0x04,0xD3,0xC4,0x99,0xC2,0xB3,0x17,0x91,0xD4 -,0xB6,0x44,0x64,0x82,0x07,0x36,0xEE,0x6D,0xDD,0x7D,0xDC,0x15,0x33,0xCB,0x5D -,0x5F,0x50,0xE2,0xA0,0x71,0x98,0xBC,0xAC,0xEF,0x30,0xF4,0x1C,0x49,0x21,0xF5 -,0x38,0xE4,0x8A,0xC1,0x49,0xE2,0xAD,0x92,0xAA,0xA0,0xE3,0x5A,0x0D,0x34,0x0D -,0x34,0xD6,0x5D,0x9E,0x82,0x5B,0x9D,0xC1,0x28,0xE1,0x96,0x9E,0x16,0x65,0x77 -,0x32,0x4F,0x28,0x8D,0x11,0x51,0x4B,0x31,0x24,0xFC,0x95,0x4F,0x41,0x96,0x27 -,0x01,0x41,0x24,0x02,0x18,0x9A,0xDB,0xD1,0x53,0x53,0xC6,0x0D,0x33,0xDB,0xAA -,0x6B,0xEE,0x6E,0xE5,0x44,0x0A,0x4F,0x08,0x97,0x89,0x07,0x2A,0xBE,0xA6,0x93 -,0x24,0x10,0x32,0x02,0x94,0xC3,0x07,0xE4,0x55,0x7A,0x3B,0xC1,0x0F,0x06,0xAD -,0xED,0xB7,0xE8,0x2F,0x97,0x6E,0x48,0x6A,0xE9,0xD9,0xC3,0xC1,0x33,0xAC,0xD5 -,0x31,0x4C,0xA3,0x2A,0x58,0x1F,0xBA,0x8C,0xAF,0x40,0x17,0x12,0x30,0x67,0xE6 -,0xC1,0x5C,0xC4,0xB6,0x6C,0xFB,0x83,0xC3,0xDD,0x87,0x24,0x36,0x1A,0x53,0x43 -,0x45,0x57,0x21,0x0B,0x15,0xB6,0xDB,0x4A,0x65,0xA8,0x91,0x8F,0x61,0xE5,0x44 -,0xA5,0x89,0x3F,0x32,0x3A,0xEA,0xE2,0x6B,0x9D,0x28,0xAD,0xB6,0xB9,0xA9,0x54 -,0xD6,0x4F,0x43,0x6A,0xA9,0x55,0x3C,0x16,0xE1,0x6A,0x96,0x61,0x4C,0xAC,0x4C -,0x84,0x62,0x64,0x48,0x00,0xEA,0xCD,0xC5,0x23,0x41,0xDC,0xE4,0xF7,0xD4,0xA6 -,0xD9,0xB4,0x2C,0x97,0x0A,0x21,0x35,0x0D,0xCE,0xCF,0x71,0xC0,0xC1,0x78,0xED -,0x34,0x26,0x3C,0xFF,0x00,0xDD,0x46,0xAC,0x3F,0x67,0xCF,0xD7,0x56,0x4E,0xE0 -,0xB9,0x5C,0x2A,0xEB,0x65,0x75,0xD9,0x5B,0xC2,0x44,0x9C,0x3C,0xFE,0x59,0xB4 -,0xB8,0x72,0x9F,0x0D,0x24,0x27,0xD3,0xF8,0xBF,0x13,0xAF,0xB7,0x4E,0x43,0x51 -,0x8B,0xC0,0xD9,0x3B,0x93,0x72,0x47,0x4C,0xD1,0x49,0x6B,0xBE,0x49,0x53,0x27 -,0x49,0x21,0x92,0xDF,0x5D,0x87,0xAA,0xA7,0x19,0x05,0x82,0xB3,0x1F,0x2F,0xCC -,0xE9,0xD7,0x03,0x3A,0x08,0xE0,0xB6,0xDC,0x76,0xE4,0xCB,0xF0,0xAB,0x52,0x88 -,0x3B,0x2D,0xAA,0x67,0x9D,0x71,0x9E,0xED,0x47,0x3B,0x31,0xC6,0x7B,0x98,0xE6 -,0x53,0xF4,0xD7,0xCD,0x6C,0xF4,0xD7,0x99,0x1A,0xAA,0xBA,0x1A,0x58,0x61,0x85 -,0x42,0x35,0xFE,0xDB,0x33,0xA4,0xF4,0xAF,0x9C,0x70,0x99,0x19,0x44,0x94,0xF9 -,0xEB,0xFD,0xE6,0x53,0xDB,0x27,0xBE,0xA5,0x54,0xB6,0x9D,0xD3,0x62,0xB0,0xD1 -,0x5D,0xEA,0x17,0xFB,0x41,0x6A,0xAA,0xA6,0x8A,0xA2,0x59,0xE9,0xA0,0xE3,0x59 -,0x4F,0xC9,0x01,0x25,0xE3,0x5E,0x92,0xA8,0xC8,0xF5,0x27,0xAB,0x03,0xF0,0x9E -,0xFA,0xFC,0x9A,0x8A,0xDF,0x78,0x5A,0x7B,0xC5,0xBE,0xAC,0xC3,0x54,0x13,0x34 -,0xD7,0x0A,0x37,0x01,0xC2,0x9F,0x6C,0xF5,0x0E,0x87,0xDD,0x18,0x15,0x3E,0xE3 -,0x41,0xA9,0xAF,0xA4,0x96,0x9A,0x85,0xA3,0xDC,0x47,0xFB,0x43,0x67,0x3E,0xAF -,0x3D,0xA2,0x1E,0x64,0x03,0x1D,0x19,0xD1,0x06,0x1C,0x0E,0xFC,0xD4,0x72,0x5E -,0xF8,0xC6,0x58,0x6F,0xFC,0x22,0xA0,0xA5,0xB7,0x78,0x9D,0x0D,0xAA,0x6B,0xAD -,0x4D,0xC3,0x6E,0xEF,0x4B,0x45,0x45,0x99,0xD2,0x79,0xBC,0xD0,0x9E,0x86,0x96 -,0x3E,0x32,0x1E,0xAC,0x0A,0xF9,0xAA,0xB9,0xCF,0xE2,0xEE,0x72,0x31,0xA1,0xB5 -,0xAD,0xDE,0xD5,0x53,0x34,0x0B,0x47,0x1B,0x70,0x06,0x46,0xA2,0xA5,0x07,0xCB -,0xA8,0x8C,0x75,0x69,0x69,0x54,0xF5,0x47,0x5E,0xEF,0x4F,0x92,0x31,0xEA,0x8F -,0xDD,0x4E,0x25,0xD6,0x2A,0xAB,0x5D,0x3D,0xBB,0x75,0xEC,0xF6,0x8E,0xAE,0x96 -,0x86,0xBE,0x0B,0xB2,0xD2,0x29,0xC8,0x06,0x37,0xE4,0xCD,0x0F,0xCB,0x92,0xF2 -,0x0C,0x9D,0x8F,0x23,0x8C,0x1C,0x86,0x0E,0xAD,0xF0,0x0E,0xF9,0x35,0xE7,0xC3 -,0x4A,0x1A,0x6A,0xE0,0x56,0xE9,0x64,0x77,0xB3,0x5C,0x94,0xF7,0x15,0x14,0xC7 -,0xCA,0x63,0xFE,0xF0,0x0A,0xFF,0x00,0xEF,0x6A,0x7B,0xAA,0xAF,0xC3,0xCB,0x85 -,0x1D,0x1F,0x8D,0x1B,0x9E,0xDB,0x44,0x57,0xF8,0x76,0xE5,0xB6,0x51,0xEE,0x5B -,0x7B,0xA7,0xE0,0x94,0x95,0xF2,0x67,0x61,0xF5,0x3C,0x60,0x63,0xFE,0xD6,0x7D -,0xF5,0x6A,0x6A,0x06,0x9A,0x69,0xA2,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0xD3,0x6E -,0xED,0xD5,0xB7,0xB6,0x9D,0xB8,0x57,0xEE,0x1B,0xAD,0x3D,0x04,0x2E,0xDC,0x22 -,0x0E,0x73,0x24,0xCD,0xEC,0x91,0xA0,0xCB,0x3B,0x7F,0x85,0x41,0x3A,0x0D,0xCE -,0xA3,0xFB,0xCF,0x79,0xED,0xCD,0xA3,0x04,0x4F,0x7B,0xB8,0x2C,0x73,0xD4,0x1E -,0x34,0xB4,0x70,0xA3,0x4B,0x53,0x54,0xDF,0x96,0x28,0x50,0x17,0x73,0xFA,0x0E -,0x9E,0xF8,0xD4,0x62,0x7B,0x9F,0x88,0x1B,0xB6,0x15,0x96,0xDD,0x4A,0xFB,0x0B -,0x6F,0xCB,0x2C,0x71,0x0B,0x8D,0xCE,0x9C,0x4B,0x73,0x9C,0xC8,0xE1,0x17,0xCA -,0xA6,0xEA,0xB0,0xE5,0x98,0x0E,0x52,0xE4,0x8C,0xE7,0x80,0xD4,0xAF,0xC3,0x8D -,0x97,0xB3,0x2C,0x5F,0x11,0x75,0xB1,0x11,0x76,0xB9,0xCB,0x24,0x90,0x56,0x5E -,0x6A,0xEA,0x3E,0x2A,0xB2,0x69,0x23,0x72,0x8E,0x8F,0x31,0xC9,0x1C,0x59,0x4A -,0x94,0x5E,0x2A,0x08,0x23,0x03,0x1A,0x2E,0x23,0x11,0xD2,0x78,0x99,0xBF,0x3A -,0xB9,0x93,0xC3,0xCD,0xBC,0xFF,0x00,0xEC,0x4D,0x79,0xA8,0x4F,0xF3,0x8E,0x97 -,0x23,0xFD,0xB7,0x1F,0xE1,0xD4,0xD7,0x62,0xEC,0x3D,0xAD,0xB2,0xA9,0xE5,0x4B -,0x05,0xB1,0x22,0xA9,0xA8,0x3C,0xAA,0xAB,0x66,0x73,0x35,0x55,0x53,0x7B,0xB4 -,0xB3,0x39,0x2E,0xE7,0x3D,0x7A,0x9C,0x0F,0x60,0x35,0x26,0xD3,0x45,0x34,0xD3 -,0x4D,0x07,0x95,0x35,0x35,0x3D,0x30,0x7F,0x87,0x82,0x38,0xBC,0xC6,0xE4,0xE5 -,0x54,0x02,0xED,0xF3,0x27,0xDC,0xFD,0x4E,0xBD,0x74,0xD5,0x23,0xF6,0xB0,0xF1 -,0x2A,0xB3,0x69,0xED,0x51,0xB5,0x76,0xC4,0x92,0x36,0xE9,0xBD,0xC7,0xE5,0xC3 -,0xE4,0xF5,0x92,0x9A,0x16,0x61,0x1F,0x35,0x03,0xAF,0x98,0xEC,0xC2,0x38,0xC7 -,0xE6,0x24,0xF6,0x43,0xA0,0x83,0xF8,0xB9,0x57,0x55,0xE3,0xCF,0x8A,0x94,0x9E -,0x1A,0x58,0xAA,0x9D,0x76,0xCD,0xB2,0x66,0x92,0xE1,0x53,0x11,0xF4,0xBF,0x96 -,0xC5,0x26,0x9B,0x3D,0x88,0x53,0x98,0x62,0x1D,0x41,0x73,0x23,0xF6,0x8C,0x1D -,0x74,0xD5,0x8E,0xD5,0x6F,0xB1,0xD9,0xA8,0xEC,0xF6,0x9A,0x58,0xE9,0x28,0x28 -,0xA1,0x58,0x29,0xE1,0x8C,0x61,0x63,0x45,0x18,0x00,0x7E,0xDA,0xAE,0xBE,0xCD -,0x1E,0x16,0xC3,0xE1,0x6F,0x87,0x70,0x50,0x55,0x71,0x9A,0xFD,0x5C,0x12,0x7B -,0xAD,0x46,0x79,0x66,0x40,0xB8,0x58,0x81,0xFC,0x91,0x8F,0x48,0xF6,0xCF,0x23 -,0xFC,0xDA,0xB4,0x74,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40 -,0xD6,0x0D,0xC6,0xE7,0x4F,0x47,0x4F,0x24,0xF2,0x4B,0x0A,0x43,0x17,0xF7,0xB3 -,0xCD,0x20,0x48,0xA3,0xEB,0x8E,0xAC,0x7D,0xF3,0xD3,0x03,0x3D,0x70,0x0E,0x33 -,0xA8,0xE5,0xE7,0x72,0xA1,0x79,0x16,0x92,0x48,0xEB,0x15,0x64,0x31,0x72,0x0E -,0x56,0x95,0x1F,0xF2,0xB3,0x80,0x5A,0x69,0x3D,0x2D,0xF7,0x51,0x83,0xD7,0xD2 -,0xC0,0x74,0x6D,0x51,0xFE,0x28,0x78,0xD9,0x41,0x64,0xAA,0x10,0x5A,0x02,0xEE -,0x3B,0xEC,0x78,0xE0,0xED,0x3C,0x70,0x52,0xD0,0x86,0x21,0x03,0xB3,0x96,0xF2 -,0xE9,0x53,0x93,0x05,0x0D,0x96,0x73,0xCB,0x89,0x91,0x08,0xC6,0x82,0xDD,0xDC -,0xDB,0xAD,0x28,0xA9,0x65,0xAF,0xA9,0xAB,0xFE,0x1F,0x4F,0x04,0x7E,0x6B,0xD6 -,0x55,0x2A,0xC7,0x22,0x2E,0x08,0xE5,0x1C,0x72,0x10,0x90,0x29,0xCB,0x62,0x49 -,0xCE,0x4E,0x0A,0x85,0x7C,0x8D,0x73,0xE6,0xEE,0xFB,0x44,0x5B,0x28,0x61,0xA8 -,0x7B,0x05,0x3B,0x1A,0x1A,0x86,0x92,0x35,0xBC,0x54,0xA4,0xAD,0x4F,0x51,0x32 -,0x29,0x24,0x20,0x60,0x26,0xAD,0x75,0x04,0x2F,0xDE,0x18,0xE2,0x05,0xE3,0x56 -,0x54,0x52,0x1B,0x5C,0xF1,0xE2,0x37,0x89,0x77,0x5D,0xC9,0x72,0xF3,0xAF,0x37 -,0x28,0x77,0x0B,0x28,0x12,0xC3,0x12,0xAC,0x91,0x5B,0xA9,0x64,0x74,0x6C,0x95 -,0x85,0x82,0xB4,0xB2,0x29,0x31,0xFD,0xE4,0xB9,0xC9,0x56,0x0C,0xB2,0xA9,0x0C -,0x6B,0xAA,0xAA,0x9A,0x8A,0xB9,0xBC,0xEA,0xAA,0x89,0x67,0x93,0x82,0xA7,0x39 -,0x1C,0xB3,0x71,0x55,0x0A,0xA3,0x27,0xD8,0x28,0x00,0x0F,0x60,0x00,0xD0,0x6E -,0x77,0x36,0xEC,0xBD,0x5F,0xCD,0x52,0x56,0xD6,0xCC,0xF4,0xF5,0x35,0xAD,0x5D -,0x2A,0xB9,0x52,0xF2,0xCC,0x57,0x88,0x79,0x1C,0x00,0x64,0x21,0x72,0x17,0x3D -,0x13,0x9B,0xF0,0x08,0x18,0x83,0xA1,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD3 -,0x4D,0x03,0x57,0x4F,0x80,0xFB,0x3D,0x2B,0xAB,0x29,0xA5,0xAB,0x05,0x0D,0x35 -,0x55,0x0D,0x7D,0x64,0x6D,0x1E,0x0B,0x23,0xCE,0xAB,0x4D,0x11,0xE4,0x81,0x80 -,0x60,0x5E,0x66,0xC3,0x32,0x3A,0x9A,0x73,0xDD,0x75,0x52,0x58,0x28,0xE9,0xEE -,0x17,0xDB,0x7D,0x05,0x65,0x67,0xC1,0x53,0x54,0xD5,0x47,0x0C,0xD5,0x3E,0x5F -,0x3F,0x25,0x19,0x80,0x67,0xE3,0x91,0xCB,0x00,0x93,0x8C,0x8C,0xE3,0xB8,0xD7 -,0x4A,0xD7,0x4F,0x57,0xB5,0xFC,0x29,0x37,0x2B,0x75,0x1D,0x3D,0x3D,0xEA,0xE8 -,0x94,0x37,0x54,0x82,0x28,0x82,0x20,0x96,0x4A,0xE5,0x74,0x89,0x50,0x60,0x05 -,0x54,0xE1,0x18,0x51,0x80,0x02,0x81,0xD3,0x41,0xF5,0xE2,0x3F,0x89,0xD5,0xD6 -,0xBB,0x1D,0x16,0xD3,0xDB,0x50,0xD5,0x24,0xE9,0x0C,0x54,0x75,0x15,0x34,0xC0 -,0x07,0x5A,0x82,0xB8,0x5A,0x68,0x89,0xEC,0xC3,0xF9,0x98,0x02,0x57,0xB0,0xC3 -,0x1C,0x89,0x7F,0xD8,0xD3,0xC3,0x04,0xB5,0xC3,0x71,0xDF,0xF7,0xB6,0x4A,0xDB -,0x9D,0x4D,0x44,0xB4,0xB4,0x33,0x93,0xCC,0x04,0x56,0x2B,0x2C,0xAA,0x4F,0x72 -,0xEE,0x19,0x43,0x77,0x2A,0xB9,0xFE,0x63,0xAA,0x36,0x9E,0x91,0xE8,0xB7,0x3C -,0xD3,0xC4,0x56,0x67,0xDB,0xB6,0x59,0xAE,0x1C,0xF0,0x5D,0xDA,0xBA,0x52,0x23 -,0x46,0x77,0x3D,0x59,0xBC,0xD9,0x12,0x41,0xDB,0xB7,0x6D,0x77,0x7E,0xCB,0xB2 -,0x41,0xB6,0xF6,0x8D,0xA3,0x6F,0xD3,0x00,0x22,0xB7,0x51,0xC5,0x4C,0x31,0xEF -,0xC1,0x40,0x27,0xF5,0x24,0x13,0xFB,0xEB,0xAF,0x8E,0xBF,0x6C,0x5A,0x59,0x97 -,0x4A,0x36,0xAA,0x85,0x5A,0x19,0x04,0x35,0x50,0xB7,0x38,0x25,0xC6,0x42,0xB7 -,0xC8,0x8F,0x75,0x23,0xA1,0x1F,0x23,0xD3,0x07,0x04,0x6B,0x2E,0x16,0xCB,0x0E -,0xF2,0xB2,0xC9,0x6F,0xDC,0x36,0x5A,0x3A,0xD8,0xD1,0x8C,0x75,0x14,0x95,0x51 -,0x89,0x3C,0xA9,0x30,0x33,0x82,0x47,0x4E,0x84,0x10,0xC3,0x19,0x04,0x11,0xDF -,0x5B,0xED,0x46,0xAF,0xD5,0x35,0x16,0xFD,0xC1,0x05,0x4C,0x34,0xE4,0xC9,0x2C -,0x7C,0x10,0x29,0xC0,0xAB,0x55,0xCB,0x34,0x3D,0x7A,0x09,0x54,0x65,0xD3,0x3F -,0x8B,0xD6,0xBD,0x3A,0xB6,0xBA,0xCB,0x10,0x84,0x5D,0x36,0x45,0xFF,0x00,0x63 -,0xC2,0xB3,0xEC,0xA3,0x5B,0x7E,0xB2,0xC6,0x02,0x1B,0x0D,0x44,0xEA,0x66,0xA6 -,0x41,0xEF,0x4D,0x33,0x9C,0x90,0xA0,0x00,0x22,0x72,0x7A,0x76,0x61,0x8C,0x18 -,0x45,0xCE,0xCF,0x05,0xC6,0x8A,0x4D,0xDF,0xB2,0x69,0xE5,0x12,0x48,0xEC,0x6E -,0x56,0x77,0x4F,0x29,0xA4,0x91,0x4E,0x1F,0xD0,0x7F,0xBB,0xA8,0x53,0xDC,0x1C -,0x07,0xEC,0x7A,0x90,0xC3,0xA3,0xA8,0xAA,0x60,0xAC,0xA4,0x8A,0xAA,0x96,0x41 -,0x2C,0x32,0xA8,0x64,0x61,0xEE,0x0E,0xAB,0xEF,0x14,0x6C,0x95,0xF6,0xB9,0x9F -,0x7B,0x6D,0xAA,0x37,0xA9,0xA8,0x8C,0x0F,0xE3,0x16,0xF8,0x87,0xAA,0xBA,0x05 -,0x18,0xF3,0x10,0x7F,0xAF,0x8C,0x76,0xFC,0xEA,0x0A,0x9C,0xE1,0x31,0xCE,0xD4 -,0xFB,0x86,0xA2,0xDF,0xB5,0x37,0x4D,0x3D,0x15,0xF2,0xD7,0x1D,0x4D,0x2C,0xCE -,0x63,0x73,0xCA,0x39,0x50,0x94,0x92,0x27,0x53,0xDC,0x7B,0xA3,0xA9,0x1F,0xA8 -,0x23,0x51,0x7A,0x7B,0xA5,0x65,0x93,0x70,0x56,0x2D,0xCE,0x38,0x92,0x26,0x61 -,0x2D,0x69,0x8D,0x78,0xC6,0xEA,0xC7,0x88,0xAD,0x45,0xEC,0xB9,0x62,0x16,0x64 -,0x1D,0x03,0x15,0x71,0xD1,0x8E,0xA6,0x5B,0xC6,0x9E,0x86,0xDF,0x24,0x1B,0xF6 -,0xC3,0x2C,0x73,0x6D,0xFB,0xC1,0x46,0xB8,0xF9,0x67,0x09,0x1B,0xBE,0x02,0x55 -,0x01,0xEC,0x0F,0x45,0x93,0xB7,0xF2,0xB1,0xEC,0xD9,0xD6,0x6E,0x9B,0x63,0xD7 -,0x52,0x25,0x55,0x2C,0x31,0x4B,0x5F,0x46,0x5A,0x4A,0x75,0x90,0x7A,0x25,0x05 -,0x4A,0xC9,0x0B,0xFF,0x00,0x82,0x44,0x25,0x0F,0xEA,0x0F,0xB0,0xD7,0x26,0xDB -,0xBD,0xAD,0xBC,0x69,0xAC,0x34,0x96,0x6F,0x8A,0x8A,0xA8,0xDC,0xB6,0x25,0x71 -,0xEB,0x0D,0x34,0x92,0x09,0xAC,0x15,0x47,0xCB,0x62,0x4A,0x82,0x00,0x84,0x94 -,0xFC,0x44,0x7F,0xCD,0xC6,0x3B,0xEB,0xAB,0xA2,0x74,0x96,0x35,0x96,0x37,0x57 -,0x47,0x01,0x95,0x94,0xE4,0x10,0x7B,0x10,0x75,0xC3,0x7B,0x17,0x72,0x4F,0xB6 -,0xAE,0xF4,0x57,0x8B,0x69,0xF8,0xAA,0x7A,0x1A,0x6C,0x3C,0x53,0xC5,0xE6,0x9A -,0xDB,0x24,0xE7,0x8C,0xB1,0x3A,0x02,0x0B,0xC9,0x0B,0x21,0x52,0x33,0xF8,0xA2 -,0xF7,0xE5,0x83,0x7F,0xFD,0x97,0x37,0x7C,0x37,0x0B,0x45,0xCF,0x63,0x3D,0x7C -,0x55,0xB2,0x6D,0xC9,0x15,0x68,0x2A,0x12,0x4E,0x62,0xA2,0xDF,0x26,0x4C,0x0C -,0x18,0xFE,0x2E,0x00,0x18,0xC9,0xFF,0x00,0x0A,0xFC,0xF5,0x05,0xCF,0xA6,0x9A -,0xC6,0xBA,0xDC,0x68,0x2D,0x36,0xE9,0xEE,0x37,0x4A,0xDA,0x7A,0x2A,0x3A,0x74 -,0x2F,0x34,0xF5,0x12,0x08,0xE3,0x8D,0x7E,0x65,0x8F,0x40,0x34,0x46,0x4E,0xB5 -,0xBB,0x96,0xFF,0x00,0x65,0xDB,0x56,0xA9,0x2E,0xB7,0xFB,0xA5,0x25,0xB6,0x8A -,0x3E,0x8D,0x35,0x44,0x81,0x06,0x7D,0x80,0xCF,0x72,0x7D,0x80,0xC9,0x3E,0xDA -,0xA3,0xFC,0x47,0xFB,0x41,0xD4,0x9B,0x7D,0x44,0x7E,0x1A,0x59,0x45,0xC9,0xC4 -,0x6C,0x63,0xB9,0xDC,0x15,0xE3,0x82,0x4C,0x0F,0xF4,0x10,0x81,0xE6,0x4D,0xFE -,0xD6,0x15,0x3D,0xF2,0x46,0xA9,0x5D,0xD0,0xF5,0xD7,0xFB,0x55,0xB7,0x7E,0xDE -,0xAF,0x75,0xD7,0x5A,0xE8,0x1E,0x9A,0xBC,0x4D,0x52,0xE0,0x84,0x88,0xB2,0x99 -,0x15,0x50,0x00,0x91,0xAF,0x06,0x63,0xC5,0x14,0x75,0x50,0x49,0x3A,0x2A,0xEF -,0xDE,0xDE,0x36,0x5D,0xEE,0x25,0xA8,0xB6,0x55,0x22,0x5A,0xA0,0x70,0x71,0x73 -,0xB9,0xC2,0x5A,0x77,0x1F,0x9A,0x1A,0x5E,0xFF,0x00,0xBC,0x98,0x23,0xF2,0x1D -,0x6B,0x3E,0xCE,0x2D,0x1C,0x5E,0x3A,0x54,0xB5,0xFE,0xA2,0xAA,0xF5,0x73,0xBA -,0xD9,0xDE,0x5A,0x4B,0x8D,0xD3,0x8C,0xB3,0xC7,0x24,0x32,0x0E,0x69,0x11,0xC7 -,0xDD,0x2B,0x24,0xC3,0x2A,0xA1,0x46,0x23,0x1A,0x8D,0x80,0x06,0x70,0x07,0x5D -,0x64,0xED,0x8A,0xC6,0xB5,0x78,0x9D,0xB2,0x6E,0xC8,0x78,0xF9,0x77,0xA8,0xE9 -,0x64,0x3F,0x34,0xA9,0x47,0xA7,0xC7,0xFE,0x29,0x50,0xFE,0xC3,0x57,0x07,0x52 -,0xEF,0xB7,0xE1,0x64,0xA7,0x6F,0x9D,0xDA,0xDC,0x3F,0xAD,0x6C,0x03,0xFF,0x00 -,0x5D,0x47,0xBC,0x0F,0x1E,0x5D,0x9B,0x72,0x53,0x7B,0x43,0xBB,0x2E,0xE0,0x0F -,0x90,0x7A,0xB9,0x24,0xFF,0x00,0xDF,0xAD,0xCF,0x89,0x2F,0xC6,0xC3,0x44,0xBF -,0x9A,0xF7,0x6B,0x1F,0xFF,0x00,0xBA,0x03,0xFF,0x00,0xA6,0xB4,0xFE,0x0C,0xE4 -,0x7F,0x6D,0x10,0xFF,0x00,0x2E,0xED,0xAE,0xC7,0xEF,0xC0,0xFF,0x00,0xEB,0xA8 -,0xA9,0xF6,0x9A,0x69,0xA0,0x69,0xA6,0x9A,0x0D,0x2E,0xFA,0xDC,0xF6,0xAD,0x9B -,0xB4,0xEE,0x3B,0x96,0xF3,0x29,0x4A,0x3A,0x18,0x8C,0x8C,0x14,0x65,0xE4,0x6E -,0xCB,0x1A,0x8F,0x76,0x66,0x21,0x40,0xF7,0x24,0x6A,0x8B,0xFB,0x3A,0xED,0x8B -,0x8E,0xFB,0xDD,0xB5,0x5E,0x31,0xEF,0x18,0x95,0xDE,0x5A,0x86,0x7B,0x64,0x24 -,0xF2,0x4F,0x30,0x02,0x81,0xD7,0xD8,0xC7,0x0A,0xE6,0x28,0xCF,0x5C,0xB1,0x9A -,0x4F,0xE7,0x53,0xA8,0xCF,0x8C,0xB7,0x69,0xFC,0x75,0xFB,0x42,0xDA,0xBC,0x1D -,0xB2,0x54,0xCB,0xFD,0x97,0xB0,0x4E,0x6A,0xEF,0xF5,0x10,0x36,0x04,0x8F,0x1F -,0x47,0x19,0x1D,0xB8,0xE7,0xCA,0x07,0xF3,0xBB,0x1F,0x61,0xAE,0xAC,0xB6,0xD1 -,0x52,0x5B,0x6D,0xF4,0xD6,0xFA,0x0A,0x78,0xE9,0xA9,0x29,0xA2,0x58,0x60,0x86 -,0x35,0xE2,0xB1,0xA2,0x8C,0x2A,0x81,0xEC,0x00,0x00,0x68,0x32,0x34,0xD3,0x4D -,0x03,0x4D,0x34,0xD0,0x34,0xD6,0x05,0x6D,0xD2,0x9E,0x9E,0x39,0x1F,0xCC,0x8C -,0x47,0x17,0xF7,0xD3,0xC8,0xE1,0x22,0x8B,0xAE,0x0E,0x58,0xFB,0xF4,0x23,0x03 -,0x27,0x38,0xCE,0x33,0x9D,0x41,0xF7,0xBF,0x88,0xF4,0xB6,0xB8,0xA5,0x85,0x27 -,0x7A,0x42,0x8A,0x0B,0x7A,0x07,0xC4,0x75,0x04,0x83,0xC5,0xFD,0x30,0x82,0x01 -,0x20,0xC8,0x0B,0xB0,0x56,0x0B,0x1B,0x1C,0x1D,0x04,0xD6,0xF1,0x7A,0xA2,0xB6 -,0x32,0xC3,0x27,0x99,0x51,0x56,0xEA,0x5E,0x3A,0x58,0x00,0x69,0x5C,0x0F,0xE6 -,0xC1,0x20,0x2A,0xFB,0x17,0x62,0x14,0x7B,0x91,0xAA,0x67,0xC4,0xCF,0x16,0xAC -,0xF4,0x1C,0x29,0xEE,0xB7,0x2A,0x79,0x9A,0x7C,0x0A,0x7B,0x65,0x23,0x34,0x89 -,0x36,0x7A,0x0C,0x85,0xC4,0x95,0x59,0xF6,0x55,0xE1,0x13,0x02,0xC3,0x32,0x95 -,0xC6,0xA9,0x6F,0x14,0x7C,0x6D,0x8C,0x50,0x4A,0x94,0x13,0x45,0x15,0x14,0xF2 -,0xA1,0x79,0x01,0xF3,0x7C,0xE0,0xCC,0x57,0xCC,0x44,0x77,0x12,0x56,0x15,0xE0 -,0xE3,0xCD,0x76,0x11,0x8E,0x0B,0xC5,0xA2,0x70,0x10,0xF3,0x7E,0xE1,0xDE,0x57 -,0x0B,0x85,0xC6,0xB2,0xAE,0x85,0xEA,0x28,0x9E,0xBE,0x30,0xB5,0xB3,0xB4,0xC2 -,0x4A,0xAA,0x96,0x28,0xCB,0x27,0x39,0x82,0xA9,0xE0,0xFC,0xD8,0x18,0xD4,0x05 -,0x2A,0x13,0x90,0x76,0x5E,0x64,0x2C,0xEF,0x19,0xBC,0x64,0xBA,0x6E,0x44,0x14 -,0xC9,0x75,0xF2,0xAD,0xEE,0x8D,0x08,0xB6,0xD0,0x54,0x00,0xE6,0x13,0x18,0x29 -,0xE7,0x4C,0x8B,0xC0,0x46,0x4B,0x20,0xF2,0x22,0xC0,0x3C,0x18,0x38,0x8D,0xC0 -,0x26,0x9C,0xBD,0xDE,0x2A,0x2E,0x86,0x24,0x68,0x69,0x69,0x29,0x29,0xF9,0x8A -,0x6A,0x4A,0x58,0x82,0x45,0x08,0x66,0xC9,0x1E,0xEC,0xE7,0xB0,0xE6,0xE5,0x9C -,0x85,0x50,0x58,0xF1,0x1A,0xD6,0xE9,0xA0,0x69,0xA6,0x9A,0x06,0x9A,0x69,0xA0 -,0x69,0xA6,0x9A,0x06,0x9A,0x69,0xA0,0xDD,0x6C,0xBF,0x24,0xDF,0x19,0x26,0xA7 -,0x86,0x71,0x25,0x0D,0x64,0x68,0xB2,0xA0,0x65,0x0E,0xD4,0xD2,0xAA,0x36,0x0F -,0xBA,0xB1,0x56,0x07,0xB8,0x20,0x11,0xD4,0x6B,0xAB,0xFC,0x76,0xB6,0xD2,0xC6 -,0xBB,0x6A,0x15,0xE5,0xC5,0xAA,0x56,0x22,0x8A,0xC5,0x71,0x1C,0x31,0x48,0xEA -,0x72,0x3A,0xF4,0x7F,0x2F,0xFA,0x6B,0x93,0x36,0x97,0xA6,0xFB,0x14,0x98,0x24 -,0x45,0x14,0xD2,0xB6,0x3E,0x49,0x13,0xB1,0xFF,0x00,0x20,0x75,0xD6,0xFE,0x3C -,0xBB,0x0B,0xFE,0xD5,0x5C,0xFA,0x19,0x2B,0x0F,0xEF,0x88,0xB1,0xFE,0x59,0xD5 -,0x49,0x54,0x9B,0x7A,0xD6,0xB7,0x0B,0xCE,0xF2,0xA9,0xA7,0x86,0x11,0x55,0x1D -,0xC6,0xCB,0x47,0x4E,0x59,0xCC,0x68,0x0C,0xB5,0x08,0x08,0x62,0xA0,0xFA,0x4F -,0x01,0x9E,0x87,0xB0,0x38,0xC8,0x1A,0xEE,0x9B,0x2D,0xC6,0x3B,0x9D,0x17,0x9C -,0x22,0x92,0x9E,0x64,0x6F,0x2E,0xA2,0x9E,0x4C,0x73,0x82,0x40,0x06,0x51,0xB1 -,0xD3,0x3D,0x41,0x04,0x74,0x20,0x82,0x09,0x04,0x1D,0x71,0x2E,0xD8,0x93,0xE1 -,0xE9,0x7C,0x4E,0xE2,0x40,0x96,0x92,0x5B,0x45,0xCD,0x47,0xBF,0x18,0x65,0x12 -,0x39,0xFE,0x9F,0xF1,0xD7,0x66,0x5F,0x69,0xEA,0xE9,0xE6,0x5B,0xED,0xA2,0x2F -,0x3E,0xA6,0x34,0x0B,0x51,0x4C,0xA4,0x0F,0x8B,0x87,0xBF,0x10,0x7B,0x79,0x8B -,0x92,0x50,0x9E,0x9D,0x4A,0x9C,0x06,0xC8,0xED,0x4E,0x21,0x89,0x6E,0xF5,0x8D -,0x74,0xA1,0xA7,0xB9,0x50,0x4B,0x45,0x54,0xAC,0x63,0x93,0x1D,0x55,0xB8,0xB2 -,0x30,0x39,0x56,0x52,0x3A,0x86,0x04,0x02,0x08,0xEA,0x08,0x07,0x4A,0x0A,0xDA -,0x7B,0x85,0xBE,0x2A,0xEA,0x29,0x04,0xD0,0xCA,0x9C,0x90,0xE0,0x8C,0xFD,0x08 -,0x3D,0x41,0xF6,0x20,0xF5,0x07,0xA1,0xD7,0xB5,0x3C,0xA9,0x3C,0x42,0x48,0xCE -,0x41,0x24,0x1F,0x98,0x20,0xE0,0x83,0xF5,0x07,0xA6,0xBA,0x32,0x83,0xD9,0xEF -,0x12,0xD8,0xAF,0x95,0x96,0xFB,0xA3,0xAA,0xF9,0x64,0x49,0x59,0x85,0xE2,0xBC -,0x5C,0xE1,0x6B,0x50,0x7B,0x46,0xE7,0x22,0x50,0x3A,0x23,0x82,0xDF,0x84,0x97 -,0x33,0xBD,0x6A,0x77,0x1D,0x9A,0x3B,0xA4,0x70,0xCF,0x13,0x24,0x37,0x0A,0x52 -,0xCD,0x4B,0x39,0x5E,0x41,0x79,0x0C,0x32,0x30,0xFE,0x68,0xD8,0x74,0x65,0xF7 -,0xE8,0x46,0x18,0x29,0x1A,0x7D,0xAD,0x73,0x6B,0x7D,0x4C,0x76,0x5A,0xC4,0x68 -,0xA9,0xDD,0xCC,0x34,0x9C,0xDB,0x91,0xA7,0x94,0x0E,0x46,0x95,0xCF,0xBE,0x17 -,0xD5,0x1B,0x7F,0x32,0x74,0x3D,0x40,0x2D,0x98,0xE1,0x7B,0x40,0x37,0x7D,0xBA -,0x9F,0x6B,0xF8,0x81,0x25,0x8E,0xB2,0x9A,0x37,0xDA,0x9B,0xC4,0x4B,0xE4,0xC6 -,0xC3,0xEE,0xE9,0xEB,0x8A,0x93,0x34,0x38,0xEC,0x16,0x65,0xCB,0x81,0xF9,0xC3 -,0xE3,0xBE,0xAB,0x8B,0x6D,0x15,0x45,0x0D,0x75,0xC7,0x6C,0x5D,0x67,0x79,0xE4 -,0xB5,0x48,0xB1,0x47,0xCB,0xA7,0x9F,0x4C,0xC3,0x30,0xC8,0xC7,0xF9,0x89,0x19 -,0x56,0xF6,0x2C,0xAC,0x31,0xAE,0x86,0xF1,0x7F,0x6A,0xB6,0xF1,0xD8,0x17,0x0B -,0x4D,0x33,0x79,0x57,0x14,0x02,0xAA,0xDB,0x30,0xE8,0x61,0xAA,0x88,0xF3,0x89 -,0x81,0xF6,0xF5,0x0C,0x1F,0xA1,0x3A,0xA1,0x77,0x55,0xC1,0x2E,0xB6,0xCD,0x9F -,0xE2,0x34,0x30,0x18,0x4D,0x5A,0x8B,0x65,0xCE,0x30,0x3A,0xC7,0xE6,0x36,0x00 -,0x3F,0xF6,0x75,0x0A,0x53,0xE9,0xCD,0xB5,0xCA,0xF1,0x92,0xD5,0x67,0x61,0x09 -,0xBD,0x51,0x43,0x60,0xBB,0x19,0x11,0x4A,0xD2,0x53,0x4A,0xD7,0x28,0x23,0x52 -,0x42,0xFC,0x3B,0x95,0x4A,0xD8,0x70,0x0F,0x55,0x19,0x8A,0x70,0xBD,0xBD,0x2F -,0xD3,0x59,0x95,0xD6,0x9A,0xEB,0x2F,0x88,0x1B,0x6E,0xEF,0xB5,0xEF,0xB5,0x36 -,0x17,0x89,0x65,0x4A,0x51,0x1E,0x64,0xA7,0x49,0x06,0x24,0xF2,0xC4,0x5C,0x82 -,0x84,0x75,0x12,0x16,0x51,0x80,0x78,0xF6,0xC9,0xD6,0xEB,0x7A,0xAC,0x31,0x5B -,0x62,0xBA,0x4F,0x17,0x9B,0x15,0xBE,0x61,0x34,0xE9,0xF9,0xE9,0xD8,0x18,0xEA -,0x17,0xF7,0x85,0xE4,0xFD,0xF1,0xAD,0x19,0x33,0xA6,0xC2,0x91,0x67,0x93,0xCD -,0xAF,0xDB,0x35,0x4C,0xB2,0x30,0xEA,0x58,0xD2,0xC9,0xD7,0xF7,0x78,0x87,0xEE -,0x1F,0x58,0x69,0x69,0xC5,0xE3,0x97,0x89,0x6D,0x74,0xA8,0xB1,0xFF,0x00,0x08 -,0xDA,0x5F,0x15,0x05,0x3C,0x73,0xFC,0x59,0x35,0x1C,0x5D,0x5C,0xBA,0x82,0x21 -,0x07,0x39,0x05,0x0E,0x47,0x3F,0x71,0xD7,0xAE,0xA3,0x3B,0x86,0x5D,0xCD,0xBC -,0x2A,0x52,0x7D,0xE7,0x7E,0x96,0xE5,0x14,0x6E,0x1E,0x2A,0x34,0x89,0x62,0xA5 -,0x8D,0x86,0x70,0x56,0x11,0x95,0x24,0x7E,0x69,0x0C,0x87,0xE5,0xC7,0x5A,0xBB -,0x99,0x58,0x37,0x8D,0x92,0xB9,0x08,0x29,0x57,0x0C,0xF4,0x44,0x8F,0xE6,0x25 -,0x44,0xC8,0x7F,0x61,0x13,0xFF,0x00,0xE2,0xD4,0x83,0x41,0xE5,0x4F,0x4F,0x0C -,0x0A,0x44,0x49,0x82,0xDF,0x89,0x89,0xCB,0x37,0xB7,0x52,0x7A,0x9F,0xDF,0x51 -,0x0A,0x08,0x04,0xBE,0x16,0x5D,0x2D,0x61,0xD4,0x0A,0x78,0x6B,0xA8,0x54,0xB1 -,0xE8,0xA2,0x37,0x92,0x35,0xCF,0xEC,0x17,0x52,0xDF,0x88,0xE6,0x40,0xA7,0x4F -,0x3B,0xAF,0x57,0x07,0x08,0x3F,0x7F,0x7F,0xDB,0x3F,0x5C,0x6A,0x23,0x4B,0x1C -,0x14,0xBB,0x43,0x74,0x55,0x54,0x81,0x32,0xAD,0x45,0xC2,0x47,0x5E,0xBC,0x7F -,0x9B,0x20,0x29,0x27,0xE4,0x7F,0xA9,0xD0,0x49,0xAD,0x75,0xCB,0x51,0x6B,0xA2 -,0xA8,0x2B,0x23,0x35,0x45,0x3A,0x49,0xE9,0x42,0x47,0x55,0x07,0xBE,0x30,0x3B -,0xEB,0x17,0x72,0x54,0xD4,0x41,0x45,0x4B,0x57,0x14,0x2F,0x1B,0x52,0xDC,0xA8 -,0x6A,0x39,0x12,0x32,0x38,0x55,0x44,0xD9,0x18,0xCF,0xCB,0x59,0x3B,0x66,0x9D -,0xE9,0x36,0xDD,0xB2,0x96,0x40,0x43,0xC3,0x47,0x14,0x6C,0x0F,0x7C,0x84,0x00 -,0xFF,0x00,0xC3,0x58,0xFB,0xC0,0xB7,0xF0,0x4F,0x2D,0x33,0xCE,0x6A,0xAA,0x68 -,0x57,0x1F,0x37,0x9E,0x35,0x1F,0xF1,0xD0,0x75,0xE7,0x88,0xA3,0x95,0xBE,0xD1 -,0x1F,0xE6,0xBE,0x50,0x7F,0xE5,0xA8,0x46,0xFF,0x00,0xDB,0xAD,0x3F,0x83,0x0D -,0xC9,0xB7,0xB1,0xCE,0x7F,0xF9,0xB6,0xB8,0x7F,0x41,0x18,0xD6,0xEF,0x7D,0x02 -,0xF2,0x6D,0xE8,0xC7,0xF3,0x5E,0xA0,0x3F,0xF8,0x55,0xDB,0xFF,0x00,0x6E,0xA3 -,0xFE,0x06,0x12,0xF4,0xDB,0xCE,0x5F,0xCF,0xBC,0x6E,0x7F,0xF9,0x64,0x09,0xFF -,0x00,0xB7,0x51,0x56,0x26,0x9A,0x69,0xA0,0x6A,0xA6,0xFB,0x50,0x78,0x9B,0x1F -,0x87,0x5B,0x04,0xC7,0x45,0x57,0x1C,0x17,0xEB,0xC1,0x7A,0x6B,0x7B,0x1E,0xBE -,0x40,0x0B,0x99,0x6A,0x08,0xF7,0x11,0xAF,0x5C,0x7B,0xB1,0x51,0x83,0x9D,0x5A -,0x75,0xD5,0x54,0xD4,0x34,0x53,0xD6,0xD6,0x4F,0x1C,0x14,0xD4,0xF1,0xB4,0xB3 -,0x4B,0x23,0x61,0x51,0x14,0x65,0x98,0x9F,0x60,0x00,0x27,0x5C,0x87,0xB1,0xAD -,0x95,0x1F,0x68,0x5F,0xB4,0x28,0xDF,0x97,0x18,0x24,0x7D,0xA7,0x60,0x94,0x35 -,0x3C,0x72,0x7F,0x77,0xC1,0x0F,0x2A,0x68,0x31,0xD8,0xBB,0x9F,0xBF,0x90,0x75 -,0xC0,0x28,0xA7,0x1D,0xB4,0x16,0xE7,0xD9,0x3F,0xC3,0x38,0xF6,0x2E,0xC8,0x92 -,0xF1,0x5D,0x44,0xD4,0xF7,0xCB,0xFF,0x00,0x0A,0x8A,0x95,0x97,0xAC,0xB0,0x42 -,0x07,0xDD,0x44,0xC7,0xF3,0xE0,0xF3,0x7F,0x9B,0xBB,0x7C,0x86,0xAE,0x6D,0x34 -,0xD0,0x34,0xD7,0xCC,0xB2,0x24,0x51,0xB4,0x92,0x3A,0xA2,0x28,0xCB,0x33,0x1C -,0x00,0x3E,0xA7,0x51,0xFD,0xC5,0xB8,0x23,0xA2,0x89,0x50,0xCE,0x68,0xFC,0xD0 -,0xDE,0x59,0x31,0x17,0xA9,0x97,0x18,0xCF,0x95,0x0F,0x7E,0x99,0x39,0x77,0x1C -,0x57,0x00,0x90,0x54,0xE7,0x41,0xB8,0xAF,0xAF,0xA7,0xA3,0x28,0x92,0x33,0x3C -,0xD2,0x7F,0x75,0x0C,0x6B,0xCA,0x49,0x3A,0x81,0xD1,0x47,0xB0,0x24,0x64,0xF6 -,0x19,0xC9,0x20,0x75,0xD4,0x4B,0x73,0xEF,0x2A,0x3B,0x6A,0xB8,0xAD,0x96,0x33 -,0x2A,0xB8,0x43,0x47,0x14,0x84,0x84,0x7F,0xC4,0x12,0x57,0x50,0x4B,0x48,0x46 -,0x0F,0x93,0x18,0x66,0x39,0x3D,0x1D,0x7A,0x8A,0xE3,0x79,0xF8,0x8E,0xB4,0x94 -,0x52,0xCD,0x4B,0x50,0x96,0xEA,0x49,0xD8,0x2B,0x54,0x99,0x5A,0x49,0x6A,0x18 -,0xE4,0xAA,0xF9,0x88,0x79,0xCC,0x4F,0x2F,0x4C,0x70,0x10,0xB8,0x07,0x84,0xAF -,0x83,0x1E,0xB9,0x77,0xC4,0xDF,0x17,0x23,0xA8,0x89,0xA0,0xB4,0x55,0x65,0x5E -,0x36,0x8D,0x56,0x36,0x53,0x28,0x46,0x50,0xEB,0x96,0x41,0xE5,0x45,0x19,0x66 -,0x04,0xC7,0x1E,0x49,0x31,0x92,0x56,0x09,0x3A,0x90,0xBB,0xBC,0x4A,0xF1,0xB2 -,0x43,0x23,0xD3,0xDA,0xDB,0xCC,0x9A,0x9D,0x03,0x06,0x47,0x48,0x96,0x9D,0x09 -,0x08,0xAC,0x5F,0x97,0x97,0x4C,0x84,0xB0,0x50,0xC1,0xCB,0xB0,0x7C,0x09,0x91 -,0x87,0x97,0xAE,0x5F,0xDE,0xBE,0x24,0xDC,0x2E,0x55,0x68,0x29,0xAA,0x22,0xAB -,0x54,0x66,0x62,0xB2,0xD3,0x03,0x4C,0xAF,0xE6,0x82,0x19,0x23,0x6E,0x93,0x06 -,0x08,0x0B,0x34,0xA9,0x86,0x2E,0x49,0x8C,0x30,0xE6,0xD0,0xDD,0xC1,0x7C,0xAD -,0xBD,0x4C,0xAD,0x52,0x22,0x8A,0x08,0xDD,0xDA,0x1A,0x78,0x57,0x8A,0x47,0xCD -,0xB2,0xC7,0x27,0x2C,0xEC,0x7A,0x02,0xEE,0x59,0xC8,0x55,0x0C,0xC7,0x03,0x5A -,0xBD,0x07,0xDC,0xF2,0xCB,0x51,0x3C,0x93,0xCF,0x2B,0xCB,0x2C,0x8C,0x5D,0xDD -,0xD8,0xB3,0x33,0x13,0x92,0x49,0x3D,0xC9,0x3E,0xFA,0xF8,0xD3,0x4D,0x03,0x4D -,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D,0x34,0xD0,0x34,0xD3,0x4D,0x03,0x4D,0x34 -,0xD0,0x6E,0x76,0x5B,0x56,0x1D,0xCB,0x4B,0x49,0x6F,0x82,0x19,0xEA,0xAE,0x02 -,0x4B,0x74,0x69,0x2A,0x92,0x33,0x53,0x1B,0x41,0x90,0x01,0x1E,0xA0,0x24,0xC8 -,0xFA,0x81,0x90,0x47,0x4D,0x75,0x07,0x89,0x75,0xF1,0xDD,0xB6,0x5F,0x87,0x5B -,0x98,0xB6,0x12,0x79,0x51,0x18,0xE7,0xB3,0x4D,0x4A,0xFD,0x0F,0xFB,0xEA,0x07 -,0xEB,0xAE,0x46,0xD7,0x56,0xED,0xDA,0xAA,0x0D,0xC7,0xE0,0x3E,0xE1,0xA1,0xA5 -,0xA7,0x89,0x64,0xB3,0x16,0xB9,0xDB,0x60,0x86,0x61,0x50,0x60,0x0C,0x3E,0x2E -,0x9E,0x30,0xC0,0x0E,0x45,0x19,0x9A,0x13,0xD0,0x1C,0xC6,0xC3,0x00,0xE4,0x00 -,0x84,0xD8,0xA9,0xA7,0x1E,0x33,0x4F,0x6C,0x83,0xEF,0x13,0x71,0xD9,0x27,0xA5 -,0x9A,0x06,0xE8,0x27,0x1E,0x5B,0x03,0x18,0x63,0xD1,0x5B,0x11,0x82,0x0F,0xCF -,0x00,0xE3,0x39,0xD7,0x60,0xF8,0x2F,0x7F,0xFE,0xD2,0xF8,0x5D,0x60,0xBA,0x49 -,0x91,0x55,0xF0,0x8B,0x05,0x62,0x37,0x46,0x4A,0x88,0xBE,0xEE,0x55,0x23,0xD8 -,0xF3,0x56,0xE8,0x75,0xC6,0x1B,0xAA,0xBE,0xAA,0x96,0x2D,0xBD,0xBE,0xED,0xB8 -,0x26,0xD5,0x51,0x1D,0x58,0x8C,0x37,0xE2,0x8D,0xCA,0x9C,0x13,0xF5,0xC2,0xA9 -,0x18,0xFE,0x66,0xD5,0xED,0xE1,0x5E,0xE3,0x8F,0x68,0x6F,0xFB,0xC3,0x0A,0xE6 -,0x9B,0x69,0xEE,0x88,0x96,0xFF,0x00,0x45,0x94,0xFE,0xE4,0xBE,0x05,0x44,0x80 -,0xFC,0x94,0xB2,0x33,0xAE,0x3A,0x23,0x72,0xC8,0xE0,0xD9,0xED,0x49,0xE1,0xCE -,0xD0,0xB9,0xEF,0x33,0xA6,0xD8,0xA9,0x6B,0xBE,0x0A,0xDA,0x27,0x90,0x7F,0x10 -,0x00,0x74,0xA6,0x63,0xD3,0xE2,0x3E,0x8B,0x9C,0x07,0xF6,0x03,0x0F,0xD3,0x0E -,0x4E,0x45,0xE5,0xE5,0xB5,0x4C,0x6F,0x34,0xF1,0xB4,0xD4,0xA7,0x1F,0x1F,0x0C -,0x63,0x2D,0xC0,0x0C,0x79,0xCA,0x07,0x76,0x51,0xDC,0x0E,0xAC,0xA3,0xA6,0x4A -,0xA8,0x3B,0x82,0x12,0x58,0x88,0x21,0x5E,0x37,0x5E,0xA3,0xB8,0x60,0x7F,0xE2 -,0x35,0x1F,0xB4,0xA9,0xDB,0xB5,0xB1,0x58,0xE4,0x27,0xF8,0x5C,0xC7,0x8D,0xB6 -,0x42,0x73,0xE4,0x9C,0x67,0xE1,0x9B,0xE8,0x00,0x25,0x0F,0xC8,0x15,0xE8,0x54 -,0x72,0xE8,0xCA,0x41,0x0C,0x91,0xCD,0x0A,0x4D,0x0C,0x89,0x24,0x6E,0xA1,0x91 -,0xD4,0xE4,0x30,0x3D,0x41,0x07,0xDC,0x6B,0x47,0xBB,0x2D,0x0B,0x59,0x03,0xD5 -,0x43,0x4E,0x67,0x90,0x20,0x49,0xE0,0x56,0xE2,0xD5,0x11,0x83,0xC8,0x05,0x6C -,0x8E,0x32,0x23,0x7A,0xA3,0x6C,0x8C,0x37,0xBA,0xF2,0x24,0x79,0xC1,0xFF,0x00 -,0xCB,0x57,0x24,0xA4,0x63,0x8B,0x2D,0x6C,0xBC,0x69,0xC9,0xED,0x47,0x33,0x1F -,0xEE,0xBE,0x91,0xB9,0x3E,0x9F,0xCA,0xC7,0x8F,0x66,0x40,0x24,0x5A,0x76,0x35 -,0x3B,0x62,0xBA,0x4A,0xBB,0x74,0x62,0x69,0xC5,0x4B,0xAA,0xE5,0x2A,0x02,0xF1 -,0xF3,0xD3,0xD9,0xC8,0xE9,0xC5,0xBD,0x99,0x70,0x30,0xC0,0xF4,0x00,0x8D,0x52 -,0x77,0x9D,0xB8,0x2A,0x26,0xF1,0x2B,0x61,0x21,0xE2,0xB2,0xD4,0x1B,0x85,0x07 -,0xB7,0x95,0xF1,0x51,0xF9,0xAA,0x47,0xC8,0x2D,0x42,0x4A,0x47,0xE9,0xAB,0x66 -,0xF3,0x23,0x6D,0x5B,0x84,0x97,0xB4,0x04,0xD9,0x2A,0x1B,0x37,0x34,0x03,0x3F -,0x08,0xE7,0xFE,0x92,0xBF,0x24,0xFF,0x00,0x58,0x3F,0x47,0xE9,0x87,0xE5,0x12 -,0xDD,0xBC,0x21,0xF1,0xBE,0x9E,0x54,0x20,0x8B,0x8E,0xDA,0x3D,0x57,0xB3,0x79 -,0x15,0x3D,0x0F,0xF4,0xA9,0xD6,0x2F,0xD3,0x55,0xED,0x50,0xD2,0xD4,0x41,0x7D -,0xD9,0xB1,0x4B,0x59,0xC6,0x28,0xEE,0x14,0x41,0x65,0x56,0x38,0xE2,0x64,0x4C -,0x32,0xFE,0xB9,0x24,0x6B,0x4D,0xB3,0xA7,0x92,0xE1,0x47,0x4E,0x56,0x25,0xE3 -,0x74,0xB3,0xD2,0xD4,0xD5,0xCA,0xFD,0x73,0x3A,0x87,0xA5,0x94,0x71,0xF9,0x9F -,0x87,0x04,0xFD,0x4E,0x7A,0xF6,0xD6,0xE7,0x6D,0xD2,0x45,0x4F,0x3D,0xE2,0x3E -,0x39,0x78,0x2F,0x35,0xF1,0xA9,0x62,0x4F,0x15,0xF8,0x87,0x20,0x2E,0x7F,0x08 -,0xC1,0x1D,0x06,0xB5,0x5B,0x32,0x55,0xF8,0xA5,0xA7,0x51,0x81,0x1C,0xF7,0x48 -,0x40,0xF9,0x04,0xAD,0xE4,0x07,0xFF,0x00,0x78,0xEB,0x8B,0x6C,0x6F,0x22,0xAA -,0x0D,0xB5,0xB6,0x67,0xA8,0xAC,0xF3,0x64,0xB7,0x57,0xD3,0xC2,0x78,0xA6,0x39 -,0xE5,0x8D,0x31,0xE5,0x92,0x49,0x3E,0xB3,0xD7,0x23,0xF4,0xD4,0xC6,0x48,0x16 -,0x56,0xCC,0xCC,0x5D,0x3D,0xA3,0xFE,0x5F,0xDC,0x7B,0xFE,0xFD,0x3E,0x9A,0x85 -,0x54,0x54,0xA7,0xF6,0x56,0x9A,0x19,0x25,0x41,0x24,0xBB,0x97,0x84,0x6A,0x58 -,0x65,0xB8,0xDC,0xC9,0xC0,0x1E,0xF8,0x0B,0xFD,0x06,0xA6,0x72,0x35,0x44,0x8C -,0x56,0x30,0x21,0x8C,0x77,0x91,0xFA,0x9F,0xD8,0x7F,0x5E,0xA7,0xE5,0xD8,0xE8 -,0x3F,0x6B,0x6A,0xE0,0xA2,0x80,0xCB,0x3B,0x30,0x00,0x12,0x15,0x10,0xB3,0x36 -,0x3E,0x4A,0x32,0x4F,0xED,0xA8,0x4D,0x18,0x9E,0xB3,0x65,0x50,0x42,0x1A,0x34 -,0x17,0xCA,0xE3,0x2F,0x96,0xCB,0x96,0x92,0x39,0xAA,0x1A,0x67,0x1F,0x4C,0x43 -,0xCB,0xE7,0xFB,0x7B,0xE4,0x78,0x87,0x7A,0x8A,0xDB,0x61,0x6A,0x3A,0x44,0x92 -,0x4A,0x9B,0xA1,0x34,0x91,0xD4,0x16,0x03,0x8F,0x25,0x3C,0xA4,0xC9,0x20,0x90 -,0xA0,0x96,0xC8,0xF4,0x8F,0x98,0xD7,0xEE,0xCE,0x81,0x6E,0xF7,0x35,0xBD,0xC4 -,0x85,0x68,0x68,0x29,0xCD,0x0D,0xB1,0x9D,0x83,0x2C,0x9D,0x83,0xCA,0x14,0x7A -,0x40,0xF4,0x84,0x1C,0x7B,0x80,0xD9,0x27,0xA6,0x82,0x61,0x22,0xC8,0x4E,0x63 -,0x97,0x89,0xC7,0x40,0xCB,0x95,0xFF,0x00,0xD0,0xFF,0x00,0x9E,0xB1,0xE9,0x69 -,0xAA,0x6E,0x3B,0xE7,0x65,0x59,0x08,0x8A,0x6F,0x8E,0xDC,0x54,0x8D,0x22,0xAA -,0x95,0x3E,0x5C,0x2F,0xE7,0xB9,0xC6,0x4E,0x46,0x22,0xC7,0xEF,0xAF,0x51,0x2C -,0xA0,0xB2,0xF1,0x8E,0x66,0x41,0xEA,0x08,0xD8,0x6C,0xFE,0x87,0xB7,0xEE,0x75 -,0x2F,0xFB,0x33,0x5B,0x63,0xDC,0xFE,0x2E,0xDC,0x37,0x14,0xB4,0x52,0xFC,0x36 -,0xD6,0xA4,0x34,0xB4,0xF2,0xB1,0x1C,0x45,0x65,0x47,0xF7,0x80,0x60,0x90,0xC5 -,0x62,0x50,0x3B,0xF4,0xF3,0x0E,0x7B,0x8D,0x24,0x74,0x46,0xE5,0x8C,0x49,0x76 -,0xDB,0x40,0xF6,0x5B,0xA3,0x37,0xF4,0xA4,0xA8,0xC7,0xF9,0xE3,0x51,0x3F,0xB3 -,0xDB,0xF9,0xFB,0x4E,0xF9,0x58,0x3B,0x54,0xEE,0xBB,0xCC,0xA3,0xF4,0x35,0xD3 -,0x01,0xFF,0x00,0x0D,0x4C,0x6F,0x8B,0xCA,0xED,0x61,0x03,0xA9,0x5A,0xE7,0x73 -,0xFA,0x7C,0x34,0xE3,0x3F,0xD5,0x87,0xF5,0xD4,0x27,0xEC,0xC2,0x44,0x9E,0x0C -,0x5B,0x2A,0xBD,0xEA,0xEB,0x6E,0x35,0x24,0xFC,0xFC,0xCA,0xE9,0xD8,0x7F,0x91 -,0x1A,0x8A,0xB3,0x34,0xD3,0x58,0x3B,0x86,0xEF,0x41,0x60,0xB0,0xD7,0xDF,0x2E -,0xB3,0x88,0x28,0x68,0x29,0xDE,0xA6,0xA2,0x43,0xFC,0xA8,0x8A,0x58,0x9F,0xAF -,0x41,0xDB,0x41,0xCE,0x5F,0x6D,0x9D,0xF7,0x71,0xA9,0x8E,0xD3,0xE0,0xBE,0xCF -,0x26,0x6B,0xFE,0xE7,0x92,0x35,0xAB,0x58,0xCF,0x58,0xE0,0x66,0xC2,0xC6,0x4F -,0xB7,0x36,0x19,0x27,0xD9,0x14,0xE7,0xA3,0x6A,0xF0,0xF0,0x93,0x64,0x5B,0x3C -,0x3B,0xF0,0xFE,0xD5,0xB4,0xED,0x81,0x59,0x28,0xE2,0x1E,0x7C,0xC1,0x70,0x6A -,0x26,0x3D,0x64,0x90,0xFD,0x59,0xB3,0xFA,0x0C,0x0F,0x6D,0x73,0xE7,0xD9,0x17 -,0x6E,0x5C,0x77,0xFF,0x00,0x89,0x3B,0x8F,0xC7,0xFD,0xD3,0x4E,0xCA,0xD5,0xB5 -,0x12,0xC1,0x64,0x8E,0x4E,0xBC,0x17,0xF0,0x33,0x2F,0xD1,0x10,0x08,0x81,0xF7 -,0xF5,0xFC,0xB5,0xD4,0x75,0xB7,0x2A,0x2A,0x3A,0x88,0x69,0xA7,0xA8,0x51,0x51 -,0x36,0x7C,0xA8,0x17,0x2D,0x23,0x81,0xDC,0x85,0x1D,0x48,0x19,0xEA,0x71,0x81 -,0xEF,0xA0,0xCB,0xD7,0x85,0x7D,0x65,0x25,0x05,0x1C,0x95,0x95,0xD5,0x30,0xD2 -,0xD3,0x44,0x39,0x49,0x2C,0xAE,0x11,0x14,0x7C,0xC9,0x3D,0x06,0xA3,0xDB,0x87 -,0x79,0x51,0x50,0x72,0x82,0x80,0x2D,0x6D,0x48,0x63,0x1B,0x1E,0x47,0xCA,0x8D -,0xC7,0xE2,0x52,0xCA,0x09,0x77,0x00,0x1C,0xA4,0x61,0x98,0x7F,0x30,0x51,0xEA -,0xD5,0x0D,0xE2,0x67,0x8B,0x54,0x74,0x15,0x98,0x96,0xBC,0x5C,0xEE,0xC8,0x15 -,0xE3,0x45,0x95,0x23,0x8E,0x98,0x31,0x0A,0xAF,0xCB,0x98,0x8E,0x9D,0x09,0x70 -,0x3C,0xCF,0x33,0x91,0x0E,0x31,0x39,0xEB,0x1E,0x82,0xD4,0xDE,0x1E,0x20,0x14 -,0x2F,0x1D,0xBA,0x36,0xA4,0x58,0xC8,0xCD,0x45,0x44,0x7F,0x7C,0x32,0xA4,0x8E -,0x11,0x30,0xFB,0xAC,0x8C,0x90,0x64,0x1C,0xC8,0x07,0x84,0x52,0x8D,0x73,0xA7 -,0x88,0xFE,0x30,0xDA,0x2D,0xF4,0xF3,0x4D,0x1D,0x42,0x57,0x99,0x9E,0x31,0x24 -,0x8C,0xE2,0x65,0x98,0x17,0x60,0x1C,0x29,0x70,0xF5,0x61,0x4A,0xC9,0x86,0xE4 -,0xB1,0x29,0x51,0xC1,0xA0,0x7C,0x46,0x69,0x0D,0xFD,0xE2,0xD5,0xCE,0xFF,0x00 -,0xCE,0x34,0x72,0xDC,0x64,0x06,0x34,0xE2,0xBF,0x08,0x8A,0x24,0x66,0x60,0x62 -,0x65,0xFB,0xEE,0x5C,0x63,0x62,0x5C,0x2A,0x12,0x5F,0x31,0x16,0x21,0xF5,0x5A -,0x55,0xD4,0xD4,0xD6,0x54,0x35,0x45,0x5D,0x44,0xB5,0x13,0x36,0x39,0x49,0x2B -,0x96,0x63,0x81,0x81,0x92,0x7A,0xF6,0x00,0x68,0x25,0xDB,0xDB,0xC4,0x6D,0xC1 -,0xB9,0x2E,0x52,0xD5,0x0A,0xDA,0xCA,0x65,0x96,0x1F,0x2A,0x42,0xD3,0x86,0x95 -,0x83,0x23,0x2C,0xAB,0xCD,0x55,0x78,0xC6,0xFC,0xDF,0x31,0xA0,0x55,0x23,0x8F -,0x30,0xEC,0x0B,0x98,0x5E,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A -,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69 -,0xA6,0x81,0xAB,0x73,0xC0,0x9D,0xD1,0x2D,0xB1,0x25,0xA6,0x56,0xA8,0x75,0x0E -,0x94,0xF5,0x80,0xC8,0xEE,0xAB,0x4B,0x24,0xC8,0x23,0x70,0xB8,0xE3,0x1A,0xC7 -,0x3B,0x10,0x7D,0x5E,0xA3,0x59,0x90,0x3D,0x24,0x9A,0x8F,0x59,0x96,0x6B,0x8C -,0xD6,0xBB,0x82,0x56,0x41,0x1C,0x12,0x30,0x47,0x8D,0x92,0x68,0xC3,0xA3,0xA3 -,0xA1,0x47,0x52,0x3D,0xB2,0xAC,0x46,0x41,0x0C,0x33,0x95,0x20,0x80,0x40,0x5F -,0x77,0x4B,0x61,0xA1,0xBE,0xDE,0x36,0xD5,0xCA,0x38,0x9E,0x82,0xAE,0x7A,0xB9 -,0xE8,0x23,0x88,0x30,0x26,0x9F,0xE2,0xA6,0x46,0x42,0x47,0x62,0xA5,0x47,0xCB -,0xA3,0x2F,0xE9,0xAF,0x6F,0x08,0xEB,0x6E,0x69,0x4E,0x76,0x04,0x95,0x10,0xC7 -,0xB9,0x6C,0x13,0xFF,0x00,0x15,0xDB,0x13,0xC8,0x4F,0x09,0xC6,0x09,0x92,0x9C -,0x92,0x06,0x51,0x94,0xBA,0x91,0xF2,0x66,0xFC,0x83,0x5B,0x7D,0xA9,0x46,0x9B -,0xE3,0x6D,0x1A,0x5A,0x79,0x9A,0x7D,0xCD,0x6B,0xA4,0x4A,0xFB,0x75,0x6D,0x41 -,0x4C,0x56,0x45,0x2C,0xD3,0xBF,0xA8,0xA9,0x60,0x39,0x07,0xF2,0xE4,0x00,0x9E -,0x12,0xA9,0x07,0xAA,0x6A,0x21,0x7D,0xA3,0xAA,0xBA,0x25,0x2D,0xF2,0xC5,0x23 -,0xD0,0xEE,0x0B,0x4C,0xE5,0xA1,0xE6,0x38,0x49,0x1C,0xA8,0x7D,0x50,0xC8,0x0F -,0x62,0x08,0xEC,0x7A,0x7E,0xCC,0x4E,0xB7,0x59,0xC9,0x66,0x63,0x5D,0x63,0xE1 -,0x8E,0xE4,0xA2,0x96,0xC9,0x6F,0x9A,0x8C,0x3C,0x76,0x2A,0xF3,0xE5,0x52,0xC7 -,0x2F,0xE3,0xB6,0x54,0x83,0xC5,0xE8,0x65,0xFC,0xA0,0x30,0x2A,0x99,0xE8,0x3F -,0x07,0x4F,0xBB,0xE5,0x3A,0xB8,0xD1,0xD3,0xDC,0x28,0xA4,0xA3,0xAA,0x8F,0x9C -,0x52,0x0E,0xA0,0x12,0x08,0x20,0xE4,0x10,0x47,0x50,0xC0,0x80,0x41,0x1D,0x41 -,0x00,0x8E,0xA3,0x5C,0xDF,0xE1,0xE6,0xF4,0xA2,0xAF,0xA4,0xAA,0xDD,0x74,0x34 -,0x6D,0x3D,0x0D,0x6A,0x88,0x77,0x96,0xDF,0x44,0x26,0x5A,0x69,0x80,0xE3,0xF1 -,0x51,0xA7,0xE2,0x2C,0x00,0xF5,0x01,0xD5,0x94,0x02,0x3D,0x69,0x83,0x7B,0xED -,0x2B,0xC4,0x55,0x50,0x53,0xD3,0x7F,0x10,0x8E,0xE1,0x14,0xD0,0xF9,0xF6,0xFA -,0xF4,0x70,0xCB,0x5B,0x07,0x4C,0x36,0x47,0x4E,0x6B,0x90,0x1B,0xE7,0x90,0xC3 -,0x19,0x2A,0xBD,0xE3,0x8E,0x1C,0xD9,0xD4,0xF0,0x3D,0x55,0x04,0xF6,0x8B,0xD2 -,0x25,0x50,0x28,0x63,0x77,0x65,0x1C,0x6A,0x63,0x3D,0x39,0x10,0x3A,0x03,0x8E -,0x8C,0x07,0xBF,0x51,0x80,0x46,0xBC,0x2C,0xB5,0x15,0x14,0x35,0x7F,0xC0,0xEE -,0x52,0xBC,0xB2,0x2A,0x96,0xA3,0xA9,0x73,0x93,0x53,0x10,0xF6,0x63,0xFE,0xB1 -,0x7A,0x03,0xF9,0x86,0x18,0x77,0x60,0xBB,0xAD,0x62,0x5D,0xA8,0x22,0xB8,0xD2 -,0x79,0x2E,0xEF,0x14,0x8A,0xC2,0x48,0x66,0x8F,0x1C,0xE1,0x90,0x76,0x75,0xCF -,0xB8,0xF9,0x1E,0x84,0x12,0x08,0x20,0x91,0xA6,0x0C,0xA6,0x50,0xCA,0x55,0x80 -,0x2A,0x46,0x08,0x23,0xA1,0xD5,0x2F,0x7E,0xB5,0x9B,0x47,0x8C,0xF6,0x2B,0x5D -,0x2C,0xB1,0x9B,0x75,0x36,0xDE,0xAE,0x7A,0x58,0x40,0x3C,0xE9,0xD1,0xAA,0x29 -,0x87,0x96,0x4F,0x62,0x80,0x8F,0x40,0xE9,0x80,0x08,0xEC,0x06,0xAD,0x6B,0x1D -,0xCA,0x4A,0x96,0x9A,0x82,0xB9,0x52,0x2B,0x9D,0x2E,0x3C,0xF8,0xD7,0xA2,0xBA -,0x9C,0xF1,0x95,0x33,0xD7,0x83,0x60,0xE3,0xBE,0x08,0x65,0x27,0x2A,0x75,0x58 -,0x54,0xCD,0xFC,0x57,0xC7,0x1D,0xCD,0x5C,0xA7,0x94,0x36,0x8B,0x75,0x25,0xA9 -,0x08,0xED,0xE6,0x37,0x3A,0x89,0x47,0xEA,0x04,0x91,0x03,0xFF,0x00,0xEB,0x58 -,0xF2,0x74,0xD5,0x7B,0x55,0x96,0x86,0xA8,0x6D,0xC1,0xBB,0x42,0xF0,0x08,0x2F -,0xF5,0x22,0x36,0x3D,0x70,0x30,0x99,0xE9,0xFE,0xD7,0x2F,0x96,0xB4,0x1B,0x3E -,0x39,0x85,0xC9,0xA4,0x49,0x11,0x54,0x4D,0x73,0x95,0xE4,0x2B,0xDD,0x5E,0xB0 -,0x28,0x20,0x7B,0x67,0xC9,0x6F,0xE9,0xEF,0xAF,0x6A,0x2B,0xD2,0x51,0xED,0xEB -,0xDD,0xFE,0xA1,0xDA,0x38,0x2A,0x2B,0xEB,0x6B,0x94,0xC0,0xBE,0x6C,0xAF,0x1B -,0xCC,0xE5,0x18,0x0C,0x61,0x46,0x31,0xD4,0xE4,0x63,0xBE,0x35,0x1C,0xAD,0xA9 -,0x96,0xCB,0x63,0xAD,0xB7,0x7C,0x64,0xB1,0x5C,0xC5,0x1D,0x1D,0xAC,0x04,0x40 -,0xCC,0x6A,0xE5,0x0F,0x51,0x2E,0x49,0xF4,0xA8,0xE7,0x52,0xE0,0x93,0x8F,0xC0 -,0x70,0x41,0xD7,0x16,0xD9,0xD6,0x99,0x29,0x67,0xB7,0xED,0x3A,0x7A,0x76,0x86 -,0x42,0xCD,0x25,0xEA,0xAA,0x49,0xE4,0x0B,0x80,0x03,0x12,0x59,0x80,0xC7,0x2F -,0x32,0x75,0xF9,0x7E,0x12,0x3A,0x6B,0x7D,0xB9,0x37,0x2D,0x0D,0x9A,0x05,0x92 -,0xAC,0x4D,0x5B,0x52,0xEC,0x12,0x1A,0x68,0xA2,0x3C,0xA4,0x7F,0x60,0xB1,0xE7 -,0x24,0xF6,0x3E,0xAF,0xD4,0x6A,0xBC,0xF2,0x6B,0xAE,0x1B,0xB2,0x9E,0xA4,0xDD -,0x24,0xDB,0xD6,0x54,0xA4,0x4A,0x4B,0x6D,0x7D,0x6C,0x41,0x3E,0x22,0x28,0xC9 -,0x56,0xF8,0x77,0xC0,0x8C,0xE5,0xD4,0x8E,0x41,0x89,0x00,0x0C,0x13,0xD4,0x6A -,0xCA,0xDB,0xFB,0x7A,0x86,0xD9,0x05,0x54,0xD6,0xE3,0xF1,0x15,0xAC,0x08,0x8A -,0xB6,0xA5,0x84,0x8E,0xC0,0xA8,0x20,0x72,0x1D,0x93,0x96,0x7D,0x2B,0x81,0xF4 -,0xD0,0x42,0xA8,0xB6,0x7D,0xFB,0x76,0xEE,0x53,0x7D,0xDD,0xF2,0xFF,0x00,0x0E -,0xA4,0x95,0x71,0x15,0xB5,0x64,0xE5,0x2F,0x94,0x31,0xE8,0xCF,0xF2,0x03,0xD3 -,0x96,0x3A,0x9C,0x90,0x42,0xE7,0x53,0xFB,0xFD,0xCE,0x0D,0xBF,0x6B,0xA7,0x8A -,0x92,0x8B,0xCE,0x9E,0x57,0x5A,0x6A,0x1A,0x38,0x70,0x9C,0xDF,0x1D,0x14,0x7B -,0x2A,0x80,0x09,0x27,0xB0,0x03,0x5F,0xBB,0xAA,0x69,0xA3,0xB1,0xC9,0x35,0x2C -,0xB4,0x34,0xF5,0x88,0x03,0xC1,0x25,0x6C,0xDE,0x54,0x71,0x37,0xE6,0x24,0x03 -,0xD8,0x13,0xD3,0xDF,0xA8,0xEC,0x75,0x0A,0xDB,0x97,0xFA,0x33,0x5D,0x3C,0x3B -,0x8A,0xE9,0x44,0xF7,0x39,0x18,0x54,0x25,0xC6,0x29,0xB9,0xD1,0xBC,0x48,0xE1 -,0x9A,0x28,0x58,0x80,0x13,0x01,0x7A,0x81,0x9C,0xF7,0x24,0x9E,0xC1,0x95,0xE1 -,0xF4,0x75,0xD0,0x50,0xDD,0x16,0xBF,0x9D,0x4D,0xCD,0x6B,0xDA,0xA6,0x46,0x4A -,0x99,0x54,0x4B,0xE6,0x46,0x8E,0x8D,0xC5,0x01,0x1C,0x48,0xC0,0xC1,0xE9,0xE9 -,0x23,0xDB,0x5D,0x89,0xF6,0x61,0xB7,0x5B,0xE8,0x3C,0x0B,0xDA,0xF3,0xD0,0x95 -,0x79,0x2E,0x54,0x6B,0x71,0xAD,0x98,0x63,0x32,0xD4,0xCD,0xEB,0x95,0x98,0xFB -,0x90,0xC4,0xAF,0xD0,0x28,0x1E,0xDA,0xE3,0x5D,0xC3,0x7F,0xA1,0xA1,0xA8,0xB4 -,0xDF,0xE8,0x68,0xAE,0xEB,0x6F,0x84,0x2D,0x35,0x5C,0xE1,0x3C,0xB4,0x92,0x98 -,0xE4,0x29,0x61,0x91,0x26,0x54,0x9E,0x4A,0x78,0xE3,0xA9,0x1F,0xCC,0x35,0x7F -,0xFD,0x99,0xB7,0x87,0xF6,0x77,0x72,0x43,0xE1,0xD4,0xCD,0xE6,0x59,0x2E,0xC2 -,0x5A,0xBB,0x0C,0xA1,0xB9,0x08,0x25,0x00,0xC9,0x35,0x3E,0x7F,0x23,0x0E,0x52 -,0xA7,0xD7,0x98,0xF9,0x6B,0x31,0x68,0xB7,0x52,0xE9,0x7F,0x15,0xFC,0x73,0x11 -,0x78,0x98,0xDE,0x79,0xFD,0x2F,0x8B,0xFD,0x52,0xD1,0xDD,0xA0,0xAA,0x97,0x1E -,0x5D,0x35,0xBA,0xB2,0xA4,0xFE,0xA8,0x62,0xEB,0xFD,0x19,0xBF,0xAE,0xA2,0x7F -,0x65,0xD8,0x1A,0x9F,0xEC,0xFB,0xB2,0xD5,0xF3,0xC9,0xED,0x89,0x29,0xCF,0xBF -,0x32,0x5F,0x3F,0xF9,0xB5,0xFB,0xE3,0x45,0xD3,0xE0,0xF6,0xEE,0xEF,0x9D,0x5B -,0x0D,0x6C,0xD9,0xD5,0xD3,0x7F,0xBD,0x2A,0xB0,0x4F,0xF3,0x80,0xEB,0x6D,0xE1 -,0x7A,0xD2,0x6D,0x9F,0x06,0x76,0xA4,0x37,0x2A,0x98,0x69,0x21,0xA1,0xB1,0xD1 -,0x45,0x2C,0xB3,0x38,0x45,0x0C,0x21,0x40,0x72,0x4F,0xB9,0x3F,0xE6,0x75,0x58 -,0x4C,0xB5,0xCE,0xFF,0x00,0x6F,0xFB,0xFD,0x55,0xAF,0xC1,0x18,0x6C,0xB4,0x2E -,0xDE,0x7D,0xF6,0xE9,0x0D,0x23,0xC6,0x87,0xD6,0xF1,0x28,0x69,0x08,0x00,0x75 -,0x3E,0xA4,0x8C,0x7F,0xBD,0xF5,0xD5,0xB3,0x71,0xDC,0xB5,0x53,0x79,0x6C,0xBC -,0xAC,0x94,0x13,0x37,0x08,0x67,0xAA,0x84,0xB5,0x6D,0x59,0xF9,0x53,0xD3,0x60 -,0xB6,0x71,0xD7,0x2E,0x32,0x30,0x7E,0xEC,0x8E,0xBA,0xE6,0x2F,0xB6,0x9D,0x75 -,0x3C,0x9B,0x9B,0x62,0xED,0x7B,0x20,0x92,0x2B,0xC5,0x4C,0xD2,0x56,0xD6,0xCD -,0x2C,0xDE,0x65,0x40,0x8B,0x2A,0xA8,0x64,0x70,0x1F,0x0A,0x38,0xCC,0x70,0x32 -,0xAA,0x17,0xA0,0xC7,0x4D,0x05,0xEB,0x6A,0xBB,0x45,0xB4,0x36,0x15,0x97,0x6D -,0x52,0x19,0x2C,0xD4,0xD6,0xFB,0x64,0x51,0x21,0x78,0x54,0xD7,0x4D,0x1C,0x68 -,0x14,0xCA,0xB0,0xB7,0xA6,0x05,0x24,0x64,0xCB,0x3E,0x02,0x9C,0xF2,0x51,0x9C -,0xEA,0x25,0xB8,0x37,0xAD,0x0D,0x9A,0xDD,0x3D,0x4D,0x4C,0xF1,0xDA,0xE9,0x2A -,0x19,0x52,0x47,0x92,0x57,0x96,0x7A,0xC6,0x23,0xD2,0xAE,0xE7,0xEF,0x67,0x62 -,0x08,0xC2,0x00,0xAA,0x01,0xF4,0x2D,0x42,0x74,0xD5,0x41,0xBE,0xFC,0x57,0xB7 -,0x58,0xED,0xA9,0x25,0x34,0xE2,0xB6,0x56,0x92,0x39,0x3E,0x2E,0x47,0xE4,0x1D -,0xCB,0x15,0xF3,0xE1,0x8C,0xC9,0xCE,0xA5,0x97,0x84,0x9F,0x7D,0xCC,0x80,0x53 -,0x02,0xA7,0xD4,0x22,0xD7,0x3B,0x6E,0xFD,0xF9,0x7B,0xBF,0xDC,0xA4,0xAB,0xF8 -,0xCA,0xC8,0x7C,0xD8,0x7C,0xA7,0x2D,0x32,0xB4,0x84,0x32,0xB0,0x95,0x43,0x2A -,0xA0,0x48,0xDF,0xCC,0x7C,0xC4,0x8A,0xA8,0x47,0x1E,0x41,0x98,0x16,0x21,0x70 -,0xF8,0xB7,0xE3,0x4D,0x43,0xAD,0x7D,0x9E,0x85,0xEA,0xAD,0x72,0xC4,0x8D,0x4E -,0x29,0xC4,0x43,0xE2,0x79,0x2F,0x1C,0x24,0xC7,0xA2,0x40,0x8B,0xC8,0x9E,0x08 -,0x18,0xAB,0xC4,0x40,0x4A,0x62,0x49,0x14,0x25,0xFA,0xF5,0x59,0x79,0x9D,0x5E -,0xA4,0x45,0x1C,0x68,0xCE,0xD1,0xC5,0x12,0x61,0x57,0x9B,0x16,0x24,0x93,0x96 -,0x91,0xBA,0x81,0xCD,0xCB,0x39,0x0A,0xA0,0xB1,0xE2,0x31,0xAD,0xD3,0x40,0xD3 -,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D -,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34 -,0x0D,0x34,0xD3,0x41,0x3B,0xF0,0x77,0x7D,0xB6,0xC8,0xBE,0x8A,0xA6,0x8F,0x92 -,0x3B,0x0C,0x49,0xCD,0xB0,0x80,0xF4,0x74,0x65,0x19,0x06,0x37,0x1C,0x79,0x10 -,0x39,0x02,0x91,0xB0,0xCF,0x03,0x1B,0xF4,0x66,0xE1,0xB1,0x51,0xEF,0x7B,0x74 -,0x7B,0xFB,0x62,0xB2,0x35,0x7C,0xA8,0x16,0xB6,0x88,0xB0,0x51,0x56,0x14,0x7E -,0x16,0x39,0xC2,0xCC,0xA3,0xF0,0xB6,0x70,0xC0,0x8E,0xA5,0x48,0x61,0xC7,0x1A -,0xB0,0xFC,0x18,0xF1,0x1A,0xE1,0xB2,0xAE,0xE2,0x2F,0x8C,0x31,0x50,0x4C,0x40 -,0x6F,0x30,0x33,0x44,0x87,0x3F,0xCE,0xAA,0x09,0x28,0x73,0xD4,0xA8,0x2C,0xBF -,0x89,0x43,0x7A,0xA3,0x90,0x27,0x53,0xC5,0x72,0xA4,0xBB,0x0D,0xD3,0xB4,0xEA -,0x9E,0xD7,0xB8,0x28,0xF3,0x1C,0xF1,0xCA,0xBC,0x04,0xC0,0x63,0x94,0x33,0xA1 -,0xEC,0x71,0x8E,0xFF,0x00,0x4F,0xF0,0xB0,0x96,0xEC,0x9F,0x11,0x22,0xAF,0x99 -,0xA0,0xB4,0xCF,0x16,0xD4,0xDC,0x4F,0x30,0xA8,0x9E,0xC5,0x72,0x63,0x15,0x24 -,0xF5,0x1F,0xEB,0xE9,0x64,0x23,0xEE,0x65,0x6C,0x9C,0x82,0x0A,0xBF,0x22,0x19 -,0x5B,0x25,0xB5,0x30,0x9E,0x87,0x69,0xF8,0x96,0x0C,0xAA,0x64,0xB3,0x6E,0x6A -,0x68,0x91,0x9D,0xA2,0x74,0xF3,0xD1,0x08,0xCA,0x37,0x4C,0xA5,0x44,0x0C,0x1B -,0x2A,0xE3,0x92,0xB0,0x6C,0xA9,0x19,0xD4,0x13,0x79,0xEC,0x0B,0xF5,0x2C,0x2D -,0x0D,0xF3,0x6F,0x47,0xB8,0x68,0x17,0xF0,0xD5,0xDB,0xA3,0x2C,0xEA,0x0F,0xB9 -,0x87,0x3E,0x62,0x1F,0xFB,0x32,0xFF,0x00,0xB6,0xB7,0x16,0x98,0x66,0x63,0x5D -,0x1B,0xB3,0x7C,0x4C,0xB3,0x5C,0xFE,0x16,0xD5,0xB8,0x9E,0x3D,0xB9,0xB9,0x9A -,0x20,0x66,0xB6,0x56,0xB8,0x4E,0x4D,0xD8,0x98,0x5C,0xFA,0x66,0x42,0x41,0xC1 -,0x42,0x4E,0x3B,0xE0,0xE7,0x53,0xCD,0x70,0x13,0xDA,0xAA,0x22,0x9A,0x9E,0x9E -,0x0B,0xE5,0x61,0x82,0x8C,0x9F,0x2E,0xD9,0x7D,0xB6,0x9A,0x94,0x8C,0x30,0x1E -,0x85,0x8E,0x65,0x05,0x54,0x8C,0x74,0x03,0x3D,0x8E,0x73,0x83,0xAD,0x85,0x35 -,0x97,0xC5,0xEB,0xC5,0x65,0x3C,0x5B,0x35,0xEB,0xEC,0x34,0xC3,0x22,0x59,0x68 -,0x26,0xAC,0xB6,0xD3,0x28,0xF6,0x3C,0x64,0x93,0x04,0x7F,0xD9,0xAE,0xB7,0xF9 -,0x19,0xF8,0xBA,0xBF,0xC7,0x2B,0xD5,0x3E,0xD5,0xD9,0xED,0xBA,0xA2,0x94,0x45 -,0x79,0xA1,0x6E,0x16,0xB5,0x03,0x91,0xA9,0x95,0xC8,0x1F,0x0E,0xCB,0x90,0x59 -,0x1F,0x1E,0xA1,0xEC,0x17,0x98,0xC1,0x40,0x45,0x20,0x95,0xD5,0x3B,0x23,0x67 -,0x6E,0x7B,0x95,0x75,0x64,0x55,0x3B,0x92,0xBD,0x0C,0x6D,0x36,0x42,0x7C,0x4D -,0x74,0x95,0x95,0x91,0xAB,0xE0,0x9E,0x80,0x65,0x7F,0x45,0x4F,0x90,0xD6,0x4E -,0xD6,0xDB,0x55,0xFB,0x5A,0xDD,0x78,0xBA,0xEE,0xED,0xCB,0x71,0xDC,0x97,0x6A -,0x3A,0x3A,0xA1,0x25,0x55,0x55,0x54,0xD2,0xA4,0x09,0xF0,0xF1,0x48,0x55,0x03 -,0xB1,0xFC,0xC7,0xD5,0x80,0x48,0x38,0xE9,0xAA,0x7B,0x72,0x6E,0xF1,0xB9,0xFC -,0x47,0xAC,0xAA,0xA0,0x72,0xD0,0xD1,0xCD,0x2C,0x16,0xC9,0x02,0xB3,0x21,0xE7 -,0x3C,0xAE,0x26,0x08,0x0E,0x64,0x90,0xF9,0x8C,0x16,0x30,0xAD,0x90,0x7D,0xBA -,0x91,0x8B,0x5B,0x5A,0x88,0xC6,0xD2,0xBA,0xB6,0x82,0xC9,0x6D,0xB7,0x5A,0x2B -,0x9C,0x4B,0x43,0x63,0x48,0x66,0xB8,0x41,0x14,0x65,0x05,0x54,0xEB,0x83,0x0C -,0x00,0xE0,0x06,0x32,0x3A,0xF2,0x6C,0x86,0xF4,0xAB,0x36,0x7E,0x7A,0xCD,0x8D -,0x4F,0x0E,0xF8,0xDF,0x16,0xC3,0xB9,0xEB,0xAB,0xED,0x16,0x45,0x4A,0x8B,0x9D -,0x55,0x74,0x14,0xB2,0xB4,0xB5,0x05,0xDF,0x8C,0xAD,0x94,0x0E,0xD1,0x42,0xCE -,0x4C,0x7E,0x6E,0x38,0x2F,0x5F,0xE6,0xC8,0xD4,0x4F,0x72,0x5F,0x29,0x62,0x85 -,0x9A,0x86,0x78,0xB9,0xB1,0x61,0x0C,0x00,0x89,0x24,0x06,0x40,0x1E,0x4A,0x99 -,0x9D,0x7E,0xEF,0x9C,0x9C,0x94,0x70,0x42,0x4A,0x84,0x28,0xC5,0x42,0x71,0x92 -,0x27,0x7A,0xBA,0x57,0x5E,0x6E,0x73,0x5C,0xAE,0x53,0x99,0xEA,0x66,0x23,0x93 -,0x71,0x0A,0xA0,0x00,0x15,0x55,0x55,0x40,0x54,0x45,0x50,0x15,0x55,0x40,0x55 -,0x50,0x00,0x00,0x00,0x35,0x86,0x9F,0xD2,0xFD,0xB5,0xE2,0x1E,0xD5,0xAE,0xB2 -,0xC3,0x66,0xDA,0x34,0x96,0x6B,0x9D,0xAA,0x8E,0x05,0xA7,0x4A,0x1A,0x59,0x44 -,0xF1,0xC7,0x1A,0x00,0x00,0x1E,0x40,0x95,0x82,0x80,0x3A,0x79,0x91,0xC7,0xF3 -,0x27,0x48,0xAD,0x7E,0x0D,0xEE,0x69,0x1D,0xAE,0x5E,0x1D,0xD8,0xCC,0xC8,0x7E -,0xF2,0x51,0x69,0xA7,0xA9,0x0B,0xF3,0x2D,0x2D,0x3F,0x31,0x18,0xFF,0x00,0xB4 -,0x2A,0x7E,0x9A,0xFE,0x6F,0xDA,0xF7,0x45,0xD6,0x8A,0x78,0x64,0x95,0xE3,0xAF -,0x58,0x8C,0x3C,0x56,0xAD,0x79,0xB2,0xA4,0x5F,0x86,0x34,0x94,0x62,0x58,0x93 -,0x07,0x04,0x44,0xE8,0x71,0x8E,0xBD,0x01,0x16,0x6E,0xD4,0xF1,0xFB,0x72,0xD2 -,0x4D,0x0A,0x5E,0xAA,0xE5,0xAD,0x82,0x39,0x1D,0x90,0x56,0xC0,0xB7,0x24,0x81 -,0x38,0x7A,0x12,0x31,0x3B,0x09,0xC1,0xE4,0x3A,0xB0,0xA9,0x18,0x07,0x20,0x12 -,0xBD,0x43,0xBC,0xF6,0xDF,0x86,0x7E,0x10,0xC7,0x8A,0xEB,0x16,0xCA,0xDA,0x12 -,0xF1,0x6F,0x4C,0xF0,0x50,0xC1,0x2F,0x16,0x1F,0x26,0xC1,0xC1,0xFD,0x35,0xA2 -,0xFB,0x56,0xED,0xCA,0x8B,0xDF,0x83,0x15,0x49,0x6E,0xB6,0x0A,0xE7,0xB5,0xD5 -,0xD2,0xD7,0xFC,0x2C,0x70,0x87,0x76,0x8A,0x19,0x54,0xC8,0x23,0x1F,0x3F,0x2F -,0x97,0x41,0xDC,0x02,0x3D,0xF5,0x41,0xEC,0xFF,0x00,0xB4,0x85,0x9A,0xE2,0x12 -,0x6B,0xB5,0x13,0x52,0x55,0x24,0x2D,0x24,0x92,0xC5,0x5E,0xB2,0xB4,0x61,0x5F -,0x88,0xC8,0xAB,0x64,0x94,0x13,0x90,0xC1,0x20,0xAA,0x63,0x83,0xDB,0xA3,0x01 -,0x6C,0x6D,0xAF,0x1A,0xAD,0x15,0x7F,0x0F,0x1D,0x06,0xEC,0xA7,0x59,0x27,0x8D -,0x5E,0x0A,0x6B,0x8A,0xF9,0x6C,0xE8,0xC3,0x21,0x84,0x75,0x46,0x17,0x60,0x41 -,0xC8,0x29,0x3C,0xD9,0xF6,0xCE,0xA4,0xC6,0xAD,0x66,0x6B,0x31,0x30,0xE7,0x5F -,0xE2,0xF6,0x8A,0xCB,0x54,0xB5,0x55,0x35,0xB4,0x2D,0x6D,0x91,0x59,0x59,0x9A -,0x45,0xE2,0xCA,0x7A,0x60,0xF5,0xE8,0x71,0x91,0xC7,0xBF,0x6E,0xC7,0xA6,0xB3 -,0x7E,0xCF,0xB3,0xD7,0xCF,0x59,0xE1,0x8C,0x4E,0x64,0x6A,0xA5,0xBE,0xA7,0xC3 -,0x06,0x8D,0x83,0x18,0x17,0xCD,0x0C,0x73,0xDB,0x02,0x2E,0x5F,0x4E,0x3A,0xE8 -,0xBB,0xCE,0xDE,0xF0,0xBF,0x7B,0xAC,0xB6,0xED,0xD5,0xB0,0x36,0xF7,0xC7,0x5C -,0x1B,0x92,0xCF,0x4A,0xAB,0x47,0x5B,0x2B,0x7E,0x70,0x66,0x58,0x25,0x39,0xEF -,0xE8,0x32,0x03,0xF3,0x3A,0xCB,0xD9,0x3E,0x19,0x78,0x7B,0xE1,0xAD,0xDE,0x4D -,0xC3,0x63,0xB2,0x5F,0x2E,0x37,0xCF,0x87,0x68,0x60,0x9E,0xB6,0x36,0x02,0x08 -,0xF1,0xD5,0x44,0x8C,0xA9,0x0C,0x43,0x03,0xAB,0x1E,0xA4,0x64,0x02,0x73,0x83 -,0xE7,0xF4,0xFE,0x96,0xBE,0x0D,0xF8,0xFD,0xBE,0xB7,0xBA,0xFB,0xC7,0x97,0xDC -,0xA2,0x9F,0x96,0x39,0xAE,0xF3,0xDC,0xF3,0x9F,0xE4,0x67,0x1F,0xD9,0x6A,0xBE -,0xD0,0x35,0x52,0xD4,0xED,0x4F,0x15,0x44,0x1D,0x19,0xE8,0x2D,0x56,0x08,0xFF -,0x00,0xC5,0x34,0xB2,0xB3,0x63,0xF5,0xC5,0x6A,0x7E,0xD8,0xD4,0xFB,0x7D,0xDC -,0xA9,0x2C,0x71,0xD3,0x88,0x23,0x8A,0x39,0xA9,0x95,0x62,0x82,0x56,0x55,0x96 -,0x48,0x72,0x38,0x81,0x18,0x63,0xE5,0xC6,0xEC,0x3A,0x06,0x63,0x96,0xC6,0x02 -,0x49,0xDB,0x51,0x6B,0xCE,0xFE,0xD8,0x56,0x5B,0x41,0x83,0x70,0x98,0xEF,0x97 -,0x1B,0x9D,0x64,0x77,0x01,0x0D,0xB6,0x06,0xA8,0xF8,0xFA,0xE8,0xDA,0x33,0x12 -,0x52,0xA7,0xE2,0x9B,0xCB,0x31,0x44,0xA1,0xC7,0xA0,0x79,0x63,0x91,0x04,0x95 -,0xD7,0x2B,0x78,0xAD,0xF6,0x88,0xBA,0xDD,0xAE,0x33,0x4F,0x6B,0x91,0x69,0xE5 -,0x2E,0x55,0x62,0x82,0x66,0x66,0x54,0xE6,0x43,0xA3,0xD4,0xA1,0x5E,0x01,0x95 -,0x7F,0x0D,0x2F,0x10,0xC1,0xD4,0xB4,0xCE,0x54,0x83,0xE9,0x7C,0x85,0xCF,0xBF -,0x77,0xDC,0x1B,0x56,0x9E,0xBE,0xB6,0xB2,0xBA,0x25,0xBC,0x3A,0xF1,0x96,0x39 -,0x27,0xCC,0x83,0xD2,0xCE,0x16,0xA2,0x59,0x3A,0xAE,0x55,0x59,0x96,0x16,0x0B -,0xCB,0x04,0x2D,0x1B,0x77,0xD7,0x1E,0xEE,0xED,0xE9,0x51,0xB8,0x6E,0xD5,0xB7 -,0x9B,0x80,0x96,0xE9,0x78,0xAE,0x8C,0x47,0x2D,0x7D,0x67,0x4F,0x25,0x78,0xA0 -,0x0B,0x0C,0x4A,0x78,0xAF,0x10,0x1D,0x03,0x31,0x7C,0xA9,0x56,0x0B,0x1B,0x0C -,0xEA,0x3D,0x7A,0xBB,0x57,0xDE,0x2A,0xD6,0xAA,0xE1,0x2A,0x49,0x22,0x46,0xB1 -,0x20,0x48,0x92,0x24,0x55,0x1E,0xC1,0x10,0x05,0x19,0x39,0x62,0x40,0xF5,0x33 -,0x33,0x1C,0xB3,0x12,0x70,0x74,0x1E,0x95,0x33,0xCD,0x53,0x53,0x2D,0x4D,0x4C -,0xD2,0x4D,0x3C,0xAE,0x5E,0x49,0x24,0x62,0xCC,0xEC,0x4E,0x4B,0x12,0x7A,0x92 -,0x4F,0x5C,0xEB,0xCF,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34 -,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3 -,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40,0xD3,0x4D,0x34,0x0D,0x34,0xD3,0x40 -,0xD3,0x4D,0x34,0x1B,0xAD,0xB7,0xB9,0xAE,0xB6,0x02,0x3E,0x02,0x45,0x01,0x64 -,0x32,0xC7,0x90,0x43,0xC5,0x27,0x02,0xBC,0xD2,0x45,0x21,0xD0,0xF5,0x04,0x85 -,0x60,0x1F,0x82,0x07,0x0C,0x14,0x0D,0x5F,0x1B,0x1F,0xED,0x09,0x5C,0x62,0x8E -,0x9E,0xE8,0xB4,0x75,0xAE,0x65,0x48,0x92,0x3A,0xB9,0x45,0x2C,0xE7,0x9B,0xB0 -,0x1F,0x7C,0x17,0xC8,0x60,0xA0,0x29,0x67,0x71,0x00,0x1C,0xBD,0xC0,0x24,0x73 -,0x6E,0x9A,0x0E,0xC0,0xB2,0x78,0xEB,0xB1,0x69,0xEE,0x17,0x46,0xBB,0xD4,0x54 -,0x5B,0xE5,0x9E,0xA1,0x5D,0x50,0x2A,0xD4,0xAE,0x04,0x48,0xBD,0x1E,0x02,0xEA -,0x7A,0xA9,0xF7,0xD6,0x6D,0xC3,0xC7,0xCD,0x94,0xB6,0xF9,0xAA,0xED,0x8E,0xF5 -,0xAB,0x16,0x39,0x19,0x25,0x8E,0x00,0x32,0xC1,0x41,0xE0,0xCD,0xE7,0x30,0xC9 -,0x19,0xE1,0x1B,0x90,0x32,0x71,0x80,0x75,0xC6,0x5A,0x6A,0xEA,0x62,0xDB,0xF1 -,0x3B,0xC5,0x76,0xDD,0x75,0x12,0x51,0xD5,0xD4,0x55,0xC9,0x6A,0x7A,0x87,0xF8 -,0x8A,0x2B,0x5B,0x7C,0x2C,0x53,0x71,0xE2,0xB1,0xC9,0xE7,0x48,0xAC,0xF2,0xE4 -,0x2F,0x67,0x8A,0x3C,0x71,0x5F,0x4E,0x73,0x8A,0xCA,0xA6,0xE5,0x23,0x42,0xF4 -,0xD4,0xB1,0xAD,0x1D,0x2B,0x8C,0x34,0x51,0x77,0x90,0x7A,0x3F,0x1B,0x7E,0x27 -,0xEA,0x8A,0xD8,0x27,0x88,0x6C,0x95,0x0B,0x9C,0x6B,0x07,0x4D,0x45,0x34,0xD3 -,0x4D,0x03,0x4D,0x34,0xD0,0x35,0xB0,0xB4,0x5E,0x6E,0x96,0xAE,0x4B,0x41,0x59 -,0x24,0x70,0xC9,0x24,0x72,0xCD,0x4E,0xD8,0x78,0x27,0x68,0xC9,0x29,0xE6,0xC4 -,0xD9,0x49,0x00,0xC9,0xF4,0xB8,0x23,0x04,0x8C,0x60,0x9D,0x6B,0xF4,0xD0,0x4F -,0x36,0x77,0x8A,0x1B,0x83,0x6E,0x8A,0x91,0x4F,0x57,0x5B,0x0A,0xCB,0xC9,0xD6 -,0x2A,0x29,0xD6,0x0A,0x76,0x72,0x57,0x02,0x4A,0x66,0x47,0xA7,0x78,0xC0,0x0D -,0xE9,0x11,0xA9,0xCB,0x67,0x96,0x06,0x35,0x67,0xD5,0xFD,0xA4,0xA6,0x8B,0x6E -,0x51,0x45,0x47,0x67,0xB0,0x4F,0x74,0x1C,0x3E,0x26,0x41,0xB5,0x29,0xE9,0x5E -,0x2F,0x49,0xE4,0x63,0x9B,0xCF,0x95,0x0B,0x06,0xC0,0x04,0xD3,0x80,0x46,0x4E -,0x17,0x1C,0x4F,0x3A,0x69,0xA0,0x92,0x6E,0xDD,0xEB,0x7F,0xDC,0xF5,0x32,0x55 -,0x5C,0xEA,0xDD,0xAA,0x6A,0x23,0xE1,0x5B,0x32,0xCB,0x21,0x7A,0xD3,0xC8,0x36 -,0x65,0x2C,0xC7,0x20,0x15,0x4C,0x20,0xC2,0x2F,0x00,0x55,0x54,0xE4,0x98,0xDE -,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A -,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68 -,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A -,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69 -,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6 -,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81 -,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6 -,0x9A,0x68,0x1A,0x69,0xA6,0x81,0xA6,0x9A,0x68,0x3F,0xFF,0xD9}; -/* end binary data. size = 22092 bytes */ -#endif - -mblk_t *ms_load_generate_yuv(MSVideoSize *reqsize) -{ - YuvBuf buf; - mblk_t *m=NULL; -#ifndef MS2_MINIMAL_SIZE - m=jpeg2yuv((uint8_t*)&def_mire,sizeof(def_mire),reqsize); - if (m!=NULL) - { - return m; - } -#endif - - m = yuv_buf_alloc(&buf, reqsize->width, reqsize->height); - int ysize=buf.strides[0]*buf.h; - memset(buf.planes[0],16,ysize); - memset(buf.planes[1],128,ysize/4); - memset(buf.planes[2],128,ysize/4); - buf.planes[3]=NULL; - return m; -} - -mblk_t *ms_load_jpeg_as_yuv(const char *jpgpath, MSVideoSize *reqsize){ - mblk_t *m=NULL; - struct stat statbuf; - uint8_t *jpgbuf; -#if !defined(_MSC_VER) - int fd=open(jpgpath,O_RDONLY); -#else - int fd=_open(jpgpath,O_RDONLY); -#endif - if (fd!=-1){ - fstat(fd,&statbuf); - if (statbuf.st_size<=0) - { -#if !defined(_MSC_VER) - close(fd); -#else - _close(fd); -#endif - ms_error("Cannot load %s",jpgpath); - m=ms_load_generate_yuv(reqsize); - return m; - } - jpgbuf=(uint8_t*)ms_malloc0(statbuf.st_size); - if (jpgbuf==NULL) - { -#if !defined(_MSC_VER) - close(fd); -#else - _close(fd); -#endif - ms_error("Cannot allocate buffer for %s",jpgpath); - m=ms_load_generate_yuv(reqsize); - return m; - } -#if !defined(_MSC_VER) - read(fd,jpgbuf,statbuf.st_size); -#else - _read(fd,jpgbuf,statbuf.st_size); -#endif - m=jpeg2yuv(jpgbuf,statbuf.st_size,reqsize); - ms_free(jpgbuf); - if (m==NULL) - { -#if !defined(_MSC_VER) - close(fd); -#else - _close(fd); -#endif - ms_error("Cannot load image from buffer for %s",jpgpath); - m=ms_load_generate_yuv(reqsize); - return m; - } - }else{ - m=ms_load_generate_yuv(reqsize); - ms_error("Cannot load %s",jpgpath); - return m; - } -#if !defined(_MSC_VER) - close(fd); -#else - _close(fd); -#endif - return m; -} - - - -#ifndef PACKAGE_DATA_DIR -#define PACKAGE_DATA_DIR "." -#endif - -#ifndef NOWEBCAM_JPG -#define NOWEBCAM_JPG "nowebcamCIF" -#endif - -static char *def_image=NULL; - -static const char *def_image_path=PACKAGE_DATA_DIR "/images/" NOWEBCAM_JPG ".jpg"; - - -mblk_t *ms_load_nowebcam(MSVideoSize *reqsize, int idx){ - char tmp[256]; - if (idx<0) - snprintf(tmp, sizeof(tmp), "%s/images/%s.jpg", PACKAGE_DATA_DIR, NOWEBCAM_JPG); - else - snprintf(tmp, sizeof(tmp), "%s/images/%s%i.jpg", PACKAGE_DATA_DIR, NOWEBCAM_JPG, idx); - return ms_load_jpeg_as_yuv(tmp,reqsize); -} - -typedef struct _SIData{ - MSVideoSize vsize; - char *nowebcamimage; - uint64_t lasttime; - mblk_t *pic; -}SIData; - -void static_image_init(MSFilter *f){ - SIData *d=(SIData*)ms_new(SIData,1); - d->vsize.width=MS_VIDEO_SIZE_CIF_W; - d->vsize.height=MS_VIDEO_SIZE_CIF_H; - - if (def_image==NULL) - def_image=ms_strdup(def_image_path); - - d->nowebcamimage=ms_strdup(def_image); - d->lasttime=0; - d->pic=NULL; - f->data=d; -} - -void static_image_uninit(MSFilter *f){ - SIData *d=(SIData*)f->data; - ms_free(d->nowebcamimage); - ms_free(d); -} - -void static_image_preprocess(MSFilter *f){ - SIData *d=(SIData*)f->data; - if (d->pic==NULL){ - d->pic=ms_load_jpeg_as_yuv(d->nowebcamimage,&d->vsize); - } -} - -void static_image_process(MSFilter *f){ - SIData *d=(SIData*)f->data; - /*output a frame every second*/ - if ((f->ticker->time - d->lasttime>1000) || d->lasttime==0){ - ms_mutex_lock(&f->lock); - if (d->pic) { - mblk_t *o=dupb(d->pic); - /*prevent mirroring at the output*/ - mblk_set_precious_flag(o,1); - ms_queue_put(f->outputs[0],o); - } - ms_mutex_unlock(&f->lock); - d->lasttime=f->ticker->time; - } -} - -void static_image_postprocess(MSFilter *f){ - SIData *d=(SIData*)f->data; - if (d->pic) { - freemsg(d->pic); - d->pic=NULL; - } -} - -int static_image_set_vsize(MSFilter *f, void* data){ - SIData *d=(SIData*)f->data; - d->vsize=*(MSVideoSize*)data; - return 0; -} - -int static_image_get_vsize(MSFilter *f, void* data){ - SIData *d=(SIData*)f->data; - *(MSVideoSize*)data=d->vsize; - return 0; -} - -int static_image_get_pix_fmt(MSFilter *f, void *data){ - *(MSPixFmt*)data=MS_YUV420P; - return 0; -} - -static int static_image_set_image(MSFilter *f, void *arg){ - SIData *d=(SIData*)f->data; - const char *image = (const char *)arg; - ms_filter_lock(f); - if (d->nowebcamimage) ms_free(d->nowebcamimage); - if (image!=NULL && image[0]!='\0') - d->nowebcamimage=ms_strdup(image); - else - d->nowebcamimage = ms_strdup(def_image); - - if (d->pic!=NULL){ - freemsg(d->pic); - d->pic=NULL; - } - - ms_filter_unlock(f); - return 0; -} - -MSFilterMethod static_image_methods[]={ - { MS_FILTER_SET_VIDEO_SIZE, static_image_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, static_image_get_vsize }, - { MS_FILTER_GET_PIX_FMT, static_image_get_pix_fmt }, - { MS_FILTER_SET_IMAGE, static_image_set_image }, - { 0,0 } -}; - -MSFilterDesc ms_static_image_desc={ - MS_STATIC_IMAGE_ID, - "MSStaticImage", - N_("A filter that outputs a static image."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - static_image_init, - static_image_preprocess, - static_image_process, - static_image_postprocess, - static_image_uninit, - static_image_methods -}; - -MS_FILTER_DESC_EXPORT(ms_static_image_desc) - -static void static_image_detect(MSWebCamManager *obj); - -static void static_image_cam_init(MSWebCam *cam){ - cam->name=ms_strdup("Static picture"); -} - - -static MSFilter *static_image_create_reader(MSWebCam *obj){ - return ms_filter_new_from_desc(&ms_static_image_desc); -} - -MSWebCamDesc static_image_desc={ - "StaticImage", - &static_image_detect, - &static_image_cam_init, - &static_image_create_reader, - NULL -}; - -static void static_image_detect(MSWebCamManager *obj){ - MSWebCam *cam=ms_web_cam_new(&static_image_desc); - ms_web_cam_manager_add_cam(obj,cam); -} - -void ms_static_image_set_default_image(const char *path){ - if (def_image!=NULL) - ms_free(def_image); - def_image=NULL; - if (path) - def_image=ms_strdup(path); -} diff --git a/linphone/mediastreamer2/src/nowebcam.h b/linphone/mediastreamer2/src/nowebcam.h deleted file mode 100644 index b77ec505d..000000000 --- a/linphone/mediastreamer2/src/nowebcam.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifndef nowebcam_h -#define nowebcam_h - -mblk_t *ms_load_jpeg_as_yuv(const char *path, MSVideoSize *reqsize); -mblk_t *ms_load_nowebcam(MSVideoSize *reqsize, int idx); - -#endif - diff --git a/linphone/mediastreamer2/src/nowebcamCIF.jpg b/linphone/mediastreamer2/src/nowebcamCIF.jpg deleted file mode 100644 index 2ab8bdc2a..000000000 Binary files a/linphone/mediastreamer2/src/nowebcamCIF.jpg and /dev/null differ diff --git a/linphone/mediastreamer2/src/oss.c b/linphone/mediastreamer2/src/oss.c deleted file mode 100644 index a4f67db0f..000000000 --- a/linphone/mediastreamer2/src/oss.c +++ /dev/null @@ -1,605 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" - -#include - -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_ALLOCA_H /*FreeBSD does not have alloca.h*/ -#include -#endif - -MSFilter *ms_oss_read_new(MSSndCard *card); -MSFilter *ms_oss_write_new(MSSndCard *card); - -static int oss_open(const char *devname, int bits,int stereo, int rate, int *minsz) -{ - int fd; - int p=0,cond=0; - int i=0; - int min_size=0,blocksize=512; - int err; - int frag; - audio_buf_info info; - - //g_message("opening sound device"); - fd=open(devname,O_RDWR|O_NONBLOCK); - if (fd<0) return -EWOULDBLOCK; - /* unset nonblocking mode */ - /* We wanted non blocking open but now put it back to normal ; thanks Xine !*/ - fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)&~O_NONBLOCK); - - /* reset is maybe not needed but takes time*/ - /*ioctl(fd, SNDCTL_DSP_RESET, 0); */ - - /* This code is used to limit the internal buffer of the sound - card so that no internal delay can occur in the sound card */ - frag = ( ( 32767 << 16 ) | 7 ); - if( ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &frag ) ) { - ms_warning("oss_open: can't set fragment size:%s.",strerror(errno)); - } - - p=AFMT_S16_NE; - - err=ioctl(fd,SNDCTL_DSP_SETFMT,&p); - if (err<0){ - ms_warning("oss_open: can't set sample format:%s.",strerror(errno)); - } - - - p = bits; /* 16 bits */ - err=ioctl(fd, SNDCTL_DSP_SAMPLESIZE, &p); - if (err<0){ - ms_warning("oss_open: can't set sample size to %i:%s.",bits,strerror(errno)); - } - - p = rate; /* rate in khz*/ - err=ioctl(fd, SNDCTL_DSP_SPEED, &p); - if (err<0){ - ms_warning("oss_open: can't set sample rate to %i:%s.",rate,strerror(errno)); - } - - p = stereo; /* stereo or not */ - err=ioctl(fd, SNDCTL_DSP_STEREO, &p); - if (err<0){ - ms_warning("oss_open: can't set mono/stereo mode:%s.",strerror(errno)); - } - - if (rate==16000) blocksize=4096; /* oss emulation is not very good at 16khz */ - else blocksize=blocksize*(rate/8000); - ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &min_size); - - /* try to subdivide BLKSIZE to reach blocksize if necessary */ - if (min_size>blocksize) - { - cond=1; - p=min_size/blocksize; - while(cond) - { - i=ioctl(fd, SNDCTL_DSP_SUBDIVIDE, &p); - //printf("SUB_DIVIDE said error=%i,errno=%i\n",i,errno); - if ((i==0) || (p==1)) cond=0; - else p=p/2; - } - } - ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &min_size); - if (min_size>blocksize) - { - ms_warning("dsp block size set to %i.",min_size); - }else{ - /* no need to access the card with less latency than needed*/ - min_size=blocksize; - } - - ms_message("/dev/dsp opened: rate=%i,bits=%i,stereo=%i blocksize=%i.", - rate,bits,stereo,min_size); - - if( ioctl( fd, SNDCTL_DSP_GETISPACE, &info ) == -1 ) { - ms_warning("oss_open: can't get ispace:%s.",strerror(errno)); - } - else{ - ms_warning("oss_open: audio buffer size: %i.", info.fragsize * sizeof( short )); - } - - - /* start recording !!! Alex */ - { - int fl,res; - - fl=PCM_ENABLE_OUTPUT|PCM_ENABLE_INPUT; - res=ioctl(fd, SNDCTL_DSP_SETTRIGGER, &fl); - if (res<0) ms_warning("OSS_TRIGGER: %s",strerror(errno)); - } - *minsz=min_size; - return fd; -} - -typedef struct OssData{ - char *pcmdev; - char *mixdev; - int pcmfd; - int rate; - int bits; - ms_thread_t thread; - ms_mutex_t mutex; - queue_t rq; - MSBufferizer * bufferizer; - bool_t read_started; - bool_t write_started; - bool_t stereo; -} OssData; - -static void oss_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent) -{ - OssData *d=(OssData*)card->data; - int p,mix_fd; - int osscmd; - if (d->mixdev==NULL) return; - switch(e){ - case MS_SND_CARD_MASTER: - osscmd=SOUND_MIXER_VOLUME; - break; - case MS_SND_CARD_CAPTURE: - osscmd=SOUND_MIXER_IGAIN; - break; - case MS_SND_CARD_PLAYBACK: - osscmd=SOUND_MIXER_PCM; - break; - default: - ms_warning("oss_card_set_level: unsupported command."); - return; - } - p=(((int)percent)<<8 | (int)percent); - mix_fd = open(d->mixdev, O_WRONLY); - ioctl(mix_fd,MIXER_WRITE(osscmd), &p); - close(mix_fd); -} - -static int oss_get_level(MSSndCard *card, MSSndCardMixerElem e) -{ - OssData *d=(OssData*)card->data; - int p=0,mix_fd; - int osscmd; - if (d->mixdev==NULL) return -1; - switch(e){ - case MS_SND_CARD_MASTER: - osscmd=SOUND_MIXER_VOLUME; - break; - case MS_SND_CARD_CAPTURE: - osscmd=SOUND_MIXER_IGAIN; - break; - case MS_SND_CARD_PLAYBACK: - osscmd=SOUND_MIXER_PCM; - break; - default: - ms_warning("oss_card_get_level: unsupported command."); - return -1; - } - mix_fd = open(d->mixdev, O_RDONLY); - ioctl(mix_fd,MIXER_READ(osscmd), &p); - close(mix_fd); - return p>>8; -} - -static void oss_set_source(MSSndCard *card, MSSndCardCapture source) -{ - OssData *d=(OssData*)card->data; - int p=0; - int mix_fd; - if (d->mixdev==NULL) return; - - switch(source){ - case MS_SND_CARD_MIC: - p = 1 << SOUND_MIXER_MIC; - break; - case MS_SND_CARD_LINE: - p = 1 << SOUND_MIXER_LINE; - break; - } - - mix_fd = open(d->mixdev, O_WRONLY); - ioctl(mix_fd, SOUND_MIXER_WRITE_RECSRC, &p); - close(mix_fd); -} - -static void oss_init(MSSndCard *card){ - OssData *d=ms_new(OssData,1); - d->pcmdev=NULL; - d->mixdev=NULL; - d->pcmfd=-1; - d->read_started=FALSE; - d->write_started=FALSE; - d->bits=16; - d->rate=8000; - d->stereo=FALSE; - qinit(&d->rq); - d->bufferizer=ms_bufferizer_new(); - ms_mutex_init(&d->mutex,NULL); - card->data=d; -} - -static void oss_uninit(MSSndCard *card){ - OssData *d=(OssData*)card->data; - if (d->pcmdev!=NULL) ms_free(d->pcmdev); - if (d->mixdev!=NULL) ms_free(d->mixdev); - ms_bufferizer_destroy(d->bufferizer); - flushq(&d->rq,0); - ms_mutex_destroy(&d->mutex); - ms_free(d); -} - -#define DSP_NAME "/dev/dsp" -#define MIXER_NAME "/dev/mixer" - -static void oss_detect(MSSndCardManager *m); -static MSSndCard *oss_duplicate(MSSndCard *obj); - -MSSndCardDesc oss_card_desc={ - .driver_type="OSS", - .detect=oss_detect, - .init=oss_init, - .set_level=oss_set_level, - .get_level=oss_get_level, - .set_capture=oss_set_source, - .set_control=NULL, - .get_control=NULL, - .create_reader=ms_oss_read_new, - .create_writer=ms_oss_write_new, - .uninit=oss_uninit, - .duplicate=oss_duplicate -}; - -static MSSndCard *oss_duplicate(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&oss_card_desc); - OssData *dcard=(OssData*)card->data; - OssData *dobj=(OssData*)obj->data; - dcard->pcmdev=ms_strdup(dobj->pcmdev); - dcard->mixdev=ms_strdup(dobj->mixdev); - card->name=ms_strdup(obj->name); - return card; -} - -static MSSndCard *oss_card_new(const char *pcmdev, const char *mixdev){ - MSSndCard *card=ms_snd_card_new(&oss_card_desc); - OssData *d=(OssData*)card->data; - d->pcmdev=ms_strdup(pcmdev); - d->mixdev=ms_strdup(mixdev); - card->name=ms_strdup(pcmdev); - return card; -} - -static void oss_detect(MSSndCardManager *m){ - int i; - char pcmdev[sizeof(DSP_NAME)+3]; - char mixdev[sizeof(MIXER_NAME)+3]; - if (access(DSP_NAME,F_OK)==0){ - MSSndCard *card=oss_card_new(DSP_NAME,MIXER_NAME); - ms_snd_card_manager_add_card(m,card); - } - for(i=0;i<10;i++){ - snprintf(pcmdev,sizeof(pcmdev),"%s%i",DSP_NAME,i); - snprintf(mixdev,sizeof(mixdev),"%s%i",MIXER_NAME,i); - if (access(pcmdev,F_OK)==0){ - MSSndCard *card=oss_card_new(pcmdev,mixdev); - ms_snd_card_manager_add_card(m,card); - } - } -} - -static void * oss_thread(void *p){ - MSSndCard *card=(MSSndCard*)p; - OssData *d=(OssData*)card->data; - int bsize=0; - uint8_t *rtmpbuff=NULL; - uint8_t *wtmpbuff=NULL; - int err; - mblk_t *rm=NULL; - d->pcmfd=oss_open(d->pcmdev,d->bits,d->stereo,d->rate,&bsize); - if (d->pcmfd>=0){ - rtmpbuff=(uint8_t*)malloc(bsize); - wtmpbuff=(uint8_t*)malloc(bsize); - if(rtmpbuff == NULL || wtmpbuff == NULL) { - free(rtmpbuff); - free(wtmpbuff); - return NULL; - } - } - while(d->read_started || d->write_started){ - if (d->pcmfd>=0){ - if (d->read_started){ - struct timeval timeout; - fd_set read_fds; - audio_buf_info info; - if (rm==NULL) rm=allocb(bsize,0); - - timeout.tv_sec = 0; - timeout.tv_usec = 0; - FD_ZERO( &read_fds ); - FD_SET( d->pcmfd, &read_fds ); - if( select( d->pcmfd + 1, &read_fds, NULL, NULL, &timeout ) == -1 ) { - } - if (FD_ISSET( d->pcmfd, &read_fds ) && ioctl( d->pcmfd, SNDCTL_DSP_GETISPACE, &info ) != -1) - { - if (info.bytes>=bsize) - { - err=read(d->pcmfd,rm->b_wptr,bsize); - if (err<0){ - ms_warning("Fail to read %i bytes from soundcard: %s", - bsize,strerror(errno)); - }else{ - rm->b_wptr+=err; - ms_mutex_lock(&d->mutex); - putq(&d->rq,rm); - ms_mutex_unlock(&d->mutex); - rm=NULL; - } - } - else - { - timeout.tv_sec = 0; - timeout.tv_usec = 5000; - select(0, 0, NULL, NULL, &timeout ); - } - } - else - { - timeout.tv_sec = 0; - timeout.tv_usec = 5000; - select(0, 0, NULL, NULL, &timeout ); - } - }else { - int sz = read(d->pcmfd,rtmpbuff,bsize); - if( sz!=bsize) ms_warning("sound device read returned %i !",sz); - } - if (d->write_started){ - - audio_buf_info info; - if( ms_bufferizer_get_avail(d->bufferizer)>=bsize && ioctl( d->pcmfd, SNDCTL_DSP_GETOSPACE, &info ) == 0 ) { - if( info.fragstotal - info.fragments > 15 ) { - static int c=0; - /* drop the fragment if the buffer starts to fill up */ - /* we got too much data: I prefer to empty the incoming buffer */ - while (ms_bufferizer_get_avail(d->bufferizer)>bsize*4){ - ms_mutex_lock(&d->mutex); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - ms_mutex_unlock(&d->mutex); - c=c+err*4; - ms_warning("drop fragment when buffer gets too much data (%i - discarded:%i)", info.fragstotal - info.fragments, c); - if (err==0) - break; - } - - }else { - ms_mutex_lock(&d->mutex); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - ms_mutex_unlock(&d->mutex); - err=write(d->pcmfd,wtmpbuff,bsize); - if (err<0){ - ms_warning("Fail to write %i bytes from soundcard: %s", - bsize,strerror(errno)); - } - } - } - - }else { - int sz; - memset(wtmpbuff,0,bsize); - sz = write(d->pcmfd,wtmpbuff,bsize); - if( sz!=bsize) ms_warning("sound device write returned %i !",sz); - } - }else usleep(20000); - } - if (d->pcmfd>=0) { - close(d->pcmfd); - d->pcmfd=-1; - } - free(rtmpbuff); - free(wtmpbuff); - if (rm!=NULL) freemsg(rm); - /*reset to default parameters */ - //d->bits=16; - //d->rate=8000; - //d->stereo=FALSE; - return NULL; -} - -static void oss_start_r(MSSndCard *card){ - OssData *d=(OssData*)card->data; - ms_mutex_lock(&d->mutex); - if (d->read_started==FALSE && d->write_started==FALSE){ - d->read_started=TRUE; - ms_thread_create(&d->thread,NULL,oss_thread,card); - }else d->read_started=TRUE; - flushq(&d->rq,0); - ms_mutex_unlock(&d->mutex); -} - -static void oss_stop_r(MSSndCard *card){ - OssData *d=(OssData*)card->data; - d->read_started=FALSE; - if (d->write_started==FALSE){ - ms_thread_join(d->thread,NULL); - } -} - -static void _flush_buffer(MSBufferizer *obj){ - flushq(&obj->q,0); - obj->size=0; -} - -static void oss_start_w(MSSndCard *card){ - OssData *d=(OssData*)card->data; - ms_mutex_lock(&d->mutex); - if (d->read_started==FALSE && d->write_started==FALSE){ - d->write_started=TRUE; - ms_thread_create(&d->thread,NULL,oss_thread,card); - }else{ - d->write_started=TRUE; - } - _flush_buffer(d->bufferizer); - ms_mutex_unlock(&d->mutex); -} - -static void oss_stop_w(MSSndCard *card){ - OssData *d=(OssData*)card->data; - d->write_started=FALSE; - if (d->read_started==FALSE){ - ms_thread_join(d->thread,NULL); - } -} - -static mblk_t *oss_get(MSSndCard *card){ - OssData *d=(OssData*)card->data; - mblk_t *m; - ms_mutex_lock(&d->mutex); - m=getq(&d->rq); - ms_mutex_unlock(&d->mutex); - return m; -} - -static void oss_put(MSSndCard *card, mblk_t *m){ - OssData *d=(OssData*)card->data; - ms_mutex_lock(&d->mutex); - ms_bufferizer_put(d->bufferizer,m); - ms_mutex_unlock(&d->mutex); -} - - -static void oss_read_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - oss_start_r(card); -} - -static void oss_read_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - oss_stop_r(card); -} - -static void oss_read_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=oss_get(card))!=NULL){ - ms_queue_put(f->outputs[0],m); - } -} - -static void oss_write_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - oss_start_w(card); -} - -static void oss_write_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - oss_stop_w(card); -} - -static void oss_write_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - oss_put(card,m); - } -} - -static int get_rate(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - OssData *d=(OssData*)card->data; - *((int*)arg)=d->rate; - return 0; -} - -static int set_rate(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - OssData *d=(OssData*)card->data; - d->rate=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - OssData *d=(OssData*)card->data; - d->stereo=(*((int*)arg)==2); - return 0; -} - -static MSFilterMethod oss_methods[]={ - { MS_FILTER_GET_SAMPLE_RATE , get_rate }, - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { 0 , NULL } -}; - -MSFilterDesc oss_read_desc={ - .id=MS_OSS_READ_ID, - .name="MSOssRead", - .text=N_("Sound capture filter for OSS drivers"), - .category=MS_FILTER_OTHER, - .ninputs=0, - .noutputs=1, - .preprocess=oss_read_preprocess, - .process=oss_read_process, - .postprocess=oss_read_postprocess, - .methods=oss_methods -}; - - -MSFilterDesc oss_write_desc={ - .id=MS_OSS_WRITE_ID, - .name="MSOssWrite", - .text=N_("Sound playback filter for OSS drivers"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .preprocess=oss_write_preprocess, - .process=oss_write_process, - .postprocess=oss_write_postprocess, - .methods=oss_methods -}; - -MSFilter *ms_oss_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&oss_read_desc); - f->data=card; - return f; -} - - -MSFilter *ms_oss_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&oss_write_desc); - f->data=card; - return f; -} - -MS_FILTER_DESC_EXPORT(oss_read_desc) -MS_FILTER_DESC_EXPORT(oss_write_desc) diff --git a/linphone/mediastreamer2/src/pasnd.c b/linphone/mediastreamer2/src/pasnd.c deleted file mode 100644 index abba82abc..000000000 --- a/linphone/mediastreamer2/src/pasnd.c +++ /dev/null @@ -1,597 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" - -#include "portaudio.h" - -MSFilter *ms_pasnd_read_new(MSSndCard *card); -MSFilter *ms_pasnd_write_new(MSSndCard *card); - -typedef struct PASndData{ - char *pcmdev; - char *mixdev; - int sound_err; - char waveoutbuffer[30][3200]; - PaStream *waveoutdev; - - PaStream *waveindev; - - int rate; - int bits; - ms_thread_t thread; - ms_mutex_t mutex; - queue_t rq; - MSBufferizer * bufferizer; - bool_t read_started; - bool_t write_started; - bool_t stereo; - - SpeexPreprocessState *pst; -} PASndData; - -int SpeakerCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) -{ - PASndData *device = (PASndData*)userData; - uint8_t *wtmpbuff=NULL; - int err; - int ovfl = (device->rate/8000)*320*6; - - memset(outputBuffer,0, framesPerBuffer*2); - if (!device->read_started && !device->write_started) - { - return 0; - } - - wtmpbuff=(uint8_t*)alloca(framesPerBuffer*2); - - memset(outputBuffer,0, framesPerBuffer*2); - - ms_mutex_lock(&device->mutex); - - /* remove extra buffer when latency is increasing: - this often happen with USB device */ - if (device->bufferizer->size>=ovfl){ - ms_warning("Extra data for sound card (total:%i %ims)", - device->bufferizer->size, (device->bufferizer->size*20)/320); - err=ms_bufferizer_read(device->bufferizer,wtmpbuff, framesPerBuffer*2); - err=ms_bufferizer_read(device->bufferizer,wtmpbuff, framesPerBuffer*2); - err=ms_bufferizer_read(device->bufferizer,wtmpbuff, framesPerBuffer*2); - err=ms_bufferizer_read(device->bufferizer,wtmpbuff, framesPerBuffer*2); - err=ms_bufferizer_read(device->bufferizer,wtmpbuff, framesPerBuffer*2); - ms_warning("Extra data for sound card removed (total:%i %ims)", - device->bufferizer->size, (device->bufferizer->size*20)/320); - } - - err=ms_bufferizer_read(device->bufferizer,wtmpbuff,framesPerBuffer*2); - ms_mutex_unlock(&device->mutex); - if (err==framesPerBuffer*2) - { - memcpy (outputBuffer, wtmpbuff, framesPerBuffer*2); - } - - return 0; -} - -int WaveInCallback( const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) -{ - PASndData *device = (PASndData*)userData; - - if (!device->read_started && !device->write_started) - { - return 0; - } - - ms_mutex_lock(&device->mutex); - if (device->read_started) - { - int vad; - mblk_t *rm=NULL; - if (rm==NULL) rm=allocb(framesPerBuffer*2,0); - memcpy(rm->b_wptr,inputBuffer, framesPerBuffer*2); - - if (device->pst!=NULL) - { - vad = speex_preprocess(device->pst, (spx_int16_t *)rm->b_wptr, NULL); -#if 0 - if (vad!=1) - ms_message("WaveInCallback : %d", vad); -#endif - } - - rm->b_wptr+=framesPerBuffer*2; - - putq(&device->rq,rm); - rm=NULL; - } - ms_mutex_unlock(&device->mutex); - - return 0; -} - -static int pasnd_open(PASndData *device, int devnumber, int bits,int stereo, int rate, int *minsz) -{ - PaStreamParameters outputParameters; - PaStreamParameters inputParameters; - PaError err; - - const PaHostApiInfo *pa_hai = Pa_GetHostApiInfo(Pa_GetDefaultHostApi()); - - ms_warning("pasnd_open : opening default input device: name=%s (%i)", - pa_hai->name, pa_hai->defaultInputDevice); - ms_warning("pasnd_open : opening default output device name=%s (%i)", - pa_hai->name, pa_hai->defaultOutputDevice); - - outputParameters.device = devnumber; /* default output device */ - outputParameters.device = pa_hai->defaultOutputDevice; - outputParameters.channelCount = 1; /* stereo output */ - outputParameters.sampleFormat = paInt16; /* 32 bit floating point output */ - outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; - outputParameters.hostApiSpecificStreamInfo = NULL; - - err = Pa_OpenStream( - &device->waveoutdev, /* stream */ - NULL, /* no input */ - &outputParameters, // - rate, // double sampleRate - 160*(rate/8000), //unsigned long framesPerBuffer - paClipOff, - SpeakerCallback, //PortAudioCallback *callback - (void *) device); //void *userData - - if (err != paNoError) - { - ms_warning("Failed to open out device. (Pa_OpenDefaultStream:0x%i)", err); - return -1; - } - - inputParameters.device = devnumber; /* default input device */ - inputParameters.device = pa_hai->defaultInputDevice; - inputParameters.channelCount = 1; /* stereo input */ - inputParameters.sampleFormat = paInt16; /* 32 bit floating point input */ - inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; - inputParameters.hostApiSpecificStreamInfo = NULL; - - err = Pa_OpenStream( - &device->waveindev, //PortAudioStream** stream - &inputParameters, /* input param*/ - NULL, /* output param */ - rate, // double sampleRate - 160*(rate/8000), //unsigned long framesPerBuffer - paClipOff, - WaveInCallback, //PortAudioCallback *callback - (void *) device); //void *userData - - - if (err != paNoError) - { - ms_warning("Failed to open in device. (Pa_OpenDefaultStream:0x%i)", err); - return -1; - } - - err = Pa_StartStream( device->waveoutdev ); - if( err != paNoError ) - { - ms_warning("Failed to start out device. (Pa_StartStream:0x%i)", err); - return -1; - } - - device->pst = speex_preprocess_state_init((device->rate/8000 * 320)/2, device->rate); - if (device->pst!=NULL) { - float f; - int i=1; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_VAD, &i); - i=1; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=0; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_AGC, &i); - f=8000; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); - i=0; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB, &i); - f=.4; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=.3; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - } - - err = Pa_StartStream( device->waveindev ); - if( err != paNoError ) - { - ms_warning("Failed to start in device: trying default device. (Pa_StartStream:0x%i)", err); - return -1; - } - - *minsz=device->rate/8000 * 320; - return 0; -} - -static void pasnd_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent) -{ - PASndData *d=(PASndData*)card->data; - - if (d->mixdev==NULL) return; - switch(e){ - case MS_SND_CARD_MASTER: - return; - break; - case MS_SND_CARD_CAPTURE: - break; - case MS_SND_CARD_PLAYBACK: - break; - default: - ms_warning("pasnd_card_set_level: unsupported command."); - return; - } -} - -static int pasnd_get_level(MSSndCard *card, MSSndCardMixerElem e) -{ - PASndData *d=(PASndData*)card->data; - - if (d->mixdev==NULL) return -1; - switch(e){ - case MS_SND_CARD_MASTER: - return 60; - break; - case MS_SND_CARD_CAPTURE: - break; - case MS_SND_CARD_PLAYBACK: - break; - default: - ms_warning("pasnd_card_get_level: unsupported command."); - return -1; - } - return -1; -} - -static void pasnd_set_source(MSSndCard *card, MSSndCardCapture source) -{ - PASndData *d=(PASndData*)card->data; - if (d->mixdev==NULL) return; - - switch(source){ - case MS_SND_CARD_MIC: - break; - case MS_SND_CARD_LINE: - break; - } -} - -static void pasnd_init(MSSndCard *card){ - PASndData *d=ms_new(PASndData,1); - memset(d, 0, sizeof(PASndData)); - d->pcmdev=NULL; - d->mixdev=NULL; - d->sound_err=-1; /* not opened */ - d->read_started=FALSE; - d->write_started=FALSE; - d->bits=16; - d->rate=8000; - d->stereo=FALSE; - qinit(&d->rq); - d->bufferizer=ms_bufferizer_new(); - ms_mutex_init(&d->mutex,NULL); - card->data=d; - d->pst=0; -} - -static void pasnd_uninit(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - if (d==NULL) - return; - if (d->pcmdev!=NULL) ms_free(d->pcmdev); - if (d->mixdev!=NULL) ms_free(d->mixdev); - ms_bufferizer_destroy(d->bufferizer); - flushq(&d->rq,0); - - ms_mutex_destroy(&d->mutex); - - if (d->pst!=NULL) - speex_preprocess_state_destroy(d->pst); - - ms_free(d); -} - -#define DSP_NAME "/dev/dsp" -#define MIXER_NAME "/dev/mixer" - -static void pasnd_detect(MSSndCardManager *m); -static MSSndCard *pasnd_duplicate(MSSndCard *obj); - -MSSndCardDesc pasnd_card_desc={ - "PASND", - pasnd_detect, - pasnd_init, - pasnd_set_level, - pasnd_get_level, - pasnd_set_source, - NULL, - NULL, - ms_pasnd_read_new, - ms_pasnd_write_new, - pasnd_uninit, - pasnd_duplicate -}; - -static MSSndCard *pasnd_duplicate(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&pasnd_card_desc); - PASndData *dcard=(PASndData*)card->data; - PASndData *dobj=(PASndData*)obj->data; - dcard->pcmdev=ms_strdup(dobj->pcmdev); - dcard->mixdev=ms_strdup(dobj->mixdev); - card->name=ms_strdup(obj->name); - return card; -} - -static MSSndCard *pasnd_card_new(const char *pcmdev, const char *mixdev){ - MSSndCard *card=ms_snd_card_new(&pasnd_card_desc); - PASndData *d=(PASndData*)card->data; - d->pcmdev=ms_strdup(pcmdev); - d->mixdev=ms_strdup(mixdev); - card->name=ms_strdup(pcmdev); - return card; -} - -static void pasnd_detect(MSSndCardManager *m){ - int err = 0; - unsigned int numDevices; - const PaDeviceInfo *pdi; - char pcmdev[1024]; - char mixdev[1024]; - int i; - - err = Pa_Initialize(); - if( err != paNoError ) - { - ms_warning("PortAudio error: %s\n", Pa_GetErrorText( err ) ); - return; - } - - numDevices = Pa_GetDeviceCount(); - - for( i=0; iname); - snprintf(mixdev,sizeof(mixdev),"%s",pdi->name); - if (i == 0) - { - card=pasnd_card_new(pcmdev,mixdev); - ms_snd_card_manager_add_card(m,card); - } - card=pasnd_card_new(pcmdev,mixdev); - ms_snd_card_manager_add_card(m,card); - } - } -} - -static void pasnd_closedriver(PASndData *d) -{ - if (d->sound_err==0) { - - int err = Pa_StopStream( d->waveindev ); - if( err != paNoError ) - { - ms_warning("Failed to stop device. (Pa_StopStream:0x%i)", err); - } - - err = Pa_CloseStream( d->waveindev); - if( err != paNoError ) - { - ms_warning("failed to close recording sound card (Pa_CloseStream:0x%i)", err); - } - else - { - ms_message("successfully closed recording sound card"); - } - - err = Pa_StopStream( d->waveoutdev ); - if( err != paNoError ) - { - ms_warning("Failed to stop device. (Pa_StopStream:0x%i)", err); - } - - err = Pa_CloseStream( d->waveoutdev ); - if( err != paNoError ) - { - ms_error("failed to stop recording sound card (Pa_CloseStream:0x%i)", err); - } - else - { - ms_message("successfully stopped recording sound card"); - } - - - d->sound_err=-1; - } -} - -static void pasnd_start_r(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - if (d->read_started==FALSE && d->write_started==FALSE){ - int bsize=0; - d->read_started=TRUE; - d->sound_err=pasnd_open(d, 0, d->bits,d->stereo,d->rate,&bsize); - }else d->read_started=TRUE; -} - -static void pasnd_stop_r(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - d->read_started=FALSE; - if (d->write_started==FALSE){ - /* ms_thread_join(d->thread,NULL); */ - pasnd_closedriver(d); - } -} - -static void pasnd_start_w(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - if (d->read_started==FALSE && d->write_started==FALSE){ - int bsize=0; - d->write_started=TRUE; - d->sound_err=pasnd_open(d, 0, d->bits,d->stereo,d->rate,&bsize); - }else{ - d->write_started=TRUE; - } -} - -static void pasnd_stop_w(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - d->write_started=FALSE; - if (d->read_started==FALSE){ - /* ms_thread_join(d->thread,NULL); */ - pasnd_closedriver(d); - } -} - -static mblk_t *pasnd_get(MSSndCard *card){ - PASndData *d=(PASndData*)card->data; - mblk_t *m; - ms_mutex_lock(&d->mutex); - m=getq(&d->rq); - ms_mutex_unlock(&d->mutex); - return m; -} - -static void pasnd_put(MSSndCard *card, mblk_t *m){ - PASndData *d=(PASndData*)card->data; - ms_mutex_lock(&d->mutex); - ms_bufferizer_put(d->bufferizer,m); - ms_mutex_unlock(&d->mutex); -} - - -static void pasnd_read_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - pasnd_start_r(card); -} - -static void pasnd_read_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - pasnd_stop_r(card); -} - -static void pasnd_read_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=pasnd_get(card))!=NULL){ - ms_queue_put(f->outputs[0],m); - } -} - -static void pasnd_write_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - pasnd_start_w(card); -} - -static void pasnd_write_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - pasnd_stop_w(card); -} - -static void pasnd_write_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - pasnd_put(card,m); - } -} - -static int set_rate(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - PASndData *d=(PASndData*)card->data; - d->rate=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - PASndData *d=(PASndData*)card->data; - d->stereo=(*((int*)arg)==2); - return 0; -} - -static MSFilterMethod pasnd_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { 0 , NULL } -}; - -MSFilterDesc pasnd_read_desc={ - MS_PASND_READ_ID, - "MSPasndRead", - "Sound capture filter for Port Audio Sound drivers", - MS_FILTER_OTHER, - NULL, - 0, - 1, - NULL, - pasnd_read_preprocess, - pasnd_read_process, - pasnd_read_postprocess, - NULL, - pasnd_methods -}; - - -MSFilterDesc pasnd_write_desc={ - MS_PASND_WRITE_ID, - "MSPasndWrite", - "Sound playback filter for Port Audio Sound drivers", - MS_FILTER_OTHER, - NULL, - 1, - 0, - NULL, - pasnd_write_preprocess, - pasnd_write_process, - pasnd_write_postprocess, - NULL, - pasnd_methods -}; - -MSFilter *ms_pasnd_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&pasnd_read_desc); - f->data=card; - return f; -} - - -MSFilter *ms_pasnd_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&pasnd_write_desc); - f->data=card; - return f; -} - -MS_FILTER_DESC_EXPORT(pasnd_read_desc) -MS_FILTER_DESC_EXPORT(pasnd_write_desc) diff --git a/linphone/mediastreamer2/src/pixconv.c b/linphone/mediastreamer2/src/pixconv.c deleted file mode 100644 index 24fc1c434..000000000 --- a/linphone/mediastreamer2/src/pixconv.c +++ /dev/null @@ -1,204 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" - -#include "ffmpeg-priv.h" - -extern void ms_ffmpeg_check_init(); - -int ms_pix_fmt_to_ffmpeg(MSPixFmt fmt){ - switch(fmt){ - case MS_RGB24: - return PIX_FMT_RGB24; - case MS_RGB24_REV: - return PIX_FMT_BGR24; - case MS_YUV420P: - return PIX_FMT_YUV420P; - case MS_YUYV: - return PIX_FMT_YUYV422; - case MS_UYVY: - return PIX_FMT_UYVY422; - case MS_YUY2: - return PIX_FMT_YUYV422; /* <- same as MS_YUYV */ - default: - ms_fatal("format not supported."); - return -1; - } - return -1; -} - -MSPixFmt ffmpeg_pix_fmt_to_ms(int fmt){ - switch(fmt){ - case PIX_FMT_RGB24: - return MS_RGB24; - case PIX_FMT_BGR24: - return MS_RGB24_REV; - case PIX_FMT_YUV420P: - return MS_YUV420P; - case PIX_FMT_YUYV422: - return MS_YUYV; - case PIX_FMT_UYVY422: - return MS_UYVY; /* same as MS_YUY2 */ - default: - ms_fatal("format not supported."); - return MS_YUV420P; /* default */ - } - return MS_YUV420P; /* default */ -} - -typedef struct PixConvState{ - YuvBuf outbuf; - mblk_t *yuv_msg; - struct SwsContext *sws_ctx; - MSVideoSize size; - enum PixelFormat in_fmt; - enum PixelFormat out_fmt; -}PixConvState; - -static void pixconv_init(MSFilter *f){ - PixConvState *s=(PixConvState *)ms_new(PixConvState,1); - s->yuv_msg=NULL; - s->size.width = MS_VIDEO_SIZE_CIF_W; - s->size.height = MS_VIDEO_SIZE_CIF_H; - s->in_fmt=PIX_FMT_YUV420P; - s->out_fmt=PIX_FMT_YUV420P; - s->sws_ctx=NULL; - f->data=s; - ms_ffmpeg_check_init(); -} - -static void pixconv_uninit(MSFilter *f){ - PixConvState *s=(PixConvState*)f->data; - if (s->sws_ctx!=NULL){ - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - if (s->yuv_msg!=NULL) freemsg(s->yuv_msg); - ms_free(s); -} - -static mblk_t * pixconv_alloc_mblk(PixConvState *s){ - if (s->yuv_msg!=NULL){ - int ref=s->yuv_msg->b_datap->db_ref; - if (ref==1){ - return dupmsg(s->yuv_msg); - }else{ - /*the last msg is still referenced by somebody else*/ - ms_message("Somebody still retaining yuv buffer (ref=%i)",ref); - freemsg(s->yuv_msg); - s->yuv_msg=NULL; - } - } - s->yuv_msg=yuv_buf_alloc(&s->outbuf,s->size.width,s->size.height); - return dupmsg(s->yuv_msg); -} - -static void pixconv_process(MSFilter *f){ - mblk_t *im,*om; - PixConvState *s=(PixConvState*)f->data; - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - if (s->in_fmt==s->out_fmt){ - om=im; - }else{ - AVPicture inbuf; - avpicture_fill(&inbuf,im->b_rptr,s->in_fmt,s->size.width,s->size.height); - om=pixconv_alloc_mblk(s); - if (s->sws_ctx==NULL){ - s->sws_ctx=sws_getContext(s->size.width,s->size.height, - s->in_fmt,s->size.width,s->size.height, - s->out_fmt,SWS_FAST_BILINEAR, - NULL, NULL, NULL); - } - if (s->in_fmt==PIX_FMT_BGR24){ - inbuf.data[0]+=inbuf.linesize[0]*(s->size.height-1); - inbuf.linesize[0]=-inbuf.linesize[0]; - } - if (sws_scale(s->sws_ctx,inbuf.data,inbuf.linesize, 0, - s->size.height, s->outbuf.planes, s->outbuf.strides)<0){ - ms_error("MSPixConv: Error in sws_scale()."); - } - freemsg(im); - } - if (om!=NULL) ms_queue_put(f->outputs[0],om); - } -} - -static int pixconv_set_vsize(MSFilter *f, void*arg){ - PixConvState *s=(PixConvState*)f->data; - s->size=*(MSVideoSize*)arg; - return 0; -} - -static int pixconv_set_pixfmt(MSFilter *f, void *arg){ - MSPixFmt fmt=*(MSPixFmt*)arg; - PixConvState *s=(PixConvState*)f->data; - s->in_fmt=(enum PixelFormat)ms_pix_fmt_to_ffmpeg(fmt); - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_VIDEO_SIZE, pixconv_set_vsize }, - { MS_FILTER_SET_PIX_FMT, pixconv_set_pixfmt }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_pix_conv_desc={ - MS_PIX_CONV_ID, - "MSPixConv", - N_("A pixel format converter"), - MS_FILTER_OTHER, - NULL, - 1, - 1, - pixconv_init, - NULL, - pixconv_process, - NULL, - pixconv_uninit, - methods -}; - -#else - -MSFilterDesc ms_pix_conv_desc={ - .id=MS_PIX_CONV_ID, - .name="MSPixConv", - .text=N_("A pixel format converter"), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=1, - .init=pixconv_init, - .process=pixconv_process, - .uninit=pixconv_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_pix_conv_desc) - diff --git a/linphone/mediastreamer2/src/rfc2429.h b/linphone/mediastreamer2/src/rfc2429.h deleted file mode 100644 index 414b2ea56..000000000 --- a/linphone/mediastreamer2/src/rfc2429.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - The mediastreamer library aims at providing modular media processing and I/O - for linphone, but also for any telephony application. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#ifndef rfc2429_h -#define rfc2429_h - -#define MAKE_MASK(bits) ( (1<<(bits)) -1 ) - -static inline unsigned int rfc2429_get_P(const uint8_t *header){ - return (header[0]>>2) & 0x1; -} - -static inline void rfc2429_set_P(uint8_t *header, bool_t val){ - header[0]=header[0] | ( (val&0x1)<<2); -} - -static inline unsigned int rfc2429_get_V(const uint8_t *header){ - return (header[0]>>1) & 0x1; -} - -static inline unsigned int rfc2429_get_PLEN(const uint8_t *header){ - unsigned short *p=(unsigned short*)header; - return (ntohs(p[0])>>3) & MAKE_MASK(6); -} - -static inline unsigned int rfc2429_get_PEBIT(const uint8_t *header){ - unsigned short *p=(unsigned short*)header; - return ntohs(p[0]) & MAKE_MASK(3); -} - - -#endif diff --git a/linphone/mediastreamer2/src/rfc3984.c b/linphone/mediastreamer2/src/rfc3984.c deleted file mode 100644 index ffb2895b8..000000000 --- a/linphone/mediastreamer2/src/rfc3984.c +++ /dev/null @@ -1,321 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/rfc3984.h" -#include "mediastreamer2/msfilter.h" - -#define TYPE_FU_A 28 /*fragmented unit 0x1C*/ -#define TYPE_STAP_A 24 /*single time aggregation packet 0x18*/ - - -static inline void nal_header_init(uint8_t *h, uint8_t nri, uint8_t type){ - *h=((nri&0x3)<<5) | (type & ((1<<5)-1)); -} - -static inline uint8_t nal_header_get_type(const uint8_t *h){ - return (*h) & ((1<<5)-1); -} - -static inline uint8_t nal_header_get_nri(const uint8_t *h){ - return ((*h) >> 5) & 0x3; -} - -void rfc3984_init(Rfc3984Context *ctx){ - ms_queue_init(&ctx->q); - ctx->m=NULL; - ctx->maxsz=ms_get_payload_max_size(); - ctx->mode=0; - ctx->last_ts=0x943FEA43;/*some random value*/ - ctx->stap_a_allowed=TRUE; -} - -void rfc3984_set_max_payload_size(Rfc3984Context *ctx, int size){ - ctx->maxsz=size; -} - -static void send_packet(MSQueue *rtpq, uint32_t ts, mblk_t *m, bool_t marker){ - mblk_set_timestamp_info(m,ts); - mblk_set_marker_info(m,marker); - ms_queue_put(rtpq,m); -} - -static void put_nal_size(mblk_t *m, uint16_t sz){ - uint16_t size=htons(sz); - *(uint16_t*)m->b_wptr=size; - m->b_wptr+=2; -} - -static mblk_t * prepend_stapa(mblk_t *m){ - mblk_t *hm=allocb(3,0); - nal_header_init(hm->b_wptr,nal_header_get_nri(m->b_rptr),TYPE_STAP_A); - hm->b_wptr+=1; - put_nal_size(hm,msgdsize(m)); - hm->b_cont=m; - return hm; -} - -static mblk_t * concat_nalus(mblk_t *m1, mblk_t *m2){ - mblk_t *l=allocb(2,0); - /*eventually append a stap-A header to m1, if not already done*/ - if (nal_header_get_type(m1->b_rptr)!=TYPE_STAP_A){ - m1=prepend_stapa(m1); - } - put_nal_size(l,msgdsize(m2)); - l->b_cont=m2; - concatb(m1,l); - return m1; -} - -static mblk_t *prepend_fu_indicator_and_header(mblk_t *m, uint8_t indicator, - bool_t start, bool_t end, uint8_t type){ - mblk_t *h=allocb(2,0); - h->b_wptr[0]=indicator; - h->b_wptr[1]=((start&0x1)<<7)|((end&0x1)<<6)|type; - h->b_wptr+=2; - h->b_cont=m; - if (start) m->b_rptr++;/*skip original nalu header */ - return h; -} - -static void frag_nalu_and_send(MSQueue *rtpq, uint32_t ts, mblk_t *nalu, bool_t marker, int maxsize){ - mblk_t *m; - int payload_max_size=maxsize-2;/*minus FUA header*/ - uint8_t fu_indicator; - uint8_t type=nal_header_get_type(nalu->b_rptr); - uint8_t nri=nal_header_get_nri(nalu->b_rptr); - bool_t start=TRUE; - - nal_header_init(&fu_indicator,nri,TYPE_FU_A); - while(nalu->b_wptr-nalu->b_rptr>payload_max_size){ - m=dupb(nalu); - nalu->b_rptr+=payload_max_size; - m->b_wptr=nalu->b_rptr; - m=prepend_fu_indicator_and_header(m,fu_indicator,start,FALSE,type); - send_packet(rtpq,ts,m,FALSE); - start=FALSE; - } - /*send last packet */ - m=prepend_fu_indicator_and_header(nalu,fu_indicator,FALSE,TRUE,type); - send_packet(rtpq,ts,m,marker); -} - -static void rfc3984_pack_mode_0(Rfc3984Context *ctx, MSQueue *naluq, MSQueue *rtpq, uint32_t ts){ - mblk_t *m; - bool_t end; - int size; - while((m=ms_queue_get(naluq))!=NULL){ - end=ms_queue_empty(naluq); - size=m->b_wptr-m->b_rptr; - if (size>ctx->maxsz){ - ms_warning("This H264 packet does not fit into mtu: size=%i",size); - } - send_packet(rtpq,ts,m,end); - } -} - -/*process NALUs and pack them into rtp payloads */ -static void rfc3984_pack_mode_1(Rfc3984Context *ctx, MSQueue *naluq, MSQueue *rtpq, uint32_t ts){ - mblk_t *m,*prevm=NULL; - int prevsz=0,sz; - bool_t end; - while((m=ms_queue_get(naluq))!=NULL){ - end=ms_queue_empty(naluq); - sz=m->b_wptr-m->b_rptr; - if (ctx->stap_a_allowed){ - if (prevm!=NULL){ - if ((prevsz+sz)<(ctx->maxsz-2)){ - prevm=concat_nalus(prevm,m); - m=NULL; - prevsz+=sz+2;/*+2 for the stapa size field*/ - continue; - }else{ - /*send prevm packet: either single nal or STAP-A*/ - if (prevm->b_cont!=NULL){ - ms_debug("Sending STAP-A"); - }else - ms_debug("Sending previous msg as single NAL"); - send_packet(rtpq,ts,prevm,FALSE); - prevm=NULL; - prevsz=0; - } - } - if (sz<(ctx->maxsz/2)){ - /*try to aggregate it with next packet*/ - prevm=m; - prevsz=sz+3; /*STAP-A header + size*/ - m=NULL; - }else{ - - /*send as single nal or FU-A*/ - if (sz>ctx->maxsz){ - ms_debug("Sending FU-A packets"); - frag_nalu_and_send(rtpq,ts,m,end, ctx->maxsz); - }else{ - ms_debug("Sending Single NAL"); - send_packet(rtpq,ts,m,end); - } - } - }else{ - if (sz>ctx->maxsz){ - ms_debug("Sending FU-A packets"); - frag_nalu_and_send(rtpq,ts,m,end, ctx->maxsz); - }else{ - ms_debug("Sending Single NAL"); - send_packet(rtpq,ts,m,end); - } - } - } - if (prevm){ - ms_debug("Sending Single NAL (2)"); - send_packet(rtpq,ts,prevm,TRUE); - } -} - -static mblk_t * aggregate_fua(Rfc3984Context *ctx, mblk_t *im){ - mblk_t *om=NULL; - uint8_t fu_header; - uint8_t nri,type; - bool_t start,end; - fu_header=im->b_rptr[1]; - type=nal_header_get_type(&fu_header); - start=fu_header>>7; - end=(fu_header>>6)&0x1; - if (start){ - nri=nal_header_get_nri(im->b_rptr); - if (ctx->m!=NULL){ - ms_error("receiving FU-A start while previous FU-A is not " - "finished"); - freemsg(ctx->m); - ctx->m=NULL; - } - im->b_rptr++; - nal_header_init(im->b_rptr,nri,type); - ctx->m=im; - }else{ - if (ctx->m!=NULL){ - im->b_rptr+=2; - concatb(ctx->m,im); - }else{ - ms_error("Receiving continuation FU packet but no start."); - freemsg(im); - } - } - if (end && ctx->m){ - msgpullup(ctx->m,-1); - om=ctx->m; - ctx->m=NULL; - } - return om; -} - -/*process incoming rtp data and output NALUs, whenever possible*/ -void rfc3984_unpack(Rfc3984Context *ctx, mblk_t *im, MSQueue *out){ - uint8_t type=nal_header_get_type(im->b_rptr); - uint8_t *p; - int marker = mblk_get_marker_info(im); - uint32_t ts=mblk_get_timestamp_info(im); - - if (ctx->last_ts!=ts){ - /*a new frame is arriving, in case the marker bit was not set in previous frame, output it now*/ - /* unless this is a FU-A (workarond some other apps bugs)*/ - ctx->last_ts=ts; - if (ctx->m==NULL){ - while(!ms_queue_empty(&ctx->q)){ - ms_queue_put(out,ms_queue_get(&ctx->q)); - } - } - } - - if (im->b_cont) msgpullup(im,-1); - - if (type==TYPE_STAP_A){ - ms_debug("Receiving STAP-A"); - /*split into nalus*/ - uint16_t sz; - uint8_t *buf=(uint8_t*)&sz; - mblk_t *nal; - for(p=im->b_rptr+1;pb_wptr;){ - buf[0]=p[0]; - buf[1]=p[1]; - sz=ntohs(sz); - nal=dupb(im); - p+=2; - nal->b_rptr=p; - p+=sz; - nal->b_wptr=p; - if (p>im->b_wptr){ - ms_error("Malformed STAP-A packet"); - freemsg(nal); - break; - } - ms_queue_put(&ctx->q,nal); - } - freemsg(im); - }else if (type==TYPE_FU_A){ - ms_debug("Receiving FU-A"); - mblk_t *o=aggregate_fua(ctx,im); - if (o) ms_queue_put(&ctx->q,o); - }else{ - if (ctx->m){ - /*discontinued FU-A, purge it*/ - freemsg(ctx->m); - ctx->m=NULL; - } - /*single nal unit*/ - ms_debug("Receiving single NAL"); - ms_queue_put(&ctx->q,im); - } - - if (marker){ - ctx->last_ts=ts; - ms_debug("Marker bit set"); - /*end of frame, output everything*/ - while(!ms_queue_empty(&ctx->q)){ - ms_queue_put(out,ms_queue_get(&ctx->q)); - } - } -} - - -void rfc3984_pack(Rfc3984Context *ctx, MSQueue *naluq, MSQueue *rtpq, uint32_t ts){ - switch(ctx->mode){ - case 0: - rfc3984_pack_mode_0(ctx,naluq,rtpq,ts); - break; - case 1: - rfc3984_pack_mode_1(ctx,naluq,rtpq,ts); - break; - default: - ms_error("Bad or unsupported mode %i",ctx->mode); - } -} - -void rfc3984_uninit(Rfc3984Context *ctx){ - ms_queue_flush(&ctx->q); - if (ctx->m) freemsg(ctx->m); - ctx->m=NULL; -} - -void rfc3984_set_mode(Rfc3984Context *ctx, int mode){ - ctx->mode=mode; -} - -void rfc3984_enable_stap_a(Rfc3984Context *ctx, bool_t yesno){ - ctx->stap_a_allowed=yesno; -} diff --git a/linphone/mediastreamer2/src/sdlout.c b/linphone/mediastreamer2/src/sdlout.c deleted file mode 100644 index 0288cb295..000000000 --- a/linphone/mediastreamer2/src/sdlout.c +++ /dev/null @@ -1,375 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" - -#include -#include - -typedef struct SdlOut -{ - MSVideoSize size; - MSVideoSize local_size; /*size of local preview */ - MSPixFmt format; - SDL_Surface *screen; - SDL_Overlay *overlay; - mblk_t *smallb; - int scale_factor; - bool_t lsize_init; -} SdlOut; - - -#define SCALE_FACTOR 6 - -static bool_t sdl_initialized=FALSE; - -static void sdl_out_init(MSFilter *f){ - SdlOut *obj=ms_new(SdlOut,1); - obj->size.width = MS_VIDEO_SIZE_CIF_W; - obj->size.height = MS_VIDEO_SIZE_CIF_H; - obj->local_size.width = MS_VIDEO_SIZE_CIF_W; - obj->local_size.height = MS_VIDEO_SIZE_CIF_H; - obj->lsize_init=FALSE; - obj->scale_factor=SCALE_FACTOR; - obj->format=MS_RGB24; - obj->screen=NULL; - obj->overlay=NULL; - obj->smallb=NULL; - -#if !defined(WIN32) && !defined(__APPLE__) - if (!sdl_initialized){ - - /* Initialize the SDL library */ - if( SDL_Init(SDL_INIT_VIDEO) < 0 ) { - ms_error("Couldn't initialize SDL: %s", SDL_GetError()); - return; - } - /* Clean up on exit */ - atexit(SDL_Quit); - sdl_initialized=TRUE; - } -#endif - f->data=obj; -} - -static void sdl_destroy_window(SdlOut *obj){ - if (obj->overlay!=NULL){ - SDL_FreeYUVOverlay(obj->overlay); - obj->overlay=NULL; - } - if (obj->screen!=NULL){ - SDL_FreeSurface(obj->screen); - obj->screen=NULL; - } -} - -static void sdl_out_uninit(MSFilter *f){ - SdlOut *s=(SdlOut*)f->data; - sdl_destroy_window(s); - if (s->smallb!=NULL) freemsg(s->smallb); - ms_free(s); -} - -static void sdl_create_window(SdlOut *obj){ - obj->screen = SDL_SetVideoMode(obj->size.width, obj->size.height, 0,SDL_SWSURFACE); - if ( obj->screen == NULL ) { - ms_warning("Couldn't set video mode: %s\n", - SDL_GetError()); - return ; - } - if (obj->screen->flags & SDL_HWSURFACE) ms_message("SDL surface created in hardware"); - SDL_WM_SetCaption("Linphone Video", NULL); - - if (obj->format==MS_YUV420P){ - ms_message("Using yuv overlay."); - obj->overlay=SDL_CreateYUVOverlay(obj->size.width,obj->size.height,SDL_YV12_OVERLAY,obj->screen); - if (obj->overlay==NULL){ - ms_warning("Couldn't create yuv overlay: %s\n", - SDL_GetError()); - return; - }else{ - if (obj->overlay->hw_overlay) ms_message("YUV overlay using hardware acceleration."); - } - } -} - -mblk_t * resize_yuv_small(unsigned char *pict, int w, int h, int scale){ - int i,j,id,jd; - int nh,nw; - unsigned char *smallpict; - int ysize,usize,ydsize,udsize; - int smallpict_sz; - unsigned char *dptr,*sptr; - mblk_t *smallb; - nw=w/scale; - nh=h/scale; - ysize=w*h; - usize=ysize/4; - ydsize=nw*nh; - udsize=ydsize/4; - smallpict_sz=(ydsize*3)/2; - smallb=allocb(smallpict_sz,0); - smallpict=smallb->b_wptr; - smallb->b_wptr+=smallpict_sz; - - dptr=smallpict; - sptr=pict; - for (j=0,jd=0;jb_rptr; - int i,j; - int jlim,ilim; - int off; - unsigned char *dptr; - - ilim=MIN(x+w,lay->w); - jlim=MIN(y+h,lay->h); - SDL_LockYUVOverlay(lay); - /* set Y */ - dptr=lay->pixels[0]; - for (j=y;jw; - for (i=x;ipixels[2]; - for (j=y/2;jw/2); - for (i=x/2;ipixels[1]; - for (j=y/2;jw/2); - for (i=x/2;ib_rptr; - int ysize=lay->pitches[0]*lay->h; - int usize; - w2=lay->w/2; - h2=lay->h/2; - usize=w2*h2; - SDL_LockYUVOverlay(lay); - memcpy(lay->pixels[0],data,ysize); - memcpy(lay->pixels[2],data+ysize,usize); - memcpy(lay->pixels[1],data+ysize+usize,usize); - SDL_UnlockYUVOverlay(lay); -} - -static void sdl_out_process(MSFilter *f){ - SdlOut *obj=(SdlOut*)f->data; - mblk_t *inm0=NULL; - mblk_t *inm1=NULL; - int err; - SDL_Rect smallrect; - SDL_Rect rect; - bool_t got_preview=FALSE; - -#if defined(WIN32) || defined(__APPLE__) - if (!sdl_initialized){ - - /* Initialize the SDL library */ - if( SDL_Init(SDL_INIT_VIDEO) < 0 ) { - ms_error("Couldn't initialize SDL: %s", SDL_GetError()); - return; - } - /* Clean up on exit */ - atexit(SDL_Quit); - sdl_initialized=TRUE; - } -#endif - - if (obj->screen==NULL){ - sdl_create_window(obj); - } - - rect.w=obj->size.width; - rect.h=obj->size.height; - rect.x=0; - rect.y=0; - smallrect.w=obj->size.width/SCALE_FACTOR; - smallrect.h=obj->size.height/SCALE_FACTOR; - smallrect.x=obj->size.width - smallrect.w ; - smallrect.y=obj->size.height -smallrect.h; - - - while (f->inputs[0]!=NULL && (inm0=ms_queue_get(f->inputs[0]))!=NULL){ - SDL_Surface *surf; - if (obj->format==MS_YUV420P){ - fill_overlay(obj->overlay,inm0); - }else { - surf=SDL_CreateRGBSurfaceFrom(inm0->b_rptr,obj->size.width,obj->size.height,24,obj->size.width*3,0,0,0,0); - - err=SDL_BlitSurface(surf,NULL,obj->screen,NULL); - if (err<0) ms_warning("Fail to blit surface: %s",SDL_GetError()); - SDL_FreeSurface(surf); - } - freemsg(inm0); - } - while (f->inputs[1]!=NULL && (inm1=ms_queue_get(f->inputs[1]))!=NULL){ - /* this message is blitted on the right,bottom corner of the screen */ - SDL_Surface *surf; - got_preview=TRUE; - if (!obj->lsize_init){ - /*attempt to guess the video size of the local preview buffer*/ - int bsize=msgdsize(inm1); - if (bsize<(MS_VIDEO_SIZE_CIF_W*MS_VIDEO_SIZE_CIF_H*3/2)){ - /*surely qcif ?*/ - obj->local_size.width=MS_VIDEO_SIZE_QCIF_W; - obj->local_size.height=MS_VIDEO_SIZE_QCIF_H; - ms_message("preview is in QCIF."); - obj->scale_factor=SCALE_FACTOR/2; - } - obj->lsize_init=TRUE; - } - if (obj->format==MS_YUV420P){ - if (obj->smallb!=NULL) { - freemsg(obj->smallb); - } - obj->smallb=resize_yuv_small(inm1->b_rptr,obj->local_size.width,obj->local_size.height,obj->scale_factor); - fill_overlay_at_pos(obj->overlay,obj->smallb,smallrect.x, smallrect.y, smallrect.w, smallrect.h); - freemsg(inm1); - }else { - surf=SDL_CreateRGBSurfaceFrom(inm1->b_rptr,obj->size.width,obj->size.height,24,obj->size.width*3,0,0,0,0); - - err=SDL_BlitSurface(surf,NULL,obj->screen,&smallrect); - if (err<0) ms_warning("Fail to blit surface: %s",SDL_GetError()); - SDL_FreeSurface(surf); - } - } - if (!got_preview){ - /* this is the case were we have only inm0, we have to redisplay inm1 */ - if (obj->format==MS_YUV420P){ - if (obj->smallb!=NULL){ - fill_overlay_at_pos(obj->overlay,obj->smallb,smallrect.x, smallrect.y, smallrect.w, smallrect.h); - } - } - } - - if (obj->format==MS_YUV420P) SDL_DisplayYUVOverlay(obj->overlay,&rect); - else SDL_UpdateRect(obj->screen,0,0,obj->size.width,obj->size.height); - -#if defined(WIN32) || defined(__APPLE__) - { - SDL_Event event; - SDL_PollEvent(&event); - } -#endif -} - -static int sdl_out_set_pix_fmt(MSFilter *f,void *arg){ - SdlOut *s=(SdlOut*)f->data; - s->format=*(MSPixFmt*)arg; - return 0; -} - -static int sdl_out_set_vsize(MSFilter *f,void *arg){ - SdlOut *s=(SdlOut*)f->data; - s->size=*(MSVideoSize*)arg; - s->local_size=*(MSVideoSize*)arg; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_PIX_FMT , sdl_out_set_pix_fmt}, - { MS_FILTER_SET_VIDEO_SIZE , sdl_out_set_vsize }, - { 0 ,NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_sdl_out_desc={ - MS_SDL_OUT_ID, - "MSSdlOut", - N_("A video display window using SDL"), - MS_FILTER_OTHER, - NULL, - 2, - 0, - sdl_out_init, - NULL, - sdl_out_process, - NULL, - sdl_out_uninit, - methods -}; - -#else - -MSFilterDesc ms_sdl_out_desc={ - .id=MS_SDL_OUT_ID, - .name="MSSdlOut", - .text=N_("A video display window using SDL"), - .category=MS_FILTER_OTHER, - .ninputs=2, - .noutputs=0, - .init=sdl_out_init, - .process=sdl_out_process, - .uninit=sdl_out_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_sdl_out_desc) diff --git a/linphone/mediastreamer2/src/sizeconv.c b/linphone/mediastreamer2/src/sizeconv.c deleted file mode 100644 index 401f2aeb5..000000000 --- a/linphone/mediastreamer2/src/sizeconv.c +++ /dev/null @@ -1,235 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msvideo.h" - -#include "ffmpeg-priv.h" - -typedef struct SizeConvState{ - MSVideoSize target_vsize; - MSVideoSize in_vsize; - YuvBuf outbuf; - struct SwsContext *sws_ctx; - mblk_t *om; - float fps; - float start_time; - int frame_count; - queue_t rq; -} SizeConvState; - - -/*this MSFilter will do on the fly picture size conversion. It attempts to guess the picture size from the yuv buffer size. YUV420P is assumed on input. -For now it only supports QCIF->CIF, QVGA->CIF and CIF->CIF (does nothing in this case)*/ - -static void size_conv_init(MSFilter *f){ - SizeConvState *s=(SizeConvState *)ms_new(SizeConvState,1); - s->target_vsize.width = MS_VIDEO_SIZE_CIF_W; - s->target_vsize.height = MS_VIDEO_SIZE_CIF_H; - s->in_vsize.width=0; - s->in_vsize.height=0; - s->sws_ctx=NULL; - s->om=NULL; - s->start_time=0; - s->frame_count=-1; - s->fps=-1; /* default to process ALL frames */ - qinit(&s->rq); - f->data=s; -} - -static void size_conv_uninit(MSFilter *f){ - SizeConvState *s=(SizeConvState*)f->data; - ms_free(s); -} - -static void size_conv_postprocess(MSFilter *f){ - SizeConvState *s=(SizeConvState*)f->data; - if (s->sws_ctx!=NULL) { - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - if (s->om!=NULL){ - freemsg(s->om); - s->om=NULL; - } - flushq(&s->rq,0); - s->frame_count=-1; -} - -static mblk_t *size_conv_alloc_mblk(SizeConvState *s){ - if (s->om!=NULL){ - int ref=s->om->b_datap->db_ref; - if (ref==1){ - return dupmsg(s->om); - }else{ - /*the last msg is still referenced by somebody else*/ - ms_message("size_conv_alloc_mblk: Somebody still retaining yuv buffer (ref=%i)",ref); - freemsg(s->om); - s->om=NULL; - } - } - s->om=yuv_buf_alloc(&s->outbuf,s->target_vsize.width,s->target_vsize.height); - return dupmsg(s->om); -} - -static struct SwsContext * get_resampler(SizeConvState *s, int w, int h){ - if (s->in_vsize.width!=w || - s->in_vsize.height!=h || s->sws_ctx==NULL){ - if (s->sws_ctx!=NULL){ - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - s->sws_ctx=sws_getContext(w,h,PIX_FMT_YUV420P, - s->target_vsize.width,s->target_vsize.height,PIX_FMT_YUV420P, - SWS_FAST_BILINEAR,NULL, NULL, NULL); - s->in_vsize.width=w; - s->in_vsize.height=h; - } - return s->sws_ctx; -} - -static void size_conv_process(MSFilter *f){ - SizeConvState *s=(SizeConvState*)f->data; - YuvBuf inbuf; - mblk_t *im; - int cur_frame; - - ms_filter_lock(f); - - if (s->frame_count==-1){ - s->start_time=(float)f->ticker->time; - s->frame_count=0; - } - while((im=ms_queue_get(f->inputs[0]))!=NULL ){ - putq(&s->rq, im); - } - - cur_frame=(int)((f->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame<=s->frame_count && s->fps>=0) { - /* too much frame */ - while(s->rq.q_mcount>1){ - ms_message("MSSizeConv: extra frame removed."); - im=getq(&s->rq); - freemsg(im); - } - ms_filter_unlock(f); - return; - } - - if (cur_frame>s->frame_count && s->fps>=0) { - /*keep the most recent frame if several frames have been captured */ - while(s->rq.q_mcount>1){ - ms_message("MSSizeConv: extra frame removed."); - im=getq(&s->rq); - freemsg(im); - } - } - while((im=getq(&s->rq))!=NULL ){ - if (yuv_buf_init_from_mblk(&inbuf,im)==0){ - if (inbuf.w==s->target_vsize.width && - inbuf.h==s->target_vsize.height){ - ms_queue_put(f->outputs[0],im); - }else{ - struct SwsContext *sws_ctx=get_resampler(s,inbuf.w,inbuf.h); - mblk_t *om=size_conv_alloc_mblk(s); - if (sws_scale(sws_ctx,inbuf.planes,inbuf.strides, 0, - inbuf.h, s->outbuf.planes, s->outbuf.strides)<0){ - ms_error("MSSizeConv: error in sws_scale()."); - } - ms_queue_put(f->outputs[0],om); - freemsg(im); - } - s->frame_count++; - }else freemsg(im); - } - - ms_filter_unlock(f); -} - - -static int sizeconv_set_vsize(MSFilter *f, void*arg){ - SizeConvState *s=(SizeConvState*)f->data; - ms_filter_lock(f); - s->target_vsize=*(MSVideoSize*)arg; - freemsg(s->om); - s->om=NULL; - if (s->sws_ctx!=NULL) { - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - ms_filter_unlock(f); - return 0; -} - -static int sizeconv_set_fps(MSFilter *f, void *arg){ - SizeConvState *s=(SizeConvState*)f->data; - s->fps=*((float*)arg); - s->frame_count=-1; /* reset counter used for fps */ - return 0; -} - - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , sizeconv_set_fps }, - { MS_FILTER_SET_VIDEO_SIZE, sizeconv_set_vsize }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_size_conv_desc={ - MS_SIZE_CONV_ID, - "MSSizeConv", - N_("A video size converter"), - MS_FILTER_OTHER, - NULL, - 1, - 1, - size_conv_init, - NULL, - size_conv_process, - size_conv_postprocess, - size_conv_uninit, - methods -}; - -#else - -MSFilterDesc ms_size_conv_desc={ - .id=MS_SIZE_CONV_ID, - .name="MSSizeConv", - .text=N_("a small video size converter"), - .ninputs=1, - .noutputs=1, - .init=size_conv_init, - .process=size_conv_process, - .postprocess=size_conv_postprocess, - .uninit=size_conv_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_size_conv_desc) - diff --git a/linphone/mediastreamer2/src/speexec.c b/linphone/mediastreamer2/src/speexec.c deleted file mode 100644 index 6e55faf27..000000000 --- a/linphone/mediastreamer2/src/speexec.c +++ /dev/null @@ -1,381 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msspeexec.h" - -#include -#include - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#ifdef WIN32 -#include /* for alloca */ -#endif - -static const int framesize=128; -static const int filter_length=2048; /*250 ms*/ - -typedef struct SpeexECState{ - SpeexEchoState *ecstate; - MSBufferizer speak_delay; - int size_delay; - int playback_delay; - MSBufferizer in[2]; - int framesize; - int filterlength; - int samplerate; - SpeexPreprocessState *den; - int ref; - int echo; - int out; - int delay_ms; - int tail_length_ms; -}SpeexECState; - -static void speex_ec_init(MSFilter *f){ - SpeexECState *s=(SpeexECState *)ms_new(SpeexECState,1); - - s->samplerate=8000; - s->framesize=framesize; - s->filterlength=filter_length; - - ms_bufferizer_init(&s->speak_delay); - s->size_delay=0; - s->delay_ms=0; - s->playback_delay=0; - s->tail_length_ms=250; - - ms_bufferizer_init(&s->in[0]); - ms_bufferizer_init(&s->in[1]); - s->ecstate=NULL; - s->den = NULL; - - f->data=s; -} - -static void speex_ec_uninit(MSFilter *f){ - SpeexECState *s=(SpeexECState*)f->data; - ms_bufferizer_uninit(&s->speak_delay); - ms_bufferizer_uninit(&s->in[0]); - ms_bufferizer_uninit(&s->in[1]); - if (s->ecstate!=NULL) - speex_echo_state_destroy(s->ecstate); - if (s->den!=NULL) - speex_preprocess_state_destroy(s->den); - - ms_free(s); -} - - -static void speex_ec_preprocess(MSFilter *f){ - SpeexECState *s=(SpeexECState*)f->data; - if (s->ecstate!=NULL) - speex_echo_state_destroy(s->ecstate); - if (s->den!=NULL) - speex_preprocess_state_destroy(s->den); - - if (s->tail_length_ms!=0) - s->filterlength=(s->tail_length_ms*s->samplerate)/1000; - if (s->delay_ms!=0) - s->playback_delay=s->delay_ms*s->samplerate/1000; - ms_message("Initializing speex echo canceler with framesize=%i, filterlength=%i, playback_delay=%i", - s->framesize,s->filterlength,s->playback_delay); - s->ecstate=speex_echo_state_init(s->framesize,s->filterlength); - s->den = speex_preprocess_state_init(s->framesize, s->samplerate); - speex_echo_ctl(s->ecstate, SPEEX_ECHO_SET_SAMPLING_RATE, &s->samplerate); - speex_preprocess_ctl(s->den, SPEEX_PREPROCESS_SET_ECHO_STATE, s->ecstate); -} - -/* inputs[0]= reference signal (sent to soundcard) - * inputs[1]= near speech & echo signal (read from soundcard) - * outputs[1]= near end speech, echo removed - towards far end -*/ -static void speex_ec_process(MSFilter *f){ - SpeexECState *s=(SpeexECState*)f->data; - int nbytes=s->framesize*2; - uint8_t *in1; - mblk_t *om0,*om1; -#ifdef AMD_WIN32_HACK - static int count=0; -#endif - mblk_t *m; - mblk_t *md; - - /* first fill delayed buffer until playback delay is reached (only in first n calls) */ - if (s->size_delayplayback_delay){ - while((m=ms_queue_get(f->inputs[0]))!=NULL && s->size_delayplayback_delay){ - // Duplicate queue : one to write to the output speaker, the other will be delayed for AEC - int size=msgdsize(m); - md = copyb(m); - s->size_delay = s->size_delay + size; - ms_bufferizer_put(&s->speak_delay,md); - ms_bufferizer_put(&s->in[0],m); - } - - if (s->size_delay<=s->playback_delay) - { - /* make sure we always send block with same size */ - while (ms_bufferizer_get_avail(&s->speak_delay)>=nbytes) - { - om0=allocb(nbytes,0); - ms_bufferizer_read(&s->speak_delay,(uint8_t*)om0->b_wptr,nbytes); - om0->b_wptr+=nbytes; - ms_queue_put(f->outputs[0],om0); - } - - /* make sure we always send block with same size */ - ms_bufferizer_put_from_queue(&s->in[1],f->inputs[1]); - while (ms_bufferizer_get_avail(&s->in[1])>=nbytes) - { - om0=allocb(nbytes,0); - ms_bufferizer_read(&s->in[1],(uint8_t*)om0->b_wptr,nbytes); - om0->b_wptr+=nbytes; - ms_queue_put(f->outputs[1],om0); - } - /* we are now equal and speaker is delayed */ - return; - } - } - - ms_bufferizer_put_from_queue(&s->in[1],f->inputs[1]); - - /*read input and put in bufferizers*/ - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - md = copyb(m); - // Duplicate queue : one to write to the output speaker, the other will be delayed for AEC - ms_bufferizer_put(&s->in[0],m); - ms_bufferizer_put(&s->speak_delay,md); - } - - - in1=(uint8_t*)alloca(nbytes); - - //ms_debug("speexec: in0=%i, in1=%i",ms_bufferizer_get_avail(&s->in[0]),ms_bufferizer_get_avail(&s->in[1])); - - while (ms_bufferizer_get_avail(&s->speak_delay)>=nbytes && ms_bufferizer_get_avail(&s->in[1])>=nbytes){ - om0=allocb(nbytes,0); - ms_bufferizer_read(&s->speak_delay,(uint8_t*)om0->b_wptr,nbytes); - om0->b_wptr+=nbytes; - ms_queue_put(f->outputs[0],om0); - - om0=allocb(nbytes,0); - ms_bufferizer_read(&s->in[0],(uint8_t*)om0->b_wptr,nbytes); - /* we have reference signal */ - /* the reference signal is sent through outputs[0]*/ - - om0->b_wptr+=nbytes; - //ms_queue_put(f->outputs[0],om0); - - ms_bufferizer_read(&s->in[1],in1,nbytes); - /* we have echo signal */ - om1=allocb(nbytes,0); - speex_echo_cancellation(s->ecstate,(short*)in1,(short*)om0->b_rptr,(short*)om1->b_wptr); - speex_preprocess_run(s->den, (short*)om1->b_wptr); - ms_filter_notify(f, MS_SPEEX_EC_ECHO_STATE, (void*)s->ecstate); - ms_filter_notify(f, MS_SPEEX_EC_PREPROCESS_MIC, (void*)s->den); - - om1->b_wptr+=nbytes; - ms_queue_put(f->outputs[1],om1); -#ifdef AMD_WIN32_HACK - count++; - if (count==100*3) - { - ms_message("periodic reset of echo canceller."); - speex_echo_state_reset(s->ecstate); - count=0; - } -#endif - freeb(om0); - } - - if (ms_bufferizer_get_avail(&s->speak_delay)> 5*320*(s->samplerate/8000)) /* above 4*20ms -> useless */ - { - /* reset evrything */ - ms_warning("speexec: -reset of echo canceller- in0=%i, in1=%i",ms_bufferizer_get_avail(&s->in[0]),ms_bufferizer_get_avail(&s->in[1])); - flushq(&s->in[1].q,0); - flushq(&s->in[0].q,0); - flushq(&s->speak_delay.q,0); - ms_bufferizer_init(&s->in[0]); - ms_bufferizer_init(&s->in[1]); - ms_bufferizer_init(&s->speak_delay); - s->size_delay=0; - speex_echo_state_reset(s->ecstate); - } - - while (ms_bufferizer_get_avail(&s->in[1])> 5*320*(s->samplerate/8000)){ - om1=allocb(nbytes,0); - ms_bufferizer_read(&s->in[1],(uint8_t*)om1->b_wptr,nbytes); - om1->b_wptr+=nbytes; - ms_queue_put(f->outputs[1],om1); - ms_message("too much echo signal, sending anyway."); - speex_echo_state_reset(s->ecstate); - } - -} - -static void speex_ec_postprocess(MSFilter *f){ - SpeexECState *s=(SpeexECState*)f->data; - ms_bufferizer_uninit(&s->in[0]); - ms_bufferizer_uninit(&s->in[1]); - ms_bufferizer_uninit(&s->speak_delay); - ms_bufferizer_init(&s->in[0]); - ms_bufferizer_init(&s->in[1]); - ms_bufferizer_init(&s->speak_delay); - s->size_delay=0; - - if (s->ecstate!=NULL){ - speex_echo_state_destroy(s->ecstate); - s->ecstate=NULL; - } - if (s->den!=NULL){ - speex_preprocess_state_destroy(s->den); - s->den=NULL; - } -} - -static int speex_ec_set_sr(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - - s->samplerate = *(int*)arg; - - if (s->ecstate!=NULL){ - speex_echo_state_destroy(s->ecstate); - if (s->den!=NULL) - speex_preprocess_state_destroy(s->den); - - s->ecstate=speex_echo_state_init(s->framesize,s->filterlength); - s->den = speex_preprocess_state_init(s->framesize, s->samplerate); - speex_echo_ctl(s->ecstate, SPEEX_ECHO_SET_SAMPLING_RATE, &s->samplerate); - speex_preprocess_ctl(s->den, SPEEX_PREPROCESS_SET_ECHO_STATE, s->ecstate); - } - return 0; -} - -static int speex_ec_set_framesize(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - s->framesize = *(int*)arg; - - if (s->ecstate!=NULL){ - speex_echo_state_destroy(s->ecstate); - if (s->den!=NULL) - speex_preprocess_state_destroy(s->den); - - s->ecstate=speex_echo_state_init(s->framesize,s->filterlength); - s->den = speex_preprocess_state_init(s->framesize, s->samplerate); - speex_echo_ctl(s->ecstate, SPEEX_ECHO_SET_SAMPLING_RATE, &s->samplerate); - speex_preprocess_ctl(s->den, SPEEX_PREPROCESS_SET_ECHO_STATE, s->ecstate); - } - return 0; -} - -static int speex_ec_set_filterlength(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - s->filterlength = (*(int*)arg)*(s->samplerate/8000); - s->tail_length_ms=0;/*trust the length in sample, not the length in milliseconds*/ - if (s->ecstate!=NULL) - speex_echo_state_destroy(s->ecstate); - if (s->den!=NULL) - speex_preprocess_state_destroy(s->den); - - s->ecstate=speex_echo_state_init(s->framesize,s->filterlength); - s->den = speex_preprocess_state_init(s->framesize, s->samplerate); - speex_echo_ctl(s->ecstate, SPEEX_ECHO_SET_SAMPLING_RATE, &s->samplerate); - speex_preprocess_ctl(s->den, SPEEX_PREPROCESS_SET_ECHO_STATE, s->ecstate); - return 0; -} - -static int speex_ec_set_delay2(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - s->delay_ms = *(int*)arg; - return 0; -} - -static int speex_ec_set_tail_length2(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - s->tail_length_ms=*(int*)arg; - return 0; -} - -static int speex_ec_set_playbackdelay(MSFilter *f, void *arg){ - SpeexECState *s=(SpeexECState*)f->data; - s->playback_delay = *(int*)arg; - - flushq(&s->in[1].q,0); - flushq(&s->in[0].q,0); - flushq(&s->speak_delay.q,0); - ms_bufferizer_init(&s->in[0]); - ms_bufferizer_init(&s->in[1]); - ms_bufferizer_init(&s->speak_delay); - s->size_delay=0; - speex_echo_state_reset(s->ecstate); - return 0; -} - -static MSFilterMethod speex_ec_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE, speex_ec_set_sr }, - { MS_SPEEX_EC_SET_TAIL_LENGTH , speex_ec_set_tail_length2 }, - { MS_SPEEX_EC_SET_DELAY , speex_ec_set_delay2 }, - { MS_SPEEX_EC_SET_FRAME_SIZE , speex_ec_set_framesize }, -/*these are kept for backward compatibility */ - { MS_FILTER_SET_FRAMESIZE, speex_ec_set_framesize }, - { MS_FILTER_SET_FILTERLENGTH, speex_ec_set_filterlength }, - { MS_FILTER_SET_PLAYBACKDELAY, speex_ec_set_playbackdelay }, - { 0 , NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_speex_ec_desc={ - MS_SPEEX_EC_ID, - "MSSpeexEC", - N_("Echo canceller using speex library"), - MS_FILTER_OTHER, - NULL, - 2, - 2, - speex_ec_init, - speex_ec_preprocess, - speex_ec_process, - speex_ec_postprocess, - speex_ec_uninit, - speex_ec_methods -}; - -#else - -MSFilterDesc ms_speex_ec_desc={ - .id=MS_SPEEX_EC_ID, - .name="MSSpeexEC", - .text=N_("Echo canceller using speex library"), - .category=MS_FILTER_OTHER, - .ninputs=2, - .noutputs=2, - .init=speex_ec_init, - .preprocess=speex_ec_preprocess, - .process=speex_ec_process, - .postprocess=speex_ec_postprocess, - .uninit=speex_ec_uninit, - .methods=speex_ec_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_speex_ec_desc) diff --git a/linphone/mediastreamer2/src/swscale.h b/linphone/mediastreamer2/src/swscale.h deleted file mode 100644 index a0c735b69..000000000 --- a/linphone/mediastreamer2/src/swscale.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2001-2003 Michael Niedermayer - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef FFMPEG_SWSCALE_H -#define FFMPEG_SWSCALE_H - -/** - * @file swscale.h - * @brief - * external api for the swscale stuff - */ - -#include "libavutil/avutil.h" - -#define LIBSWSCALE_VERSION_MAJOR 0 -#define LIBSWSCALE_VERSION_MINOR 5 -#define LIBSWSCALE_VERSION_MICRO 1 - -#define LIBSWSCALE_VERSION_INT AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \ - LIBSWSCALE_VERSION_MINOR, \ - LIBSWSCALE_VERSION_MICRO) -#define LIBSWSCALE_VERSION AV_VERSION(LIBSWSCALE_VERSION_MAJOR, \ - LIBSWSCALE_VERSION_MINOR, \ - LIBSWSCALE_VERSION_MICRO) -#define LIBSWSCALE_BUILD LIBSWSCALE_VERSION_INT - -#define LIBSWSCALE_IDENT "SwS" AV_STRINGIFY(LIBSWSCALE_VERSION) - -/* values for the flags, the stuff on the command line is different */ -#define SWS_FAST_BILINEAR 1 -#define SWS_BILINEAR 2 -#define SWS_BICUBIC 4 -#define SWS_X 8 -#define SWS_POINT 0x10 -#define SWS_AREA 0x20 -#define SWS_BICUBLIN 0x40 -#define SWS_GAUSS 0x80 -#define SWS_SINC 0x100 -#define SWS_LANCZOS 0x200 -#define SWS_SPLINE 0x400 - -#define SWS_SRC_V_CHR_DROP_MASK 0x30000 -#define SWS_SRC_V_CHR_DROP_SHIFT 16 - -#define SWS_PARAM_DEFAULT 123456 - -#define SWS_PRINT_INFO 0x1000 - -//the following 3 flags are not completely implemented -//internal chrominace subsampling info -#define SWS_FULL_CHR_H_INT 0x2000 -//input subsampling info -#define SWS_FULL_CHR_H_INP 0x4000 -#define SWS_DIRECT_BGR 0x8000 -#define SWS_ACCURATE_RND 0x40000 - -#define SWS_CPU_CAPS_MMX 0x80000000 -#define SWS_CPU_CAPS_MMX2 0x20000000 -#define SWS_CPU_CAPS_3DNOW 0x40000000 -#define SWS_CPU_CAPS_ALTIVEC 0x10000000 -#define SWS_CPU_CAPS_BFIN 0x01000000 - -#define SWS_MAX_REDUCE_CUTOFF 0.002 - -#define SWS_CS_ITU709 1 -#define SWS_CS_FCC 4 -#define SWS_CS_ITU601 5 -#define SWS_CS_ITU624 5 -#define SWS_CS_SMPTE170M 5 -#define SWS_CS_SMPTE240M 7 -#define SWS_CS_DEFAULT 5 - - - -// when used for filters they must have an odd number of elements -// coeffs cannot be shared between vectors -typedef struct { - double *coeff; - int length; -} SwsVector; - -// vectors can be shared -typedef struct { - SwsVector *lumH; - SwsVector *lumV; - SwsVector *chrH; - SwsVector *chrV; -} SwsFilter; - -struct SwsContext; - -void sws_freeContext(struct SwsContext *swsContext); - -struct SwsContext *sws_getContext(int srcW, int srcH, int srcFormat, int dstW, int dstH, int dstFormat, int flags, - SwsFilter *srcFilter, SwsFilter *dstFilter, double *param); -int sws_scale(struct SwsContext *context, uint8_t* src[], int srcStride[], int srcSliceY, - int srcSliceH, uint8_t* dst[], int dstStride[]); -int sws_scale_ordered(struct SwsContext *context, uint8_t* src[], int srcStride[], int srcSliceY, - int srcSliceH, uint8_t* dst[], int dstStride[]) attribute_deprecated; - - -int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4], int srcRange, const int table[4], int dstRange, int brightness, int contrast, int saturation); -int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table, int *srcRange, int **table, int *dstRange, int *brightness, int *contrast, int *saturation); -SwsVector *sws_getGaussianVec(double variance, double quality); -SwsVector *sws_getConstVec(double c, int length); -SwsVector *sws_getIdentityVec(void); -void sws_scaleVec(SwsVector *a, double scalar); -void sws_normalizeVec(SwsVector *a, double height); -void sws_convVec(SwsVector *a, SwsVector *b); -void sws_addVec(SwsVector *a, SwsVector *b); -void sws_subVec(SwsVector *a, SwsVector *b); -void sws_shiftVec(SwsVector *a, int shift); -SwsVector *sws_cloneVec(SwsVector *a); - -void sws_printVec(SwsVector *a); -void sws_freeVec(SwsVector *a); - -SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur, - float lumaSarpen, float chromaSharpen, - float chromaHShift, float chromaVShift, - int verbose); -void sws_freeFilter(SwsFilter *filter); - -struct SwsContext *sws_getCachedContext(struct SwsContext *context, - int srcW, int srcH, int srcFormat, - int dstW, int dstH, int dstFormat, int flags, - SwsFilter *srcFilter, SwsFilter *dstFilter, double *param); - -#endif /* FFMPEG_SWSCALE_H */ diff --git a/linphone/mediastreamer2/src/tee.c b/linphone/mediastreamer2/src/tee.c deleted file mode 100644 index 23c5be4c0..000000000 --- a/linphone/mediastreamer2/src/tee.c +++ /dev/null @@ -1,110 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mstee.h" - -#define MS_TEE_NOUTPUTS 10 - -typedef struct _TeeData{ - bool_t muted[MS_TEE_NOUTPUTS]; -}TeeData; - -static void tee_init(MSFilter *f){ - f->data=ms_new0(TeeData,1); -} - -static void tee_uninit(MSFilter *f){ - ms_free(f->data); -} - -static void tee_process(MSFilter *f){ - TeeData *d=(TeeData*)f->data; - mblk_t *im; - int i; - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - for(i=0;idesc->noutputs;i++){ - if (f->outputs[i]!=NULL && !d->muted[i]) - ms_queue_put(f->outputs[i],dupmsg(im)); - } - freemsg(im); - } -} - -static int tee_mute(MSFilter *f, void *arg){ - TeeData *d=(TeeData*)f->data; - int pin=((int*)arg)[0]; - if (pin>=0 && pinmuted[pin]=TRUE; - return 0; - } - return -1; -} - -static int tee_unmute(MSFilter *f, void *arg){ - TeeData *d=(TeeData*)f->data; - int pin=((int*)arg)[0]; - if (pin>=0 && pinmuted[pin]=FALSE; - return 0; - } - return -1; -} - -static MSFilterMethod tee_methods[]={ - { MS_TEE_MUTE , tee_mute }, - { MS_TEE_UNMUTE , tee_unmute }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_tee_desc={ - MS_TEE_ID, - "MSTee", - N_("A filter that reads from input and copy to its multiple outputs."), - MS_FILTER_OTHER, - NULL, - 1, - MS_TEE_NOUTPUTS, - tee_init, - NULL, - tee_process, - NULL, - tee_uninit, - tee_methods -}; - -#else - -MSFilterDesc ms_tee_desc={ - .id=MS_TEE_ID, - .name="MSTee", - .text=N_("A filter that reads from input and copy to its multiple outputs."), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=MS_TEE_NOUTPUTS, - .init=tee_init, - .process=tee_process, - .uninit=tee_uninit, - .methods=tee_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_tee_desc) diff --git a/linphone/mediastreamer2/src/theora.c b/linphone/mediastreamer2/src/theora.c deleted file mode 100644 index 4f043254c..000000000 --- a/linphone/mediastreamer2/src/theora.c +++ /dev/null @@ -1,590 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msvideo.h" - -#include - -typedef struct EncState{ - theora_state tstate; - theora_info tinfo; - yuv_buffer yuv; - mblk_t *packed_conf; - uint64_t start_time; - uint64_t conf_time; - unsigned int mtu; - unsigned int nframes; -} EncState; - -static void enc_init(MSFilter *f){ - EncState *s=(EncState *)ms_new(EncState,1); - theora_info_init(&s->tinfo); - s->tinfo.width=MS_VIDEO_SIZE_CIF_W; - s->tinfo.height=MS_VIDEO_SIZE_CIF_H; - s->tinfo.frame_width=MS_VIDEO_SIZE_CIF_W; - s->tinfo.frame_height=MS_VIDEO_SIZE_CIF_H; - s->tinfo.offset_x=0; - s->tinfo.offset_y=0; - s->tinfo.target_bitrate=500000; - s->tinfo.pixelformat=OC_PF_420; - s->tinfo.fps_numerator=15; - s->tinfo.fps_denominator=1; - s->tinfo.aspect_numerator=1; - s->tinfo.aspect_denominator=1; - s->tinfo.colorspace=OC_CS_UNSPECIFIED; - s->tinfo.dropframes_p=0; - s->tinfo.quick_p=1; - s->tinfo.quality=63; - s->tinfo.keyframe_auto_p=1; - s->tinfo.keyframe_frequency=64; - s->tinfo.keyframe_frequency_force=64; - s->tinfo.keyframe_data_target_bitrate=s->tinfo.target_bitrate*1.2; - s->tinfo.keyframe_auto_threshold=80; - s->tinfo.keyframe_mindistance=8; - s->tinfo.noise_sensitivity=1; - s->packed_conf=NULL; - s->start_time=0; - s->conf_time=0; - s->mtu=ms_get_payload_max_size()-6; - s->nframes=0; - f->data=s; -} - -static void enc_uninit(MSFilter *f){ - EncState *s=(EncState*)f->data; - theora_info_clear(&s->tinfo); - ms_free(s); -} - -static int enc_set_vsize(MSFilter *f, void*data){ - MSVideoSize *vs=(MSVideoSize*)data; - EncState *s=(EncState*)f->data; - s->tinfo.width=vs->width; - s->tinfo.height=vs->height; - s->tinfo.frame_width=vs->width; - s->tinfo.frame_height=vs->height; - return 0; -} - -static int enc_get_vsize(MSFilter *f, void *data){ - EncState *s=(EncState*)f->data; - MSVideoSize *vs=(MSVideoSize*)data; - vs->width=s->tinfo.width; - vs->height=s->tinfo.height; - return 0; -} - -static int enc_add_attr(MSFilter *f, void*data){ - /*const char *attr=(const char*)data; - EncState *s=(EncState*)f->data;*/ - return 0; -} - -static int enc_set_fps(MSFilter *f, void *data){ - float *fps=(float*)data; - EncState *s=(EncState*)f->data; - s->tinfo.fps_numerator=*fps; - s->tinfo.keyframe_frequency=(*fps)*5; - s->tinfo.keyframe_frequency_force=(*fps)*5; - return 0; -} - -static int enc_get_fps(MSFilter *f, void *data){ - EncState *s=(EncState*)f->data; - float *fps=(float*)data; - *fps=s->tinfo.fps_numerator; - return 0; -} - -static int enc_set_br(MSFilter *f, void*data){ - int br=*(int*)data; - EncState *s=(EncState*)f->data; - MSVideoSize vsize; - float fps; - float codecbr=(float)br; - vsize.width=s->tinfo.width; - vsize.height=s->tinfo.height; - fps=s->tinfo.fps_numerator; - s->tinfo.target_bitrate=codecbr*0.9; - s->tinfo.keyframe_data_target_bitrate=codecbr; - /*those default settings would need to be affined*/ - if (br>=1024000){ - vsize.width = MS_VIDEO_SIZE_4CIF_W; - vsize.height = MS_VIDEO_SIZE_4CIF_H; - s->tinfo.quality=15; - fps=30; - }else if (br>=512000){ - vsize.width = MS_VIDEO_SIZE_CIF_W; - vsize.height = MS_VIDEO_SIZE_CIF_H; - s->tinfo.quality=15; - fps=15; - }else if (br>=256000){ - vsize.width = MS_VIDEO_SIZE_CIF_W; - vsize.height = MS_VIDEO_SIZE_CIF_H; - s->tinfo.quality=5; - fps=15; - }else if(br>=128000){ - vsize.width=MS_VIDEO_SIZE_QCIF_W; - vsize.height=MS_VIDEO_SIZE_QCIF_H; - s->tinfo.quality=20; - fps=10; - }else if(br>=64000){ - vsize.width=MS_VIDEO_SIZE_QCIF_W; - vsize.height=MS_VIDEO_SIZE_QCIF_H; - s->tinfo.quality=7; - fps=7; - } - enc_set_vsize(f,&vsize); - enc_set_fps(f,&fps); - return 0; -} - -static int enc_set_mtu(MSFilter *f, void*data){ - EncState *s=(EncState*)f->data; - s->mtu=*(int*)data; - return 0; -} - -#define THEORA_RAW_DATA 0 -#define THEORA_PACKED_CONF 1 -#define THEORA_COMMENT 2 -#define THEORA_RESERVED 3 - -#define NOT_FRAGMENTED 0 -#define START_FRAGMENT 1 -#define CONT_FRAGMENT 2 -#define END_FRAGMENT 3 - - -static inline void payload_header_set(uint8_t *buf, uint32_t ident, uint8_t ft, uint8_t tdt, uint8_t pkts){ - uint32_t tmp; - tmp=((ident&0xFFFFFF)<<8) | ((ft&0x3)<<6) | ((tdt&0x3)<<4) | (pkts&0xf); - *((uint32_t*)buf)=htonl(tmp); -} - -static inline uint32_t payload_header_get_ident(uint8_t *buf){ - uint32_t *tmp=(uint32_t*)buf; - return (ntohl(*tmp)>>8) & 0xFFFFFF; -} - -static inline uint32_t payload_header_get_tdt(uint8_t *buf){ - uint32_t *tmp=(uint32_t*)buf; - return ((ntohl(*tmp))>>4) & 0x3; -} - -static inline uint32_t payload_header_get_ft(uint8_t *buf){ - uint32_t *tmp=(uint32_t*)buf; - return ((ntohl(*tmp))>>6) & 0x3; -} - -static inline uint32_t payload_header_get_pkts(uint8_t *buf){ - uint32_t *tmp=(uint32_t*)buf; - return ntohl(*tmp) & 0xf; -} - -static int create_packed_conf(EncState *s){ - ogg_packet p; - theora_state *tstate=&s->tstate; - mblk_t *h,*t; - if (theora_encode_header(tstate,&p)!=0){ - ms_error("theora_encode_header() error."); - return -1; - } - h=allocb(p.bytes,0); - memcpy(h->b_wptr,p.packet,p.bytes); - h->b_wptr+=p.bytes; - if (theora_encode_tables(tstate,&p)!=0){ - ms_error("theora_encode_tables error."); - freemsg(h); - return -1; - } - t=allocb(p.bytes,0); - memcpy(t->b_wptr,p.packet,p.bytes); - t->b_wptr+=p.bytes; - h->b_cont=t; - msgpullup(h,-1); - s->packed_conf=h; - return 0; -} - -static void enc_preprocess(MSFilter *f){ - EncState *s=(EncState*)f->data; - int err; - if ((err=theora_encode_init(&s->tstate,&s->tinfo))!=0){ - ms_error("error in theora_encode_init() : %i !",err); - } - s->yuv.y_width=s->tinfo.width; - s->yuv.y_height=s->tinfo.height; - s->yuv.y_stride=s->tinfo.width; - s->yuv.uv_width=s->tinfo.width/2; - s->yuv.uv_height=s->tinfo.height/2; - s->yuv.uv_stride=s->tinfo.width/2; - create_packed_conf(s); - s->conf_time=0; - s->nframes=0; -} - -static void enc_postprocess(MSFilter *f){ - EncState *s=(EncState*)f->data; - theora_clear(&s->tstate); - - //If preprocess is called after postprocess, - //then we loose all info... - //theora_info_clear(&s->tinfo); - - if (s->packed_conf) { - freemsg(s->packed_conf); - s->packed_conf=NULL; - } -} - -static void enc_fill_yuv(yuv_buffer *yuv, mblk_t *im){ - yuv->y=(uint8_t*)im->b_rptr; - yuv->u=(uint8_t*)im->b_rptr+(yuv->y_stride*yuv->y_height); - yuv->v=(uint8_t*)yuv->u+(yuv->uv_stride*yuv->uv_height); -} - - -static void packetize_and_send(MSFilter *f, EncState *s, mblk_t *om, uint32_t timestamp, uint8_t tdt){ - mblk_t *packet; - mblk_t *h; - int npackets=0; - static const int ident=0xdede; - while(om!=NULL){ - if (om->b_wptr-om->b_rptr>=s->mtu){ - packet=dupb(om); - packet->b_wptr=packet->b_rptr+s->mtu; - om->b_rptr=packet->b_wptr; - }else { - packet=om; - om=NULL; - } - ++npackets; - h=allocb(6,0); - if (npackets==1){ - if (om==NULL) - payload_header_set(h->b_wptr,ident,NOT_FRAGMENTED,tdt,1); - else - payload_header_set(h->b_wptr,ident,START_FRAGMENT,tdt,1); - }else{ - if (om==NULL) - payload_header_set(h->b_wptr,ident,END_FRAGMENT,tdt,1); - else - payload_header_set(h->b_wptr,ident,CONT_FRAGMENT,tdt,1); - } - h->b_wptr+=4; - *((uint16_t*)h->b_wptr)=htons(msgdsize(packet)); - h->b_wptr+=2; - h->b_cont=packet; - mblk_set_timestamp_info(h,timestamp); - ms_debug("sending theora frame of size %i",msgdsize(h)); - ms_queue_put(f->outputs[0],h); - } -} - -bool_t need_send_conf(EncState *s, uint64_t elapsed){ - /*send immediately then 10 seconds later */ - if ( (elapsed==0 && s->conf_time==0) - || (elapsed>=3000 && s->conf_time==1) - || (elapsed>=10000 && s->conf_time==2)){ - s->conf_time++; - return TRUE; - } - return FALSE; -} - -static void enc_process(MSFilter *f){ - mblk_t *im,*om; - ogg_packet op; - EncState *s=(EncState*)f->data; - uint64_t timems=f->ticker->time; - uint32_t timestamp=timems*90; - uint64_t elapsed; - - - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - /*for the firsts frames only send theora packed conf*/ - om=NULL; - if (s->nframes==0){ - s->start_time=timems; - } - elapsed=timems-s->start_time; - - if (need_send_conf(s,elapsed)){ - if (s->packed_conf) { - om=dupmsg(s->packed_conf); - ms_message("sending theora packed conf (%i bytes)",msgdsize(om)); - packetize_and_send(f,s,om,timestamp,THEORA_PACKED_CONF); - }else { - ms_error("No packed conf to send."); - } - }else{ - enc_fill_yuv(&s->yuv,im); - ms_debug("subtmitting yuv frame to theora encoder..."); - if (theora_encode_YUVin(&s->tstate,&s->yuv)!=0){ - ms_error("theora_encode_YUVin error."); - }else{ - if (theora_encode_packetout(&s->tstate,0,&op)==1){ - ms_debug("Got theora coded frame"); - om=allocb(op.bytes,0); - memcpy(om->b_wptr,op.packet,op.bytes); - om->b_wptr+=op.bytes; - packetize_and_send(f,s,om,timestamp,THEORA_RAW_DATA); - } - } - } - freemsg(im); - s->nframes++; - } -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_SET_VIDEO_SIZE, enc_set_vsize }, - { MS_FILTER_SET_FPS, enc_set_fps }, - { MS_FILTER_GET_VIDEO_SIZE, enc_get_vsize }, - { MS_FILTER_GET_FPS, enc_get_fps }, - { MS_FILTER_ADD_ATTR, enc_add_attr }, - { MS_FILTER_SET_BITRATE, enc_set_br }, - { MS_FILTER_SET_MTU, enc_set_mtu }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_theora_enc_desc={ - MS_THEORA_ENC_ID, - "MSTheoraEnc", - N_("The theora video encoder from xiph.org"), - MS_FILTER_ENCODER, - "theora", - 1, - 1, - enc_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_theora_enc_desc={ - .id=MS_THEORA_ENC_ID, - .name="MSTheoraEnc", - .text=N_("The open-source and royalty-free 'theora' video codec from xiph.org"), - .category=MS_FILTER_ENCODER, - .enc_fmt="theora", - .ninputs=1, - .noutputs=1, - .init=enc_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=enc_methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_theora_enc_desc) - -typedef struct DecState{ - theora_state tstate; - theora_info tinfo; - mblk_t *yuv; - mblk_t *curframe; - bool_t ready; -}DecState; - -static void dec_init(MSFilter *f){ - DecState *s=(DecState *)ms_new(DecState,1); - s->ready=FALSE; - theora_info_init(&s->tinfo); - s->yuv=NULL; - s->curframe=NULL; - f->data=s; -} - -static void dec_uninit(MSFilter *f){ - DecState *s=(DecState*)f->data; - if (s->yuv!=NULL) freemsg(s->yuv); - if (s->curframe!=NULL) freemsg(s->curframe); - theora_info_clear(&s->tinfo); - ms_free(s); -} - -static bool_t dec_init_theora(DecState *s, ogg_packet *op){ - theora_comment tcom; - static const int ident_packet_size=42; - theora_comment_init(&tcom); - tcom.vendor="dummy"; - op->b_o_s=1; - if (theora_decode_header(&s->tinfo,&tcom,op)==0){ - op->packet+=ident_packet_size; - op->bytes-=ident_packet_size; - /*recall once to decode tables*/ - if (theora_decode_header(&s->tinfo,&tcom,op)==0){ - if (theora_decode_init(&s->tstate,&s->tinfo)==0){ - ms_debug("theora decoder ready, pixfmt=%i", - s->tinfo.pixelformat); - return TRUE; - } - }else{ - ms_warning("error decoding theora tables"); - } - }else{ - ms_warning("error decoding theora header"); - } - return FALSE; -} -/* remove payload header and agregates fragmented packets */ -static mblk_t *dec_unpacketize(MSFilter *f, DecState *s, mblk_t *im, int *tdt){ - uint8_t ft; - *tdt=payload_header_get_tdt((uint8_t*)im->b_rptr); - ft=payload_header_get_ft((uint8_t*)im->b_rptr); - im->b_rptr+=6; - - if (ft==NOT_FRAGMENTED) return im; - if (ft==START_FRAGMENT){ - if (s->curframe!=NULL) - freemsg(s->curframe); - s->curframe=im; - }else if (ft==CONT_FRAGMENT){ - if (s->curframe!=NULL) - concatb(s->curframe,im); - else - freemsg(im); - }else{/*end fragment*/ - if (s->curframe!=NULL){ - mblk_t *ret; - concatb(s->curframe,im); - msgpullup(s->curframe,-1); - ret=s->curframe; - s->curframe=NULL; - return ret; - }else - freemsg(im); - } - return NULL; -} - -static void dec_process_frame(MSFilter *f, DecState *s, ogg_packet *op){ - yuv_buffer yuv; - if (theora_decode_packetin(&s->tstate,op)==0){ - if (theora_decode_YUVout(&s->tstate,&yuv)==0){ - mblk_t *om; - int i; - int ylen=yuv.y_width*yuv.y_height; - int uvlen=yuv.uv_width*yuv.uv_height; - ms_debug("Got yuv buffer from theora decoder"); - if (s->yuv==NULL){ - int len=(ylen)+(2*uvlen); - s->yuv=allocb(len,0); - } - om=dupb(s->yuv); - for(i=0;ib_wptr,yuv.y+yuv.y_stride*i,yuv.y_width); - om->b_wptr+=yuv.y_width; - } - for(i=0;ib_wptr,yuv.u+yuv.uv_stride*i,yuv.uv_width); - om->b_wptr+=yuv.uv_width; - } - for(i=0;ib_wptr,yuv.v+yuv.uv_stride*i,yuv.uv_width); - om->b_wptr+=yuv.uv_width; - } - ms_queue_put(f->outputs[0],om); - } - }else{ - ms_warning("theora decoding error"); - } -} - -static void dec_process(MSFilter *f){ - mblk_t *im; - mblk_t *m; - ogg_packet op; - int tdt; - DecState *s=(DecState*)f->data; - while( (im=ms_queue_get(f->inputs[0]))!=0) { - m=dec_unpacketize(f,s,im,&tdt); - if (m!=NULL){ - /* now in im we have only the theora data*/ - op.packet=(uint8_t*)m->b_rptr; - op.bytes=m->b_wptr-m->b_rptr; - op.b_o_s=0; - op.e_o_s=0; - op.granulepos=0; - op.packetno=0; - if (tdt!=THEORA_RAW_DATA) /*packed conf*/ { - if (!s->ready){ - if (dec_init_theora(s,&op)) - s->ready=TRUE; - } - }else{ - if (s->ready){ - dec_process_frame(f,s,&op); - }else{ - ms_warning("skipping theora packet because decoder was not initialized yet with theora header and tables"); - } - } - freemsg(m); - } - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_theora_dec_desc={ - MS_THEORA_DEC_ID, - "MSTheoraDec", - N_("The theora video decoder from xiph.org"), - MS_FILTER_DECODER, - "theora", - 1, - 1, - dec_init, - NULL, - dec_process, - NULL, - dec_uninit, - NULL -}; - -#else - -MSFilterDesc ms_theora_dec_desc={ - .id=MS_THEORA_DEC_ID, - .name="MSTheoraDec", - .text=N_("The theora video decoder from xiph.org"), - .category=MS_FILTER_DECODER, - .enc_fmt="theora", - .ninputs=1, - .noutputs=1, - .init=dec_init, - .process=dec_process, - .uninit=dec_uninit -}; - -#endif -MS_FILTER_DESC_EXPORT(ms_theora_dec_desc) diff --git a/linphone/mediastreamer2/src/ulaw.c b/linphone/mediastreamer2/src/ulaw.c deleted file mode 100644 index 5d948f434..000000000 --- a/linphone/mediastreamer2/src/ulaw.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "g711common.h" - -typedef struct _UlawEncData{ - MSBufferizer *bz; - int ptime; - uint32_t ts; -} UlawEncData; - -static UlawEncData * ulaw_enc_data_new(){ - UlawEncData *obj=(UlawEncData *)ms_new(UlawEncData,1); - obj->bz=ms_bufferizer_new(); - obj->ptime=0; - obj->ts=0; - return obj; -} - -static void ulaw_enc_data_destroy(UlawEncData *obj){ - ms_bufferizer_destroy(obj->bz); - ms_free(obj); -} - -static void ulaw_enc_init(MSFilter *obj){ - obj->data=ulaw_enc_data_new(); -} - -static void ulaw_enc_uninit(MSFilter *obj){ - ulaw_enc_data_destroy((UlawEncData*)obj->data); -} - -static void ulaw_enc_process(MSFilter *obj){ - UlawEncData *dt=(UlawEncData*)obj->data; - MSBufferizer *bz=dt->bz; - uint8_t buffer[2240]; - int frame_per_packet=2; - int size_of_pcm=320; - - mblk_t *m; - - if (dt->ptime>=10) - { - frame_per_packet = dt->ptime/10; - } - - if (frame_per_packet<=0) - frame_per_packet=1; - if (frame_per_packet>14) /* 7*20 == 140 ms max */ - frame_per_packet=14; - - size_of_pcm = 160*frame_per_packet; /* ex: for 20ms -> 160*2==320 */ - - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - ms_bufferizer_put(bz,m); - } - - while (ms_bufferizer_read(bz,buffer,size_of_pcm)==size_of_pcm){ - mblk_t *o=allocb(size_of_pcm/2,0); - int i; - for (i=0;ib_wptr=s16_to_ulaw(((int16_t*)buffer)[i]); - o->b_wptr++; - } - mblk_set_timestamp_info(o,dt->ts); - dt->ts+=size_of_pcm/2; - ms_queue_put(obj->outputs[0],o); - } -} - -static int enc_add_fmtp(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - UlawEncData *s=(UlawEncData*)f->data; - char val[30]; - if (fmtp_get_value(fmtp,"ptime",val,sizeof(val))){ - s->ptime=atoi(val); - ms_message("MSUlawEnc: got ptime=%i",s->ptime); - } - return 0; -} - - -static int enc_add_attr(MSFilter *f, void *arg){ - const char *fmtp=(const char *)arg; - UlawEncData *s=(UlawEncData*)f->data; - if (strstr(fmtp,"ptime:10")!=NULL){ - s->ptime=10; - }else if (strstr(fmtp,"ptime:20")!=NULL){ - s->ptime=20; - }else if (strstr(fmtp,"ptime:30")!=NULL){ - s->ptime=30; - }else if (strstr(fmtp,"ptime:40")!=NULL){ - s->ptime=40; - }else if (strstr(fmtp,"ptime:50")!=NULL){ - s->ptime=50; - }else if (strstr(fmtp,"ptime:60")!=NULL){ - s->ptime=60; - }else if (strstr(fmtp,"ptime:70")!=NULL){ - s->ptime=70; - }else if (strstr(fmtp,"ptime:80")!=NULL){ - s->ptime=80; - }else if (strstr(fmtp,"ptime:90")!=NULL){ - s->ptime=90; - }else if (strstr(fmtp,"ptime:100")!=NULL){ - s->ptime=100; - }else if (strstr(fmtp,"ptime:110")!=NULL){ - s->ptime=110; - }else if (strstr(fmtp,"ptime:120")!=NULL){ - s->ptime=120; - }else if (strstr(fmtp,"ptime:130")!=NULL){ - s->ptime=130; - }else if (strstr(fmtp,"ptime:140")!=NULL){ - s->ptime=140; - } - return 0; -} - -static MSFilterMethod enc_methods[]={ - { MS_FILTER_ADD_ATTR , enc_add_attr}, - { MS_FILTER_ADD_FMTP , enc_add_fmtp}, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_ulaw_enc_desc={ - MS_ULAW_ENC_ID, - "MSUlawEnc", - N_("ITU-G.711 ulaw encoder"), - MS_FILTER_ENCODER, - "pcmu", - 1, - 1, - ulaw_enc_init, - NULL, - ulaw_enc_process, - NULL, - ulaw_enc_uninit, - enc_methods -}; - -#else - -MSFilterDesc ms_ulaw_enc_desc={ - .id=MS_ULAW_ENC_ID, - .name="MSUlawEnc", - .text=N_("ITU-G.711 ulaw encoder"), - .category=MS_FILTER_ENCODER, - .enc_fmt="pcmu", - .ninputs=1, - .noutputs=1, - .init=ulaw_enc_init, - .process=ulaw_enc_process, - .uninit=ulaw_enc_uninit, - .methods=enc_methods -}; - -#endif - -static void ulaw_dec_process(MSFilter *obj){ - mblk_t *m; - while((m=ms_queue_get(obj->inputs[0]))!=NULL){ - mblk_t *o; - msgpullup(m,-1); - o=allocb((m->b_wptr-m->b_rptr)*2,0); - for(;m->b_rptrb_wptr;m->b_rptr++,o->b_wptr+=2){ - *((int16_t*)(o->b_wptr))=ulaw_to_s16(*m->b_rptr); - } - freemsg(m); - ms_queue_put(obj->outputs[0],o); - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_ulaw_dec_desc={ - MS_ULAW_DEC_ID, - "MSUlawDec", - N_("ITU-G.711 ulaw decoder"), - MS_FILTER_DECODER, - "pcmu", - 1, - 1, - NULL, - NULL, - ulaw_dec_process, - NULL, - NULL, - NULL -}; - -#else - -MSFilterDesc ms_ulaw_dec_desc={ - .id=MS_ULAW_DEC_ID, - .name="MSUlawDec", - .text=N_("ITU-G.711 ulaw decoder"), - .category=MS_FILTER_DECODER, - .enc_fmt="pcmu", - .ninputs=1, - .noutputs=1, - .process=ulaw_dec_process, -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_ulaw_dec_desc) -MS_FILTER_DESC_EXPORT(ms_ulaw_enc_desc) - - diff --git a/linphone/mediastreamer2/src/vfw-missing.h b/linphone/mediastreamer2/src/vfw-missing.h deleted file mode 100755 index 0c9006cbb..000000000 --- a/linphone/mediastreamer2/src/vfw-missing.h +++ /dev/null @@ -1,286 +0,0 @@ -#ifndef vfw_missing_h -#define vfw_missing_h - -typedef struct videohdr_tag { - LPBYTE lpData; /* pointer to locked data buffer */ - DWORD dwBufferLength; /* Length of data buffer */ - DWORD dwBytesUsed; /* Bytes actually used */ - DWORD dwTimeCaptured; /* Milliseconds from start of stream */ - DWORD_PTR dwUser; /* for client's use */ - DWORD dwFlags; /* assorted flags (see defines) */ - DWORD_PTR dwReserved[4]; /* reserved for driver */ -} VIDEOHDR, NEAR *PVIDEOHDR, FAR * LPVIDEOHDR; - -typedef struct tagCaptureParms { - DWORD dwRequestMicroSecPerFrame; // Requested capture rate - BOOL fMakeUserHitOKToCapture; // Show "Hit OK to cap" dlg? - UINT wPercentDropForError; // Give error msg if > (10%) - BOOL fYield; // Capture via background task? - DWORD dwIndexSize; // Max index size in frames (32K) - UINT wChunkGranularity; // Junk chunk granularity (2K) - BOOL fUsingDOSMemory; // Use DOS buffers? - UINT wNumVideoRequested; // # video buffers, If 0, autocalc - BOOL fCaptureAudio; // Capture audio? - UINT wNumAudioRequested; // # audio buffers, If 0, autocalc - UINT vKeyAbort; // Virtual key causing abort - BOOL fAbortLeftMouse; // Abort on left mouse? - BOOL fAbortRightMouse; // Abort on right mouse? - BOOL fLimitEnabled; // Use wTimeLimit? - UINT wTimeLimit; // Seconds to capture - BOOL fMCIControl; // Use MCI video source? - BOOL fStepMCIDevice; // Step MCI device? - DWORD dwMCIStartTime; // Time to start in MS - DWORD dwMCIStopTime; // Time to stop in MS - BOOL fStepCaptureAt2x; // Perform spatial averaging 2x - UINT wStepCaptureAverageFrames; // Temporal average n Frames - DWORD dwAudioBufferSize; // Size of audio bufs (0 = default) - BOOL fDisableWriteCache; // Attempt to disable write cache - UINT AVStreamMaster; // Which stream controls length? -} CAPTUREPARMS, *PCAPTUREPARMS, FAR *LPCAPTUREPARMS; - -typedef struct { - UINT uiImageWidth; - UINT uiImageHeight; - BOOL fLiveWindow; - BOOL fOverlayWindow; - BOOL fScale; - POINT ptScroll; - BOOL fUsingDefaultPalette; - BOOL fAudioHardware; - BOOL fCapFileExists; - DWORD dwCurrentVideoFrame; - DWORD dwCurrentVideoFramesDropped; - DWORD dwCurrentWaveSamples; - DWORD dwCurrentTimeElapsedMS; - HPALETTE hPalCurrent; - BOOL fCapturingNow; - DWORD dwReturn; - UINT wNumVideoAllocated; - UINT wNumAudioAllocated; -} CAPSTATUS, *PCAPSTATUS, FAR *LPCAPSTATUS; - - -#ifdef __cplusplus -/* SendMessage in C++*/ -#define AVICapSM(hwnd,m,w,l) ( (::IsWindow(hwnd)) ? ::SendMessage(hwnd,m,w,l) : 0) -#else -/* SendMessage in C */ -#define AVICapSM(hwnd,m,w,l) ( (IsWindow(hwnd)) ? SendMessage(hwnd,m,w,l) : 0) -#endif /* __cplusplus */ - -#define WM_CAP_START WM_USER - -// start of unicode messages -#define WM_CAP_UNICODE_START WM_USER+100 - -#define WM_CAP_GET_CAPSTREAMPTR (WM_CAP_START+ 1) - -#define WM_CAP_SET_CALLBACK_ERRORW (WM_CAP_UNICODE_START+ 2) -#define WM_CAP_SET_CALLBACK_STATUSW (WM_CAP_UNICODE_START+ 3) -#define WM_CAP_SET_CALLBACK_ERRORA (WM_CAP_START+ 2) -#define WM_CAP_SET_CALLBACK_STATUSA (WM_CAP_START+ 3) -#ifdef UNICODE -#define WM_CAP_SET_CALLBACK_ERROR WM_CAP_SET_CALLBACK_ERRORW -#define WM_CAP_SET_CALLBACK_STATUS WM_CAP_SET_CALLBACK_STATUSW -#else -#define WM_CAP_SET_CALLBACK_ERROR WM_CAP_SET_CALLBACK_ERRORA -#define WM_CAP_SET_CALLBACK_STATUS WM_CAP_SET_CALLBACK_STATUSA -#endif - - -#define WM_CAP_SET_CALLBACK_YIELD (WM_CAP_START+ 4) -#define WM_CAP_SET_CALLBACK_FRAME (WM_CAP_START+ 5) -#define WM_CAP_SET_CALLBACK_VIDEOSTREAM (WM_CAP_START+ 6) -#define WM_CAP_SET_CALLBACK_WAVESTREAM (WM_CAP_START+ 7) -#define WM_CAP_GET_USER_DATA (WM_CAP_START+ 8) -#define WM_CAP_SET_USER_DATA (WM_CAP_START+ 9) - -#define WM_CAP_DRIVER_CONNECT (WM_CAP_START+ 10) -#define WM_CAP_DRIVER_DISCONNECT (WM_CAP_START+ 11) - -#define WM_CAP_DRIVER_GET_NAMEA (WM_CAP_START+ 12) -#define WM_CAP_DRIVER_GET_VERSIONA (WM_CAP_START+ 13) -#define WM_CAP_DRIVER_GET_NAMEW (WM_CAP_UNICODE_START+ 12) -#define WM_CAP_DRIVER_GET_VERSIONW (WM_CAP_UNICODE_START+ 13) -#ifdef UNICODE -#define WM_CAP_DRIVER_GET_NAME WM_CAP_DRIVER_GET_NAMEW -#define WM_CAP_DRIVER_GET_VERSION WM_CAP_DRIVER_GET_VERSIONW -#else -#define WM_CAP_DRIVER_GET_NAME WM_CAP_DRIVER_GET_NAMEA -#define WM_CAP_DRIVER_GET_VERSION WM_CAP_DRIVER_GET_VERSIONA -#endif - -#define WM_CAP_DRIVER_GET_CAPS (WM_CAP_START+ 14) - -#define WM_CAP_FILE_SET_CAPTURE_FILEA (WM_CAP_START+ 20) -#define WM_CAP_FILE_GET_CAPTURE_FILEA (WM_CAP_START+ 21) -#define WM_CAP_FILE_SAVEASA (WM_CAP_START+ 23) -#define WM_CAP_FILE_SAVEDIBA (WM_CAP_START+ 25) -#define WM_CAP_FILE_SET_CAPTURE_FILEW (WM_CAP_UNICODE_START+ 20) -#define WM_CAP_FILE_GET_CAPTURE_FILEW (WM_CAP_UNICODE_START+ 21) -#define WM_CAP_FILE_SAVEASW (WM_CAP_UNICODE_START+ 23) -#define WM_CAP_FILE_SAVEDIBW (WM_CAP_UNICODE_START+ 25) -#ifdef UNICODE -#define WM_CAP_FILE_SET_CAPTURE_FILE WM_CAP_FILE_SET_CAPTURE_FILEW -#define WM_CAP_FILE_GET_CAPTURE_FILE WM_CAP_FILE_GET_CAPTURE_FILEW -#define WM_CAP_FILE_SAVEAS WM_CAP_FILE_SAVEASW -#define WM_CAP_FILE_SAVEDIB WM_CAP_FILE_SAVEDIBW -#else -#define WM_CAP_FILE_SET_CAPTURE_FILE WM_CAP_FILE_SET_CAPTURE_FILEA -#define WM_CAP_FILE_GET_CAPTURE_FILE WM_CAP_FILE_GET_CAPTURE_FILEA -#define WM_CAP_FILE_SAVEAS WM_CAP_FILE_SAVEASA -#define WM_CAP_FILE_SAVEDIB WM_CAP_FILE_SAVEDIBA -#endif - -// out of order to save on ifdefs -#define WM_CAP_FILE_ALLOCATE (WM_CAP_START+ 22) -#define WM_CAP_FILE_SET_INFOCHUNK (WM_CAP_START+ 24) - -#define WM_CAP_EDIT_COPY (WM_CAP_START+ 30) - -#define WM_CAP_SET_AUDIOFORMAT (WM_CAP_START+ 35) -#define WM_CAP_GET_AUDIOFORMAT (WM_CAP_START+ 36) - -#define WM_CAP_DLG_VIDEOFORMAT (WM_CAP_START+ 41) -#define WM_CAP_DLG_VIDEOSOURCE (WM_CAP_START+ 42) -#define WM_CAP_DLG_VIDEODISPLAY (WM_CAP_START+ 43) -#define WM_CAP_GET_VIDEOFORMAT (WM_CAP_START+ 44) -#define WM_CAP_SET_VIDEOFORMAT (WM_CAP_START+ 45) -#define WM_CAP_DLG_VIDEOCOMPRESSION (WM_CAP_START+ 46) - -#define WM_CAP_SET_PREVIEW (WM_CAP_START+ 50) -#define WM_CAP_SET_OVERLAY (WM_CAP_START+ 51) -#define WM_CAP_SET_PREVIEWRATE (WM_CAP_START+ 52) -#define WM_CAP_SET_SCALE (WM_CAP_START+ 53) -#define WM_CAP_GET_STATUS (WM_CAP_START+ 54) -#define WM_CAP_SET_SCROLL (WM_CAP_START+ 55) - -#define WM_CAP_GRAB_FRAME (WM_CAP_START+ 60) -#define WM_CAP_GRAB_FRAME_NOSTOP (WM_CAP_START+ 61) - -#define WM_CAP_SEQUENCE (WM_CAP_START+ 62) -#define WM_CAP_SEQUENCE_NOFILE (WM_CAP_START+ 63) -#define WM_CAP_SET_SEQUENCE_SETUP (WM_CAP_START+ 64) -#define WM_CAP_GET_SEQUENCE_SETUP (WM_CAP_START+ 65) - -#define WM_CAP_SET_MCI_DEVICEA (WM_CAP_START+ 66) -#define WM_CAP_GET_MCI_DEVICEA (WM_CAP_START+ 67) -#define WM_CAP_SET_MCI_DEVICEW (WM_CAP_UNICODE_START+ 66) -#define WM_CAP_GET_MCI_DEVICEW (WM_CAP_UNICODE_START+ 67) -#ifdef UNICODE -#define WM_CAP_SET_MCI_DEVICE WM_CAP_SET_MCI_DEVICEW -#define WM_CAP_GET_MCI_DEVICE WM_CAP_GET_MCI_DEVICEW -#else -#define WM_CAP_SET_MCI_DEVICE WM_CAP_SET_MCI_DEVICEA -#define WM_CAP_GET_MCI_DEVICE WM_CAP_GET_MCI_DEVICEA -#endif - - - -#define WM_CAP_STOP (WM_CAP_START+ 68) -#define WM_CAP_ABORT (WM_CAP_START+ 69) - -#define WM_CAP_SINGLE_FRAME_OPEN (WM_CAP_START+ 70) -#define WM_CAP_SINGLE_FRAME_CLOSE (WM_CAP_START+ 71) -#define WM_CAP_SINGLE_FRAME (WM_CAP_START+ 72) - -#define WM_CAP_PAL_OPENA (WM_CAP_START+ 80) -#define WM_CAP_PAL_SAVEA (WM_CAP_START+ 81) -#define WM_CAP_PAL_OPENW (WM_CAP_UNICODE_START+ 80) -#define WM_CAP_PAL_SAVEW (WM_CAP_UNICODE_START+ 81) -#ifdef UNICODE -#define WM_CAP_PAL_OPEN WM_CAP_PAL_OPENW -#define WM_CAP_PAL_SAVE WM_CAP_PAL_SAVEW -#else -#define WM_CAP_PAL_OPEN WM_CAP_PAL_OPENA -#define WM_CAP_PAL_SAVE WM_CAP_PAL_SAVEA -#endif - -#define WM_CAP_PAL_PASTE (WM_CAP_START+ 82) -#define WM_CAP_PAL_AUTOCREATE (WM_CAP_START+ 83) -#define WM_CAP_PAL_MANUALCREATE (WM_CAP_START+ 84) - -// Following added post VFW 1.1 -#define WM_CAP_SET_CALLBACK_CAPCONTROL (WM_CAP_START+ 85) - - -// Defines end of the message range -#define WM_CAP_UNICODE_END WM_CAP_PAL_SAVEW -#define WM_CAP_END WM_CAP_UNICODE_END - -#define capSetCallbackOnError(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_ERROR, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnStatus(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_STATUS, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnYield(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_YIELD, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnFrame(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_FRAME, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnVideoStream(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnWaveStream(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_WAVESTREAM, 0, (LPARAM)(LPVOID)(fpProc))) -#define capSetCallbackOnCapControl(hwnd, fpProc) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_CALLBACK_CAPCONTROL, 0, (LPARAM)(LPVOID)(fpProc))) - -#define capSetUserData(hwnd, lUser) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_USER_DATA, 0, (LPARAM)lUser)) -#define capGetUserData(hwnd) (AVICapSM(hwnd, WM_CAP_GET_USER_DATA, 0, 0)) - -#define capDriverConnect(hwnd, i) ((BOOL)AVICapSM(hwnd, WM_CAP_DRIVER_CONNECT, (WPARAM)(i), 0L)) -#define capDriverDisconnect(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_DRIVER_DISCONNECT, (WPARAM)0, 0L)) -#define capDriverGetName(hwnd, szName, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_DRIVER_GET_NAME, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capDriverGetVersion(hwnd, szVer, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_DRIVER_GET_VERSION, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPTSTR)(szVer))) -#define capDriverGetCaps(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_DRIVER_GET_CAPS, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPCAPDRIVERCAPS)(s))) - -#define capFileSetCaptureFile(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_SET_CAPTURE_FILE, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capFileGetCaptureFile(hwnd, szName, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_GET_CAPTURE_FILE, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capFileAlloc(hwnd, dwSize) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_ALLOCATE, 0, (LPARAM)(DWORD)(dwSize))) -#define capFileSaveAs(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_SAVEAS, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capFileSetInfoChunk(hwnd, lpInfoChunk) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_SET_INFOCHUNK, (WPARAM)0, (LPARAM)(LPCAPINFOCHUNK)(lpInfoChunk))) -#define capFileSaveDIB(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_FILE_SAVEDIB, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) - -#define capEditCopy(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_EDIT_COPY, 0, 0L)) - -#define capSetAudioFormat(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_AUDIOFORMAT, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPWAVEFORMATEX)(s))) -#define capGetAudioFormat(hwnd, s, wSize) ((DWORD)AVICapSM(hwnd, WM_CAP_GET_AUDIOFORMAT, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPWAVEFORMATEX)(s))) -#define capGetAudioFormatSize(hwnd) ((DWORD)AVICapSM(hwnd, WM_CAP_GET_AUDIOFORMAT, (WPARAM)0, (LPARAM)0L)) - -#define capDlgVideoFormat(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_DLG_VIDEOFORMAT, 0, 0L)) -#define capDlgVideoSource(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_DLG_VIDEOSOURCE, 0, 0L)) -#define capDlgVideoDisplay(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_DLG_VIDEODISPLAY, 0, 0L)) -#define capDlgVideoCompression(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_DLG_VIDEOCOMPRESSION, 0, 0L)) - -#define capGetVideoFormat(hwnd, s, wSize) ((DWORD)AVICapSM(hwnd, WM_CAP_GET_VIDEOFORMAT, (WPARAM)(wSize), (LPARAM)(LPVOID)(s))) -#define capGetVideoFormatSize(hwnd) ((DWORD)AVICapSM(hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0L)) -#define capSetVideoFormat(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_VIDEOFORMAT, (WPARAM)(wSize), (LPARAM)(LPVOID)(s))) - -#define capPreview(hwnd, f) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_PREVIEW, (WPARAM)(BOOL)(f), 0L)) -#define capPreviewRate(hwnd, wMS) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_PREVIEWRATE, (WPARAM)(wMS), 0)) -#define capOverlay(hwnd, f) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_OVERLAY, (WPARAM)(BOOL)(f), 0L)) -#define capPreviewScale(hwnd, f) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_SCALE, (WPARAM)(BOOL)f, 0L)) -#define capGetStatus(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_GET_STATUS, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPCAPSTATUS)(s))) -#define capSetScrollPos(hwnd, lpP) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_SCROLL, (WPARAM)0, (LPARAM)(LPPOINT)(lpP))) - -#define capGrabFrame(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_GRAB_FRAME, (WPARAM)0, (LPARAM)0L)) -#define capGrabFrameNoStop(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_GRAB_FRAME_NOSTOP, (WPARAM)0, (LPARAM)0L)) - -#define capCaptureSequence(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_SEQUENCE, (WPARAM)0, (LPARAM)0L)) -#define capCaptureSequenceNoFile(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_SEQUENCE_NOFILE, (WPARAM)0, (LPARAM)0L)) -#define capCaptureStop(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_STOP, (WPARAM)0, (LPARAM)0L)) -#define capCaptureAbort(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_ABORT, (WPARAM)0, (LPARAM)0L)) - -#define capCaptureSingleFrameOpen(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_SINGLE_FRAME_OPEN, (WPARAM)0, (LPARAM)0L)) -#define capCaptureSingleFrameClose(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_SINGLE_FRAME_CLOSE, (WPARAM)0, (LPARAM)0L)) -#define capCaptureSingleFrame(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_SINGLE_FRAME, (WPARAM)0, (LPARAM)0L)) - -#define capCaptureGetSetup(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_GET_SEQUENCE_SETUP, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPCAPTUREPARMS)(s))) -#define capCaptureSetSetup(hwnd, s, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_SEQUENCE_SETUP, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPCAPTUREPARMS)(s))) - -#define capSetMCIDeviceName(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_SET_MCI_DEVICE, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capGetMCIDeviceName(hwnd, szName, wSize) ((BOOL)AVICapSM(hwnd, WM_CAP_GET_MCI_DEVICE, (WPARAM)(wSize), (LPARAM)(LPVOID)(LPTSTR)(szName))) - -#define capPaletteOpen(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_PAL_OPEN, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capPaletteSave(hwnd, szName) ((BOOL)AVICapSM(hwnd, WM_CAP_PAL_SAVE, 0, (LPARAM)(LPVOID)(LPTSTR)(szName))) -#define capPalettePaste(hwnd) ((BOOL)AVICapSM(hwnd, WM_CAP_PAL_PASTE, (WPARAM) 0, (LPARAM)0L)) -#define capPaletteAuto(hwnd, iFrames, iColors) ((BOOL)AVICapSM(hwnd, WM_CAP_PAL_AUTOCREATE, (WPARAM)(iFrames), (LPARAM)(DWORD)(iColors))) -#define capPaletteManual(hwnd, fGrab, iColors) ((BOOL)AVICapSM(hwnd, WM_CAP_PAL_MANUALCREATE, (WPARAM)(fGrab), (LPARAM)(DWORD)(iColors))) - -#define AVSTREAMMASTER_AUDIO 0 /* Audio master (VFW 1.0, 1.1) */ -#define AVSTREAMMASTER_NONE 1 /* No master */ - - -#endif - diff --git a/linphone/mediastreamer2/src/videodec.c b/linphone/mediastreamer2/src/videodec.c deleted file mode 100644 index 1ea0b1f22..000000000 --- a/linphone/mediastreamer2/src/videodec.c +++ /dev/null @@ -1,858 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "ffmpeg-priv.h" - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" -#include "rfc2429.h" - - -extern void ms_ffmpeg_check_init(); - -typedef struct DecState{ - AVCodecContext av_context; - AVCodec *av_codec; - enum CodecID codec; - mblk_t *input; - YuvBuf outbuf; - mblk_t *yuv_msg; - struct SwsContext *sws_ctx; - enum PixelFormat output_pix_fmt; - uint8_t dci[512]; - int dci_size; - bool_t snow_initialized; -}DecState; - - -static void dec_init(MSFilter *f, enum CodecID cid){ - DecState *s=(DecState *)ms_new0(DecState,1); - ms_ffmpeg_check_init(); - - avcodec_get_context_defaults(&s->av_context); - s->av_codec=NULL; - s->codec=cid; - s->input=NULL; - s->yuv_msg=NULL; - s->output_pix_fmt=PIX_FMT_YUV420P; - s->snow_initialized=FALSE; - s->outbuf.w=0; - s->outbuf.h=0; - s->sws_ctx=NULL; - f->data=s; - - s->av_codec=avcodec_find_decoder(s->codec); - if (s->av_codec==NULL){ - ms_error("Could not find decoder %i!",s->codec); - } - /* - s->av_context.width=MS_VIDEO_SIZE_QCIF_W; - s->av_context.height=MS_VIDEO_SIZE_QCIF_H; - */ -} - -static void dec_h263_init(MSFilter *f){ - dec_init(f,CODEC_ID_H263); -} - -static void dec_mpeg4_init(MSFilter *f){ - dec_init(f,CODEC_ID_MPEG4); -} - -static void dec_mjpeg_init(MSFilter *f){ - dec_init(f,CODEC_ID_MJPEG); -} - -static void dec_snow_init(MSFilter *f){ - dec_init(f,CODEC_ID_SNOW); -} - -static void dec_uninit(MSFilter *f){ - DecState *s=(DecState*)f->data; - if (s->input!=NULL) freemsg(s->input); - if (s->yuv_msg!=NULL) freemsg(s->yuv_msg); - if (s->sws_ctx!=NULL){ - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - ms_free(s); -} - -static int dec_add_fmtp(MSFilter *f, void *data){ - const char *fmtp=(const char*)data; - DecState *s=(DecState*)f->data; - char config[512]; - if (fmtp_get_value(fmtp,"config",config,sizeof(config))){ - /*convert hexa decimal config string into a bitstream */ - int i,j,max=strlen(config); - char octet[3]; - octet[2]=0; - for(i=0,j=0;idci[j]=(uint8_t)strtol(octet,NULL,16); - } - s->dci_size=j; - ms_message("Got mpeg4 config string: %s",config); - } - return 0; -} - -static void dec_preprocess(MSFilter *f){ - DecState *s=(DecState*)f->data; - int error; - /* we must know picture size before initializing snow decoder*/ - if (s->codec!=CODEC_ID_SNOW){ - error=avcodec_open(&s->av_context, s->av_codec); - if (error!=0) ms_error("avcodec_open() failed: %i",error); - if (s->codec==CODEC_ID_MPEG4 && s->dci_size>0){ - s->av_context.extradata=s->dci; - s->av_context.extradata_size=s->dci_size; - } - } -} - -static void dec_postprocess(MSFilter *f){ - DecState *s=(DecState*)f->data; - if (s->av_context.codec!=NULL){ - avcodec_close(&s->av_context); - s->av_context.codec=NULL; - } -} - -static mblk_t * skip_rfc2190_header(mblk_t *inm){ - if (msgdsize(inm) >= 4) { - uint8_t *ph = inm->b_rptr; - int F = (ph[0]>>7) & 0x1; - int P = (ph[0]>>6) & 0x1; - if (F == 0) inm->b_rptr += 4; // mode A - else if (P == 0) inm->b_rptr += 8; // mode B - else inm->b_rptr += 12; // mode C - } else { - freemsg(inm); - inm=NULL; - } - return inm; -} - -static mblk_t * skip_rfc2429_header(mblk_t *inm){ - if (msgdsize(inm) >= 2){ - uint32_t *p = (uint32_t*)inm->b_rptr; - uint8_t *ph=inm->b_rptr; - int PLEN; - int gob_num; - bool_t P; - - P=rfc2429_get_P(ph); - PLEN=rfc2429_get_PLEN(ph); - /*printf("receiving new packet; P=%i; V=%i; PLEN=%i; PEBIT=%i\n",P,rfc2429_get_V(ph),PLEN,rfc2429_get_PEBIT(ph)); - */ - gob_num = (ntohl(*p) >> 10) & 0x1f; - /*ms_message("gob %i, size %i", gob_num, msgdsize(inm)); - ms_message("ms_AVdecoder_process: received %08x %08x", ntohl(p[0]), ntohl(p[1]));*/ - - /* remove H.263 Payload Header */ - if (PLEN>0){ - /* we ignore the redundant picture header and - directly go to the bitstream */ - inm->b_rptr+=PLEN; - } - if (P){ - inm->b_rptr[0]=inm->b_rptr[1]=0; - }else{ - /* no PSC omitted */ - inm->b_rptr+=2; - } - return inm; - }else freemsg(inm); - return NULL; -} - -static mblk_t * parse_snow_header(DecState *s,mblk_t *inm){ - if (msgdsize(inm) >= 4){ - uint32_t h = ntohl(*(uint32_t*)inm->b_rptr); - if (!s->snow_initialized){ - int error; - s->av_context.width=h>>16; - s->av_context.height=h&0xffff; - error=avcodec_open(&s->av_context, s->av_codec); - if (error!=0) ms_error("avcodec_open() failed for snow: %i",error); - else { - s->snow_initialized=TRUE; - ms_message("Snow decoder initialized,size=%ix%i", - s->av_context.width, - s->av_context.height); - } - } - inm->b_rptr+=4; - return inm; - }else { - freemsg(inm); - return NULL; - } -} - -struct jpeghdr { - //unsigned int tspec:8; /* type-specific field */ - unsigned int off:32; /* fragment byte offset */ - uint8_t type; /* id of jpeg decoder params */ - uint8_t q; /* quantization factor (or table id) */ - uint8_t width; /* frame width in 8 pixel blocks */ - uint8_t height; /* frame height in 8 pixel blocks */ -}; - -struct jpeghdr_rst { - uint16_t dri; - unsigned int f:1; - unsigned int l:1; - unsigned int count:14; -}; - -struct jpeghdr_qtable { - uint8_t mbz; - uint8_t precision; - uint16_t length; -}; - - -static u_char lum_dc_codelens[] = { - 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, -}; - -static u_char lum_dc_symbols[] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -}; - -static u_char lum_ac_codelens[] = { - 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d, -}; - -static u_char lum_ac_symbols[] = { - 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, - 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, - 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, - 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, - 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, - 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, - 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, - 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, - 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, - 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, - 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, - 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, - 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, - 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, - 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, - 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, - 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, - 0xf9, 0xfa, -}; - -static u_char chm_dc_codelens[] = { - 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, -}; - -static u_char chm_dc_symbols[] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -}; - -static u_char chm_ac_codelens[] = { - 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77, -}; - -static u_char chm_ac_symbols[] = { - 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, - 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, - 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, - 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, - 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, - 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, - 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, - 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, - 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, - 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, - 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, - 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, - 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, - 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, - 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, - 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, - 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, - 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, - 0xf9, 0xfa, -}; - -static u_char * -MakeQuantHeader(u_char *p, u_char *qt, int tableNo, int table_len) -{ - *p++ = 0xff; - *p++ = 0xdb; /* DQT */ - *p++ = 0; /* length msb */ - *p++ = table_len+3; /* length lsb */ - *p++ = tableNo; - memcpy(p, qt, table_len); - return (p + table_len); -} - -static u_char * -MakeHuffmanHeader(u_char *p, u_char *codelens, int ncodes, - u_char *symbols, int nsymbols, int tableNo, - int tableClass) -{ - *p++ = 0xff; - *p++ = 0xc4; /* DHT */ - *p++ = 0; /* length msb */ - *p++ = 3 + ncodes + nsymbols; /* length lsb */ - *p++ = (tableClass << 4) | tableNo; - memcpy(p, codelens, ncodes); - p += ncodes; - memcpy(p, symbols, nsymbols); - p += nsymbols; - return (p); -} - -static u_char * -MakeDRIHeader(u_char *p, u_short dri) { - *p++ = 0xff; - *p++ = 0xdd; /* DRI */ - *p++ = 0x0; /* length msb */ - *p++ = 4; /* length lsb */ - *p++ = dri >> 8; /* dri msb */ - *p++ = dri & 0xff; /* dri lsb */ - return (p); -} - -/* - * Arguments: - * type, width, height: as supplied in RTP/JPEG header - * lqt, cqt: quantization tables as either derived from - * the Q field using MakeTables() or as specified - * in section 4.2. - * dri: restart interval in MCUs, or 0 if no restarts. - * - * p: pointer to return area - * - * Return value: - * The length of the generated headers. - * - * Generate a frame and scan headers that can be prepended to the - * RTP/JPEG data payload to produce a JPEG compressed image in - * interchange format (except for possible trailing garbage and - * absence of an EOI marker to terminate the scan). - */ -static int MakeHeaders(u_char *p, int type, int w, int h, u_char *lqt, - u_char *cqt, unsigned table_len, u_short dri) -{ - u_char *start = p; - - /* convert from blocks to pixels */ - w <<= 3; - h <<= 3; - - *p++ = 0xff; - *p++ = 0xd8; /* SOI */ - - if (table_len>64) - { - p = MakeQuantHeader(p, lqt, 0, table_len/2); - p = MakeQuantHeader(p, cqt, 1, table_len/2); - } - else - { - p = MakeQuantHeader(p, lqt, 0, table_len); - //p = MakeQuantHeader(p, lqt, 1, table_len); - } - if (dri != 0) - p = MakeDRIHeader(p, dri); - - *p++ = 0xff; - *p++ = 0xc0; /* SOF */ - *p++ = 0; /* length msb */ - *p++ = 17; /* length lsb */ - *p++ = 8; /* 8-bit precision */ - *p++ = h >> 8; /* height msb */ - *p++ = h; /* height lsb */ - *p++ = w >> 8; /* width msb */ - *p++ = w; /* wudth lsb */ - *p++ = 3; /* number of components */ - *p++ = 0; /* comp 0 */ - if (type == 0) - *p++ = 0x21; /* hsamp = 2, vsamp = 1 */ - else - *p++ = 0x22; /* hsamp = 2, vsamp = 2 */ - *p++ = 0; /* quant table 0 */ - *p++ = 1; /* comp 1 */ - *p++ = 0x11; /* hsamp = 1, vsamp = 1 */ - *p++ = table_len <= 64 ? 0x00 : 0x01; //1 /* quant table 1 */ - *p++ = 2; /* comp 2 */ - *p++ = 0x11; /* hsamp = 1, vsamp = 1 */ - *p++ = table_len <= 64 ? 0x00 : 0x01; //1; /* quant table 1 */ - p = MakeHuffmanHeader(p, lum_dc_codelens, - sizeof(lum_dc_codelens), - lum_dc_symbols, - sizeof(lum_dc_symbols), 0, 0); - p = MakeHuffmanHeader(p, lum_ac_codelens, - sizeof(lum_ac_codelens), - lum_ac_symbols, - sizeof(lum_ac_symbols), 0, 1); - p = MakeHuffmanHeader(p, chm_dc_codelens, - sizeof(chm_dc_codelens), - chm_dc_symbols, - sizeof(chm_dc_symbols), 1, 0); - p = MakeHuffmanHeader(p, chm_ac_codelens, - sizeof(chm_ac_codelens), - chm_ac_symbols, - sizeof(chm_ac_symbols), 1, 1); - - *p++ = 0xff; - *p++ = 0xda; /* SOS */ - *p++ = 0; /* length msb */ - *p++ = 12; /* length lsb */ - *p++ = 3; /* 3 components */ - *p++ = 0; /* comp 0 */ - *p++ = 0; /* huffman table 0 */ - *p++ = 1; /* comp 1 */ - *p++ = 0x11; /* huffman table 1 */ - *p++ = 2; /* comp 2 */ - *p++ = 0x11; /* huffman table 1 */ - *p++ = 0; /* first DCT coeff */ - *p++ = 63; /* last DCT coeff */ - *p++ = 0; /* sucessive approx. */ - - return (p - start); -}; - - -/* - * Table K.1 from JPEG spec. - */ -static const int jpeg_luma_quantizer[64] = { - 16, 11, 10, 16, 24, 40, 51, 61, - 12, 12, 14, 19, 26, 58, 60, 55, - 14, 13, 16, 24, 40, 57, 69, 56, - 14, 17, 22, 29, 51, 87, 80, 62, - 18, 22, 37, 56, 68, 109, 103, 77, - 24, 35, 55, 64, 81, 104, 113, 92, - 49, 64, 78, 87, 103, 121, 120, 101, - 72, 92, 95, 98, 112, 100, 103, 99 -}; - -/* - * Table K.2 from JPEG spec. - */ -static const int jpeg_chroma_quantizer[64] = { - 17, 18, 24, 47, 99, 99, 99, 99, - 18, 21, 26, 66, 99, 99, 99, 99, - 24, 26, 56, 99, 99, 99, 99, 99, - 47, 66, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99 -}; - -/* - * Call MakeTables with the Q factor and two u_char[64] return arrays - */ -static void MakeTables(int q, u_char *lqt, u_char *cqt) -{ - int i; - int factor = q; - - if (q < 1) factor = 1; - if (q > 99) factor = 99; - if (q < 50) - q = 5000 / factor; - else - q = 200 - factor*2; - - for (i=0; i < 64; i++) { - int lq = (jpeg_luma_quantizer[i] * q + 50) / 100; - int cq = (jpeg_chroma_quantizer[i] * q + 50) / 100; - - /* Limit the quantizers to 1 <= q <= 255 */ - if (lq < 1) lq = 1; - else if (lq > 255) lq = 255; - lqt[i] = lq; - - if (cq < 1) cq = 1; - else if (cq > 255) cq = 255; - cqt[i] = cq; - } -} - -static mblk_t * -read_rfc2435_header(DecState *s,mblk_t *inm) -{ - if (msgdsize(inm) >= sizeof(struct jpeghdr)) { - struct jpeghdr *hdr = (struct jpeghdr *)inm->b_rptr; - uint32_t off = ntohl(*(uint32_t*)inm->b_rptr); - uint16_t dri=0; - uint16_t table_len=0; - int len=0; - - mblk_t *headers=NULL; - - inm->b_rptr += sizeof(struct jpeghdr); - if (hdr->type>63){ - struct jpeghdr_rst *rsthdr = (struct jpeghdr_rst *)inm->b_rptr; - dri = ntohs(rsthdr->dri); - inm->b_rptr += sizeof(struct jpeghdr_rst); - } - - if (off==0){ - if (hdr->q>=128){ - inm->b_rptr++; /* MBZ */ - inm->b_rptr++; /* Precision */ - table_len = ntohs(*((uint16_t*)(inm->b_rptr))); - inm->b_rptr++; /* len */ - inm->b_rptr++; /* len */ - headers = allocb(495 + table_len*2 + (dri > 0 ? 6 : 0), 0); - len = MakeHeaders(headers->b_rptr, hdr->type, hdr->width, hdr->height, - inm->b_rptr, inm->b_rptr+table_len/2, table_len, dri); - inm->b_rptr += table_len; - headers->b_wptr += len; - }else{ - uint8_t lqt_cqt[128]; - MakeTables(hdr->q, lqt_cqt, lqt_cqt+64); - table_len=128; - headers = allocb(495 + table_len + (dri > 0 ? 6 : 0), 0); - len = MakeHeaders(headers->b_rptr, hdr->type, hdr->width, hdr->height, - lqt_cqt, lqt_cqt+64, table_len, dri); - headers->b_wptr += len; - } - } - - if (headers!=NULL) - { - /* prepend headers to JPEG RTP data */ - if (mblk_get_marker_info(inm)) - mblk_set_marker_info(headers, TRUE); - headers->b_cont=inm; - msgpullup(headers, -1); - return headers; - } - } else { - freemsg(inm); - inm=NULL; - } - return inm; -} - -static mblk_t *get_as_yuvmsg(MSFilter *f, DecState *s, AVFrame *orig){ - AVCodecContext *ctx=&s->av_context; - - if (s->outbuf.w!=ctx->width || s->outbuf.h!=ctx->height){ - if (s->sws_ctx!=NULL){ - sws_freeContext(s->sws_ctx); - s->sws_ctx=NULL; - } - s->yuv_msg=yuv_buf_alloc(&s->outbuf,ctx->width,ctx->height); - s->outbuf.w=ctx->width; - s->outbuf.h=ctx->height; - s->sws_ctx=sws_getContext(ctx->width,ctx->height,ctx->pix_fmt, - ctx->width,ctx->height,s->output_pix_fmt,SWS_FAST_BILINEAR, - NULL, NULL, NULL); - } - if (sws_scale(s->sws_ctx,orig->data,orig->linesize, 0, - ctx->height, s->outbuf.planes, s->outbuf.strides)<0){ - ms_error("%s: error in sws_scale().",f->desc->name); - } - return dupmsg(s->yuv_msg); -} - -static void dec_process_frame(MSFilter *f, mblk_t *inm){ - DecState *s=(DecState*)f->data; - AVFrame orig; - int got_picture; - /* get a picture from the input queue */ - - if (f->desc->id==MS_H263_DEC_ID) inm=skip_rfc2429_header(inm); - else if (f->desc->id==MS_H263_OLD_DEC_ID) inm=skip_rfc2190_header(inm); - else if (s->codec==CODEC_ID_SNOW && s->input==NULL) inm=parse_snow_header(s,inm); - else if (s->codec==CODEC_ID_MJPEG && f->desc->id==MS_JPEG_DEC_ID) inm=read_rfc2435_header(s,inm); - if (inm){ - /* accumulate the video packet until we have the rtp markbit*/ - if (s->input==NULL){ - s->input=inm; - }else{ - concatb(s->input,inm); - } - - if (mblk_get_marker_info(inm)){ - mblk_t *frame; - int remain,len; - /*ms_message("got marker bit !");*/ - /*append some padding bytes for ffmpeg to safely - read extra bytes...*/ - msgpullup(s->input,msgdsize(s->input)+8); - frame=s->input; - s->input=NULL; - while ( (remain=frame->b_wptr-frame->b_rptr)> 0) { - AVPacket pkt; - av_init_packet(&pkt); - pkt.data = frame->b_rptr; - pkt.size = remain; - len=avcodec_decode_video2(&s->av_context,&orig,&got_picture,&pkt); - /*len=avcodec_decode_video(&s->av_context,&orig,&got_picture,(uint8_t*)frame->b_rptr,remain );*/ - if (len<=0) { - ms_warning("ms_AVdecoder_process: error %i.",len); - break; - } - if (got_picture) { - ms_queue_put(f->outputs[0],get_as_yuvmsg(f,s,&orig)); - } - frame->b_rptr+=len; - } - freemsg(frame); - } - } -} - -static void dec_process(MSFilter *f){ - mblk_t *inm; - while((inm=ms_queue_get(f->inputs[0]))!=0){ - dec_process_frame(f,inm); - } -} - - -static MSFilterMethod methods[]={ - { MS_FILTER_ADD_FMTP , dec_add_fmtp }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_h263_dec_desc={ - MS_H263_DEC_ID, - "MSH263Dec", - N_("A H.263 decoder using ffmpeg library"), - MS_FILTER_DECODER, - "H263-1998", - 1, - 1, - dec_h263_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - -MSFilterDesc ms_h263_old_dec_desc={ - MS_H263_OLD_DEC_ID, - "MSH263OldDec", - N_("A H.263 decoder using ffmpeg library"), - MS_FILTER_DECODER, - "H263", - 1, - 1, - dec_h263_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - - -MSFilterDesc ms_mpeg4_dec_desc={ - MS_MPEG4_DEC_ID, - "MSMpeg4Dec", - N_("A MPEG4 decoder using ffmpeg library"), - MS_FILTER_DECODER, - "MP4V-ES", - 1, - 1, - dec_mpeg4_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - -MSFilterDesc ms_jpeg_dec_desc={ - MS_JPEG_DEC_ID, - "MSJpegDec", - N_("A RTP/JPEG decoder using ffmpeg library"), - MS_FILTER_DECODER, - "JPEG", - 1, - 1, - dec_mjpeg_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - -MSFilterDesc ms_mjpeg_dec_desc={ - MS_MJPEG_DEC_ID, - "MSMJpegDec", - N_("A MJPEG decoder using ffmpeg library"), - MS_FILTER_DECODER, - "MJPEG", - 1, - 1, - dec_mjpeg_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - -MSFilterDesc ms_snow_dec_desc={ - MS_SNOW_DEC_ID, - "MSSnowDec", - N_("A snow decoder using ffmpeg library"), - MS_FILTER_DECODER, - "snow", - 1, - 1, - dec_snow_init, - dec_preprocess, - dec_process, - dec_postprocess, - dec_uninit, - methods -}; - -#else - -MSFilterDesc ms_h263_dec_desc={ - .id=MS_H263_DEC_ID, - .name="MSH263Dec", - .text=N_("A H.263 decoder using ffmpeg library"), - .category=MS_FILTER_DECODER, - .enc_fmt="H263-1998", - .ninputs=1, - .noutputs=1, - .init=dec_h263_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - -MSFilterDesc ms_h263_old_dec_desc={ - .id=MS_H263_OLD_DEC_ID, - .name="MSH263OldDec", - .text=N_("A H.263 decoder using ffmpeg library"), - .category=MS_FILTER_DECODER, - .enc_fmt="H263", - .ninputs=1, - .noutputs=1, - .init=dec_h263_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - - -MSFilterDesc ms_mpeg4_dec_desc={ - .id=MS_MPEG4_DEC_ID, - .name="MSMpeg4Dec", - .text="A MPEG4 decoder using ffmpeg library", - .category=MS_FILTER_DECODER, - .enc_fmt="MP4V-ES", - .ninputs=1, - .noutputs=1, - .init=dec_mpeg4_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - -MSFilterDesc ms_jpeg_dec_desc={ - .id=MS_JPEG_DEC_ID, - .name="MSJpegDec", - .text="A RTP/MJEPG decoder using ffmpeg library", - .category=MS_FILTER_DECODER, - .enc_fmt="JPEG", - .ninputs=1, - .noutputs=1, - .init=dec_mjpeg_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - -MSFilterDesc ms_mjpeg_dec_desc={ - .id=MS_MJPEG_DEC_ID, - .name="MSMJpegDec", - .text="A MJEPG decoder using ffmpeg library", - .category=MS_FILTER_DECODER, - .enc_fmt="MJPEG", - .ninputs=1, - .noutputs=1, - .init=dec_mjpeg_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - -MSFilterDesc ms_snow_dec_desc={ - .id=MS_SNOW_DEC_ID, - .name="MSSnowDec", - .text="A snow decoder using ffmpeg library", - .category=MS_FILTER_DECODER, - .enc_fmt="x-snow", - .ninputs=1, - .noutputs=1, - .init=dec_snow_init, - .preprocess=dec_preprocess, - .process=dec_process, - .postprocess=dec_postprocess, - .uninit=dec_uninit, - .methods= methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_mpeg4_dec_desc) -MS_FILTER_DESC_EXPORT(ms_h263_dec_desc) -MS_FILTER_DESC_EXPORT(ms_h263_old_dec_desc) -MS_FILTER_DESC_EXPORT(ms_snow_dec_desc) - -/* decode JPEG image with RTP/jpeg headers */ -MS_FILTER_DESC_EXPORT(ms_jpeg_dec_desc) -/* decode JPEG image with jpeg headers */ -MS_FILTER_DESC_EXPORT(ms_mjpeg_dec_desc) diff --git a/linphone/mediastreamer2/src/videoenc.c b/linphone/mediastreamer2/src/videoenc.c deleted file mode 100644 index 3cbf5f69a..000000000 --- a/linphone/mediastreamer2/src/videoenc.c +++ /dev/null @@ -1,1041 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#ifdef HAVE_LIBAVCODEC_AVCODEC_H -#include -#else -#include -#endif - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" - -#ifdef _WIN32 -#include -#else -#include /* ntohl(3) */ -#endif - -#include "rfc2429.h" - -static bool_t avcodec_initialized=FALSE; - -#ifdef ENABLE_LOG_FFMPEG - -void ms_ffmpeg_log_callback(void* ptr, int level, const char* fmt, va_list vl) -{ - static char message[8192]; - - vsnprintf(message, sizeof message, fmt, vl); - ms_message(message); -} - -#endif - -void ms_ffmpeg_check_init(){ - if(!avcodec_initialized){ - avcodec_init(); - avcodec_register_all(); - avcodec_initialized=TRUE; -#ifdef ENABLE_LOG_FFMPEG - av_log_set_level(AV_LOG_WARNING); - av_log_set_callback(&ms_ffmpeg_log_callback); -#endif - } -} - -typedef struct EncState{ - AVCodecContext av_context; - AVCodec *av_codec; - enum CodecID codec; - mblk_t *comp_buf; - MSVideoSize vsize; - int mtu; /* network maximum transmission unit in bytes */ - int profile; - float fps; - int maxbr; - int qmin; - uint32_t framenum; - bool_t req_vfu; -}EncState; - -static int enc_set_fps(MSFilter *f, void *arg){ - EncState *s=(EncState*)f->data; - s->fps=*(float*)arg; - return 0; -} - -static int enc_get_fps(MSFilter *f, void *arg){ - EncState *s=(EncState*)f->data; - *(float*)arg=s->fps; - return 0; -} - -static int enc_set_vsize(MSFilter *f,void *arg){ - EncState *s=(EncState*)f->data; - s->vsize=*(MSVideoSize*)arg; - return 0; -} - -static int enc_get_vsize(MSFilter *f,void *arg){ - EncState *s=(EncState*)f->data; - *(MSVideoSize*)arg=s->vsize; - return 0; -} - -static int enc_set_mtu(MSFilter *f,void *arg){ - EncState *s=(EncState*)f->data; - s->mtu=*(int*)arg; - return 0; -} - -static bool_t parse_video_fmtp(const char *fmtp, float *fps, MSVideoSize *vsize){ - char *tmp=ms_strdup(fmtp); - char *semicolon; - char *equal; - bool_t ret=TRUE; - - ms_message("parsing %s",fmtp); - /*extract fisrt pair */ - if ((semicolon=strchr(tmp,';'))!=NULL){ - *semicolon='\0'; - } - if ((equal=strchr(tmp,'='))!=NULL){ - int divider; - *equal='\0'; - if (strcasecmp(tmp,"CIF")==0){ - if (vsize->width>=MS_VIDEO_SIZE_CIF_W){ - vsize->width=MS_VIDEO_SIZE_CIF_W; - vsize->height=MS_VIDEO_SIZE_CIF_H; - } - }else if (strcasecmp(tmp,"QCIF")==0){ - vsize->width=MS_VIDEO_SIZE_QCIF_W; - vsize->height=MS_VIDEO_SIZE_QCIF_H; - }else{ - ms_warning("unsupported video size %s",tmp); - ret=FALSE; - } - divider=atoi(equal+1); - if (divider!=0){ - float newfps=29.97/divider; - if (*fps>newfps) *fps=newfps; - }else{ - ms_warning("Could not find video fps"); - ret=FALSE; - } - }else ret=FALSE; - ms_free(tmp); - return ret; -} - -static int enc_add_fmtp(MSFilter *f,void *arg){ - EncState *s=(EncState*)f->data; - const char *fmtp=(const char*)arg; - char val[10]; - if (fmtp_get_value(fmtp,"profile",val,sizeof(val))){ - s->profile=atoi(val); - }else parse_video_fmtp(fmtp,&s->fps,&s->vsize); - return 0; -} - -static int enc_req_vfu(MSFilter *f, void *unused){ - EncState *s=(EncState*)f->data; - s->req_vfu=TRUE; - return 0; -} - -static void enc_init(MSFilter *f, enum CodecID codec) -{ - EncState *s=(EncState *)ms_new(EncState,1); - f->data=s; - ms_ffmpeg_check_init(); - s->profile=0;/*always default to profile 0*/ - s->comp_buf=NULL; - s->fps=15; - s->mtu=ms_get_payload_max_size()-2;/*-2 for the H263 payload header*/ - s->maxbr=500000; - s->codec=codec; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->qmin=2; - s->req_vfu=FALSE; - s->framenum=0; - s->av_context.codec=NULL; -} - -static void enc_h263_init(MSFilter *f){ - enc_init(f,CODEC_ID_H263P); -} - -static void enc_mpeg4_init(MSFilter *f){ - enc_init(f,CODEC_ID_MPEG4); -} - -static void enc_snow_init(MSFilter *f){ - enc_init(f,CODEC_ID_SNOW); -} - -static void enc_mjpeg_init(MSFilter *f){ - enc_init(f,CODEC_ID_MJPEG); -} - -static void prepare(EncState *s){ - AVCodecContext *c=&s->av_context; - avcodec_get_context_defaults(c); - if (s->codec==CODEC_ID_MJPEG) - { - ms_message("Codec bitrate set to %i",c->bit_rate); - c->width = s->vsize.width; - c->height = s->vsize.height; - c->time_base.num = 1; - c->time_base.den = (int)s->fps; - c->gop_size=(int)s->fps*5; /*emit I frame every 5 seconds*/ - c->pix_fmt=PIX_FMT_YUVJ420P; - s->comp_buf=allocb(c->bit_rate*2,0); - return; - } - - /* put codec parameters */ - c->bit_rate=(float)s->maxbr*0.7; - c->bit_rate_tolerance=s->fps!=1?(float)c->bit_rate/(s->fps-1):c->bit_rate; - - if (s->codec!=CODEC_ID_SNOW && s->maxbr<256000){ - /*snow does not like 1st pass rate control*/ - /*and rate control eats too much cpu with CIF high fps pictures*/ - c->rc_max_rate=(float)s->maxbr*0.8; - c->rc_min_rate=0; - c->rc_buffer_size=c->rc_max_rate; - }else{ - /*use qmin instead*/ - c->qmin=s->qmin; - } - - ms_message("Codec bitrate set to %i",c->bit_rate); - c->width = s->vsize.width; - c->height = s->vsize.height; - c->time_base.num = 1; - c->time_base.den = (int)s->fps; - c->gop_size=(int)s->fps*5; /*emit I frame every 5 seconds*/ - c->pix_fmt=PIX_FMT_YUV420P; - s->comp_buf=allocb(c->bit_rate*2,0); - if (s->codec==CODEC_ID_SNOW){ - c->strict_std_compliance=-2; - } - -} - -static void prepare_h263(EncState *s){ - AVCodecContext *c=&s->av_context; - /* we don't use the rtp_callback but use rtp_mode that forces ffmpeg to insert - Start Codes as much as possible in the bitstream */ -#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0) - c->rtp_mode = 1; -#endif - c->rtp_payload_size = s->mtu/2; - if (s->profile==0){ - s->codec=CODEC_ID_H263; - }else{ - c->flags|=CODEC_FLAG_H263P_UMV; - c->flags|=CODEC_FLAG_AC_PRED; - c->flags|=CODEC_FLAG_H263P_SLICE_STRUCT; - /* - c->flags|=CODEC_FLAG_OBMC; - c->flags|=CODEC_FLAG_AC_PRED; - */ - s->codec=CODEC_ID_H263P; - } -} - -static void prepare_mpeg4(EncState *s){ - AVCodecContext *c=&s->av_context; - c->max_b_frames=0; /*don't use b frames*/ - c->flags|=CODEC_FLAG_AC_PRED; - c->flags|=CODEC_FLAG_H263P_UMV; - /*c->flags|=CODEC_FLAG_QPEL;*/ /*don't enable this one: this forces profile_level to advanced simple profile */ - c->flags|=CODEC_FLAG_4MV; - c->flags|=CODEC_FLAG_GMC; - c->flags|=CODEC_FLAG_LOOP_FILTER; - c->flags|=CODEC_FLAG_H263P_SLICE_STRUCT; -} - -static void enc_uninit(MSFilter *f){ - EncState *s=(EncState*)f->data; - ms_free(s); -} -#if 0 -static void enc_set_rc(EncState *s, AVCodecContext *c){ - int factor=c->width/MS_VIDEO_SIZE_QCIF_W; - c->rc_min_rate=0; - c->bit_rate=400; /* this value makes around 100kbit/s at QCIF=2 */ - c->rc_max_rate=c->bit_rate+1; - c->rc_buffer_size=20000*factor; /* food recipe */ -} -#endif - -static void enc_preprocess(MSFilter *f){ - EncState *s=(EncState*)f->data; - int error; - prepare(s); - if (s->codec==CODEC_ID_H263P || s->codec==CODEC_ID_H263) - prepare_h263(s); - else if (s->codec==CODEC_ID_MPEG4) - prepare_mpeg4(s); - else if (s->codec==CODEC_ID_SNOW){ - /**/ - }else if (s->codec==CODEC_ID_MJPEG){ - /**/ - }else { - ms_error("Unsupported codec id %i",s->codec); - return; - } - s->av_codec=avcodec_find_encoder(s->codec); - if (s->av_codec==NULL){ - ms_error("could not find encoder for codec id %i",s->codec); - return; - } - error=avcodec_open(&s->av_context, s->av_codec); - if (error!=0) { - ms_error("avcodec_open() failed: %i",error); - return; - } - ms_debug("image format is %i.",s->av_context.pix_fmt); - ms_message("qmin=%i qmax=%i",s->av_context.qmin,s->av_context.qmax); -} - -static void enc_postprocess(MSFilter *f){ - EncState *s=(EncState*)f->data; - if (s->av_context.codec!=NULL){ - avcodec_close(&s->av_context); - s->av_context.codec=NULL; - } - if (s->comp_buf!=NULL) { - freemsg(s->comp_buf); - s->comp_buf=NULL; - } -} - -static void add_rfc2190_header(mblk_t **packet, AVCodecContext *context){ - mblk_t *header; - header = allocb(4, 0); - memset(header->b_wptr, 0, 4); - // assume video size is CIF or QCIF - if (context->width == 352 && context->height == 288) header->b_wptr[1] = 0x60; - else header->b_wptr[1] = 0x40; - if (context->coded_frame->pict_type != FF_I_TYPE) header->b_wptr[1] |= 0x10; - header->b_wptr += 4; - header->b_cont = *packet; - *packet = header; -} - -#if 0 -static int get_gbsc(uint8_t *psc, uint8_t *end) -{ - int len = end-psc; - uint32_t buf; - int i, j, k; - k = len; - for (i = 2; i < len-4; i++) { - buf = *((uint32_t *)(psc+i)); - for (j = 0; j < 8; j++) { - if (((buf >> j) & 0x00FCFFFF) == 0x00800000) {/*PSC*/ - i += 2; - k=i; - break; - } else if (((buf >> j) & 0x0080FFFF) == 0x00800000) {/*GBSC*/ - i += 2; - k = i; - break; - } - } - } - return k; -} -#else -static int get_gbsc_bytealigned(uint8_t *begin, uint8_t *end){ - int i; - int len = end - begin; - for (i = len - 2; /*len + length of scan window*/ - i > 2 + 2; /*length of scan window + 2 avoidance of 1st gob or psc*/ - i--){ - if(*(begin + i) == 0 && - *(begin + i+1) == 0 && - (*(begin + i+2) & 0x80) == 0x80){ - /*ms_message("JV psc/gob found! %2x %2x %2x", *(begin + i), *(begin + i+1), *(begin + i + 2));*/ - return i; - } - } - /*ms_message("JV no psc or gob found!");*/ - return len; -} -#endif - -static void rfc2190_generate_packets(MSFilter *f, EncState *s, mblk_t *frame, uint32_t timestamp){ - mblk_t *packet=NULL; - - while (frame->b_rptrb_wptr){ - packet=dupb(frame); - /*frame->b_rptr=packet->b_wptr=packet->b_rptr+get_gbsc(packet->b_rptr, MIN(packet->b_rptr+s->mtu,frame->b_wptr));*/ - frame->b_rptr = packet->b_wptr = - packet->b_rptr + get_gbsc_bytealigned(packet->b_rptr, MIN(packet->b_rptr+s->mtu,frame->b_wptr)); - add_rfc2190_header(&packet, &s->av_context); - mblk_set_timestamp_info(packet,timestamp); - ms_queue_put(f->outputs[0],packet); - } - /* the marker bit is set on the last packet, if any.*/ - mblk_set_marker_info(packet,TRUE); -} - -static void mpeg4_fragment_and_send(MSFilter *f,EncState *s,mblk_t *frame, uint32_t timestamp){ - uint8_t *rptr; - mblk_t *packet=NULL; - int len; - for (rptr=frame->b_rptr;rptrb_wptr;){ - len=MIN(s->mtu,(frame->b_wptr-rptr)); - packet=dupb(frame); - packet->b_rptr=rptr; - packet->b_wptr=rptr+len; - mblk_set_timestamp_info(packet,timestamp); - ms_queue_put(f->outputs[0],packet); - rptr+=len; - } - /*set marker bit on last packet*/ - mblk_set_marker_info(packet,TRUE); -} - -static void rfc4629_generate_follow_on_packets(MSFilter *f, EncState *s, mblk_t *frame, uint32_t timestamp, uint8_t *psc, uint8_t *end, bool_t last_packet){ - mblk_t *packet; - int len=end-psc; - - packet=dupb(frame); - packet->b_rptr=psc; - packet->b_wptr=end; - /*ms_message("generating packet of size %i",end-psc);*/ - rfc2429_set_P(psc,1); - mblk_set_timestamp_info(packet,timestamp); - - - if (len>s->mtu){ - /*need to slit the packet using "follow-on" packets */ - /*compute the number of packets need (rounded up)*/ - int num=(len+s->mtu-1)/s->mtu; - int i; - uint8_t *pos; - /*adjust the first packet generated*/ - pos=packet->b_wptr=packet->b_rptr+s->mtu; - ms_queue_put(f->outputs[0],packet); - ms_debug("generating %i follow-on packets",num); - for (i=1;ib_rptr=pos; - pos=packet->b_wptr=MIN(pos+s->mtu,end); - header=allocb(2,0); - header->b_wptr[0]=0; - header->b_wptr[1]=0; - header->b_wptr+=2; - /*no P bit is set */ - header->b_cont=packet; - packet=header; - mblk_set_timestamp_info(packet,timestamp); - ms_queue_put(f->outputs[0],packet); - } - }else ms_queue_put(f->outputs[0],packet); - /* the marker bit is set on the last packet, if any.*/ - mblk_set_marker_info(packet,last_packet); -} - -/* returns the last psc position just below packet_size */ -static uint8_t *get_psc(uint8_t *begin,uint8_t *end, int packet_size){ - int i; - uint8_t *ret=NULL; - uint8_t *p; - if (begin==end) return NULL; - for(i=1,p=begin+1;p= 128, or undefined otherwise. - * lqt: The quantization table for the luminance channel if q >= 128 - * cqt: The quantization table for the chrominance channels if - * q >= 128 - * - * Return value: - * the sequence number to be sent for the first packet of the next - * frame. - * - * The following are assumed to be defined: - * - * PACKET_SIZE - The size of the outgoing packet - * send_packet(u_int8 *data, int len) - Sends the packet to the network - */ - -static void mjpeg_fragment_and_send(MSFilter *f,EncState *s,mblk_t *frame, uint32_t timestamp, - uint8_t type, uint8_t typespec, int dri, - uint8_t q, mblk_t *lqt, mblk_t *cqt) { - struct jpeghdr jpghdr; - struct jpeghdr_rst rsthdr; - struct jpeghdr_qtable qtblhdr; - int bytes_left = msgdsize(frame); - int data_len; - - mblk_t *packet; - - /* Initialize JPEG header - */ - //jpghdr.tspec = typespec; - jpghdr.off = 0; - jpghdr.type = type | ((dri != 0) ? RTP_JPEG_RESTART : 0); - jpghdr.q = q; - jpghdr.width = s->vsize.width / 8; - jpghdr.height = s->vsize.height / 8; - - /* Initialize DRI header - */ - if (dri != 0) { - rsthdr.dri = htons(dri); - rsthdr.f = 1; /* This code does not align RIs */ - rsthdr.l = 1; - rsthdr.count = 0x3fff; - } - - /* Initialize quantization table header - */ - if (q >= 128) { - qtblhdr.mbz = 0; - qtblhdr.precision = 0; /* This code uses 8 bit tables only */ - qtblhdr.length = htons(msgdsize(lqt)+msgdsize(cqt)); /* 2 64-byte tables */ - } - - while (bytes_left > 0) { - packet = allocb(s->mtu, 0); - - jpghdr.off = htonl(jpghdr.off); - memcpy(packet->b_wptr, &jpghdr, sizeof(jpghdr)); - jpghdr.off = ntohl(jpghdr.off); - packet->b_wptr += sizeof(jpghdr); - - if (dri != 0) { - memcpy(packet->b_wptr, &rsthdr, sizeof(rsthdr)); - packet->b_wptr += sizeof(rsthdr); - } - - if (q >= 128 && jpghdr.off == 0) { - memcpy(packet->b_wptr, &qtblhdr, sizeof(qtblhdr)); - packet->b_wptr += sizeof(qtblhdr); - if (msgdsize(lqt)){ - memcpy(packet->b_wptr, lqt->b_rptr, msgdsize(lqt)); - packet->b_wptr += msgdsize(lqt); - } - if (msgdsize(cqt)){ - memcpy(packet->b_wptr, cqt->b_rptr, msgdsize(cqt)); - packet->b_wptr += msgdsize(cqt); - } - } - - data_len = s->mtu - (packet->b_wptr - packet->b_rptr); - if (data_len >= bytes_left) { - data_len = bytes_left; - mblk_set_marker_info(packet,TRUE); - } - - memcpy(packet->b_wptr, frame->b_rptr + jpghdr.off, data_len); - packet->b_wptr=packet->b_wptr + data_len; - - mblk_set_timestamp_info(packet,timestamp); - ms_queue_put(f->outputs[0],packet); - - jpghdr.off += data_len; - bytes_left -= data_len; - } -} - -static int find_marker(uint8_t **pbuf_ptr, uint8_t *buf_end){ - - uint8_t *buf_ptr; - unsigned int v, v2; - int val; - - buf_ptr = *pbuf_ptr; - while (buf_ptr < buf_end) { - v = *buf_ptr++; - v2 = *buf_ptr; - if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) { - val = *buf_ptr++; - *pbuf_ptr = buf_ptr; - return val; - } - } - val = -1; - return val; -} - -static mblk_t *skip_jpeg_headers(mblk_t *full_frame, mblk_t **lqt, mblk_t **cqt){ - int err; - uint8_t *pbuf_ptr=full_frame->b_rptr; - uint8_t *buf_end=full_frame->b_wptr; - - ms_message("image size: %i)", buf_end-pbuf_ptr); - - *lqt=NULL; - *cqt=NULL; - - err = find_marker(&pbuf_ptr, buf_end); - while (err!=-1) - { - ms_message("marker found: %x (offset from beginning%i)", err, pbuf_ptr-full_frame->b_rptr); - if (err==0xdb) - { - /* copy DQT table */ - int len = ntohs(*(uint16_t*)(pbuf_ptr)); - if (*lqt==NULL) - { - mblk_t *_lqt = allocb(len-3, 0); - memcpy(_lqt->b_rptr, pbuf_ptr+3, len-3); - _lqt->b_wptr += len-3; - *lqt = _lqt; - //*cqt = dupb(*lqt); - } - else - { - mblk_t *_cqt = allocb(len-3, 0); - memcpy(_cqt->b_rptr, pbuf_ptr+3, len-3); - _cqt->b_wptr += len-3; - *cqt = _cqt; - } - } - if (err==0xda) - { - uint16_t *bistream=(uint16_t *)pbuf_ptr; - uint16_t len = ntohs(*bistream); - full_frame->b_rptr = pbuf_ptr+len; - } - err = find_marker(&pbuf_ptr, buf_end); - } - return full_frame; -} - -static void split_and_send(MSFilter *f, EncState *s, mblk_t *frame){ - uint8_t *lastpsc; - uint8_t *psc; - uint32_t timestamp=f->ticker->time*90LL; - - if (s->codec==CODEC_ID_MPEG4 || s->codec==CODEC_ID_SNOW) - { - mpeg4_fragment_and_send(f,s,frame,timestamp); - return; - } - else if (s->codec==CODEC_ID_MJPEG) - { - mblk_t *lqt=NULL; - mblk_t *cqt=NULL; - skip_jpeg_headers(frame, &lqt, &cqt); - mjpeg_fragment_and_send(f,s,frame,timestamp, - 1, /* 420? */ - 0, - 0, /* dri ?*/ - 255, /* q */ - lqt, - cqt); - return; - } - - ms_debug("processing frame of size %i",frame->b_wptr-frame->b_rptr); - if (f->desc->id==MS_H263_ENC_ID){ - lastpsc=frame->b_rptr; - while(1){ - psc=get_psc(lastpsc+2,frame->b_wptr,s->mtu); - if (psc!=NULL){ - rfc4629_generate_follow_on_packets(f,s,frame,timestamp,lastpsc,psc,FALSE); - lastpsc=psc; - }else break; - } - /* send the end of frame */ - rfc4629_generate_follow_on_packets(f,s,frame, timestamp,lastpsc,frame->b_wptr,TRUE); - }else if (f->desc->id==MS_H263_OLD_ENC_ID){ - rfc2190_generate_packets(f,s,frame,timestamp); - }else{ - ms_fatal("Ca va tres mal."); - } -} - -static void process_frame(MSFilter *f, mblk_t *inm){ - EncState *s=(EncState*)f->data; - AVFrame pict; - AVCodecContext *c=&s->av_context; - int error; - mblk_t *comp_buf=s->comp_buf; - int comp_buf_sz=comp_buf->b_datap->db_lim-comp_buf->b_datap->db_base; - - /* convert image if necessary */ - avcodec_get_frame_defaults(&pict); - avpicture_fill((AVPicture*)&pict,(uint8_t*)inm->b_rptr,c->pix_fmt,c->width,c->height); - - /* timestamp used by ffmpeg, unset here */ - pict.pts=AV_NOPTS_VALUE; - - if (s->framenum==(int)(s->fps*2.0) || s->framenum==(int)(s->fps*4.0)){ - /*sends an I frame at 2 seconds and 4 seconds after the beginning of the call*/ - s->req_vfu=TRUE; - } - if (s->req_vfu){ - pict.pict_type=FF_I_TYPE; - s->req_vfu=FALSE; - } - comp_buf->b_rptr=comp_buf->b_wptr=comp_buf->b_datap->db_base; - if (s->codec==CODEC_ID_SNOW){ - //prepend picture size - uint32_t header=((s->vsize.width&0xffff)<<16) | (s->vsize.height&0xffff); - *(uint32_t*)comp_buf->b_wptr=htonl(header); - comp_buf->b_wptr+=4; - comp_buf_sz-=4; - } - error=avcodec_encode_video(c, (uint8_t*)comp_buf->b_wptr,comp_buf_sz, &pict); - if (error<=0) ms_warning("ms_AVencoder_process: error %i.",error); - else{ - s->framenum++; - if (c->coded_frame->pict_type==FF_I_TYPE){ - ms_message("Emitting I-frame"); - } - comp_buf->b_wptr+=error; - split_and_send(f,s,comp_buf); - } - freemsg(inm); -} - -static void enc_process(MSFilter *f){ - mblk_t *inm; - EncState *s=(EncState*)f->data; - if (s->av_context.codec==NULL) { - ms_queue_flush(f->inputs[0]); - return; - } - ms_filter_lock(f); - while((inm=ms_queue_get(f->inputs[0]))!=0){ - process_frame(f,inm); - } - ms_filter_unlock(f); -} - - -static int enc_get_br(MSFilter *f, void *arg){ - EncState *s=(EncState*)f->data; - *(int*)arg=s->maxbr; - return 0; -} - -static int enc_set_br(MSFilter *f, void *arg){ - EncState *s=(EncState*)f->data; - bool_t snow=s->codec==CODEC_ID_SNOW; - s->maxbr=*(int*)arg; - if (s->maxbr>=1024000 && s->codec!=CODEC_ID_H263P){ - s->vsize.width = MS_VIDEO_SIZE_SVGA_W; - s->vsize.height = MS_VIDEO_SIZE_SVGA_H; - s->fps=17; - }else if (s->maxbr>=800000 && s->codec!=CODEC_ID_H263P){ - s->vsize.width = MS_VIDEO_SIZE_VGA_W; - s->vsize.height = MS_VIDEO_SIZE_VGA_H; - s->fps=17; - }else if (s->maxbr>=512000){ - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->fps=17; - }else if (s->maxbr>=256000){ - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->fps=10; - s->qmin=3; - }else if (s->maxbr>=128000){ - s->vsize.width=MS_VIDEO_SIZE_QCIF_W; - s->vsize.height=MS_VIDEO_SIZE_QCIF_H; - s->fps=10; - s->qmin=3; - }else if (s->maxbr>=64000){ - s->vsize.width=MS_VIDEO_SIZE_QCIF_W; - s->vsize.height=MS_VIDEO_SIZE_QCIF_H; - s->fps=snow ? 7 : 5; - s->qmin=snow ? 4 : 5; - }else{ - s->vsize.width=MS_VIDEO_SIZE_QCIF_W; - s->vsize.height=MS_VIDEO_SIZE_QCIF_H; - s->fps=5; - s->qmin=5; - } - if (s->av_context.codec!=NULL){ - /*apply new settings dynamically*/ - ms_filter_lock(f); - enc_postprocess(f); - enc_preprocess(f); - ms_filter_unlock(f); - } - return 0; -} - - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , enc_set_fps }, - { MS_FILTER_GET_FPS , enc_get_fps }, - { MS_FILTER_SET_VIDEO_SIZE , enc_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE , enc_get_vsize }, - { MS_FILTER_ADD_FMTP , enc_add_fmtp }, - { MS_FILTER_SET_BITRATE , enc_set_br }, - { MS_FILTER_GET_BITRATE , enc_get_br }, - { MS_FILTER_SET_MTU , enc_set_mtu }, - { MS_FILTER_REQ_VFU , enc_req_vfu }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_h263_enc_desc={ - MS_H263_ENC_ID, - "MSH263Enc", - N_("A video H.263 encoder using ffmpeg library."), - MS_FILTER_ENCODER, - "H263-1998", - 1, /*MS_YUV420P is assumed on this input */ - 1, - enc_h263_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - methods -}; - -MSFilterDesc ms_h263_old_enc_desc={ - MS_H263_OLD_ENC_ID, - "MSH263OldEnc", - N_("A video H.263 encoder using ffmpeg library. It is compliant with old RFC2190 spec."), - MS_FILTER_ENCODER, - "H263", - 1, /*MS_YUV420P is assumed on this input */ - 1, - enc_h263_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - methods -}; - -MSFilterDesc ms_mpeg4_enc_desc={ - MS_MPEG4_ENC_ID, - "MSMpeg4Enc", - N_("A video MPEG4 encoder using ffmpeg library."), - MS_FILTER_ENCODER, - "MP4V-ES", - 1, /*MS_YUV420P is assumed on this input */ - 1, - enc_mpeg4_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - methods -}; - -MSFilterDesc ms_snow_enc_desc={ - MS_SNOW_ENC_ID, - "MSSnowEnc", - N_("A video snow encoder using ffmpeg library."), - MS_FILTER_ENCODER, - "x-snow", - 1, /*MS_YUV420P is assumed on this input */ - 1, - enc_snow_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - methods -}; - -MSFilterDesc ms_mjpeg_enc_desc={ - MS_JPEG_ENC_ID, - "MSJpegEnc", - N_("A RTP/MJPEG encoder using ffmpeg library."), - MS_FILTER_ENCODER, - "JPEG", - 1, /*MS_YUV420P is assumed on this input */ - 1, - enc_mjpeg_init, - enc_preprocess, - enc_process, - enc_postprocess, - enc_uninit, - methods -}; - -#else - -MSFilterDesc ms_h263_enc_desc={ - .id=MS_H263_ENC_ID, - .name="MSH263Enc", - .text=N_("A video H.263 encoder using ffmpeg library."), - .category=MS_FILTER_ENCODER, - .enc_fmt="H263-1998", - .ninputs=1, /*MS_YUV420P is assumed on this input */ - .noutputs=1, - .init=enc_h263_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=methods -}; - -MSFilterDesc ms_h263_old_enc_desc={ - .id=MS_H263_OLD_ENC_ID, - .name="MSH263Enc", - .text=N_("A video H.263 encoder using ffmpeg library, compliant with old RFC2190 spec."), - .category=MS_FILTER_ENCODER, - .enc_fmt="H263", - .ninputs=1, /*MS_YUV420P is assumed on this input */ - .noutputs=1, - .init=enc_h263_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=methods -}; - -MSFilterDesc ms_mpeg4_enc_desc={ - .id=MS_MPEG4_ENC_ID, - .name="MSMpeg4Enc", - .text=N_("A video MPEG4 encoder using ffmpeg library."), - .category=MS_FILTER_ENCODER, - .enc_fmt="MP4V-ES", - .ninputs=1, /*MS_YUV420P is assumed on this input */ - .noutputs=1, - .init=enc_mpeg4_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=methods -}; - -MSFilterDesc ms_snow_enc_desc={ - .id=MS_SNOW_ENC_ID, - .name="MSSnowEnc", - .text=N_("The snow codec is royalty-free and is open-source. \n" - "It uses innovative techniques that makes it one of most promising video " - "codec. It is implemented within the ffmpeg project.\n" - "However it is under development, quite unstable and compatibility with other versions " - "cannot be guaranteed."), - .category=MS_FILTER_ENCODER, - .enc_fmt="x-snow", - .ninputs=1, /*MS_YUV420P is assumed on this input */ - .noutputs=1, - .init=enc_snow_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=methods -}; - -MSFilterDesc ms_mjpeg_enc_desc={ - .id=MS_JPEG_ENC_ID, - .name="MSMJpegEnc", - .text=N_("A MJPEG encoder using ffmpeg library."), - .category=MS_FILTER_ENCODER, - .enc_fmt="JPEG", - .ninputs=1, /*MS_YUV420P is assumed on this input */ - .noutputs=1, - .init=enc_mjpeg_init, - .preprocess=enc_preprocess, - .process=enc_process, - .postprocess=enc_postprocess, - .uninit=enc_uninit, - .methods=methods -}; - -#endif - -void __register_ffmpeg_encoders_if_possible(void){ - ms_ffmpeg_check_init(); - if (avcodec_find_encoder(CODEC_ID_MPEG4)) - ms_filter_register(&ms_mpeg4_enc_desc); - if (avcodec_find_encoder(CODEC_ID_H263)){ - ms_filter_register(&ms_h263_enc_desc); - ms_filter_register(&ms_h263_old_enc_desc); - } - if (avcodec_find_encoder(CODEC_ID_SNOW)) - ms_filter_register(&ms_snow_enc_desc); - if (avcodec_find_encoder(CODEC_ID_MJPEG)) - { - ms_filter_register(&ms_mjpeg_enc_desc); - } -} - diff --git a/linphone/mediastreamer2/src/videoout.c b/linphone/mediastreamer2/src/videoout.c deleted file mode 100644 index 51e6a3eff..000000000 --- a/linphone/mediastreamer2/src/videoout.c +++ /dev/null @@ -1,1005 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" - -/*required for dllexport of win_display_desc */ -#define INVIDEOUT_C 1 -#include "mediastreamer2/msvideoout.h" - -#include "ffmpeg-priv.h" - -static int video_out_set_vsize(MSFilter *f,void *arg); - -bool_t ms_display_poll_event(MSDisplay *d, MSDisplayEvent *ev){ - if (d->desc->pollevent) - return d->desc->pollevent(d,ev); - else return FALSE; -} - -#ifdef HAVE_SDL - -#include -#include - -static bool_t sdl_initialized=FALSE; - -static ms_mutex_t sdl_mutex; - -static SDL_Surface *sdl_screen=0; - -#ifdef HAVE_X11_XLIB_H - -#include - -static long sdl_get_native_window_id(){ - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if ( SDL_GetWMInfo(&info) ) { - if ( info.subsystem == SDL_SYSWM_X11 ) { - return (long) info.info.x11.wmwindow; - } - } - return 0; -} - -static void sdl_show_window(bool_t show){ - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if ( SDL_GetWMInfo(&info) ) { - if ( info.subsystem == SDL_SYSWM_X11 ) { - Display *display; - Window window; - - info.info.x11.lock_func(); - display = info.info.x11.display; - window = info.info.x11.wmwindow; - if (show) - XMapWindow(display,window); - else - XUnmapWindow(display,window); - info.info.x11.unlock_func(); - } - } -} - -#else - -static void sdl_show_window(bool_t show){ - ms_warning("SDL window show/hide not implemented"); -} - -static long sdl_get_native_window_id(){ - ms_warning("sdl_get_native_window_id not implemented"); - return 0; -} - -#endif - -static void sdl_display_uninit(MSDisplay *obj); - -static SDL_Overlay * sdl_create_window(int w, int h){ - static bool_t once=TRUE; - SDL_Overlay *lay; - sdl_screen = SDL_SetVideoMode(w,h, 0,SDL_SWSURFACE|SDL_RESIZABLE); - if (sdl_screen == NULL ) { - ms_warning("Couldn't set video mode: %s\n", - SDL_GetError()); - return NULL; - } - if (sdl_screen->flags & SDL_HWSURFACE) ms_message("SDL surface created in hardware"); - if (once) { - SDL_WM_SetCaption("Video window", NULL); - once=FALSE; - } - ms_message("Using yuv overlay."); - lay=SDL_CreateYUVOverlay(w , h ,SDL_YV12_OVERLAY,sdl_screen); - if (lay==NULL){ - ms_warning("Couldn't create yuv overlay: %s\n", - SDL_GetError()); - return NULL; - }else{ - ms_message("%i x %i YUV overlay created: hw_accel=%i, pitches=%i,%i,%i",lay->w,lay->h,lay->hw_overlay, - lay->pitches[0],lay->pitches[1],lay->pitches[2]); - ms_message("planes= %p %p %p %i %i",lay->pixels[0],lay->pixels[1],lay->pixels[2], - lay->pixels[1]-lay->pixels[0],lay->pixels[2]-lay->pixels[1]); - } - return lay; -} - -static bool_t sdl_display_init(MSDisplay *obj, MSPicture *fbuf){ - SDL_Overlay *lay; - if (!sdl_initialized){ - /* Initialize the SDL library */ - if( SDL_Init(SDL_INIT_VIDEO) < 0 ) { - ms_error("Couldn't initialize SDL: %s", SDL_GetError()); - return FALSE; - } - /* Clean up on exit */ - atexit(SDL_Quit); - sdl_initialized=TRUE; - ms_mutex_init(&sdl_mutex,NULL); - } - ms_mutex_lock(&sdl_mutex); - if (obj->data!=NULL){ - SDL_FreeYUVOverlay((SDL_Overlay*)obj->data); - } - - lay=sdl_create_window(fbuf->w, fbuf->h); - if (lay){ - fbuf->planes[0]=lay->pixels[0]; - fbuf->planes[1]=lay->pixels[2]; - fbuf->planes[2]=lay->pixels[1]; - fbuf->planes[3]=NULL; - fbuf->strides[0]=lay->pitches[0]; - fbuf->strides[1]=lay->pitches[2]; - fbuf->strides[2]=lay->pitches[1]; - fbuf->strides[3]=0; - fbuf->w=lay->w; - fbuf->h=lay->h; - obj->data=lay; - sdl_show_window(TRUE); - obj->window_id=sdl_get_native_window_id(); - ms_mutex_unlock(&sdl_mutex); - return TRUE; - } - ms_mutex_unlock(&sdl_mutex); - return FALSE; -} - -static void sdl_display_lock(MSDisplay *obj){ - ms_mutex_lock(&sdl_mutex); - SDL_LockYUVOverlay((SDL_Overlay*)obj->data); - ms_mutex_unlock(&sdl_mutex); -} - -static void sdl_display_unlock(MSDisplay *obj){ - SDL_Overlay *lay=(SDL_Overlay*)obj->data; - ms_mutex_lock(&sdl_mutex); - SDL_UnlockYUVOverlay(lay); - ms_mutex_unlock(&sdl_mutex); -} - -static void sdl_display_update(MSDisplay *obj){ - SDL_Rect rect; - SDL_Overlay *lay=(SDL_Overlay*)obj->data; - rect.x=0; - rect.y=0; - rect.w=lay->w; - rect.h=lay->h; - ms_mutex_lock(&sdl_mutex); - SDL_DisplayYUVOverlay(lay,&rect); - ms_mutex_unlock(&sdl_mutex); -} - -static bool_t sdl_poll_event(MSDisplay *obj, MSDisplayEvent *ev){ - SDL_Event event; - bool_t ret=FALSE; - if (sdl_screen==NULL) return FALSE; - ms_mutex_lock(&sdl_mutex); - if (SDL_PollEvent(&event)){ - ms_mutex_unlock(&sdl_mutex); - switch(event.type){ - case SDL_VIDEORESIZE: - ev->evtype=MS_DISPLAY_RESIZE_EVENT; - ev->w=event.resize.w; - ev->h=event.resize.h; - return TRUE; - break; - default: - break; - } - }else ms_mutex_unlock(&sdl_mutex); - return ret; -} - -static void sdl_display_uninit(MSDisplay *obj){ - SDL_Overlay *lay=(SDL_Overlay*)obj->data; - SDL_Event event; - int i; - if (lay==NULL) - return; - if (lay!=NULL) - SDL_FreeYUVOverlay(lay); - if (sdl_screen!=NULL){ - SDL_FreeSurface(sdl_screen); - sdl_screen=NULL; - } -#ifdef __linux - /*purge the event queue before leaving*/ - for(i=0;SDL_PollEvent(&event) && i<100;++i){ - } -#endif - sdl_show_window(FALSE); -} - -MSDisplayDesc ms_sdl_display_desc={ - .init=sdl_display_init, - .lock=sdl_display_lock, - .unlock=sdl_display_unlock, - .update=sdl_display_update, - .uninit=sdl_display_uninit, - .pollevent=sdl_poll_event, -}; - -#elif defined(WIN32) - -#include - - -typedef struct _WinDisplay{ - HWND window; - HDRAWDIB ddh; - MSPicture fb; - MSDisplayEvent last_rsz; - uint8_t *rgb; - uint8_t *black; - int last_rect_w; - int last_rect_h; - int rgb_len; - struct SwsContext *sws; - bool_t new_ev; -}WinDisplay; - -static LRESULT CALLBACK window_proc( - HWND hwnd, // handle to window - UINT uMsg, // message identifier - WPARAM wParam, // first message parameter - LPARAM lParam) // second message parameter -{ - switch(uMsg){ - case WM_DESTROY: - break; - case WM_SIZE: - if (wParam==SIZE_RESTORED){ - int h=(lParam>>16) & 0xffff; - int w=lParam & 0xffff; - MSDisplay *obj; - WinDisplay *wd; - ms_message("Resized to %i,%i",w,h); - obj=(MSDisplay*)GetWindowLongPtr(hwnd,GWLP_USERDATA); - if (obj!=NULL){ - wd=(WinDisplay*)obj->data; - wd->last_rsz.evtype=MS_DISPLAY_RESIZE_EVENT; - wd->last_rsz.w=w; - wd->last_rsz.h=h; - wd->new_ev=TRUE; - }else{ - ms_error("Could not retrieve MSDisplay from window !"); - } - } - break; - default: - return DefWindowProc(hwnd, uMsg, wParam, lParam); - } - return 0; -} - -static HWND create_window(int w, int h) -{ - WNDCLASS wc; - HINSTANCE hInstance = GetModuleHandle(NULL); - HWND hwnd; - RECT rect; - wc.style = 0 ; - wc.lpfnWndProc = window_proc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = NULL; - wc.hIcon = NULL; - wc.hCursor = LoadCursor(hInstance, IDC_ARROW); - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; - wc.lpszClassName = "Video Window"; - - if(!RegisterClass(&wc)) - { - /* already registred! */ - } - rect.left=100; - rect.top=100; - rect.right=rect.left+w; - rect.bottom=rect.top+h; - if (!AdjustWindowRect(&rect,WS_OVERLAPPEDWINDOW|WS_VISIBLE /*WS_CAPTION WS_TILED|WS_BORDER*/,FALSE)){ - ms_error("AdjustWindowRect failed."); - } - ms_message("AdjustWindowRect: %li,%li %li,%li",rect.left,rect.top,rect.right,rect.bottom); - hwnd=CreateWindow("Video Window", "Video window", - WS_OVERLAPPEDWINDOW /*WS_THICKFRAME*/ | WS_VISIBLE , - CW_USEDEFAULT, CW_USEDEFAULT, rect.right-rect.left,rect.bottom-rect.top, - NULL, NULL, hInstance, NULL); - if (hwnd==NULL){ - ms_error("Fail to create video window"); - } - return hwnd; -} - -static bool_t win_display_init(MSDisplay *obj, MSPicture *fbuf){ - WinDisplay *wd=(WinDisplay*)obj->data; - int ysize,usize; - - if (wd!=NULL) - { - if (wd->ddh) DrawDibClose(wd->ddh); - wd->ddh=NULL; - if (wd->fb.planes[0]) ms_free(wd->fb.planes[0]); - wd->fb.planes[0]=NULL; - wd->fb.planes[1]=NULL; - wd->fb.planes[2]=NULL; - wd->fb.planes[3]=NULL; - if (wd->rgb) ms_free(wd->rgb); - if (wd->black) ms_free(wd->black); - wd->rgb=NULL; - wd->black=NULL; - wd->rgb_len=0; - sws_freeContext(wd->sws); - wd->sws=NULL; - wd->last_rect_w=0; - wd->last_rect_h=0; - } - else - wd=(WinDisplay*)ms_new0(WinDisplay,1); - - obj->data=wd; - - wd->fb.w=fbuf->w; - wd->fb.h=fbuf->h; - - if (wd->window==NULL){ - if (obj->use_external_window && obj->window_id!=0){ - void *p; - wd->window=(HWND)obj->window_id; - p=(void*)GetWindowLongPtr(wd->window,GWLP_USERDATA); - if (p!=NULL){ - ms_error("Gulp: this externally supplied windows seems to " - "already have a userdata ! resizing will crash !"); - }else SetWindowLongPtr(wd->window,GWLP_USERDATA,(LONG_PTR)obj); - }else{ - wd->window=create_window(wd->fb.w,wd->fb.h); - obj->window_id=(long)wd->window; - if (wd->window!=NULL) SetWindowLongPtr(wd->window,GWLP_USERDATA,(LONG_PTR)obj); - else return FALSE; - } - }else if (!obj->use_external_window){ - /* the window might need to be resized*/ - RECT cur; - GetWindowRect(wd->window,&cur); - MoveWindow(wd->window,cur.left, cur.top, wd->fb.w, wd->fb.h,TRUE); - } - - if (wd->ddh==NULL) wd->ddh=DrawDibOpen(); - if (wd->ddh==NULL){ - ms_error("DrawDibOpen() failed."); - return FALSE; - } - /*allocate yuv and rgb buffers*/ - if (wd->fb.planes[0]) ms_free(wd->fb.planes[0]); - if (wd->rgb) ms_free(wd->rgb); - if (wd->black) ms_free(wd->black); - ysize=wd->fb.w*wd->fb.h; - usize=ysize/4; - fbuf->planes[0]=wd->fb.planes[0]=(uint8_t*)ms_malloc0(ysize+2*usize); - fbuf->planes[1]=wd->fb.planes[1]=wd->fb.planes[0]+ysize; - fbuf->planes[2]=wd->fb.planes[2]=wd->fb.planes[1]+usize; - fbuf->planes[3]=NULL; - fbuf->strides[0]=wd->fb.strides[0]=wd->fb.w; - fbuf->strides[1]=wd->fb.strides[1]=wd->fb.w/2; - fbuf->strides[2]=wd->fb.strides[2]=wd->fb.w/2; - fbuf->strides[3]=0; - - wd->rgb_len=ysize*3; - wd->rgb=(uint8_t*)ms_malloc0(wd->rgb_len); - wd->black = (uint8_t*)ms_malloc0(wd->rgb_len); - wd->last_rect_w=0; - wd->last_rect_h=0; - return TRUE; -} - -typedef struct rgb{ - uint8_t r,g,b; -} rgb_t; - -typedef struct yuv{ - uint8_t y,u,v; -} yuv_t; - - - -static void yuv420p_to_rgb(WinDisplay *wd, MSPicture *src, uint8_t *rgb){ - int rgb_stride=-src->w*3; - uint8_t *p; - - p=rgb+(src->w*3*(src->h-1)); - if (wd->sws==NULL){ - wd->sws=sws_getContext(src->w,src->h,PIX_FMT_YUV420P, - src->w,src->h, PIX_FMT_BGR24, - SWS_FAST_BILINEAR, NULL, NULL, NULL); - } - if (sws_scale(wd->sws,src->planes,src->strides, 0, - src->h, &p, &rgb_stride)<0){ - ms_error("Error in 420->rgb sws_scale()."); - } -} - -static int gcd(int m, int n) -{ - if(n == 0) - return m; - else - return gcd(n, m % n); -} - -static void reduce(int *num, int *denom) -{ - int divisor = gcd(*num, *denom); - *num /= divisor; - *denom /= divisor; -} - -static void win_display_update(MSDisplay *obj){ - WinDisplay *wd=(WinDisplay*)obj->data; - HDC hdc; - BITMAPINFOHEADER bi; - RECT rect; - bool_t ret; - int ratiow; - int ratioh; - int w; - int h; - - if (wd->window==NULL) return; - hdc=GetDC(wd->window); - if (hdc==NULL) { - ms_error("Could not get window dc"); - return; - } - yuv420p_to_rgb(wd, &wd->fb, wd->rgb); - memset(&bi,0,sizeof(bi)); - bi.biSize=sizeof(bi); - GetClientRect(wd->window,&rect); - - bi.biWidth=wd->fb.w; - bi.biHeight=wd->fb.h; - bi.biPlanes=1; - bi.biBitCount=24; - bi.biCompression=BI_RGB; - bi.biSizeImage=wd->rgb_len; - - ratiow=wd->fb.w; - ratioh=wd->fb.h; - reduce(&ratiow, &ratioh); - w = rect.right/ratiow*ratiow; - h = rect.bottom/ratioh*ratioh; - - if (h*ratiow>w*ratioh) - { - w = w; - h = w*ratioh/ratiow; - } - else - { - h = h; - w = h*ratiow/ratioh; - } - - if (h*wd->fb.w!=w*wd->fb.h) - ms_error("wrong ratio"); - - //if (wd->last_rect_w!=rect.right || wd->last_rect_h!=rect.bottom) - { - ret=DrawDibDraw(wd->ddh,hdc,0,0, - (rect.right-w)/2,rect.bottom, - &bi,wd->black, - 0,0,bi.biWidth,bi.biHeight,0); - - ret=DrawDibDraw(wd->ddh,hdc,0,0, - rect.right,(rect.bottom-h)/2, - &bi,wd->black, - 0,0,bi.biWidth,bi.biHeight,0); - - ret=DrawDibDraw(wd->ddh,hdc,0,(rect.bottom)-((rect.bottom-h+1)&~0x1)/2, - rect.right,((rect.bottom-h+1)&~0x1)/2, - &bi,wd->black, - 0,0,bi.biWidth,bi.biHeight,0); - - ret=DrawDibDraw(wd->ddh,hdc,(rect.right)-((rect.right-w+1)&~0x1)/2,0, - ((rect.right-w+1)&~0x1)/2,rect.bottom, - &bi,wd->black, - 0,0,bi.biWidth,bi.biHeight,0); - - wd->last_rect_w=rect.right; - wd->last_rect_h=rect.bottom; - } - - ret=DrawDibDraw(wd->ddh,hdc, - (rect.right-w)/2, - (rect.bottom-h)/2, - w, - h, - &bi,wd->rgb, - 0,0,bi.biWidth,bi.biHeight,0); - - - if (!ret) ms_error("DrawDibDraw failed."); - ReleaseDC(NULL,hdc); -} - -static void win_display_uninit(MSDisplay *obj){ - WinDisplay *wd=(WinDisplay*)obj->data; - if (wd==NULL) - return; - if (wd->window && !obj->use_external_window) DestroyWindow(wd->window); - if (wd->ddh) DrawDibClose(wd->ddh); - if (wd->fb.planes[0]) ms_free(wd->fb.planes[0]); - if (wd->rgb) ms_free(wd->rgb); - if (wd->black) ms_free(wd->black); - if (wd->sws) sws_freeContext(wd->sws); - ms_free(wd); -} - -bool_t win_display_pollevent(MSDisplay *d, MSDisplayEvent *ev){ - return FALSE; -} - -#ifdef _MSC_VER - -extern MSDisplayDesc ms_win_display_desc={ - win_display_init, - NULL, - NULL, - win_display_update, - win_display_uninit, - win_display_pollevent -}; - -#else - -MSDisplayDesc ms_win_display_desc={ - .init=win_display_init, - .update=win_display_update, - .uninit=win_display_uninit, - .pollevent=win_display_pollevent -}; - -#endif - -#endif - -MSDisplay *ms_display_new(MSDisplayDesc *desc){ - MSDisplay *obj=(MSDisplay *)ms_new0(MSDisplay,1); - obj->desc=desc; - obj->data=NULL; - return obj; -} - -void ms_display_set_window_id(MSDisplay *d, long id){ - d->window_id=id; - d->use_external_window=TRUE; -} - -void ms_display_destroy(MSDisplay *obj){ - obj->desc->uninit(obj); - ms_free(obj); -} - -#ifdef HAVE_SDL -static MSDisplayDesc *default_display_desc=&ms_sdl_display_desc; -#elif defined(WIN32) -static MSDisplayDesc *default_display_desc=&ms_win_display_desc; -#else -static MSDisplayDesc *default_display_desc=NULL; -#endif - -void ms_display_desc_set_default(MSDisplayDesc *desc){ - default_display_desc=desc; -} - -MSDisplayDesc * ms_display_desc_get_default(void){ - return default_display_desc; -} - -void ms_display_desc_set_default_window_id(MSDisplayDesc *desc, long id){ - desc->default_window_id=id; -} - -typedef struct VideoOut -{ - AVRational ratio; - MSPicture fbuf; - MSPicture local_pic; - MSRect local_rect; - mblk_t *local_msg; - MSVideoSize prevsize; - int corner; - struct SwsContext *sws1; - struct SwsContext *sws2; - MSDisplay *display; - bool_t own_display; - bool_t ready; - bool_t autofit; - bool_t mirror; -} VideoOut; - - -#define SCALE_FACTOR 6 - -static void set_corner(VideoOut *s, int corner) -{ - s->corner=corner; - s->local_pic.w=(s->fbuf.w/SCALE_FACTOR) & ~0x1; - s->local_pic.h=(s->fbuf.h/SCALE_FACTOR) & ~0x1; - if (corner==1) - { - /* top left corner */ - s->local_rect.x=0; - s->local_rect.y=0; - s->local_rect.w=s->local_pic.w; - s->local_rect.h=s->local_pic.h; - } - else if (corner==2) - { - /* top right corner */ - s->local_rect.x=s->fbuf.w-s->local_pic.w; - s->local_rect.y=0; - s->local_rect.w=s->local_pic.w; - s->local_rect.h=s->local_pic.h; - } - else if (corner==3) - { - /* bottom left corner */ - s->local_rect.x=0; - s->local_rect.y=s->fbuf.h-s->local_pic.h; - s->local_rect.w=s->local_pic.w; - s->local_rect.h=s->local_pic.h; - } - else - { - /* default: bottom right corner */ - /* corner can be set to -1: to disable the self view... */ - s->local_rect.x=s->fbuf.w-s->local_pic.w; - s->local_rect.y=s->fbuf.h-s->local_pic.h; - s->local_rect.w=s->local_pic.w; - s->local_rect.h=s->local_pic.h; - } -} - -static void set_vsize(VideoOut *s, MSVideoSize *sz){ - s->fbuf.w=sz->width & ~0x1; - s->fbuf.h=sz->height & ~0x1; - set_corner(s,s->corner); - ms_message("Video size set to %ix%i",s->fbuf.w,s->fbuf.h); -} - -static void video_out_init(MSFilter *f){ - VideoOut *obj=(VideoOut*)ms_new(VideoOut,1); - MSVideoSize def_size; - obj->ratio.num=11; - obj->ratio.den=9; - def_size.width=MS_VIDEO_SIZE_CIF_W; - def_size.height=MS_VIDEO_SIZE_CIF_H; - obj->prevsize.width=0; - obj->prevsize.height=0; - obj->local_msg=NULL; - obj->corner=0; - obj->sws1=NULL; - obj->sws2=NULL; - obj->display=NULL; - obj->own_display=FALSE; - obj->ready=FALSE; - obj->autofit=FALSE; - obj->mirror=FALSE; - set_vsize(obj,&def_size); - f->data=obj; -} - - -static void video_out_uninit(MSFilter *f){ - VideoOut *obj=(VideoOut*)f->data; - if (obj->display!=NULL && obj->own_display) - ms_display_destroy(obj->display); - if (obj->sws1!=NULL){ - sws_freeContext(obj->sws1); - obj->sws1=NULL; - } - if (obj->sws2!=NULL){ - sws_freeContext(obj->sws2); - obj->sws2=NULL; - } - if (obj->local_msg!=NULL) { - freemsg(obj->local_msg); - obj->local_msg=NULL; - } - ms_free(obj); -} - -static void video_out_prepare(MSFilter *f){ - VideoOut *obj=(VideoOut*)f->data; - if (obj->display==NULL){ - if (default_display_desc==NULL){ - ms_error("No default display built in !"); - return; - } - obj->display=ms_display_new(default_display_desc); - obj->own_display=TRUE; - } - if (!ms_display_init(obj->display,&obj->fbuf)){ - if (obj->own_display) ms_display_destroy(obj->display); - obj->display=NULL; - } - if (obj->sws1!=NULL){ - sws_freeContext(obj->sws1); - obj->sws1=NULL; - } - if (obj->sws2!=NULL){ - sws_freeContext(obj->sws2); - obj->sws2=NULL; - } - if (obj->local_msg!=NULL) { - freemsg(obj->local_msg); - obj->local_msg=NULL; - } - set_corner(obj,obj->corner); - obj->ready=TRUE; -} - -static int video_out_handle_resizing(MSFilter *f, void *data){ - VideoOut *s=(VideoOut*)f->data; - MSDisplay *disp=s->display; - if (disp!=NULL){ - MSDisplayEvent ev; - if (ms_display_poll_event(disp,&ev)){ - if (ev.evtype==MS_DISPLAY_RESIZE_EVENT){ - MSVideoSize sz; - sz.width=ev.w; - sz.height=ev.h; - ms_filter_lock(f); - if (s->ready){ - set_vsize(s,&sz); - s->ready=FALSE; - } - ms_filter_unlock(f); - } - } - } - return 0; -} - -static void video_out_preprocess(MSFilter *f){ - video_out_prepare(f); -} - - -static void video_out_process(MSFilter *f){ - VideoOut *obj=(VideoOut*)f->data; - mblk_t *inm; - - ms_filter_lock(f); - if (!obj->ready) video_out_prepare(f); - if (obj->display==NULL){ - ms_filter_unlock(f); - if (f->inputs[0]!=NULL) - ms_queue_flush(f->inputs[0]); - if (f->inputs[1]!=NULL) - ms_queue_flush(f->inputs[1]); - return; - } - /*get most recent message and draw it*/ - if (f->inputs[1]!=NULL && (inm=ms_queue_peek_last(f->inputs[1]))!=0) { - if (obj->corner==-1){ - if (obj->local_msg!=NULL) { - freemsg(obj->local_msg); - obj->local_msg=NULL; - } - }else{ - MSPicture src; - if (yuv_buf_init_from_mblk(&src,inm)==0){ - - if (obj->sws2==NULL){ - obj->sws2=sws_getContext(src.w,src.h,PIX_FMT_YUV420P, - obj->local_pic.w,obj->local_pic.h,PIX_FMT_YUV420P, - SWS_FAST_BILINEAR, NULL, NULL, NULL); - } - if (obj->local_msg==NULL){ - obj->local_msg=yuv_buf_alloc(&obj->local_pic, - obj->local_pic.w,obj->local_pic.h); - } - if (sws_scale(obj->sws2,src.planes,src.strides, 0, - src.h, obj->local_pic.planes, obj->local_pic.strides)<0){ - ms_error("Error in sws_scale()."); - } - if (!mblk_get_precious_flag(inm)) yuv_buf_mirror(&obj->local_pic); - } - } - ms_queue_flush(f->inputs[1]); - } - - if (f->inputs[0]!=NULL && (inm=ms_queue_peek_last(f->inputs[0]))!=0) { - MSPicture src; - if (yuv_buf_init_from_mblk(&src,inm)==0){ - MSVideoSize cur,newsize; - cur.width=obj->fbuf.w; - cur.height=obj->fbuf.h; - newsize.width=src.w; - newsize.height=src.h; - if (obj->autofit && !ms_video_size_equal(newsize,obj->prevsize) ) { - MSVideoSize qvga_size; - qvga_size.width=MS_VIDEO_SIZE_QVGA_W; - qvga_size.height=MS_VIDEO_SIZE_QVGA_H; - obj->prevsize=newsize; - ms_message("received size is %ix%i",newsize.width,newsize.height); - /*don't resize less than QVGA, it is too small*/ - if (ms_video_size_greater_than(qvga_size,newsize)){ - newsize.width=MS_VIDEO_SIZE_QVGA_W; - newsize.height=MS_VIDEO_SIZE_QVGA_H; - } - if (!ms_video_size_equal(newsize,cur)){ - set_vsize(obj,&newsize); - ms_message("autofit: new size is %ix%i",newsize.width,newsize.height); - video_out_prepare(f); - } - } - if (obj->sws1==NULL){ - obj->sws1=sws_getContext(src.w,src.h,PIX_FMT_YUV420P, - obj->fbuf.w,obj->fbuf.h,PIX_FMT_YUV420P, - SWS_FAST_BILINEAR, NULL, NULL, NULL); - } - ms_display_lock(obj->display); - if (sws_scale(obj->sws1,src.planes,src.strides, 0, - src.h, obj->fbuf.planes, obj->fbuf.strides)<0){ - ms_error("Error in sws_scale()."); - } - if (obj->mirror && !mblk_get_precious_flag(inm)) yuv_buf_mirror(&obj->fbuf); - ms_display_unlock(obj->display); - } - ms_queue_flush(f->inputs[0]); - } - /*copy resized local view into main buffer, at bottom left corner:*/ - if (obj->local_msg!=NULL){ - MSPicture corner=obj->fbuf; - MSVideoSize roi; - roi.width=obj->local_pic.w; - roi.height=obj->local_pic.h; - corner.w=obj->local_pic.w; - corner.h=obj->local_pic.h; - corner.planes[0]+=obj->local_rect.x+(obj->local_rect.y*corner.strides[0]); - corner.planes[1]+=(obj->local_rect.x/2)+((obj->local_rect.y/2)*corner.strides[1]); - corner.planes[2]+=(obj->local_rect.x/2)+((obj->local_rect.y/2)*corner.strides[2]); - corner.planes[3]=0; - ms_display_lock(obj->display); - yuv_buf_copy(obj->local_pic.planes,obj->local_pic.strides, - corner.planes,corner.strides,roi); - ms_display_unlock(obj->display); - } - ms_display_update(obj->display); - ms_filter_unlock(f); -} - -static int video_out_set_vsize(MSFilter *f,void *arg){ - VideoOut *s=(VideoOut*)f->data; - ms_filter_lock(f); - set_vsize(s,(MSVideoSize*)arg); - ms_filter_unlock(f); - return 0; -} - -static int video_out_set_display(MSFilter *f,void *arg){ - VideoOut *s=(VideoOut*)f->data; - s->display=(MSDisplay*)arg; - return 0; -} - -static int video_out_auto_fit(MSFilter *f, void *arg){ - VideoOut *s=(VideoOut*)f->data; - s->autofit=*(int*)arg; - return 0; -} - -static int video_out_set_corner(MSFilter *f,void *arg){ - VideoOut *s=(VideoOut*)f->data; - ms_filter_lock(f); - set_corner(s, *(int*)arg); - if (s->display){ - ms_display_lock(s->display); - { - int w=s->fbuf.w; - int h=s->fbuf.h; - int ysize=w*h; - int usize=ysize/4; - - memset(s->fbuf.planes[0], 0, ysize); - memset(s->fbuf.planes[1], 0, usize); - memset(s->fbuf.planes[2], 0, usize); - s->fbuf.planes[3]=NULL; - } - ms_display_unlock(s->display); - } - ms_filter_unlock(f); - return 0; -} - -static int video_out_enable_mirroring(MSFilter *f,void *arg){ - VideoOut *s=(VideoOut*)f->data; - s->mirror=*(int*)arg; - return 0; -} - -static int video_out_get_native_window_id(MSFilter *f, void*arg){ - VideoOut *s=(VideoOut*)f->data; - unsigned long *id=(unsigned long*)arg; - *id=0; - if (s->display){ - *id=s->display->window_id; - return 0; - } - return -1; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_VIDEO_SIZE , video_out_set_vsize }, - { MS_VIDEO_OUT_SET_DISPLAY , video_out_set_display}, - { MS_VIDEO_OUT_SET_CORNER , video_out_set_corner}, - { MS_VIDEO_OUT_AUTO_FIT , video_out_auto_fit}, - { MS_VIDEO_OUT_HANDLE_RESIZING , video_out_handle_resizing}, - { MS_VIDEO_OUT_ENABLE_MIRRORING , video_out_enable_mirroring}, - { MS_VIDEO_OUT_GET_NATIVE_WINDOW_ID, video_out_get_native_window_id}, - { 0 ,NULL} -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_video_out_desc={ - MS_VIDEO_OUT_ID, - "MSVideoOut", - N_("A generic video display"), - MS_FILTER_OTHER, - NULL, - 2, - 0, - video_out_init, - video_out_preprocess, - video_out_process, - NULL, - video_out_uninit, - methods -}; - -#else - -MSFilterDesc ms_video_out_desc={ - .id=MS_VIDEO_OUT_ID, - .name="MSVideoOut", - .text=N_("A generic video display"), - .category=MS_FILTER_OTHER, - .ninputs=2, - .noutputs=0, - .init=video_out_init, - .preprocess=video_out_preprocess, - .process=video_out_process, - .uninit=video_out_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_video_out_desc) diff --git a/linphone/mediastreamer2/src/videostream.c b/linphone/mediastreamer2/src/videostream.c deleted file mode 100644 index 65b800cea..000000000 --- a/linphone/mediastreamer2/src/videostream.c +++ /dev/null @@ -1,583 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mediastream.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msrtp.h" -#include "mediastreamer2/msvideoout.h" - - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -extern RtpSession * create_duplex_rtpsession( int locport, bool_t ipv6); - -#define MAX_RTP_SIZE UDP_MAX_SIZE - -/* this code is not part of the library itself, it is part of the mediastream program */ -void video_stream_free (VideoStream * stream) -{ - if (stream->session!=NULL){ - rtp_session_unregister_event_queue(stream->session,stream->evq); - rtp_session_destroy(stream->session); - } - if (stream->rtprecv != NULL) - ms_filter_destroy (stream->rtprecv); - if (stream->rtpsend!=NULL) - ms_filter_destroy (stream->rtpsend); - if (stream->source != NULL) - ms_filter_destroy (stream->source); - if (stream->output != NULL) - ms_filter_destroy (stream->output); - if (stream->decoder != NULL) - ms_filter_destroy (stream->decoder); - if (stream->sizeconv != NULL) - ms_filter_destroy (stream->sizeconv); - if (stream->pixconv!=NULL) - ms_filter_destroy(stream->pixconv); - if (stream->tee!=NULL) - ms_filter_destroy(stream->tee); - if (stream->ticker != NULL) - ms_ticker_destroy (stream->ticker); - if (stream->evq!=NULL) - ortp_ev_queue_destroy(stream->evq); - ms_free (stream); -} - -/*this function must be called from the MSTicker thread: -it replaces one filter by another one. -This is a dirty hack that works anyway. -It would be interesting to have something that does the job -simplier within the MSTicker api -*/ -void video_stream_change_decoder(VideoStream *stream, int payload){ - RtpSession *session=stream->session; - RtpProfile *prof=rtp_session_get_profile(session); - PayloadType *pt=rtp_profile_get_payload(prof,payload); - if (pt!=NULL){ - MSFilter *dec=ms_filter_create_decoder(pt->mime_type); - if (dec!=NULL){ - ms_filter_unlink(stream->rtprecv, 0, stream->decoder, 0); - ms_filter_unlink(stream->decoder,0,stream->output,0); - ms_filter_postprocess(stream->decoder); - ms_filter_destroy(stream->decoder); - stream->decoder=dec; - if (pt->recv_fmtp!=NULL) - ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)pt->recv_fmtp); - ms_filter_link (stream->rtprecv, 0, stream->decoder, 0); - ms_filter_link (stream->decoder,0 , stream->output, 0); - ms_filter_preprocess(stream->decoder,stream->ticker); - - }else{ - ms_warning("No decoder found for %s",pt->mime_type); - } - }else{ - ms_warning("No payload defined with number %i",payload); - } -} - -static void video_stream_adapt_bitrate(VideoStream *stream, int jitter, float lost){ - if (stream->encoder!=NULL){ - if (lost>10){ - int bitrate=0; - int new_bitrate; - ms_warning("Remote reports bad receiving experience, trying to reduce bitrate of video encoder."); - - ms_filter_call_method(stream->encoder,MS_FILTER_GET_BITRATE,&bitrate); - if (bitrate==0){ - ms_error("Video encoder does not implement MS_FILTER_GET_BITRATE."); - return; - } - if (bitrate>=20000){ - new_bitrate=bitrate-10000; - ms_warning("Encoder bitrate reduced from %i to %i b/s.",bitrate,new_bitrate); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_BITRATE,&new_bitrate); - }else{ - ms_warning("Video encoder bitrate already at minimum."); - } - - } - } -} - -static void video_steam_process_rtcp(VideoStream *stream, mblk_t *m){ - do{ - if (rtcp_is_SR(m)){ - const report_block_t *rb; - ms_message("video_steam_process_rtcp: receiving RTCP SR"); - rb=rtcp_SR_get_report_block(m,0); - if (rb){ - unsigned int ij; - float flost; - ij=report_block_get_interarrival_jitter(rb); - flost=(float)(100.0*report_block_get_fraction_lost(rb)/256.0); - ms_message("interarrival jitter=%u , lost packets percentage since last report=%f ",ij,flost); - if (stream->adapt_bitrate) video_stream_adapt_bitrate(stream,ij,flost); - } - } - }while(rtcp_next_packet(m)); -} - -void video_stream_iterate(VideoStream *stream){ - - if (stream->output!=NULL) - ms_filter_call_method_noarg(stream->output, - MS_VIDEO_OUT_HANDLE_RESIZING); - - if (stream->evq){ - OrtpEvent *ev=ortp_ev_queue_get(stream->evq); - if (ev!=NULL){ - if (ortp_event_get_type(ev)==ORTP_EVENT_RTCP_PACKET_RECEIVED){ - OrtpEventData *evd=ortp_event_get_data(ev); - video_steam_process_rtcp(stream,evd->packet); - } - ortp_event_destroy(ev); - } - } -} - -static void payload_type_changed(RtpSession *session, unsigned long data){ - VideoStream *stream=(VideoStream*)data; - int pt=rtp_session_get_recv_payload_type(stream->session); - video_stream_change_decoder(stream,pt); -} - -VideoStream *video_stream_new(int locport, bool_t use_ipv6){ - VideoStream *stream = (VideoStream *)ms_new0 (VideoStream, 1); - stream->session=create_duplex_rtpsession(locport,use_ipv6); - stream->evq=ortp_ev_queue_new(); - stream->rtpsend=ms_filter_new(MS_RTP_SEND_ID); - rtp_session_register_event_queue(stream->session,stream->evq); - stream->sent_vsize.width=MS_VIDEO_SIZE_CIF_W; - stream->sent_vsize.height=MS_VIDEO_SIZE_CIF_H; - return stream; -} - -void video_stream_set_sent_video_size(VideoStream *stream, MSVideoSize vsize){ - ms_message("Setting vidoe size %dx%d", vsize.width, vsize.height); - stream->sent_vsize=vsize; -} - -void video_stream_set_relay_session_id(VideoStream *stream, const char *id){ - ms_filter_call_method(stream->rtpsend, MS_RTP_SEND_SET_RELAY_SESSION_ID,(void*)id); -} - -void video_stream_enable_self_view(VideoStream *stream, bool_t val){ - MSFilter *out=stream->output; - stream->corner=val ? 0 : -1; - if (out){ - ms_filter_call_method(out,MS_VIDEO_OUT_SET_CORNER,&stream->corner); - } -} - -void video_stream_enable_adaptive_bitrate_control(VideoStream *s, bool_t yesno){ - s->adapt_bitrate=yesno; -} - -int video_stream_start (VideoStream *stream, RtpProfile *profile, const char *remip, int remport, - int rem_rtcp_port, int payload, int jitt_comp, MSWebCam *cam){ - PayloadType *pt; - RtpSession *rtps=stream->session; - MSPixFmt format; - MSVideoSize vsize,cam_vsize,disp_size; - float fps=15; - int tmp; - JBParameters jbp; - const int socket_buf_size=2000000; - - ms_message("%s entry", __FUNCTION__); - - pt=rtp_profile_get_payload(profile,payload); - if (pt==NULL){ - ms_error("videostream.c: undefined payload type."); - return -1; - } - stream->encoder=ms_filter_create_encoder(pt->mime_type); - stream->decoder=ms_filter_create_decoder(pt->mime_type); - if ((stream->encoder==NULL) || (stream->decoder==NULL)){ - /* big problem: we have not a registered codec for this payload...*/ - ms_error("videostream.c: No codecs available for payload %i:%s.",payload,pt->mime_type); - return -1; - } - - rtp_session_set_profile(rtps,profile); - if (remport>0) rtp_session_set_remote_addr_full(rtps,remip,remport,rem_rtcp_port); - rtp_session_set_payload_type(rtps,payload); - rtp_session_set_jitter_compensation(rtps,jitt_comp); - - rtp_session_signal_connect(stream->session,"payload_type_changed", - (RtpCallback)payload_type_changed,(unsigned long)stream); - - rtp_session_set_recv_buf_size(stream->session,MAX_RTP_SIZE); - - rtp_session_get_jitter_buffer_params(stream->session,&jbp); - jbp.max_packets=1000;//needed for high resolution video - rtp_session_set_jitter_buffer_params(stream->session,&jbp); - - rtp_session_set_rtp_socket_recv_buffer_size(stream->session,socket_buf_size); - rtp_session_set_rtp_socket_send_buffer_size(stream->session,socket_buf_size); - - /* creates two rtp filters to recv send streams (remote part) */ - if (remport>0) ms_filter_call_method(stream->rtpsend,MS_RTP_SEND_SET_SESSION,stream->session); - - stream->rtprecv = ms_filter_new (MS_RTP_RECV_ID); - ms_filter_call_method(stream->rtprecv,MS_RTP_RECV_SET_SESSION,stream->session); - - /* creates the filters */ - stream->source = ms_web_cam_create_reader(cam); - stream->tee = ms_filter_new(MS_TEE_ID); - stream->output=ms_filter_new(MS_VIDEO_OUT_ID); - stream->sizeconv=ms_filter_new(MS_SIZE_CONV_ID); - - if (pt->normal_bitrate>0){ - ms_message("Limiting bitrate of video encoder to %i bits/s",pt->normal_bitrate); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_BITRATE,&pt->normal_bitrate); - } - /* set parameters to the encoder and decoder*/ - if (pt->send_fmtp){ - ms_filter_call_method(stream->encoder,MS_FILTER_ADD_FMTP,pt->send_fmtp); - ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,pt->send_fmtp); - } - ms_filter_call_method(stream->encoder,MS_FILTER_GET_VIDEO_SIZE,&vsize); - vsize=ms_video_size_min(vsize,stream->sent_vsize); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_VIDEO_SIZE,&vsize); - ms_filter_call_method(stream->encoder,MS_FILTER_GET_FPS,&fps); - ms_message("Setting vsize=%ix%i, fps=%f",vsize.width,vsize.height,fps); - /* configure the filters */ - ms_filter_call_method(stream->source,MS_FILTER_SET_FPS,&fps); - ms_filter_call_method(stream->source,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - /* get the output format for webcam reader */ - ms_filter_call_method(stream->source,MS_FILTER_GET_PIX_FMT,&format); - if (format==MS_MJPEG){ - stream->pixconv=ms_filter_new(MS_MJPEG_DEC_ID); - }else{ - stream->pixconv = ms_filter_new(MS_PIX_CONV_ID); - /*set it to the pixconv */ - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_PIX_FMT,&format); - - ms_filter_call_method(stream->source,MS_FILTER_GET_VIDEO_SIZE,&cam_vsize); - - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_VIDEO_SIZE,&cam_vsize); - } - - ms_filter_call_method(stream->sizeconv,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - /*force the decoder to output YUV420P */ - format=MS_YUV420P; - ms_filter_call_method(stream->decoder,MS_FILTER_SET_PIX_FMT,&format); - - disp_size.width=MS_VIDEO_SIZE_CIF_W; - disp_size.height=MS_VIDEO_SIZE_CIF_H; - tmp=1; - ms_filter_call_method(stream->output,MS_FILTER_SET_VIDEO_SIZE,&disp_size); - ms_filter_call_method(stream->output,MS_VIDEO_OUT_AUTO_FIT,&tmp); - ms_filter_call_method(stream->output,MS_FILTER_SET_PIX_FMT,&format); - ms_filter_call_method(stream->output,MS_VIDEO_OUT_SET_CORNER,&stream->corner); - - if (pt->recv_fmtp!=NULL) - ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)pt->recv_fmtp); - - /* and then connect all */ - ms_filter_link (stream->source, 0, stream->pixconv, 0); - ms_filter_link (stream->pixconv, 0, stream->sizeconv, 0); - ms_filter_link (stream->sizeconv, 0, stream->tee, 0); - ms_filter_link (stream->tee, 0 ,stream->encoder, 0 ); - ms_filter_link (stream->encoder,0, stream->rtpsend,0); - - ms_filter_link (stream->rtprecv, 0, stream->decoder, 0); - ms_filter_link (stream->decoder,0 , stream->output, 0); - /* the source video must be send for preview */ - ms_filter_link(stream->tee,1,stream->output,1); - - /* create the ticker */ - stream->ticker = ms_ticker_new(); - ms_ticker_set_name(stream->ticker,"Video MSTicker"); - /* attach it the graph */ - ms_ticker_attach (stream->ticker, stream->source); - return 0; -} - -void video_stream_send_vfu(VideoStream *stream){ - if (stream->encoder) - ms_filter_call_method_noarg(stream->encoder,MS_FILTER_REQ_VFU); -} - -void -video_stream_stop (VideoStream * stream) -{ - if (stream->ticker){ - ms_ticker_detach(stream->ticker,stream->source); - - rtp_stats_display(rtp_session_get_stats(stream->session),"Video session's RTP statistics"); - - ms_filter_unlink(stream->source,0,stream->pixconv,0); - ms_filter_unlink (stream->pixconv, 0, stream->sizeconv, 0); - ms_filter_unlink (stream->sizeconv, 0, stream->tee, 0); - ms_filter_unlink(stream->tee,0,stream->encoder,0); - ms_filter_unlink(stream->encoder, 0, stream->rtpsend,0); - ms_filter_unlink(stream->rtprecv, 0, stream->decoder, 0); - ms_filter_unlink(stream->decoder,0,stream->output,0); - ms_filter_unlink(stream->tee,1,stream->output,1); - } - video_stream_free (stream); -} - - -void video_stream_set_rtcp_information(VideoStream *st, const char *cname, const char *tool){ - if (st->session!=NULL){ - rtp_session_set_source_description(st->session,cname,NULL,NULL,NULL,NULL,tool, - "This is free software (GPL) !"); - } -} - -unsigned long video_stream_get_native_window_id(VideoStream *stream){ - unsigned long id; - if (stream->output){ - if (ms_filter_call_method(stream->output,MS_VIDEO_OUT_GET_NATIVE_WINDOW_ID,&id)==0) - return id; - } - return 0; -} - - -VideoStream * video_preview_start(MSWebCam *device, MSVideoSize disp_size){ - VideoStream *stream = (VideoStream *)ms_new0 (VideoStream, 1); - MSVideoSize vsize=disp_size; - MSPixFmt format; - float fps=(float)29.97; - int mirroring=1; - - /* creates the filters */ - stream->source = ms_web_cam_create_reader(device); - stream->output = ms_filter_new(MS_VIDEO_OUT_ID); - - - /* configure the filters */ - ms_filter_call_method(stream->source,MS_FILTER_SET_VIDEO_SIZE,&vsize); - ms_filter_call_method(stream->source,MS_FILTER_SET_FPS,&fps); - ms_filter_call_method(stream->source,MS_FILTER_GET_PIX_FMT,&format); - ms_filter_call_method(stream->source,MS_FILTER_GET_VIDEO_SIZE,&vsize); - if (format==MS_MJPEG){ - stream->pixconv=ms_filter_new(MS_MJPEG_DEC_ID); - }else{ - stream->pixconv=ms_filter_new(MS_PIX_CONV_ID); - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_PIX_FMT,&format); - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_VIDEO_SIZE,&vsize); - } - - format=MS_YUV420P; - ms_filter_call_method(stream->output,MS_FILTER_SET_PIX_FMT,&format); - ms_filter_call_method(stream->output,MS_FILTER_SET_VIDEO_SIZE,&disp_size); - ms_filter_call_method(stream->output,MS_VIDEO_OUT_ENABLE_MIRRORING,&mirroring); - /* and then connect all */ - - ms_filter_link(stream->source,0, stream->pixconv,0); - ms_filter_link(stream->pixconv, 0, stream->output, 0); - - /* create the ticker */ - stream->ticker = ms_ticker_new(); - ms_ticker_set_name(stream->ticker,"Video MSTicker"); - ms_ticker_attach (stream->ticker, stream->source); - return stream; -} - -void video_preview_stop(VideoStream *stream){ - ms_ticker_detach(stream->ticker, stream->source); - ms_filter_unlink(stream->source,0,stream->pixconv,0); - ms_filter_unlink(stream->pixconv,0,stream->output,0); - - video_stream_free(stream); -} - - -int video_stream_send_only_start(VideoStream* stream, RtpProfile *profile, const char *remip, int remport, - int rem_rtcp_port, int payload, int jitt_comp, MSWebCam *device){ - PayloadType *pt; - MSPixFmt format; - MSVideoSize vsize; - RtpSession *rtps=stream->session; - float fps=15; - - vsize.width=MS_VIDEO_SIZE_CIF_W; - vsize.height=MS_VIDEO_SIZE_CIF_H; - - rtp_session_set_profile(rtps,profile); - if (remport>0) rtp_session_set_remote_addr_full(rtps,remip,remport,rem_rtcp_port); - rtp_session_set_payload_type(rtps,payload); - rtp_session_set_jitter_compensation(rtps,jitt_comp); - - /* creates rtp filter to send streams (remote part) */ - rtp_session_set_recv_buf_size(rtps,MAX_RTP_SIZE); - stream->rtpsend =ms_filter_new(MS_RTP_SEND_ID); - if (remport>0) ms_filter_call_method(stream->rtpsend,MS_RTP_SEND_SET_SESSION,stream->session); - - /* creates the filters */ - pt=rtp_profile_get_payload(profile,payload); - if (pt==NULL){ - video_stream_free(stream); - ms_error("videostream.c: undefined payload type."); - return -1; - } - stream->encoder=ms_filter_create_encoder(pt->mime_type); - if ((stream->encoder==NULL)){ - /* big problem: we have not a registered codec for this payload...*/ - video_stream_free(stream); - ms_error("videostream.c: No codecs available for payload %i.",payload); - return -1; - } - - /* creates the filters */ - stream->source = ms_web_cam_create_reader(device); - stream->sizeconv=ms_filter_new(MS_SIZE_CONV_ID); - - /* configure the filters */ - if (pt->send_fmtp) - ms_filter_call_method(stream->encoder,MS_FILTER_ADD_FMTP,pt->send_fmtp); - - if (pt->normal_bitrate>0){ - ms_message("Limiting bitrate of video encoder to %i bits/s",pt->normal_bitrate); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_BITRATE,&pt->normal_bitrate); - } - - ms_filter_call_method(stream->encoder,MS_FILTER_GET_FPS,&fps); - ms_filter_call_method(stream->encoder,MS_FILTER_GET_VIDEO_SIZE,&vsize); - vsize=ms_video_size_min(vsize,stream->sent_vsize); - ms_filter_call_method(stream->encoder,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - ms_filter_call_method(stream->source,MS_FILTER_SET_FPS,&fps); - ms_filter_call_method(stream->source,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - /* get the output format for webcam reader */ - ms_filter_call_method(stream->source,MS_FILTER_GET_PIX_FMT,&format); - /*set it to the pixconv */ - - /* bug fix from AMD: What about MJPEG mode???*/ - if (format==MS_MJPEG){ - stream->pixconv=ms_filter_new(MS_MJPEG_DEC_ID); - }else{ - stream->pixconv=ms_filter_new(MS_PIX_CONV_ID); - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_PIX_FMT,&format); - - ms_filter_call_method(stream->source,MS_FILTER_GET_VIDEO_SIZE,&vsize); - ms_filter_call_method(stream->pixconv,MS_FILTER_SET_VIDEO_SIZE,&vsize); - } - - ms_filter_call_method(stream->encoder,MS_FILTER_GET_VIDEO_SIZE,&vsize); - ms_filter_call_method(stream->sizeconv,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - ms_message("vsize=%ix%i, fps=%f, send format: %s, capture format: %d, bitrate: %d", - vsize.width,vsize.height,fps,pt->send_fmtp,format, pt->normal_bitrate); - - /* and then connect all */ - ms_filter_link (stream->source, 0, stream->pixconv, 0); - ms_filter_link (stream->pixconv, 0, stream->sizeconv, 0); - ms_filter_link (stream->sizeconv, 0, stream->encoder, 0); - ms_filter_link (stream->encoder,0, stream->rtpsend,0); - - /* create the ticker */ - stream->ticker = ms_ticker_new(); - /* attach it the graph */ - ms_ticker_attach (stream->ticker, stream->source); - return 0; -} - -void video_stream_send_only_stop(VideoStream *stream){ - if (stream->ticker){ - ms_ticker_detach (stream->ticker, stream->source); - ms_filter_unlink(stream->source,0,stream->pixconv,0); - ms_filter_unlink (stream->pixconv, 0, stream->sizeconv, 0); - ms_filter_unlink (stream->sizeconv, 0, stream->encoder, 0); - ms_filter_unlink(stream->encoder,0,stream->rtpsend,0); - } - video_stream_free(stream); -} - -int video_stream_recv_only_start (VideoStream *stream, RtpProfile *profile, const char *remip, int remport,int payload, int jitt_comp){ - PayloadType *pt; - MSPixFmt format; - MSVideoSize vsize; - RtpSession *rtps=stream->session; - - vsize.width=MS_VIDEO_SIZE_CIF_W; - vsize.height=MS_VIDEO_SIZE_CIF_H; - - rtp_session_set_profile(rtps,profile); - if (remport>0) rtp_session_set_remote_addr(rtps,remip,remport); - rtp_session_set_payload_type(rtps,payload); - rtp_session_set_jitter_compensation(rtps,jitt_comp); - - /* creates rtp filters to recv streams */ - rtp_session_set_recv_buf_size(rtps,MAX_RTP_SIZE); - stream->rtprecv = ms_filter_new (MS_RTP_RECV_ID); - ms_filter_call_method(stream->rtprecv,MS_RTP_RECV_SET_SESSION,rtps); - - /* creates the filters */ - pt=rtp_profile_get_payload(profile,payload); - if (pt==NULL){ - ms_error("videostream.c: undefined payload type."); - return -1; - } - stream->decoder=ms_filter_create_decoder(pt->mime_type); - if (stream->decoder==NULL){ - /* big problem: we have not a registered codec for this payload...*/ - ms_error("videostream.c: No codecs available for payload %i:%s.",payload,pt->mime_type); - return -1; - } - stream->output=ms_filter_new(MS_VIDEO_OUT_ID); - - /*force the decoder to output YUV420P */ - format=MS_YUV420P; - /*ask the size-converter to always output CIF */ - vsize.width=MS_VIDEO_SIZE_CIF_W; - vsize.height=MS_VIDEO_SIZE_CIF_H; - ms_message("Setting output vsize=%ix%i",vsize.width,vsize.height); - - ms_filter_call_method(stream->decoder,MS_FILTER_SET_PIX_FMT,&format); - ms_filter_call_method(stream->output,MS_FILTER_SET_PIX_FMT,&format); - ms_filter_call_method(stream->output,MS_FILTER_SET_VIDEO_SIZE,&vsize); - - if (pt->recv_fmtp!=NULL) { - ms_message("pt->recv_fmtp: %s", pt->recv_fmtp); - ms_filter_call_method(stream->decoder,MS_FILTER_ADD_FMTP,(void*)pt->recv_fmtp); - } - - /* and then connect all */ - ms_filter_link (stream->rtprecv, 0, stream->decoder, 0); - ms_filter_link (stream->decoder,0 , stream->output, 0); - - /* create the ticker */ - stream->ticker = ms_ticker_new(); - /* attach it the graph */ - ms_ticker_attach (stream->ticker, stream->rtprecv); - return 0; -} - -void video_stream_recv_only_stop (VideoStream * stream){ - if (stream->ticker!=NULL){ - ms_ticker_detach(stream->ticker, stream->rtprecv); - rtp_stats_display(rtp_session_get_stats(stream->session),"Video session's RTP statistics"); - ms_filter_unlink(stream->rtprecv, 0, stream->decoder, 0); - ms_filter_unlink(stream->decoder,0,stream->output,0); - } - video_stream_free (stream); -} - diff --git a/linphone/mediastreamer2/src/void.c b/linphone/mediastreamer2/src/void.c deleted file mode 100644 index 3a38fb776..000000000 --- a/linphone/mediastreamer2/src/void.c +++ /dev/null @@ -1,61 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" - - -static void void_sink_process(MSFilter *f){ - mblk_t *im; - while((im=ms_queue_get(f->inputs[0]))!=NULL){ - freemsg(im); - } -} - -#ifdef _MSC_VER - -MSFilterDesc ms_void_sink_desc={ - MS_VOID_SINK_ID, - "MSVoidSink", - N_("A filter that trashes its input (useful for terminating some graphs)."), - MS_FILTER_OTHER, - NULL, - 1, - 0, - NULL, - NULL, - void_sink_process, - NULL, - NULL -}; - -#else - -MSFilterDesc ms_void_sink_desc={ - .id=MS_VOID_SINK_ID, - .name="MSVoidSink", - .text=N_("A filter that trashes its input (useful for terminating some graphs)."), - .category=MS_FILTER_OTHER, - .ninputs=1, - .noutputs=0, - .process=void_sink_process, -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_void_sink_desc) diff --git a/linphone/mediastreamer2/src/wincevideods.c b/linphone/mediastreamer2/src/wincevideods.c deleted file mode 100644 index 7160d601e..000000000 --- a/linphone/mediastreamer2/src/wincevideods.c +++ /dev/null @@ -1,1003 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef VIDEO_ENABLED - -/* need to link with "dmoguids.lib strmiids.lib strmbase.lib atls.lib" */ - -#define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA - -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" - -#include -#include "nowebcam.h" -#if 0 -#include -#endif - -#include -#include -#include - -#include -//#include -#include "dxfilter.h" -#if 0 -#include -#endif -#include -#include - -typedef struct V4wState{ - - char dev[512]; - int devidx; - - CComPtr m_pGraph; - CComPtr m_pBuilder; - CComPtr m_pControl; - CDXFilter *m_pDXFilter; - CComPtr m_pIDXFilter; - CComPtr m_pNullRenderer; - CComPtr m_pDeviceFilter; - DWORD rotregvalue; - - MSVideoSize vsize; - int pix_fmt; - mblk_t *mire[10]; - queue_t rq; - ms_mutex_t mutex; - int frame_ind; - int frame_max; - float fps; - float start_time; - int frame_count; - bool_t running; - bool_t startwith_yuv_bug; /* avoid bug with USB vimicro cards. */ -}V4wState; - -static V4wState *s_callback=NULL; - -static void dummy(void*p){ -} - -HRESULT ( Callback)(IMediaSample* pSample, REFERENCE_TIME* sTime, REFERENCE_TIME* eTime, BOOL changed) -{ - BYTE *byte_buf=NULL; - mblk_t *buf; - - V4wState *s = s_callback; - if (s==NULL) - return S_OK; - - HRESULT hr = pSample->GetPointer(&byte_buf); - if (FAILED(hr)) - { - return S_OK; - } - - int size = pSample->GetActualDataLength(); - if (size>+1000) - { - buf=allocb(size,0); - memcpy(buf->b_wptr, byte_buf, size); - if (s->pix_fmt==MS_RGB24) - { - /* Conversion from top down bottom up (BGR to RGB and flip) */ - unsigned long Index,nPixels; - unsigned char *blue; - unsigned char tmp; - short iPixelSize; - - blue=buf->b_wptr; - - nPixels=s->vsize.width*s->vsize.height; - iPixelSize=24/8; - - for(Index=0;Index!=nPixels;Index++) // For each pixel - { - tmp=*blue; - *blue=*(blue+2); - *(blue+2)=tmp; - blue+=iPixelSize; - } - - unsigned char *pLine1, *pLine2; - int iLineLen,iIndex; - - iLineLen=s->vsize.width*iPixelSize; - pLine1=buf->b_wptr; - pLine2=&(buf->b_wptr)[iLineLen * (s->vsize.height - 1)]; - - for( ;pLine1b_wptr+=size; - - ms_mutex_lock(&s->mutex); - putq(&s->rq, buf); - ms_mutex_unlock(&s->mutex); - - } - return S_OK; -} - -HRESULT GetFirstCameraDriver( WCHAR *pwzName ) { - HRESULT hr = S_OK; - HANDLE handle = NULL; - DEVMGR_DEVICE_INFORMATION di; - GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, - 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86 }; - - if( pwzName == NULL ) { - return E_POINTER; - } - - di.dwSize = sizeof(di); - - handle = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &di ); - if(( handle == NULL ) || ( di.hDevice == NULL )) { - return S_FALSE; - } - - StringCchCopy( pwzName, MAX_PATH, di.szLegacyName ); - - FindClose( handle ); - return hr; -} - -struct VAR_LIST -{ - VARIANT var; - VAR_LIST *pNext; - BSTR pBSTRName; -}; - -class CPropertyBag : public IPropertyBag -{ -public: - CPropertyBag(); - ~CPropertyBag(); - - HRESULT STDMETHODCALLTYPE - Read( - LPCOLESTR pszPropName, - VARIANT *pVar, - IErrorLog *pErrorLog - ); - - - HRESULT STDMETHODCALLTYPE - Write( - LPCOLESTR pszPropName, - VARIANT *pVar - ); - - ULONG STDMETHODCALLTYPE AddRef(); - ULONG STDMETHODCALLTYPE Release(); - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv); - -private: - ULONG _refCount; - VAR_LIST *pVar; -}; - -CPropertyBag::CPropertyBag() : _refCount(1), pVar(0) -{ -} - -CPropertyBag::~CPropertyBag() -{ - VAR_LIST *pTemp = pVar; - HRESULT hr = S_OK; - - while(pTemp) - { - VAR_LIST *pDel = pTemp; - VariantClear(&pTemp->var); - SysFreeString(pTemp->pBSTRName); - pTemp = pTemp->pNext; - delete pDel; - } - -} - -HRESULT STDMETHODCALLTYPE -CPropertyBag::Read(LPCOLESTR pszPropName, - VARIANT *_pVar, - IErrorLog *pErrorLog) -{ - VAR_LIST *pTemp = pVar; - HRESULT hr = S_OK; - - while(pTemp) - { - if(0 == wcscmp(pszPropName, pTemp->pBSTRName)) - { - hr = VariantCopy(_pVar, &pTemp->var); - break; - } - pTemp = pTemp->pNext; - } - return hr; -} - - -HRESULT STDMETHODCALLTYPE -CPropertyBag::Write(LPCOLESTR pszPropName, - VARIANT *_pVar) -{ - HRESULT hr = S_OK; - VAR_LIST *pTemp = new VAR_LIST(); - ASSERT(pTemp); - - if( !pTemp ) - { - return E_OUTOFMEMORY; - } - - VariantInit(&pTemp->var); - pTemp->pBSTRName = SysAllocString(pszPropName); - pTemp->pNext = pVar; - pVar = pTemp; - return VariantCopy(&pTemp->var, _pVar); -} - -ULONG STDMETHODCALLTYPE -CPropertyBag::AddRef() -{ - return InterlockedIncrement((LONG *)&_refCount); -} - -ULONG STDMETHODCALLTYPE -CPropertyBag::Release() -{ - ASSERT(_refCount != 0xFFFFFFFF); - ULONG ret = InterlockedDecrement((LONG *)&_refCount); - if(!ret) - delete this; - return ret; -} - -HRESULT STDMETHODCALLTYPE -CPropertyBag::QueryInterface(REFIID riid, void** ppv) -{ - if(!ppv) - return E_POINTER; - if(riid == IID_IPropertyBag) - *ppv = static_cast(this); - else - return *ppv = 0, E_NOINTERFACE; - - return AddRef(), S_OK; -} - -static int v4w_open_videodevice(V4wState *s, int format, MSVideoSize *vsize) -{ - // Initialize COM - CoInitialize(NULL); - - // get a Graph - HRESULT hr=s->m_pGraph.CoCreateInstance(CLSID_FilterGraph); - if(FAILED(hr)) - { - return -1; - } - - // get a CaptureGraphBuilder2 -#if !defined(_WIN32_WCE) - hr=s->m_pBuilder.CoCreateInstance(CLSID_CaptureGraphBuilder2); -#else - hr=s->m_pBuilder.CoCreateInstance(CLSID_CaptureGraphBuilder); -#endif - if(FAILED(hr)) - { - return -2; - } - - // connect capture graph builder with the graph - s->m_pBuilder->SetFiltergraph(s->m_pGraph); - - // get mediacontrol so we can start and stop the filter graph - hr=s->m_pGraph.QueryInterface(&(s->m_pControl)); - if(FAILED(hr)) - { - return -3; - } - - // get DXFilter - s->m_pDXFilter = new CDXFilter(NULL, &hr, FALSE); - if(s->m_pDXFilter==NULL) - { - return -4; - } - s->m_pDXFilter->AddRef(); - if(FAILED(hr)) - { - return -4; - } - - CMediaType mt; - mt.SetType(&MEDIATYPE_Video); - - if (format==MS_YUV420P) - { - GUID m = (GUID)FOURCCMap(MAKEFOURCC('I','4','2','0')); - mt.SetSubtype(&m); - mt.SetSubtype(&MEDIASUBTYPE_YV12); - } - else //if (format==MS_RGB24) - { - mt.SetSubtype(&MEDIASUBTYPE_RGB24); - } - - //mt.SetSubtype(&MEDIASUBTYPE_IYUV); - //mt.SetSubtype(&MEDIASUBTYPE_YUYV); - //mt.SetSubtype(&MEDIASUBTYPE_RGB24); - //mt.SetSampleSize(); - mt.formattype = FORMAT_VideoInfo; - mt.SetTemporalCompression(FALSE); - - VIDEOINFO *pvi = (VIDEOINFO *) - mt.AllocFormatBuffer(sizeof(VIDEOINFO)); - if (NULL == pvi) - return E_OUTOFMEMORY; - ZeroMemory(pvi, sizeof(VIDEOINFO)); - if (format==MS_YUV420P) - { - pvi->bmiHeader.biCompression = MAKEFOURCC('I','4','2','0'); - pvi->bmiHeader.biCompression = MAKEFOURCC('Y','V','1','2'); - pvi->bmiHeader.biBitCount = 12; - } - else - { - pvi->bmiHeader.biCompression = BI_RGB; - pvi->bmiHeader.biBitCount = 24; - } - pvi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - pvi->bmiHeader.biWidth = vsize->width; - pvi->bmiHeader.biHeight = vsize->height; - pvi->bmiHeader.biPlanes = 1; - pvi->bmiHeader.biSizeImage = GetBitmapSize(&pvi->bmiHeader); - pvi->bmiHeader.biClrImportant = 0; - mt.SetSampleSize(pvi->bmiHeader.biSizeImage); - mt.SetFormat((BYTE*)pvi, sizeof(VIDEOINFO)); - - hr = s->m_pDXFilter->SetAcceptedMediaType(&mt); - if(FAILED(hr)) - { - return -5; - } - - hr = s->m_pDXFilter->SetCallback(Callback); - if(FAILED(hr)) - { - return -6; - } - - hr = s->m_pDXFilter->QueryInterface(IID_IBaseFilter, - (LPVOID *)&s->m_pIDXFilter); - if(FAILED(hr)) - { - return -7; - } - - hr = s->m_pGraph->AddFilter(s->m_pIDXFilter, L"DXFilter Filter"); - if(FAILED(hr)) - { - return -8; - } - -#ifdef WM6 - ICreateDevEnum *pCreateDevEnum = NULL; - IEnumMoniker *pEnumMoniker = NULL; - IMoniker *pMoniker = NULL; - - ULONG nFetched = 0; - - hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, - IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum); - if(FAILED(hr)) - { - return -9; - } - - hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, - &pEnumMoniker, 0); - if (FAILED(hr) || pEnumMoniker == NULL) { - //printf("no device\n"); - return -10; - } - - pEnumMoniker->Reset(); - - hr = pEnumMoniker->Next(1, &pMoniker, &nFetched); - if(FAILED(hr) || pMoniker==NULL) - { - return -11; - } - - hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&s->m_pDeviceFilter ); - if(FAILED(hr)) - { - return -12; - } - - s->m_pGraph->AddFilter(s->m_pDeviceFilter, L"Device Filter"); - - pMoniker->Release(); - pEnumMoniker->Release(); - pCreateDevEnum->Release(); -#else - WCHAR wzDeviceName[ MAX_PATH + 1 ]; - CComVariant varCamName; - CPropertyBag PropBag; - CComPtr pPropertyBag; - GetFirstCameraDriver(wzDeviceName); - - hr = s->m_pDeviceFilter.CoCreateInstance( CLSID_VideoCapture ); - if (FAILED(hr)) - { - return -8; - } - - s->m_pDeviceFilter.QueryInterface( &pPropertyBag ); - varCamName = wzDeviceName; - if(( varCamName.vt == VT_BSTR ) == NULL ) { - return E_OUTOFMEMORY; - } - PropBag.Write( L"VCapName", &varCamName ); - pPropertyBag->Load( &PropBag, NULL ); - pPropertyBag.Release(); - - hr = s->m_pGraph->AddFilter( s->m_pDeviceFilter, L"Video capture source" ); -#endif - - if (FAILED(hr)) - { - return -8; - } - - // get null renderer - s->m_pNullRenderer = NULL; -#if 0 - hr=s->m_pNullRenderer.CoCreateInstance(CLSID_NullRenderer); - if(FAILED(hr)) - { - return -13; - } -#endif - if (s->m_pNullRenderer!=NULL) - { - s->m_pGraph->AddFilter(s->m_pNullRenderer, L"Null Renderer"); - } - - hr = s->m_pBuilder->RenderStream(&PIN_CATEGORY_PREVIEW, - &MEDIATYPE_Video, s->m_pDeviceFilter, s->m_pIDXFilter, s->m_pNullRenderer); - if (FAILED(hr)) - { - //hr = s->m_pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, - // &MEDIATYPE_Video, s->m_pDeviceFilter, s->m_pIDXFilter, s->m_pNullRenderer); - if (FAILED(hr)) - { - return -14; - } - } - - //m_pDXFilter->SetBufferSamples(TRUE); - - - // Create the System Device Enumerator. -IFilterMapper *pMapper = NULL; -//IEnumMoniker *pEnum = NULL; -IEnumRegFilters *pEnum = NULL; - -hr = CoCreateInstance(CLSID_FilterMapper, - NULL, CLSCTX_INPROC, IID_IFilterMapper, - (void **) &pMapper); - -if (FAILED(hr)) -{ - // Error handling omitted for clarity. -} - -GUID arrayInTypes[2]; -arrayInTypes[0] = MEDIATYPE_Video; -arrayInTypes[1] = MEDIASUBTYPE_dvsd; - -hr = pMapper->EnumMatchingFilters( - &pEnum, - MERIT_HW_COMPRESSOR, // Minimum merit. - FALSE, // At least one input pin? - MEDIATYPE_NULL, - MEDIASUBTYPE_NULL, - FALSE, // Must be a renderer? - FALSE, // At least one output pin? - MEDIATYPE_NULL, - MEDIASUBTYPE_NULL); - -// Enumerate the monikers. -//IMoniker *pMoniker; -REGFILTER *pMoniker; -ULONG cFetched; -while (pEnum->Next(1, &pMoniker, &cFetched) == S_OK) -{ - IPropertyBag *pPropBag = NULL; -#if 0 - hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, - (void **)&pPropBag); - - if (SUCCEEDED(hr)) - { - // To retrieve the friendly name of the filter, do the following: - VARIANT varName; - VariantInit(&varName); - hr = pPropBag->Read(L"FriendlyName", &varName, 0); - if (SUCCEEDED(hr)) - { - // Display the name in your UI somehow. - } - VariantClear(&varName); - - // To create an instance of the filter, do the following: - IBaseFilter *pFilter; - hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pFilter); - // Now add the filter to the graph. Remember to release pFilter later. - - // Clean up. - pPropBag->Release(); - } - pMoniker->Release(); -#endif - -} - -// Clean up. -pMapper->Release(); -pEnum->Release(); - - - - - s_callback = s; - hr = s->m_pControl->Run(); - if(FAILED(hr)) - { - return -15; - } - - s->rotregvalue=1; - s->pix_fmt = format; - s->vsize.height = vsize->height; - s->vsize.width = vsize->width; - return 0; -} - -static void v4w_init(MSFilter *f){ - V4wState *s=(V4wState *)ms_new0(V4wState,1); - int idx; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - //s->pix_fmt=MS_RGB24; - s->pix_fmt=MS_YUV420P; - - s->rotregvalue = 0; - s->m_pGraph=NULL; - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pDXFilter=NULL; - s->m_pIDXFilter=NULL; - s->m_pDeviceFilter=NULL; - - qinit(&s->rq); - for (idx=0;idx<10;idx++) - { - s->mire[idx]=NULL; - } - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - - f->data=s; -} - -static int try_format(V4wState *s, int format, MSVideoSize *vsize) -{ - int i = v4w_open_videodevice(s, format, vsize); - if (i==-14) - { - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pIDXFilter=NULL; - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - s->m_pDXFilter=NULL; - s->m_pGraph=NULL; - s->m_pNullRenderer=NULL; - s->m_pDeviceFilter=NULL; - CoUninitialize(); - } - return i; -} - -static int _v4w_start(V4wState *s, void *arg) -{ - MSVideoSize try_vsize; - int tryformat; - int i; - s->frame_count=-1; - - if (s->pix_fmt==MS_YUV420P) - tryformat = MS_RGB24; - else if (s->pix_fmt==MS_RGB24) - tryformat = MS_YUV420P; - - try_vsize.height = s->vsize.height; - try_vsize.width = s->vsize.width; - i = try_format(s, s->pix_fmt, &try_vsize); - if (i==-14) - { - /* try second format with same size */ - i = try_format(s, tryformat, &try_vsize); - } - - /* try both format with CIF size */ - if (i==-14 && s->vsize.height!=MS_VIDEO_SIZE_CIF_H) - { - try_vsize.height = MS_VIDEO_SIZE_CIF_H; - try_vsize.width = MS_VIDEO_SIZE_CIF_W; - i = try_format(s, s->pix_fmt, &try_vsize); - if (i==-14) - { - i = try_format(s, tryformat, &try_vsize); - } - } - if (i==-14 && s->vsize.height!=MS_VIDEO_SIZE_QCIF_H) - { - try_vsize.height = MS_VIDEO_SIZE_QCIF_H; - try_vsize.width = MS_VIDEO_SIZE_QCIF_W; - i = try_format(s, s->pix_fmt, &try_vsize); - if (i==-14) - { - i = try_format(s, tryformat, &try_vsize); - } - } - if (i==-14 && s->vsize.height!=MS_VIDEO_SIZE_VGA_H) - { - try_vsize.height = MS_VIDEO_SIZE_VGA_H; - try_vsize.width = MS_VIDEO_SIZE_VGA_W; - i = try_format(s, s->pix_fmt, &try_vsize); - if (i==-14) - { - i = try_format(s, tryformat, &try_vsize); - } - } - - if (i==-14 && s->vsize.height!=MS_VIDEO_SIZE_QVGA_H) - { - try_vsize.height = MS_VIDEO_SIZE_QVGA_H; - try_vsize.width = MS_VIDEO_SIZE_QVGA_W; - i = try_format(s, s->pix_fmt, &try_vsize); - if (i==-14) - { - i = try_format(s, tryformat, &try_vsize); - } - } - - if (i==0) - { - if (s->pix_fmt==MS_YUV420P) - ms_message("Using YUV420P"); - else if (s->pix_fmt==MS_RGB24) - ms_message("Using RGB24"); - } - - if (s->rotregvalue==0){ - //RemoveGraphFromRot(s->rotregvalue); - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pIDXFilter=NULL; - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - s->m_pDXFilter=NULL; - s->m_pGraph=NULL; - s->m_pNullRenderer=NULL; - s->m_pDeviceFilter=NULL; - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: graph not started (err=%i)", i); - s->rotregvalue=0; - } - return i; -} - -static int _v4w_stop(V4wState *s, void *arg){ - s->frame_count=-1; - if (s->rotregvalue>0){ - HRESULT hr = s->m_pControl->Stop(); - if(FAILED(hr)) - { - ms_message("v4w: could not stop graph"); - } - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - //RemoveGraphFromRot(s->rotregvalue); - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pIDXFilter=NULL; - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - s->m_pDXFilter=NULL; - s->m_pGraph=NULL; - s->m_pNullRenderer=NULL; - s->m_pDeviceFilter=NULL; - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: graph destroyed"); - s->rotregvalue=0; - } - return 0; -} - - -static int v4w_start(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - _v4w_start(s, NULL); - return 0; -} - -static int v4w_stop(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - _v4w_stop(s, NULL); - return 0; -} - - -static void v4w_uninit(MSFilter *f){ - V4wState *s=(V4wState*)f->data; - int idx; - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - for (idx=0;idx<10;idx++) - { - if (s->mire[idx]==NULL) - break; - freemsg(s->mire[idx]); - } - if (s->rotregvalue>0){ - HRESULT hr = s->m_pControl->Stop(); - if(FAILED(hr)) - { - ms_message("v4w: could not stop graph"); - } - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - //RemoveGraphFromRot(s->rotregvalue); - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pIDXFilter=NULL; - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - s->m_pDXFilter=NULL; - s->m_pGraph=NULL; - s->m_pNullRenderer=NULL; - s->m_pDeviceFilter=NULL; - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: graph destroyed"); - s->rotregvalue=0; - } - ms_free(s); -} - -static mblk_t * v4w_make_nowebcam(V4wState *s){ -#if defined(_WIN32_WCE) - return NULL; -#else - int idx; - int count; - if (s->mire[0]==NULL && s->frame_ind==0){ - /* load several images to fake a movie */ - for (idx=0;idx<10;idx++) - { - s->mire[idx]=ms_load_nowebcam(&s->vsize, idx); - if (s->mire[idx]==NULL) - break; - } - if (idx==0) - s->mire[0]=ms_load_nowebcam(&s->vsize, -1); - } - for (count=0;count<10;count++) - { - if (s->mire[count]==NULL) - break; - } - - s->frame_ind++; - if (count==0) - return NULL; - - idx = s->frame_ind%count; - if (s->mire[idx]!=NULL) - return s->mire[idx]; - return s->mire[0]; -#endif -} - -static void v4w_preprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - s->running=TRUE; - if (s->rotregvalue==0) - s->fps=1; -} - -static void v4w_postprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - s->running=FALSE; -} - -static void v4w_process(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - mblk_t *m; - uint32_t timestamp; - int cur_frame; - - if (s->frame_count==-1){ - s->start_time=obj->ticker->time; - s->frame_count=0; - } - - - cur_frame=((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>s->frame_count){ - mblk_t *om=NULL; - ms_mutex_lock(&s->mutex); - /*keep the most recent frame if several frames have been captured */ - if (s->rotregvalue!=0){ - while((m=getq(&s->rq))!=NULL){ - if (om!=NULL) freemsg(om); - om=m; - } - }else { - mblk_t *nowebcam = v4w_make_nowebcam(s); - if (nowebcam!=NULL) - om=dupmsg(nowebcam); - } - ms_mutex_unlock(&s->mutex); - if (om!=NULL){ - timestamp=obj->ticker->time*90;/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - ms_queue_put(obj->outputs[0],om); - /*ms_message("picture sent");*/ - } - s->frame_count++; - } -} - - - -static int v4w_set_fps(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->fps=*((float*)arg); - return 0; -} - -static int v4w_get_pix_fmt(MSFilter *f,void *arg){ - V4wState *s=(V4wState*)f->data; - *((MSPixFmt*)arg) = (MSPixFmt)s->pix_fmt; - return 0; -} - -static int v4w_set_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->vsize=*((MSVideoSize*)arg); - return 0; -} - -static int v4w_get_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - MSVideoSize *vs=(MSVideoSize*)arg; - vs->width=s->vsize.width; - vs->height=s->vsize.height; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , v4w_set_fps }, - { MS_FILTER_GET_PIX_FMT , v4w_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, v4w_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, v4w_get_vsize }, - { MS_V4L_START , v4w_start }, - { MS_V4L_STOP , v4w_stop }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_v4w_desc={ - MS_V4L_ID, - "MSV4w", - N_("A video4windows compatible source filter to stream pictures."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - v4w_init, - v4w_preprocess, - v4w_process, - v4w_postprocess, - v4w_uninit, - methods -}; - -#else - -MSFilterDesc ms_v4w_desc={ - .id=MS_V4L_ID, - .name="MSV4w", - .text=N_("A video4windows compatible source filter to stream pictures."), - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=v4w_init, - .preprocess=v4w_preprocess, - .process=v4w_process, - .postprocess=v4w_postprocess, - .uninit=v4w_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_v4w_desc) - -#endif diff --git a/linphone/mediastreamer2/src/winsnd.c b/linphone/mediastreamer2/src/winsnd.c deleted file mode 100644 index 74f21d620..000000000 --- a/linphone/mediastreamer2/src/winsnd.c +++ /dev/null @@ -1,972 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#if defined(_WIN32_WCE) -#define DISABLE_SPEEX -#endif - -#ifndef WINSND_BUFLEN -#define WINSND_BUFLEN 320 -#endif - -#ifndef MAX_WAVEHDR -#define MAX_WAVEHDR 6 -#endif - -#ifndef DISABLE_SPEEX -#include -#endif - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" - -#ifdef WIN32 -#include /* for alloca */ -#endif - -#include -#ifdef _MSC_VER -#include -#endif -#include - -MSFilter *ms_winsnd_read_new(MSSndCard *card); -MSFilter *ms_winsnd_write_new(MSSndCard *card); - -typedef struct WinSndData{ - char *pcmdev; - char *mixdev; - int devid; - - int sound_err; - WAVEFORMATEX wfx; -#ifdef CONTROLVOLUME - DWORD dwOldVolume; -#endif - WAVEHDR waveouthdr[30]; - char waveoutbuffer[30][3200]; - HWAVEOUT waveoutdev; - int buffer_playing; - int pos_whdr; - - WAVEHDR waveinhdr[30]; - HWAVEIN waveindev; - char waveinbuffer[30][3200]; - - int rate; - int bits; - ms_thread_t thread; - ms_mutex_t mutex; - queue_t rq; - MSBufferizer * bufferizer; - bool_t read_started; - bool_t write_started; - bool_t stereo; - -#ifndef DISABLE_SPEEX - SpeexPreprocessState *pst; -#endif - - uint64_t bytes_read; - int32_t stat_input; - int32_t stat_output; - int32_t stat_notplayed; -} WinSndData; - -static uint64_t winsnd_get_cur_time( void *data){ - WinSndData *d=(WinSndData*)data; - uint64_t curtime=(d->bytes_read*1000)/(d->rate*(d->bits/8)*((d->stereo==FALSE) ? 1 : 2)); - ms_debug("winsnd_get_cur_time: bytes_read=%lu, rate=%i, bits=%i, stereo=%i return %lu\n", - (unsigned long)d->bytes_read,d->rate,d->bits,d->stereo,(unsigned long)curtime); - return curtime; -} - -static void CALLBACK -SpeakerCallback (HWAVEOUT _waveoutdev, UINT uMsg, DWORD dwInstance, - DWORD dwParam1, DWORD dwParam2) -{ - WAVEHDR *wHdr; - WinSndData *device; - - switch (uMsg) - { - case WOM_OPEN: - ms_message("SpeakerCallback : WOM_OPEN"); - break; - case WOM_CLOSE: - ms_message("SpeakerCallback : WOM_CLOSE"); - break; - case WOM_DONE: - wHdr = (WAVEHDR *) dwParam1; - device = (WinSndData *)dwInstance; - device->buffer_playing--; - if (device->stat_output==0) - { - device->stat_input=1; /* reset */ - device->stat_notplayed=0; - } - device->stat_output++; - break; - default: - break; - } -} - -static void CALLBACK -WaveInCallback (HWAVEIN waveindev, UINT uMsg, DWORD dwInstance, DWORD dwParam1, - DWORD dwParam2) -{ - WAVEHDR *wHdr; - MMRESULT mr = NOERROR; - WinSndData *device; - - device = (WinSndData *)dwInstance; - - switch (uMsg) - { - case MM_WOM_DONE: - wHdr = (WAVEHDR *) dwParam1; - /* A waveform-audio data block has been played and - can now be freed. */ - ms_message("WaveInCallback : MM_WOM_DONE"); - waveInUnprepareHeader (waveindev, (LPWAVEHDR) wHdr, sizeof (WAVEHDR)); - break; - - case WIM_OPEN: - ms_message("WaveInCallback : WIM_OPEN"); - break; - case WIM_CLOSE: - ms_message("WaveInCallback : WIM_CLOSE"); - break; - case WIM_DATA: - wHdr = (WAVEHDR *) dwParam1; - - device->bytes_read+=wHdr->dwBytesRecorded; - - if (!device->read_started && !device->write_started) - { - mr = waveInUnprepareHeader (device->waveindev, (LPWAVEHDR) wHdr, sizeof (WAVEHDR)); - ms_warning("WaveInCallback : unprepare header (waveInUnprepareHeader:0x%i)", mr); - return; - } - - if (wHdr->dwBufferLength!=wHdr->dwBytesRecorded) - { - mr = waveInAddBuffer (device->waveindev, - wHdr, - sizeof (device->waveinhdr[wHdr->dwUser])); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("WaveInCallback : error adding buffer to sound card (waveInAddBuffer:0x%i)", mr); - } - return; - } - ms_mutex_lock(&device->mutex); - if (device->read_started) - { - mblk_t *rm=NULL; - if (rm==NULL) rm=allocb(wHdr->dwBufferLength,0); - memcpy(rm->b_wptr,wHdr->lpData, wHdr->dwBufferLength); - -#ifndef DISABLE_SPEEX - if (device->pst!=NULL) - { - int vad; - //memset(rm->b_wptr,0, wHdr->dwBufferLength); - - vad = speex_preprocess(device->pst, (short*)rm->b_wptr, NULL); -#if 0 - if (vad!=1) - ms_message("WaveInCallback : %d", vad); -#endif - } - -#endif - rm->b_wptr+=wHdr->dwBufferLength; - putq(&device->rq,rm); - device->stat_input++; - rm=NULL; - } - ms_mutex_unlock(&device->mutex); - - mr = waveInAddBuffer (device->waveindev, - wHdr, - sizeof (device->waveinhdr[wHdr->dwUser])); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("WaveInCallback : error adding buffer to sound card (waveInAddBuffer:0x%i)", mr); - return; - } - } -} - -static int winsnd_open(WinSndData *device, int devnumber, int bits,int stereo, int rate, int *minsz) -{ - MMRESULT mr = NOERROR; - DWORD dwFlag; - int i; - int channel = 1; - if (stereo>0) - channel = stereo; - device->wfx.wFormatTag = WAVE_FORMAT_PCM; - device->wfx.cbSize = 0; - device->wfx.nAvgBytesPerSec = 16000; - device->wfx.nBlockAlign = 2; - device->wfx.nChannels = channel; - device->wfx.nSamplesPerSec = rate; /* 8000; */ - device->wfx.wBitsPerSample = bits; - - - dwFlag = CALLBACK_FUNCTION; - if (devnumber != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveOutOpen (&(device->waveoutdev), devnumber, &(device->wfx), (DWORD) SpeakerCallback, - (DWORD)device, dwFlag); - if (mr != NOERROR) - { - ms_warning("Failed to open device: trying default device. (waveOutOpen:0x%i)", mr); - dwFlag = CALLBACK_FUNCTION; - mr = waveOutOpen (&(device->waveoutdev), WAVE_MAPPER, &(device->wfx), (DWORD) SpeakerCallback, - (DWORD)device, dwFlag); - } - if (mr != NOERROR) - { - ms_warning("Failed to open windows sound device. (waveOutOpen:0x%i)", mr); - return -1; - } - -#if 0 -#define MM_WOM_SETSECONDARYGAINCLASS (WM_USER) -#define MM_WOM_SETSECONDARYGAINLIMIT (WM_USER+1) -#define MM_WOM_FORCESPEAKER (WM_USER+2) - - bool bSpeaker=TRUE; - mr = waveOutMessage(device->waveoutdev, MM_WOM_FORCESPEAKER, bSpeaker, 0); - if (mr != NOERROR) - { - ms_warning("Failed to use earphone. (waveOutMessage:0x%i)", mr); - return -1; - } - - typedef HRESULT (* _SetSpeakerMode)(DWORD mode); - _SetSpeakerMode pfnSetSpeakerMode; - - HINSTANCE hDll = LoadLibrary(L"\\windows\\ossvcs.dll"); - //_debug(L"ossvcs.dll h=%X",hDll); - pfnSetSpeakerMode = (_SetSpeakerMode)GetProcAddress(hDll,(LPCTSTR)218); - if (pfnSetSpeakerMode) - { - //_debug(L"SetSpeakerMode imported."); - DWORD sm = 0; - //_debug(L"SpeakerMode set to %d", sm); - pfnSetSpeakerMode(sm); - } - //else - //_debug(L"pfnSetSpeakerMode import failed."); - FreeLibrary(hDll); -#endif - -#ifdef CONTROLVOLUME - mr = waveOutGetVolume(device->waveoutdev, &device->dwOldVolume); - if (mr != NOERROR) - { - ms_warning("Failed to get volume device. (waveOutGetVolume:0x%i)", mr); - } - - mr = waveOutSetVolume(device->waveoutdev, 0xFFFFFFFF); - if (mr != NOERROR) - { - ms_warning("Failed to set volume device. (waveOutSetVolume:0x%i)", mr); - } -#endif - - /* prepare windows buffers */ - - for (i = 0; i < MAX_WAVEHDR; i++) - { - memset (&(device->waveouthdr[i]), 0, sizeof (device->waveouthdr[i])); - device->waveouthdr[i].lpData = device->waveoutbuffer[i]; - /* BUG: on ne connait pas la taille des frames a recevoir... - on utilise enc_frame_per_packet au lien de dec_frame_per_packet */ - - device->waveouthdr[i].dwBufferLength = device->rate/8000 * WINSND_BUFLEN; - /* 480 pour 98 (speex) */ - device->waveouthdr[i].dwFlags = 0; - device->waveouthdr[i].dwUser = i; - - mr = waveOutPrepareHeader (device->waveoutdev, &(device->waveouthdr[i]), - sizeof (device->waveouthdr[i])); - if (mr != MMSYSERR_NOERROR){ - ms_warning("Failed to prepare windows sound device. (waveOutPrepareHeader:0x%i)", mr); - } - else - { - ms_message("Sound Header prepared %i for windows sound device. (waveOutPrepareHeader)", i); - } - } - - - /* Init Microphone device */ - dwFlag = CALLBACK_FUNCTION; - if (devnumber != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveInOpen (&(device->waveindev), devnumber, &(device->wfx), - (DWORD) WaveInCallback, (DWORD)device, dwFlag); - if (mr != NOERROR) - { - ms_warning("Failed to open device: trying default device. (waveInOpen:0x%i)", mr); - dwFlag = CALLBACK_FUNCTION; - mr = waveInOpen (&(device->waveindev), WAVE_MAPPER, &(device->wfx), - (DWORD) WaveInCallback, (DWORD)device, dwFlag); - } - - if (mr != NOERROR) - { - ms_warning("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - return -1; - } - - - - for (i = 0; i < MAX_WAVEHDR; i++) - { - memset (&(device->waveinhdr[i]), 0, sizeof (device->waveinhdr[i])); - device->waveinhdr[i].lpData = device->waveinbuffer[i]; - /* frameSize */ - device->waveinhdr[i].dwBufferLength = device->rate/8000 * WINSND_BUFLEN; - device->waveinhdr[i].dwFlags = 0; - device->waveinhdr[i].dwUser = i; - mr = waveInPrepareHeader (device->waveindev, &(device->waveinhdr[i]), - sizeof (device->waveinhdr[i])); - if (mr == MMSYSERR_NOERROR){ - mr = waveInAddBuffer (device->waveindev, &(device->waveinhdr[i]), - sizeof (device->waveinhdr[i])); - if (mr == MMSYSERR_NOERROR) - { - ms_message("Sound Header prepared %i for windows sound device. (waveInAddBuffer)", i); - } - else - { - ms_warning("Failed to prepare windows sound device. (waveInAddBuffer:0x%i)", mr); - } - } - else - { - ms_warning("Failed to prepare windows sound device. (waveInPrepareHeader:0x%i)", mr); - } - } - -#ifndef DISABLE_SPEEX -#if 0 - device->pst = speex_preprocess_state_init((device->rate/8000 * 320)/2, device->rate); - if (device->pst!=NULL) { - float f; - i=1; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_VAD, &i); - i=1; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=0; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_AGC, &i); - f=8000; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); - i=0; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB, &i); - f=.4; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=.3; - speex_preprocess_ctl(device->pst, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - } -#endif -#endif - - mr = waveInStart (device->waveindev); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("Failed to start recording on windows sound device. (waveInStart:0x%i)", mr); - return -1; - } - - *minsz=device->rate/8000 * 320; - return 0; -} - -static void winsnd_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent) -{ - WinSndData *d=(WinSndData*)card->data; - MMRESULT mr = NOERROR; - DWORD dwVolume = 0xFFFF; - dwVolume = ((0xFFFF) * percent) / 100; - - if (d->mixdev==NULL) return; - switch(e){ - case MS_SND_CARD_MASTER: - mr = waveOutSetVolume(d->waveoutdev, dwVolume); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("Failed to set master volume. (waveOutSetVolume:0x%i)", mr); - return; - } - return; - break; -#if 0 - case MS_SND_CARD_CAPTURE: - wincmd=SOUND_MIXER_IGAIN; - break; - case MS_SND_CARD_PLAYBACK: - wincmd=SOUND_MIXER_PCM; - break; -#endif - default: - ms_warning("winsnd_card_set_level: unsupported command."); - return; - } -} - -static int winsnd_get_level(MSSndCard *card, MSSndCardMixerElem e) -{ - WinSndData *d=(WinSndData*)card->data; - MMRESULT mr = NOERROR; - DWORD dwVolume = 0x0000; - - if (d->mixdev==NULL) return -1; - switch(e){ - case MS_SND_CARD_MASTER: - mr=waveOutGetVolume(d->waveoutdev, &dwVolume); - // Transform to 0 to 100 scale - //dwVolume = (dwVolume *100) / (0xFFFF); - return 60; - break; -#if 0 - case MS_SND_CARD_CAPTURE: - osscmd=SOUND_MIXER_IGAIN; - break; - case MS_SND_CARD_PLAYBACK: - osscmd=SOUND_MIXER_PCM; - break; -#endif - default: - ms_warning("winsnd_card_get_level: unsupported command."); - return -1; - } - return -1; -} - -static void winsnd_set_source(MSSndCard *card, MSSndCardCapture source) -{ - WinSndData *d=(WinSndData*)card->data; - if (d->mixdev==NULL) return; - - switch(source){ - case MS_SND_CARD_MIC: - break; - case MS_SND_CARD_LINE: - break; - } -} - -static void winsnd_init(MSSndCard *card){ - WinSndData *d=(WinSndData*)ms_new(WinSndData,1); - memset(d, 0, sizeof(WinSndData)); - d->bytes_read=0; - d->pcmdev=NULL; - d->mixdev=NULL; - d->sound_err=-1; /* not opened */ - d->read_started=FALSE; - d->write_started=FALSE; - d->bits=16; - d->rate=8000; - d->stereo=FALSE; - qinit(&d->rq); - d->bufferizer=ms_bufferizer_new(); - ms_mutex_init(&d->mutex,NULL); - card->data=d; -#ifndef DISABLE_SPEEX - d->pst=0; -#endif - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; -} - -static void winsnd_uninit(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - if (d==NULL) - return; - if (d->pcmdev!=NULL) ms_free(d->pcmdev); - if (d->mixdev!=NULL) ms_free(d->mixdev); - ms_bufferizer_destroy(d->bufferizer); - flushq(&d->rq,0); - - ms_mutex_destroy(&d->mutex); - -#ifndef DISABLE_SPEEX - if (d->pst!=NULL) - speex_preprocess_state_destroy(d->pst); -#endif - - ms_free(d); -} - -#define DSP_NAME "/dev/dsp" -#define MIXER_NAME "/dev/mixer" - -static void winsnd_detect(MSSndCardManager *m); -static MSSndCard *winsnd_dup(MSSndCard *obj); - -MSSndCardDesc winsnd_card_desc={ - "WINSND", - winsnd_detect, - winsnd_init, - winsnd_set_level, - winsnd_get_level, - winsnd_set_source, - NULL, - NULL, - ms_winsnd_read_new, - ms_winsnd_write_new, - winsnd_uninit, - winsnd_dup -}; - -static MSSndCard *winsnd_dup(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - WinSndData *dcard=(WinSndData*)card->data; - WinSndData *dobj=(WinSndData*)obj->data; - dcard->pcmdev=ms_strdup(dobj->pcmdev); - dcard->mixdev=ms_strdup(dobj->mixdev); - dcard->devid=dobj->devid; - card->name=ms_strdup(obj->name); - return card; -} - -static MSSndCard *winsnd_card_new(const char *pcmdev, const char *mixdev, int id){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - WinSndData *d=(WinSndData*)card->data; - d->pcmdev=ms_strdup(pcmdev); - d->mixdev=ms_strdup(mixdev); - card->name=ms_strdup(pcmdev); - d->devid=id; - return card; -} - -static void winsnd_detect(MSSndCardManager *m){ - MMRESULT mr = NOERROR; - unsigned int nInDevices = waveInGetNumDevs (); - unsigned int item; - char pcmdev[1024]; - char mixdev[1024]; - - for (item = 0; item < nInDevices; item++) - { - WAVEINCAPS caps; - mr = waveInGetDevCaps (item, &caps, sizeof (WAVEINCAPS)); - if (mr == MMSYSERR_NOERROR) - { - MSSndCard *card; - snprintf(pcmdev,sizeof(pcmdev),"%s",caps.szPname); - snprintf(mixdev,sizeof(mixdev),"%s",caps.szPname); - if (item == 0) - { - card=winsnd_card_new(pcmdev,mixdev, item-1); - ms_snd_card_manager_add_card(m,card); - } - card=winsnd_card_new(pcmdev,mixdev, item); - ms_snd_card_manager_add_card(m,card); - } - } -#if 0 - nInDevices = mixerGetNumDevs (); - for (item = 0; item < nInDevices; item++) - { - MIXERCAPS caps; - mr = mixerGetDevCaps (item, &caps, sizeof (MIXERCAPS)); - if (mr == MMSYSERR_NOERROR) - { - snprintf(pcmdev,sizeof(pcmdev),"%s",caps.szPname); - snprintf(mixdev,sizeof(mixdev),"%s",caps.szPname); - } - } -#endif -} - -static void * winsnd_thread(void *p){ - MSSndCard *card=(MSSndCard*)p; - WinSndData *d=(WinSndData*)card->data; - int bsize=d->rate/8000 * 320; - uint8_t *rtmpbuff=NULL; - uint8_t *wtmpbuff=NULL; - int err; - - MMRESULT mr = NOERROR; - int pos_whdr=0; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->sound_err=winsnd_open(d, d->devid, d->bits,d->stereo,d->rate,&bsize); - if (d->sound_err==0){ - rtmpbuff=(uint8_t*)alloca(bsize); - wtmpbuff=(uint8_t*)alloca(bsize); - } - while(d->read_started || d->write_started){ - if (d->sound_err==0){ - if (d->write_started){ -#if 0 - if (d->stat_output>0 && d->buffer_playing==0) - { - ms_error("No data currently playing in sound card" ); - } - if (d->stat_output>0 && (d->stat_input-d->stat_output>10 || d->stat_input-d->stat_output<-10)) - ms_error("Not perfectly synchronized (input-output=%i)", d->stat_input-d->stat_output); -#endif - - while (d->buffer_playing<6 && d->buffer_playingmutex); - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - ms_mutex_unlock(&d->mutex); - if (err!=bsize) - break; - - ms_mutex_lock(&d->mutex); - /* write to sound devide! */ - memcpy (d->waveouthdr[pos_whdr].lpData, wtmpbuff, bsize); - - mr = waveOutWrite (d->waveoutdev, - &(d->waveouthdr[pos_whdr]), - sizeof (d->waveouthdr[pos_whdr])); - - if (mr != MMSYSERR_NOERROR) - { - if (mr == WAVERR_STILLPLAYING) - { - /* retry later */ - /* data should go back to queue */ - /* TODO */ - ms_warning("sound device write STILL_PLAYING (waveOutWrite:0x%i)", mr); - } - else - { - ms_warning("sound device write returned (waveOutWrite:0x%i)", mr); - } - } - else - { - d->buffer_playing++; - pos_whdr++; - if (pos_whdr == MAX_WAVEHDR) - pos_whdr = 0; /* loop over the prepared blocks */ - } - ms_mutex_unlock(&d->mutex); - - - if (err<0){ -#if !defined(_WIN32_WCE) - ms_warning("Fail to write %i bytes from soundcard: %s", - bsize,strerror(errno)); -#else - ms_warning("Fail to write %i bytes from soundcard: %i", - bsize,WSAGetLastError()); -#endif - } - } - - if (d->buffer_playing==6 || d->buffer_playing==MAX_WAVEHDR) - { - int discarded=0; - ms_mutex_lock(&d->mutex); - while (d->bufferizer->size>=bsize){ - discarded++; - d->stat_notplayed++; - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - } - ms_mutex_unlock(&d->mutex); - if (discarded>0) - ms_error("Extra data for sound card removed (%ims), (playing: %i) (input-output: %i)", (discarded*20*320)/320, d->buffer_playing, d->stat_input - d->stat_output); - } -#if !defined(_WIN32_WCE) - Sleep(5); -#endif -#if defined(_WIN32_WCE) - Sleep(10); -#endif - }else { - int discarded=0; - /* don't think this is usefull, anyway... */ - ms_mutex_lock(&d->mutex); - while (d->bufferizer->size>=bsize){ - discarded++; - err=ms_bufferizer_read(d->bufferizer,wtmpbuff,bsize); - } - ms_mutex_unlock(&d->mutex); - if (discarded>0) - ms_error("Extra data for sound card removed (%ims), (playing: %i) (input-output: %i)", (discarded*20)/320, d->buffer_playing, d->stat_input - d->stat_output); - Sleep(10); - } - }else Sleep(10); - } - if (d->sound_err==0) { - int i; - int count=0; - /* close sound card */ - ms_error("Shutting down sound device (playing: %i) (input-output: %i) (notplayed: %i)", d->buffer_playing, d->stat_input - d->stat_output, d->stat_notplayed); - - /* unprepare buffer */ - for (i = 0; i < MAX_WAVEHDR; i++) - { - int counttry=0; - for (counttry=0;counttry<10;counttry++) - { - mr = waveInUnprepareHeader (d->waveindev, - &(d->waveinhdr[i]), - sizeof (d->waveinhdr[i])); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to unprepared %i buffer from sound card (waveInUnprepareHeader:0x%i", count, mr); - Sleep (20); - } else - { - count++; - ms_message("successfully unprepared %i buffer from sound card.", count); - break; - } - } - } - ms_warning("unprepared %i buffer from sound card.", count); - - mr = waveInStop (d->waveindev); - if (mr != MMSYSERR_NOERROR) - { - ms_error("failed to stop recording sound card (waveInStop:0x%i)", mr); - } else - { - ms_message("successfully stopped recording sound card"); - } - - mr = waveInReset (d->waveindev); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("failed to reset recording sound card (waveInReset:0x%i)", mr); - } else - { - ms_message("successful reset of recording sound card"); - } - - mr = waveInClose (d->waveindev); - if (mr != MMSYSERR_NOERROR) - { - ms_warning("failed to close recording sound card (waveInClose:0x%i)", mr); - } else - { - ms_message("successfully closed recording sound card"); - } - d->sound_err=-1; - } - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - return NULL; -} - -static void winsnd_start_r(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - if (d->read_started==FALSE && d->write_started==FALSE){ - d->read_started=TRUE; - ms_thread_create(&d->thread,NULL,winsnd_thread,card); - }else d->read_started=TRUE; -} - -static void winsnd_stop_r(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - d->read_started=FALSE; - if (d->write_started==FALSE){ - ms_thread_join(d->thread,NULL); - } -} - -static void winsnd_start_w(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - if (d->read_started==FALSE && d->write_started==FALSE){ - d->write_started=TRUE; - ms_thread_create(&d->thread,NULL,winsnd_thread,card); - }else{ - d->write_started=TRUE; - } -} - -static void winsnd_stop_w(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - d->write_started=FALSE; - if (d->read_started==FALSE){ - ms_thread_join(d->thread,NULL); - } -#ifdef CONTROLVOLUME - waveOutSetVolume(d->waveoutdev, d->dwOldVolume); -#endif -} - -static mblk_t *winsnd_get(MSSndCard *card){ - WinSndData *d=(WinSndData*)card->data; - mblk_t *m; - ms_mutex_lock(&d->mutex); - m=getq(&d->rq); - ms_mutex_unlock(&d->mutex); - return m; -} - -static void winsnd_put(MSSndCard *card, mblk_t *m){ - WinSndData *d=(WinSndData*)card->data; - ms_mutex_lock(&d->mutex); - ms_bufferizer_put(d->bufferizer,m); - ms_mutex_unlock(&d->mutex); -} - - -static void winsnd_read_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - winsnd_start_r(card); - ms_ticker_set_time_func(f->ticker,winsnd_get_cur_time,card->data); -} - -static void winsnd_read_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - ms_ticker_set_time_func(f->ticker,NULL,NULL); - winsnd_stop_r(card); -} - -static void winsnd_read_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - while((m=winsnd_get(card))!=NULL){ - ms_queue_put(f->outputs[0],m); - } -} - -static void winsnd_write_preprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - winsnd_start_w(card); -} - -static void winsnd_write_postprocess(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - winsnd_stop_w(card); -} - -static void winsnd_write_process(MSFilter *f){ - MSSndCard *card=(MSSndCard*)f->data; - mblk_t *m; - - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - winsnd_put(card,m); - } -} - -static int set_rate(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - WinSndData *d=(WinSndData*)card->data; - d->rate=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - WinSndData *d=(WinSndData*)card->data; - d->stereo=(*((int*)arg)==2); - return 0; -} - -static int winsnd_get_stat_input(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - WinSndData *d=(WinSndData*)card->data; - - return d->stat_input; -} - -static int winsnd_get_stat_ouptut(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - WinSndData *d=(WinSndData*)card->data; - - return d->stat_output; -} - -static int winsnd_get_stat_discarded(MSFilter *f, void *arg){ - MSSndCard *card=(MSSndCard*)f->data; - WinSndData *d=(WinSndData*)card->data; - - return d->stat_notplayed; -} - -static MSFilterMethod winsnd_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { MS_FILTER_GET_STAT_INPUT, winsnd_get_stat_input }, - { MS_FILTER_GET_STAT_OUTPUT, winsnd_get_stat_ouptut }, - { MS_FILTER_GET_STAT_DISCARDED, winsnd_get_stat_discarded }, - { 0 , NULL } -}; - -MSFilterDesc winsnd_read_desc={ - MS_WINSND_READ_ID, - "MSWinSndRead", - "Sound capture filter for Windows Sound drivers", - MS_FILTER_OTHER, - NULL, - 0, - 1, - NULL, - winsnd_read_preprocess, - winsnd_read_process, - winsnd_read_postprocess, - NULL, - winsnd_methods -}; - - -MSFilterDesc winsnd_write_desc={ - MS_WINSND_WRITE_ID, - "MSWinSndWrite", - "Sound playback filter for Windows Sound drivers", - MS_FILTER_OTHER, - NULL, - 1, - 0, - NULL, - winsnd_write_preprocess, - winsnd_write_process, - winsnd_write_postprocess, - NULL, - winsnd_methods -}; - -MSFilter *ms_winsnd_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_read_desc); - f->data=card; - return f; -} - - -MSFilter *ms_winsnd_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_write_desc); - f->data=card; - return f; -} - -MS_FILTER_DESC_EXPORT(winsnd_read_desc) -MS_FILTER_DESC_EXPORT(winsnd_write_desc) diff --git a/linphone/mediastreamer2/src/winsnd2.c b/linphone/mediastreamer2/src/winsnd2.c deleted file mode 100755 index 56c8d404c..000000000 --- a/linphone/mediastreamer2/src/winsnd2.c +++ /dev/null @@ -1,1593 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifndef UNICODE -#define UNICODE -#endif - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" - -#include -#ifdef _MSC_VER -#include -#endif -#include - -#if defined(_WIN32_WCE) -/*#define DISABLE_SPEEX */ -/*#define WCE_OPTICON_WORKAROUND 1000 */ -#endif -#ifndef DISABLE_SPEEX -#include -#endif - -#define WINSND_NBUFS 10 -#define WINSND_OUT_NBUFS 20 -#define WINSND_NSAMPLES 160 -#define WINSND_MINIMUMBUFFER 5 - -static MSFilter *ms_winsnd_read_new(MSSndCard *card); -static MSFilter *ms_winsnd_write_new(MSSndCard *card); - -typedef struct WinSndCard{ - int in_devid; - int out_devid; - int removed; -}WinSndCard; - -static void winsndcard_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent){ - WinSndCard *d=(WinSndCard*)card->data; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_UNSIGNED mcdu = {0}; - - MMRESULT mr = MMSYSERR_NOERROR; - DWORD dwVolume = ((0xFFFF) * percent) / 100; - - WORD wLeftVol, wRightVol; - DWORD dwNewVol; - wLeftVol = LOWORD(dwVolume); // get higher WORD - wRightVol = LOWORD(dwVolume); // get lower WORD - - dwNewVol = MAKELONG(wLeftVol, wRightVol); - - switch(e){ - case MS_SND_CARD_PLAYBACK: - case MS_SND_CARD_MASTER: - { - mr = mixerGetID( (HMIXEROBJ)d->out_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_level: mixerGetID failed. (0x%x)", mr); - return; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerOpen failed. (0x%x)", mr); - return; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - - mcdu.dwValue = 65535*percent/100; /* the volume is a number between 0 and 65535 */ - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_level: mixerSetControlDetails failed. (0x%x)", mr); - return; - } - } - break; - case MS_SND_CARD_CAPTURE: - mr = mixerGetID( (HMIXEROBJ)d->in_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_level: mixerGetID failed. (0x%x)", mr); - return; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - if (mr == MMSYSERR_NOERROR) - { - mcdu.dwValue = 65535*percent/100; /* the volume is a number between 0 and 65535 */ - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr == MMSYSERR_NOERROR) - { - return; - } - ms_error("winsndcard_set_level: mixerSetControlDetails failed. (0x%x)", mr); - ms_warning("winsndcard_set_level: control the SRC_MICROPHONE instead"); - } - else - { - ms_error("winsndcard_set_level: mixerGetLineControls failed. (0x%x)", mr); - ms_warning("winsndcard_set_level: control the SRC_MICROPHONE instead"); - } - - /* In case capture doesn't work: use the SRC_MICROPHONE volume */ - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_VOLUME, 1, sizeof(MIXERCONTROL), pmxctrl}; - if(!mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, - MIXER_GETLINECONTROLSF_ONEBYTYPE)){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_UNSIGNED pUnsigned; - MIXERCONTROLDETAILS mxcd; - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pUnsigned = - (LPMIXERCONTROLDETAILS_UNSIGNED) - malloc(cChannels * sizeof(MIXERCONTROLDETAILS_UNSIGNED)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mxcd.paDetails = (LPVOID) pUnsigned; - - mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - pUnsigned[0].dwValue = pUnsigned[cChannels - 1].dwValue - = pmxctrl->Bounds.dwMaximum*percent/100; - mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - free(pmxctrl); - free(pUnsigned); - } - else - free(pmxctrl); - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_level: mixerClose failed. (0x%x)", mr); - return; - } - break; - default: - ms_warning("winsnd_card_set_level: unsupported command."); - } -} - -static int winsndcard_get_level(MSSndCard *card, MSSndCardMixerElem e){ - WinSndCard *d=(WinSndCard*)card->data; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_UNSIGNED mcdu = {0}; - - MMRESULT mr = MMSYSERR_NOERROR; - int percent; - - switch(e){ - case MS_SND_CARD_MASTER: - case MS_SND_CARD_PLAYBACK: - { - mr = mixerGetID( (HMIXEROBJ)d->out_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_get_level: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerGetLineControls failed. (0x%x)", mr); - return -1; - } - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (mcdu.dwValue *100) / (mc.Bounds.dwMaximum); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerGetControlDetails failed. (0x%x)", mr); - return -1; - } - return percent; - } - break; - case MS_SND_CARD_CAPTURE: - mr = mixerGetID( (HMIXEROBJ)d->in_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_get_level: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if (mr == MMSYSERR_NOERROR) - { - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (mcdu.dwValue *100) / (mc.Bounds.dwMaximum); - - if (mr == MMSYSERR_NOERROR) - { - return percent; - } - ms_error("winsndcard_get_level: mixerGetControlDetails failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - else - { - ms_error("winsndcard_get_level: mixerGetLineControls failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_VOLUME, 1, sizeof(MIXERCONTROL), pmxctrl}; - if(!mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, - MIXER_GETLINECONTROLSF_ONEBYTYPE)){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_UNSIGNED pUnsigned; - MIXERCONTROLDETAILS mxcd; - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pUnsigned = - (LPMIXERCONTROLDETAILS_UNSIGNED) - malloc(cChannels * sizeof(MIXERCONTROLDETAILS_UNSIGNED)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mxcd.paDetails = (LPVOID) pUnsigned; - - mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (pUnsigned[0].dwValue *100) / (pmxctrl->Bounds.dwMaximum); - free(pmxctrl); - free(pUnsigned); - } - else - free(pmxctrl); - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerClose failed. (0x%x)", mr); - return -1; - } - return percent; - break; - default: - ms_warning("winsndcard_get_level: unsupported command."); - return -1; - } - return -1; -} - -static void winsndcard_set_source(MSSndCard *card, MSSndCardCapture source){ - - switch(source){ - case MS_SND_CARD_MIC: - break; - case MS_SND_CARD_LINE: - break; - } -} - -static int winsndcard_set_control(MSSndCard *card, MSSndCardControlElem e, int val){ - WinSndCard *d=(WinSndCard*)card->data; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_BOOLEAN bMute; - - MMRESULT mr = MMSYSERR_NOERROR; - - switch(e){ - case MS_SND_CARD_CAPTURE_MUTE: - - bMute.fValue = (val>0); - - mr = mixerGetID( (HMIXEROBJ)d->in_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_control: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - /* unmute */ - /* Find a mute control, if any, of the microphone line */ - - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_MUTE, 1, sizeof(MIXERCONTROL), pmxctrl}; - if(!mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, MIXER_GETLINECONTROLSF_ONEBYTYPE)){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_BOOLEAN pbool; - MIXERCONTROLDETAILS mxcd; - - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pbool = (LPMIXERCONTROLDETAILS_BOOLEAN) malloc(cChannels * sizeof( - MIXERCONTROLDETAILS_BOOLEAN)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); - mxcd.paDetails = (LPVOID) pbool; - - mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - /* Unmute the microphone line (for both channels) */ - pbool[0].fValue = pbool[cChannels - 1].fValue = val; /* 0 -> unmute; */ - mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - free(pmxctrl); - free(pbool); - } - else - free(pmxctrl); - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_control: mixerClose failed. (0x%x)", mr); - return -1; - } - return 0; - - case MS_SND_CARD_MASTER_MUTE: - case MS_SND_CARD_PLAYBACK_MUTE: - { - bMute.fValue = (val>0); - - mr = mixerGetID( (HMIXEROBJ)d->out_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_control: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER_MUTE==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerSetControlDetails failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE; //MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &bMute; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_control: mixerSetControlDetails failed. (0x%x)", mr); - return -1; - } - return 0; - } - break; - default: - ms_warning("winsndcard_set_control: unsupported command."); - } - return -1; -} - -static int winsndcard_get_control(MSSndCard *card, MSSndCardControlElem e){ - WinSndCard *d=(WinSndCard*)card->data; - return -1; -} - -static void winsndcard_init(MSSndCard *card){ - WinSndCard *c=(WinSndCard *)ms_new(WinSndCard,1); - c->removed=0; - card->data=c; -} - -static void winsndcard_uninit(MSSndCard *card){ - ms_free(card->data); -} - -static void winsndcard_detect(MSSndCardManager *m); -static MSSndCard *winsndcard_dup(MSSndCard *obj); -static void winsndcard_unload(MSSndCardManager *m); - -MSSndCardDesc winsnd_card_desc={ - "MME", - winsndcard_detect, - winsndcard_init, - winsndcard_set_level, - winsndcard_get_level, - winsndcard_set_source, - winsndcard_set_control, - winsndcard_get_control, - ms_winsnd_read_new, - ms_winsnd_write_new, - winsndcard_uninit, - winsndcard_dup, - winsndcard_unload -}; - -static MSSndCard *winsndcard_dup(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - card->name=ms_strdup(obj->name); - card->data=ms_new(WinSndCard,1); - memcpy(card->data,obj->data,sizeof(WinSndCard)); - return card; -} - -static MSSndCard *winsndcard_new(const char *name, int in_dev, int out_dev, unsigned cap){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - WinSndCard *d=(WinSndCard*)card->data; - card->name=ms_strdup(name); - d->in_devid=in_dev; - d->out_devid=out_dev; - card->capabilities=cap; - return card; -} - -static void add_or_update_card(MSSndCardManager *m, const char *name, int indev, int outdev, unsigned int capability){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsnd_card_desc.driver_type)==0 - && strcmp(card->name,name)==0){ - /*update already entered card */ - WinSndCard *d=(WinSndCard*)card->data; - card->capabilities|=capability; - if (indev!=-1) - d->in_devid=indev; - if (outdev!=-1) - d->out_devid=outdev; - d->removed=0; - return; - } - } - /* add this new card:*/ - ms_snd_card_manager_add_card(m,winsndcard_new(name,indev,outdev,capability)); -} - - -static void _winsndcard_detect(MSSndCardManager *m){ - MMRESULT mr = NOERROR; - unsigned int nOutDevices = waveOutGetNumDevs (); - unsigned int nInDevices = waveInGetNumDevs (); - unsigned int item; - - if (nOutDevices>nInDevices) - nInDevices = nOutDevices; - - for (item = 0; item < nInDevices; item++){ - - WAVEINCAPS incaps; - WAVEOUTCAPS outcaps; - mr = waveInGetDevCaps (item, &incaps, sizeof (WAVEINCAPS)); - if (mr == MMSYSERR_NOERROR) - { -#if defined(_WIN32_WCE) - char card[256]; - snprintf(card, sizeof(card), "Input card %i", item); - add_or_update_card(m,card,item,-1,MS_SND_CARD_CAP_CAPTURE); - /* _tprintf(L"new card: %s", incaps.szPname); */ -#else - char szName[256]; - WideCharToMultiByte(CP_UTF8,0,incaps.szPname,-1,szName,256,0,0); - add_or_update_card(m,szName,item,-1,MS_SND_CARD_CAP_CAPTURE); -#endif - } - mr = waveOutGetDevCaps (item, &outcaps, sizeof (WAVEOUTCAPS)); - if (mr == MMSYSERR_NOERROR) - { -#if defined(_WIN32_WCE) - char card[256]; - snprintf(card, sizeof(card), "Output card %i", item); - add_or_update_card(m,card,-1,item,MS_SND_CARD_CAP_PLAYBACK); - /* _tprintf(L"new card: %s", outcaps.szPname); */ -#else - char szName[256]; - WideCharToMultiByte(CP_UTF8,0,outcaps.szPname,-1,szName,256,0,0); - add_or_update_card(m,szName,-1,item,MS_SND_CARD_CAP_PLAYBACK); -#endif - } - } -} - -static void deactivate_removed_cards(MSSndCardManager *m){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsnd_card_desc.driver_type)==0){ - /*mark all cards as potentially removed, detect will check them immediately after */ - WinSndCard *d=(WinSndCard*)card->data; - if (d->removed) card->capabilities=0; - } - } -} - -static void mark_as_removed(MSSndCardManager *m){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsnd_card_desc.driver_type)==0){ - /*mark all cards as potentially removed, detect will check them immediately after */ - WinSndCard *d=(WinSndCard*)card->data; - d->removed=1; - } - } -} - -static ms_thread_t poller_thread=NULL; -static bool_t poller_running=TRUE; - -static void * new_device_polling_thread(void *ignore){ - MSSndCardManager *m; - /*check for new devices every 5 seconds*/ - while(poller_running){ - ms_sleep(5); - if (poller_running){ - m=ms_snd_card_manager_get(); - if(!m) break; - mark_as_removed(m); - _winsndcard_detect(m); - deactivate_removed_cards(m); - } - } - return NULL; -} - -static void stop_poller(){ - poller_running=FALSE; - ms_thread_join(poller_thread,NULL); - poller_thread=NULL; -} - -static void winsndcard_unload(MSSndCardManager *m){ - stop_poller(); -} - -static void winsndcard_detect(MSSndCardManager *m){ - _winsndcard_detect(m); - if (poller_thread==NULL) - ms_thread_create(&poller_thread,NULL,new_device_polling_thread,NULL); -} - -typedef struct WinSnd{ - int dev_id; - HWAVEIN indev; - HWAVEOUT outdev; - WAVEFORMATEX wfx; - WAVEHDR hdrs_read[WINSND_NBUFS]; - WAVEHDR hdrs_write[WINSND_OUT_NBUFS]; - queue_t rq; - ms_mutex_t mutex; - uint64_t bytes_read; - unsigned int nbufs_playing; - bool_t running; - - int32_t stat_input; - int32_t stat_output; - int32_t stat_notplayed; - - int32_t stat_minimumbuffer; - - queue_t write_rq; -#ifndef DISABLE_SPEEX - SpeexPreprocessState *pst; - int pst_frame_size; -#endif - int ready; - int workaround; /* workaround for opticon audio device */ -}WinSnd; - -static void winsnd_apply_settings(WinSnd *d){ - d->wfx.nBlockAlign=d->wfx.nChannels*d->wfx.wBitsPerSample/8; - d->wfx.nAvgBytesPerSec=d->wfx.nSamplesPerSec*d->wfx.nBlockAlign; -} - - -/*#define _TRUE_TIME*/ -#ifndef _TRUE_TIME -static uint64_t winsnd_get_cur_time( void *data){ - WinSnd *d=(WinSnd*)data; - uint64_t curtime=(d->bytes_read*1000)/(uint64_t)d->wfx.nAvgBytesPerSec; - /* ms_debug("winsnd_get_cur_time: bytes_read=%u return %lu\n",d->bytes_read,(unsigned long)curtime); */ - return curtime; -} -#endif - - -static void winsnd_init(MSFilter *f){ - WinSnd *d=(WinSnd *)ms_new0(WinSnd,1); - d->wfx.wFormatTag = WAVE_FORMAT_PCM; - d->wfx.cbSize = 0; - d->wfx.nAvgBytesPerSec = 16000; - d->wfx.nBlockAlign = 2; - d->wfx.nChannels = 1; - d->wfx.nSamplesPerSec = 8000; - d->wfx.wBitsPerSample = 16; - qinit(&d->rq); - qinit(&d->write_rq); -#ifndef DISABLE_SPEEX - d->pst=NULL; - d->pst_frame_size=0; -#endif - d->ready=0; - d->workaround=0; - ms_mutex_init(&d->mutex,NULL); - f->data=d; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; -} - -static void winsnd_uninit(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - flushq(&d->rq,0); - flushq(&d->write_rq,0); -#ifndef DISABLE_SPEEX - if (d->pst!=NULL) - speex_preprocess_state_destroy(d->pst); - d->pst=NULL; - d->pst_frame_size=0; -#endif - d->ready=0; - d->workaround=0; - ms_mutex_destroy(&d->mutex); - ms_free(f->data); -} - -static void add_input_buffer(WinSnd *d, WAVEHDR *hdr, int buflen){ - mblk_t *m=allocb(buflen,0); - MMRESULT mr; - memset(hdr,0,sizeof(*hdr)); - if (buflen==0) ms_error("add_input_buffer: buflen=0 !"); - hdr->lpData=(LPSTR)m->b_wptr; - hdr->dwBufferLength=buflen; - hdr->dwFlags = 0; - hdr->dwUser = (DWORD)m; - mr = waveInPrepareHeader (d->indev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInPrepareHeader() error"); - return ; - } - mr=waveInAddBuffer(d->indev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInAddBuffer() error"); - return ; - } -} - -static void CALLBACK -read_callback (HWAVEIN waveindev, UINT uMsg, DWORD dwInstance, DWORD dwParam1, - DWORD dwParam2) -{ - WAVEHDR *wHdr=(WAVEHDR *) dwParam1; - MSFilter *f=(MSFilter *)dwInstance; - WinSnd *d=(WinSnd*)f->data; - mblk_t *m; - int bsize; - switch (uMsg){ - case WIM_OPEN: - ms_debug("read_callback : WIM_OPEN"); - break; - case WIM_CLOSE: - ms_debug("read_callback : WIM_CLOSE"); - break; - case WIM_DATA: - bsize=wHdr->dwBytesRecorded; - if (bsize<=0) { -#if 0 - if (d->running==TRUE) /* avoid adding buffer back when calling waveInReset */ - { - MMRESULT mr; - mr=waveInAddBuffer(d->indev,wHdr,sizeof(*wHdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInAddBuffer() error"); - return ; - } - ms_warning("read_callback : EMPTY DATA, WIM_DATA (%p,%i)",wHdr,bsize); - } - m=(mblk_t*)wHdr->dwUser; - wHdr->dwUser=0; - freemsg(m); - return; -#endif - } - - /* ms_warning("read_callback : WIM_DATA (%p,%i)",wHdr,bsize); */ - m=(mblk_t*)wHdr->dwUser; - m->b_wptr+=bsize; - wHdr->dwUser=0; - ms_mutex_lock(&d->mutex); - putq(&d->rq,m); - ms_mutex_unlock(&d->mutex); - d->bytes_read+=wHdr->dwBufferLength; - d->stat_input++; - d->stat_input++; -#ifdef WIN32_TIMERS - if (f->ticker->TimeEvent!=NULL) - SetEvent(f->ticker->TimeEvent); -#endif - break; - } -} - - -static void winsnd_read_preprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; - int bsize; - DWORD dwFlag; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; - - winsnd_apply_settings(d); - /* Init Microphone device */ - dwFlag = CALLBACK_FUNCTION | WAVE_FORMAT_DIRECT; - mr = waveInOpen (&d->indev, d->dev_id, &d->wfx, - (DWORD) read_callback, (DWORD)f, dwFlag); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - if (d->dev_id != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveInOpen (&d->indev, d->dev_id, &d->wfx, - (DWORD) read_callback, (DWORD)f, dwFlag); - } - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - mr = waveInOpen (&d->indev, WAVE_MAPPER, &d->wfx, - (DWORD) read_callback, (DWORD)f, CALLBACK_FUNCTION); - if (mr != MMSYSERR_NOERROR) - { - d->indev=NULL; - ms_error("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - return ; - } - } -#ifndef _TRUE_TIME - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f->ticker,winsnd_get_cur_time,d); - ms_mutex_unlock(&f->ticker->lock); -#endif - - bsize=WINSND_NSAMPLES*d->wfx.nAvgBytesPerSec/8000; - ms_debug("Using input buffers of %i bytes",bsize); - for(i=0;ihdrs_read[i]; - add_input_buffer(d,hdr,bsize); - } - d->running=TRUE; - mr=waveInStart(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInStart() error"); -#ifndef _TRUE_TIME - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f->ticker,NULL,NULL); - ms_mutex_unlock(&f->ticker->lock); -#endif - return ; - } -} - -static void winsnd_read_postprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; -#ifndef _TRUE_TIME - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f->ticker,NULL,NULL); - ms_mutex_unlock(&f->ticker->lock); -#endif - d->running=FALSE; - mr=waveInStop(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInStop() error"); - return ; - } - mr=waveInReset(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInReset() error"); - return ; - } - for(i=0;ihdrs_read[i]; - if (hdr->dwFlags & WHDR_PREPARED) - { - mr = waveInUnprepareHeader(d->indev,hdr,sizeof (*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInUnPrepareHeader() error"); - } - } - } - mr = waveInClose(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInClose() error"); - return ; - } - - ms_message("Shutting down sound device (playing: %i) (input-output: %i) (notplayed: %i)", d->nbufs_playing, d->stat_input - d->stat_output, d->stat_notplayed); - flushq(&d->rq,0); -} - -static void winsnd_read_process(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - mblk_t *m; - int i; - ms_mutex_lock(&d->mutex); - while((m=getq(&d->rq))!=NULL){ - ms_queue_put(f->outputs[0],m); - } - ms_mutex_unlock(&d->mutex); - for(i=0;ihdrs_read[i]; - if (hdr->dwUser==0) { - MMRESULT mr; - mr=waveInUnprepareHeader(d->indev,hdr,sizeof(*hdr)); - if (mr!=MMSYSERR_NOERROR) - ms_warning("winsnd_read_process: Fail to unprepare header!"); - add_input_buffer(d,hdr,hdr->dwBufferLength); - } - } -} - -static void CALLBACK -write_callback(HWAVEOUT outdev, UINT uMsg, DWORD dwInstance, - DWORD dwParam1, DWORD dwParam2) -{ - WAVEHDR *hdr=(WAVEHDR *) dwParam1; - WinSnd *d=(WinSnd*)dwInstance; - - switch (uMsg){ - case WOM_OPEN: - break; - case WOM_CLOSE: - case WOM_DONE: - if (hdr){ - d->nbufs_playing--; - } - if (d->stat_output==0) - { - d->stat_input=1; /* reset */ - d->stat_notplayed=0; - } - d->stat_output++; - break; - } -} - -static void winsnd_write_preprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - DWORD dwFlag; - int i; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; - - winsnd_apply_settings(d); - /* Init Microphone device */ - dwFlag = CALLBACK_FUNCTION | WAVE_FORMAT_DIRECT; - mr = waveOutOpen (&d->outdev, d->dev_id, &d->wfx, - (DWORD) write_callback, (DWORD)d, dwFlag); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to open windows sound device %i. (waveOutOpen:0x%i)",d->dev_id, mr); - if (d->dev_id != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveOutOpen (&d->outdev, d->dev_id, &d->wfx, - (DWORD) write_callback, (DWORD)d, dwFlag); - } - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to open windows sound device %i. (waveOutOpen:0x%i)",d->dev_id, mr); - mr = waveOutOpen (&d->outdev, WAVE_MAPPER, &d->wfx, - (DWORD) write_callback, (DWORD)d, CALLBACK_FUNCTION); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to open windows sound device %i. (waveOutOpen:0x%i)",d->dev_id, mr); - d->outdev=NULL; - return ; - } - } - for(i=0;ihdrs_write[i]; - hdr->dwFlags=0; - hdr->dwUser=0; - } -} - -static void winsnd_write_postprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; - if (d->outdev==NULL) return; - mr=waveOutReset(d->outdev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutReset() error"); - return ; - } - for(i=0;ihdrs_write[i]; - mblk_t *old; - if (hdr->dwFlags & WHDR_DONE){ - mr=waveOutUnprepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutUnprepareHeader error"); - } - old=(mblk_t*)hdr->dwUser; - if (old) freemsg(old); - hdr->dwUser=0; - } - } - mr=waveOutClose(d->outdev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutClose() error"); - return ; - } - ms_message("Shutting down sound device (playing: %i) (d->write_rq.q_mcount=%i) (input-output: %i) (notplayed: %i)", d->nbufs_playing, d->write_rq.q_mcount, d->stat_input - d->stat_output, d->stat_notplayed); - flushq(&d->write_rq,0); - d->ready=0; - d->workaround=0; - -#ifndef DISABLE_SPEEX - if (d->pst!=NULL) - speex_preprocess_state_destroy(d->pst); - d->pst=NULL; - d->pst_frame_size=0; -#endif -} - -static void winsnd_write_process(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - mblk_t *m,*old; - MMRESULT mr; - int i; - int discarded=0; - int possible_size=0; - - if (d->outdev==NULL) { - ms_queue_flush(f->inputs[0]); - return; - } - - while((m=ms_queue_get(f->inputs[0]))!=NULL){ - possible_size = msgdsize(m); -#ifndef DISABLE_SPEEX - if (d->pst_frame_size==0) - { - d->pst_frame_size=possible_size; - - d->pst = speex_preprocess_state_init(d->pst_frame_size/2, d->wfx.nSamplesPerSec); - if (d->pst!=NULL) { - float f; - i=1; - speex_preprocess_ctl(d->pst, SPEEX_PREPROCESS_SET_VAD, &i); - i=0; - speex_preprocess_ctl(d->pst, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=0; - speex_preprocess_ctl(d->pst, SPEEX_PREPROCESS_SET_AGC, &i); - f=8000; - speex_preprocess_ctl(d->pst, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); - i=0; - speex_preprocess_ctl(d->pst, SPEEX_PREPROCESS_SET_DEREVERB, &i); - } - } -#endif - - putq(&d->write_rq,m); - } - -#ifdef AMD_HACK - /* too many sound card are crappy on windows... */ - d->stat_minimumbuffer=15; - if (d->wfx.nSamplesPerSec>=32000) /* better results for high rates */ - d->stat_minimumbuffer=8; -#endif - - if (d->wfx.nSamplesPerSec>=32000) /* better results for high rates */ - { - if (d->nbufs_playing+d->write_rq.q_mcount<4) - { - d->ready=0; - } - } - else - { - if (d->nbufs_playing+d->write_rq.q_mcount<7) - { - d->ready=0; - } - } -#if defined(WCE_OPTICON_WORKAROUND) - if (d->workaround==0) - { - d->workaround=1; - Sleep(WCE_OPTICON_WORKAROUND); - } -#endif - - while((m=peekq(&d->write_rq))!=NULL){ - -#ifndef DISABLE_SPEEX - int vad=1; - if (d->pst!=NULL && msgdsize(m)==d->pst_frame_size && d->pst_frame_size<=4096) - { - char tmp[4096]; - memcpy(tmp, m->b_rptr, msgdsize(m)); - vad = speex_preprocess(d->pst, (short*)tmp, NULL); - - if (d->ready==0) - { - if (vad==0) - { - int missing; - missing = 10 - d->write_rq.q_mcount - d->nbufs_playing; - if (d->wfx.nSamplesPerSec>=32000) /* better results for high rates */ - missing = 6 - d->write_rq.q_mcount - d->nbufs_playing; - - ms_message("WINSND trouble: inserting %i silence", missing); - while(missing>0) - { - old=dupb(m); - putq(&d->write_rq,old); - missing--; - } - } - d->ready=1; - } - } -#else - if (d->ready==0) - { - int missing; - missing = 10 - d->write_rq.q_mcount - d->nbufs_playing; - if (d->wfx.nSamplesPerSec>=32000) /* better results for high rates */ - missing = 6 - d->write_rq.q_mcount - d->nbufs_playing; - ms_message("WINSND trouble: inserting %i silence", missing); - while(missing>0) - { - old=dupb(m); - putq(&d->write_rq,old); - missing--; - } - d->ready=1; - } -#endif - - for(i=0;istat_minimumbuffer;++i){ - WAVEHDR *hdr=&d->hdrs_write[i]; - if (hdr->dwFlags & WHDR_DONE){ - old=(mblk_t*)hdr->dwUser; - mr=waveOutUnprepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutUnprepareHeader error"); - } - freemsg(old); - hdr->dwUser=0; - } - if (hdr->dwUser==0){ - hdr->lpData=(LPSTR)m->b_rptr; - hdr->dwBufferLength=msgdsize(m); - hdr->dwFlags = 0; - hdr->dwUser = (DWORD)m; - mr = waveOutPrepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutPrepareHeader() error"); - getq(&d->write_rq); - freemsg(m); - discarded++; - d->stat_notplayed++; - break; - } - mr=waveOutWrite(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutWrite() error"); - getq(&d->write_rq); - freemsg(m); - discarded++; - d->stat_notplayed++; - break; - }else { - getq(&d->write_rq); - d->nbufs_playing++; - /* ms_debug("waveOutWrite() done"); */ - } - break; - } - } - if (i==d->stat_minimumbuffer){ - /* ms_error("winsnd_write_process: All buffers are busy."); */ -#ifndef DISABLE_SPEEX - if (d->pst==NULL) - { - /* initial behavior (detection in process?) */ - getq(&d->write_rq); - freemsg(m); - discarded++; - d->stat_notplayed++; - } - else - { - if (vad==0) - { - getq(&d->write_rq); - freemsg(m); - ms_message("WINSND trouble: silence removed"); - discarded++; - d->stat_notplayed++; - } - } -#else - getq(&d->write_rq); - freemsg(m); - discarded++; - d->stat_notplayed++; -#endif - - break; - } - } -} - -static int get_rate(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - *((int*)arg)=d->wfx.nSamplesPerSec; - return 0; -} - -static int set_rate(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - d->wfx.nSamplesPerSec=*((int*)arg); - d->wfx.nSamplesPerSec=44100; - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - d->wfx.nChannels=*((int*)arg); - return 0; -} - -static int winsnd_get_stat_input(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - return d->stat_input; -} - -static int winsnd_get_stat_ouptut(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - - return d->stat_output; -} - -static int winsnd_get_stat_discarded(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - - return d->stat_notplayed; -} - -static MSFilterMethod winsnd_methods[]={ - { MS_FILTER_GET_SAMPLE_RATE , get_rate }, - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { MS_FILTER_GET_STAT_INPUT, winsnd_get_stat_input }, - { MS_FILTER_GET_STAT_OUTPUT, winsnd_get_stat_ouptut }, - { MS_FILTER_GET_STAT_DISCARDED, winsnd_get_stat_discarded }, - { 0 , NULL } -}; - -MSFilterDesc winsnd_read_desc={ - MS_WINSND_READ_ID, - "MMERead", - "MME capture filter for Windows", - MS_FILTER_OTHER, - NULL, - 0, - 1, - winsnd_init, - winsnd_read_preprocess, - winsnd_read_process, - winsnd_read_postprocess, - winsnd_uninit, - winsnd_methods -}; - - -MSFilterDesc winsnd_write_desc={ - MS_WINSND_WRITE_ID, - "MMEWrite", - "MME playback filter for Windows", - MS_FILTER_OTHER, - NULL, - 1, - 0, - winsnd_init, - winsnd_write_preprocess, - winsnd_write_process, - winsnd_write_postprocess, - winsnd_uninit, - winsnd_methods -}; - -MSFilter *ms_winsnd_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_read_desc); - WinSndCard *wc=(WinSndCard*)card->data; - WinSnd *d=(WinSnd*)f->data; - d->dev_id=wc->in_devid; - return f; -} - - -MSFilter *ms_winsnd_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_write_desc); - WinSndCard *wc=(WinSndCard*)card->data; - WinSnd *d=(WinSnd*)f->data; - d->dev_id=wc->out_devid; - return f; -} - -MS_FILTER_DESC_EXPORT(winsnd_read_desc) -MS_FILTER_DESC_EXPORT(winsnd_write_desc) diff --git a/linphone/mediastreamer2/src/winsnd3.c b/linphone/mediastreamer2/src/winsnd3.c deleted file mode 100755 index a554a159f..000000000 --- a/linphone/mediastreamer2/src/winsnd3.c +++ /dev/null @@ -1,713 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" - -#include -#ifdef _MSC_VER -#include -#endif -#include - -#if defined(_WIN32_WCE) -//#define DISABLE_SPEEX -//#define WCE_OPTICON_WORKAROUND 1000 -#endif - - -#define WINSND_NBUFS 10 -#define WINSND_OUT_DELAY 0.100 -#define WINSND_OUT_NBUFS 20 -#define WINSND_NSAMPLES 320 -#define WINSND_MINIMUMBUFFER 5 - -static MSFilter *ms_winsnd_read_new(MSSndCard *card); -static MSFilter *ms_winsnd_write_new(MSSndCard *card); - -typedef struct WinSndCard{ - int in_devid; - int out_devid; -}WinSndCard; - -static void winsndcard_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent){ - MMRESULT mr = MMSYSERR_NOERROR; - DWORD dwVolume = 0xFFFF; - dwVolume = ((0xFFFF) * percent) / 100; - - switch(e){ - case MS_SND_CARD_MASTER: - /*mr = waveOutSetVolume(d->waveoutdev, dwVolume); */ - if (mr != MMSYSERR_NOERROR) - { - ms_warning("Failed to set master volume. (waveOutSetVolume:0x%i)", mr); - return; - } - break; - case MS_SND_CARD_CAPTURE: - break; - case MS_SND_CARD_PLAYBACK: - break; - default: - ms_warning("winsnd_card_set_level: unsupported command."); - } -} - -static int winsndcard_get_level(MSSndCard *card, MSSndCardMixerElem e){ - switch(e){ - case MS_SND_CARD_MASTER: - /*mr=waveOutGetVolume(d->waveoutdev, &dwVolume);*/ - /* Transform to 0 to 100 scale*/ - /*dwVolume = (dwVolume *100) / (0xFFFF);*/ - return 60; - break; - case MS_SND_CARD_CAPTURE: - break; - case MS_SND_CARD_PLAYBACK: - break; - default: - ms_warning("winsnd_card_get_level: unsupported command."); - return -1; - } - return -1; -} - -static void winsndcard_set_source(MSSndCard *card, MSSndCardCapture source){ - - switch(source){ - case MS_SND_CARD_MIC: - break; - case MS_SND_CARD_LINE: - break; - } -} - -static void winsndcard_init(MSSndCard *card){ - WinSndCard *c=(WinSndCard *)ms_new(WinSndCard,1); - card->data=c; -} - -static void winsndcard_uninit(MSSndCard *card){ - ms_free(card->data); -} - -static void winsndcard_detect(MSSndCardManager *m); -static MSSndCard *winsndcard_dup(MSSndCard *obj); - -MSSndCardDesc winsnd_card_desc={ - "WINSND", - winsndcard_detect, - winsndcard_init, - winsndcard_set_level, - winsndcard_get_level, - winsndcard_set_source, - NULL, - NULL, - ms_winsnd_read_new, - ms_winsnd_write_new, - winsndcard_uninit, - winsndcard_dup -}; - -static MSSndCard *winsndcard_dup(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - card->name=ms_strdup(obj->name); - card->data=ms_new(WinSndCard,1); - memcpy(card->data,obj->data,sizeof(WinSndCard)); - return card; -} - -static MSSndCard *winsndcard_new(const char *name, int in_dev, int out_dev, unsigned cap){ - MSSndCard *card=ms_snd_card_new(&winsnd_card_desc); - WinSndCard *d=(WinSndCard*)card->data; - card->name=ms_strdup(name); - d->in_devid=in_dev; - d->out_devid=out_dev; - card->capabilities=cap; - return card; -} - -static void add_or_update_card(MSSndCardManager *m, const char *name, int indev, int outdev, unsigned int capability){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->name,name)==0){ - /*update already entered card */ - WinSndCard *d=(WinSndCard*)card->data; - card->capabilities|=capability; - if (indev!=-1) - d->in_devid=indev; - if (outdev!=-1) - d->out_devid=outdev; - - return; - } - } - /* add this new card:*/ - ms_snd_card_manager_add_card(m,winsndcard_new(name,indev,outdev,capability)); -} - -static void winsndcard_detect(MSSndCardManager *m){ - MMRESULT mr = NOERROR; - unsigned int nOutDevices = waveOutGetNumDevs (); - unsigned int nInDevices = waveInGetNumDevs (); - unsigned int item; - - if (nOutDevices>nInDevices) - nInDevices = nOutDevices; - - for (item = 0; item < nInDevices; item++){ - - WAVEINCAPS incaps; - WAVEOUTCAPS outcaps; - mr = waveInGetDevCaps (item, &incaps, sizeof (WAVEINCAPS)); - if (mr == MMSYSERR_NOERROR) - { -#if defined(_WIN32_WCE) - char card[256]; - snprintf(card, sizeof(card), "Input card %i", item); - add_or_update_card(m,card,item,-1,MS_SND_CARD_CAP_CAPTURE); - /* _tprintf(L"new card: %s", incaps.szPname); */ -#else - add_or_update_card(m,incaps.szPname,item,-1,MS_SND_CARD_CAP_CAPTURE); -#endif - } - mr = waveOutGetDevCaps (item, &outcaps, sizeof (WAVEOUTCAPS)); - if (mr == MMSYSERR_NOERROR) - { -#if defined(_WIN32_WCE) - char card[256]; - snprintf(card, sizeof(card), "Output card %i", item); - add_or_update_card(m,card,-1,item,MS_SND_CARD_CAP_PLAYBACK); - /* _tprintf(L"new card: %s", outcaps.szPname); */ -#else - add_or_update_card(m,outcaps.szPname,-1,item,MS_SND_CARD_CAP_PLAYBACK); -#endif - } - } -} - - -typedef struct WinSnd{ - int dev_id; - HWAVEIN indev; - HWAVEOUT outdev; - WAVEFORMATEX wfx; - WAVEHDR hdrs_read[WINSND_NBUFS]; - WAVEHDR hdrs_write[WINSND_OUT_NBUFS]; - queue_t rq; - ms_mutex_t mutex; - unsigned int bytes_read; - unsigned int nbufs_playing; - bool_t running; - int outcurbuf; - int nsamples; - queue_t wq; - int32_t stat_input; - int32_t stat_output; - int32_t stat_notplayed; - - int32_t stat_minimumbuffer; - int ready; - int workaround; /* workaround for opticon audio device */ - bool_t overrun; -}WinSnd; - -static void winsnd_apply_settings(WinSnd *d){ - d->wfx.nBlockAlign=d->wfx.nChannels*d->wfx.wBitsPerSample/8; - d->wfx.nAvgBytesPerSec=d->wfx.nSamplesPerSec*d->wfx.nBlockAlign; -} - - -#ifndef _TRUE_TIME -static uint64_t winsnd_get_cur_time( void *data){ - WinSnd *d=(WinSnd*)data; - uint64_t curtime=((uint64_t)d->bytes_read*1000)/(uint64_t)d->wfx.nAvgBytesPerSec; - /* ms_debug("winsnd_get_cur_time: bytes_read=%u return %lu\n",d->bytes_read,(unsigned long)curtime); */ - return curtime; -} -#endif - - -static void winsnd_init(MSFilter *f){ - WinSnd *d=(WinSnd *)ms_new0(WinSnd,1); - d->wfx.wFormatTag = WAVE_FORMAT_PCM; - d->wfx.cbSize = 0; - d->wfx.nAvgBytesPerSec = 16000; - d->wfx.nBlockAlign = 2; - d->wfx.nChannels = 1; - d->wfx.nSamplesPerSec = 8000; - d->wfx.wBitsPerSample = 16; - qinit(&d->rq); - qinit(&d->wq); - d->ready=0; - d->workaround=0; - ms_mutex_init(&d->mutex,NULL); - f->data=d; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; -} - -static void winsnd_uninit(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - flushq(&d->rq,0); - flushq(&d->wq,0); - d->ready=0; - d->workaround=0; - ms_mutex_destroy(&d->mutex); - ms_free(f->data); -} - -static void add_input_buffer(WinSnd *d, WAVEHDR *hdr, int buflen){ - mblk_t *m=allocb(buflen,0); - MMRESULT mr; - memset(hdr,0,sizeof(*hdr)); - if (buflen==0) ms_error("add_input_buffer: buflen=0 !"); - hdr->lpData=(LPSTR)m->b_wptr; - hdr->dwBufferLength=buflen; - hdr->dwFlags = 0; - hdr->dwUser = (DWORD)m; - mr = waveInPrepareHeader (d->indev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInPrepareHeader() error"); - return ; - } - mr=waveInAddBuffer(d->indev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInAddBuffer() error"); - return ; - } -} - -static void CALLBACK -read_callback (HWAVEIN waveindev, UINT uMsg, DWORD dwInstance, DWORD dwParam1, - DWORD dwParam2) -{ - WAVEHDR *wHdr=(WAVEHDR *) dwParam1; - MSFilter *f=(MSFilter *)dwInstance; - WinSnd *d=(WinSnd*)f->data; - mblk_t *m; - int bsize; - switch (uMsg){ - case WIM_OPEN: - ms_debug("read_callback : WIM_OPEN"); - break; - case WIM_CLOSE: - ms_debug("read_callback : WIM_CLOSE"); - break; - case WIM_DATA: - bsize=wHdr->dwBytesRecorded; - - /* ms_warning("read_callback : WIM_DATA (%p,%i)",wHdr,bsize); */ - m=(mblk_t*)wHdr->dwUser; - m->b_wptr+=bsize; - wHdr->dwUser=0; - ms_mutex_lock(&d->mutex); - putq(&d->rq,m); - ms_mutex_unlock(&d->mutex); - d->bytes_read+=wHdr->dwBufferLength; - d->stat_input++; - d->stat_input++; -#ifdef WIN32_TIMERS - if (f->ticker->TimeEvent!=NULL) - SetEvent(f->ticker->TimeEvent); -#endif - break; - } -} - - -static void winsnd_read_preprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; - int bsize; - DWORD dwFlag; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; - - winsnd_apply_settings(d); - /* Init Microphone device */ - dwFlag = CALLBACK_FUNCTION; - if (d->dev_id != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveInOpen (&d->indev, d->dev_id, &d->wfx, - (DWORD) read_callback, (DWORD)f, dwFlag); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - mr = waveInOpen (&d->indev, WAVE_MAPPER, &d->wfx, - (DWORD) read_callback, (DWORD)f, CALLBACK_FUNCTION); - if (mr != MMSYSERR_NOERROR) - { - d->indev=NULL; - ms_error("Failed to prepare windows sound device. (waveInOpen:0x%i)", mr); - return ; - } - } - bsize=WINSND_NSAMPLES*d->wfx.nAvgBytesPerSec/8000; - ms_debug("Using input buffers of %i bytes",bsize); - for(i=0;ihdrs_read[i]; - add_input_buffer(d,hdr,bsize); - } - d->running=TRUE; - mr=waveInStart(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInStart() error"); - return ; - } -#ifndef _TRUE_TIME - ms_ticker_set_time_func(f->ticker,winsnd_get_cur_time,d); -#endif -} - -static void winsnd_read_postprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; -#ifndef _TRUE_TIME - ms_ticker_set_time_func(f->ticker,NULL,NULL); -#endif - d->running=FALSE; - mr=waveInStop(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInStop() error"); - return ; - } - mr=waveInReset(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInReset() error"); - return ; - } - for(i=0;ihdrs_read[i]; - if (hdr->dwFlags & WHDR_PREPARED) - { - mr = waveInUnprepareHeader(d->indev,hdr,sizeof (*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInUnPrepareHeader() error"); - } - } - } - mr = waveInClose(d->indev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveInClose() error"); - return ; - } - - ms_message("Shutting down sound device (playing: %i) (input-output: %i) (notplayed: %i)", d->nbufs_playing, d->stat_input - d->stat_output, d->stat_notplayed); - flushq(&d->rq,0); -} - -static void winsnd_read_process(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - mblk_t *m; - int i; - ms_mutex_lock(&d->mutex); - while((m=getq(&d->rq))!=NULL){ - ms_queue_put(f->outputs[0],m); - } - ms_mutex_unlock(&d->mutex); - for(i=0;ihdrs_read[i]; - if (hdr->dwUser==0) { - MMRESULT mr; - mr=waveInUnprepareHeader(d->indev,hdr,sizeof(*hdr)); - if (mr!=MMSYSERR_NOERROR) - ms_warning("winsnd_read_process: Fail to unprepare header!"); - add_input_buffer(d,hdr,hdr->dwBufferLength); - } - } -} - -static void CALLBACK -write_callback(HWAVEOUT outdev, UINT uMsg, DWORD dwInstance, - DWORD dwParam1, DWORD dwParam2) -{ - WAVEHDR *hdr=(WAVEHDR *) dwParam1; - WinSnd *d=(WinSnd*)dwInstance; - - switch (uMsg){ - case WOM_OPEN: - break; - case WOM_CLOSE: - case WOM_DONE: - if (hdr){ - d->nbufs_playing--; - } - if (d->stat_output==0) - { - d->stat_input=1; /* reset */ - d->stat_notplayed=0; - } - d->stat_output++; - break; - } -} - -static void winsnd_write_preprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - DWORD dwFlag; - int i; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - d->stat_minimumbuffer=WINSND_MINIMUMBUFFER; - - winsnd_apply_settings(d); - /* Init Microphone device */ - dwFlag = CALLBACK_FUNCTION; - if (d->dev_id != WAVE_MAPPER) - dwFlag = WAVE_MAPPED | CALLBACK_FUNCTION; - mr = waveOutOpen (&d->outdev, d->dev_id, &d->wfx, - (DWORD) write_callback, (DWORD)d, dwFlag); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to open windows sound device %i. (waveOutOpen:0x%i)",d->dev_id, mr); - mr = waveOutOpen (&d->outdev, WAVE_MAPPER, &d->wfx, - (DWORD) write_callback, (DWORD)d, CALLBACK_FUNCTION); - if (mr != MMSYSERR_NOERROR) - { - ms_error("Failed to open windows sound device %i. (waveOutOpen:0x%i)",d->dev_id, mr); - d->outdev=NULL; - return ; - } - } - for(i=0;ihdrs_write[i]; - hdr->dwFlags=0; - hdr->dwUser=0; - } - d->outcurbuf=0; - d->overrun=FALSE; - d->nsamples=0; -} - -static void winsnd_write_postprocess(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - MMRESULT mr; - int i; - if (d->outdev==NULL) return; - mr=waveOutReset(d->outdev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutReset() error"); - return ; - } - for(i=0;ihdrs_write[i]; - mblk_t *old; - if (hdr->dwFlags & WHDR_DONE){ - mr=waveOutUnprepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutUnprepareHeader error"); - } - old=(mblk_t*)hdr->dwUser; - if (old) freemsg(old); - hdr->dwUser=0; - } - } - mr=waveOutClose(d->outdev); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutClose() error"); - return ; - } - d->ready=0; - d->workaround=0; -} - -static void playout_buf(WinSnd *d, WAVEHDR *hdr, mblk_t *m){ - MMRESULT mr; - hdr->dwUser=(DWORD)m; - hdr->lpData=(LPSTR)m->b_rptr; - hdr->dwBufferLength=msgdsize(m); - hdr->dwFlags = 0; - mr = waveOutPrepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutPrepareHeader() error"); - d->stat_notplayed++; - } - mr=waveOutWrite(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutWrite() error"); - d->stat_notplayed++; - }else { - d->nbufs_playing++; - } -} - -static void winsnd_write_process(MSFilter *f){ - WinSnd *d=(WinSnd*)f->data; - mblk_t *m; - MMRESULT mr; - mblk_t *old; - if (d->outdev==NULL) { - ms_queue_flush(f->inputs[0]); - return; - } - if (d->overrun){ - ms_warning("nbufs_playing=%i",d->nbufs_playing); - if (d->nbufs_playing>0){ - ms_queue_flush(f->inputs[0]); - return; - } - else d->overrun=FALSE; - } - while(1){ - int outcurbuf=d->outcurbuf % WINSND_OUT_NBUFS; - WAVEHDR *hdr=&d->hdrs_write[outcurbuf]; - old=(mblk_t*)hdr->dwUser; - if (d->nsamples==0){ - int tmpsize=WINSND_OUT_DELAY*d->wfx.nAvgBytesPerSec; - mblk_t *tmp=allocb(tmpsize,0); - memset(tmp->b_wptr,0,tmpsize); - tmp->b_wptr+=tmpsize; - playout_buf(d,hdr,tmp); - d->outcurbuf++; - d->nsamples+=WINSND_OUT_DELAY*d->wfx.nSamplesPerSec; - continue; - } - m=ms_queue_get(f->inputs[0]); - if (!m) break; - d->nsamples+=msgdsize(m)/d->wfx.nBlockAlign; - /*if the output buffer has finished to play, unprepare it*/ - if (hdr->dwFlags & WHDR_DONE){ - mr=waveOutUnprepareHeader(d->outdev,hdr,sizeof(*hdr)); - if (mr != MMSYSERR_NOERROR){ - ms_error("waveOutUnprepareHeader error"); - } - freemsg(old); - old=NULL; - hdr->dwFlags=0; - hdr->dwUser=0; - } - if (old==NULL){ - /* a free wavheader */ - playout_buf(d,hdr,m); - }else{ - /* no more free wavheader, overrun !*/ - ms_warning("WINSND overrun, restarting"); - d->overrun=TRUE; - d->nsamples=0; - waveOutReset(d->outdev); - } - d->outcurbuf++; - } -} - -static int set_rate(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - d->wfx.nSamplesPerSec=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - d->wfx.nChannels=*((int*)arg); - return 0; -} - -static int winsnd_get_stat_input(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - return d->stat_input; -} - -static int winsnd_get_stat_ouptut(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - - return d->stat_output; -} - -static int winsnd_get_stat_discarded(MSFilter *f, void *arg){ - WinSnd *d=(WinSnd*)f->data; - - return d->stat_notplayed; -} - -static MSFilterMethod winsnd_methods[]={ - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { MS_FILTER_GET_STAT_INPUT, winsnd_get_stat_input }, - { MS_FILTER_GET_STAT_OUTPUT, winsnd_get_stat_ouptut }, - { MS_FILTER_GET_STAT_DISCARDED, winsnd_get_stat_discarded }, - { 0 , NULL } -}; - -MSFilterDesc winsnd_read_desc={ - MS_WINSND_READ_ID, - "MSWinSndRead", - "Sound capture filter for Windows Sound drivers", - MS_FILTER_OTHER, - NULL, - 0, - 1, - winsnd_init, - winsnd_read_preprocess, - winsnd_read_process, - winsnd_read_postprocess, - winsnd_uninit, - winsnd_methods -}; - - -MSFilterDesc winsnd_write_desc={ - MS_WINSND_WRITE_ID, - "MSWinSndWrite", - "Sound playback filter for Windows Sound drivers", - MS_FILTER_OTHER, - NULL, - 1, - 0, - winsnd_init, - winsnd_write_preprocess, - winsnd_write_process, - winsnd_write_postprocess, - winsnd_uninit, - winsnd_methods -}; - -MSFilter *ms_winsnd_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_read_desc); - WinSndCard *wc=(WinSndCard*)card->data; - WinSnd *d=(WinSnd*)f->data; - d->dev_id=wc->in_devid; - return f; -} - - -MSFilter *ms_winsnd_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsnd_write_desc); - WinSndCard *wc=(WinSndCard*)card->data; - WinSnd *d=(WinSnd*)f->data; - d->dev_id=wc->out_devid; - return f; -} - -MS_FILTER_DESC_EXPORT(winsnd_read_desc) -MS_FILTER_DESC_EXPORT(winsnd_write_desc) diff --git a/linphone/mediastreamer2/src/winsndds.cpp b/linphone/mediastreamer2/src/winsndds.cpp deleted file mode 100644 index fe539fe8e..000000000 --- a/linphone/mediastreamer2/src/winsndds.cpp +++ /dev/null @@ -1,1864 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef __DIRECTSOUND_ENABLED__ - -#define UNICODE - -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msfilter.h" -#include "mediastreamer2/msticker.h" - -#include -#ifdef _MSC_VER -#include -#endif -#include - -#include -#include - -const GUID GUID_DSCFX_MS_AEC = {0xcdebb919, 0x379a, 0x488a, {0x87, 0x65, 0xf5, 0x3c, 0xfd, 0x36, 0xde, 0x40}}; -const GUID GUID_DSCFX_CLASS_AEC = {0xBF963D80L, 0xC559, 0x11D0, {0x8A, 0x2B, 0x00, 0xA0, 0xC9, 0x25, 0x5A, 0xC1}}; - -const GUID CLSID_DirectSoundPrivate= { 0x11ab3ec0, 0x25ec, 0x11d1, {0xa4, 0xd8, 0x0, 0xc0, 0x4f, 0xc2, 0x8a, 0xca}}; -const GUID DSPROPSETID_DirectSoundDevice = {0x84624f82, 0x25ec, 0x11d1, {0xa4, 0xd8, 0x0, 0xc0, 0x4f, 0xc2, 0x8a, 0xca}}; - -#define WINSNDDS_MINIMUMBUFFER 5 - -static MSFilter *ms_winsndds_read_new(MSSndCard *card); -static MSFilter *ms_winsndds_write_new(MSSndCard *card); - -static HMODULE ms_lib_instance=NULL; -static HRESULT (WINAPI *ms_DllGetClassObject)(REFCLSID , REFIID , LPVOID *); - -static HRESULT (WINAPI *ms_DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN); -static HRESULT (WINAPI *ms_DirectSoundEnumerate)(LPDSENUMCALLBACKW, LPVOID); - -static HRESULT (WINAPI *ms_DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN); -static HRESULT (WINAPI *ms_DirectSoundCaptureEnumerate)(LPDSENUMCALLBACKW, LPVOID); - -static HRESULT (WINAPI *ms_DirectSoundFullDuplexCreate)(LPCGUID , LPCGUID , - LPCDSCBUFFERDESC , LPCDSBUFFERDESC , HWND , - DWORD , LPDIRECTSOUNDFULLDUPLEX* , LPDIRECTSOUNDCAPTUREBUFFER8 *, - LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN ); - -typedef struct WinSndDsCard{ - int in_devid; - int out_devid; - GUID in_guid; - GUID out_guid; - int removed; -}WinSndDsCard; - -static BOOL GetWaveIdFromDSoundGUID( GUID i_sGUID, DWORD *dwWaveID) -{ - LPKSPROPERTYSET pKsPropertySet = NULL; - LPCLASSFACTORY pClassFactory = NULL; - HRESULT hr; - BOOL retval = FALSE; - - PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA psDirectSoundDeviceDescription = NULL; - DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA sDirectSoundDeviceDescription; - - memset(&sDirectSoundDeviceDescription,0,sizeof(sDirectSoundDeviceDescription)); - - hr = ms_DllGetClassObject (CLSID_DirectSoundPrivate, IID_IClassFactory, (LPVOID *)&pClassFactory ); - - if(SUCCEEDED(hr)) - { - hr = pClassFactory->CreateInstance ( NULL, IID_IKsPropertySet, (LPVOID *)&pKsPropertySet ); - } - - // Release the class factory - if(pClassFactory) - { - pClassFactory->Release(); - } - - if(SUCCEEDED(hr)) - { - ULONG ulBytesReturned = 0; - sDirectSoundDeviceDescription.DeviceId = i_sGUID; - - // On the first call the final size is unknown so pass the size of the struct in order to receive - // "Type" and "DataFlow" values, ulBytesReturned will be populated with bytes required for struct+strings. - hr = pKsPropertySet->Get(DSPROPSETID_DirectSoundDevice, - DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION, - NULL, - 0, - &sDirectSoundDeviceDescription, - sizeof(sDirectSoundDeviceDescription), - &ulBytesReturned - ); - - if (ulBytesReturned) - { - // On the first call it notifies us of the required amount of memory in order to receive the strings. - // Allocate the required memory, the strings will be pointed to the memory space directly after the struct. - psDirectSoundDeviceDescription = (PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA)new BYTE[ulBytesReturned]; - *psDirectSoundDeviceDescription = sDirectSoundDeviceDescription; - - hr = pKsPropertySet->Get(DSPROPSETID_DirectSoundDevice, - DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION, - NULL, - 0, - psDirectSoundDeviceDescription, - ulBytesReturned, - &ulBytesReturned - ); - - *dwWaveID = psDirectSoundDeviceDescription->WaveDeviceId; - delete [] psDirectSoundDeviceDescription; - retval = TRUE; - } - - pKsPropertySet->Release(); - } - - return retval; -} - -static void winsnddscard_set_level(MSSndCard *card, MSSndCardMixerElem e, int percent){ - WinSndDsCard *d=(WinSndDsCard*)card->data; - DWORD waveout_devid = WAVE_MAPPER; - DWORD wavein_devid = WAVE_MAPPER; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_UNSIGNED mcdu = {0}; - - MMRESULT mr = MMSYSERR_NOERROR; - DWORD dwVolume = ((0xFFFF) * percent) / 100; - - WORD wLeftVol, wRightVol; - DWORD dwNewVol; - wLeftVol = LOWORD(dwVolume); // get higher WORD - wRightVol = LOWORD(dwVolume); // get lower WORD - - dwNewVol = MAKELONG(wLeftVol, wRightVol); - - GetWaveIdFromDSoundGUID(d->in_guid, &wavein_devid); - GetWaveIdFromDSoundGUID(d->out_guid, &waveout_devid); - - switch(e){ - case MS_SND_CARD_PLAYBACK: - case MS_SND_CARD_MASTER: - { - - mr = mixerGetID( (HMIXEROBJ)waveout_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_level: mixerGetID failed. (0x%x)", mr); - return; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerOpen failed. (0x%x)", mr); - return; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_level: mixerGetLineControls failed. (0x%x)", mr); - return; - } - - mcdu.dwValue = 65535*percent/100; /* the volume is a number between 0 and 65535 */ - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_level: mixerSetControlDetails failed. (0x%x)", mr); - return; - } - } - break; - case MS_SND_CARD_CAPTURE: - mr = mixerGetID( (HMIXEROBJ)wavein_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_level: mixerGetID failed. (0x%x)", mr); - return; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - if (mr == MMSYSERR_NOERROR) - { - mcdu.dwValue = 65535*percent/100; /* the volume is a number between 0 and 65535 */ - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr == MMSYSERR_NOERROR) - { - return; - } - ms_error("winsndcard_set_level: mixerSetControlDetails failed. (0x%x)", mr); - ms_warning("winsndcard_set_level: control the SRC_MICROPHONE instead"); - } - else - { - ms_error("winsndcard_set_level: mixerGetLineControls failed. (0x%x)", mr); - ms_warning("winsndcard_set_level: control the SRC_MICROPHONE instead"); - } - - /* In case capture doesn't work: use the SRC_MICROPHONE volume */ - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_level: mixerGetLineInfo failed. (0x%x)", mr); - return; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_VOLUME, 1, sizeof(MIXERCONTROL), pmxctrl}; - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if(!mr){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_UNSIGNED pUnsigned; - MIXERCONTROLDETAILS mxcd; - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pUnsigned = - (LPMIXERCONTROLDETAILS_UNSIGNED) - malloc(cChannels * sizeof(MIXERCONTROLDETAILS_UNSIGNED)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mxcd.paDetails = (LPVOID) pUnsigned; - - mr = mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - if(!mr){ - pUnsigned[0].dwValue = pUnsigned[cChannels - 1].dwValue - = pmxctrl->Bounds.dwMaximum*percent/100; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - if(mr){ - ms_error("winsndcard_set_level: mixerSetControlDetails failed. (0x%x)", mr); - } - } - else - { - ms_error("winsndcard_set_level: mixerGetControlDetails failed. (0x%x)", mr); - } - free(pmxctrl); - free(pUnsigned); - } - else - { - ms_error("winsndcard_set_level: mixerGetLineControls failed. (0x%x)", mr); - free(pmxctrl); - } - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_level: mixerClose failed. (0x%x)", mr); - return; - } - break; - default: - ms_warning("winsnd_card_set_level: unsupported command."); - } -} - -static int winsnddscard_get_level(MSSndCard *card, MSSndCardMixerElem e){ - WinSndDsCard *d=(WinSndDsCard*)card->data; - DWORD waveout_devid = WAVE_MAPPER; - DWORD wavein_devid = WAVE_MAPPER; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_UNSIGNED mcdu = {0}; - - MMRESULT mr = MMSYSERR_NOERROR; - int percent; - - GetWaveIdFromDSoundGUID(d->in_guid, &wavein_devid); - GetWaveIdFromDSoundGUID(d->out_guid, &waveout_devid); - - switch(e){ - case MS_SND_CARD_MASTER: - case MS_SND_CARD_PLAYBACK: - { - mr = mixerGetID( (HMIXEROBJ)waveout_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_get_level: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerGetLineControls failed. (0x%x)", mr); - return -1; - } - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (mcdu.dwValue *100) / (mc.Bounds.dwMaximum); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerGetControlDetails failed. (0x%x)", mr); - return -1; - } - return percent; - } - break; - case MS_SND_CARD_CAPTURE: - mr = mixerGetID( (HMIXEROBJ)wavein_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_get_level: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if (mr == MMSYSERR_NOERROR) - { - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &mcdu; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mcd.cChannels = 1; - mr = mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (mcdu.dwValue *100) / (mc.Bounds.dwMaximum); - - if (mr == MMSYSERR_NOERROR) - { - return percent; - } - ms_error("winsndcard_get_level: mixerGetControlDetails failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - else - { - ms_error("winsndcard_get_level: mixerGetLineControls failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_get_level: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_VOLUME, 1, sizeof(MIXERCONTROL), pmxctrl}; - if(!mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, - MIXER_GETLINECONTROLSF_ONEBYTYPE)){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_UNSIGNED pUnsigned; - MIXERCONTROLDETAILS mxcd; - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pUnsigned = - (LPMIXERCONTROLDETAILS_UNSIGNED) - malloc(cChannels * sizeof(MIXERCONTROLDETAILS_UNSIGNED)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); - mxcd.paDetails = (LPVOID) pUnsigned; - - mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - percent = (pUnsigned[0].dwValue *100) / (pmxctrl->Bounds.dwMaximum); - free(pmxctrl); - free(pUnsigned); - } - else - free(pmxctrl); - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_get_level: mixerClose failed. (0x%x)", mr); - return -1; - } - return percent; - break; - default: - ms_warning("winsndcard_get_level: unsupported command."); - return -1; - } - return -1; -} - -static void winsnddscard_set_source(MSSndCard *card, MSSndCardCapture source){ - - switch(source){ - case MS_SND_CARD_MIC: - break; - case MS_SND_CARD_LINE: - break; - } -} - -static int winsnddscard_set_control(MSSndCard *card, MSSndCardControlElem e, int val){ - WinSndDsCard *d=(WinSndDsCard*)card->data; - DWORD waveout_devid = WAVE_MAPPER; - DWORD wavein_devid = WAVE_MAPPER; - - UINT uMixerID; - DWORD dwMixerHandle; - MIXERLINE MixerLine; - MIXERLINE Line; - UINT uLineIndex; - - MIXERLINECONTROLS mlc = {0}; - MIXERCONTROL mc = {0}; - MIXERCONTROLDETAILS mcd = {0}; - MIXERCONTROLDETAILS_BOOLEAN bMute; - - MMRESULT mr = MMSYSERR_NOERROR; - - GetWaveIdFromDSoundGUID(d->in_guid, &wavein_devid); - GetWaveIdFromDSoundGUID(d->out_guid, &waveout_devid); - - switch(e){ - case MS_SND_CARD_CAPTURE_MUTE: - bMute.fValue = (val>0); - - mr = mixerGetID( (HMIXEROBJ)wavein_devid, &uMixerID, MIXER_OBJECTF_WAVEIN ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_control: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE; //MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - if (mr == MMSYSERR_NOERROR) - { - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &bMute; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr == MMSYSERR_NOERROR) - { - return 0; - } - ms_error("winsndcard_set_control: mixerSetControlDetails failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - else - { - ms_error("winsndcard_set_control: mixerGetLineControls failed. (0x%x)", mr); - ms_warning("winsndcard_get_level: control the SRC_MICROPHONE instead"); - } - - - for (uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++) - { - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_LINEID); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - memset( &Line, 0, sizeof(MIXERLINE) ); - Line.cbStruct = sizeof(MIXERLINE); - Line.dwDestination = MixerLine.dwDestination; - Line.dwSource = uLineIndex; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerGetLineInfo failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("LineID: %d\n", MixerLine.dwLineID); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - if (MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE == Line.dwComponentType) - { - /* unmute */ - /* Find a mute control, if any, of the microphone line */ - - LPMIXERCONTROL pmxctrl = (LPMIXERCONTROL)malloc(sizeof(MIXERCONTROL)); - MIXERLINECONTROLS mxlctrl = {sizeof(mxlctrl), Line.dwLineID, MIXERCONTROL_CONTROLTYPE_MUTE, 1, sizeof(MIXERCONTROL), pmxctrl}; - if(!mixerGetLineControls((HMIXEROBJ)dwMixerHandle, &mxlctrl, MIXER_GETLINECONTROLSF_ONEBYTYPE)){ - DWORD cChannels = Line.cChannels; - LPMIXERCONTROLDETAILS_BOOLEAN pbool; - MIXERCONTROLDETAILS mxcd; - - if (MIXERCONTROL_CONTROLF_UNIFORM & pmxctrl->fdwControl) - cChannels = 1; - pbool = (LPMIXERCONTROLDETAILS_BOOLEAN) malloc(cChannels * sizeof( - MIXERCONTROLDETAILS_BOOLEAN)); - - mxcd.cbStruct = sizeof(mxcd); - mxcd.dwControlID = pmxctrl->dwControlID; - mxcd.cChannels = cChannels; - mxcd.hwndOwner = (HWND)0; - mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); - mxcd.paDetails = (LPVOID) pbool; - - mixerGetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - /* Unmute the microphone line (for both channels) */ - pbool[0].fValue = pbool[cChannels - 1].fValue = val; /* 0 -> unmute; */ - mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, &mxcd, - MIXER_SETCONTROLDETAILSF_VALUE); - free(pmxctrl); - free(pbool); - } - else - free(pmxctrl); - } - } - mixerClose( (HMIXER)dwMixerHandle ); - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_control: mixerClose failed. (0x%x)", mr); - return -1; - } - return 0; - - case MS_SND_CARD_MASTER_MUTE: - case MS_SND_CARD_PLAYBACK_MUTE: - { - bMute.fValue = (val>0); - - mr = mixerGetID( (HMIXEROBJ)waveout_devid, &uMixerID, MIXER_OBJECTF_WAVEOUT ); - if ( mr != MMSYSERR_NOERROR ) - { - ms_error("winsndcard_set_control: mixerGetID failed. (0x%x)", mr); - return -1; - } - mr = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerOpen failed. (0x%x)", mr); - return -1; - } - memset( &MixerLine, 0, sizeof(MIXERLINE) ); - MixerLine.cbStruct = sizeof(MIXERLINE); - if (MS_SND_CARD_MASTER_MUTE==e) - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; - else - MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; - mr = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE ); - if ( mr != MMSYSERR_NOERROR ) - { - mixerClose( (HMIXER)dwMixerHandle ); - ms_error("winsndcard_set_control: mixerSetControlDetails failed. (0x%x)", mr); - return -1; - } - - /* ms_message("Name: %s\n", MixerLine.szName); */ - /* ms_message("Source Line: %d\n", MixerLine.dwSource); */ - /* ms_message("ComponentType: %d\n", MixerLine.dwComponentType); */ - - mlc.cbStruct = sizeof(MIXERLINECONTROLS); - mlc.dwLineID = MixerLine.dwLineID; - mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE; //MIXERCONTROL_CONTROLTYPE_VOLUME; - mlc.cControls = 1; - mlc.pamxctrl = &mc; - mlc.cbmxctrl = sizeof(MIXERCONTROL); - mr = mixerGetLineControls((HMIXEROBJ)dwMixerHandle, - &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); - - mcd.cbStruct = sizeof(MIXERCONTROLDETAILS); - mcd.hwndOwner = 0; - mcd.dwControlID = mc.dwControlID; - mcd.paDetails = &bMute; - mcd.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN); - mcd.cChannels = 1; - mr = mixerSetControlDetails((HMIXEROBJ)dwMixerHandle, - &mcd, MIXER_SETCONTROLDETAILSF_VALUE); - - if (mr != MMSYSERR_NOERROR) - { - ms_error("winsndcard_set_control: mixerSetControlDetails failed. (0x%x)", mr); - return -1; - } - return 0; - } - break; - default: - ms_warning("winsndcard_set_control: unsupported command."); - } - return -1; -} - -static int winsnddscard_get_control(MSSndCard *card, MSSndCardControlElem e){ - WinSndDsCard *d=(WinSndDsCard*)card->data; - return -1; -} - -static void winsnddscard_init(MSSndCard *card){ - WinSndDsCard *c=(WinSndDsCard *)ms_new(WinSndDsCard,1); - c->removed=0; - card->data=c; -} - -static void winsnddscard_uninit(MSSndCard *card){ - ms_free(card->data); -} - -static void winsnddscard_detect(MSSndCardManager *m); -static MSSndCard *winsnddscard_dup(MSSndCard *obj); -static void winsnddscard_unload(MSSndCardManager *m); - -MSSndCardDesc winsndds_card_desc={ - "DirectSound", - winsnddscard_detect, - winsnddscard_init, - winsnddscard_set_level, - winsnddscard_get_level, - winsnddscard_set_source, - winsnddscard_set_control, - NULL, - ms_winsndds_read_new, - ms_winsndds_write_new, - winsnddscard_uninit, - winsnddscard_dup, - winsnddscard_unload -}; - -static MSSndCard *winsnddscard_dup(MSSndCard *obj){ - MSSndCard *card=ms_snd_card_new(&winsndds_card_desc); - card->name=ms_strdup(obj->name); - card->data=ms_new(WinSndDsCard,1); - memcpy(card->data,obj->data,sizeof(WinSndDsCard)); - return card; -} - -static MSSndCard *winsnddscard_new(const char *name, LPGUID lpguid, int in_dev, int out_dev, unsigned cap){ - MSSndCard *card=ms_snd_card_new(&winsndds_card_desc); - WinSndDsCard *d=(WinSndDsCard*)card->data; - card->name=ms_strdup(name); - d->in_devid=in_dev; - d->out_devid=out_dev; - card->capabilities=cap; - memset(&d->out_guid, 0, sizeof(GUID)); - memset(&d->in_guid, 0, sizeof(GUID)); - if (out_dev!=-1) - { - if (lpguid!=NULL) - memcpy(&d->out_guid, lpguid, sizeof(GUID)); - } - else - { - if (lpguid!=NULL) - memcpy(&d->in_guid, lpguid, sizeof(GUID)); - } - return card; -} - -static void add_or_update_card(MSSndCardManager *m, const char *name, LPGUID lpguid, int indev, int outdev, unsigned int capability){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsndds_card_desc.driver_type)==0 - && strcmp(card->name,name)==0){ - /*update already entered card */ - WinSndDsCard *d=(WinSndDsCard*)card->data; - card->capabilities|=capability; - if (indev!=-1) - d->in_devid=indev; - if (outdev!=-1) - d->out_devid=outdev; - - if (outdev!=-1) - { - if (lpguid!=NULL) - memcpy(&d->out_guid, lpguid, sizeof(GUID)); - else - memset(&d->out_guid, 0, sizeof(GUID)); - } - if (indev!=-1) - { - if (lpguid!=NULL) - memcpy(&d->in_guid, lpguid, sizeof(GUID)); - else - memset(&d->in_guid, 0, sizeof(GUID)); - } - /* if (d->in_devid!=-1 && d->out_devid!=-1) */ - /* ms_message("DS: new full duplex card %s", name); */ - d->removed=0; - return; - } - } - /* add this new card:*/ - ms_snd_card_manager_add_card(m,winsnddscard_new(name,lpguid, indev,outdev,capability)); -} - -static BOOL CALLBACK enumerate_capture_devices_callback(LPGUID lpGUID, - LPCWSTR lpszDesc, - LPCWSTR lpszDrvName, - LPVOID lpContext ) -{ - MSSndCardManager *m = (MSSndCardManager*)lpContext; - static int dev_index=0; - - if ( lpGUID == NULL ) /* primary device */ - { - char szName[256]; - wchar_t snd_card_name[256]; - swprintf(snd_card_name, 256, L"%s", lpszDesc); - WideCharToMultiByte(CP_UTF8,0,snd_card_name,-1,szName,256,0,0); - - add_or_update_card(m,szName,lpGUID,dev_index,-1,MS_SND_CARD_CAP_CAPTURE); - dev_index++; - } - else - { - char szName[256]; - wchar_t snd_card_name[256]; - swprintf(snd_card_name, 256, L"%s", lpszDesc); - WideCharToMultiByte(CP_UTF8,0,snd_card_name,-1,szName,256,0,0); - - add_or_update_card(m,szName,lpGUID,dev_index,-1,MS_SND_CARD_CAP_CAPTURE); - dev_index++; - } - - return true; -} - -static BOOL CALLBACK enumerate_playback_devices_callback(LPGUID lpGUID, - LPCWSTR lpszDesc, - LPCWSTR lpszDrvName, - LPVOID lpContext ) -{ - MSSndCardManager *m = (MSSndCardManager*)lpContext; - static int dev_index=0; - - if ( lpGUID == NULL ) /* primary device */ - { - char szName[256]; - wchar_t snd_card_name[256]; - swprintf(snd_card_name, 256, L"%s", lpszDesc); - WideCharToMultiByte(CP_UTF8,0,snd_card_name,-1,szName,256,0,0); - - add_or_update_card(m,szName,lpGUID,-1,dev_index,MS_SND_CARD_CAP_PLAYBACK); - dev_index++; - } - else - { - char szName[256]; - wchar_t snd_card_name[256]; - swprintf(snd_card_name, 256, L"%s", lpszDesc); - WideCharToMultiByte(CP_UTF8,0,snd_card_name,-1,szName,256,0,0); - - add_or_update_card(m,szName,lpGUID,-1,dev_index,MS_SND_CARD_CAP_PLAYBACK); - dev_index++; - } - - return true; -} - -static void _winsnddscard_detect(MSSndCardManager *m){ - MMRESULT mr = NOERROR; - - if (ms_lib_instance==NULL) - { - ms_lib_instance = LoadLibrary(L"dsound.dll"); - if( ms_lib_instance == NULL ) - { - /* error */ - ms_debug("winsnddscard_detect: no support for dsound (missing dsound.dll)\n"); - return; - } - - ms_DllGetClassObject =(HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *)) - GetProcAddress( ms_lib_instance, "DllGetClassObject" ); - - ms_DirectSoundCreate =(HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN)) - GetProcAddress( ms_lib_instance, "DirectSoundCreate" ); - - ms_DirectSoundEnumerate =(HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID)) - GetProcAddress( ms_lib_instance, "DirectSoundEnumerateW" ); - - ms_DirectSoundCaptureCreate =(HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN)) - GetProcAddress( ms_lib_instance, "DirectSoundCaptureCreate" ); - - ms_DirectSoundCaptureEnumerate =(HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID)) - GetProcAddress( ms_lib_instance, "DirectSoundCaptureEnumerateW" ); - - ms_DirectSoundFullDuplexCreate =(HRESULT (WINAPI *)(LPCGUID , LPCGUID , - LPCDSCBUFFERDESC , LPCDSBUFFERDESC , HWND , - DWORD , LPDIRECTSOUNDFULLDUPLEX* , LPDIRECTSOUNDCAPTUREBUFFER8 *, - LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN)) - GetProcAddress( ms_lib_instance, "DirectSoundFullDuplexCreate" ); - - if( ms_DllGetClassObject == NULL || - ms_DirectSoundCreate == NULL || - ms_DirectSoundEnumerate == NULL || - ms_DirectSoundCaptureEnumerate == NULL || - ms_DirectSoundCaptureCreate == NULL ) - { - /* error */ - ms_debug("winsnddscard_detect: no support for dsound\n"); - return; - } - } - - ms_DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)enumerate_capture_devices_callback, (void *)m ); - ms_DirectSoundEnumerate( (LPDSENUMCALLBACK)enumerate_playback_devices_callback, (void *)m ); -} - -static void deactivate_removed_cards(MSSndCardManager *m){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsndds_card_desc.driver_type)==0){ - /*mark all cards as potentially removed, detect will check them immediately after */ - WinSndDsCard *d=(WinSndDsCard*)card->data; - if (d->removed) card->capabilities=0; - } - } -} - -static void mark_as_removed(MSSndCardManager *m){ - MSSndCard *card; - const MSList *elem=ms_snd_card_manager_get_list(m); - for(;elem!=NULL;elem=elem->next){ - card=(MSSndCard*)elem->data; - if (strcmp(card->desc->driver_type, winsndds_card_desc.driver_type)==0){ - /*mark all cards as potentially removed, detect will check them immediately after */ - WinSndDsCard *d=(WinSndDsCard*)card->data; - d->removed=1; - } - } -} - -static ms_thread_t poller_thread=NULL; -static bool_t poller_running=TRUE; - -static void * new_device_polling_thread(void *ignore){ - MSSndCardManager *m; - /*check for new devices every 2 seconds*/ - while(poller_running){ - ms_sleep(5); - if (poller_running){ - m=ms_snd_card_manager_get(); - if(!m) break; - mark_as_removed(m); - _winsnddscard_detect(m); - deactivate_removed_cards(m); - } - } - return NULL; -} - -static void stop_poller(){ - poller_running=FALSE; - ms_thread_join(poller_thread,NULL); - poller_thread=NULL; -} - -static void winsnddscard_unload(MSSndCardManager *m){ - stop_poller(); -} - -static void winsnddscard_detect(MSSndCardManager *m){ - _winsnddscard_detect(m); - if (poller_thread==NULL) - ms_thread_create(&poller_thread,NULL,new_device_polling_thread,NULL); -} - -typedef struct WinSndDs{ - int dev_id; - GUID in_guid; - GUID out_guid; - - ms_thread_t thread; - ms_mutex_t thread_lock; - ms_cond_t thread_cond; - bool_t thread_running; - - MSBufferizer output_buff; - LPDIRECTSOUNDFULLDUPLEX lpDirectSoundFullDuplex; - LPDIRECTSOUND lpDirectSound; - LPDIRECTSOUNDBUFFER lpDirectSoundOutputBuffer; - double dsw_framesWritten; - UINT writeOffset; /* last read position */ - - LPDIRECTSOUNDCAPTURE lpDirectSoundCapture; - LPDIRECTSOUNDCAPTUREBUFFER lpDirectSoundInputBuffer; - UINT readOffset; /* last read position */ - - int framesPerDSBuffer; - - WAVEFORMATEX wfx; - queue_t rq; - ms_mutex_t mutex; - uint64_t bytes_read; - unsigned int nbufs_playing; - - int32_t stat_input; - int32_t stat_output; - int32_t stat_notplayed; - -}WinSndDs; - -void * -winsndds_read_thread(void *arg) -{ - WinSndDs *d=(WinSndDs*)arg; - - ms_mutex_lock(&d->thread_lock); - ms_cond_signal(&d->thread_cond); - ms_mutex_unlock(&d->thread_lock); - - while(d->thread_running) - { - HRESULT hr; - DWORD capturePos; - DWORD readPos; - long filled = 0; - long bytesFilled = 0; - LPBYTE lpInBuf1 = NULL; - LPBYTE lpInBuf2 = NULL; - DWORD dwInSize1 = 0; - DWORD dwInSize2 = 0; - - hr = IDirectSoundCaptureBuffer_GetCurrentPosition( d->lpDirectSoundInputBuffer, - &capturePos, &readPos ); - if( hr != DS_OK ) - { - continue; - } - - filled = readPos - d->readOffset; - if( filled < 0 ) filled += d->framesPerDSBuffer; - bytesFilled = filled; - - hr = IDirectSoundCaptureBuffer_Lock ( d->lpDirectSoundInputBuffer, - d->readOffset, bytesFilled, - (void **) &lpInBuf1, &dwInSize1, - (void **) &lpInBuf2, &dwInSize2, 0); - if (hr != DS_OK) - { - Sleep(10); - continue; - } - - if (dwInSize1==0) - { - Sleep(10); - } - else if (dwInSize1>=bytesFilled) - { - mblk_t *m=allocb(bytesFilled,0); - memcpy(m->b_rptr, lpInBuf1, bytesFilled); - m->b_wptr+=bytesFilled; - ms_mutex_lock(&d->mutex); - putq(&d->rq,m); - ms_mutex_unlock(&d->mutex); - d->bytes_read+=bytesFilled; - /* ms_message("bytesFilled=%i\n",bytesFilled); */ - } - else - { - mblk_t *m=allocb(bytesFilled,0); - memcpy(m->b_rptr, lpInBuf1, dwInSize1); - memcpy(m->b_rptr+dwInSize1, lpInBuf2, dwInSize2); - m->b_wptr+=bytesFilled; - ms_mutex_lock(&d->mutex); - putq(&d->rq,m); - ms_mutex_unlock(&d->mutex); - d->bytes_read+=bytesFilled; - /* ms_message("bytesFilled=%i\n",bytesFilled); */ - } - - d->readOffset = (d->readOffset + bytesFilled) % d->framesPerDSBuffer; - - IDirectSoundCaptureBuffer_Unlock( d->lpDirectSoundInputBuffer, - lpInBuf1, dwInSize1, lpInBuf2, dwInSize2); - } - - ms_mutex_lock(&d->thread_lock); - ms_cond_signal(&d->thread_cond); - ms_mutex_unlock(&d->thread_lock); - ms_thread_exit(NULL); - return NULL; -} - -static void winsndds_apply_settings(WinSndDs *d){ - d->wfx.nBlockAlign=d->wfx.nChannels*d->wfx.wBitsPerSample/8; - d->wfx.nAvgBytesPerSec=d->wfx.nSamplesPerSec*d->wfx.nBlockAlign; -} - -static uint64_t winsndds_get_cur_time( void *data){ - WinSndDs *d=(WinSndDs*)data; - uint64_t curtime=(d->bytes_read*1000)/(uint64_t)d->wfx.nAvgBytesPerSec; - return curtime; -} - - -static void winsndds_init(MSFilter *f){ - WinSndDs *d=(WinSndDs *)ms_new0(WinSndDs,1); - d->wfx.wFormatTag = WAVE_FORMAT_PCM; - d->wfx.cbSize = 0; - d->wfx.nAvgBytesPerSec = 16000; - d->wfx.nBlockAlign = 2; - d->wfx.nChannels = 1; - d->wfx.nSamplesPerSec = 8000; - d->wfx.wBitsPerSample = 16; - qinit(&d->rq); - ms_mutex_init(&d->mutex,NULL); - f->data=d; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - - d->framesPerDSBuffer = 320 * (8000 / 1000); - - d->thread = NULL; - ms_mutex_init(&d->thread_lock,NULL); - ms_cond_init(&d->thread_cond,NULL); - d->thread_running = FALSE; - - ms_bufferizer_init(&d->output_buff); -} - -static void winsndds_uninit(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - - d->thread = NULL; - d->thread_running = FALSE; - ms_cond_destroy(&d->thread_cond); - ms_mutex_destroy(&d->thread_lock); - ms_bufferizer_uninit(&d->output_buff); - - flushq(&d->rq,0); - ms_mutex_destroy(&d->mutex); - ms_free(f->data); -} - -static void winsndds_read_preprocess(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - DSCBUFFERDESC captureDesc; - HRESULT hr; - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - - d->framesPerDSBuffer = d->wfx.nAvgBytesPerSec/4; - winsndds_apply_settings(d); - ms_message("full duplex and echo canceller! (%x)" ,d->lpDirectSound); - ms_DirectSoundCaptureCreate( &d->in_guid, &d->lpDirectSoundCapture, NULL ); - - ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC)); - captureDesc.dwSize = sizeof(DSCBUFFERDESC); - captureDesc.dwFlags = 0; - captureDesc.dwBufferBytes = d->framesPerDSBuffer; - captureDesc.lpwfxFormat = &d->wfx; - - if ((hr = IDirectSoundCapture_CreateCaptureBuffer( d->lpDirectSoundCapture, - &captureDesc, &d->lpDirectSoundInputBuffer, NULL)) != DS_OK) - { - return; - } - d->readOffset = 0; - - hr = IDirectSoundCaptureBuffer_Start( d->lpDirectSoundInputBuffer, DSCBSTART_LOOPING ); - - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f->ticker,winsndds_get_cur_time,d); - ms_mutex_unlock(&f->ticker->lock); - - d->thread_running=TRUE; - ms_thread_create(&d->thread,NULL,winsndds_read_thread,d); - ms_mutex_lock(&d->thread_lock); - ms_cond_wait(&d->thread_cond,&d->thread_lock); - ms_mutex_unlock(&d->thread_lock); - - return; -} - -static void winsndds_read_postprocess(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - - ms_mutex_lock(&d->thread_lock); - d->thread_running=FALSE; - ms_cond_wait(&d->thread_cond,&d->thread_lock); - ms_mutex_unlock(&d->thread_lock); - ms_thread_join(d->thread,NULL); - - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f->ticker,NULL,NULL); - ms_mutex_unlock(&f->ticker->lock); - - if( d->lpDirectSoundInputBuffer ) - { - IDirectSoundCaptureBuffer_Stop( d->lpDirectSoundInputBuffer ); - IDirectSoundCaptureBuffer_Release( d->lpDirectSoundInputBuffer ); - d->lpDirectSoundInputBuffer = NULL; - } - - if( d->lpDirectSoundCapture ) - { - IDirectSoundCapture_Release( d->lpDirectSoundCapture ); - d->lpDirectSoundCapture = NULL; - } - - ms_message("Shutting down sound device (playing: %i) (input-output: %i) (notplayed: %i)", d->nbufs_playing, d->stat_input - d->stat_output, d->stat_notplayed); - flushq(&d->rq,0); -} - -static void winsndds_read_process(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - mblk_t *m; - - ms_mutex_lock(&d->mutex); - while((m=getq(&d->rq))!=NULL){ - ms_queue_put(f->outputs[0],m); - } - ms_mutex_unlock(&d->mutex); -} - -static void winsndds_write_preprocess(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - - DWORD dwDataLen; - DWORD playCursor; - HWND hWnd; - HRESULT hr; - LPDIRECTSOUNDBUFFER pPrimaryBuffer; - DSBUFFERDESC primaryDesc; - DSBUFFERDESC secondaryDesc; - unsigned char* pDSBuffData; - DWORD outputBufferWriteOffsetBytes; - - MSList *filters=NULL; - MSFilter *f_capture_filter=NULL; - WinSndDs *d_capture_filter=NULL; - - filters=ms_filter_find_neighbours(f); - if (filters!=NULL) - { - MSList *it; - /* search for another winsndds filter */ - for(it=filters;it!=NULL;it=it->next) - { - f_capture_filter = (MSFilter*)it->data; - if (f_capture_filter->desc->id == MS_WINSNDDS_READ_ID) - { - /* found */ - d_capture_filter=(WinSndDs*)f_capture_filter->data; - break; - } - f_capture_filter=NULL; - } - ms_list_free(filters); - } - - d->stat_input=0; - d->stat_output=0; - d->stat_notplayed=0; - - d->framesPerDSBuffer = d->wfx.nAvgBytesPerSec/4; - winsndds_apply_settings(d); - - if (d_capture_filter!=NULL - && d_capture_filter->lpDirectSoundCapture!=NULL - && IsEqualIID(d_capture_filter->in_guid, d->in_guid)) - { - DSCBUFFERDESC captureDesc; - - winsndds_read_postprocess(f_capture_filter); - - DSCEFFECTDESC dscfx[1]; - ZeroMemory( &dscfx[0], sizeof( DSCEFFECTDESC ) ); - dscfx[0].dwSize = sizeof( DSCEFFECTDESC ); - dscfx[0].dwFlags = DSCFX_LOCSOFTWARE ; - dscfx[0].guidDSCFXClass = GUID_DSCFX_CLASS_AEC; - dscfx[0].guidDSCFXInstance = GUID_DSCFX_MS_AEC; - dscfx[0].dwReserved1 = 0; - dscfx[0].dwReserved2 = 0; - - d_capture_filter->framesPerDSBuffer = d_capture_filter->wfx.nAvgBytesPerSec/4; - winsndds_apply_settings(d_capture_filter); - - ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC)); - captureDesc.dwSize = sizeof(DSCBUFFERDESC); - captureDesc.dwFlags = DSCBCAPS_CTRLFX; - captureDesc.dwBufferBytes = d_capture_filter->framesPerDSBuffer; - captureDesc.lpwfxFormat = &d_capture_filter->wfx; - captureDesc.dwFXCount = 1; - captureDesc.lpDSCFXDesc = dscfx; - - ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC)); - secondaryDesc.dwSize = sizeof(DSBUFFERDESC); - secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2 - | DSBCAPS_LOCSOFTWARE; - secondaryDesc.dwBufferBytes = d->framesPerDSBuffer; - secondaryDesc.lpwfxFormat = &d->wfx; - - hWnd = GetDesktopWindow(); - hr = ms_DirectSoundFullDuplexCreate(&d_capture_filter->in_guid, - &d->out_guid, - &captureDesc, - &secondaryDesc, - hWnd, - DSSCL_NORMAL, - &d->lpDirectSoundFullDuplex, - (LPDIRECTSOUNDCAPTUREBUFFER8*)&d_capture_filter->lpDirectSoundInputBuffer, - (LPDIRECTSOUNDBUFFER8*)&d->lpDirectSoundOutputBuffer, - NULL); - - if (hr!=DS_OK) - { - ms_message("full duplex and echo canceller: disabled!"); - captureDesc.dwFlags = 0; - captureDesc.dwFXCount = 0; - captureDesc.lpDSCFXDesc = NULL; - - hr = ms_DirectSoundFullDuplexCreate(&d_capture_filter->in_guid, - &d->out_guid, - &captureDesc, - &secondaryDesc, - hWnd, - DSSCL_NORMAL, - &d->lpDirectSoundFullDuplex, - (LPDIRECTSOUNDCAPTUREBUFFER8*)&d_capture_filter->lpDirectSoundInputBuffer, - (LPDIRECTSOUNDBUFFER8*)&d->lpDirectSoundOutputBuffer, - NULL); - } - if (hr!=DS_OK) - { - ms_message("full duplex and echo canceller: disabled!"); - return; - } - ms_message("full duplex and echo canceller: activated!"); - - d_capture_filter->readOffset = 0; - - hr = IDirectSoundCaptureBuffer_Start( d_capture_filter->lpDirectSoundInputBuffer, DSCBSTART_LOOPING ); - - ms_mutex_lock(&f->ticker->lock); - ms_ticker_set_time_func(f_capture_filter->ticker,winsndds_get_cur_time,d_capture_filter); - ms_mutex_unlock(&f->ticker->lock); - - d_capture_filter->thread_running=TRUE; - ms_thread_create(&d_capture_filter->thread,NULL,winsndds_read_thread,d_capture_filter); - ms_mutex_lock(&d_capture_filter->thread_lock); - ms_cond_wait(&d_capture_filter->thread_cond,&d_capture_filter->thread_lock); - ms_mutex_unlock(&d_capture_filter->thread_lock); - } - else - { - ms_DirectSoundCreate( &d->out_guid, &d->lpDirectSound, NULL ); - - - hWnd = GetDesktopWindow(); - if ((hr = IDirectSound_SetCooperativeLevel( d->lpDirectSound, - hWnd, DSSCL_PRIORITY)) != DS_OK) //DSSCL_EXCLUSIVE)) != DS_OK) - { - return ; - } - - ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC)); - primaryDesc.dwSize = sizeof(DSBUFFERDESC); - primaryDesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_PRIMARYBUFFER; - primaryDesc.dwBufferBytes = 0; - primaryDesc.lpwfxFormat = NULL; - if ((hr = IDirectSound_CreateSoundBuffer( d->lpDirectSound, - &primaryDesc, &pPrimaryBuffer, NULL)) != DS_OK) - { - return ; - } - - if ((hr = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &d->wfx)) != DS_OK) - { - return ; - } - IDirectSoundBuffer_Release(pPrimaryBuffer); - - ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC)); - secondaryDesc.dwSize = sizeof(DSBUFFERDESC); - secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2; - secondaryDesc.dwBufferBytes = d->framesPerDSBuffer; - secondaryDesc.lpwfxFormat = &d->wfx; - if ((hr = IDirectSound_CreateSoundBuffer( d->lpDirectSound, - &secondaryDesc, &d->lpDirectSoundOutputBuffer, NULL)) != DS_OK) - { - return ; - } - } - - if ((hr = IDirectSoundBuffer_Lock( d->lpDirectSoundOutputBuffer, 0, - d->framesPerDSBuffer, - (LPVOID*)&pDSBuffData, - &dwDataLen, NULL, 0, 0)) != DS_OK) - { - return ; - } - - ZeroMemory(pDSBuffData, dwDataLen); - if ((hr = IDirectSoundBuffer_Unlock( d->lpDirectSoundOutputBuffer, - pDSBuffData, dwDataLen, NULL, 0)) != DS_OK) - { - return ; - } - - hr = IDirectSoundBuffer_GetCurrentPosition( d->lpDirectSoundOutputBuffer, - &playCursor, &outputBufferWriteOffsetBytes ); - if( hr != DS_OK ) - { - return ; - } - - hr = IDirectSoundBuffer_SetCurrentPosition( d->lpDirectSoundOutputBuffer, 0 ); - if( hr != DS_OK ) - { - return ; - } - - hr = IDirectSoundBuffer_Play( d->lpDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING); - if( hr != DS_OK ) - { - return ; - } - d->writeOffset=-1; - - return ; -} - -static void winsndds_write_postprocess(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - - if( d->lpDirectSoundOutputBuffer ) - { - IDirectSoundBuffer_Stop( d->lpDirectSoundOutputBuffer ); - IDirectSoundBuffer_Release( d->lpDirectSoundOutputBuffer ); - d->lpDirectSoundOutputBuffer = NULL; - } - - if( d->lpDirectSound ) - { - IDirectSound_Release( d->lpDirectSound ); - d->lpDirectSound = NULL; - } - - if( d->lpDirectSoundFullDuplex ) - { - IDirectSoundFullDuplex_Release( d->lpDirectSoundFullDuplex ); - d->lpDirectSoundFullDuplex = NULL; - } - - ms_message("Shutting down sound device (playing: %i) (input-output: %i) (notplayed: %i)", d->nbufs_playing, d->stat_input - d->stat_output, d->stat_notplayed); - d->writeOffset=-1; -} - -static void winsndds_write_process(MSFilter *f){ - WinSndDs *d=(WinSndDs*)f->data; - int discarded=0; - DWORD dwStatus; - HRESULT hr; - - if (d->lpDirectSoundOutputBuffer==NULL) { - ms_queue_flush(f->inputs[0]); - return; - } - - ms_bufferizer_put_from_queue(&d->output_buff,f->inputs[0]); - - if (d->writeOffset==-1) - { - if (ms_bufferizer_get_avail(&d->output_buff)>=d->framesPerDSBuffer) - { - DWORD playCursor; - DWORD outputBufferWriteOffsetBytes; - IDirectSoundBuffer_GetCurrentPosition( d->lpDirectSoundOutputBuffer, - &playCursor, &outputBufferWriteOffsetBytes ); - d->writeOffset = outputBufferWriteOffsetBytes; - } - else - return; - } - - DWORD current_playOffset; - long msize_max = 0; - DWORD currentWriteOffset; - IDirectSoundBuffer_GetCurrentPosition( d->lpDirectSoundOutputBuffer, - ¤t_playOffset, ¤tWriteOffset ); - - msize_max = current_playOffset - currentWriteOffset; - if( msize_max < 0 ) msize_max += d->framesPerDSBuffer; - - /* write from d->writeOffset up to current_playOffset */ - msize_max=current_playOffset-d->writeOffset; - if( msize_max < 0 ) msize_max += d->framesPerDSBuffer; - - //ms_message("DS information: last_writeOffset=%i current_playOffset=%i current_writeOffset=%i max_writable=%i", - // d->writeOffset, current_playOffset, currentWriteOffset, msize_max); - - hr = IDirectSoundBuffer_GetStatus (d->lpDirectSoundOutputBuffer, &dwStatus); - if (dwStatus & DSBSTATUS_BUFFERLOST) { - hr = IDirectSoundBuffer_Restore (d->lpDirectSoundOutputBuffer); - d->writeOffset = 0; - ms_message("DSBSTATUS_BUFFERLOST: restoring buffer"); - } - - if (msize_max==0) - return; - int msize=d->framesPerDSBuffer/4; - if (msize>msize_max) - msize = msize_max; - while (ms_bufferizer_get_avail(&d->output_buff)>=msize) - { - LPBYTE lpOutBuf1 = NULL; - LPBYTE lpOutBuf2 = NULL; - DWORD dwOutSize1 = 0; - DWORD dwOutSize2 = 0; - char input[15360]; - - hr = IDirectSoundBuffer_Lock ( d->lpDirectSoundOutputBuffer, - d->writeOffset, msize, - (void **) &lpOutBuf1, &dwOutSize1, - (void **) &lpOutBuf2, &dwOutSize2, 0); /* DSBLOCK_FROMWRITECURSOR); */ - if (hr != DS_OK) - { - ms_error("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n", hr); - break; - } - - if (dwOutSize1==0) - { - ms_error("no free room to play sample\n"); - } - else if (dwOutSize1+dwOutSize2!=msize) - { - ms_bufferizer_read(&d->output_buff,(uint8_t*)input,dwOutSize1+dwOutSize2); - memcpy(lpOutBuf1, input, dwOutSize1); - memcpy(lpOutBuf2, input+dwOutSize1, dwOutSize2); - } - else if (dwOutSize1>=msize) - { - ms_bufferizer_read(&d->output_buff,(uint8_t*)input,msize); - memcpy(lpOutBuf1, input, msize); - } - else - { - ms_bufferizer_read(&d->output_buff,(uint8_t*)input,msize); - memcpy(lpOutBuf1, input, dwOutSize1); - memcpy(lpOutBuf2, input+dwOutSize1, dwOutSize2); - } - - d->writeOffset=(d->writeOffset+dwOutSize1+dwOutSize2) % d->framesPerDSBuffer; - msize_max = msize_max - (dwOutSize1+dwOutSize2); - if (msize>msize_max) - msize = msize_max; - IDirectSoundBuffer_Unlock( d->lpDirectSoundOutputBuffer, - lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2); - if (dwOutSize1==0) - break; - if (dwOutSize1+dwOutSize2!=msize) - break; - } - if (msize==0) - { - if (ms_bufferizer_get_avail(&d->output_buff)>=3*d->wfx.nSamplesPerSec/50) - { - ms_warning("Removing extra data for sound card %i", ms_bufferizer_get_avail(&d->output_buff)); - ms_bufferizer_uninit(&d->output_buff); - ms_bufferizer_init(&d->output_buff); - } - } - - if (discarded>0) - ms_warning("Extra data for sound card removed (%i buf), (playing: %i) (input-output: %i)", discarded, d->nbufs_playing, d->stat_input - d->stat_output); -} - -static int get_rate(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - *((int*)arg)=d->wfx.nSamplesPerSec; - return 0; -} - -static int set_rate(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - d->wfx.nSamplesPerSec=*((int*)arg); - return 0; -} - -static int set_nchannels(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - d->wfx.nChannels=*((int*)arg); - return 0; -} - -static int winsndds_get_stat_input(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - return d->stat_input; -} - -static int winsndds_get_stat_ouptut(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - - return d->stat_output; -} - -static int winsndds_get_stat_discarded(MSFilter *f, void *arg){ - WinSndDs *d=(WinSndDs*)f->data; - - return d->stat_notplayed; -} - -static MSFilterMethod winsndds_methods[]={ - { MS_FILTER_GET_SAMPLE_RATE , get_rate }, - { MS_FILTER_SET_SAMPLE_RATE , set_rate }, - { MS_FILTER_SET_NCHANNELS , set_nchannels }, - { MS_FILTER_GET_STAT_INPUT, winsndds_get_stat_input }, - { MS_FILTER_GET_STAT_OUTPUT, winsndds_get_stat_ouptut }, - { MS_FILTER_GET_STAT_DISCARDED, winsndds_get_stat_discarded }, - { 0 , NULL } -}; - -MSFilterDesc winsndds_read_desc={ - MS_WINSNDDS_READ_ID, - "DirecSoundRead", - "DirectSound capture filter for Windows", - MS_FILTER_OTHER, - NULL, - 0, - 1, - winsndds_init, - winsndds_read_preprocess, - winsndds_read_process, - winsndds_read_postprocess, - winsndds_uninit, - winsndds_methods -}; - - -MSFilterDesc winsndds_write_desc={ - MS_WINSNDDS_WRITE_ID, - "DirecSoundWrite", - "DirectSound playback filter for Windows", - MS_FILTER_OTHER, - NULL, - 1, - 0, - winsndds_init, - winsndds_write_preprocess, - winsndds_write_process, - winsndds_write_postprocess, - winsndds_uninit, - winsndds_methods -}; - -MSFilter *ms_winsndds_read_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsndds_read_desc); - WinSndDsCard *wc=(WinSndDsCard*)card->data; - WinSndDs *d=(WinSndDs*)f->data; - d->dev_id=wc->in_devid; - memcpy(&d->in_guid, &wc->in_guid, sizeof(GUID)); - memcpy(&d->out_guid, &wc->out_guid, sizeof(GUID)); - return f; -} - - -MSFilter *ms_winsndds_write_new(MSSndCard *card){ - MSFilter *f=ms_filter_new_from_desc(&winsndds_write_desc); - WinSndDsCard *wc=(WinSndDsCard*)card->data; - WinSndDs *d=(WinSndDs*)f->data; - d->dev_id=wc->out_devid; - memcpy(&d->in_guid, &wc->in_guid, sizeof(GUID)); - memcpy(&d->out_guid, &wc->out_guid, sizeof(GUID)); - return f; -} - -MS_FILTER_DESC_EXPORT(winsndds_read_desc) -MS_FILTER_DESC_EXPORT(winsndds_write_desc) - -#endif diff --git a/linphone/mediastreamer2/src/winvideo.c b/linphone/mediastreamer2/src/winvideo.c deleted file mode 100644 index 91c123ba4..000000000 --- a/linphone/mediastreamer2/src/winvideo.c +++ /dev/null @@ -1,682 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" -#include "Vfw.h" -#include -#include - -#include "nowebcam.h" -#include "mediastreamer2/mswebcam.h" - -#ifndef AVSTREAMMASTER_NONE -#define AVSTREAMMASTER_NONE 1 -#endif - -#define AMD_HACK2 - -typedef struct V4wState{ -#ifdef AMD_HACK2 - ms_thread_t thread; - ms_mutex_t thread_lock; - ms_cond_t thread_cond; - bool_t thread_running; -#endif - char dev[512]; - int devidx; - HWND capvideo; - MSVideoSize vsize; - int pix_fmt; - mblk_t *mire[10]; - mblk_t *reverted; - queue_t rq; - ms_mutex_t mutex; - int frame_ind; - int frame_max; - float fps; - float start_time; - int frame_count; - bool_t running; - bool_t startwith_yuv_bug; /* avoid bug with USB vimicro cards. */ - bool_t started; - bool_t autostarted; - bool_t invert_rgb; -}V4wState; - -static void dummy(void*p){ -} - -LRESULT CALLBACK VideoStreamCallback(HWND hWnd, LPVIDEOHDR lpVHdr) -{ - V4wState *s; - mblk_t *buf; - int size; - - s = (V4wState *)capGetUserData(hWnd); - if (s==NULL) - return FALSE; - - size = lpVHdr->dwBufferLength; - if (size>0 && s->running){ - buf = esballoc(lpVHdr->lpData,size,0,dummy); - buf->b_wptr+=size; - - ms_mutex_lock(&s->mutex); - putq(&s->rq, buf); - ms_mutex_unlock(&s->mutex); - } - return TRUE ; -} - -static bool_t try_format(V4wState *s, BITMAPINFO *videoformat, MSPixFmt pixfmt){ - bool_t ret; - capGetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - videoformat->bmiHeader.biSizeImage = 0; - videoformat->bmiHeader.biWidth = s->vsize.width; - videoformat->bmiHeader.biHeight = s->vsize.height; - switch(pixfmt){ - case MS_YUV420P: - videoformat->bmiHeader.biBitCount = 12; - videoformat->bmiHeader.biCompression=MAKEFOURCC('I','4','2','0'); - break; - case MS_YUY2: - videoformat->bmiHeader.biBitCount = 16; - videoformat->bmiHeader.biCompression=MAKEFOURCC('Y','U','Y','2'); - break; - case MS_RGB24: - videoformat->bmiHeader.biBitCount = 24; - videoformat->bmiHeader.biCompression=BI_RGB; - break; - default: - return FALSE; - } - ret=capSetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - if (ret) { - /*recheck video format */ - capGetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - } - return ret; -} - -static int v4w_open_videodevice(V4wState *s) -{ - CAPTUREPARMS capparam ; - BITMAPINFO videoformat; - char compname[5]; - int i; - MSPixFmt driver_last; - char dev[80]; - char ver[80]; - compname[4]='\0'; - - for (i = 0; i < 9; i++){ - if (capGetDriverDescription(i, dev, sizeof (dev), - ver, sizeof (ver))) - { - snprintf(s->dev, sizeof(s->dev), "%s/%s",dev,ver); - ms_message("v4w: detected %s",s->dev); - s->devidx=i; - break; - } - } - if (s->capvideo==NULL) - { - s->capvideo = capCreateCaptureWindow("Capture Window",WS_CHILD /* WS_OVERLAPPED */ - ,0,0,s->vsize.width,s->vsize.height,HWND_MESSAGE, 0) ; - if (s->capvideo==NULL) - { - ms_warning("v4w: could not create capture windows"); - return -1; - } - } - - if(!capDriverConnect(s->capvideo,s->devidx )) - { - ms_warning("v4w: could not connect to capture driver"); - DestroyWindow(s->capvideo); - s->capvideo=NULL; - s->pix_fmt=MS_YUV420P; /* no webcam stuff */ - return -1; - } - /* - capPreviewRate(s->capvideo,s->fps) ; - if(!capPreview (s->capvideo, 1)) - { - ms_warning("v4w: cannot start video preview"); - capDriverDisconnect(s->capvideo); - DestroyWindow(s->capvideo); - s->capvideo=NULL; - return -1; - } - */ - capCaptureGetSetup(s->capvideo,&capparam,sizeof(capparam)) ; - capparam.dwRequestMicroSecPerFrame = 100000 ; - // detach capture from application - capparam.fYield = TRUE ; - capparam.fMakeUserHitOKToCapture = FALSE; - capparam.fAbortLeftMouse = FALSE; - capparam.fAbortRightMouse = FALSE; - capparam.wPercentDropForError = 90 ; - capparam.fCaptureAudio = FALSE ; - capparam.fAbortRightMouse = FALSE; - capparam.fAbortLeftMouse = FALSE; - capparam.AVStreamMaster = AVSTREAMMASTER_NONE ; - - if (!capCaptureSetSetup(s->capvideo,&capparam,sizeof(capparam))){ - ms_error("capCaptureSetSetup failed."); - } - capSetUserData(s->capvideo, s); - capGetVideoFormat(s->capvideo, &videoformat, sizeof(BITMAPINFO)); - /* "orig planes = " disp->videoformat.bmiHeader.biPlanes */ - /* "orig bitcount = " disp->videoformat.bmiHeader.biBitCount */ - /* "orig compression = " disp->videoformat.bmiHeader.biCompression */ - memcpy(compname,&videoformat.bmiHeader.biCompression,4); - ms_message("v4w: camera's current format is %s", compname); - - driver_last=ms_fourcc_to_pix_fmt(videoformat.bmiHeader.biCompression); - if (s->startwith_yuv_bug==TRUE && try_format(s,&videoformat,MS_RGB24)){ - s->pix_fmt=MS_RGB24; - ms_message("Using RGB24"); - }else if (driver_last!=MS_PIX_FMT_UNKNOWN && try_format(s,&videoformat,driver_last)){ - ms_message("Using driver last setting"); - s->pix_fmt=driver_last; - }else if (try_format(s,&videoformat,MS_YUV420P)){ - s->pix_fmt=MS_YUV420P; - ms_message("Using YUV420P"); - }else if (try_format(s,&videoformat,MS_RGB24)){ - s->pix_fmt=MS_RGB24; - ms_message("Using RGB24"); - s->startwith_yuv_bug=TRUE; - }else if (try_format(s,&videoformat,MS_YUY2)){ - s->pix_fmt=MS_YUY2; - ms_message("Using YUY2"); - }else{ - ms_error("v4w: Failed to set any video format."); - capDriverDisconnect (s->capvideo); - DestroyWindow(s->capvideo); - s->capvideo=NULL; - return -1; - } - if (s->pix_fmt==MS_RGB24){ - s->invert_rgb=(videoformat.bmiHeader.biHeight>0); - }else s->invert_rgb=FALSE; - - if (!capSetCallbackOnVideoStream(s->capvideo, VideoStreamCallback)) - { - ms_error("v4w: fail to set capture callback"); - capDriverDisconnect (s->capvideo); - DestroyWindow(s->capvideo); - s->capvideo=NULL; - return -1; - } - if (!capCaptureSequenceNoFile(s->capvideo)){ - ms_error("v4w: fail to start capture"); - capDriverDisconnect (s->capvideo); - capSetCallbackOnVideoStream(s->capvideo, NULL); - DestroyWindow(s->capvideo); - s->capvideo=NULL; - } - return 0; -} - -static void v4w_init(MSFilter *f){ - V4wState *s=(V4wState *)ms_new0(V4wState,1); - int idx; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->pix_fmt=MS_RGB24; - - s->capvideo=NULL; - qinit(&s->rq); - for (idx=0;idx<10;idx++) - { - s->mire[idx]=NULL; - } - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - s->started=FALSE; - s->autostarted=FALSE; - s->invert_rgb=FALSE; - s->reverted=NULL; -#ifdef AMD_HACK2 - /* avoid bug with USB vimicro cards: - How can I detect that this problem exist? - */ - s->startwith_yuv_bug=FALSE; -#endif - -#ifdef AMD_HACK2 - s->thread = NULL; - ms_mutex_init(&s->thread_lock,NULL); - ms_cond_init(&s->thread_cond,NULL); - s->thread_running = FALSE; -#endif - - f->data=s; -} - -static int _v4w_start(V4wState *s, void *arg) -{ - int i; - s->frame_count=-1; - i = v4w_open_videodevice(s); - if (i==0 && s->startwith_yuv_bug==TRUE) - { - /* reopen device directly with MS_RGB24 */ - if (s->capvideo){ - capSetUserData(s->capvideo, (long) 0); - capCaptureStop(s->capvideo); - capCaptureAbort(s->capvideo); - capDriverDisconnect(s->capvideo); - capSetCallbackOnVideoStream(s->capvideo, NULL); - flushq(&s->rq,0); - ms_message("v4w: destroying capture window"); - DestroyWindow(s->capvideo); - ms_message("v4w: capture window destroyed"); - s->capvideo=NULL; - } - i = v4w_open_videodevice(s); - } - return i; -} - -static int _v4w_stop(V4wState *s, void *arg){ - s->frame_count=-1; - if (s->capvideo){ - capCaptureStop(s->capvideo); - Sleep(1000); - //capCaptureAbort(s->capvideo); - capSetCallbackOnVideoStream(s->capvideo, NULL); - //SendMessage(s->capvideo, WM_CLOSE, 0, 0); - capDriverDisconnect(s->capvideo); - capSetUserData(s->capvideo, (long) 0); - flushq(&s->rq,0); - ms_message("v4w: destroying capture window"); - DestroyWindow(s->capvideo); - ms_message("v4w: capture window destroyed"); - s->capvideo=NULL; - } -#if 0 - if (s->capvideo){ - CAPSTATUS status; - capCaptureStop(s->capvideo); - capDriverDisconnect(s->capvideo); - capCaptureAbort(s->capvideo); - - capSetCallbackOnVideoStream(s->capvideo, NULL); - while (1) - { - if (capGetStatus(s->capvideo, &status, sizeof(status))) - { - if (status.fCapturingNow==FALSE) - break; - Sleep(10); - ms_message("still capturing"); - } - } - DestroyWindow(s->capvideo); - s->capvideo=NULL; - } -#endif - return 0; -} - -#ifdef AMD_HACK2 - -void * -v4w_thread(void *arg) -{ - V4wState *s=(V4wState*)arg; - MSG msg; - - ms_mutex_lock(&s->thread_lock); - _v4w_start(s, NULL); - ms_cond_signal(&s->thread_cond); - ms_mutex_unlock(&s->thread_lock); - - while(s->thread_running) - { - BOOL fGotMessage; - if((fGotMessage = PeekMessage(&msg, (HWND) s->capvideo, 0, 0, PM_REMOVE)) != 0) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - else - Sleep(10); - } - - ms_mutex_lock(&s->thread_lock); - _v4w_stop(s, NULL); - ms_cond_signal(&s->thread_cond); - ms_mutex_unlock(&s->thread_lock); - ms_thread_exit(NULL); - return NULL; -} - - -static int v4w_start(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->thread_running=TRUE; - ms_thread_create(&s->thread,NULL,v4w_thread,s); - ms_mutex_lock(&s->thread_lock); - ms_cond_wait(&s->thread_cond,&s->thread_lock); - ms_mutex_unlock(&s->thread_lock); - s->started=TRUE; - return 0; -} - -static int v4w_stop(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - ms_mutex_lock(&s->thread_lock); - s->thread_running=FALSE; - //SendMessage(s->capvideo, WM_CLOSE, 0, 0); - ms_cond_wait(&s->thread_cond,&s->thread_lock); - ms_mutex_unlock(&s->thread_lock); - ms_thread_join(s->thread,NULL); - s->started=FALSE; - return 0; -} - -#else - -static int v4w_start(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - _v4w_start(s, NULL); - s->started=TRUE; - return 0; -} - -static int v4w_stop(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - _v4w_stop(s, NULL); - s->started=FALSE; - return 0; -} - -#endif - -static void v4w_uninit(MSFilter *f){ - V4wState *s=(V4wState*)f->data; - int idx; - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - for (idx=0;idx<10;idx++) - { - if (s->mire[idx]==NULL) - break; - freemsg(s->mire[idx]); - } - if (s->capvideo!=NULL) - { - ms_message("v4w: destroying capture window"); - DestroyWindow(s->capvideo); - ms_message("v4w: capture window destroyed"); - s->capvideo=NULL; - } - if (s->reverted){ - freemsg(s->reverted); - } -#ifdef AMD_HACK2 - ms_cond_destroy(&s->thread_cond); - ms_mutex_destroy(&s->thread_lock); -#endif - ms_free(s); -} - -static mblk_t * v4w_make_nowebcam(V4wState *s){ - int idx; - int count; - if (s->mire[0]==NULL && s->frame_ind==0){ - /* load several images to fake a movie */ - for (idx=0;idx<10;idx++) - { - s->mire[idx]=ms_load_nowebcam(&s->vsize, idx); - if (s->mire[idx]==NULL) - break; - } - if (idx==0) - s->mire[0]=ms_load_nowebcam(&s->vsize, -1); - } - for (count=0;count<10;count++) - { - if (s->mire[count]==NULL) - break; - } - - s->frame_ind++; - if (count==0) - return NULL; - - idx = s->frame_ind%count; - if (s->mire[idx]!=NULL) - return s->mire[idx]; - return s->mire[0]; -} - -static void v4w_preprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - if (!s->started) { - ms_message("V4W auto-started."); - v4w_start(obj,NULL); - s->autostarted=TRUE; - } - s->running=TRUE; - if (s->capvideo==NULL) - s->fps=1; -} - -static void v4w_postprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - s->running=FALSE; - if (s->autostarted){ - v4w_stop(obj,NULL); - } -} - -static void v4w_process(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - mblk_t *m; - uint32_t timestamp; - int cur_frame; - - if (s->frame_count==-1){ - s->start_time=obj->ticker->time; - s->frame_count=0; - } - - - cur_frame=((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>s->frame_count){ - mblk_t *om=NULL; - ms_mutex_lock(&s->mutex); - /*keep the most recent frame if several frames have been captured */ - if (s->capvideo!=NULL){ - while((m=getq(&s->rq))!=NULL){ - if (om!=NULL) freemsg(om); - om=m; - } - if (om!=NULL){ - if (s->invert_rgb){ - MSVideoSize roi; - if (s->reverted==NULL){ - s->reverted=allocb(om->b_wptr-om->b_rptr,0); - s->reverted->b_wptr=s->reverted->b_datap->db_lim; - } - roi=s->vsize; - rgb24_copy_revert(s->reverted->b_rptr,roi.width*3, - om->b_rptr,roi.width*3,roi); - freemsg(om); - om=dupb(s->reverted); - } - } - }else { - mblk_t *nowebcam = v4w_make_nowebcam(s); - if (nowebcam!=NULL){ - om=dupmsg(nowebcam); - mblk_set_precious_flag(om,1); - } - } - ms_mutex_unlock(&s->mutex); - if (om!=NULL){ - timestamp=obj->ticker->time*90;/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - ms_queue_put(obj->outputs[0],om); - } - s->frame_count++; - } -} - -static int v4w_set_fps(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->fps=*((float*)arg); - return 0; -} - -static int v4w_get_pix_fmt(MSFilter *f,void *arg){ - V4wState *s=(V4wState*)f->data; - if (!s->started) { - ms_message("V4W auto-started in v4w_get_pix_fmt()"); - v4w_start(f,NULL); - s->autostarted=TRUE; - } - *((MSPixFmt*)arg) = (MSPixFmt)s->pix_fmt; - return 0; -} - -static int v4w_set_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->vsize=*((MSVideoSize*)arg); - return 0; -} - -static int v4w_get_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - MSVideoSize *vs=(MSVideoSize*)arg; - vs->width=s->vsize.width; - vs->height=s->vsize.height; - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , v4w_set_fps }, - { MS_FILTER_GET_PIX_FMT , v4w_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, v4w_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, v4w_get_vsize }, - { MS_V4L_START , v4w_start }, - { MS_V4L_STOP , v4w_stop }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_v4w_desc={ - MS_V4L_ID, - "MSV4w", - N_("A video4windows compatible source filter to stream pictures."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - v4w_init, - v4w_preprocess, - v4w_process, - v4w_postprocess, - v4w_uninit, - methods -}; - -#else - -MSFilterDesc ms_v4w_desc={ - .id=MS_V4L_ID, - .name="MSV4w", - .text=N_("A video4windows compatible source filter to stream pictures."), - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=v4w_init, - .preprocess=v4w_preprocess, - .process=v4w_process, - .postprocess=v4w_postprocess, - .uninit=v4w_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_v4w_desc) - -#if 0 -static void ms_v4w_detect(MSWebCamManager *obj); - -static void ms_v4w_cam_init(MSWebCam *cam){ -} - - -static MSFilter *ms_v4w_create_reader(MSWebCam *obj){ - MSFilter *f= ms_filter_new_from_desc(&ms_v4w_desc); - V4wState *s=(V4wState*)f->data; - s->devidx=(int)obj->data; - return f; -} - -MSWebCamDesc ms_v4w_cam_desc={ - "VideoForWindows grabber", - &ms_v4w_detect, - &ms_v4w_cam_init, - &ms_v4w_create_reader, - NULL -}; - -static void ms_v4w_detect(MSWebCamManager *obj){ - int i; - char dev[80]; - char ver[80]; - char name[160]; - MSWebCam *cam; - for (i = 0; i < 9; i++){ - if (capGetDriverDescription(i, dev, sizeof (dev), - ver, sizeof (ver))){ - HWND hwnd=capCreateCaptureWindow("Capture Window",WS_CHILD /* WS_OVERLAPPED */ - ,0,0,352,288,HWND_MESSAGE, 0) ; - if (hwnd==NULL) break; - if(!capDriverConnect(hwnd,i )){ - ms_warning("v4w: could not connect to capture driver, no webcam connected."); - DestroyWindow(hwnd); - break; - }else{ - capGetDriverDescription(i, dev, sizeof (dev),ver, sizeof (ver)); - capDriverDisconnect(hwnd); - DestroyWindow(hwnd); - } - snprintf(name, sizeof(name), "%s/%s",dev,ver); - cam=ms_web_cam_new(&ms_v4w_cam_desc); - cam->data=(void*)i;/*store the device index */ - cam->name=ms_strdup(name); - ms_web_cam_manager_add_cam(obj,cam); - } - } -} - -#endif diff --git a/linphone/mediastreamer2/src/winvideo2.c b/linphone/mediastreamer2/src/winvideo2.c deleted file mode 100755 index eb64ae2ae..000000000 --- a/linphone/mediastreamer2/src/winvideo2.c +++ /dev/null @@ -1,505 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" -#include "Vfw.h" -#include -#include - -#include "mediastreamer2/mswebcam.h" - -#ifndef AVSTREAMMASTER_NONE -#define AVSTREAMMASTER_NONE 1 -#endif - -typedef void (*queue_msg_t)(void *, mblk_t *); - -typedef struct VfwEngine{ - ms_thread_t thread; - char dev[512]; - int devidx; - HWND capvideo; - MSVideoSize vsize; - MSPixFmt pix_fmt; - queue_msg_t cb; - void *cb_data; - bool_t started; - bool_t configured; - bool_t thread_running; -}VfwEngine; - -#define VFW_ENGINE_MAX_INSTANCES 9 - -static VfwEngine *engines[VFW_ENGINE_MAX_INSTANCES]={0}; - -static bool_t try_format(VfwEngine *s, BITMAPINFO *videoformat, MSPixFmt pixfmt){ - MSVideoSize tried_size=s->vsize; - bool_t ret; - do{ - capGetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - videoformat->bmiHeader.biSizeImage = 0; - videoformat->bmiHeader.biWidth = tried_size.width; - videoformat->bmiHeader.biHeight = tried_size.height; - switch(pixfmt){ - case MS_YUV420P: - videoformat->bmiHeader.biBitCount = 12; - videoformat->bmiHeader.biCompression=MAKEFOURCC('I','4','2','0'); - break; - case MS_YUY2: - videoformat->bmiHeader.biBitCount = 16; - videoformat->bmiHeader.biCompression=MAKEFOURCC('Y','U','Y','2'); - break; - case MS_RGB24: - videoformat->bmiHeader.biBitCount = 24; - videoformat->bmiHeader.biCompression=BI_RGB; - break; - default: - return FALSE; - } - ms_message("Trying video size %ix%i",tried_size.width,tried_size.height); - ret=capSetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - tried_size=ms_video_size_get_just_lower_than(tried_size); - }while(ret==FALSE && tried_size.width!=0); - if (ret) { - /*recheck video format */ - capGetVideoFormat(s->capvideo, videoformat, sizeof(BITMAPINFO)); - s->vsize.width=videoformat->bmiHeader.biWidth; - s->vsize.height=videoformat->bmiHeader.biHeight; - } - return ret; -} - -static int _vfw_engine_select_format(VfwEngine *obj){ - BITMAPINFO videoformat; - MSPixFmt driver_last; - char compname[5]; - - capGetVideoFormat(obj->capvideo, &videoformat, sizeof(BITMAPINFO)); - memcpy(compname,&videoformat.bmiHeader.biCompression,4); - compname[4]='\0'; - ms_message("vfw: camera's current format is '%s' at %ix%i", compname, - videoformat.bmiHeader.biWidth,videoformat.bmiHeader.biHeight); - driver_last=ms_fourcc_to_pix_fmt(videoformat.bmiHeader.biCompression); - if (driver_last!=MS_PIX_FMT_UNKNOWN && try_format(obj,&videoformat,driver_last)){ - ms_message("Using driver last setting"); - obj->pix_fmt=driver_last; - }else if (try_format(obj,&videoformat,MS_YUV420P)){ - obj->pix_fmt=MS_YUV420P; - ms_message("Using YUV420P"); - }else if (try_format(obj,&videoformat,MS_RGB24)){ - obj->pix_fmt=MS_RGB24; - ms_message("Using RGB24"); - }else if (try_format(obj,&videoformat,MS_YUY2)){ - obj->pix_fmt=MS_YUY2; - ms_message("Using YUY2"); - }else{ - ms_error("v4w: Failed to set any video format."); - return -1; - } - if (obj->pix_fmt==MS_RGB24){ - if (videoformat.bmiHeader.biHeight>0){ - obj->pix_fmt=MS_RGB24_REV; - } - } - return 0; -} - -static void dummy(void*p){ -} - -LRESULT CALLBACK vfw_engine_stream_callback(HWND hWnd, LPVIDEOHDR lpVHdr) -{ - VfwEngine *s; - mblk_t *buf; - int size; - - s = (VfwEngine *)capGetUserData(hWnd); - if (s==NULL) - return FALSE; - - size = lpVHdr->dwBufferLength; - if (size>0 && s->cb!=NULL && s->started){ - buf = esballoc(lpVHdr->lpData,size,0,dummy); - buf->b_wptr+=size; - s->cb(s->cb_data,buf); - } - return TRUE ; -} - -static void * -vfw_engine_thread(void *arg) -{ - VfwEngine *s=(VfwEngine*)arg; - MSG msg; - - while(s->thread_running) - { - BOOL fGotMessage; - while((fGotMessage = PeekMessage(&msg, (HWND) s->capvideo, 0, 0, PM_REMOVE)) != 0) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - Sleep(10); - } - ms_thread_exit(NULL); - return NULL; -} - -static void _vfw_engine_unconfigure(VfwEngine *obj){ - if (!capCaptureStop(obj->capvideo)){ - ms_error("vfw: fail to stop capture !"); - } - obj->thread_running=FALSE; - ms_thread_join(obj->thread,NULL); - obj->configured=FALSE; -} - -static void _vfw_engine_disconnect(VfwEngine *obj){ - capDriverDisconnect(obj->capvideo); - DestroyWindow(obj->capvideo); - obj->capvideo=NULL; -} - -static void vfw_engine_destroy(VfwEngine *obj){ - if (obj->configured){ - _vfw_engine_unconfigure(obj); - } - _vfw_engine_disconnect(obj); - ms_free(obj); -} - -static int _vfw_engine_setup(VfwEngine *obj){ - CAPTUREPARMS capparam ; - capCaptureGetSetup(obj->capvideo,&capparam,sizeof(capparam)) ; - capparam.dwRequestMicroSecPerFrame = 33000 ; /*makes around 30fps*/ - // detach capture from application - capparam.fYield = TRUE ; - capparam.fMakeUserHitOKToCapture = FALSE; - capparam.fAbortLeftMouse = FALSE; - capparam.fAbortRightMouse = FALSE; - capparam.wPercentDropForError = 90 ; - capparam.fCaptureAudio = FALSE ; - capparam.fAbortRightMouse = FALSE; - capparam.fAbortLeftMouse = FALSE; - capparam.AVStreamMaster = AVSTREAMMASTER_NONE ; - if (!capCaptureSetSetup(obj->capvideo,&capparam,sizeof(capparam))){ - ms_error("capCaptureSetSetup failed."); - return -1; - } - capSetUserData(obj->capvideo, obj); - return 0; -} - -static int _vfw_engine_connect(VfwEngine *obj){ - MSVideoSize sz; - sz.width=MS_VIDEO_SIZE_CIF_W; - sz.height=MS_VIDEO_SIZE_CIF_H; - HWND hwnd=capCreateCaptureWindow("Capture Window",WS_CHILD /* WS_OVERLAPPED */ - ,0,0,sz.width,sz.height,HWND_MESSAGE, 0) ; - - if (hwnd==NULL) return -1; - if(!capDriverConnect(hwnd,obj->devidx)){ - ms_warning("vfw: could not connect to capture driver, no webcam connected."); - DestroyWindow(hwnd); - return -1; - } - obj->capvideo=hwnd; - obj->vsize=sz; - return 0; -} - -static VfwEngine * vfw_engine_new(int i){ - char dev[512]; - char ver[512]; - VfwEngine *obj=(VfwEngine*)ms_new0(VfwEngine,1); - if (capGetDriverDescription(i, dev, sizeof (dev), - ver, sizeof (ver))){ - obj->devidx=i; - if (_vfw_engine_connect(obj)==-1){ - ms_free(obj); - return NULL; - } - strcpy(obj->dev,dev); - engines[i]=obj; - return obj; - } - return NULL; -} - -static void _vfw_engine_configure(VfwEngine *obj){ - if (_vfw_engine_setup(obj)==-1){ - return; - } - if (_vfw_engine_select_format(obj)==-1){ - return ; - } - capSetCallbackOnVideoStream(obj->capvideo, vfw_engine_stream_callback); - if (!capCaptureSequenceNoFile(obj->capvideo)){ - ms_error("vfw: fail to start capture !"); - } - ms_thread_create(&obj->thread,NULL,vfw_engine_thread,obj); - obj->configured=TRUE; -} - -static MSPixFmt vfw_engine_get_pix_fmt(VfwEngine *obj){ - if (!obj->configured) - _vfw_engine_configure(obj); - return obj->pix_fmt; -} - -static MSVideoSize vfw_engine_get_video_size(VfwEngine *obj){ - return obj->vsize; -} - -static void vfw_engine_set_video_size(VfwEngine *obj, MSVideoSize vsize){ - if (!obj->configured) - obj->vsize=vsize; - else if (ms_video_size_greater_than(vsize,obj->vsize) && !ms_video_size_equal(vsize,obj->vsize) ){ - _vfw_engine_unconfigure(obj); - _vfw_engine_disconnect(obj); - _vfw_engine_connect(obj); - obj->vsize=vsize; - _vfw_engine_configure(obj); - } -} - -static void vfw_engine_set_callback(VfwEngine* obj, queue_msg_t cb, void *cb_data){ - obj->cb=cb; - obj->cb_data=cb_data; -} - -static void vfw_engine_start_capture(VfwEngine *obj){ - if (!obj->configured) _vfw_engine_configure(obj); - obj->started=TRUE; -} - -static void vfw_engine_stop_capture(VfwEngine *obj){ - obj->started=FALSE; -} - -static void vfw_engines_free(void){ - int i; - for(i=0;ivsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - qinit(&s->rq); - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - f->data=s; -} - - - -static void vfw_uninit(MSFilter *f){ - VfwState *s=(VfwState*)f->data; - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - ms_free(s); -} - -static void vfw_callback(void *data, mblk_t *m){ - VfwState *s=(VfwState*)data; - ms_mutex_lock(&s->mutex); - putq(&s->rq,m); - ms_mutex_unlock(&s->mutex); -} - -static void vfw_preprocess(MSFilter * obj){ - VfwState *s=(VfwState*)obj->data; - if (s->eng==NULL) s->eng=engines[0]; - vfw_engine_set_callback(s->eng,vfw_callback,s); - vfw_engine_start_capture(s->eng); -} - -static void vfw_postprocess(MSFilter * obj){ - VfwState *s=(VfwState*)obj->data; - vfw_engine_stop_capture(s->eng); - flushq(&s->rq,0); -} - -static void vfw_process(MSFilter * obj){ - VfwState *s=(VfwState*)obj->data; - mblk_t *m; - uint32_t timestamp; - int cur_frame; - - if (s->frame_count==-1){ - s->start_time=(float)obj->ticker->time; - s->frame_count=0; - } - - cur_frame=(int)((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>s->frame_count){ - mblk_t *om=NULL; - /*keep the most recent frame if several frames have been captured */ - if (s->eng!=NULL){ - ms_mutex_lock(&s->mutex); - while((m=getq(&s->rq))!=NULL){ - ms_mutex_unlock(&s->mutex); - if (om!=NULL) freemsg(om); - om=m; - ms_mutex_lock(&s->mutex); - } - ms_mutex_unlock(&s->mutex); - } - if (om!=NULL){ - timestamp=(uint32_t)(obj->ticker->time*90);/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - ms_queue_put(obj->outputs[0],om); - } - s->frame_count++; - } -} - -static int vfw_set_fps(MSFilter *f, void *arg){ - VfwState *s=(VfwState*)f->data; - s->fps=*((float*)arg); - return 0; -} - -static int vfw_get_pix_fmt(MSFilter *f,void *arg){ - VfwState *s=(VfwState*)f->data; - MSPixFmt fmt=vfw_engine_get_pix_fmt(s->eng); - *((MSPixFmt*)arg)=fmt; - return 0; -} - -static int vfw_set_vsize(MSFilter *f, void *arg){ - VfwState *s=(VfwState*)f->data; - s->vsize=*((MSVideoSize*)arg); - vfw_engine_set_video_size(s->eng,s->vsize); - return 0; -} - -static int vfw_get_vsize(MSFilter *f, void *arg){ - VfwState *s=(VfwState*)f->data; - MSVideoSize *vs=(MSVideoSize*)arg; - *vs=vfw_engine_get_video_size(s->eng); - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , vfw_set_fps }, - { MS_FILTER_GET_PIX_FMT , vfw_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, vfw_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, vfw_get_vsize }, - { 0 , NULL } -}; - -#ifdef _MSC_VER - -MSFilterDesc ms_vfw_desc={ - MS_VFW_ID, - "MSVfw", - N_("A video for windows (vfw.h) based source filter to grab pictures."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - vfw_init, - vfw_preprocess, - vfw_process, - vfw_postprocess, - vfw_uninit, - methods -}; - -#else - -MSFilterDesc ms_vfw_desc={ - .id=MS_VFW_ID, - .name="MSVfw", - .text=N_("A video for windows (vfw.h) based source filter to grab pictures."), - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=vfw_init, - .preprocess=vfw_preprocess, - .process=vfw_process, - .postprocess=vfw_postprocess, - .uninit=vfw_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_vfw_desc) - -static void ms_vfw_detect(MSWebCamManager *obj); - -static void ms_vfw_cam_init(MSWebCam *cam){ -} - - -static MSFilter *ms_vfw_create_reader(MSWebCam *obj){ - MSFilter *f= ms_filter_new_from_desc(&ms_vfw_desc); - VfwState *s=(VfwState*)f->data; - s->eng=(VfwEngine*)obj->data; - return f; -} - -MSWebCamDesc ms_vfw_cam_desc={ - "VideoForWindows grabber", - &ms_vfw_detect, - &ms_vfw_cam_init, - &ms_vfw_create_reader, - NULL -}; - -static void ms_vfw_detect(MSWebCamManager *obj){ - int i; - MSWebCam *cam; - for (i = 0; i < VFW_ENGINE_MAX_INSTANCES; i++){ - VfwEngine *eng; - if ((eng=vfw_engine_new(i))!=NULL){ - cam=ms_web_cam_new(&ms_vfw_cam_desc); - cam->data=(void*)eng;/*store the engine */ - cam->name=ms_strdup(eng->dev); - ms_web_cam_manager_add_cam(obj,cam); - } - } - atexit(vfw_engines_free); -} - diff --git a/linphone/mediastreamer2/src/winvideods.c b/linphone/mediastreamer2/src/winvideods.c deleted file mode 100644 index bd442e3d1..000000000 --- a/linphone/mediastreamer2/src/winvideods.c +++ /dev/null @@ -1,1493 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#define UNICODE -#define AYMERIC_TEST -#define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA - -#include "mediastreamer2/msvideo.h" -#include "mediastreamer2/msticker.h" -#include "mediastreamer2/msv4l.h" -#include "mediastreamer2/mswebcam.h" - -#include "nowebcam.h" - -#ifdef HAVE_LIBAVCODEC_AVCODEC_H -#include -#else -#include -#endif - -#include -#include -#include - -#include -#include - -#include "dxfilter.h" -EXTERN_C const CLSID CLSID_NullRenderer; - -typedef struct V4wState{ - - char dev[512]; - int devidx; - - IGraphBuilder *m_pGraph; - ICaptureGraphBuilder2 *m_pBuilder; - IMediaControl *m_pControl; - CDXFilter *m_pDXFilter; - IBaseFilter *m_pIDXFilter; - IBaseFilter *m_pNullRenderer; - IBaseFilter *m_pDeviceFilter; - DWORD rotregvalue; - - MSVideoSize vsize; - int pix_fmt; - mblk_t *mire[10]; - char nowebcamimage[256]; - queue_t rq; - ms_mutex_t mutex; - int frame_ind; - int frame_max; - float fps; - uint64_t start_time; - int frame_count; -}V4wState; - -static V4wState *s_callback=NULL; - -static void dummy(void*p){ -} - -HRESULT ( Callback)(IMediaSample* pSample, REFERENCE_TIME* sTime, REFERENCE_TIME* eTime, BOOL changed) -{ - BYTE *byte_buf=NULL; - mblk_t *buf; - - V4wState *s = s_callback; - if (s==NULL) - return S_OK; - - HRESULT hr = pSample->GetPointer(&byte_buf); - if (FAILED(hr)) - { - return S_OK; - } - - int size = pSample->GetActualDataLength(); - if (size>+1000) - { - buf=allocb(size,0); - memcpy(buf->b_wptr, byte_buf, size); - if (s->pix_fmt==MS_RGB24) - { - /* Conversion from top down bottom up (BGR to RGB and flip) */ - unsigned long Index,nPixels; - unsigned char *blue; - unsigned char tmp; - short iPixelSize; - - blue=buf->b_wptr; - - nPixels=s->vsize.width*s->vsize.height; - iPixelSize=24/8; - - for(Index=0;Index!=nPixels;Index++) // For each pixel - { - tmp=*blue; - *blue=*(blue+2); - *(blue+2)=tmp; - blue+=iPixelSize; - } - - unsigned char *pLine1, *pLine2; - int iLineLen,iIndex; - - iLineLen=s->vsize.width*iPixelSize; - pLine1=buf->b_wptr; - pLine2=&(buf->b_wptr)[iLineLen * (s->vsize.height - 1)]; - - for( ;pLine1b_wptr+=size; - - ms_mutex_lock(&s->mutex); - putq(&s->rq, buf); - ms_mutex_unlock(&s->mutex); - - } - return S_OK; -} - -HRESULT GetPinCategory(IPin *pPin, GUID *pPinCategory) -{ - HRESULT hr; - IKsPropertySet *pKs; - hr = pPin->QueryInterface(IID_IKsPropertySet, (void **)&pKs); - if (FAILED(hr)) - { - // The pin does not support IKsPropertySet. - return hr; - } - // Try to retrieve the pin category. - DWORD cbReturned; - hr = pKs->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0, - pPinCategory, sizeof(GUID), &cbReturned); - - // If this succeeded, pPinCategory now contains the category GUID. - - pKs->Release(); - return hr; -} - -int try_format(IBaseFilter *m_pDeviceFilter, int format, GUID *pPinCategory) -{ - HRESULT hr=S_OK; - IEnumPins *pEnum=0; - ULONG ulFound; - IPin *pPin; - - GUID guid_format; - DWORD biCompression; - DWORD biBitCount; - - // Verify input - if (!m_pDeviceFilter) - return -1; - - if (format == MS_YUV420P) - guid_format = (GUID)FOURCCMap(MAKEFOURCC('I','4','2','0')); - else if (format == MS_YUYV) - guid_format = MEDIASUBTYPE_YUYV; - else if (format == MS_UYVY) - guid_format = MEDIASUBTYPE_UYVY; - else if (format == MS_RGB24) - guid_format = MEDIASUBTYPE_RGB24; - else if (format == MS_YUY2) - guid_format = MEDIASUBTYPE_YUY2; - - if (format == MS_YUV420P) - biCompression = MAKEFOURCC('I','4','2','0'); - else if (format == MS_YUYV) - biCompression = MAKEFOURCC('Y','U','Y','V'); - else if (format == MS_UYVY) - biCompression = MAKEFOURCC('U','Y','V','Y'); - else if (format == MS_RGB24) - biCompression = BI_RGB; - else if (format == MS_YUY2) - biCompression = MAKEFOURCC('Y','U','Y','2'); - - if (format == MS_YUV420P) - biBitCount = 12; - else if (format == MS_YUYV) - biBitCount = 16; - else if (format == MS_UYVY) - biBitCount = 16; - else if (format == MS_RGB24) - biBitCount = 24; - else if (format == MS_YUY2) - biBitCount = 16; - - // Get pin enumerator - hr = m_pDeviceFilter->EnumPins(&pEnum); - if(FAILED(hr)) - return -1; - - pEnum->Reset(); - - // Count every pin on the filter - while(S_OK == pEnum->Next(1, &pPin, &ulFound)) - { - PIN_DIRECTION pindir = (PIN_DIRECTION) 3; - - hr = pPin->QueryDirection(&pindir); - - if(pindir != PINDIR_INPUT) - { - IEnumMediaTypes *ppEnum; - ULONG ulFound2; - - GetPinCategory(pPin, pPinCategory); - if (*pPinCategory!=PIN_CATEGORY_CAPTURE - && *pPinCategory!=PIN_CATEGORY_PREVIEW) - continue; - - hr = pPin->EnumMediaTypes(&ppEnum); - if(FAILED(hr)) - continue; - - AM_MEDIA_TYPE *ppMediaTypes; - while(S_OK == ppEnum->Next(1, &ppMediaTypes, &ulFound2)) - { - if (ppMediaTypes->formattype != FORMAT_VideoInfo) - continue; - if (ppMediaTypes->majortype != MEDIATYPE_Video) - continue; - if (ppMediaTypes->subtype != guid_format) - continue; - VIDEOINFO *pvi = (VIDEOINFO *)ppMediaTypes->pbFormat; - if (pvi->bmiHeader.biCompression!=biCompression) - continue; - if (pvi->bmiHeader.biBitCount!=biBitCount) - continue; - - pPin->Release(); - pEnum->Release(); - return 0; - } - } - - pPin->Release(); - } - - pEnum->Release(); - return -1; -} - -int try_format_size(V4wState *s, int format, int width, int height, GUID *pPinCategory) -{ - HRESULT hr=S_OK; - IEnumPins *pEnum=0; - ULONG ulFound; - IPin *pPin; - - GUID guid_format; - DWORD biCompression; - DWORD biBitCount; - - // Verify input - if (!s->m_pDeviceFilter) - return -1; - - if (format == MS_YUV420P) - guid_format = (GUID)FOURCCMap(MAKEFOURCC('I','4','2','0')); - else if (format == MS_YUYV) - guid_format = MEDIASUBTYPE_YUYV; - else if (format == MS_UYVY) - guid_format = MEDIASUBTYPE_UYVY; - else if (format == MS_RGB24) - guid_format = MEDIASUBTYPE_RGB24; - else if (format == MS_YUY2) - guid_format = MEDIASUBTYPE_YUY2; - - if (format == MS_YUV420P) - biCompression = MAKEFOURCC('I','4','2','0'); - else if (format == MS_YUYV) - biCompression = MAKEFOURCC('Y','U','Y','V'); - else if (format == MS_UYVY) - biCompression = MAKEFOURCC('U','Y','V','Y'); - else if (format == MS_RGB24) - biCompression = BI_RGB; - else if (format == MS_YUY2) - biCompression = MAKEFOURCC('Y','U','Y','2'); - - if (format == MS_YUV420P) - biBitCount = 12; - else if (format == MS_YUYV) - biBitCount = 16; - else if (format == MS_UYVY) - biBitCount = 16; - else if (format == MS_RGB24) - biBitCount = 24; - else if (format == MS_YUY2) - biBitCount = 16; - - // Get pin enumerator - hr = s->m_pDeviceFilter->EnumPins(&pEnum); - if(FAILED(hr)) - return -1; - - pEnum->Reset(); - - // Count every pin on the filter - while(S_OK == pEnum->Next(1, &pPin, &ulFound)) - { - PIN_DIRECTION pindir = (PIN_DIRECTION) 3; - - hr = pPin->QueryDirection(&pindir); - - if(pindir != PINDIR_INPUT) - { - IEnumMediaTypes *ppEnum; - ULONG ulFound2; - hr = pPin->EnumMediaTypes(&ppEnum); - if(FAILED(hr)) - continue; - - GUID pCurrentPinCategory; - GetPinCategory(pPin, &pCurrentPinCategory); - if (*pPinCategory!=pCurrentPinCategory) - continue; - - AM_MEDIA_TYPE *ppMediaTypes; - while(S_OK == ppEnum->Next(1, &ppMediaTypes, &ulFound2)) - { - if (ppMediaTypes->formattype != FORMAT_VideoInfo) - continue; - if (ppMediaTypes->majortype != MEDIATYPE_Video) - continue; - if (ppMediaTypes->subtype != guid_format) - continue; - VIDEOINFO *pvi = (VIDEOINFO *)ppMediaTypes->pbFormat; - if (pvi->bmiHeader.biCompression!=biCompression) - continue; - if (pvi->bmiHeader.biBitCount!=biBitCount) - continue; - if (pvi->bmiHeader.biHeight!=height) - continue; - if (pvi->bmiHeader.biWidth!=width) - continue; - - s->vsize.width = width; - s->vsize.height = height; - - pPin->Release(); - pEnum->Release(); - return 0; - } - } - - pPin->Release(); - } - - pEnum->Release(); - return -1; -} - -static int v4w_configure_videodevice(V4wState *s) -{ - // Initialize COM - CoInitialize(NULL); - - // get a Graph - HRESULT hr= CoCreateInstance (CLSID_FilterGraph, - NULL, - CLSCTX_INPROC_SERVER, - IID_IGraphBuilder, //IID_IBaseFilter, - (void **)&s->m_pGraph); - if(FAILED(hr)) - { - return -1; - } - - // get a CaptureGraphBuilder2 - hr= CoCreateInstance (CLSID_CaptureGraphBuilder2, - NULL, - CLSCTX_INPROC_SERVER, - IID_ICaptureGraphBuilder2, //IID_IBaseFilter, - (void **)&s->m_pBuilder); - if(FAILED(hr)) - { - return -2; - } - - // connect capture graph builder with the graph - s->m_pBuilder->SetFiltergraph(s->m_pGraph); - - // get mediacontrol so we can start and stop the filter graph - hr=s->m_pGraph->QueryInterface (IID_IMediaControl, (void **)&s->m_pControl); - if(FAILED(hr)) - { - return -3; - } - - - ICreateDevEnum *pCreateDevEnum = NULL; - IEnumMoniker *pEnumMoniker = NULL; - IMoniker *pMoniker = NULL; - - ULONG nFetched = 0; - - hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, - IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum); - if(FAILED(hr)) - { - return -4; - } - - hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, - &pEnumMoniker, 0); - if (FAILED(hr) || pEnumMoniker == NULL) { - //printf("no device\n"); - return -5; - } - - pEnumMoniker->Reset(); - - int pos=0; - while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) ) - { - IPropertyBag *pBag; - hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag ); - if( hr != S_OK ) - continue; - - if (s->dev[0]=='\0') - break; - - VARIANT var; - VariantInit(&var); - hr = pBag->Read( L"FriendlyName", &var, NULL ); - if( hr != S_OK ) - { - pMoniker->Release(); - continue; - } - //USES_CONVERSION; - char szName[256]; - - WideCharToMultiByte(CP_UTF8,0,var.bstrVal,-1,szName,256,0,0); - VariantClear(&var); - - if (strcmp(szName, s->dev)==0) - break; - - pMoniker->Release(); - pBag->Release(); - pMoniker=NULL; - pBag=NULL; - } - - if(pMoniker==NULL) - { - int pos=0; - while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) ) - { - IPropertyBag *pBag; - hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag ); - if( hr != S_OK ) - continue; - } - - } - - if(pMoniker==NULL) - { - return -6; - } - - hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&s->m_pDeviceFilter ); - if(FAILED(hr)) - { - return -7; - } - - s->m_pGraph->AddFilter(s->m_pDeviceFilter, L"Device Filter"); - - pMoniker->Release(); - pEnumMoniker->Release(); - pCreateDevEnum->Release(); - - - GUID pPinCategory; - - if (try_format(s->m_pDeviceFilter, s->pix_fmt, &pPinCategory)==0) - s->pix_fmt = s->pix_fmt; - else if (try_format(s->m_pDeviceFilter,MS_YUV420P, &pPinCategory)==0) - s->pix_fmt = MS_YUV420P; - else if (try_format(s->m_pDeviceFilter,MS_YUY2, &pPinCategory)==0) - s->pix_fmt = MS_YUY2; - else if (try_format(s->m_pDeviceFilter,MS_YUYV, &pPinCategory)==0) - s->pix_fmt = MS_YUYV; - else if (try_format(s->m_pDeviceFilter,MS_UYVY, &pPinCategory)==0) - s->pix_fmt = MS_UYVY; - else if (try_format(s->m_pDeviceFilter,MS_RGB24, &pPinCategory)==0) - s->pix_fmt = MS_RGB24; - else - { - ms_error("Unsupported video pixel format."); - return -8; - } - - if (s->pix_fmt == MS_YUV420P) - ms_message("Driver supports YUV420P, using that format."); - else if (s->pix_fmt == MS_YUY2) - ms_message("Driver supports YUY2 (UYVY), using that format."); - else if (s->pix_fmt == MS_YUYV) - ms_message("Driver supports YUV422, using that format."); - else if (s->pix_fmt == MS_UYVY) - ms_message("Driver supports UYVY, using that format."); - else if (s->pix_fmt == MS_RGB24) - ms_message("Driver supports RGB24, using that format."); - - if (try_format_size(s, s->pix_fmt, s->vsize.width, s->vsize.height, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", s->vsize.width, s->vsize.height); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H); - else - { - ms_error("No supported size found for format."); - /* size not supported? */ - return -9; - } - - return 0; -} - -static int v4w_open_videodevice(V4wState *s) -{ - // Initialize COM - CoInitialize(NULL); - - // get a Graph - HRESULT hr= CoCreateInstance (CLSID_FilterGraph, - NULL, - CLSCTX_INPROC_SERVER, - IID_IGraphBuilder, //IID_IBaseFilter, - (void **)&s->m_pGraph); - if(FAILED(hr)) - { - return -1; - } - - // get a CaptureGraphBuilder2 - hr= CoCreateInstance (CLSID_CaptureGraphBuilder2, - NULL, - CLSCTX_INPROC_SERVER, - IID_ICaptureGraphBuilder2, //IID_IBaseFilter, - (void **)&s->m_pBuilder); - if(FAILED(hr)) - { - return -2; - } - - // connect capture graph builder with the graph - s->m_pBuilder->SetFiltergraph(s->m_pGraph); - - // get mediacontrol so we can start and stop the filter graph - hr=s->m_pGraph->QueryInterface (IID_IMediaControl, (void **)&s->m_pControl); - if(FAILED(hr)) - { - return -3; - } - - - ICreateDevEnum *pCreateDevEnum = NULL; - IEnumMoniker *pEnumMoniker = NULL; - IMoniker *pMoniker = NULL; - - ULONG nFetched = 0; - - hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, - IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum); - if(FAILED(hr)) - { - return -4; - } - - hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, - &pEnumMoniker, 0); - if (FAILED(hr) || pEnumMoniker == NULL) { - //printf("no device\n"); - return -5; - } - - pEnumMoniker->Reset(); - - int pos=0; - while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) ) - { - IPropertyBag *pBag; - hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag ); - if( hr != S_OK ) - continue; - - if (s->dev[0]=='\0') - break; - - VARIANT var; - VariantInit(&var); - hr = pBag->Read( L"FriendlyName", &var, NULL ); - if( hr != S_OK ) - { - pMoniker->Release(); - continue; - } - //USES_CONVERSION; - char szName[256]; - - WideCharToMultiByte(CP_UTF8,0,var.bstrVal,-1,szName,256,0,0); - VariantClear(&var); - - if (strcmp(szName, s->dev)==0) - break; - - pMoniker->Release(); - pBag->Release(); - pMoniker=NULL; - pBag=NULL; - } - - if(pMoniker==NULL) - { - return -6; - } - - hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&s->m_pDeviceFilter ); - if(FAILED(hr)) - { - return -7; - } - - s->m_pGraph->AddFilter(s->m_pDeviceFilter, L"Device Filter"); - - pMoniker->Release(); - pEnumMoniker->Release(); - pCreateDevEnum->Release(); - - - GUID pPinCategory; - - if (try_format(s->m_pDeviceFilter, s->pix_fmt, &pPinCategory)==0) - s->pix_fmt = s->pix_fmt; - else if (try_format(s->m_pDeviceFilter,MS_YUV420P, &pPinCategory)==0) - s->pix_fmt = MS_YUV420P; - else if (try_format(s->m_pDeviceFilter,MS_YUY2, &pPinCategory)==0) - s->pix_fmt = MS_YUY2; - else if (try_format(s->m_pDeviceFilter,MS_YUYV, &pPinCategory)==0) - s->pix_fmt = MS_YUYV; - else if (try_format(s->m_pDeviceFilter,MS_UYVY, &pPinCategory)==0) - s->pix_fmt = MS_UYVY; - else if (try_format(s->m_pDeviceFilter,MS_RGB24, &pPinCategory)==0) - s->pix_fmt = MS_RGB24; - else - { - ms_error("Unsupported video pixel format."); - return -8; - } - - if (s->pix_fmt == MS_YUV420P) - ms_message("Driver supports YUV420P, using that format."); - else if (s->pix_fmt == MS_YUY2) - ms_message("Driver supports YUY2 (UYVY), using that format."); - else if (s->pix_fmt == MS_YUYV) - ms_message("Driver supports YUV422, using that format."); - else if (s->pix_fmt == MS_UYVY) - ms_message("Driver supports UYVY, using that format."); - else if (s->pix_fmt == MS_RGB24) - ms_message("Driver supports RGB24, using that format."); - - if (try_format_size(s, s->pix_fmt, s->vsize.width, s->vsize.height, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", s->vsize.width, s->vsize.height); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QCIF_W, MS_VIDEO_SIZE_QCIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_CIF_W, MS_VIDEO_SIZE_CIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4CIF_W, MS_VIDEO_SIZE_4CIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QVGA_W, MS_VIDEO_SIZE_QVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QQVGA_W, MS_VIDEO_SIZE_QQVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_NS1_W, MS_VIDEO_SIZE_NS1_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_QSIF_W, MS_VIDEO_SIZE_QSIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SIF_W, MS_VIDEO_SIZE_SIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_VGA_W, MS_VIDEO_SIZE_VGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SDTV_W, MS_VIDEO_SIZE_SDTV_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_288P_W, MS_VIDEO_SIZE_288P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_448P_W, MS_VIDEO_SIZE_448P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_576P_W, MS_VIDEO_SIZE_576P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_720P_W, MS_VIDEO_SIZE_720P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_1080P_W, MS_VIDEO_SIZE_1080P_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_4SIF_W, MS_VIDEO_SIZE_4SIF_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_SVGA_W, MS_VIDEO_SIZE_SVGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_XGA_W, MS_VIDEO_SIZE_XGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_WXGA_W, MS_VIDEO_SIZE_WXGA_H); - else if (try_format_size(s, s->pix_fmt, MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H, &pPinCategory)==0) - ms_message("Selected Size: %ix%i.", MS_VIDEO_SIZE_HDTVP_W, MS_VIDEO_SIZE_HDTVP_H); - else - { - ms_error("No supported size found for format."); - /* size not supported? */ - return -9; - } - - // get DXFilter - s->m_pDXFilter = new CDXFilter(NULL, &hr, FALSE); - if(s->m_pDXFilter==NULL) - { - return -10; - } - s->m_pDXFilter->AddRef(); - - CMediaType mt; - mt.SetType(&MEDIATYPE_Video); - - GUID m = MEDIASUBTYPE_RGB24; - if (s->pix_fmt == MS_YUV420P) - m = (GUID)FOURCCMap(MAKEFOURCC('I','4','2','0')); - else if (s->pix_fmt == MS_YUY2) - m = MEDIASUBTYPE_YUY2; - else if (s->pix_fmt == MS_YUYV) - m = MEDIASUBTYPE_YUYV; - else if (s->pix_fmt == MS_UYVY) - m = MEDIASUBTYPE_UYVY; - else if (s->pix_fmt == MS_RGB24) - m = MEDIASUBTYPE_RGB24; - mt.SetSubtype(&m); - - mt.formattype = FORMAT_VideoInfo; - mt.SetTemporalCompression(FALSE); - - VIDEOINFO *pvi = (VIDEOINFO *) - mt.AllocFormatBuffer(sizeof(VIDEOINFO)); - if (NULL == pvi) - return -11; - ZeroMemory(pvi, sizeof(VIDEOINFO)); - - if (s->pix_fmt == MS_YUV420P) - pvi->bmiHeader.biCompression = MAKEFOURCC('I','4','2','0'); - else if (s->pix_fmt == MS_YUY2) - pvi->bmiHeader.biCompression = MAKEFOURCC('Y','U','Y','2'); - else if (s->pix_fmt == MS_YUYV) - pvi->bmiHeader.biCompression = MAKEFOURCC('Y','U','Y','V'); - else if (s->pix_fmt == MS_UYVY) - pvi->bmiHeader.biCompression = MAKEFOURCC('U','Y','V','Y'); - else if (s->pix_fmt == MS_RGB24) - pvi->bmiHeader.biCompression = BI_RGB; - - if (s->pix_fmt == MS_YUV420P) - pvi->bmiHeader.biBitCount = 12; - else if (s->pix_fmt == MS_YUY2) - pvi->bmiHeader.biBitCount = 16; - else if (s->pix_fmt == MS_YUYV) - pvi->bmiHeader.biBitCount = 16; - else if (s->pix_fmt == MS_UYVY) - pvi->bmiHeader.biBitCount = 16; - else if (s->pix_fmt == MS_RGB24) - pvi->bmiHeader.biBitCount = 24; - - pvi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - pvi->bmiHeader.biWidth = s->vsize.width; - pvi->bmiHeader.biHeight = s->vsize.height; - pvi->bmiHeader.biPlanes = 1; - pvi->bmiHeader.biSizeImage = GetBitmapSize(&pvi->bmiHeader); - pvi->bmiHeader.biClrImportant = 0; - mt.SetSampleSize(pvi->bmiHeader.biSizeImage); - - mt.SetFormat((BYTE*)pvi, sizeof(VIDEOINFO)); - - hr = s->m_pDXFilter->SetAcceptedMediaType(&mt); - if(FAILED(hr)) - { - return -12; - } - - hr = s->m_pDXFilter->SetCallback(Callback); - if(FAILED(hr)) - { - return -13; - } - - hr = s->m_pDXFilter->QueryInterface(IID_IBaseFilter, - (LPVOID *)&s->m_pIDXFilter); - if(FAILED(hr)) - { - return -14; - } - - hr = s->m_pGraph->AddFilter(s->m_pIDXFilter, L"DXFilter Filter"); - if(FAILED(hr)) - { - return -15; - } - - - // get null renderer - hr=CoCreateInstance (CLSID_NullRenderer, - NULL, - CLSCTX_INPROC_SERVER, - IID_IBaseFilter, - (void **)&s->m_pNullRenderer); - if(FAILED(hr)) - { - return -16; - } - if (s->m_pNullRenderer!=NULL) - { - s->m_pGraph->AddFilter(s->m_pNullRenderer, L"Null Renderer"); - } - - hr = s->m_pBuilder->RenderStream(&pPinCategory, - &MEDIATYPE_Video, s->m_pDeviceFilter, s->m_pIDXFilter, s->m_pNullRenderer); - if (FAILED(hr)) - { - return -17; - } - - IAMStreamConfig *pConfig = NULL; - hr = s->m_pBuilder->FindInterface( - &pPinCategory, // Preview pin. - &MEDIATYPE_Video, // Any media type. - s->m_pDeviceFilter, // Pointer to the capture filter. - IID_IAMStreamConfig, (void**)&pConfig); - if (pConfig!=NULL) - { - AM_MEDIA_TYPE *pType = NULL; - int iCount, iSize; - pConfig->GetNumberOfCapabilities(&iCount, &iSize); - - for (int i = 0; i < iCount; i++) { - VIDEO_STREAM_CONFIG_CAPS scc; - pType = NULL; - pConfig->GetStreamCaps(i, &pType, (BYTE *)&scc); - - if (!((pType->formattype == FORMAT_VideoInfo) && - (pType->cbFormat >= sizeof(VIDEOINFOHEADER)) && - (pType->pbFormat != NULL))) - continue; - - VIDEOINFOHEADER & videoInfo = *(VIDEOINFOHEADER *)pType->pbFormat; - - if (m != pType->subtype) - continue; - - if (videoInfo.bmiHeader.biWidth != s->vsize.width) - continue; - - if (videoInfo.bmiHeader.biHeight != s->vsize.height) - continue; - - if (videoInfo.bmiHeader.biBitCount != pvi->bmiHeader.biBitCount) - continue; - - if (videoInfo.bmiHeader.biCompression != pvi->bmiHeader.biCompression) - continue; - - videoInfo.AvgTimePerFrame = UNITS / (LONGLONG)s->fps; - pConfig->SetFormat(pType); - } - - pConfig->GetFormat(&pType); - if (pType!=NULL) - { - VIDEOINFO *pvi; - pvi = (VIDEOINFO *)pType->pbFormat; - ms_message("v4w: camera asked fps=%i // real fps=%i", (int)(UNITS / (LONGLONG)s->fps), pvi->AvgTimePerFrame); - } - - pConfig->Release(); - } - - //m_pDXFilter->SetBufferSamples(TRUE); - - s_callback = s; - hr = s->m_pControl->Run(); - if(FAILED(hr)) - { - return -18; - } - - - s->rotregvalue=1; - return 0; -} - -static void v4w_init(MSFilter *f){ - V4wState *s=(V4wState *)ms_new0(V4wState,1); - int idx; - s->devidx=0; - s->vsize.width=MS_VIDEO_SIZE_CIF_W; - s->vsize.height=MS_VIDEO_SIZE_CIF_H; - s->pix_fmt=MS_YUV420P; - - s->rotregvalue = 0; - s->m_pGraph=NULL; - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pDXFilter=NULL; - s->m_pIDXFilter=NULL; - s->m_pDeviceFilter=NULL; - - qinit(&s->rq); - for (idx=0;idx<10;idx++) - { - s->mire[idx]=NULL; - } - memset(s->nowebcamimage, 0, sizeof(s->nowebcamimage)); - ms_mutex_init(&s->mutex,NULL); - s->start_time=0; - s->frame_count=-1; - s->fps=15; - memset(s->dev, 0, sizeof(s->dev)); - - f->data=s; -} - -static int _v4w_test(V4wState *s, void *arg) -{ - int i; - i = v4w_configure_videodevice(s); - - if (i!=0) - { - s->pix_fmt = MS_YUV420P; - s->vsize.width = MS_VIDEO_SIZE_CIF_W; - s->vsize.height = MS_VIDEO_SIZE_CIF_H; - } - - if (s->m_pGraph!=NULL) - { - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - } - - if (s->m_pNullRenderer) - s->m_pNullRenderer->Release(); - if (s->m_pIDXFilter) - s->m_pIDXFilter->Release(); - if (s->m_pDeviceFilter) - s->m_pDeviceFilter->Release(); - - if (s->m_pBuilder) - s->m_pBuilder->Release(); - if (s->m_pControl) - s->m_pControl->Release(); - if (s->m_pGraph) - s->m_pGraph->Release(); - - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - - s->m_pNullRenderer=NULL; - s->m_pIDXFilter=NULL; - s->m_pDeviceFilter=NULL; - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pGraph=NULL; - s->m_pDXFilter=NULL; - - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: checked device size=%ix%i format=%i (err=%i)", s->vsize.width, s->vsize.height, s->pix_fmt, i); - - return i; -} - -static int _v4w_start(V4wState *s, void *arg) -{ - int i; - s->frame_count=-1; - - i = v4w_open_videodevice(s); - - if (s->rotregvalue==0){ - if (s->m_pGraph!=NULL) - { - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - } - - if (s->m_pNullRenderer) - s->m_pNullRenderer->Release(); - if (s->m_pIDXFilter) - s->m_pIDXFilter->Release(); - if (s->m_pDeviceFilter) - s->m_pDeviceFilter->Release(); - - if (s->m_pBuilder) - s->m_pBuilder->Release(); - if (s->m_pControl) - s->m_pControl->Release(); - if (s->m_pGraph) - s->m_pGraph->Release(); - - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - - s->m_pNullRenderer=NULL; - s->m_pIDXFilter=NULL; - s->m_pDeviceFilter=NULL; - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pGraph=NULL; - s->m_pDXFilter=NULL; - - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: graph not started (err=%i)", i); - s->rotregvalue=0; - s->pix_fmt = MS_YUV420P; - } - return i; -} - -static void v4w_uninit(MSFilter *f){ - V4wState *s=(V4wState*)f->data; - int idx; - flushq(&s->rq,0); - ms_mutex_destroy(&s->mutex); - for (idx=0;idx<10;idx++) - { - if (s->mire[idx]==NULL) - break; - freemsg(s->mire[idx]); - } - if (s->rotregvalue>0){ - HRESULT hr = s->m_pControl->Stop(); - if(FAILED(hr)) - { - ms_message("v4w: could not stop graph"); - } - - if (s->m_pGraph!=NULL) - { - if (s->m_pNullRenderer!=NULL) - s->m_pGraph->RemoveFilter(s->m_pNullRenderer); - if (s->m_pIDXFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pIDXFilter); - if (s->m_pDeviceFilter!=NULL) - s->m_pGraph->RemoveFilter(s->m_pDeviceFilter); - } - - if (s->m_pNullRenderer) - s->m_pNullRenderer->Release(); - if (s->m_pIDXFilter) - s->m_pIDXFilter->Release(); - if (s->m_pDeviceFilter) - s->m_pDeviceFilter->Release(); - - if (s->m_pBuilder) - s->m_pBuilder->Release(); - if (s->m_pControl) - s->m_pControl->Release(); - if (s->m_pGraph) - s->m_pGraph->Release(); - - if (s->m_pDXFilter!=NULL) - s->m_pDXFilter->Release(); - - s->m_pNullRenderer=NULL; - s->m_pIDXFilter=NULL; - s->m_pDeviceFilter=NULL; - s->m_pBuilder=NULL; - s->m_pControl=NULL; - s->m_pGraph=NULL; - s->m_pDXFilter=NULL; - - CoUninitialize(); - s_callback = NULL; - flushq(&s->rq,0); - ms_message("v4w: graph destroyed"); - s->rotregvalue=0; - } - ms_free(s); -} - -static mblk_t * v4w_make_nowebcam(V4wState *s){ -#if defined(_WIN32_WCE) - return NULL; -#else - int idx; - int count; - if(s->mire[0]==NULL && s->frame_ind==0 && s->nowebcamimage[0] != '\0') - { - s->mire[0] = ms_load_jpeg_as_yuv(s->nowebcamimage,&s->vsize); - } - if (s->mire[0]==NULL && s->frame_ind==0){ - /* load several images to fake a movie */ - for (idx=0;idx<10;idx++) - { - s->mire[idx]=ms_load_nowebcam(&s->vsize, idx); - if (s->mire[idx]==NULL) - break; - } - if (idx==0) - s->mire[0]=ms_load_nowebcam(&s->vsize, -1); - } - for (count=0;count<10;count++) - { - if (s->mire[count]==NULL) - break; - } - - s->frame_ind++; - if (count==0) - return NULL; - - idx = s->frame_ind%count; - if (s->mire[idx]!=NULL) - return s->mire[idx]; - return s->mire[0]; -#endif -} - -static void v4w_preprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - if (s->rotregvalue==0) - _v4w_start(s, NULL); - if (s->rotregvalue==0) - s->fps=1; -} - -static void v4w_postprocess(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - s->start_time=0; - s->frame_count=-1; - flushq(&s->rq,0); -} - -static void v4w_process(MSFilter * obj){ - V4wState *s=(V4wState*)obj->data; - mblk_t *m; - uint32_t timestamp; - int cur_frame; - - if (s->frame_count==-1){ - s->start_time=obj->ticker->time; - s->frame_count=0; - } - - cur_frame=(int)((obj->ticker->time-s->start_time)*s->fps/1000.0); - if (cur_frame>s->frame_count){ - mblk_t *om=NULL; - ms_mutex_lock(&s->mutex); - /*keep the most recent frame if several frames have been captured */ - if (s->rotregvalue!=0){ - while((m=getq(&s->rq))!=NULL){ - if (om!=NULL) freemsg(om); - om=m; - } - }else { - mblk_t *nowebcam = v4w_make_nowebcam(s); - if (nowebcam!=NULL){ - om=dupmsg(nowebcam); - mblk_set_precious_flag(om,1); - } - } - ms_mutex_unlock(&s->mutex); - if (om!=NULL){ - timestamp=(uint32_t)obj->ticker->time*90;/* rtp uses a 90000 Hz clockrate for video*/ - mblk_set_timestamp_info(om,timestamp); - ms_queue_put(obj->outputs[0],om); - /*ms_message("picture sent");*/ - } - s->frame_count++; - } -} - - - -static int v4w_set_fps(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->fps=*((float*)arg); - s->frame_count=-1; /* reset counter used for fps */ - return 0; -} - - -static int v4w_set_pix_fmt(MSFilter *f,void *arg){ - V4wState *s=(V4wState*)f->data; - s->pix_fmt=*((MSPixFmt*)arg); - return 0; -} - -static int v4w_get_pix_fmt(MSFilter *f,void *arg){ - V4wState *s=(V4wState*)f->data; - if (s->rotregvalue==0){ - _v4w_test(s, NULL); /* check supported format */ - *((MSPixFmt*)arg) = (MSPixFmt)s->pix_fmt; - return 0; - } - *((MSPixFmt*)arg) = (MSPixFmt)s->pix_fmt; - return 0; -} - -static int v4w_set_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->vsize=*((MSVideoSize*)arg); - return 0; -} - -static int v4w_get_vsize(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - MSVideoSize *vs=(MSVideoSize*)arg; - vs->width=s->vsize.width; - vs->height=s->vsize.height; - return 0; -} - -static int v4w_set_device(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - s->devidx=*((int*)arg); - return 0; -} - -static int v4w_set_image(MSFilter *f, void *arg){ - int idx; - V4wState *s=(V4wState*)f->data; - char *image = (char *)arg; - ms_mutex_lock(&s->mutex); - if (image!=NULL && image[0]!='\0') - snprintf(s->nowebcamimage, sizeof(s->nowebcamimage), "%s", image); - else - s->nowebcamimage[0] = '\0'; - for (idx=0;idx<10;idx++) - { - if (s->mire[idx]==NULL) - break; - freemsg(s->mire[idx]); - s->mire[idx]=NULL; - } - s->frame_ind=0; - ms_mutex_unlock(&s->mutex); - return 0; -} - -static int v4w_set_name(MSFilter *f, void *arg){ - V4wState *s=(V4wState*)f->data; - snprintf(s->dev, sizeof(s->dev), (char*)arg); - return 0; -} - -static MSFilterMethod methods[]={ - { MS_FILTER_SET_FPS , v4w_set_fps }, - { MS_FILTER_SET_PIX_FMT , v4w_set_pix_fmt }, - { MS_FILTER_GET_PIX_FMT , v4w_get_pix_fmt }, - { MS_FILTER_SET_VIDEO_SIZE, v4w_set_vsize }, - { MS_FILTER_GET_VIDEO_SIZE, v4w_get_vsize }, - { MS_V4L_SET_DEVICE, v4w_set_device }, - { MS_FILTER_SET_IMAGE, v4w_set_image }, - { 0, NULL } -}; - -#if defined(_MSC_VER) || defined(__cplusplus) - -MSFilterDesc ms_v4w_desc={ - MS_V4L_ID, - "MSV4w", - N_("A video4windows compatible source filter to stream pictures."), - MS_FILTER_OTHER, - NULL, - 0, - 1, - v4w_init, - v4w_preprocess, - v4w_process, - v4w_postprocess, - v4w_uninit, - methods -}; - -#else - -MSFilterDesc ms_v4w_desc={ - .id=MS_V4L_ID, - .name="MSV4w", - .text=N_("A video4windows compatible source filter to stream pictures."), - .ninputs=0, - .noutputs=1, - .category=MS_FILTER_OTHER, - .init=v4w_init, - .preprocess=v4w_preprocess, - .process=v4w_process, - .postprocess=v4w_postprocess, - .uninit=v4w_uninit, - .methods=methods -}; - -#endif - -MS_FILTER_DESC_EXPORT(ms_v4w_desc) - -static MSFilter *vfw_create_reader(MSWebCam *obj){ - MSFilter *f=ms_filter_new_from_desc(&ms_v4w_desc); - v4w_set_name(f,obj->name); - return f; -} - -static void vfw_detect(MSWebCamManager *obj); - -static void vfw_cam_init(MSWebCam *cam){ -} - -MSWebCamDesc ms_directx_cam_desc={ - "DirectX Video Grabber", - &vfw_detect, - &vfw_cam_init, - &vfw_create_reader, - NULL -}; - -static void vfw_detect(MSWebCamManager *obj){ - ICreateDevEnum *pCreateDevEnum = NULL; - IEnumMoniker *pEnumMoniker = NULL; - IMoniker *pMoniker = NULL; - HRESULT hr; - - ULONG nFetched = 0; - - // Initialize COM - CoInitialize(NULL); - - hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, - IID_ICreateDevEnum, (PVOID *)&pCreateDevEnum); - if(FAILED(hr)) - { - CoUninitialize(); - return ; - } - - hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, - &pEnumMoniker, 0); - if (FAILED(hr) || pEnumMoniker == NULL) { - //printf("no device\n"); - CoUninitialize(); - return ; - } - - pEnumMoniker->Reset(); - - int pos=0; - while(S_OK == pEnumMoniker->Next(1, &pMoniker, &nFetched) ) - { - IPropertyBag *pBag; - hr = pMoniker->BindToStorage( 0, 0, IID_IPropertyBag, (void**) &pBag ); - if( hr != S_OK ) - continue; - - VARIANT var; - VariantInit(&var); - hr = pBag->Read( L"FriendlyName", &var, NULL ); - if( hr != S_OK ) - { - pMoniker->Release(); - continue; - } - //USES_CONVERSION; - char szName[256]; - - WideCharToMultiByte(CP_UTF8,0,var.bstrVal,-1,szName,256,0,0); - VariantClear(&var); - - IBaseFilter *m_pDeviceFilter; - hr = pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&m_pDeviceFilter ); - if(SUCCEEDED(hr)) - { - GUID pPinCategory; - int fmt_supported = 0; - - //basic testing for the device. - if (try_format(m_pDeviceFilter,MS_YUV420P, &pPinCategory)==0) - fmt_supported = 1; - else if (try_format(m_pDeviceFilter,MS_YUY2, &pPinCategory)==0) - fmt_supported = 1; - else if (try_format(m_pDeviceFilter,MS_YUYV, &pPinCategory)==0) - fmt_supported = 1; - else if (try_format(m_pDeviceFilter,MS_UYVY, &pPinCategory)==0) - fmt_supported = 1; - else if (try_format(m_pDeviceFilter,MS_RGB24, &pPinCategory)==0) - fmt_supported = 1; - else - { - ms_warning("Unsupported video pixel format/refuse camera (%s).", szName); - } - - if (fmt_supported==1) - { - MSWebCam *cam=ms_web_cam_new(&ms_directx_cam_desc); - cam->name=ms_strdup(szName); - ms_web_cam_manager_add_cam(obj,cam); - } - m_pDeviceFilter->Release(); - m_pDeviceFilter=NULL; - } - - - pMoniker->Release(); - pBag->Release(); - pMoniker=NULL; - pBag=NULL; - } - - pEnumMoniker->Release(); - pCreateDevEnum->Release(); - CoUninitialize(); -} diff --git a/linphone/mediastreamer2/tests/.gitignore b/linphone/mediastreamer2/tests/.gitignore deleted file mode 100644 index eeece4336..000000000 --- a/linphone/mediastreamer2/tests/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -Makefile.in -Makefile -.deps -.libs -echo -mediastream -ring -videodisplay -bench -mtudiscover - diff --git a/linphone/mediastreamer2/tests/Makefile.am b/linphone/mediastreamer2/tests/Makefile.am deleted file mode 100644 index 443b0edf1..000000000 --- a/linphone/mediastreamer2/tests/Makefile.am +++ /dev/null @@ -1,37 +0,0 @@ -if BUILD_TESTS - -noinst_PROGRAMS=echo ring mtudiscover bench - -if BUILD_VIDEO -noinst_PROGRAMS+=videodisplay -endif - -echo_SOURCES=echo.c -ring_SOURCES=ring.c -videodisplay_SOURCES=videodisplay.c -mtudiscover_SOURCES=mtudiscover.c -bench_SOURCES=bench.c - -libexec_PROGRAMS=mediastream - -mediastream_SOURCES=mediastream.c - -#libquickstream.la would be enough, but to workaround a bug of libtool when -#cross compiling we need to add all the dependencies. -LDADD= $(top_builddir)/src/libmediastreamer.la \ - $(ORTP_LIBS) \ - $(ALSA_LIBS) \ - $(ARTS_LIBS) \ - $(SPEEX_LIBS) \ - $(GSM_LIBS) \ - $(THEORA_LIBS) \ - $(VIDEO_LIBS) - - - -INCLUDES=-I$(top_srcdir)/include/ - -AM_CFLAGS=-I$(top_srcdir) $(ORTP_CFLAGS) $(STRICT_OPTIONS) $(VIDEO_CFLAGS) -AM_LDFLAGS=-rdynamic - -endif diff --git a/linphone/mediastreamer2/tests/bench.c b/linphone/mediastreamer2/tests/bench.c deleted file mode 100644 index a7c12721e..000000000 --- a/linphone/mediastreamer2/tests/bench.c +++ /dev/null @@ -1,365 +0,0 @@ - -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msticker.h" - -#include "mediastreamer2/msrtp.h" -#include "mediastreamer2/msfileplayer.h" -#include "mediastreamer2/msfilerec.h" - -#include - -#define MAX_RTP_SIZE 1500 - -static int run=1; - -static void stop(int signum){ - run=0; -} - -struct test_session { - RtpSession *rtps; - - MSFilter *fplayer; - MSFilter *encoder; - MSFilter *rtpsend; - - MSFilter *rtprecv; - MSFilter *decoder; - MSFilter *frecorder; -}; - -struct bench_config { - int num_session; - int num_session_record; - - int port_origin; - char *ip_destination; - int port_destination; - - int payload; - int rate; - int ptime; - char *wavfile; - - MSTicker *ticker; - MSList *tsessions; /* list of struct test_session */ -}; - -#define NUM_SESSION 50 /* num of session to start per block */ -#define NUM_SESSION_RECORD 1 - -struct bench_config cfg[] = { - { NUM_SESSION,NUM_SESSION_RECORD, - 8000,"127.0.0.1",9000,8,8000,20,"test1.wav",NULL,NULL }, - { NUM_SESSION,NUM_SESSION_RECORD, - 9000,"127.0.0.1",8000,8,8000,20,"test1.wav",NULL,NULL }, - - { NUM_SESSION,NUM_SESSION_RECORD, - 10000,"127.0.0.1",11000,8,8000,20,"test1.wav",NULL,NULL }, - { NUM_SESSION,NUM_SESSION_RECORD, - 11000,"127.0.0.1",10000,8,8000,20,"test1.wav",NULL,NULL }, - - { 0,0,0,'\0',0,0,0,0,NULL,NULL,NULL }, -}; - -RtpSession *create_duplex_rtpsession(int locport){ - RtpSession *rtpr; - rtpr=rtp_session_new(RTP_SESSION_SENDRECV); - rtp_session_set_recv_buf_size(rtpr,MAX_RTP_SIZE); - rtp_session_set_scheduling_mode(rtpr,0); - rtp_session_set_blocking_mode(rtpr,0); - rtp_session_enable_adaptive_jitter_compensation(rtpr,FALSE); - rtp_session_set_symmetric_rtp(rtpr,TRUE); - rtp_session_set_local_addr(rtpr,"0.0.0.0",locport); - rtp_session_signal_connect(rtpr,"timestamp_jump",(RtpCallback)rtp_session_resync,(long)NULL); - rtp_session_signal_connect(rtpr,"ssrc_changed",(RtpCallback)rtp_session_resync,(long)NULL); - return rtpr; -} - -int init_bench(struct bench_config *bench) -{ - PayloadType *pt; - int pos; - int val; - int count; - bench->ticker=ms_ticker_new(); - - count = 0; - /* creates the couple of encoder/decoder */ - pt=rtp_profile_get_payload(&av_profile,bench->payload); - if (pt==NULL){ - ms_error("audiostream.c: undefined payload type."); - return count; - } - if (pt->clock_rate!=8000 && pt->clock_rate!=16000 && pt->clock_rate!=32000){ - ms_error("audiostream.c: wrong rate."); - return count; - } - for (pos=0;posnum_session;pos++) - { - struct test_session *ts = (struct test_session *)ortp_malloc(sizeof(struct test_session)); - memset(ts, 0, sizeof(struct test_session)); - - ts->rtps = create_duplex_rtpsession(bench->port_origin+pos*2); - if (ts->rtps==NULL) - { - ms_error("bench.c: cannot create rtp_session!"); - ortp_free(ts); - return count; - } - - rtp_session_set_payload_type(ts->rtps,bench->payload); - rtp_session_set_remote_addr_full(ts->rtps, - bench->ip_destination, - bench->port_destination+pos*2, - bench->port_destination+1+pos*2); - - ts->fplayer = ms_filter_new(MS_FILE_PLAYER_ID); - if (strstr(bench->wavfile, ".au")==NULL) - ts->encoder = ms_filter_create_encoder(pt->mime_type); - ts->rtpsend = ms_filter_new(MS_RTP_SEND_ID); - - ts->rtprecv = ms_filter_new(MS_RTP_RECV_ID); - ts->decoder = ms_filter_create_decoder(pt->mime_type); - ts->frecorder = ms_filter_new(MS_FILE_REC_ID); - - if ((ts->encoder==NULL && strstr(bench->wavfile, ".au")==NULL) - || (ts->decoder==NULL )){ - ms_error("bench.c: No decoder available for payload %i.",bench->payload); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - if (ts->fplayer==NULL){ - ms_error("bench.c: missing player filter."); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - if (ts->frecorder==NULL){ - ms_error("bench.c: missing recorder filter."); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - if (ts->rtpsend==NULL){ - ms_error("bench.c: missing rtpsend filter."); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - if (ts->rtprecv==NULL){ - ms_error("bench.c: missing rtprecv filter."); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - - ms_filter_call_method(ts->rtpsend,MS_RTP_SEND_SET_SESSION,ts->rtps); - ms_filter_call_method(ts->rtprecv,MS_RTP_RECV_SET_SESSION,ts->rtps); - - ms_filter_call_method (ts->rtprecv, MS_FILTER_SET_SAMPLE_RATE, - &pt->clock_rate); - - ms_filter_call_method (ts->frecorder, MS_FILTER_SET_SAMPLE_RATE, - &pt->clock_rate); - - val = ms_filter_call_method(ts->fplayer,MS_FILE_PLAYER_OPEN,(void*)bench->wavfile); - if (val!=0) - { - ms_error("bench.c: Cannot open wav file (%s)", bench->wavfile); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - - val=0; - ms_filter_call_method (ts->fplayer, MS_FILTER_GET_SAMPLE_RATE, - &val); - if (val!=pt->clock_rate) - { - ms_error("bench.c: unsupported rate for wav file: codec=%i / file=%i", - pt->clock_rate, val); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - ms_filter_call_method (ts->fplayer, MS_FILTER_GET_NCHANNELS, - &val); - - if (val!=1) - { - ms_error("bench.c: unsupported number of channel for wav file: codec=1 / file=%i", - val); - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - ortp_free(ts); - return count; - } - ms_filter_call_method_noarg(ts->fplayer,MS_FILE_PLAYER_START); - - if (strstr(bench->wavfile, ".au")==NULL) - { - ms_filter_link(ts->fplayer,0,ts->encoder,0); - ms_filter_link(ts->encoder,0,ts->rtpsend,0); - } - else - { - ms_filter_link(ts->fplayer,0,ts->rtpsend,0); - } - - ms_filter_link(ts->rtprecv,0,ts->decoder,0); - ms_filter_link(ts->decoder,0,ts->frecorder,0); - - ms_ticker_attach(bench->ticker,ts->fplayer); - ms_ticker_attach(bench->ticker,ts->rtprecv); - - if (pos < bench->num_session_record) - { - char rec_file[128]; - snprintf(rec_file, sizeof(rec_file), "rec_%s_%i.wav", - bench->ip_destination, - bench->port_destination+pos*2); - ms_filter_call_method(ts->frecorder,MS_FILE_REC_OPEN,(void*)rec_file); - ms_filter_call_method_noarg(ts->frecorder,MS_FILE_REC_START); - } - - bench->tsessions = ms_list_append(bench->tsessions, (void*)ts); - count++; - } - - return count; -} - -static int uninit_bench(struct bench_config *bench) -{ - MSList *it; - for(it=bench->tsessions;it!=NULL;it=bench->tsessions){ - struct test_session *ts = (struct test_session *)it->data; - bench->tsessions = ms_list_remove_link(bench->tsessions, it); - - ms_ticker_detach(bench->ticker,ts->fplayer); - ms_ticker_detach(bench->ticker,ts->rtprecv); - - ms_filter_call_method_noarg(ts->frecorder,MS_FILE_REC_CLOSE); - - if (strstr(bench->wavfile, ".au")==NULL) - { - ms_filter_unlink(ts->fplayer,0,ts->encoder,0); - ms_filter_unlink(ts->encoder,0,ts->rtpsend,0); - } - else - { - ms_filter_unlink(ts->fplayer,0,ts->rtpsend,0); - } - - ms_filter_unlink(ts->rtprecv,0,ts->decoder,0); - ms_filter_unlink(ts->decoder,0,ts->frecorder,0); - - if (ts->fplayer) ms_filter_destroy(ts->fplayer); - if (ts->encoder) ms_filter_destroy(ts->encoder); - if (ts->rtpsend) ms_filter_destroy(ts->rtpsend); - - if (ts->rtprecv) ms_filter_destroy(ts->rtprecv); - if (ts->decoder) ms_filter_destroy(ts->decoder); - if (ts->frecorder) ms_filter_destroy(ts->frecorder); - - ortp_free(ts); - } - - ms_ticker_destroy(bench->ticker); - return 0; -} - - -int main(int argc, char *argv[]){ - int pos; - int count; - ortp_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - ms_init(); - rtp_profile_set_payload(&av_profile,115,&payload_type_lpc1015); - rtp_profile_set_payload(&av_profile,110,&payload_type_speex_nb); - rtp_profile_set_payload(&av_profile,111,&payload_type_speex_wb); - rtp_profile_set_payload(&av_profile,112,&payload_type_ilbc); - - signal(SIGINT,stop); - - count=0; - for (pos=0;cfg[pos].num_session!=0;pos++) - { - count = count + init_bench(&cfg[pos]); - ms_sleep(10); - } - - ms_message("Number of session started: %i.", count); - - while(run) - ms_sleep(1); - - for (pos=0;cfg[pos].num_session!=0;pos++) - { - uninit_bench(&cfg[pos]); - } - - return 0; -} - diff --git a/linphone/mediastreamer2/tests/echo.c b/linphone/mediastreamer2/tests/echo.c deleted file mode 100644 index ca2ddbfc2..000000000 --- a/linphone/mediastreamer2/tests/echo.c +++ /dev/null @@ -1,99 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/msfilter.h" -#include "mediastreamer2/mssndcard.h" -#include "mediastreamer2/msticker.h" - -#ifndef _WIN32_WCE -#include -#elif defined(_MSC_VER) -#define main _tmain -#endif - -static int run=1; - -static void stop(int signum){ - run=0; -} - -int main(int argc, char *argv[]){ - MSFilter *f1,*f2; - MSSndCard *card_capture; - MSSndCard *card_playback; - MSTicker *ticker; - char *card_id=NULL; - int rate = 16000; - - ortp_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - ms_init(); - -#ifndef _WIN32_WCE - signal(SIGINT,stop); -#endif - - if (argc>1) - card_id=argv[1]; - - if (card_id!=NULL) - { - card_capture = ms_snd_card_manager_get_card(ms_snd_card_manager_get(),card_id); - card_playback = ms_snd_card_manager_get_card(ms_snd_card_manager_get(),card_id); -#ifdef __linux - if (card_playback==NULL) - card_playback = ms_alsa_card_new_custom(card_id, card_id); - if (card_capture==NULL) - card_capture = ms_alsa_card_new_custom(card_id, card_id); -#endif - } - else - { - card_capture = ms_snd_card_manager_get_default_capture_card(ms_snd_card_manager_get()); - card_playback = ms_snd_card_manager_get_default_playback_card(ms_snd_card_manager_get()); - } - if (card_playback==NULL || card_capture==NULL){ - ms_error("No card."); - return -1; - } - f1=ms_snd_card_create_reader(card_capture); - f2=ms_snd_card_create_writer(card_playback); - - ms_filter_call_method (f1, MS_FILTER_SET_SAMPLE_RATE, - &rate); - ms_filter_call_method (f2, MS_FILTER_SET_SAMPLE_RATE, - &rate); - - ticker=ms_ticker_new(); - ms_filter_link(f1,0,f2,0); - ms_ticker_attach(ticker,f1); -#ifndef _WIN32_WCE - while(run) - ms_sleep(1); -#else - ms_sleep(5); -#endif - ms_ticker_detach(ticker,f1); - ms_ticker_destroy(ticker); - ms_filter_unlink(f1,0,f2,0); - ms_filter_destroy(f1); - ms_filter_destroy(f2); - return 0; -} diff --git a/linphone/mediastreamer2/tests/mediastream.c b/linphone/mediastreamer2/tests/mediastream.c deleted file mode 100644 index c15362f12..000000000 --- a/linphone/mediastreamer2/tests/mediastream.c +++ /dev/null @@ -1,381 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include - -#include "mediastreamer2/mediastream.h" -#include "mediastreamer2/msequalizer.h" -#include "mediastreamer2/msvolume.h" -#ifdef VIDEO_ENABLED -#include "mediastreamer2/msv4l.h" -#endif - -#include -#include -#ifndef WIN32 -#include -#endif -#include -#include -#include - -static int cond=1; - -static const char * capture_card=NULL; -static float ng_threshold=-1; -static bool_t use_ng=FALSE; - -/* starting values echo canceller */ -static int ec_len_ms=0, ec_delay_ms=250, ec_framesize; - - -static void stop_handler(int signum) -{ - cond--; - if (cond<0) exit(-1); -} - -static bool_t parse_addr(const char *addr, char *ip, int len, int *port) -{ - const char *semicolon=NULL; - int iplen; - int slen; - const char *p; - - *port=0; - semicolon=strchr(addr,':'); - for (p=addr+strlen(addr)-1;p>addr;p--){ - if (*p==':') { - semicolon=p; - break; - } - } - if (semicolon==NULL) return FALSE; - iplen=semicolon-addr; - slen=MIN(iplen,len-1); - strncpy(ip,addr,slen); - ip[slen]='\0'; - *port=atoi(semicolon+1); - return TRUE; -} - -static void display_items(void *user_data, uint32_t csrc, rtcp_sdes_type_t t, const char *content, uint8_t content_len){ - char str[256]; - int len=MIN(sizeof(str)-1,content_len); - strncpy(str,content,len); - str[len]='\0'; - switch(t){ - case RTCP_SDES_CNAME: - ms_message("Found CNAME=%s",str); - break; - case RTCP_SDES_TOOL: - ms_message("Found TOOL=%s",str); - break; - case RTCP_SDES_NOTE: - ms_message("Found NOTE=%s",str); - break; - default: - ms_message("Unhandled SDES item (%s)",str); - } -} - -static void parse_rtcp(mblk_t *m){ - do{ - if (rtcp_is_RR(m)){ - ms_message("Receiving RTCP RR"); - }else if (rtcp_is_SR(m)){ - ms_message("Receiving RTCP SR"); - }else if (rtcp_is_SDES(m)){ - ms_message("Receiving RTCP SDES"); - rtcp_sdes_parse(m,display_items,NULL); - }else { - ms_message("Receiving unhandled RTCP message"); - } - }while(rtcp_next_packet(m)); -} - -static void parse_events(OrtpEvQueue *q){ - OrtpEvent *ev; - while((ev=ortp_ev_queue_get(q))!=NULL){ - OrtpEventData *d=ortp_event_get_data(ev); - switch(ortp_event_get_type(ev)){ - case ORTP_EVENT_RTCP_PACKET_RECEIVED: - parse_rtcp(d->packet); - break; - default: - ms_warning("Unhandled ortp event."); - } - ortp_event_destroy(ev); - } -} - -const char *usage="mediastream --local --remote --payload \n" - "[ --fmtp ]\n" - "[ --jitter ]\n" - "[ --width ]\n" - "[ --height ]\n" - "[ --bitrate ]\n" - "[ --ec (enable echo canceller)]\n" - "[ --agc (enable automatic gain control)]\n" - "[ --ng (enable noise gate)]\n" - "[ --ng-threshold <(float) [0-1]> (noise gate threshold)]\n" - "[ --capture-card ] \n"; - -static void run_media_streams(int localport, const char *remote_ip, int remoteport, int payload, const char *fmtp, - int jitter, int bitrate, MSVideoSize vs, bool_t ec, bool_t agc, bool_t eq); - -int main(int argc, char * argv[]) -{ - int i; - int localport=0,remoteport=0,payload=0; - char ip[50]; - const char *fmtp=NULL; - int jitter=50; - int bitrate=0; - MSVideoSize vs; - bool_t ec=FALSE; - bool_t agc=FALSE; - bool_t eq=FALSE; - /*create the rtp session */ - ortp_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - rtp_profile_set_payload(&av_profile,115,&payload_type_lpc1015); - rtp_profile_set_payload(&av_profile,110,&payload_type_speex_nb); - rtp_profile_set_payload(&av_profile,111,&payload_type_speex_wb); - rtp_profile_set_payload(&av_profile,112,&payload_type_ilbc); -#ifdef VIDEO_ENABLED - rtp_profile_set_payload(&av_profile,26,&payload_type_jpeg); - rtp_profile_set_payload(&av_profile,98,&payload_type_h263_1998); - rtp_profile_set_payload(&av_profile,97,&payload_type_theora); - rtp_profile_set_payload(&av_profile,99,&payload_type_mp4v); - rtp_profile_set_payload(&av_profile,100,&payload_type_x_snow); - rtp_profile_set_payload(&av_profile,102,&payload_type_h264); -#endif - - vs.width=MS_VIDEO_SIZE_CIF_W; - vs.height=MS_VIDEO_SIZE_CIF_H; - if (argc<4) { - printf(usage); - return -1; - } - for (i=1;i0) pt->normal_bitrate=bitrate; - - if (pt->type!=PAYLOAD_VIDEO){ - MSSndCardManager *manager=ms_snd_card_manager_get(); - MSSndCard *capt= capture_card==NULL ? ms_snd_card_manager_get_default_capture_card(manager) : - ms_snd_card_manager_get_card(manager,capture_card); - audio=audio_stream_new(localport,ms_is_ipv6(remote_ip)); - audio_stream_enable_automatic_gain_control(audio,agc); - audio_stream_enable_noise_gate(audio,use_ng); - audio_stream_set_echo_canceller_params(audio,ec_len_ms,ec_delay_ms,ec_framesize); - printf("Starting audio stream.\n"); - audio_stream_start_now(audio,profile,remote_ip,remoteport,remoteport+1,payload,jitter, - ms_snd_card_manager_get_default_playback_card(manager), - capt, - ec); - if (audio) { - if (use_ng && ng_threshold!=-1) - ms_filter_call_method(audio->volsend,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_threshold); - session=audio->session; - } - }else{ -#ifdef VIDEO_ENABLED - if (eq){ - ms_fatal("Cannot put an audio equalizer in a video stream !"); - exit(-1); - } - printf("Starting video stream.\n"); - video=video_stream_new(localport, ms_is_ipv6(remote_ip)); - video_stream_set_sent_video_size(video,vs); - video_stream_start(video,profile, - remote_ip, - remoteport,remoteport+1, - payload, - jitter, - ms_web_cam_manager_get_default_cam(ms_web_cam_manager_get())); - session=video->session; -#else - printf("Error: video support not compiled.\n"); -#endif - } - if (eq || ec){ /*read from stdin interactive commands */ - char commands[128]; - commands[127]='\0'; - ms_sleep(1); /* ensure following text be printed after ortp messages */ - if (eq) - printf("\nPlease enter equalizer requests, such as 'eq active 1', 'eq active 0', 'eq 1200 0.1 200'\n"); - if (ec) - printf("\nPlease enter echo canceller requests: ec reset; ec equalizer,MS_EQUALIZER_GET_NUM_FREQUENCIES,&n); - t=(float*)alloca(sizeof(float)*n); - ms_filter_call_method(audio->equalizer,MS_EQUALIZER_DUMP_STATE,t); - for(i=0;i0.01){ - printf("%i:%f:0 ",(i*pt->clock_rate)/(2*n),t[i]); - } - } - printf("\nOK\n"); - }else if (sscanf(commands,"ec reset %i",&active)==1){ - //audio_stream_enable_equalizer(audio,active); - //printf("OK\n"); - }else if (sscanf(commands,"ec active %i",&active)==1){ - //audio_stream_enable_equalizer(audio,active); - //printf("OK\n"); - }else if (sscanf(commands,"ec %i %i",&delay_ms,&tail_ms)==2){ - audio_stream_set_echo_canceller_params(audio,tail_ms,delay_ms,128); - // revisit: workaround with old method call to force echo reset - delay_ms*=8; - ms_filter_call_method(audio->ec,MS_FILTER_SET_PLAYBACKDELAY,&delay_ms); - printf("OK\n"); - }else if (strstr(commands,"quit")){ - break; - }else printf("Cannot understand this.\n"); - } - }else{ /* no interactive stuff - continuous debug output */ - rtp_session_register_event_queue(session,q); - while(cond) - { - int n; - for(n=0;n<100;++n){ - #ifdef WIN32 - MSG msg; - Sleep(10); - while (PeekMessage(&msg, NULL, 0, 0,1)){ - TranslateMessage(&msg); - DispatchMessage(&msg); - } - #else - struct timespec ts; - ts.tv_sec=0; - ts.tv_nsec=10000000; - nanosleep(&ts,NULL); - #endif - #if defined(VIDEO_ENABLED) - if (video) video_stream_iterate(video); - #endif - } - ortp_global_stats_display(); - if (session){ - printf("Bandwidth usage: download=%f kbits/sec, upload=%f kbits/sec\n", - rtp_session_compute_recv_bandwidth(session)*1e-3, - rtp_session_compute_send_bandwidth(session)*1e-3); - parse_events(q); - } - } - } - - printf("stopping all...\n"); - - if (audio) audio_stream_stop(audio); -#ifdef VIDEO_ENABLED - if (video) video_stream_stop(video); -#endif - ortp_ev_queue_destroy(q); - rtp_profile_destroy(profile); -} diff --git a/linphone/mediastreamer2/tests/mtudiscover.c b/linphone/mediastreamer2/tests/mtudiscover.c deleted file mode 100644 index 92f2285ea..000000000 --- a/linphone/mediastreamer2/tests/mtudiscover.c +++ /dev/null @@ -1,33 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mscommon.h" - -int main(int argc, char *argv[]){ - - ms_init(); - if (argc<2){ - ms_error("Usage: mtudiscover [host]"); - return -1; - } - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - printf("result: %i \n",ms_discover_mtu(argv[1])); - return 0; -} diff --git a/linphone/mediastreamer2/tests/ring.c b/linphone/mediastreamer2/tests/ring.c deleted file mode 100644 index 8751eff98..000000000 --- a/linphone/mediastreamer2/tests/ring.c +++ /dev/null @@ -1,52 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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. -*/ - -#ifdef HAVE_CONFIG_H -#include "mediastreamer-config.h" -#endif - -#include "mediastreamer2/mediastream.h" - -int main(int argc, char *argv[]){ - RingStream *r; - const char *file; - MSSndCard *sc; - const char * card_id=NULL; - - ortp_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - ms_init(); - if (argc>1){ - file=argv[1]; - }else file="/usr/share/sounds/linphone/rings/oldphone.wav"; - if (argc>2){ - card_id=argv[2]; - } - - sc=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),card_id); -#ifdef __linux - if (sc==NULL) - sc = ms_alsa_card_new_custom(card_id, card_id); -#endif - - r=ring_start(file,2000,sc); - ms_sleep(10); - ring_stop(r); - return 0; -} diff --git a/linphone/mediastreamer2/tests/videodisplay.c b/linphone/mediastreamer2/tests/videodisplay.c deleted file mode 100644 index 843b4e097..000000000 --- a/linphone/mediastreamer2/tests/videodisplay.c +++ /dev/null @@ -1,115 +0,0 @@ -/* -mediastreamer2 library - modular sound and video processing and streaming -Copyright (C) 2006 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 "mediastreamer2/mediastream.h" -#include "mediastreamer2/msvideoout.h" -#include "mediastreamer2/msv4l.h" - -int main(int argc, char *argv[]){ - VideoStream *vs; - MSWebCam *cam; - MSVideoSize vsize; - int i; - - vsize.width=MS_VIDEO_SIZE_CIF_W; - vsize.height=MS_VIDEO_SIZE_CIF_H; - - ortp_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); - ms_init(); - cam=ms_web_cam_manager_get_default_cam(ms_web_cam_manager_get()); - /* this is to test the sequence start/stop */ - for(i=0;i<1;++i){ - int n; - vs=video_preview_start(cam,vsize); - - for(n=0;n<1000;++n){ -#ifdef WIN32 - MSG msg; - Sleep(100); - while (PeekMessage(&msg, NULL, 0, 0,1)){ - TranslateMessage(&msg); - DispatchMessage(&msg); - } -#else - struct timespec ts; - ts.tv_sec=0; - ts.tv_nsec=10000000; - nanosleep(&ts,NULL); - - if (vs) video_stream_iterate(vs); -#endif - -/* test code */ - if (n==400) - { - ms_ticker_detach (vs->ticker, vs->source); - - vs->tee = ms_filter_new(MS_TEE_ID); - - ms_filter_unlink(vs->pixconv,0, vs->output,0); - - ms_filter_link(vs->pixconv,0,vs->tee,0); - ms_filter_link(vs->tee,0,vs->output,0); - ms_filter_link(vs->tee,1,vs->output,1); - - //ms_filter_unlink(vs->tee,0,vs->output,0); - ms_ticker_attach (vs->ticker, vs->source); - - } - if (n==500) - { - int corner=1; - ms_filter_call_method(vs->output,MS_VIDEO_OUT_SET_CORNER,&corner); - } - if (n==600) - { - int corner=2; - ms_filter_call_method(vs->output,MS_VIDEO_OUT_SET_CORNER,&corner); - } - if (n==700) - { - int corner=3; - ms_filter_call_method(vs->output,MS_VIDEO_OUT_SET_CORNER,&corner); - } - if (n==800) - { - int corner=-1; - ms_filter_call_method(vs->output,MS_VIDEO_OUT_SET_CORNER,&corner); - } - if (n==900) - { - ms_ticker_detach (vs->ticker, vs->source); - - ms_filter_unlink(vs->pixconv,0,vs->tee,0); - ms_filter_unlink(vs->tee,0,vs->output,0); - ms_filter_unlink(vs->tee,1,vs->output,1); - ms_filter_destroy(vs->tee); - vs->tee=NULL; - - ms_filter_link(vs->pixconv,0, vs->output,0); - - - ms_ticker_attach (vs->ticker, vs->source); - } - } - video_preview_stop(vs); - } - return 0; -} diff --git a/linphone/mingw-envsetup.sh b/linphone/mingw-envsetup.sh deleted file mode 100644 index 9f79d8976..000000000 --- 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/oRTP/.gitignore b/linphone/oRTP/.gitignore deleted file mode 100644 index 8babbdc96..000000000 --- a/linphone/oRTP/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -Makefile -Makefile.in -aclocal.m4 -autom4te.cache -config.guess -config.log -config.status -config.sub -configure -depcomp -install-sh -libtool -ltmain.sh -missing -ortp-config.h -ortp-config.h.in -ortp.defs -ortp.pc -ortp.spec -stamp-h1 -doc -ortp.doxygen -.settings diff --git a/linphone/oRTP/AUTHORS b/linphone/oRTP/AUTHORS deleted file mode 100644 index 6e305d120..000000000 --- a/linphone/oRTP/AUTHORS +++ /dev/null @@ -1,4 +0,0 @@ -Simon MORLAT (simon dot morlat at linphone dot org) is the author the oRTP library. - - -Lovadina Nicola < lovadina dot nicola dot 10272 at unimo dot it > worked on RTCP support. diff --git a/linphone/oRTP/COPYING b/linphone/oRTP/COPYING deleted file mode 100644 index b1e3f5a26..000000000 --- a/linphone/oRTP/COPYING +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey 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 library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/linphone/oRTP/ChangeLog b/linphone/oRTP/ChangeLog deleted file mode 100644 index 8276cdffa..000000000 --- a/linphone/oRTP/ChangeLog +++ /dev/null @@ -1,153 +0,0 @@ -2007-07-26 Francois-Xavier Kowalski - - * pkg.list: 1.3 - Do not run makewhatis when installing EPM-generated package. - -2007-04-19 Francois-Xavier Kowalski - - * ortp.spec.in (Requires): 1.4 - Adapt to new documentation generation change from gtk-doc to - Doxygen. - - * Makefile.am (docdir): 1.27 - automake's docdir is not always defined & is generally not - package specific, so we manually define docdir & pkgdocdir. - -2007-03-01 Francois-Xavier Kowalski - - * include/ortp/payloadtype.h: 1.28 - Encompass every declaration (whether lvalue or not) under extern - "C". - -2007-01-18 Francois-Xavier Kowalski - - * oRTP/Makefile.am: 1.24 - Fix RPM package generattion to cope with - - -2006-10-24 Francois-Xavier 'FiX' KOWALSKI - - * include/ortp/port.h: 1.21 - * src/scheduler.h (ortp_get_scheduler): 1.13 - Disable some Intel C/C++ warnings to build with icc. - - * include/ortp/stun_udp.h (__STUN_UDP_H__): 1.6 - * include/ortp/stun.h: 1.6 - Use - -2006-07-10 Francois-Xavier 'FiX' KOWALSKI - - * configure.ac: 1.89 - * gtk-doc.make (dist-check-gtkdoc): 1.1 - Non-fatal but incomplete "make dist" when gtk-doc is not - installed. - -2006-07-07 Francois-Xavier 'FiX' KOWALSKI - - * src/avprofile.c (NORMAL_BITRATE): 1.27 - Use ISO C/99 tagged struct syntax rather than GCC's legacy one. - -2006-07-07 Francois-Xavier Kowalski - - * src/rtpsession.c (RTP_SEQ_IS_GREATER): 1.132 - Fix comment content (using <>) that breaks gtkdoc SGML - generation. - - * include/ortp/event.h: 1.3 - OrtpEventData cannot be a type a s struct at the same time. - - * ortp.spec.in (Requires): 1.2 - Drop glib option - - * gtk-doc.make: - * docs/Makefile.am (#DOC_MAIN_SGML_FILE): 1.7 - * Makefile.am - Use slightly modified gtkdocize. - - * ortp.spec.in (Requires): 1.2 - Force build of gtk-doc, as the default choice that comes with - GTK_DOC_CHECK m4 macro is "no". - -2006-07-06 Francois-Xavier Kowalski - - * src/payloadtype.c (rtp_profile_destroy): 1.20 - avoid double-free - - * configure.ac: 1.88 - ortp-0.10.1.1 - -Friday March 10 2006 : ortp-0.9.1 - - fix package name (was 0.9.0.) - -Wednesday March 8 2006 : ortp-0.9.0 - - a lot of cleanups, glib dropped, win32 port reactivated - -Tuesday December 20 2005 : ortp-0.8.1 - - change session's clockrate dependant parameters upon payload type changed events at socket level - - rtp_session_set_recv_buf_size() added. - - bugfix in rtp_session_set_remote_addr() - - memory leak fixed in rtp_profile_destroy() - -Wednesday December 07 2005: ortp-0.8.0 - - make package modifications - - make rpm added - - add support for different payload types for incoming and outgoing stream (which breaks api compatibility) - - prefix all PayloadType with payload_type_* to avoid naming conflicts - -Wednesday August 24 2005: ortp-0.7.1 - - added patch for pkgconfig support from Jean-Philippe Barrette-LaPierre - -Monday August 8 2005: ortp-0.7.1pre5 - - adaptive jitter buffer improvements - - timestamp compensated packets returned by rtp_session_recvm_with_ts - - new payload definitions. - -Tuesday August 2 2005: ortp-0.7.1pre4 - - adaptive jitter buffer cleanups. - - hton24 utility function added for RTCP - -Tuesday July 4 2005: ortp-0.7.1pre3 - - improve automatic jitter buffer: no more closed-loop; just estimation. - - merge patch for multicast from Samuel Thibault - - merge patch for parsing of rtcp packets from Nicola Baldo - - add static payload definitions for g723.1 and g729. - -Wednesday November 17 2004: ortp-0.7.0 series starts - - add automatic jitter buffer: - * compensate clock slides - * estimate the jitter and sets the minimum jitter compensation delay accordingly - - posix timer simplified - - less system calls: use non blocking recv() and don't use select() or poll() - - add new functions for optimized packet sending - - recv() and send() are always made within the rtp_session_recv..() and rtp_session_send..() - functions. That means that scheduled non blocking mode does no more work as it worked before, ie - that packet will be sent immediately rather than being sent on time by the scheduler as it was before. - - HPUX kernel target removed. - - scheduler always built. - -Tuesday August 12 2003 : ortp-0.6.3 - - some improvements by Aymeric Moizard for Win32 build - - some bug fixes concerning ipv6 support. - -Thursday August 7 2003 : ortp-0.6.2 - - just some minor improvements for using oRTP in a C++ environment. - -Wednesday January 8 2003: ortp-0.6.0 - - many bug fixes by Telisma: the most important bug concerned the windows port. - - some new functionnalities concerning the RTP profiles and payload management. - - ported to glib-2.0 . - -Monday September 23 2002: ortp-0.5.0 - - ortp has been ported to the Microsoft Windows OS (version 2000 and later) by Eloquant - (http://www.eloquant.com) - - some bug fixes and improvements of the windows port have been made by Telisma - (http://www.telisma.com) - -Wednesday June 5 2002: ortp-0.4.4 - - Some crashing bugs fixed. - -Wednesday May 15 2002: ortp-0.4.3 - - Install include files properly. - -Tuesday May 7 2002: ortp-0.4.2 - - First official and public release of oRTP. diff --git a/linphone/oRTP/INSTALL b/linphone/oRTP/INSTALL deleted file mode 100644 index 54caf7c19..000000000 --- a/linphone/oRTP/INSTALL +++ /dev/null @@ -1,229 +0,0 @@ -Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002 Free Software -Foundation, Inc. - - This file is free documentation; the Free Software Foundation gives -unlimited permission to copy, distribute and modify it. - -Basic Installation -================== - - These are generic installation instructions. - - 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 only 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. If you're - using `csh' on an old version of System V, you might need to type - `sh ./configure' instead to prevent `csh' from trying to execute - `configure' itself. - - Running `configure' takes awhile. 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. - -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=c89 CFLAGS=-O2 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 must use a version of `make' that -supports the `VPATH' variable, such as 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 `..'. - - If you have to use a `make' that does not support the `VPATH' -variable, you have 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. - -Installation Names -================== - - By default, `make install' will install the package's files in -`/usr/local/bin', `/usr/local/man', etc. You can specify an -installation prefix other than `/usr/local' by giving `configure' the -option `--prefix=PATH'. - - You can specify separate installation prefixes for -architecture-specific files and architecture-independent files. If you -give `configure' the option `--exec-prefix=PATH', the package will use -PATH as the prefix for installing programs and libraries. -Documentation and other data files will still use the regular prefix. - - In addition, if you use an unusual directory layout you can give -options like `--bindir=PATH' 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. - -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 `--target=TYPE' option 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 - -will cause the specified gcc to be used as the C compiler (unless it is -overridden in the site shell script). - -`configure' Invocation -====================== - - `configure' recognizes the following options to control how it -operates. - -`--help' -`-h' - Print a summary of the options to `configure', and exit. - -`--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. - -`configure' also accepts some other, not widely useful, options. Run -`configure --help' for more details. - diff --git a/linphone/oRTP/Makefile.am b/linphone/oRTP/Makefile.am deleted file mode 100644 index 5fea49152..000000000 --- a/linphone/oRTP/Makefile.am +++ /dev/null @@ -1,89 +0,0 @@ -# linphone/oRTP/Makefile.am -- - -EXTRA_DIST = oRTP.prj ortp-config.h.in TODO pkg.list autogen.sh ortp.pc.in ortp.spec.in ortp.spec ortp.doxygen - -SUBDIRS=src build include - -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = ortp.pc - -SOURCES=$(top_srcdir)/include/ortp/*.h $(top_srcdir)/src/*.c $(top_srcdir)/src/*.h - -#html doc -if HAVE_DOXYGEN - -# doxdir & pkgdocdir are not always defined by automake -docdir=$(datadir)/doc -pkgdocdir=$(docdir)/$(PACKAGE)-$(VERSION) -doc_htmldir=$(pkgdocdir)/html - -doc_html_DATA = $(top_builddir)/doc/html/html.tar - -$(doc_html_DATA): $(top_builddir)/doc/html/index.html - cd $( - TAR_OPTIONS=--wildcards rpmbuild -ta --clean --rmsource --rmspec $(PACKAGE)-$(VERSION).tar.gz - -# `make package' - -if WITH_EPM - -.PHONY: package - -PKG_NAME = $(PACKAGE)-$(VERSION)-$(RELEASE) -BUILDROOT = $(shell pwd)/epm-install - -package: $(srcdir)/pkg.list $(srcdir)/configure - -rm -rf pkg $(BUILDROOT) $(PKG_NAME).* - $(MAKE) install DESTDIR=$(BUILDROOT) - $(MKEPMLIST) -u $(SYS_USER) -g $(SYS_GROUP) --prefix $(prefix) \ - $(BUILDROOT)/$(prefix) > files.list - $(EPM) -vv -f native -g -n -a $(ARCH) --keep-files --output-dir pkg \ - srcdir=$(srcdir) \ - top_srcdir=$(top_srcdir) \ - top_builddir=$(top_builddir) \ - PACKAGE=$(PACKAGE) \ - SUMMARY="$(SUMMARY)" \ - VERSION=$(ORTP_PKGCONFIG_VERSION) \ - RELEASE=$(RELEASE) \ - LICENSE="$(LICENSE)" \ - VENDOR="$(VENDOR)" \ - PACKAGER="$(PACKAGER)" \ - $(PACKAGE) $(srcdir)/pkg.list - mv -f pkg/$(PACKAGE)-$(ORTP_PKGCONFIG_VERSION)-$(RELEASE).$(EPM_PKG_EXT) $(PKG_NAME).$(ARCH).$(EPM_PKG_EXT) - -clean-local: - rm -rf pkg $(BUILDROOT) - rm -f files.list - rm -rf doc - -endif WITH_EPM - -distclean-local: - -rm -f ortp.defs - -all-local: ortp.spec - -ortp.spec: ortp.spec.in - diff --git a/linphone/oRTP/NEWS b/linphone/oRTP/NEWS deleted file mode 100644 index f3a081082..000000000 --- a/linphone/oRTP/NEWS +++ /dev/null @@ -1,51 +0,0 @@ -September 17, 2009: ortp-0.16.1 - - minor compilation fixes - -May 4, 2009 : ortp-0.16.0 - - update stun api to support new RFC - - fix gcc warnings - - added new PayloadType - -October 13, 2008: ortp-0.15.0 - - telephone event detection bugfix - - reduce number of memory allocation: !! attention here ABI/API change !! - If you are using mp=rtp_session_recvm_with_ts(), the payload data is no more pointed by mp->b_cont->b_rptr. - Instead you can use the following to skip the header: - rtp_get_payload(mp,mp->b_rptr); - -March 14, 2007: ortp-0.14.3 - - new ortp_set_memory_functions() method - - jitter buffer bugfixes, simplification and improvements - -July 27, 2007: ortp-0.14.0 - - a few optimisations - - support for number of channels in PayloadType (interface changed !) - - srtp optional support (using libsrtp from http://srtp.sf.net) - -April, 11 2007: ortp-0.13.1: - - do not recv rtcp packets from rtp_session_sendm_with_ts() when session is not send-only. - - removed gtk-doc, using doxygen instead. - - minor patches - -January, 23 2007: ortp-0.13.0 - - add support for a pluggable transport layer - - enables use of different RtpProfile for send and recv directions - - fix RTCP memleak - - new telephone-event types added. - -November, 9 2006: ortp-0.12.0 - - fix statistics - - jitter buffer accuracy improved - - enable 0 ms jitter buffer (implies permissive dequeuing of packets) - - enable optional connected mode: the udp socket is connect()ed so only - packets coming from the connected destination are received. - -August, 22 2006: ortp-0.11.0 - - added rtp_session_set_dscp, rtp_session_send_rtcp_APP - - fixed statistics little bugs. - -May, 30 2006: ortp-0.10.0 - - new RTCP parser - - new event api - - stun helper routines - - permissive algorithm for video packet enqueueing diff --git a/linphone/oRTP/README b/linphone/oRTP/README deleted file mode 100644 index be6a82033..000000000 --- a/linphone/oRTP/README +++ /dev/null @@ -1,58 +0,0 @@ -What is it ? -************ - -oRTP is a LGPL licensed C library implementing the RTP protocol (rfc3550). It is available -for most unix clones (primilarly Linux and HP-UX), and Microsoft Windows. - -What are the build prequisites ? -******************************** -libc library and header files. - -How do you I test ? -******************* - -There are shorts and easy to understand programs given with the library. There are good example -to understand how to use oRTP api. -- rtpsend : sends a stream from a file on disk. -- rtprecv : receives a stream and writes it to disk. -- mrtpsend: sends multiple streams from a file on disk to a range of remote port. -- mrtprecv: receives mutiple streams on a range of local ports and writes them on disk. - - -Is there some documentation ? -***************************** - -See the doxygen generated API documentation in docs/html. Program examples are a very good -starting point. - - -What are the current features ? -****************************** - - works with ipv6 - - packet scheduler - - adaptive jitter compensation - - automatic sending of RTCP SR or RR coumpounded with a SDES - - RTCP parser API - - -What are the planned features ? -******************************* - - multi-endpoint rtp sessions. - - -In which application oRTP is being used ? -***************************************** - - linphone (http://www.linphone.org) was the first. - - the OCMP platform (a Hewlett Packard product). - -How to compile my program using ortp ? -************************************** -gcc -o myprogram `pkg-config --cflags ortp` myprogram.c \ - `pkg-config --libs ortp` - - -What about Windows port ? -************************* -There are instructions and Microsoft Visual C++ project files in build/win32native/oRTP. - - diff --git a/linphone/oRTP/TODO b/linphone/oRTP/TODO deleted file mode 100644 index ade9114db..000000000 --- a/linphone/oRTP/TODO +++ /dev/null @@ -1,2 +0,0 @@ -* make statistics thread-safe. -* add a rtp_stats_display() func to display rtp_stats_t properly. diff --git a/linphone/oRTP/autogen.sh b/linphone/oRTP/autogen.sh deleted file mode 100755 index 99302cbe4..000000000 --- a/linphone/oRTP/autogen.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh -AM_VERSION="1.10" -if ! type aclocal-$AM_VERSION 1>/dev/null 2>&1; then - # automake-1.10 (recommended) is not available on Fedora 8 - AUTOMAKE=automake - ACLOCAL=aclocal -else - ACLOCAL=aclocal-${AM_VERSION} - AUTOMAKE=automake-${AM_VERSION} -fi - -if test -f /opt/local/bin/glibtoolize ; then - # darwin - LIBTOOLIZE=/opt/local/bin/glibtoolize -else - LIBTOOLIZE=libtoolize -fi -if test -d /opt/local/share/aclocal ; then - ACLOCAL_ARGS="-I /opt/local/share/aclocal" -fi - - -set -x -rm -rf config.cache autom4te.cache -$LIBTOOLIZE --copy --force -$ACLOCAL $ACLOCAL_ARGS -autoheader -$AUTOMAKE --add-missing --copy -autoconf - diff --git a/linphone/oRTP/build/.gitignore b/linphone/oRTP/build/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/oRTP/build/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/oRTP/build/Makefile.am b/linphone/oRTP/build/Makefile.am deleted file mode 100644 index 30b1fe2e8..000000000 --- a/linphone/oRTP/build/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS= win32native wince winmob diff --git a/linphone/oRTP/build/win32native/.gitignore b/linphone/oRTP/build/win32native/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/oRTP/build/win32native/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/oRTP/build/win32native/Makefile.am b/linphone/oRTP/build/win32native/Makefile.am deleted file mode 100644 index 3a96a0bac..000000000 --- a/linphone/oRTP/build/win32native/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=oRTP.vcproj ortp.def - diff --git a/linphone/oRTP/build/win32native/oRTP.vcproj b/linphone/oRTP/build/win32native/oRTP.vcproj deleted file mode 100644 index 7c8b7d61f..000000000 --- a/linphone/oRTP/build/win32native/oRTP.vcproj +++ /dev/null @@ -1,393 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/oRTP/build/win32native/ortp.def b/linphone/oRTP/build/win32native/ortp.def deleted file mode 100755 index 4b418e029..000000000 --- a/linphone/oRTP/build/win32native/ortp.def +++ /dev/null @@ -1,203 +0,0 @@ -LIBRARY ortp - -EXPORTS - - ortp_init - ortp_scheduler_init - ortp_exit - - ortp_get_scheduler - ortp_set_log_file - ortp_set_log_level_mask - ortp_logv_out - ortp_set_log_handler - ortp_strdup_printf - ortp_logv - - ortp_get_global_stats - ortp_global_stats_display - - session_set_new - session_set_select - session_set_destroy - - rtp_stats_display - rtp_session_get_stats - - rtp_session_init - rtp_session_new - - rtp_session_set_scheduling_mode - rtp_session_set_blocking_mode - rtp_session_set_profile - rtp_session_get_profile - rtp_session_set_data - - rtp_session_signal_connect - rtp_session_signal_disconnect_by_callback - rtp_session_set_ssrc - rtp_session_set_seq_number - rtp_session_get_seq_number - rtp_session_set_jitter_compensation - rtp_session_set_local_addr - rtp_session_set_remote_addr - rtp_session_enable_adaptive_jitter_compensation - rtp_session_set_recv_buf_size - - rtp_session_send_with_ts - rtp_session_sendm_with_ts - - rtp_session_set_sockets - rtp_session_get_rtp_socket - rtp_session_get_rtcp_socket - - rtp_session_set_payload_type - rtp_session_set_send_payload_type - rtp_session_get_send_payload_type - rtp_session_set_recv_payload_type - rtp_session_get_recv_payload_type - - rtp_session_recv_with_ts - rtp_session_recvm_with_ts - rtp_session_create_packet - - rtp_session_get_current_send_ts - rtp_session_get_current_recv_ts - rtp_session_reset - rtp_session_uninit - rtp_session_destroy - - rtp_add_csrc - - rtp_session_send_dtmf - rtp_session_add_telephone_event - rtp_session_create_telephone_event_packet - - rtp_session_set_source_description - rtp_session_set_symmetric_rtp - - rtp_profile_new - rtp_profile_set_payload - rtp_profile_clone_full - rtp_profile_destroy - rtp_profile_get_payload_from_rtpmap - - payload_type_set_send_fmtp - payload_type_clone - fmtp_get_value - - ortp_free - ortp_malloc - ortp_strdup - ortp_realloc - ortp_malloc0 - freemsg - dupmsg - - allocb - getq - putq - msgpullup - qinit - flushq - msgdsize - peekq - freeb - dupb - concatb - esballoc - - WIN_thread_create - WIN_thread_join - WIN_cond_init - WIN_mutex_init - WIN_mutex_unlock - WIN_cond_wait - WIN_mutex_lock - WIN_cond_destroy - WIN_mutex_destroy - WIN_cond_signal - - __ortp_log_mask - - rtp_session_register_event_queue - rtp_session_unregister_event_queue - ortp_ev_queue_new - ortp_ev_queue_flush - ortp_ev_queue_get - ortp_ev_queue_destroy - ortp_event_get_type - ortp_event_get_data - ortp_event_destroy - - stunParseHostName - stunParseServerName - sendMessage - stunEncodeMessage - stunBuildReqSimple - stunParseMessage - stunServerProcessMsg - stunNatType - stunTest - stunOpenSocket - stunOpenSocketPair - stunCalculateIntegrity_shortterm - stunCalculateIntegrity_longterm - stunCalculateFingerprint - - getWinSocketError - - rtp_session_set_transports - srtp_transport_new - - ortp_srtp_init - ortp_srtp_create - ortp_srtp_dealloc - ortp_srtp_add_stream - - rtp_session_set_dscp - rtp_session_compute_recv_bandwidth - rtp_session_compute_send_bandwidth - rtcp_next_packet - rtcp_is_SDES - rtcp_sdes_parse - rtcp_is_SR - rtcp_SR_get_ssrc - rtcp_SR_get_report_block - rtcp_SR_get_sender_info - rtcp_is_RR - rtcp_RR_get_ssrc - rtcp_RR_get_report_block - rtcp_is_BYE - rtcp_BYE_get_ssrc - rtcp_BYE_get_reason - rtcp_is_APP - rtcp_APP_get_subtype - rtcp_APP_get_ssrc - rtcp_APP_get_name - rtcp_APP_get_data - rtp_session_flush_sockets - rtp_session_resync - rtp_session_set_remote_addr_and_port - rtp_session_set_time_jump_limit - - copymsg - rtp_session_enable_jitter_buffer - - rtp_session_set_rtp_socket_recv_buffer_size - rtp_session_set_rtp_socket_send_buffer_size - rtp_session_set_jitter_buffer_params - - rtp_get_payload - - rtp_session_set_remote_addr_full - rtp_session_send_rtcp_APP - b64_decode - b64_encode - - payload_type_set_recv_fmtp - rtp_session_get_local_port - rtp_session_get_jitter_buffer_params - - copyb - turnAllocateSocketPair diff --git a/linphone/oRTP/build/wince/.gitignore b/linphone/oRTP/build/wince/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/oRTP/build/wince/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/oRTP/build/wince/Makefile.am b/linphone/oRTP/build/wince/Makefile.am deleted file mode 100644 index 3a96a0bac..000000000 --- a/linphone/oRTP/build/wince/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=oRTP.vcproj ortp.def - diff --git a/linphone/oRTP/build/wince/oRTP.vcproj b/linphone/oRTP/build/wince/oRTP.vcproj deleted file mode 100644 index c64f9a2ce..000000000 --- a/linphone/oRTP/build/wince/oRTP.vcproj +++ /dev/null @@ -1,877 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/oRTP/build/wince/ortp.def b/linphone/oRTP/build/wince/ortp.def deleted file mode 100644 index e7e4c7ea6..000000000 --- a/linphone/oRTP/build/wince/ortp.def +++ /dev/null @@ -1,209 +0,0 @@ -LIBRARY ortp - -EXPORTS - - ortp_init - ortp_scheduler_init - ortp_exit - - ortp_get_scheduler - ortp_set_log_file - ortp_set_log_level_mask - ortp_logv_out - ortp_set_log_handler - ortp_strdup_printf - ortp_logv - - ortp_get_global_stats - ortp_global_stats_display - - session_set_new - session_set_select - session_set_destroy - - rtp_stats_display - rtp_session_get_stats - - rtp_session_init - rtp_session_new - - rtp_session_set_scheduling_mode - rtp_session_set_blocking_mode - rtp_session_set_profile - rtp_session_get_profile - rtp_session_set_data - - rtp_session_signal_connect - rtp_session_signal_disconnect_by_callback - rtp_session_set_ssrc - rtp_session_set_seq_number - rtp_session_get_seq_number - rtp_session_set_jitter_compensation - rtp_session_set_local_addr - rtp_session_set_remote_addr - rtp_session_enable_adaptive_jitter_compensation - rtp_session_set_recv_buf_size - - rtp_session_send_with_ts - rtp_session_sendm_with_ts - - rtp_session_set_sockets - rtp_session_get_rtp_socket - rtp_session_get_rtcp_socket - - rtp_session_set_payload_type - rtp_session_set_send_payload_type - rtp_session_get_send_payload_type - rtp_session_set_recv_payload_type - rtp_session_get_recv_payload_type - - rtp_session_recv_with_ts - rtp_session_recvm_with_ts - rtp_session_create_packet - - rtp_session_get_current_send_ts - rtp_session_get_current_recv_ts - rtp_session_reset - rtp_session_uninit - rtp_session_destroy - - rtp_add_csrc - - rtp_session_send_dtmf - rtp_session_add_telephone_event - rtp_session_create_telephone_event_packet - - rtp_session_set_source_description - rtp_session_set_symmetric_rtp - - rtp_profile_new - rtp_profile_set_payload - rtp_profile_clone_full - rtp_profile_destroy - rtp_profile_get_payload_from_rtpmap - rtp_profile_get_payload_number_from_rtpmap - rtp_profile_get_payload_number_from_mime - - payload_type_new - payload_type_set_send_fmtp - payload_type_append_send_fmtp - payload_type_clone - payload_type_destroy - fmtp_get_value - - ortp_free - ortp_malloc - ortp_strdup - ortp_realloc - ortp_malloc0 - - freemsg - dupmsg - allocb - getq - putq - msgpullup - qinit - flushq - msgdsize - peekq - freeb - dupb - concatb - esballoc - - WIN_thread_create - WIN_thread_join - WIN_cond_init - WIN_mutex_init - WIN_mutex_unlock - WIN_cond_wait - WIN_mutex_lock - WIN_cond_destroy - WIN_mutex_destroy - WIN_cond_signal - - __ortp_log_mask - ortp_strdup_printf - ortp_strdup_vprintf - - rtp_session_register_event_queue - rtp_session_unregister_event_queue - ortp_ev_queue_new - ortp_ev_queue_flush - ortp_ev_queue_get - ortp_ev_queue_destroy - ortp_event_get_type - ortp_event_get_data - ortp_event_destroy - - stunParseHostName - stunParseServerName - sendMessage - stunEncodeMessage - stunBuildReqSimple - stunParseMessage - stunServerProcessMsg - stunNatType - stunTest - stunOpenSocket - stunOpenSocketPair - stunCalculateIntegrity_shortterm - stunCalculateIntegrity_longterm - stunCalculateFingerprint - - getWinSocketError - close_socket - set_non_blocking_socket - ortp_strerror - gettimeofday - ortp_file_exist - - - - rtp_session_set_dscp - rtp_session_compute_recv_bandwidth - rtp_session_compute_send_bandwidth - rtcp_next_packet - rtcp_is_SDES - rtcp_sdes_parse - rtcp_is_SR - rtcp_SR_get_ssrc - rtcp_SR_get_report_block - rtcp_SR_get_sender_info - rtcp_is_RR - rtcp_RR_get_ssrc - rtcp_RR_get_report_block - rtcp_is_BYE - rtcp_BYE_get_ssrc - rtcp_BYE_get_reason - rtcp_is_APP - rtcp_APP_get_subtype - rtcp_APP_get_ssrc - rtcp_APP_get_name - rtcp_APP_get_data - rtp_session_flush_sockets - rtp_session_resync - rtp_session_set_remote_addr_and_port - rtp_session_set_time_jump_limit - - copymsg - rtp_session_enable_jitter_buffer - - rtp_session_set_rtp_socket_recv_buffer_size - rtp_session_set_rtp_socket_send_buffer_size - rtp_session_set_jitter_buffer_params - - rtp_get_payload - - rtp_session_set_remote_addr_full - rtp_session_send_rtcp_APP - b64_decode - b64_encode - - payload_type_set_recv_fmtp - rtp_session_get_local_port - rtp_session_get_jitter_buffer_params - - copyb - turnAllocateSocketPair diff --git a/linphone/oRTP/build/winmob/Makefile.am b/linphone/oRTP/build/winmob/Makefile.am deleted file mode 100644 index b3208113b..000000000 --- a/linphone/oRTP/build/winmob/Makefile.am +++ /dev/null @@ -1,3 +0,0 @@ -EXTRA_DIST=oRTP.vcproj ortp.def oRTP.sln - - diff --git a/linphone/oRTP/build/winmob/oRTP.sln b/linphone/oRTP/build/winmob/oRTP.sln deleted file mode 100644 index e481bdf21..000000000 --- a/linphone/oRTP/build/winmob/oRTP.sln +++ /dev/null @@ -1,46 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "oRTP", "oRTP.vcproj", "{9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9FEA0683-C391-4C74-BCF6-2F9E4DE1B541}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/linphone/oRTP/build/winmob/oRTP.vcproj b/linphone/oRTP/build/winmob/oRTP.vcproj deleted file mode 100644 index fdfc895e1..000000000 --- a/linphone/oRTP/build/winmob/oRTP.vcproj +++ /dev/null @@ -1,916 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/oRTP/build/winmob/ortp.def b/linphone/oRTP/build/winmob/ortp.def deleted file mode 100644 index 4f43d85be..000000000 --- a/linphone/oRTP/build/winmob/ortp.def +++ /dev/null @@ -1,207 +0,0 @@ -LIBRARY ortp - -EXPORTS - - ortp_init - ortp_scheduler_init - ortp_exit - - ortp_get_scheduler - ortp_set_log_file - ortp_set_log_level_mask - ortp_logv_out - ortp_set_log_handler - ortp_strdup_printf - ortp_logv - - ortp_get_global_stats - ortp_global_stats_display - - session_set_new - session_set_select - session_set_destroy - - rtp_stats_display - rtp_session_get_stats - - rtp_session_init - rtp_session_new - - rtp_session_set_scheduling_mode - rtp_session_set_blocking_mode - rtp_session_set_profile - rtp_session_get_profile - rtp_session_set_data - - rtp_session_signal_connect - rtp_session_signal_disconnect_by_callback - rtp_session_set_ssrc - rtp_session_set_seq_number - rtp_session_get_seq_number - rtp_session_set_jitter_compensation - rtp_session_set_local_addr - rtp_session_set_remote_addr - rtp_session_enable_adaptive_jitter_compensation - rtp_session_set_recv_buf_size - - rtp_session_send_with_ts - rtp_session_sendm_with_ts - - rtp_session_set_sockets - rtp_session_get_rtp_socket - rtp_session_get_rtcp_socket - - rtp_session_set_payload_type - rtp_session_set_send_payload_type - rtp_session_get_send_payload_type - rtp_session_set_recv_payload_type - rtp_session_get_recv_payload_type - - rtp_session_recv_with_ts - rtp_session_recvm_with_ts - rtp_session_create_packet - - rtp_session_get_current_send_ts - rtp_session_get_current_recv_ts - rtp_session_reset - rtp_session_uninit - rtp_session_destroy - - rtp_add_csrc - - rtp_session_send_dtmf - - rtp_session_set_source_description - rtp_session_set_symmetric_rtp - - rtp_profile_new - rtp_profile_set_payload - rtp_profile_clone_full - rtp_profile_destroy - rtp_profile_get_payload_from_rtpmap - rtp_profile_get_payload_number_from_rtpmap - rtp_profile_get_payload_number_from_mime - - payload_type_new - payload_type_set_send_fmtp - payload_type_append_send_fmtp - payload_type_clone - payload_type_destroy - fmtp_get_value - - ortp_free - ortp_malloc - ortp_strdup - ortp_realloc - ortp_malloc0 - - freemsg - dupmsg - allocb - getq - putq - msgpullup - qinit - flushq - msgdsize - peekq - freeb - dupb - concatb - esballoc - - WIN_thread_create - WIN_thread_join - WIN_cond_init - WIN_mutex_init - WIN_mutex_unlock - WIN_cond_wait - WIN_mutex_lock - WIN_cond_destroy - WIN_mutex_destroy - WIN_cond_signal - - __ortp_log_mask - ortp_strdup_printf - ortp_strdup_vprintf - - rtp_session_register_event_queue - rtp_session_unregister_event_queue - ortp_ev_queue_new - ortp_ev_queue_flush - ortp_ev_queue_get - ortp_ev_queue_destroy - ortp_event_get_type - ortp_event_get_data - ortp_event_destroy - - stunParseHostName - stunParseServerName - sendMessage - stunEncodeMessage - stunBuildReqSimple - stunParseMessage - stunServerProcessMsg - stunNatType - stunTest - stunOpenSocket - stunOpenSocketPair - stunCalculateIntegrity_shortterm - stunCalculateIntegrity_longterm - stunCalculateFingerprint - - getWinSocketError - close_socket - set_non_blocking_socket - ortp_strerror - gettimeofday - ortp_file_exist - - - - rtp_session_set_dscp - rtp_session_compute_recv_bandwidth - rtp_session_compute_send_bandwidth - rtcp_next_packet - rtcp_is_SDES - rtcp_sdes_parse - rtcp_is_SR - rtcp_SR_get_ssrc - rtcp_SR_get_report_block - rtcp_SR_get_sender_info - rtcp_is_RR - rtcp_RR_get_ssrc - rtcp_RR_get_report_block - rtcp_is_BYE - rtcp_BYE_get_ssrc - rtcp_BYE_get_reason - rtcp_is_APP - rtcp_APP_get_subtype - rtcp_APP_get_ssrc - rtcp_APP_get_name - rtcp_APP_get_data - rtp_session_flush_sockets - rtp_session_resync - rtp_session_set_remote_addr_and_port - rtp_session_set_time_jump_limit - - copymsg - rtp_session_enable_jitter_buffer - - rtp_session_set_rtp_socket_recv_buffer_size - rtp_session_set_rtp_socket_send_buffer_size - rtp_session_set_jitter_buffer_params - - rtp_get_payload - - rtp_session_set_remote_addr_full - rtp_session_send_rtcp_APP - b64_decode - b64_encode - - payload_type_set_recv_fmtp - rtp_session_get_local_port - rtp_session_get_jitter_buffer_params - - copyb - turnAllocateSocketPair diff --git a/linphone/oRTP/configure.ac b/linphone/oRTP/configure.ac deleted file mode 100644 index addc9ca25..000000000 --- a/linphone/oRTP/configure.ac +++ /dev/null @@ -1,389 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. -AC_INIT([ortp],[0.16.1]) -AC_CANONICAL_SYSTEM - -dnl Source packaging numbers -ORTP_MAJOR_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f1) -ORTP_MINOR_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f2) -ORTP_MICRO_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f3) -ORTP_EXTRA_VERSION=$(echo $PACKAGE_VERSION | cut -d. -f4) - -LIBORTP_SO_CURRENT=8 dnl increment this number when you add/change/remove an interface -LIBORTP_SO_REVISION=0 dnl increment this number when you change source code, without changing interfaces; set to 0 when incrementing CURRENT -LIBORTP_SO_AGE=0 dnl increment this number when you add an interface, set to 0 if you remove an interface - -LIBORTP_SO_VERSION=$LIBORTP_SO_CURRENT:$LIBORTP_SO_REVISION:$LIBORTP_SO_AGE -ORTP_VERSION=${ORTP_MAJOR_VERSION}.${ORTP_MINOR_VERSION}.${ORTP_MICRO_VERSION} - -if test -n "$ORTP_EXTRA_VERSION" ; then - ORTP_VERSION="${ORTP_VERSION}.${ORTP_EXTRA_VERSION}" -fi - -ORTP_PKGCONFIG_VERSION=${ORTP_VERSION} - -AC_SUBST(LIBORTP_SO_VERSION) -AC_SUBST(ORTP_VERSION) -AC_SUBST(ORTP_PKGCONFIG_VERSION) - - -PACKAGE=ortp - -AM_INIT_AUTOMAKE([tar-ustar]) -m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])],) -AC_CONFIG_HEADERS(ortp-config.h) -AC_DEFINE_UNQUOTED(ORTP_MAJOR_VERSION,$ORTP_MAJOR_VERSION, [major version]) -AC_DEFINE_UNQUOTED(ORTP_MINOR_VERSION,$ORTP_MINOR_VERSION, [minor version]) -AC_DEFINE_UNQUOTED(ORTP_MICRO_VERSION,$ORTP_MICRO_VERSION, [micro version]) -AC_DEFINE_UNQUOTED(ORTP_VERSION,"$ORTP_VERSION",[ortp version number]) - -AC_SUBST([mkdir_p]) - -AC_MSG_CHECKING([warning make an error on compilation]) -AC_ARG_ENABLE(strict, -[ --enable-strict Enable error on compilation warning [default=yes]], -[wall_werror=$enableval], -[wall_werror=yes] -) - -AC_ARG_ENABLE(perf, -[ --enable-perf Disable costly features to reduce cpu consumtion [default=no]], -[perf=$enableval], -[perf=no] -) - -ORTP_DEFS= - -dnl enable ipv6 support -AC_ARG_ENABLE(ipv6, - [ --enable-ipv6 Turn on ipv6 support], - [case "${enableval}" in - yes) ipv6=true;; - no) ipv6=false;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-ipv6) ;; - esac],[ipv6=true]) -if test x$ipv6 = xtrue ; then - ORTP_DEFS="$ORTP_DEFS -DORTP_INET6" -fi - -AC_ARG_ENABLE(mode64bit, - [ --enable-mode64bit=[yes/no] produce a 64-bit library. [default=no]], - [case "${enableval}" in - yes) mode64bit_enabled=yes;; - no) mode64bit_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-mode64bit");; - esac], - [mode64bit_enabled=no]) - -AC_ARG_ENABLE(debug, - [ --enable-debug=[yes/no] enables the display of traces showing the execution of the library. [default=yes]], - [case "${enableval}" in - yes) debug_enabled=yes;; - no) debug_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-debug");; - esac], - [debug_enabled=no]) - - -hpux_host=no -posixtimer_interval=10000 -PTHREAD_LDFLAGS= - -case "$target_os" in - *hpux*) - hpux_host=yes - AC_DEFINE(NOCONNECT,1,[Defined if we should not use connect() on udp sockets]) - CFLAGS="$CFLAGS -D_HPUX_SOURCE -D_XOPEN_SOURCE_EXTENDED -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=199506L" - LIBS="$LIBS -lxnet" - ;; - *freebsd*) - AC_DEFINE(NOCONNECT,1,[Defined if we should not use connect() on udp sockets]) - PTHREAD_LDFLAGS="-pthread" - ;; - *mingw32ce) - CFLAGS="$CFLAGS -D_WIN32_WCE -D_WIN32_WINNT=0x0501 -DORTP_STATIC" - LIBS="$LIBS -lws2 -liphlpapi" - build_tests=no - mingw_found=yes - ;; - *mingw*) - CFLAGS="$CFLAGS -D_WIN32_WINNT=0x0501 -DORTP_STATIC" - LIBS="$LIBS -lws2_32 -liphlpapi -lwinmm" - build_tests=no - ;; -esac - -AC_CONFIG_COMMANDS([libtool-hacking],[ -if test "$mingw_found" = "yes" ; then - echo "Hacking libtool to work with mingw..." - sed -e 's/\*\" \$a_deplib \"\*/\*/' < ./libtool > libtool.tmp - cp -f ./libtool.tmp ./libtool - rm -f ./libtool.tmp -fi -],[mingw_found=$mingw_found]) - -dnl Checks for programs. -AC_PROG_CC -AC_LIBTOOL_WIN32_DLL -AC_PROG_LIBTOOL -AC_ENABLE_SHARED(yes) -AC_ENABLE_STATIC(no) - -if test "$GCC" != "yes" ; then - if test "$hpux_host" = "yes" ; then - dnl we are probably using HPUX cc compiler, so add a +O2 to CFLAGS - CFLAGS="$CFLAGS +O2 -g " - if test x$mode64bit_enabled = xyes ; then - CFLAGS="$CFLAGS +DA2.0W +DS2.0" - fi - fi -else - CFLAGS="$CFLAGS -Wall" -fi - -build_scheduler=yes - -dnl Check if we have seteuid system call -AC_CHECK_FUNCS(seteuid) - - -dnl check if we can use the pthread_library -AC_CHECK_LIB(pthread, pthread_mutex_init, [pthread_enabled=yes], [pthread_enabled=no]) -if test $pthread_enabled = "no" ; then - build_scheduler=no -else - PTHREAD_LIBS="-lpthread" - PTHREAD_CFLAGS="-D_REENTRANT" - AC_SUBST(PTHREAD_CFLAGS) - AC_SUBST(PTHREAD_LIBS) - AC_SUBST(PTHREAD_LDFLAGS) -fi -AC_ARG_WITH(thread-stack-size, - AC_HELP_STRING([--with-thread-stack-size=SIZE-IN-BYTES],[Set thread stack size [[default=os-default]]]), - [thread_stack_size=$withval], [thread_stack_size=0]) -AC_DEFINE_UNQUOTED(ORTP_DEFAULT_THREAD_STACK_SIZE, $thread_stack_size, [Default thread stack size (0 = let operating system decide)]) - - -dnl check for libsrtp support (secure rtp) -AC_ARG_WITH( srtp, - [ --with-srtp Set prefix where libsrtp can be found (ex:/usr or /usr/local)[default=/usr] ], - [ srtp_prefix=${withval}],[ srtp_prefix=/usr ]) - - -if test "${srtp_prefix}" != "/usr" ; then - SRTP_CFLAGS="-I${srtp_prefix}/include" - SRTP_LIBS="-L${srtp_prefix}/lib" -fi -SRTP_LIBS="$SRTP_LIBS -lsrtp" - -dnl check srtp headers -have_srtp=no -CPPFLAGS_save=$CPPFLAGS -CPPFLAGS=$SRTP_CFLAGS -AC_CHECK_HEADER([srtp/srtp.h],have_srtp_headers=yes) -CPPFLAGS=$CPPFLAGS_save - -dnl check for srtp lib -LDFLAGS_save=$LDFLAGS -LDFLAGS=$SRTP_LIBS -LIBS_save=$LIBS -AC_CHECK_LIB(srtp,srtp_init,have_srtp_lib=yes) -LDFLAGS=$LDFLAGS_save -LIBS=$LIBS_save - -if test "$have_srtp_headers$have_srtp_lib" = "yesyes" ; then - have_srtp=yes - AC_DEFINE(HAVE_SRTP, 1, [Defined when srtp support is compiled]) -else - AC_MSG_NOTICE([Could not find libsrtp headers or lib, cryto transport disabled.]) - SRTP_CFLAGS= - SRTP_LIBS= -fi - -AC_SUBST(SRTP_CFLAGS) -AC_SUBST(SRTP_LIBS) - -if test $debug_enabled = "yes"; then - ORTP_DEFS="$ORTP_DEFS -DORTP_DEBUG_MODE -g" - CFLAGS=`echo $CFLAGS | sed 's/-O.//'` -fi - -AC_ARG_ENABLE(memcheck, - [ --enable-memcheck=[yes/no] enables memory leak detection (HPUX only).], - [case "${enableval}" in - yes) memcheck_enabled=yes;; - no) memcheck_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-memcheck");; - esac], - [memcheck_enabled=no]) - -if test "$memcheck_enabled" = "yes" ; then - if test "$hpux_host" = "yes" ; then - AC_DEFINE(ENABLE_MEMCHECK,1,[Defined when memory leak checking if enabled]) - else - echo "WARNING ************ : the memory check option is only available for HPUX." - fi -fi - -AC_ARG_ENABLE(so-reuseaddr, - [ --enable-so-reuseaddr=[yes/no] enables SO_REUSEADDR socket option in the rtp_session_set_local_addr() function.], - [case "${enableval}" in - yes) so_reuseaddr_enabled=yes;; - no) so_reuseaddr_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-so-reuseaddr");; - esac], - [so_reuseaddr_enabled=yes]) - -if test "$so_reuseaddr_enabled" = "yes" ; then - AC_DEFINE(SO_REUSE_ADDR,1,[Defined when SO_REUSEADDR socket option in the rtp_session_set_local_addr() function is enabled]) -fi - - -dnl Checks for header files. -AC_HEADER_STDC -AC_CHECK_HEADERS(poll.h sys/poll.h sys/uio.h fcntl.h sys/time.h unistd.h sys/audio.h linux/soundcard.h) - -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 - ORTP_DEFS="$ORTP_DEFS -DORTP_BIGENDIAN" -fi - -dnl Checks for library functions. -AC_CHECK_FUNCS(select socket strerror) - -if test $hpux_host = "yes" ; then -dnl it seems 10 ms is too fast on hpux and it causes trouble - posixtimer_interval=20000 -fi - -AC_DEFINE_UNQUOTED(POSIXTIMER_INTERVAL,$posixtimer_interval,[Defines the periodicity of the rtp scheduler in microseconds]) - -if test "$perf" = "yes" ; then - CFLAGS="$CFLAGS -DPERF" -fi - -if test $GCC = yes && test $wall_werror = yes; then - CFLAGS="$CFLAGS -Werror " -fi - -AC_ARG_ENABLE(ssl-hmac, - [ --enable-ssl-hmac=[yes/no] enables use of ssl/hmac for stun], - [case "${enableval}" in - yes) ssl_hmac_enabled=yes;; - no) ssl_hmac_enabled=no;; - *) AC_MSG_ERROR("Bad value for --enable-ssl-hmac");; - esac], - [ssl_hmac_enabled=yes]) - -if test "$ssl_hmac_enabled" = "yes" ; then - AC_CHECK_HEADERS(openssl/hmac.h openssl/md5.h) - AC_CHECK_LIB(ssl,SSL_CTX_new,[SSL_LIBS="-lssl"]) - AC_CHECK_LIB(crypto,MD5,[SSL_LIBS="$SSL_LIBS -lcrypto"]) -fi - - - - - -AC_SUBST(SSL_LIBS) - -ORTPDEPS_LIBS="$ORTPDEPS_LIBS $PTHREAD_LIBS $PTHREAD_LDFLAGS $SRTP_LIBS $SSL_LIBS" -ORTPDEPS_CFLAGS="$ORTPDEPS_CFLAGS $PTHREAD_CFLAGS $ORTP_DEFS $SRTP_CFLAGS" -CFLAGS="$CFLAGS $ORTP_DEFS" -echo "$ORTPDEPS_CFLAGS" > ortp.defs - - -dnl ################################################## -dnl # Check for doxygen -dnl ################################################## - -AC_PATH_PROG(DOXYGEN,doxygen,false) -AM_CONDITIONAL(HAVE_DOXYGEN, test $DOXYGEN != false) - - -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) -AM_CONDITIONAL(BUILD_TESTS,test x$build_tests != xno) - -# 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="An LGPL implementation of RTP - RFC3550" -AC_SUBST(SUMMARY) -PACKAGER=anonymous -AC_SUBST(PACKAGER) -LICENSE=LGPL -AC_SUBST(LICENSE) -VENDOR=Linphone -AC_SUBST(VENDOR) -RELEASE=1 -AC_SUBST(RELEASE) - -AC_SUBST(ORTPDEPS_CFLAGS) -AC_SUBST(ORTPDEPS_LIBS) -AC_SUBST(ORTPDEPS_LDFLAGS) - -AC_OUTPUT( -Makefile -include/Makefile -include/ortp/Makefile -src/Makefile -src/tests/Makefile -src/tests/win_receiver/Makefile -src/tests/win_sender/Makefile -build/Makefile -build/win32native/Makefile -build/wince/Makefile -build/winmob/Makefile -ortp.pc -ortp.spec -ortp.doxygen -) - -AC_MSG_WARN([ortp-0.15.0 breaks compatibility with older releases, because value returned by rtp_session_recvm_with_ts() has - changed. See the API documentation in doc/ for further readings.]) diff --git a/linphone/oRTP/docs/.gitignore b/linphone/oRTP/docs/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/oRTP/docs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/oRTP/include/.gitignore b/linphone/oRTP/include/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/oRTP/include/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/oRTP/include/Makefile.am b/linphone/oRTP/include/Makefile.am deleted file mode 100644 index ca785d102..000000000 --- a/linphone/oRTP/include/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS=ortp diff --git a/linphone/oRTP/include/ortp/.gitignore b/linphone/oRTP/include/ortp/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/oRTP/include/ortp/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/oRTP/include/ortp/Makefile.am b/linphone/oRTP/include/ortp/Makefile.am deleted file mode 100644 index c8f0133f1..000000000 --- a/linphone/oRTP/include/ortp/Makefile.am +++ /dev/null @@ -1,11 +0,0 @@ - - -ortp_includedir=$(includedir)/ortp - -ortp_include_HEADERS=str_utils.h rtpsession.h rtp.h port.h \ - ortp.h telephonyevents.h sessionset.h payloadtype.h rtpsignaltable.h \ - rtcp.h \ - event.h stun.h stun_udp.h srtp.h \ - b64.h - -EXTRA_DIST=$(ortp_include_HEADERS) diff --git a/linphone/oRTP/include/ortp/b64.h b/linphone/oRTP/include/ortp/b64.h deleted file mode 100644 index f2ce4578a..000000000 --- a/linphone/oRTP/include/ortp/b64.h +++ /dev/null @@ -1,420 +0,0 @@ -/* ///////////////////////////////////////////////////////////////////////////// - * File: b64/b64.h - * - * Purpose: Header file for the b64 library - * - * Created: 18th October 2004 - * Updated: 24th August 2008 - * - * Thanks: To Adam McLaurin, for ideas regarding the b64_decode2() and - * b64_encode2(). - * - * Home: http://synesis.com.au/software/ - * - * Copyright (c) 2004-2008, Matthew Wilson and Synesis Software - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of - * any contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. - * - * ////////////////////////////////////////////////////////////////////////// */ - - -/** \file b64/b64.h - * - * \brief [C/C++] Header file for the b64 library. - */ - -#ifndef B64_INCL_B64_H_B64 -#define B64_INCL_B64_H_B64 - -/* ///////////////////////////////////////////////////////////////////////////// - * Version information - */ - -#ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_B64_H_B64_MAJOR 1 -# define B64_VER_B64_H_B64_MINOR 5 -# define B64_VER_B64_H_B64_REVISION 4 -# define B64_VER_B64_H_B64_EDIT 28 -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -/** \def B64_VER_MAJOR - * The major version number of b64 - */ - -/** \def B64_VER_MINOR - * The minor version number of b64 - */ - -/** \def B64_VER_REVISION - * The revision version number of b64 - */ - -/** \def B64_VER - * The current composite version number of b64 - */ - -#ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_1_0_1 0x01000100 -# define B64_VER_1_0_2 0x01000200 -# define B64_VER_1_0_3 0x01000300 -# define B64_VER_1_1_1 0x01010100 -# define B64_VER_1_1_2 0x01010200 -# define B64_VER_1_1_3 0x01010300 -# define B64_VER_1_2_1 0x01020100 -# define B64_VER_1_2_2 0x01020200 -# define B64_VER_1_2_3 0x01020300 -# define B64_VER_1_2_4 0x01020400 -# define B64_VER_1_2_5 0x01020500 -# define B64_VER_1_2_6 0x01020600 -# define B64_VER_1_2_7 0x01020700 -# define B64_VER_1_3_1 0x010301ff -# define B64_VER_1_3_2 0x010302ff -# define B64_VER_1_3_3 0x010303ff -# define B64_VER_1_3_4 0x010304ff - -# define B64_VER B64_VER_1_3_4 -#else /* ? B64_DOCUMENTATION_SKIP_SECTION */ -# define B64_VER 0x010304ff -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -#define B64_VER_MAJOR 1 -#define B64_VER_MINOR 3 -#define B64_VER_REVISION 4 - -/* ///////////////////////////////////////////////////////////////////////////// - * Includes - */ - -#include - -/* ///////////////////////////////////////////////////////////////////////////// - * Namespace - */ - -#if !defined(B64_NO_NAMESPACE) && \ - !defined(__cplusplus) -# define B64_NO_NAMESPACE -#endif /* !B64_NO_NAMESPACE && !__cplusplus */ - -#ifdef B64_NAMESPACE -# undef B64_NAMESPACE -#endif /* B64_NAMESPACE */ - -#ifdef B64_NAMESPACE_QUALIFIER -# undef B64_NAMESPACE_QUALIFIER -#endif /* B64_NAMESPACE_QUALIFIER */ - - -#ifndef B64_NO_NAMESPACE - -# ifdef B64_CUSTOM_NAMESPACE -# define B64_NAMESPACE B64_CUSTOM_NAMESPACE -# else /* ? B64_CUSTOM_NAMESPACE */ -# define B64_NAMESPACE b64 -# endif /* B64_CUSTOM_NAMESPACE */ - -# if defined(B64_CUSTOM_NAMESPACE) && \ - defined(B64_CUSTOM_NAMESPACE_QUALIFIER) -# define B64_NAMESPACE_QUALIFIER B64_CUSTOM_NAMESPACE_QUALIFIER -# else /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ -# define B64_NAMESPACE_QUALIFIER ::B64_NAMESPACE -# endif /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ - - -/** \brief [C/C++] The b64 namespace, within which the core library types and functions - * reside in C++ compilation. In C compilation, they all reside in the global - * namespace. - * - * \htmlonly - *


- * \endhtmlonly - */ -namespace B64_NAMESPACE -{ -#endif /* !B64_NO_NAMESPACE */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Enumerations - */ - -/** \brief Return codes (from b64_encode2() / b64_decode2()) - */ -enum B64_RC -{ - B64_RC_OK = 0 /*!< Operation was successful. */ - , B64_RC_INSUFFICIENT_BUFFER = 1 /*!< The given translation buffer was not of sufficient size. */ - , B64_RC_TRUNCATED_INPUT = 2 /*!< The input did not represent a fully formed stream of octet couplings. */ - , B64_RC_DATA_ERROR = 3 /*!< Invalid data. */ -#ifndef B64_DOCUMENTATION_SKIP_SECTION - , B64_max_RC_value -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ -}; - -#ifndef __cplusplus -typedef enum B64_RC B64_RC; -#endif /* !__cplusplus */ - -/** \brief Coding behaviour modification flags (for b64_encode2() / b64_decode2()) - */ -enum B64_FLAGS -{ - B64_F_LINE_LEN_USE_PARAM = 0x0000 /*!< Uses the lineLen parameter to b64_encode2(). Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_INFINITE = 0x0001 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is infinite. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_64 = 0x0002 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 64. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_76 = 0x0003 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 76. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_MASK = 0x000f /*!< Mask for testing line length flags to b64_encode2(). Ignored by b64_encode2(). */ - , B64_F_STOP_ON_NOTHING = 0x0000 /*!< Decoding ignores all invalid characters in the input data. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_UNKNOWN_CHAR = 0x0100 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/], non-whitespace character is encountered. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_UNEXPECTED_WS = 0x0200 /*!< Causes decoding to break if any unexpected whitespace is encountered. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_BAD_CHAR = 0x0300 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/] character is encountered. Ignored by b64_encode2(). */ -}; - -#ifndef __cplusplus -typedef enum B64_FLAGS B64_FLAGS; -#endif /* !__cplusplus */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Functions - */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** \brief Encodes a block of binary data into Base-64 - * - * \param src Pointer to the block to be encoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. - * \param srcSize Length of block to be encoded - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destLen Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \link b64::b64_encode b64_encode(NULL, srcSize, NULL, 0)\endlink. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destLen - * - * \note The function returns the required length if \c dest is NULL - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note Threading: The function is fully re-entrant. - * - * \see b64::encode() - */ -size_t b64_encode(void const *src, size_t srcSize, char *dest, size_t destLen); - -/** \brief Encodes a block of binary data into Base-64 - * - * \param src Pointer to the block to be encoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. - * \param srcSize Length of block to be encoded - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destLen Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \link b64::b64_encode2 b64_encode2(NULL, srcSize, NULL, 0, flags, lineLen, rc)\endlink. - * \param flags A combination of the B64_FLAGS enumeration, that moderate the - * behaviour of the function - * \param lineLen If the flags parameter contains B64_F_LINE_LEN_USE_PARAM, then - * this parameter represents the length of the lines into which the encoded form is split, - * with a hard line break ('\\r\\n'). If this value is 0, then the line is not - * split. If it is <0, then the RFC-1113 recommended line length of 64 is used - * \param rc The return code representing the status of the operation. May be NULL. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destLen - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note Threading: The function is fully re-entrant. - * - * \see b64::encode() - */ -size_t b64_encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = 0 */ - , B64_RC *rc /* = NULL */); - -/** \brief Decodes a sequence of Base-64 into a block of binary data - * - * \param src Pointer to the Base-64 block to be decoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. If \c dest is NULL, and \c src is - * not NULL, then the returned value is calculated exactly, otherwise a value - * is returned that is guaranteed to be large enough to hold the decoded block. - * - * \param srcLen Length of block to be encoded. Must be an integral of 4, the Base-64 - * encoding quantum, otherwise the Base-64 block is assumed to be invalid - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destSize Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c b64_decode(src, srcSize, NULL, 0), even in the case where the encoded form - * contains a number of characters that will be ignored, resulting in a lower total - * length of converted form. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destSize - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note \anchor anchor__4_characters The behaviour of both - * \link b64::b64_encode2 b64_encode2()\endlink - * and - * \link b64::b64_decode2 b64_decode2()\endlink - * are undefined if the line length is not a multiple of 4. - * - * \note Threading: The function is fully re-entrant. - * - * \see b64::decode() - */ -size_t b64_decode(char const *src, size_t srcLen, void *dest, size_t destSize); - -/** \brief Decodes a sequence of Base-64 into a block of binary data - * - * \param src Pointer to the Base-64 block to be decoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. If \c dest is NULL, and \c src is - * not NULL, then the returned value is calculated exactly, otherwise a value - * is returned that is guaranteed to be large enough to hold the decoded block. - * - * \param srcLen Length of block to be encoded. Must be an integral of 4, the Base-64 - * encoding quantum, otherwise the Base-64 block is assumed to be invalid - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destSize Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c b64_decode(src, srcSize, NULL, 0), even in the case where the encoded form - * contains a number of characters that will be ignored, resulting in a lower total - * length of converted form. - * \param flags A combination of the B64_FLAGS enumeration, that moderate the - * behaviour of the function. - * \param rc The return code representing the status of the operation. May be NULL. - * \param badChar If the flags parameter does not contain B64_F_STOP_ON_NOTHING, this - * parameter specifies the address of a pointer that will be set to point to any - * character in the sequence that stops the parsing, as dictated by the flags - * parameter. May be NULL. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destSize, or a bad character stopped parsing. - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note The behaviour of both - * \link b64::b64_encode2 b64_encode2()\endlink - * and - * \link b64::b64_decode2 b64_decode2()\endlink - * are undefined if the line length is not a multiple of 4. - * - * \note Threading: The function is fully re-entrant. - * - * \see b64::decode() - */ -size_t b64_decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , B64_RC *rc /* = NULL */); - - -/** \brief Returns the textual description of the error - * - * \param code The \link b64::B64_RC error code\endlink - */ -char const *b64_getErrorString(B64_RC code); - -/** \brief Returns the length of the textual description of the error - * - * \see b64_getErrorString() - * - * \param code The \link b64::B64_RC error code\endlink - */ -size_t b64_getErrorStringLength(B64_RC code); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* __cplusplus */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Namespace - */ - -#ifndef B64_NO_NAMESPACE -} /* namespace B64_NAMESPACE */ - -# ifndef B64_DOCUMENTATION_SKIP_SECTION - -namespace stlsoft -{ - - inline char const *c_str_data_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - inline char const *c_str_data( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - - inline size_t c_str_len_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); - } - inline size_t c_str_len( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); - } - - inline char const *c_str_ptr_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - inline char const *c_str_ptr( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - -} /* namespace stlsoft */ - -# endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -#endif /* !B64_NO_NAMESPACE */ - -/* ////////////////////////////////////////////////////////////////////////// */ - -#endif /* B64_INCL_B64_H_B64 */ - -/* ////////////////////////////////////////////////////////////////////////// */ diff --git a/linphone/oRTP/include/ortp/event.h b/linphone/oRTP/include/ortp/event.h deleted file mode 100644 index 071d417d6..000000000 --- a/linphone/oRTP/include/ortp/event.h +++ /dev/null @@ -1,85 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef ortp_events_h -#define ortp_events_h - -#include - -typedef mblk_t OrtpEvent; - -typedef unsigned long OrtpEventType; - -typedef struct RtpEndpoint{ -#ifdef ORTP_INET6 - struct sockaddr_storage addr; -#else - struct sockaddr addr; -#endif - socklen_t addrlen; -}RtpEndpoint; - - -struct _OrtpEventData{ - mblk_t *packet; /* most events are associated to a received packet */ - RtpEndpoint *ep; - union { - int telephone_event; - int payload_type; - } info; -}; - -typedef struct _OrtpEventData OrtpEventData; - - - -#ifdef __cplusplus -extern "C"{ -#endif - -RtpEndpoint *rtp_endpoint_new(struct sockaddr *addr, socklen_t addrlen); -RtpEndpoint *rtp_endpoint_dup(const RtpEndpoint *ep); - -OrtpEvent * ortp_event_new(OrtpEventType tp); -OrtpEventType ortp_event_get_type(const OrtpEvent *ev); -/* type is one of the following*/ -#define ORTP_EVENT_STUN_PACKET_RECEIVED 1 -#define ORTP_EVENT_PAYLOAD_TYPE_CHANGED 2 -#define ORTP_EVENT_TELEPHONE_EVENT 3 -#define ORTP_EVENT_RTCP_PACKET_RECEIVED 4 -OrtpEventData * ortp_event_get_data(OrtpEvent *ev); -void ortp_event_destroy(OrtpEvent *ev); -OrtpEvent *ortp_event_dup(OrtpEvent *ev); - -typedef struct OrtpEvQueue{ - queue_t q; - ortp_mutex_t mutex; -} OrtpEvQueue; - -OrtpEvQueue * ortp_ev_queue_new(void); -void ortp_ev_queue_destroy(OrtpEvQueue *q); -OrtpEvent * ortp_ev_queue_get(OrtpEvQueue *q); -void ortp_ev_queue_flush(OrtpEvQueue * qp); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/linphone/oRTP/include/ortp/ortp.h b/linphone/oRTP/include/ortp/ortp.h deleted file mode 100644 index 8176af523..000000000 --- a/linphone/oRTP/include/ortp/ortp.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/** \mainpage oRTP API documentation - * - * \section init Initializing oRTP - * - * see ortp.h documentation. - * - * \section rtpsession the RtpSession object - * - * see the rtpsession.h documentation. - * - * \section payloadtypes Managing PayloadType(s) and RtpProfile(s) - * - * see the payloadtype.h documentation. - * - * \section telephonevents Sending and receiving telephone-event (RFC2833) - * - * see the telephonyevents.h documentation. - * To get informed about incoming telephone-event you can register a callback - * using rtp_session_signal_connect() or by registering an event queue using - * rtp_session_register_event_queue(). - * - * \section sessionset Managing several RtpSession simultaneously - * - * see the sessionset.h documentation. - * - * \section rtcp Parsing incoming rtcp packets. - * - * The parsing api is defined in rtcp.h (not yet documented). - * - * \section examples Examples - * - * oRTP comes with a set of examples in src/tests. - * - rtprecv.c rtpsend.c show how to receive and send a single RTP stream. - * - mrtprecv.c mrtpsend.c show how to receive and send multiple RTP streams - * simultaneously - * - */ - -/** - * \file ortp.h - * \brief General purpose library functions. - * -**/ - -#ifndef ORTP_H -#define ORTP_H - -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -bool_t ortp_min_version_required(int major, int minor, int micro); -void ortp_init(void); -void ortp_scheduler_init(void); -void ortp_exit(void); - -/***************/ -/* logging api */ -/***************/ - -typedef enum { - ORTP_DEBUG=1, - ORTP_MESSAGE=1<<1, - ORTP_WARNING=1<<2, - ORTP_ERROR=1<<3, - ORTP_FATAL=1<<4, - ORTP_LOGLEV_END=1<<5 -} OrtpLogLevel; - - -typedef void (*OrtpLogFunc)(OrtpLogLevel lev, const char *fmt, va_list args); - -void ortp_set_log_file(FILE *file); -void ortp_set_log_handler(OrtpLogFunc func); - -VAR_DECLSPEC OrtpLogFunc ortp_logv_out; - -extern unsigned int __ortp_log_mask; - -#define ortp_log_level_enabled(level) (__ortp_log_mask & (level)) - -#if !defined(WIN32) && !defined(_WIN32_WCE) -#define ortp_logv(level,fmt,args) \ -{\ - if (ortp_logv_out!=NULL && ortp_log_level_enabled(level)) \ - ortp_logv_out(level,fmt,args);\ - if ((level)==ORTP_FATAL) abort();\ -}while(0) -#else -void ortp_logv(int level, const char *fmt, va_list args); -#endif - -void ortp_set_log_level_mask(int levelmask); - -#ifdef ORTP_DEBUG_MODE -static inline void ortp_debug(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_DEBUG, fmt, args); - va_end (args); -} -#else - -#define ortp_debug(...) - -#endif - -#ifdef ORTP_NOMESSAGE_MODE - -#define ortp_log(...) -#define ortp_message(...) -#define ortp_warning(...) - -#else - -static inline void ortp_log(OrtpLogLevel lev, const char *fmt,...){ - va_list args; - va_start (args, fmt); - ortp_logv(lev, fmt, args); - va_end (args); -} - -static inline void ortp_message(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_MESSAGE, fmt, args); - va_end (args); -} - -static inline void ortp_warning(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_WARNING, fmt, args); - va_end (args); -} - -#endif - -static inline void ortp_error(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_ERROR, fmt, args); - va_end (args); -} - -static inline void ortp_fatal(const char *fmt,...) -{ - va_list args; - va_start (args, fmt); - ortp_logv(ORTP_FATAL, fmt, args); - va_end (args); -} - - -/****************/ -/*statistics api*/ -/****************/ - -extern rtp_stats_t ortp_global_stats; - -void ortp_global_stats_reset(void); -rtp_stats_t *ortp_get_global_stats(void); - -void ortp_global_stats_display(void); -void rtp_stats_display(const rtp_stats_t *stats, const char *header); -void rtp_stats_reset(rtp_stats_t *stats); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/payloadtype.h b/linphone/oRTP/include/ortp/payloadtype.h deleted file mode 100644 index 0d9849956..000000000 --- a/linphone/oRTP/include/ortp/payloadtype.h +++ /dev/null @@ -1,212 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/** - * \file payloadtype.h - * \brief Using and creating standart and custom RTP profiles - * -**/ - -#ifndef PAYLOADTYPE_H -#define PAYLOADTYPE_H -#include - -#ifdef __cplusplus -extern "C"{ -#endif - -/* flags for PayloadType::flags */ - -#define PAYLOAD_TYPE_ALLOCATED (1) - /* private flags for future use by ortp */ -#define PAYLOAD_TYPE_PRIV1 (1<<1) -#define PAYLOAD_TYPE_PRIV2 (1<<2) -#define PAYLOAD_TYPE_PRIV3 (1<<3) - /* user flags, can be used by the application on top of oRTP */ -#define PAYLOAD_TYPE_USER_FLAG_0 (1<<4) -#define PAYLOAD_TYPE_USER_FLAG_1 (1<<5) -#define PAYLOAD_TYPE_USER_FLAG_2 (1<<6) - /* ask for more if you need*/ - -#define PAYLOAD_AUDIO_CONTINUOUS 0 -#define PAYLOAD_AUDIO_PACKETIZED 1 -#define PAYLOAD_VIDEO 2 -#define PAYLOAD_OTHER 3 /* ?? */ - -struct _PayloadType -{ - int type; /**< one of PAYLOAD_* macros*/ - int clock_rate; /**< rtp clock rate*/ - char bits_per_sample; /* in case of continuous audio data */ - char *zero_pattern; - int pattern_length; - /* other useful information for the application*/ - int normal_bitrate; /*in bit/s */ - char *mime_type; /**flags|=((int)flag) -#define payload_type_unset_flag(pt,flag) (pt)->flags&=(~(int)flag) -#define payload_type_get_flags(pt) (pt)->flags - -#define RTP_PROFILE_MAX_PAYLOADS 128 - -/** - * The RTP profile is a table RTP_PROFILE_MAX_PAYLOADS entries to make the matching - * between RTP payload type number and the PayloadType that defines the type of - * media. -**/ -struct _RtpProfile -{ - char *name; - PayloadType *payload[RTP_PROFILE_MAX_PAYLOADS]; -}; - - -typedef struct _RtpProfile RtpProfile; - -PayloadType *payload_type_new(void); -PayloadType *payload_type_clone(PayloadType *payload); -char *payload_type_get_rtpmap(PayloadType *pt); -void payload_type_destroy(PayloadType *pt); -void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp); -void payload_type_set_send_fmtp(PayloadType *pt, const char *fmtp); -void payload_type_append_recv_fmtp(PayloadType *pt, const char *fmtp); -void payload_type_append_send_fmtp(PayloadType *pt, const char *fmtp); - - -bool_t fmtp_get_value(const char *fmtp, const char *param_name, char *result, size_t result_len); - -VAR_DECLSPEC RtpProfile av_profile; - -#define payload_type_set_user_data(pt,p) (pt)->user_data=(p) -#define payload_type_get_user_data(pt) ((pt)->user_data) - -#define rtp_profile_get_name(profile) (const char*)((profile)->name) - -void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType *pt); - -/** - * Set payload type number @index unassigned in the profile. - * - *@param profile an RTP profile - *@param index the payload type number -**/ -#define rtp_profile_clear_payload(profile,index) \ - rtp_profile_set_payload(profile,index,NULL) - -/* I prefer have this function inlined because it is very often called in the code */ -/** - * - * Gets the payload description of the payload type @index in the profile. - * - *@param profile an RTP profile (a #RtpProfile object) - *@param index the payload type number - *@return the payload description (a PayloadType object) -**/ -static inline PayloadType * rtp_profile_get_payload(RtpProfile *prof, int idx){ - if (idx<0 || idx>=RTP_PROFILE_MAX_PAYLOADS) { - return NULL; - } - return prof->payload[idx]; -} -void rtp_profile_clear_all(RtpProfile *prof); -void rtp_profile_set_name(RtpProfile *prof, const char *name); -PayloadType * rtp_profile_get_payload_from_mime(RtpProfile *profile,const char *mime); -PayloadType * rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap); -int rtp_profile_get_payload_number_from_mime(RtpProfile *profile,const char *mime); -int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile, const char *rtpmap); -int rtp_profile_find_payload_number(RtpProfile *prof,const char *mime,int rate, int channels); -PayloadType * rtp_profile_find_payload(RtpProfile *prof,const char *mime,int rate, int channels); -int rtp_profile_move_payload(RtpProfile *prof,int oldpos,int newpos); - -RtpProfile * rtp_profile_new(const char *name); -/* clone a profile, payload are not cloned */ -RtpProfile * rtp_profile_clone(RtpProfile *prof); - - -/*clone a profile and its payloads (ie payload type are newly allocated, not reusing payload types of the reference profile) */ -RtpProfile * rtp_profile_clone_full(RtpProfile *prof); -/* frees the profile and all its PayloadTypes*/ -void rtp_profile_destroy(RtpProfile *prof); - - -/* some payload types */ -/* audio */ -VAR_DECLSPEC PayloadType payload_type_pcmu8000; -VAR_DECLSPEC PayloadType payload_type_pcma8000; -VAR_DECLSPEC PayloadType payload_type_pcm8000; -VAR_DECLSPEC PayloadType payload_type_l16_mono; -VAR_DECLSPEC PayloadType payload_type_l16_stereo; -VAR_DECLSPEC PayloadType payload_type_lpc1016; -VAR_DECLSPEC PayloadType payload_type_g729; -VAR_DECLSPEC PayloadType payload_type_g7231; -VAR_DECLSPEC PayloadType payload_type_g7221; -VAR_DECLSPEC PayloadType payload_type_g726_40; -VAR_DECLSPEC PayloadType payload_type_g726_32; -VAR_DECLSPEC PayloadType payload_type_g726_24; -VAR_DECLSPEC PayloadType payload_type_g726_16; -VAR_DECLSPEC PayloadType payload_type_gsm; -VAR_DECLSPEC PayloadType payload_type_lpc; -VAR_DECLSPEC PayloadType payload_type_lpc1015; -VAR_DECLSPEC PayloadType payload_type_speex_nb; -VAR_DECLSPEC PayloadType payload_type_speex_wb; -VAR_DECLSPEC PayloadType payload_type_speex_uwb; -VAR_DECLSPEC PayloadType payload_type_ilbc; -VAR_DECLSPEC PayloadType payload_type_amr; -VAR_DECLSPEC PayloadType payload_type_amrwb; -VAR_DECLSPEC PayloadType payload_type_truespeech; -VAR_DECLSPEC PayloadType payload_type_evrc0; -VAR_DECLSPEC PayloadType payload_type_evrcb0; - -/* video */ -VAR_DECLSPEC PayloadType payload_type_mpv; -VAR_DECLSPEC PayloadType payload_type_h261; -VAR_DECLSPEC PayloadType payload_type_h263; -VAR_DECLSPEC PayloadType payload_type_h263_1998; -VAR_DECLSPEC PayloadType payload_type_h263_2000; -VAR_DECLSPEC PayloadType payload_type_mp4v; -VAR_DECLSPEC PayloadType payload_type_theora; -VAR_DECLSPEC PayloadType payload_type_h264; -VAR_DECLSPEC PayloadType payload_type_x_snow; -VAR_DECLSPEC PayloadType payload_type_jpeg; - -VAR_DECLSPEC PayloadType payload_type_t140; - -/* non standard file transfer over UDP */ -VAR_DECLSPEC PayloadType payload_type_x_udpftp; - -/* telephone-event */ -VAR_DECLSPEC PayloadType payload_type_telephone_event; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/port.h b/linphone/oRTP/include/ortp/port.h deleted file mode 100644 index b8a32bb40..000000000 --- a/linphone/oRTP/include/ortp/port.h +++ /dev/null @@ -1,320 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* this file is responsible of the portability of the stack */ - -#ifndef ORTP_PORT_H -#define ORTP_PORT_H - - -#if !defined(WIN32) && !defined(_WIN32_WCE) -/********************************/ -/* definitions for UNIX flavour */ -/********************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __linux -#include -#endif - - -#include -#include -#include -#if defined(_XOPEN_SOURCE_EXTENDED) || !defined(__hpux) -#include -#endif - - - -#include - -#ifdef ORTP_INET6 -#include -#endif - -typedef int ortp_socket_t; -typedef pthread_t ortp_thread_t; -typedef pthread_mutex_t ortp_mutex_t; -typedef pthread_cond_t ortp_cond_t; - -#ifdef __INTEL_COMPILER -#pragma warning(disable : 111) // statement is unreachable -#pragma warning(disable : 181) // argument is incompatible with corresponding format string conversion -#pragma warning(disable : 188) // enumerated type mixed with another type -#pragma warning(disable : 593) // variable "xxx" was set but never used -#pragma warning(disable : 810) // conversion from "int" to "unsigned short" may lose significant bits -#pragma warning(disable : 869) // parameter "xxx" was never referenced -#pragma warning(disable : 981) // operands are evaluated in unspecified order -#pragma warning(disable : 1418) // external function definition with no prior declaration -#pragma warning(disable : 1419) // external declaration in primary source file -#pragma warning(disable : 1469) // "cc" clobber ignored -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -int __ortp_thread_join(ortp_thread_t thread, void **ptr); -int __ortp_thread_create(pthread_t *thread, pthread_attr_t *attr, void * (*routine)(void*), void *arg); - -#ifdef __cplusplus -} -#endif - -#define ortp_thread_create __ortp_thread_create -#define ortp_thread_join __ortp_thread_join -#define ortp_thread_exit pthread_exit -#define ortp_mutex_init pthread_mutex_init -#define ortp_mutex_lock pthread_mutex_lock -#define ortp_mutex_unlock pthread_mutex_unlock -#define ortp_mutex_destroy pthread_mutex_destroy -#define ortp_cond_init pthread_cond_init -#define ortp_cond_signal pthread_cond_signal -#define ortp_cond_broadcast pthread_cond_broadcast -#define ortp_cond_wait pthread_cond_wait -#define ortp_cond_destroy pthread_cond_destroy - -#define SOCKET_OPTION_VALUE void * -#define SOCKET_BUFFER void * - -#define getSocketError() strerror(errno) -#define getSocketErrorCode() (errno) - -#define ortp_log10f(x) log10f(x) - - -#else -/*********************************/ -/* definitions for WIN32 flavour */ -/*********************************/ - -#include -#include -#include -#include -#include - - -#ifdef _MSC_VER -#pragma push_macro("_WINSOCKAPI_") -#ifndef _WINSOCKAPI_ -#define _WINSOCKAPI_ -#endif - -typedef unsigned __int64 uint64_t; -typedef __int64 int64_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef int int32_t; -typedef unsigned char uint8_t; -typedef __int16 int16_t; -#else -#include /*provided by mingw32*/ -#endif - -#define vsnprintf _vsnprintf -#define srandom srand -#define random rand - - -typedef SOCKET ortp_socket_t; -typedef HANDLE ortp_cond_t; -typedef HANDLE ortp_mutex_t; -typedef HANDLE ortp_thread_t; - -#define ortp_thread_create WIN_thread_create -#define ortp_thread_join WIN_thread_join -#define ortp_thread_exit(arg) -#define ortp_mutex_init WIN_mutex_init -#define ortp_mutex_lock WIN_mutex_lock -#define ortp_mutex_unlock WIN_mutex_unlock -#define ortp_mutex_destroy WIN_mutex_destroy -#define ortp_cond_init WIN_cond_init -#define ortp_cond_signal WIN_cond_signal -#define ortp_cond_broadcast WIN_cond_broadcast -#define ortp_cond_wait WIN_cond_wait -#define ortp_cond_destroy WIN_cond_destroy - - -#ifdef __cplusplus -extern "C" -{ -#endif - -int WIN_mutex_init(ortp_mutex_t *m, void *attr_unused); -int WIN_mutex_lock(ortp_mutex_t *mutex); -int WIN_mutex_unlock(ortp_mutex_t *mutex); -int WIN_mutex_destroy(ortp_mutex_t *mutex); -int WIN_thread_create(ortp_thread_t *t, void *attr_unused, void *(*func)(void*), void *arg); -int WIN_thread_join(ortp_thread_t thread, void **unused); -int WIN_cond_init(ortp_cond_t *cond, void *attr_unused); -int WIN_cond_wait(ortp_cond_t * cond, ortp_mutex_t * mutex); -int WIN_cond_signal(ortp_cond_t * cond); -int WIN_cond_broadcast(ortp_cond_t * cond); -int WIN_cond_destroy(ortp_cond_t * cond); - -#ifdef __cplusplus -} -#endif - -#define SOCKET_OPTION_VALUE char * -#define inline __inline - -#if defined(_WIN32_WCE) - -#define ortp_log10f(x) (float)log10 ((double)x) - -#ifdef assert - #undef assert -#endif /*assert*/ -#define assert(exp) ((void)0) - -#ifdef errno - #undef errno -#endif /*errno*/ -#define errno GetLastError() -#ifdef strerror - #undef strerror -#endif /*strerror*/ -const char * ortp_strerror(DWORD value); -#define strerror ortp_strerror - - -#else /*_WIN32_WCE*/ - -#define ortp_log10f(x) log10f(x) - -#endif - -const char *getWinSocketError(int error); -#define getSocketErrorCode() WSAGetLastError() -#define getSocketError() getWinSocketError(WSAGetLastError()) - -#define snprintf _snprintf -#define strcasecmp _stricmp - -#if 0 -struct timeval { - long tv_sec; /* seconds */ - long tv_usec; /* and microseconds */ -}; -#endif - -int gettimeofday (struct timeval *tv, void* tz); -#ifdef _WORKAROUND_MINGW32_BUGS -char * WSAAPI gai_strerror(int errnum); -#endif - - -#endif - -typedef unsigned char bool_t; -#undef TRUE -#undef FALSE -#define TRUE 1 -#define FALSE 0 - -#ifdef __cplusplus -extern "C"{ -#endif - -void* ortp_malloc(size_t sz); -void ortp_free(void *ptr); -void* ortp_realloc(void *ptr, size_t sz); -void* ortp_malloc0(size_t sz); -char * ortp_strdup(const char *tmp); - -/*override the allocator with this method, to be called BEFORE ortp_init()*/ -typedef struct _OrtpMemoryFunctions{ - void *(*malloc_fun)(size_t sz); - void *(*realloc_fun)(void *ptr, size_t sz); - void (*free_fun)(void *ptr); -}OrtpMemoryFunctions; - -void ortp_set_memory_functions(OrtpMemoryFunctions *functions); - -#define ortp_new(type,count) ortp_malloc(sizeof(type)*(count)) -#define ortp_new0(type,count) ortp_malloc0(sizeof(type)*(count)) - -int close_socket(ortp_socket_t sock); -int set_non_blocking_socket(ortp_socket_t sock); - -char *ortp_strndup(const char *str,int n); -char *ortp_strdup_printf(const char *fmt,...); -char *ortp_strdup_vprintf(const char *fmt, va_list ap); - -int ortp_file_exist(const char *pathname); - -/* portable named pipes */ -#if !defined(_WIN32_WCE) -#ifdef WIN32 -typedef HANDLE ortp_pipe_t; -#define ORTP_PIPE_INVALID INVALID_HANDLE_VALUE -#else -typedef int ortp_pipe_t; -#define ORTP_PIPE_INVALID (-1) -#endif - -ortp_pipe_t ortp_server_pipe_create(const char *name); -/* - * warning: on win32 ortp_server_pipe_accept_client() might return INVALID_HANDLE_VALUE without - * any specific error, this happens when ortp_server_pipe_close() is called on another pipe. - * This pipe api is not thread-safe. -*/ -ortp_pipe_t ortp_server_pipe_accept_client(ortp_pipe_t server); -int ortp_server_pipe_close(ortp_pipe_t spipe); -int ortp_server_pipe_close_client(ortp_pipe_t client); - -ortp_pipe_t ortp_client_pipe_connect(const char *name); -int ortp_client_pipe_close(ortp_pipe_t sock); - -int ortp_pipe_read(ortp_pipe_t p, uint8_t *buf, int len); -int ortp_pipe_write(ortp_pipe_t p, const uint8_t *buf, int len); -#endif - -#ifdef __cplusplus -} - -#endif - - -#if (defined(WIN32) || defined(_WIN32_WCE)) && !defined(ORTP_STATIC) -#ifdef ORTP_EXPORTS - #define VAR_DECLSPEC __declspec(dllexport) -#else - #define VAR_DECLSPEC __declspec(dllimport) -#endif -#else - #define VAR_DECLSPEC extern -#endif - - -#endif - - diff --git a/linphone/oRTP/include/ortp/rtcp.h b/linphone/oRTP/include/ortp/rtcp.h deleted file mode 100644 index 950179764..000000000 --- a/linphone/oRTP/include/ortp/rtcp.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#ifndef RTCP_H -#define RTCP_H - -#include - -#define RTCP_MAX_RECV_BUFSIZE 1024 - -#define RTCP_SENDER_INFO_SIZE 20 -#define RTCP_REPORT_BLOCK_SIZE 24 -#define RTCP_COMMON_HEADER_SIZE 4 -#define RTCP_SSRC_FIELD_SIZE 4 - -#ifdef __cplusplus -extern "C"{ -#endif - -/* RTCP common header */ - -typedef enum { - RTCP_SR = 200, - RTCP_RR = 201, - RTCP_SDES = 202, - RTCP_BYE = 203, - RTCP_APP = 204 -} rtcp_type_t; - - -typedef struct rtcp_common_header -{ -#ifdef ORTP_BIGENDIAN - uint16_t version:2; - uint16_t padbit:1; - uint16_t rc:5; - uint16_t packet_type:8; -#else - uint16_t rc:5; - uint16_t padbit:1; - uint16_t version:2; - uint16_t packet_type:8; -#endif - uint16_t length:16; -} rtcp_common_header_t; - -#define rtcp_common_header_set_version(ch,v) (ch)->version=v -#define rtcp_common_header_set_padbit(ch,p) (ch)->padbit=p -#define rtcp_common_header_set_rc(ch,rc) (ch)->rc=rc -#define rtcp_common_header_set_packet_type(ch,pt) (ch)->packet_type=pt -#define rtcp_common_header_set_length(ch,l) (ch)->length=htons(l) - -#define rtcp_common_header_get_version(ch) ((ch)->version) -#define rtcp_common_header_get padbit(ch) ((ch)->padbit) -#define rtcp_common_header_get_rc(ch) ((ch)->rc) -#define rtcp_common_header_get_packet_type(ch) ((ch)->packet_type) -#define rtcp_common_header_get_length(ch) ntohs((ch)->length) - - -/* SR or RR packets */ - -typedef struct sender_info -{ - uint32_t ntp_timestamp_msw; - uint32_t ntp_timestamp_lsw; - uint32_t rtp_timestamp; - uint32_t senders_packet_count; - uint32_t senders_octet_count; -} sender_info_t; - -uint64_t sender_info_get_ntp_timestamp(const sender_info_t *si); -#define sender_info_get_rtp_timestamp(si) ((si)->rtp_timestamp) -#define sender_info_get_packet_count(si) \ - ntohl((si)->senders_packet_count) -#define sender_info_get_octet_count(si) \ - ntohl((si)->senders_octet_count) - - -typedef struct report_block -{ - uint32_t ssrc; - uint32_t fl_cnpl;/*fraction lost + cumulative number of packet lost*/ - uint32_t ext_high_seq_num_rec; /*extended highest sequence number received */ - uint32_t interarrival_jitter; - uint32_t lsr; /*last SR */ - uint32_t delay_snc_last_sr; /*delay since last sr*/ -} report_block_t; - -#define report_block_get_ssrc(rb) \ - ntohl((rb)->ssrc) -#define report_block_get_fraction_lost(rb) \ - (((uint32_t)ntohl((rb)->fl_cnpl))>>24) -#define report_block_get_cum_packet_loss(rb) \ - (((uint32_t)ntohl((rb)->fl_cnpl)) & 0xFFFFFF) -#define report_block_get_high_ext_seq(rb) \ - ntohl(((report_block_t*)(rb))->ext_high_seq_num_rec) -#define report_block_get_interarrival_jitter(rb) \ - ntohl(((report_block_t*)(rb))->interarrival_jitter) -#define report_block_get_last_SR_time(rb) \ - ntohl(((report_block_t*)(rb))->lsr) -#define report_block_get_last_SR_delay(rb) \ - ntohl(((report_block_t*)(rb))->delay_snc_last_sr) - -#define report_block_set_fraction_lost(rb,fl)\ - ((rb)->fl_cnpl)=htonl( (ntohl((rb)->fl_cnpl) & 0xFFFFFF) | (((fl) & 0xFF)<<24)) - -#define report_block_set_cum_packet_lost(rb,cpl)\ - ((rb)->fl_cnpl)=htonl( (ntohl((rb)->fl_cnpl) & 0xFF000000) | (((cpl) & 0xFFFFFF))) - -/* SDES packets */ - -typedef enum { - RTCP_SDES_END = 0, - RTCP_SDES_CNAME = 1, - RTCP_SDES_NAME = 2, - RTCP_SDES_EMAIL = 3, - RTCP_SDES_PHONE = 4, - RTCP_SDES_LOC = 5, - RTCP_SDES_TOOL = 6, - RTCP_SDES_NOTE = 7, - RTCP_SDES_PRIV = 8, - RTCP_SDES_MAX = 9 -} rtcp_sdes_type_t; - -typedef struct sdes_chunk -{ - uint32_t csrc; -} sdes_chunk_t; - - -#define sdes_chunk_get_csrc(c) ntohl((c)->csrc) - -typedef struct sdes_item -{ - uint8_t item_type; - uint8_t len; - char content[1]; -} sdes_item_t; - -#define RTCP_SDES_MAX_STRING_SIZE 255 -#define RTCP_SDES_ITEM_HEADER_SIZE 2 -#define RTCP_SDES_CHUNK_DEFAULT_SIZE 1024 -#define RTCP_SDES_CHUNK_HEADER_SIZE (sizeof(sdes_chunk_t)) - -/* RTCP bye packet */ - -typedef struct rtcp_bye_reason -{ - uint8_t len; - char content[1]; -} rtcp_bye_reason_t; - -typedef struct rtcp_bye -{ - rtcp_common_header_t ch; - uint32_t ssrc[1]; /* the bye may contain several ssrc/csrc */ -} rtcp_bye_t; -#define RTCP_BYE_HEADER_SIZE sizeof(rtcp_bye_t) -#define RTCP_BYE_REASON_MAX_STRING_SIZE 255 - - - -typedef struct rtcp_sr{ - rtcp_common_header_t ch; - uint32_t ssrc; - sender_info_t si; - report_block_t rb[1]; -} rtcp_sr_t; - -typedef struct rtcp_rr{ - rtcp_common_header_t ch; - uint32_t ssrc; - report_block_t rb[1]; -} rtcp_rr_t; - -typedef struct rtcp_app{ - rtcp_common_header_t ch; - uint32_t ssrc; - char name[4]; -} rtcp_app_t; - -struct _RtpSession; -void rtp_session_rtcp_process_send(struct _RtpSession *s); -void rtp_session_rtcp_process_recv(struct _RtpSession *s); - -#define RTCP_DEFAULT_REPORT_INTERVAL 5 - - -/* packet parsing api */ - -/*in case of coumpound packet, set read pointer of m to the beginning of the next RTCP -packet */ -bool_t rtcp_next_packet(mblk_t *m); -/* put the read pointer at the first RTCP packet of the compound packet (as before any previous calls ot rtcp_next_packet() */ -void rtcp_rewind(mblk_t *m); -/* get common header*/ -const rtcp_common_header_t * rtcp_get_common_header(const mblk_t *m); - -/*Sender Report accessors */ -/* check if this packet is a SR and if it is correct */ -bool_t rtcp_is_SR(const mblk_t *m); -uint32_t rtcp_SR_get_ssrc(const mblk_t *m); -const sender_info_t * rtcp_SR_get_sender_info(const mblk_t *m); -const report_block_t * rtcp_SR_get_report_block(const mblk_t *m, int idx); - -/*Receiver report accessors*/ -bool_t rtcp_is_RR(const mblk_t *m); -uint32_t rtcp_RR_get_ssrc(const mblk_t *m); -const report_block_t * rtcp_RR_get_report_block(const mblk_t *m,int idx); - -/*SDES accessors */ -bool_t rtcp_is_SDES(const mblk_t *m); -typedef void (*SdesItemFoundCallback)(void *user_data, uint32_t csrc, rtcp_sdes_type_t t, const char *content, uint8_t content_len); -void rtcp_sdes_parse(const mblk_t *m, SdesItemFoundCallback cb, void *user_data); - -/*BYE accessors */ -bool_t rtcp_is_BYE(const mblk_t *m); -bool_t rtcp_BYE_get_ssrc(const mblk_t *m, int idx, uint32_t *ssrc); -bool_t rtcp_BYE_get_reason(const mblk_t *m, const char **reason, int *reason_len); - -/*APP accessors */ -bool_t rtcp_is_APP(const mblk_t *m); -int rtcp_APP_get_subtype(const mblk_t *m); -uint32_t rtcp_APP_get_ssrc(const mblk_t *m); -/* name argument is supposed to be at least 4 characters (note: no '\0' written)*/ -void rtcp_APP_get_name(const mblk_t *m, char *name); -/* retrieve the data. when returning, data points directly into the mblk_t */ -void rtcp_APP_get_data(const mblk_t *m, uint8_t **data, int *len); - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/rtp.h b/linphone/oRTP/include/ortp/rtp.h deleted file mode 100644 index 5ecd95def..000000000 --- a/linphone/oRTP/include/ortp/rtp.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#ifndef RTP_H -#define RTP_H - -#include -#include - -#define IPMAXLEN 20 -#define UDP_MAX_SIZE 1500 -#define RTP_FIXED_HEADER_SIZE 12 -#define RTP_DEFAULT_JITTER_TIME 80 /*miliseconds*/ -#define RTP_DEFAULT_MULTICAST_TTL 5 /*hops*/ -#define RTP_DEFAULT_MULTICAST_LOOPBACK 0 /*false*/ -#define RTP_DEFAULT_DSCP 0x00 /*best effort*/ - - - -typedef struct rtp_header -{ -#ifdef ORTP_BIGENDIAN - uint16_t version:2; - uint16_t padbit:1; - uint16_t extbit:1; - uint16_t cc:4; - uint16_t markbit:1; - uint16_t paytype:7; -#else - uint16_t cc:4; - uint16_t extbit:1; - uint16_t padbit:1; - uint16_t version:2; - uint16_t paytype:7; - uint16_t markbit:1; -#endif - uint16_t seq_number; - uint32_t timestamp; - uint32_t ssrc; - uint32_t csrc[16]; -} rtp_header_t; - - - - -typedef struct rtp_stats -{ - uint64_t packet_sent; - uint64_t sent; /* bytes sent */ - uint64_t recv; /* bytes of payload received and delivered in time to the application */ - uint64_t hw_recv; /* bytes of payload received */ - uint64_t packet_recv; /* number of packets received */ - uint64_t unavaillable; /* packets not availlable when they were queried */ - uint64_t outoftime; /* number of packets that were received too late */ - uint64_t cum_packet_loss; /* cumulative number of packet lost */ - uint64_t bad; /* packets that did not appear to be RTP */ - uint64_t discarded; /* incoming packets discarded because the queue exceeds its max size */ -} rtp_stats_t; - -#define RTP_TIMESTAMP_IS_NEWER_THAN(ts1,ts2) \ - ((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2))< (uint32_t)(1<<31)) - -#define RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(ts1,ts2) \ - ( ((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2))< (uint32_t)(1<<31)) && (ts1)!=(ts2) ) - -#define TIME_IS_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_NEWER_THAN(t1,t2) - -#define TIME_IS_STRICTLY_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(t1,t2) - - -#ifdef __cplusplus -extern "C"{ -#endif - -/* packet api */ -/* the first argument is a mblk_t. The header is supposed to be not splitted */ -#define rtp_set_markbit(mp,value) ((rtp_header_t*)((mp)->b_rptr))->markbit=(value) -#define rtp_set_seqnumber(mp,seq) ((rtp_header_t*)((mp)->b_rptr))->seq_number=(seq) -#define rtp_set_timestamp(mp,ts) ((rtp_header_t*)((mp)->b_rptr))->timestamp=(ts) -#define rtp_set_ssrc(mp,_ssrc) ((rtp_header_t*)((mp)->b_rptr))->ssrc=(_ssrc) -void rtp_add_csrc(mblk_t *mp ,uint32_t csrc); -#define rtp_set_payload_type(mp,pt) ((rtp_header_t*)((mp)->b_rptr))->paytype=(pt) - -#define rtp_get_markbit(mp) (((rtp_header_t*)((mp)->b_rptr))->markbit) -#define rtp_get_timestamp(mp) (((rtp_header_t*)((mp)->b_rptr))->timestamp) -#define rtp_get_seqnumber(mp) (((rtp_header_t*)((mp)->b_rptr))->seq_number) -#define rtp_get_payload_type(mp) (((rtp_header_t*)((mp)->b_rptr))->paytype) -#define rtp_get_ssrc(mp) (((rtp_header_t*)((mp)->b_rptr))->ssrc) -#define rtp_get_cc(mp) (((rtp_header_t*)((mp)->b_rptr))->cc) -#define rtp_get_csrc(mp, idx) (((rtp_header_t*)((mp)->b_rptr))->csrc[idx]) - -int rtp_get_payload(mblk_t *packet, unsigned char **start); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/rtpsession.h b/linphone/oRTP/include/ortp/rtpsession.h deleted file mode 100644 index 5b127d9ca..000000000 --- a/linphone/oRTP/include/ortp/rtpsession.h +++ /dev/null @@ -1,380 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/** - * \file rtpsession.h - * \brief The RtpSession api - * - * The RtpSession objects represent a RTP session: once it is configured with - * local and remote network addresses and a payload type is given, it let you send - * and recv a media stream. -**/ - - -#ifndef RTPSESSION_H -#define RTPSESSION_H - - -#include -#include -#include -#include -#include -#include -#include -#include - - - -typedef enum { - RTP_SESSION_RECVONLY, - RTP_SESSION_SENDONLY, - RTP_SESSION_SENDRECV -} RtpSessionMode; - - -/*! Jitter buffer parameters -*/ -typedef struct _JBParameters{ - int min_size; /**< in milliseconds*/ - int nom_size; /**< idem */ - int max_size; /**< idem */ - bool_t adaptive; - bool_t pad[3]; - int max_packets; /**< max number of packets allowed to be queued in the jitter buffer */ -} JBParameters; - -typedef struct _JitterControl -{ - int count; - int jitt_comp; /* the user jitt_comp in miliseconds*/ - int jitt_comp_ts; /* the jitt_comp converted in rtp time (same unit as timestamp) */ - int adapt_jitt_comp_ts; - int64_t slide; - int64_t prev_slide; - float jitter; - int olddiff; - float inter_jitter; /* interarrival jitter as defined in the RFC */ - int corrective_step; - int corrective_slide; - bool_t adaptive; - bool_t enabled; -} JitterControl; - -typedef struct _WaitPoint -{ - ortp_mutex_t lock; - ortp_cond_t cond; - uint32_t time; - bool_t wakeup; -} WaitPoint; - -typedef struct _RtpTransport -{ - void *data; - ortp_socket_t (*t_getsocket)(struct _RtpTransport *t); - int (*t_sendto)(struct _RtpTransport *t, mblk_t *msg , int flags, const struct sockaddr *to, socklen_t tolen); - int (*t_recvfrom)(struct _RtpTransport *t, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen); - struct _RtpSession *session;//flags|=(flag) -#define rtp_session_unset_flag(session,flag) (session)->flags&=~(flag) -void rtp_session_uninit(RtpSession *session); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/rtpsignaltable.h b/linphone/oRTP/include/ortp/rtpsignaltable.h deleted file mode 100644 index fb74e8ddc..000000000 --- a/linphone/oRTP/include/ortp/rtpsignaltable.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef rtpsignaltable_h -#define rtpsignaltable_h - -#define RTP_CALLBACK_TABLE_MAX_ENTRIES 5 - -typedef void (*RtpCallback)(struct _RtpSession *, ...); - -struct _RtpSignalTable -{ - RtpCallback callback[RTP_CALLBACK_TABLE_MAX_ENTRIES]; - unsigned long user_data[RTP_CALLBACK_TABLE_MAX_ENTRIES]; - struct _RtpSession *session; - const char *signal_name; - int count; -}; - -typedef struct _RtpSignalTable RtpSignalTable; - -void rtp_signal_table_init(RtpSignalTable *table,struct _RtpSession *session, const char *signal_name); - -int rtp_signal_table_add(RtpSignalTable *table,RtpCallback cb, unsigned long user_data); - -void rtp_signal_table_emit(RtpSignalTable *table); - -/* emit but with a second arg */ -void rtp_signal_table_emit2(RtpSignalTable *table, unsigned long arg); - -/* emit but with a third arg */ -void rtp_signal_table_emit3(RtpSignalTable *table, unsigned long arg1, unsigned long arg2); - -int rtp_signal_table_remove_by_callback(RtpSignalTable *table,RtpCallback cb); - -#endif - diff --git a/linphone/oRTP/include/ortp/sessionset.h b/linphone/oRTP/include/ortp/sessionset.h deleted file mode 100644 index 028167361..000000000 --- a/linphone/oRTP/include/ortp/sessionset.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/** - * \file sessionset.h - * \brief Sending and receiving multiple streams together with only one thread. - * -**/ -#ifndef SESSIONSET_H -#define SESSIONSET_H - - -#include - -#ifdef __cplusplus -extern "C"{ -#endif - - -#if !defined(_WIN32) && !defined(_WIN32_WCE) -/* UNIX */ -#include -#include -#include - -#define ORTP_FD_SET(d, s) FD_SET(d, s) -#define ORTP_FD_CLR(d, s) FD_CLR(d, s) -#define ORTP_FD_ISSET(d, s) FD_ISSET(d, s) -#define ORTP_FD_ZERO(s) FD_ZERO(s) - -typedef fd_set ortp_fd_set; - - -#else -/* WIN32 */ - -#define ORTP_FD_ZERO(s) \ - do { \ - unsigned int __i; \ - ortp_fd_set *__arr = (s); \ - for (__i = 0; __i < sizeof (ortp_fd_set) / sizeof (ortp__fd_mask); ++__i) \ - ORTP__FDS_BITS (__arr)[__i] = 0; \ - } while (0) -#define ORTP_FD_SET(d, s) (ORTP__FDS_BITS (s)[ORTP__FDELT(d)] |= ORTP__FDMASK(d)) -#define ORTP_FD_CLR(d, s) (ORTP__FDS_BITS (s)[ORTP__FDELT(d)] &= ~ORTP__FDMASK(d)) -#define ORTP_FD_ISSET(d, s) ((ORTP__FDS_BITS (s)[ORTP__FDELT(d)] & ORTP__FDMASK(d)) != 0) - - - -/* The fd_set member is required to be an array of longs. */ -typedef long int ortp__fd_mask; - - -/* Number of bits per word of `fd_set' (some code assumes this is 32). */ -#define ORTP__FD_SETSIZE 1024 - -/* It's easier to assume 8-bit bytes than to get CHAR_BIT. */ -#define ORTP__NFDBITS (8 * sizeof (ortp__fd_mask)) -#define ORTP__FDELT(d) ((d) / ORTP__NFDBITS) -#define ORTP__FDMASK(d) ((ortp__fd_mask) 1 << ((d) % ORTP__NFDBITS)) - - -/* fd_set for select and pselect. */ -typedef struct - { - ortp__fd_mask fds_bits[ORTP__FD_SETSIZE / ORTP__NFDBITS]; -# define ORTP__FDS_BITS(set) ((set)->fds_bits) - } ortp_fd_set; - - -#endif /*end WIN32*/ - -struct _SessionSet -{ - ortp_fd_set rtpset; -}; - - -typedef struct _SessionSet SessionSet; - -#define session_set_init(ss) ORTP_FD_ZERO(&(ss)->rtpset) - -SessionSet * session_set_new(void); -/** - * This macro adds the rtp session to the set. - * @param ss a set (SessionSet object) - * @param rtpsession a RtpSession -**/ -#define session_set_set(ss,rtpsession) ORTP_FD_SET((rtpsession)->mask_pos,&(ss)->rtpset) - -/** - * This macro tests if the session is part of the set. 1 is returned if true, 0 else. - *@param ss a set (#SessionSet object) - *@param rtpsession a rtp session - * -**/ -#define session_set_is_set(ss,rtpsession) ORTP_FD_ISSET((rtpsession)->mask_pos,&(ss)->rtpset) - -/** - * Removes the session from the set. - *@param ss a set of sessions. - *@param rtpsession a rtp session. - * - * -**/ -#define session_set_clr(ss,rtpsession) ORTP_FD_CLR((rtpsession)->mask_pos,&(ss)->rtpset) - -#define session_set_copy(dest,src) memcpy(&(dest)->rtpset,&(src)->rtpset,sizeof(ortp_fd_set)) - - -/** - * Frees a SessionSet. -**/ -void session_set_destroy(SessionSet *set); - - -int session_set_select(SessionSet *recvs, SessionSet *sends, SessionSet *errors); -int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/srtp.h b/linphone/oRTP/include/ortp/srtp.h deleted file mode 100644 index f6dae3874..000000000 --- a/linphone/oRTP/include/ortp/srtp.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef ortp_srtp_h -#define ortp_srtp_h - -#include -#include - -#ifdef __cplusplus -extern "C"{ -#endif - - -err_status_t ortp_srtp_init(void); -err_status_t ortp_srtp_create(srtp_t *session, const srtp_policy_t *policy); -err_status_t ortp_srtp_dealloc(srtp_t session); -err_status_t ortp_srtp_add_stream(srtp_t session, const srtp_policy_t *policy); - -bool_t ortp_srtp_supported(void); - -int srtp_transport_new(srtp_t srtp, RtpTransport **rtpt, RtpTransport **rtcpt ); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/str_utils.h b/linphone/oRTP/include/ortp/str_utils.h deleted file mode 100644 index ae073dd5b..000000000 --- a/linphone/oRTP/include/ortp/str_utils.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef STR_UTILS_H -#define STR_UTILS_H - - -#include - - -typedef struct msgb -{ - struct msgb *b_prev; - struct msgb *b_next; - struct msgb *b_cont; - struct datab *b_datap; - unsigned char *b_rptr; - unsigned char *b_wptr; - uint32_t reserved1; - uint32_t reserved2; -} mblk_t; - -typedef struct datab -{ - unsigned char *db_base; - unsigned char *db_lim; - void (*db_freefn)(void*); - int db_ref; -} dblk_t; - -typedef struct _queue -{ - mblk_t _q_stopper; - int q_mcount; /*number of packet in the q */ -} queue_t; - -#ifdef __cplusplus -extern "C" { -#endif - -void qinit(queue_t *q); - -void putq(queue_t *q, mblk_t *m); - -mblk_t * getq(queue_t *q); - -void insq(queue_t *q,mblk_t *emp, mblk_t *mp); - -void remq(queue_t *q, mblk_t *mp); - -mblk_t * peekq(queue_t *q); - -/* remove and free all messages in the q */ -#define FLUSHALL 0 -void flushq(queue_t *q, int how); - -void mblk_init(mblk_t *mp); - -/* allocates a mblk_t, that points to a datab_t, that points to a buffer of size size. */ -mblk_t *allocb(int size, int unused); -#define BPRI_MED 0 - -/* allocates a mblk_t, that points to a datab_t, that points to buf; buf will be freed using freefn */ -mblk_t *esballoc(uint8_t *buf, int size, int pri, void (*freefn)(void*) ); - -/* frees a mblk_t, and if the datab ref_count is 0, frees it and the buffer too */ -void freeb(mblk_t *m); - -/* frees recursively (follow b_cont) a mblk_t, and if the datab -ref_count is 0, frees it and the buffer too */ -void freemsg(mblk_t *mp); - -/* duplicates a mblk_t , buffer is not duplicated*/ -mblk_t *dupb(mblk_t *m); - -/* duplicates a complex mblk_t, buffer is not duplicated */ -mblk_t *dupmsg(mblk_t* m); - -/* returns the size of data of a message */ -int msgdsize(const mblk_t *mp); - -/* concatenates all fragment of a complex message*/ -void msgpullup(mblk_t *mp,int len); - -/* duplicates a single message, but with buffer included */ -mblk_t *copyb(mblk_t *mp); - -/* duplicates a complex message with buffer included */ -mblk_t *copymsg(mblk_t *mp); - -mblk_t * appendb(mblk_t *mp, const char *data, int size, bool_t pad); -void msgappend(mblk_t *mp, const char *data, int size, bool_t pad); - -mblk_t *concatb(mblk_t *mp, mblk_t *newm); - -#define qempty(q) (&(q)->_q_stopper==(q)->_q_stopper.b_next) -#define qfirst(q) ((q)->_q_stopper.b_next!=&(q)->_q_stopper ? (q)->_q_stopper.b_next : NULL) -#define qbegin(q) ((q)->_q_stopper.b_next) -#define qlast(q) ((q)->_q_stopper.b_prev!=&(q)->_q_stopper ? (q)->_q_stopper.b_prev : NULL) -#define qend(q,mp) ((mp)==&(q)->_q_stopper) -#define qnext(q,mp) ((mp)->b_next) - -typedef struct _msgb_allocator{ - queue_t q; -}msgb_allocator_t; - -void msgb_allocator_init(msgb_allocator_t *pa); -mblk_t *msgb_allocator_alloc(msgb_allocator_t *pa, int size); -void msgb_allocator_uninit(msgb_allocator_t *pa); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/stun.h b/linphone/oRTP/include/ortp/stun.h deleted file mode 100644 index 42b6ce3b9..000000000 --- a/linphone/oRTP/include/ortp/stun.h +++ /dev/null @@ -1,550 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* ==================================================================== - * The Vovida Software License, Version 1.0 - * - * Copyright (c) 2000 Vovida Networks, 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 names "VOCAL", "Vovida Open Communication Application Library", - * and "Vovida Open Communication Application Library (VOCAL)" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact vocal@vovida.org. - * - * 4. Products derived from this software may not be called "VOCAL", nor - * may "VOCAL" appear in their name, without prior written - * permission of Vovida Networks, Inc. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND - * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA - * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES - * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (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 Vovida - * Networks, Inc. and many individuals on behalf of Vovida Networks, - * Inc. For more information on Vovida Networks, Inc., please see - * . - * - */ - - -#ifndef __STUN_H__ -#define __STUN_H__ - -#include -#include -#include -#include - -#ifdef __APPLE__ - #include "TargetConditionals.h" -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* if you change this version, change in makefile too */ -#define STUN_VERSION "0.99" - -#define STUN_MAX_STRING 256 -#define STUN_MAX_UNKNOWN_ATTRIBUTES 8 -#define STUN_MAX_MESSAGE_SIZE 2048 - -#define STUN_PORT 3478 - -/* define some basic types */ -#if 0 -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; - -#if defined(WIN32) || defined(_WIN32_WCE) -typedef unsigned __int64 uint64_t; -#else -typedef unsigned long long uint64_t; -#endif -#endif -typedef struct { unsigned char octet[12]; } UInt96; - -/* define a structure to hold a stun address */ -#define IPv4Family 0x01 -#define IPv6Family 0x02 - -/* define flags */ -#define ChangeIpFlag 0x04 -#define ChangePortFlag 0x02 - -/* define stun attribute */ -#define SA_MAPPEDADDRESS 0x0001 -#define SA_RESPONSEADDRESS 0x0002 /** deprecated **/ -#define SA_CHANGEREQUEST 0x0003 /** deprecated **/ -#define SA_SOURCEADDRESS 0x0004 /** deprecated **/ -#define SA_CHANGEDADDRESS 0x0005 /** deprecated **/ -#define SA_USERNAME 0x0006 -#define SA_PASSWORD 0x0007 /** deprecated **/ -#define SA_MESSAGEINTEGRITY 0x0008 -#define SA_ERRORCODE 0x0009 -#define SA_UNKNOWNATTRIBUTE 0x000A -#define SA_REFLECTEDFROM 0x000B /** deprecated **/ -#define SA_REALM 0x0014 -#define SA_NONCE 0x0015 -#define SA_XORMAPPEDADDRESS 0x0020 - -#define SA_XORMAPPEDADDRESS2 0x8020 /* Non standard extention */ -#define SA_XORONLY 0x0021 /* deprecated */ -#define SA_SECONDARYADDRESS 0x0050 /* Non standard extention */ - -#define SA_SOFTWARE 0x8022 -#define SA_ALTERNATESERVER 0x8023 -#define SA_FINGERPRINT 0x8028 - -/* define turn attribute */ -#define TA_CHANNELNUMBER 0x000C -#define TA_LIFETIME 0x000D -#define TA_DEPRECATEDBANDWIDTH 0x0010 -#define TA_XORPEERADDRESS 0x0012 -#define TA_DATA 0x0013 -#define TA_XORRELAYEDADDRESS 0x0016 -#define TA_EVENPORT 0x0018 -#define TA_REQUESTEDTRANSPORT 0x0019 -#define TA_DONTFRAGMENT 0x001A -#define TA_DEPRECATEDTIMERVAL 0x0021 -#define TA_RESERVATIONTOKEN 0x0022 - -#define ICEA_PRIORITY 0x0024 -#define ICEA_USECANDIDATE 0x0025 -#define ICEA_ICECONTROLLED 0x8029 -#define ICEA_ICECONTROLLING 0x802a - -#define STUN_REQUEST 0x0000 -#define STUN_INDICATION 0x0010 -#define STUN_SUCCESS_RESP 0x0100 -#define STUN_ERR_RESP 0x0110 - -#define STUN_IS_REQUEST(msg_type) (((msg_type) & 0x0110) == 0x0000) -#define STUN_IS_INDICATION(msg_type) (((msg_type) & 0x0110) == 0x0010) -#define STUN_IS_SUCCESS_RESP(msg_type) (((msg_type) & 0x0110) == 0x0100) -#define STUN_IS_ERR_RESP(msg_type) (((msg_type) & 0x0110) == 0x0110) - -/* define types for a stun message */ -#define STUN_METHOD_BINDING 0x0001 -#define TURN_MEDHOD_ALLOCATE 0x0003 //(only request/response semantics defined) -#define TURN_METHOD_REFRESH 0x0004 //(only request/response semantics defined) -#define TURN_METHOD_CREATEPERMISSION 0x0008 //(only request/response semantics defined -#define TURN_METHOD_CHANNELBIND 0x0009 //(only request/response semantics defined) - -//#define BindResponseMsg 0x0101 -//#define BindErrorResponseMsg 0x0111 -#define SharedSecretRequestMsg 0x0002 -#define SharedSecretResponseMsg 0x0102 -#define SharedSecretErrorResponseMsg 0x0112 - -#define TURN_INDICATION_SEND 0x0006 //(only indication semantics defined) -#define TURN_INDICATION_DATA 0x0007 //(only indication semantics defined) - -typedef struct -{ - uint16_t msgType; - uint16_t msgLength; - uint32_t magic_cookie; - UInt96 tr_id; -} StunMsgHdr; - - -typedef struct -{ - uint16_t type; - uint16_t length; -} StunAtrHdr; - -typedef struct -{ - uint16_t port; - uint32_t addr; -} StunAddress4; - -typedef struct -{ - uint8_t pad; - uint8_t family; - StunAddress4 ipv4; -} StunAtrAddress4; - -typedef struct -{ - uint32_t value; -} StunAtrChangeRequest; - -typedef struct -{ - uint16_t pad; /* all 0 */ - uint8_t errorClass; - uint8_t number; - char reason[STUN_MAX_STRING]; - uint16_t sizeReason; -} StunAtrError; - -typedef struct -{ - uint16_t attrType[STUN_MAX_UNKNOWN_ATTRIBUTES]; - uint16_t numAttributes; -} StunAtrUnknown; - -typedef struct -{ - uint16_t channelNumber; - uint16_t rffu; /* Reserved For Future Use */ -} TurnAtrChannelNumber; - -typedef struct -{ - uint32_t lifetime; -} TurnAtrLifetime; - -typedef struct -{ - char value[1500]; - uint16_t sizeValue; -} TurnAtrData; - -typedef struct -{ - uint8_t proto; - uint8_t pad1; - uint8_t pad2; - uint8_t pad3; -} TurnAtrRequestedTransport; - -typedef struct -{ - uint64_t value; -} TurnAtrReservationToken; - -typedef struct -{ - uint32_t fingerprint; -} StunAtrFingerprint; - - -typedef struct -{ - char value[STUN_MAX_STRING]; - uint16_t sizeValue; -} StunAtrString; - -typedef struct -{ - uint32_t priority; -} IceAtrPriority; - -typedef struct -{ - uint64_t value; -} IceAtrIceControll; - -typedef struct -{ - char hash[20]; -} StunAtrIntegrity; - -typedef enum -{ - HmacUnkown=0, - HmacOK, - HmacBadUserName, - HmacUnkownUserName, - HmacFailed -} StunHmacStatus; - - -typedef struct -{ - uint16_t attrType[STUN_MAX_UNKNOWN_ATTRIBUTES]; - uint16_t numAttributes; -} TurnAtrUnknown; - -typedef struct -{ - StunMsgHdr msgHdr; - - bool_t hasMappedAddress; - StunAtrAddress4 mappedAddress; - - bool_t hasResponseAddress; - StunAtrAddress4 responseAddress; - - bool_t hasChangeRequest; - StunAtrChangeRequest changeRequest; - - bool_t hasSourceAddress; - StunAtrAddress4 sourceAddress; - - bool_t hasChangedAddress; - StunAtrAddress4 changedAddress; - - bool_t hasUsername; - StunAtrString username; - - bool_t hasPassword; - StunAtrString password; - - bool_t hasMessageIntegrity; - StunAtrIntegrity messageIntegrity; - - bool_t hasErrorCode; - StunAtrError errorCode; - - bool_t hasUnknownAttributes; - StunAtrUnknown unknownAttributes; - - bool_t hasReflectedFrom; - StunAtrAddress4 reflectedFrom; - - bool_t hasRealm; - StunAtrString realmName; - - bool_t hasNonce; - StunAtrString nonceName; - - bool_t hasXorMappedAddress; - StunAtrAddress4 xorMappedAddress; - - bool_t hasSoftware; - StunAtrString softwareName; - - bool_t hasXorPeerAddress; - StunAtrAddress4 xorPeerAddress; - - bool_t hasXorRelayedAddress; - StunAtrAddress4 xorRelayedAddress; - - bool_t hasFingerprint; - StunAtrFingerprint fingerprint; - - /* Turn elements */ - bool_t hasChannelNumberAttributes; - TurnAtrChannelNumber channelNumberAttributes; - - bool_t hasLifetimeAttributes; - TurnAtrLifetime lifetimeAttributes; - - bool_t hasData; - TurnAtrData data; - - bool_t hasRequestedTransport; - TurnAtrRequestedTransport requestedTransport; - - bool_t hasDontFragment; - - bool_t hasReservationToken; - TurnAtrReservationToken reservationToken; - - bool_t hasPriority; - IceAtrPriority priority; - - bool_t hasUseCandidate; - - bool_t hasIceControlled; - IceAtrIceControll iceControlled; - - bool_t hasIceControlling; - IceAtrIceControll iceControlling; -} StunMessage; - - -/* Define enum with different types of NAT */ -typedef enum -{ - StunTypeUnknown=0, - StunTypeOpen, - StunTypeConeNat, - StunTypeRestrictedNat, - StunTypePortRestrictedNat, - StunTypeSymNat, - StunTypeSymFirewall, - StunTypeBlocked, - StunTypeFailure -} NatType; - - -#define MAX_MEDIA_RELAYS 500 -#define MAX_RTP_MSG_SIZE 1500 -#define MEDIA_RELAY_TIMEOUT 3*60 - -typedef struct -{ - int relayPort; /* media relay port */ - int fd; /* media relay file descriptor */ - StunAddress4 destination; /* NAT IP:port */ - time_t expireTime; /* if no activity after time, close the socket */ -} StunMediaRelay; - -typedef struct -{ - StunAddress4 myAddr; - StunAddress4 altAddr; - Socket myFd; - Socket altPortFd; - Socket altIpFd; - Socket altIpPortFd; - bool_t relay; /* true if media relaying is to be done */ - StunMediaRelay relays[MAX_MEDIA_RELAYS]; -} StunServerInfo; - -void -stunCalculateIntegrity_longterm(char* hmac, const char* input, int length, - const char *username, const char *realm, const char *password); -void -stunCalculateIntegrity_shortterm(char* hmac, const char* input, int length, const char* key); -uint32_t -stunCalculateFingerprint(const char* input, int length); - -bool_t -stunParseMessage( char* buf, - unsigned int bufLen, - StunMessage *message); - -void -stunBuildReqSimple( StunMessage* msg, - const StunAtrString *username, - bool_t changePort, bool_t changeIp, unsigned int id ); - -unsigned int -stunEncodeMessage( const StunMessage *message, - char* buf, - unsigned int bufLen, - const StunAtrString *password); - -void -stunCreateUserName(const StunAddress4 *addr, StunAtrString* username); - -void -stunGetUserNameAndPassword( const StunAddress4 *dest, - StunAtrString* username, - StunAtrString* password); - -void -stunCreatePassword(const StunAtrString *username, StunAtrString* password); - -int -stunRand(void); - -uint64_t -stunGetSystemTimeSecs(void); - -/* find the IP address of a the specified stun server - return false is fails parse */ -bool_t -stunParseServerName( const char* serverName, StunAddress4 *stunServerAddr); - -bool_t -stunParseHostName( const char* peerName, - uint32_t *ip, - uint16_t *portVal, - uint16_t defaultPort ); - -/* return true if all is OK - Create a media relay and do the STERN thing if startMediaPort is non-zero */ -bool_t -stunInitServer(StunServerInfo *info, - const StunAddress4 *myAddr, - const StunAddress4 *altAddr, - int startMediaPort); - -void -stunStopServer(StunServerInfo *info); - -/* returns number of address found - take array or addres */ -int -stunFindLocalInterfaces(uint32_t* addresses, int maxSize ); - -int -stunTest( StunAddress4 *dest, int testNum, StunAddress4* srcAddr, StunAddress4 *sMappedAddr, StunAddress4* sChangedAddr); - -NatType -stunNatType( StunAddress4 *dest, - bool_t* preservePort, /* if set, is return for if NAT preservers ports or not */ - bool_t* hairpin , /* if set, is the return for if NAT will hairpin packets */ - int port, /* port to use for the test, 0 to choose random port */ - StunAddress4* sAddr /* NIC to use */ - ); - -bool_t -stunServerProcessMsg( char* buf, - unsigned int bufLen, - StunAddress4 *from, - StunAddress4 *myAddr, - StunAddress4 *altAddr, - StunMessage *resp, - StunAddress4 *destination, - StunAtrString *hmacPassword, - bool_t* changePort, - bool_t* changeIp); - -int -stunOpenSocket( StunAddress4 *dest, - StunAddress4* mappedAddr, - int port, - StunAddress4* srcAddr); - -bool_t -stunOpenSocketPair(StunAddress4 *dest, - StunAddress4* mapAddr_rtp, - StunAddress4* mapAddr_rtcp, - int* fd1, int* fd2, - int srcPort, StunAddress4* srcAddr); - -bool_t -turnAllocateSocketPair(StunAddress4 *dest, - StunAddress4* mapAddr_rtp, - StunAddress4* mapAddr_rtcp, - int* fd1, int* fd2, - int srcPort, StunAddress4* srcAddr); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/linphone/oRTP/include/ortp/stun_udp.h b/linphone/oRTP/include/ortp/stun_udp.h deleted file mode 100644 index e510a2e08..000000000 --- a/linphone/oRTP/include/ortp/stun_udp.h +++ /dev/null @@ -1,139 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* ==================================================================== - * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, 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 names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (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 Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * . - * - */ - -#ifndef __STUN_UDP_H__ -#define __STUN_UDP_H__ - -#ifndef __cplusplus -//#define bool int -//#define false 0 -//#define true 1 -#endif - -#ifdef __MACH__ -#include -#ifndef _SOCKLEN_T -typedef int socklen_t; -#endif -#endif - -#include - -#if !defined(_WIN32_WCE) -#include -#endif - -#if defined(WIN32) || defined(_WIN32_WCE) -#define snprintf _snprintf - -#include -/* #include */ - -typedef int socklen_t; -typedef SOCKET Socket; - -#define EWOULDBLOCK WSAEWOULDBLOCK -#define EINPROGRESS WSAEINPROGRESS -#define EALREADY WSAEALREADY -#define ENOTSOCK WSAENOTSOCK -#define EDESTADDRREQ WSAEDESTADDRREQ -#define EMSGSIZE WSAEMSGSIZE -#define EPROTOTYPE WSAEPROTOTYPE -#define ENOPROTOOPT WSAENOPROTOOPT -#define EPROTONOSUPPORT WSAEPROTONOSUPPORT -#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT -#define EOPNOTSUPP WSAEOPNOTSUPP -#define EPFNOSUPPORT WSAEPFNOSUPPORT -#define EAFNOSUPPORT WSAEAFNOSUPPORT -#define EADDRINUSE WSAEADDRINUSE -#define EADDRNOTAVAIL WSAEADDRNOTAVAIL -#define ENETDOWN WSAENETDOWN -#define ENETUNREACH WSAENETUNREACH -#define ENETRESET WSAENETRESET -#define ECONNABORTED WSAECONNABORTED -#define ECONNRESET WSAECONNRESET -#define ENOBUFS WSAENOBUFS -#define EISCONN WSAEISCONN -#define ENOTCONN WSAENOTCONN -#define ESHUTDOWN WSAESHUTDOWN -#define ETOOMANYREFS WSAETOOMANYREFS -#define ETIMEDOUT WSAETIMEDOUT -#define ECONNREFUSED WSAECONNREFUSED -#define ELOOP WSAELOOP -#define EHOSTDOWN WSAEHOSTDOWN -#define EHOSTUNREACH WSAEHOSTUNREACH -#define EPROCLIM WSAEPROCLIM -#define EUSERS WSAEUSERS -#define EDQUOT WSAEDQUOT -#define ESTALE WSAESTALE -#define EREMOTE WSAEREMOTE - -typedef LONGLONG Int64; - -#else - -typedef int Socket; -#define INVALID_SOCKET -1 -#define SOCKET_ERROR -1 - -#define closesocket(fd) close(fd) - -#define WSANOTINITIALISED EPROTONOSUPPORT - -#endif - -#ifdef __cplusplus -extern "C"{ -#endif - -int getErrno(void); - -/* Open a UDP socket to receive on the given port - if port is 0, pick a a - port, if interfaceIp!=0 then use ONLY the interface specified instead of - all of them */ -Socket -openPort( unsigned short port, unsigned int interfaceIp); - - -/* recive a UDP message */ -bool_t -getMessage( Socket fd, char* buf, int* len, - unsigned int* srcIp, unsigned short* srcPort); - - -/* send a UDP message */ -bool_t -sendMessage( Socket fd, char* msg, int len, - unsigned int dstIp, unsigned short dstPort); - - -/* set up network - does nothing in unix but needed for windows */ -void -initNetwork(void); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/linphone/oRTP/include/ortp/telephonyevents.h b/linphone/oRTP/include/ortp/telephonyevents.h deleted file mode 100644 index 284e097ee..000000000 --- a/linphone/oRTP/include/ortp/telephonyevents.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/** - * \file telephonyevents.h - * \brief Receiving and sending telephone events (RFC2833) - * -**/ - - -#ifndef TELEPHONYEVENTS_H -#define TELEPHONYEVENTS_H - -#include - - -struct _telephone_event -{ -#ifdef ORTP_BIGENDIAN - uint32_t event:8; - uint32_t E:1; - uint32_t R:1; - uint32_t volume:6; - uint32_t duration:16; -#else - uint32_t event:8; - uint32_t volume:6; - uint32_t R:1; - uint32_t E:1; - uint32_t duration:16; -#endif -}; - -typedef struct _telephone_event telephone_event_t; - -#ifdef __cplusplus -extern "C" { -#endif - -/* tell if the session supports telephony events. For this the telephony events payload_type - must be present in the rtp profile used by the session */ - -/* low level functions */ -int rtp_session_telephone_events_supported(RtpSession *session); -int rtp_session_send_telephone_events_supported(RtpSession *session); -int rtp_session_recv_telephone_events_supported(RtpSession *session); - -mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start); - -int rtp_session_add_telephone_event(RtpSession *session, - mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration); - -int rtp_session_read_telephone_event(RtpSession *session, - mblk_t *packet,telephone_event_t **tab); - -/* high level functions*/ -int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts); -int rtp_session_send_dtmf2(RtpSession *session, char dtmf, uint32_t userts, int duration); -/* for high level telephony event callback */ -void rtp_session_check_telephone_events(RtpSession *session, mblk_t *m0); - -#ifdef __cplusplus -} -#endif - -/* the size allocated for telephony events packets */ -#define TELEPHONY_EVENTS_ALLOCATED_SIZE (4*sizeof(telephone_event_t)) - -/* list of named events */ -#define TEV_DTMF_0 (0) -#define TEV_DTMF_1 (1) -#define TEV_DTMF_2 (2) -#define TEV_DTMF_3 (3) -#define TEV_DTMF_4 (4) -#define TEV_DTMF_5 (5) -#define TEV_DTMF_6 (6) -#define TEV_DTMF_7 (7) -#define TEV_DTMF_8 (8) -#define TEV_DTMF_9 (9) -#define TEV_DTMF_STAR (10) -#define TEV_DTMF_POUND (11) -#define TEV_DTMF_A (12) -#define TEV_DTMF_B (13) -#define TEV_DTMF_C (14) -#define TEV_DTMF_D (15) -#define TEV_FLASH (16) - - -#endif diff --git a/linphone/oRTP/oRTP.prj b/linphone/oRTP/oRTP.prj deleted file mode 100644 index 1c406516d..000000000 --- a/linphone/oRTP/oRTP.prj +++ /dev/null @@ -1,193 +0,0 @@ -# Anjuta Version 1.1.97 -Compatibility Level: 1 - - -Some description - - - - - - - - - - - - - - - - - -props.file.type=project - -anjuta.version=1.1.97 -anjuta.compatibility.level=1 - -project.name=oRTP -project.type=GENERIC -project.target.type=EXECUTABLE -project.version=0.99 -project.author=Simon Morlat -project.source.target=Rtp stack -project.has.gettext=0 -project.gui.command= -project.programming.language=C -project.excluded.modules=intl - -project.config.extra.modules.before= -project.config.extra.modules.after= -project.config.blocked=1 -project.config.disable.overwriting=1 1 1 1 1 1 1 1 1 - -project.menu.entry=oRTP Version 0.99 -project.menu.group=Application -project.menu.comment=oRTP Version 0.99 -project.menu.icon= -project.menu.need.terminal=0 - -project.configure.options= -anjuta.program.arguments= -preferences.build.option.jobs=0 -preferences.build.option.silent=0 -preferences.build.option.autosave=1 -preferences.anjuta.make.options=-k -preferences.make=make -preferences.build.option.keep.going=1 -preferences.build.option.warn.undef=0 -preferences.autoformat.custom.style= -i8 -sc -bli0 -bl0 -cbi0 -ss -preferences.autoformat.style=Style of Kangleipak -preferences.indent.opening=0 -preferences.autoformat.disable=0 -preferences.indent.automatic=1 -preferences.use.tabs=1 -preferences.indent.size=4 -preferences.tabsize=4 -preferences.indent.closing=0 - -module.include.name=. -module.include.type= -module.include.files=\ - src/errno-win32.h\ - src/export.h\ - src/ortp-config-win32.h\ - src/ortp.h\ - src/payloadtype.h\ - src/port_fct.h\ - src/rtp.h\ - src/rtpmod.h\ - src/rtpport.h\ - src/rtpsession.h\ - src/rtpsignaltable.h\ - src/rtptimer.h\ - src/scheduler.h\ - src/sessionset.h\ - src/str_utils.h\ - src/telephonyevents.h\ - src/rtcp.h\ - ortp-config.h - -module.source.name=. -module.source.type= -module.source.files=\ - src/avprofile.c\ - src/export.c\ - src/mrtprecv.c\ - src/mrtpsend.c\ - src/ortp.c\ - src/ortpdlkm.c\ - src/payloadtype.c\ - src/port_fct.c\ - src/posixtimer.c\ - src/rtpmemtest.c\ - src/rtpmod.c\ - src/rtpparse.c\ - src/rtprecv.c\ - src/rtpsend.c\ - src/rtpsession.c\ - src/rtpsignaltable.c\ - src/rtptimer.c\ - src/scheduler.c\ - src/sessionset.c\ - src/str_utils.c\ - src/telephonyevents.c\ - src/test_tevrecv.c\ - src/test_tevsend.c\ - src/test_timer.c\ - src/tevmrtprecv.c\ - src/tevrtprecv.c\ - src/tevrtpsend.c - -module.pixmap.name=. -module.pixmap.type= -module.pixmap.files=\ - docs/html/home.png\ - docs/html/left.png\ - docs/html/right.png\ - docs/html/up.png - -module.data.name=. -module.data.type= -module.data.files= - -module.help.name=. -module.help.type= -module.help.files= - -module.doc.name=. -module.doc.type= -module.doc.files=\ - build/win32/oRTP/README\ - AUTHORS\ - COPYING\ - ChangeLog\ - INSTALL\ - NEWS\ - README\ - TODO\ - docs/tmpl/multiplexing.sgml\ - docs/tmpl/ortp-unused.sgml\ - docs/tmpl/payloads.sgml\ - docs/tmpl/rtpsessionapi.sgml\ - docs/tmpl/stackinit.sgml\ - docs/tmpl/stackmanagement.sgml\ - docs/tmpl/telephoneevents.sgml\ - docs/sgml/payloads.sgml\ - docs/sgml/tree_index.sgml\ - docs/sgml/object_index.sgml\ - docs/sgml/rtpsessionapi.sgml\ - docs/sgml/stackmanagement.sgml\ - docs/sgml/multiplexing.sgml\ - docs/sgml/telephoneevents.sgml\ - docs/ortp-docs.sgml\ - docs/html/book1.html\ - docs/html/ortpapi.html\ - docs/html/ortp-stack-management-functions.html\ - docs/html/ortp-rtpsession-api.html\ - docs/html/ortp-rtp-payloads-and-profiles.html\ - docs/html/ortp-multiplexing-sessions-(in-a-one-thread-design).html\ - docs/html/ortp-telephone-events-(rfc2833)-.html\ - docs/html/index.sgml\ - docs/html/ortp-library-management-functions.html - -module.po.files= - -compiler.options.supports= -compiler.options.include.paths=\ - .\ - .. -compiler.options.library.paths= -compiler.options.libraries= -compiler.options.libraries.selected= -compiler.options.defines=\ - HAVE_CONFIG_H -compiler.options.defines.selected= -compiler.options.warning.buttons=0 0 1 1 0 1 0 0 0 0 0 0 0 1 0 0 -compiler.options.optimize.buttons=0 0 1 0 -compiler.options.other.buttons=1 0 -compiler.options.other.c.flags= -compiler.options.other.l.flags= -compiler.options.other.l.libs= - -project.src.paths= diff --git a/linphone/oRTP/oRTP.pws b/linphone/oRTP/oRTP.pws deleted file mode 100644 index 342999ad9..000000000 --- a/linphone/oRTP/oRTP.pws +++ /dev/null @@ -1,67 +0,0 @@ - -[executer] -RunInTerminal=true - -[Project DBase] -ShowLocals=true - -[filenumbers] -0=1846 -1=270 -2=1 -3=34 -4=43 -5=1 -6=4 -7=27 -8=9 - -[filemarkers] -0= -1= -2= -3= -4= -5= -6= -7= -8= - -[File View] -filter.file.unmatch=*.so *.o *.a *.la -filter.file.ignore.hidden=0 -filter.dir.ignore.hidden=0 - -[filelist] -0=/home/sangamon/src/devel/linphone/oRTP/src/rtpsession.c -1=/home/sangamon/src/devel/linphone/oRTP/src/rtpsession.h -2=/home/sangamon/src/devel/linphone/oRTP/src/rtcp.h -3=/home/sangamon/src/devel/linphone/oRTP/src/scheduler.c - -[Project Tree] -0=0 -1=0:1 - -[File Tree] -0=0 - -[replace_text] -0=telephone_event -1=session->rtp -2=PAYLOAD_AUDIO_CONTINUOUS -3=ortp_global_stats -4=session->rtp.rq -5=session->rtp.wq - -[find_text] -0=rtp_session_create -1=chunk_item_new -2=rtcp_calculate_sdes_padding -3=rtp_session_process -4=scheduler -5=rtp -6=rtp_send -7=RtpSession - -[find_in_files] -0=exit diff --git a/linphone/oRTP/ortp.doxygen.in b/linphone/oRTP/ortp.doxygen.in deleted file mode 100644 index 69ba62da2..000000000 --- a/linphone/oRTP/ortp.doxygen.in +++ /dev/null @@ -1,225 +0,0 @@ -# Doxyfile 1.5.1 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = oRTP -PROJECT_NUMBER = @ORTP_VERSION@ -OUTPUT_DIRECTORY = doc -CREATE_SUBDIRS = NO -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = NO -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = YES -OPTIMIZE_OUTPUT_JAVA = NO -BUILTIN_STL_SUPPORT = NO -DISTRIBUTE_GROUP_DOC = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = NO -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = @srcdir@/src @srcdir@/include/ortp -FILE_PATTERNS = *.c *.h -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXAMPLE_PATH = @srcdir@/src/tests -EXAMPLE_PATTERNS = *.c -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = YES -REFERENCES_RELATION = YES -REFERENCES_LINK_SOURCE = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = NO -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -CALLER_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/linphone/oRTP/ortp.pc.in b/linphone/oRTP/ortp.pc.in deleted file mode 100644 index 8084faecd..000000000 --- a/linphone/oRTP/ortp.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -# This is a comment -prefix=@prefix@ -exec_prefix=@exec_prefix@ -includedir=@includedir@ - -Name: oRTP -Description: Implement the RFC3550 (RTP) with a easy to use API with high and low level access. -Version: @ORTP_PKGCONFIG_VERSION@ -Libs: -L@libdir@ -lortp @ORTPDEPS_LIBS@ -Cflags: -I@includedir@ @ORTPDEPS_CFLAGS@ diff --git a/linphone/oRTP/ortp.spec.in b/linphone/oRTP/ortp.spec.in deleted file mode 100644 index f73cdfcdf..000000000 --- a/linphone/oRTP/ortp.spec.in +++ /dev/null @@ -1,83 +0,0 @@ -# -*- rpm-spec -*- -# -# ortp -- Real-time Transport Protocol Stack -# -# Default is optimized for Pentium IV but will execute on Pentium II & -# later (i686). - -%ifarch %ix86 -%define ortp_cpu pentium4 -%endif - -Summary: Real-time Transport Protocol Stack -Name: ortp -Version: @ORTP_PKGCONFIG_VERSION@ -Release: 1 -License: LGPL -Group: Applications/Communications -URL: http://linphone.org/ortp/ -Source0: %{name}-@ORTP_PKGCONFIG_VERSION@.tar.gz -BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot -%ifarch %ix86 -BuildArch: i686 -%endif - -%description -oRTP is a LGPL licensed C library implementing the RTP protocol -(rfc1889). It is available for most unix clones (primilarly Linux and -HP-UX), and Microsoft Windows. - -%package devel -Summary: Headers, libraries and docs for the oRTP library -Group: Development/Libraries -Requires: %{name} = %{version}-%{release} - -%description devel -oRTP is a LGPL licensed C library implementing the RTP protocol -(rfc1889). It is available for most unix clones (primilarly Linux and -HP-UX), and Microsoft Windows. - -This package contains header files and development libraries needed to -develop programs using the oRTP library. - -%ifarch %ix86 -%define ortp_arch_cflags -malign-double -march=i686 -mcpu=%{ortp_cpu} -%else -# Must be non-empty -%define ortp_arch_cflags -Wall -%endif -%define ortp_cflags %ortp_arch_cflags -Wall -g -pipe -pthread -O3 -fomit-frame-pointer -fno-schedule-insns -fschedule-insns2 -fstrict-aliasing - -%prep -%setup -q - -%build -%configure \ - --enable-shared \ - --enable-static -%{__make} -j$RPM_BUILD_NCPUS CFLAGS="%ortp_cflags" CXXFLAGS="%ortp_cflags" - -%install -rm -rf $RPM_BUILD_ROOT -%makeinstall - -%clean -rm -rf $RPM_BUILD_ROOT - -%files -%defattr(-,root,root,-) -%doc AUTHORS COPYING ChangeLog INSTALL NEWS README TODO -%{_libdir}/*.so.* - -%files devel -%defattr(-,root,root,-) -%doc doc/html -%{_libdir}/*.la -%{_libdir}/*.a -%{_libdir}/*.so -%{_libdir}/pkgconfig/*.pc -%{_includedir} - -%changelog -* Tue Oct 25 2005 Francois-Xavier Kowalski -- Add to oRTP distribution with "make rpm" target diff --git a/linphone/oRTP/pkg.list b/linphone/oRTP/pkg.list deleted file mode 100644 index e02f91683..000000000 --- a/linphone/oRTP/pkg.list +++ /dev/null @@ -1,38 +0,0 @@ -# -*- rpm-spec -*- ############################################################ -# -# EPM list file. See epm(1) and epm.list(5) for details -# -############################################################################### - -%product ${SUMMARY} -%version ${VERSION} -%release ${RELEASE} -%description ${SUMMARY} -%vendor ${VENDOR} -%copyright ${LICENSE} -%license ${LICENSE} -%readme ${srcdir}/README -%packager ${PACKAGER} - -%system linux - -# Package all-in one: should be split later on... -%provides ortp-devel - -%postinstall << EOF -ldconfig 2>&1 | logger -i -s -t ${PACKAGE} -EOF - -%postremove << EOF -ldconfig 2>&1 | logger -i -s -t ${PACKAGE} -EOF - -%system hpux - -%system all - -%include files.list - -%provides ortp -%replaces ortp - diff --git a/linphone/oRTP/src/.gitignore b/linphone/oRTP/src/.gitignore deleted file mode 100644 index fec93a5ec..000000000 --- a/linphone/oRTP/src/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -*.lo -.deps -.libs -Makefile -Makefile.in -libortp.la -mrtprecv -mrtpsend -rtpmemtest -rtprecv -rtpsend -test_timer -tevmrtprecv -tevrtprecv -tevrtpsend diff --git a/linphone/oRTP/src/Makefile.am b/linphone/oRTP/src/Makefile.am deleted file mode 100644 index 251c6dff7..000000000 --- a/linphone/oRTP/src/Makefile.am +++ /dev/null @@ -1,41 +0,0 @@ - -EXTRA_DIST=ortp-config-win32.h dll_entry.c - -AM_CFLAGS= $(PTHREAD_CFLAGS) -I$(top_srcdir) $(TRUESPEECH_CFLAGS) $(SRTP_CFLAGS) -AM_LDFLAGS= $(PTHREAD_LDFLAGS) - -INCLUDES=-I$(top_srcdir)/include/ - -lib_LTLIBRARIES = libortp.la - -libortp_la_SOURCES= str_utils.c \ - port.c \ - rtpparse.c \ - rtpsession.c \ - rtpsession_inet.c \ - rtpsession_priv.h \ - jitterctl.c jitterctl.h \ - rtpsignaltable.c \ - rtptimer.c rtptimer.h \ - posixtimer.c \ - ortp.c \ - scheduler.c scheduler.h \ - avprofile.c \ - sessionset.c \ - telephonyevents.c \ - payloadtype.c \ - rtcp.c \ - utils.c utils.h \ - rtcpparse.c \ - event.c \ - stun.c stun_udp.c \ - srtp.c \ - b64.c - - -libortp_la_LIBADD= $(PTHREAD_LIBS) -lm $(SRTP_LIBS) $(SSL_LIBS) - -libortp_la_LDFLAGS= -version-info $(LIBORTP_SO_VERSION) -no-undefined - - -SUBDIRS= . tests diff --git a/linphone/oRTP/src/avprofile.c b/linphone/oRTP/src/avprofile.c deleted file mode 100644 index a16a4c345..000000000 --- a/linphone/oRTP/src/avprofile.c +++ /dev/null @@ -1,516 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include - -char offset127=127; -char offset0xD5=(char)0xD5; -char offset0[4] = {0x00, 0x00, 0x00, 0x00}; - -/* - * IMPORTANT : some compiler don't support the tagged-field syntax. Those - * macros are there to trap the problem This means that if you want to keep - * portability, payload types must be defined with their fields in the right - * order. - */ -#if defined(_ISOC99_SOURCE) -// ISO C99's tagged syntax -#define TYPE(val) .type=(val) -#define CLOCK_RATE(val) .clock_rate=(val) -#define BITS_PER_SAMPLE(val) .bits_per_sample=(val) -#define ZERO_PATTERN(val) .zero_pattern=(val) -#define PATTERN_LENGTH(val) .pattern_length=(val) -#define NORMAL_BITRATE(val) .normal_bitrate=(val) -#define MIME_TYPE(val) .mime_type=(val) -#define CHANNELS(val) .channels=(val) -#define FMTP(val) .FMTP=(val) -#elif defined(__GNUC__) -// GCC's legacy tagged syntax (even old versions have it) -#define TYPE(val) type: (val) -#define CLOCK_RATE(val) clock_rate: (val) -#define BITS_PER_SAMPLE(val) bits_per_sample: (val) -#define ZERO_PATTERN(val) zero_pattern: (val) -#define PATTERN_LENGTH(val) pattern_length: (val) -#define NORMAL_BITRATE(val) normal_bitrate: (val) -#define MIME_TYPE(val) mime_type: (val) -#define CHANNELS(val) channels: (val) -#define FMTP(val) FMTP: (val) -#else -// No tagged syntax supported -#define TYPE(val) (val) -#define CLOCK_RATE(val) (val) -#define BITS_PER_SAMPLE(val) (val) -#define ZERO_PATTERN(val) (val) -#define PATTERN_LENGTH(val) (val) -#define NORMAL_BITRATE(val) (val) -#define MIME_TYPE(val) (val) -#define CHANNELS(val) (val) -#define FMTP(val) (val) - -#endif - -PayloadType payload_type_pcmu8000={ - TYPE( PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE( 8000), - BITS_PER_SAMPLE(8), - ZERO_PATTERN( &offset127), - PATTERN_LENGTH( 1), - NORMAL_BITRATE( 64000), - MIME_TYPE ("PCMU"), - CHANNELS(1) -}; - -PayloadType payload_type_pcma8000={ - TYPE( PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(8), - ZERO_PATTERN( &offset0xD5), - PATTERN_LENGTH( 1), - NORMAL_BITRATE( 64000), - MIME_TYPE ("PCMA"), - CHANNELS(1) -}; - -PayloadType payload_type_pcm8000={ - TYPE( PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(16), - ZERO_PATTERN( offset0), - PATTERN_LENGTH(1), - NORMAL_BITRATE( 128000), - MIME_TYPE ("PCM"), - CHANNELS(1) -}; - -PayloadType payload_type_l16_mono={ - TYPE( PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(44100), - BITS_PER_SAMPLE(16), - ZERO_PATTERN( offset0 ), - PATTERN_LENGTH(2), - NORMAL_BITRATE(705600), /* (44100 x 16bits per frame x 1 channel) */ - MIME_TYPE ("L16"), - CHANNELS(1) -}; - -PayloadType payload_type_l16_stereo={ - TYPE( PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(44100), - BITS_PER_SAMPLE(32), /* 16bits x 2 channels */ - ZERO_PATTERN( offset0 ), - PATTERN_LENGTH(4), - NORMAL_BITRATE(1411200), /* (44100 x 16bits per frame x 2 channels) */ - MIME_TYPE ("L16"), - CHANNELS(2) -}; - -PayloadType payload_type_lpc1016={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN( NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 2400), - MIME_TYPE ("1016"), - CHANNELS(1) -}; - - -PayloadType payload_type_gsm= -{ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 13500), - MIME_TYPE ("GSM"), - CHANNELS(1) -}; - -PayloadType payload_type_lpc= -{ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 5600), /* 20ms / 14 octets per frame */ - MIME_TYPE ("LPC"), - CHANNELS(1) -}; - -PayloadType payload_type_g7231= -{ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 6300), - MIME_TYPE ("G723"), - CHANNELS(1) -}; - -PayloadType payload_type_g729={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 8000), - MIME_TYPE ("G729"), - CHANNELS(1) -}; - -PayloadType payload_type_g7221={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 24000), - MIME_TYPE ("G7221"), - CHANNELS(1) -}; - -PayloadType payload_type_g726_40={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 8000), - MIME_TYPE ("G726-40"), - CHANNELS(1) -}; - -PayloadType payload_type_g726_32={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 8000), - MIME_TYPE ("G726-32"), - CHANNELS(1) -}; - -PayloadType payload_type_g726_24={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 8000), - MIME_TYPE ("G726-24"), - CHANNELS(1) -}; - -PayloadType payload_type_g726_16={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE( 8000), - MIME_TYPE ("G726-16"), - CHANNELS(1) -}; - -PayloadType payload_type_mpv= -{ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE( 256000), - MIME_TYPE ("MPV"), - CHANNELS(0) -}; - - -PayloadType payload_type_h261={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("H261"), - CHANNELS(0) -}; - -PayloadType payload_type_h263={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("H263"), - CHANNELS(0) -}; - -PayloadType payload_type_truespeech= -{ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE( 0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH( 0), - NORMAL_BITRATE(8536), - MIME_TYPE ("TSP0"), - CHANNELS(0) -}; - - -#ifdef __cplusplus -extern "C" -{ -#endif -RtpProfile av_profile; -#ifdef __cplusplus -} -#endif - - -void av_profile_init(RtpProfile *profile) -{ - rtp_profile_clear_all(profile); - profile->name="AV profile"; - rtp_profile_set_payload(profile,0,&payload_type_pcmu8000); - rtp_profile_set_payload(profile,1,&payload_type_lpc1016); - rtp_profile_set_payload(profile,3,&payload_type_gsm); - rtp_profile_set_payload(profile,7,&payload_type_lpc); - rtp_profile_set_payload(profile,4,&payload_type_g7231); - rtp_profile_set_payload(profile,8,&payload_type_pcma8000); - rtp_profile_set_payload(profile,10,&payload_type_l16_stereo); - rtp_profile_set_payload(profile,11,&payload_type_l16_mono); - rtp_profile_set_payload(profile,18,&payload_type_g729); - rtp_profile_set_payload(profile,31,&payload_type_h261); - rtp_profile_set_payload(profile,32,&payload_type_mpv); - rtp_profile_set_payload(profile,34,&payload_type_h263); -} - -/* these are extra payload types that can be used dynamically */ -PayloadType payload_type_lpc1015={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(2400), - MIME_TYPE ("1015"), - CHANNELS(1) -}; - -PayloadType payload_type_speex_nb={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(8000), /*not true: 8000 is the minimum*/ - MIME_TYPE ("speex"), - CHANNELS(1) -}; - -PayloadType payload_type_speex_wb={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(28000), - MIME_TYPE ("speex"), - CHANNELS(1) -}; - -PayloadType payload_type_speex_uwb={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(32000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(28000), - MIME_TYPE ("speex"), - CHANNELS(1) -}; - -PayloadType payload_type_ilbc={ - TYPE( PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(13300), /* the minimum, with 30ms frames */ - MIME_TYPE ("iLBC"), - CHANNELS(1), -}; - -PayloadType payload_type_amr={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("AMR"), - CHANNELS(1) -}; - -PayloadType payload_type_amrwb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("AMR-WB"), - CHANNELS(1) -}; - -PayloadType payload_type_mp4v={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("MP4V-ES"), - CHANNELS(0) -}; - - -PayloadType payload_type_evrc0={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("EVRC0"), - CHANNELS(1) -}; - -PayloadType payload_type_evrcb0={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("EVRCB0"), - CHANNELS(1) -}; - -PayloadType payload_type_h263_1998={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("H263-1998"), - CHANNELS(0) -}; - -PayloadType payload_type_h263_2000={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE ("H263-2000"), - CHANNELS(0) -}; - -PayloadType payload_type_theora={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("theora"), - CHANNELS(0) -}; - -PayloadType payload_type_h264={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("H264"), - CHANNELS(0) -}; - -PayloadType payload_type_x_snow={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("x-snow"), - CHANNELS(0) -}; - -PayloadType payload_type_jpeg={ - TYPE( PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE ("JPEG"), - CHANNELS(0) -}; - - -PayloadType payload_type_t140={ - PAYLOAD_AUDIO_PACKETIZED, /*type */ - 1000, - 0, - NULL, - 0, - 0, - "t140", - 0, - 0 -}; - -PayloadType payload_type_x_udpftp={ - PAYLOAD_AUDIO_PACKETIZED, /*type */ - 1000, - 0, - NULL, - 0, - 0, - "x-udpftp", - 0, - 0 -}; - diff --git a/linphone/oRTP/src/b64.c b/linphone/oRTP/src/b64.c deleted file mode 100644 index 08b0ed3e6..000000000 --- a/linphone/oRTP/src/b64.c +++ /dev/null @@ -1,607 +0,0 @@ -/* ///////////////////////////////////////////////////////////////////////////// - * File: b64.c - * - * Purpose: Implementation file for the b64 library - * - * Created: 18th October 2004 - * Updated: 3rd May 2008 - * - * Home: http://synesis.com.au/software/ - * - * Copyright (c) 2004-2008, Matthew Wilson and Synesis Software - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of - * any contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. - * - * ////////////////////////////////////////////////////////////////////////// */ - - -/** \file b64.c Implementation file for the b64 library - */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Version information - */ - -#ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_C_B64_MAJOR 1 -# define B64_VER_C_B64_MINOR 2 -# define B64_VER_C_B64_REVISION 3 -# define B64_VER_C_B64_EDIT 17 -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Includes - */ - -#include "ortp/b64.h" - -#include -#include -#include "ortp/port.h" -/* ///////////////////////////////////////////////////////////////////////////// - * Constants and definitions - */ - -#ifndef B64_DOCUMENTATION_SKIP_SECTION -# define NUM_PLAIN_DATA_BYTES (3) -# define NUM_ENCODED_DATA_BYTES (4) -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Macros - */ - -#ifndef NUM_ELEMENTS -# define NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0])) -#endif /* !NUM_ELEMENTS */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Warnings - */ - -#if defined(_MSC_VER) && \ - _MSC_VER < 1000 -# pragma warning(disable : 4705) -#endif /* _MSC_VER < 1000 */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Data - */ - -static const char b64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -static const signed char b64_indexes[] = -{ - /* 0 - 31 / 0x00 - 0x1f */ - -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - /* 32 - 63 / 0x20 - 0x3f */ - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, 62, -1, -1, -1, 63 /* ... , '+', ... '/' */ - , 52, 53, 54, 55, 56, 57, 58, 59 /* '0' - '7' */ - , 60, 61, -1, -1, -1, -1, -1, -1 /* '8', '9', ... */ - /* 64 - 95 / 0x40 - 0x5f */ - , -1, 0, 1, 2, 3, 4, 5, 6 /* ..., 'A' - 'G' */ - , 7, 8, 9, 10, 11, 12, 13, 14 /* 'H' - 'O' */ - , 15, 16, 17, 18, 19, 20, 21, 22 /* 'P' - 'W' */ - , 23, 24, 25, -1, -1, -1, -1, -1 /* 'X', 'Y', 'Z', ... */ - /* 96 - 127 / 0x60 - 0x7f */ - , -1, 26, 27, 28, 29, 30, 31, 32 /* ..., 'a' - 'g' */ - , 33, 34, 35, 36, 37, 38, 39, 40 /* 'h' - 'o' */ - , 41, 42, 43, 44, 45, 46, 47, 48 /* 'p' - 'w' */ - , 49, 50, 51, -1, -1, -1, -1, -1 /* 'x', 'y', 'z', ... */ - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 -}; - -/* ///////////////////////////////////////////////////////////////////////////// - * Helper functions - */ - -/** This function reads in 3 bytes at a time, and translates them into 4 - * characters. - */ -static size_t b64_encode_( unsigned char const *src - , size_t srcSize - , char *const dest - , size_t destLen - , unsigned lineLen - , B64_RC *rc) -{ - size_t total = ((srcSize + (NUM_PLAIN_DATA_BYTES - 1)) / NUM_PLAIN_DATA_BYTES) * NUM_ENCODED_DATA_BYTES; - - assert(NULL != rc); - *rc = B64_RC_OK; - - if(lineLen > 0) - { - size_t numLines = (total + (lineLen - 1)) / lineLen; - - total += 2 * (numLines - 1); - } - - if(NULL == dest) - { - return total; - } - else if(destLen < total) - { - *rc = B64_RC_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - char *p = dest; - char *end = dest + destLen; - size_t len = 0; - - for(; NUM_PLAIN_DATA_BYTES <= srcSize; srcSize -= NUM_PLAIN_DATA_BYTES) - { - char characters[NUM_ENCODED_DATA_BYTES]; - - /* - * - * | 0 | 1 | 2 | - * - * | | | | - * | | | | | | | - * | | | | | | | | | | | | | - * | | | | | | | | | | | | | | | | | | | | | | | | | - * - * | 0 | 1 | 2 | 3 | - * - */ - - /* characters[0] is the 6 left-most bits of src[0] */ - characters[0] = (char)((src[0] & 0xfc) >> 2); - /* characters[0] is the right-most 2 bits of src[0] and the left-most 4 bits of src[1] */ - characters[1] = (char)(((src[0] & 0x03) << 4) + ((src[1] & 0xf0) >> 4)); - /* characters[0] is the right-most 4 bits of src[1] and the 2 left-most bits of src[2] */ - characters[2] = (char)(((src[1] & 0x0f) << 2) + ((src[2] & 0xc0) >> 6)); - /* characters[3] is the right-most 6 bits of src[2] */ - characters[3] = (char)(src[2] & 0x3f); - -#ifndef __WATCOMC__ - assert(characters[0] >= 0 && characters[0] < 64); - assert(characters[1] >= 0 && characters[1] < 64); - assert(characters[2] >= 0 && characters[2] < 64); - assert(characters[3] >= 0 && characters[3] < 64); -#endif /* __WATCOMC__ */ - - src += NUM_PLAIN_DATA_BYTES; - *p++ = b64_chars[(unsigned char)characters[0]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[1]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[2]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[3]]; - assert(NULL != strchr(b64_chars, *(p-1))); - - if( ++len == lineLen && - p != end) - { - *p++ = '\r'; - *p++ = '\n'; - len = 0; - } - } - - if(0 != srcSize) - { - /* Deal with the overspill, by boosting it up to three bytes (using 0s) - * and then appending '=' for any missing characters. - * - * This is done into a temporary buffer, so we can call ourselves and - * have the output continue to be written direct to the destination. - */ - - unsigned char dummy[NUM_PLAIN_DATA_BYTES]; - size_t i; - - for(i = 0; i < srcSize; ++i) - { - dummy[i] = *src++; - } - - for(; i < NUM_PLAIN_DATA_BYTES; ++i) - { - dummy[i] = '\0'; - } - - b64_encode_(&dummy[0], NUM_PLAIN_DATA_BYTES, p, NUM_ENCODED_DATA_BYTES * (1 + 2), 0, rc); - - for(p += 1 + srcSize; srcSize++ < NUM_PLAIN_DATA_BYTES; ) - { - *p++ = '='; - } - } - - return total; - } -} - -/** This function reads in a character string in 4-character chunks, and writes - * out the converted form in 3-byte chunks to the destination. - */ -static size_t b64_decode_( char const *src - , size_t srcLen - , unsigned char *dest - , size_t destSize - , unsigned flags - , char const **badChar - , B64_RC *rc) -{ - const size_t wholeChunks = (srcLen / NUM_ENCODED_DATA_BYTES); - const size_t remainderBytes = (srcLen % NUM_ENCODED_DATA_BYTES); - size_t maxTotal = (wholeChunks + (0 != remainderBytes)) * NUM_PLAIN_DATA_BYTES; - unsigned char *dest_ = dest; - - ((void)remainderBytes); - - assert(NULL != badChar); - assert(NULL != rc); - - *badChar = NULL; - *rc = B64_RC_OK; - - if(NULL == dest) - { - return maxTotal; - } - else if(destSize < maxTotal) - { - *rc = B64_RC_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - /* Now we iterate through the src, collecting together four characters - * at a time from the Base-64 alphabet, until the end-point is reached. - * - * - */ - - char const *begin = src; - char const *const end = begin + srcLen; - size_t currIndex = 0; - size_t numPads = 0; - signed char indexes[NUM_ENCODED_DATA_BYTES]; /* 4 */ - - for(; begin != end; ++begin) - { - const char ch = *begin; - - if('=' == ch) - { - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = '\0'; - - ++numPads; - } - else - { - /* NOTE: Had to rename 'index' to 'ix', due to name clash with GCC on 64-bit Linux. */ - signed char ix = b64_indexes[(unsigned char)ch]; - - if(-1 == ix) - { - switch(ch) - { - case ' ': - case '\t': - case '\b': - case '\v': - if(B64_F_STOP_ON_UNEXPECTED_WS & flags) - { - *rc = B64_RC_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - /* Fall through */ - } - case '\r': - case '\n': - continue; - default: - if(B64_F_STOP_ON_UNKNOWN_CHAR & flags) - { - *rc = B64_RC_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - continue; - } - } - } - else - { - numPads = 0; - - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = ix; - } - } - - if(NUM_ENCODED_DATA_BYTES == currIndex) - { - unsigned char bytes[NUM_PLAIN_DATA_BYTES]; /* 3 */ - - bytes[0] = (unsigned char)((indexes[0] << 2) + ((indexes[1] & 0x30) >> 4)); - - currIndex = 0; - - *dest++ = bytes[0]; - if(2 != numPads) - { - bytes[1] = (unsigned char)(((indexes[1] & 0xf) << 4) + ((indexes[2] & 0x3c) >> 2)); - - *dest++ = bytes[1]; - - if(1 != numPads) - { - bytes[2] = (unsigned char)(((indexes[2] & 0x3) << 6) + indexes[3]); - - *dest++ = bytes[2]; - } - } - if(0 != numPads) - { - break; - } - } - } - - return (size_t)(dest - dest_); - } -} - -/* ///////////////////////////////////////////////////////////////////////////// - * API functions - */ - -size_t b64_encode(void const *src, size_t srcSize, char *dest, size_t destLen) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere. - */ - B64_RC rc_; - - return b64_encode_((unsigned char const*)src, srcSize, dest, destLen, 0, &rc_); -} - -size_t b64_encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = -1 */ - , B64_RC *rc /* = NULL */) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere - */ - B64_RC rc_; - if(NULL == rc) - { - rc = &rc_; - } - - switch(B64_F_LINE_LEN_MASK & flags) - { - case B64_F_LINE_LEN_USE_PARAM: - if(lineLen >= 0) - { - break; - } - /* Fall through to 64 */ - case B64_F_LINE_LEN_64: - lineLen = 64; - break; - case B64_F_LINE_LEN_76: - lineLen = 76; - break; - default: - /*the following assert makes a compiler error with icc*/ - /*assert(!"Bad line length flag specified to b64_encode2()");*/ - case B64_F_LINE_LEN_INFINITE: - lineLen = 0; - break; - } - - assert(0 == (lineLen % 4)); - - return b64_encode_((unsigned char const*)src, srcSize, dest, destLen, (unsigned)lineLen, rc); -} - -size_t b64_decode(char const *src, size_t srcLen, void *dest, size_t destSize) -{ - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - char const *badChar_; - B64_RC rc_; - - return b64_decode_(src, srcLen, (unsigned char*)dest, destSize, B64_F_STOP_ON_NOTHING, &badChar_, &rc_); -} - -size_t b64_decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , B64_RC *rc /* = NULL */) -{ - char const *badChar_; - B64_RC rc_; - - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - if(NULL == badChar) - { - badChar = &badChar_; - } - if(NULL == rc) - { - rc = &rc_; - } - - return b64_decode_(src, srcLen, (unsigned char*)dest, destSize, flags, badChar, rc); -} - -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef B64_DOCUMENTATION_SKIP_SECTION -struct b64ErrorString_t_ -#else /* !B64_DOCUMENTATION_SKIP_SECTION */ -typedef struct b64ErrorString_t_ b64ErrorString_t_; -struct b64ErrorString_t_ -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ -{ - int code; /*!< The error code. */ - char const *str; /*!< The string. */ - size_t len; /*!< The string length. */ -}; - - - -#define SEVERITY_STR_DECL(rc, desc) \ - \ - static const char s_str##rc[] = desc; \ - static const b64ErrorString_t_ s_rct##rc = { rc, s_str##rc, NUM_ELEMENTS(s_str##rc) - 1 } - - -#define SEVERITY_STR_ENTRY(rc) \ - \ - &s_rct##rc - - -static char const *b64_LookupCodeA_(int code, b64ErrorString_t_ const **mappings, size_t cMappings, size_t *len) -{ - /* Use Null Object (Variable) here for len, so do not need to check - * elsewhere. - */ - size_t len_; - - if(NULL == len) - { - len = &len_; - } - - /* Checked, indexed search. */ - if( code >= 0 && - code < B64_max_RC_value) - { - if(code == mappings[code]->code) - { - return (*len = mappings[code]->len, mappings[code]->str); - } - } - - /* Linear search. Should only be needed if order in - * b64_LookupErrorStringA_() messed up. - */ - { size_t i; for(i = 0; i < cMappings; ++i) - { - if(code == mappings[i]->code) - { - return (*len = mappings[i]->len, mappings[i]->str); - } - }} - - return (*len = 0, ""); -} - -static char const *b64_LookupErrorStringA_(int error, size_t *len) -{ - SEVERITY_STR_DECL(B64_RC_OK , "Operation was successful" ); - SEVERITY_STR_DECL(B64_RC_INSUFFICIENT_BUFFER , "The given translation buffer was not of sufficient size" ); - SEVERITY_STR_DECL(B64_RC_TRUNCATED_INPUT , "The input did not represent a fully formed stream of octet couplings" ); - SEVERITY_STR_DECL(B64_RC_DATA_ERROR , "Invalid data" ); - - static const b64ErrorString_t_ *s_strings[] = - { - SEVERITY_STR_ENTRY(B64_RC_OK), - SEVERITY_STR_ENTRY(B64_RC_INSUFFICIENT_BUFFER), - SEVERITY_STR_ENTRY(B64_RC_TRUNCATED_INPUT), - SEVERITY_STR_ENTRY(B64_RC_DATA_ERROR), - }; - - return b64_LookupCodeA_(error, s_strings, NUM_ELEMENTS(s_strings), len); -} - -char const *b64_getErrorString(B64_RC code) -{ - return b64_LookupErrorStringA_((int)code, NULL); -} - -size_t b64_getErrorStringLength(B64_RC code) -{ - size_t len; - - return (b64_LookupErrorStringA_((int)code, &len), len); -} - -/* ////////////////////////////////////////////////////////////////////////// */ diff --git a/linphone/oRTP/src/dll_entry.c b/linphone/oRTP/src/dll_entry.c deleted file mode 100644 index 37ac6cf12..000000000 --- a/linphone/oRTP/src/dll_entry.c +++ /dev/null @@ -1,147 +0,0 @@ - -#ifdef WIN32 -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif -#include "ortp/ortp.h" - -typedef struct __STRUCT_SHARED_DATA__ -{ - DWORD m_nReference; - DWORD m_dwStartTime; - BOOL m_bInitialize; - -} SHARED_DATA, * LPSHARED_DATA; - -#ifdef EXTERNAL_LOGGER -#include "logger.h" -#else -#define RegisterLog(logVar, logString); -#define UnregisterLog(logVar, logString); -#endif - -extern DWORD dwoRTPLogLevel; - -#define SHMEMSIZE sizeof(SHARED_DATA) - -static LPSHARED_DATA lpSharedData; -static HANDLE hMapObject = NULL; // handle to file mapping - -BOOL WINAPI DllMain( - HINSTANCE hinstDLL, // handle to DLL module - DWORD fdwReason, // reason for calling function - LPVOID lpReserved // reserved - ) -{ - BOOL fInit = FALSE; - WORD wVersionRequested; - WSADATA wsaData; - - // Perform actions based on the reason for calling. - switch( fdwReason ) - { - case DLL_PROCESS_ATTACH: - - OutputDebugString("--> dll_entry.c - oRTP.dll - DLL_PROCESS_ATTACH()\n"); - - wVersionRequested = MAKEWORD( 1, 0 ); - - if (WSAStartup(wVersionRequested,&wsaData)!=0) - { - return FALSE; - } - - // Create a named file mapping object. - hMapObject = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file - NULL, // default security attributes - PAGE_READWRITE, // read/write access - 0, // size: high 32-bits - SHMEMSIZE, // size: low 32-bits - "oRTPSharedMemory"); // name of map object - - if (hMapObject == NULL) - return FALSE; - - // The first process to attach initializes memory. - fInit = (GetLastError() != ERROR_ALREADY_EXISTS); - - // Get a pointer to the file-mapped shared memory. - - lpSharedData = (LPSHARED_DATA) MapViewOfFile( hMapObject, // object to map view of - FILE_MAP_WRITE, // read/write access - 0, // high offset: map from - 0, // low offset: beginning - 0); // default: map entire file - if (lpSharedData == NULL) - return FALSE; - - // Initialize memory if this is the first process. - - if (fInit) - { - OutputDebugString("--> dll_entry.c - oRTP.dll - Initializing module\n"); - - lpSharedData->m_dwStartTime = GetTickCount(); - lpSharedData->m_nReference = 1; - lpSharedData->m_bInitialize = FALSE; - - // Register the log - RegisterLog(&dwoRTPLogLevel, "LOG_ORTP"); - } - else - { - OutputDebugString("--> dll_entry.c - oRTP.dll - Binding\n"); - lpSharedData->m_nReference++; - } - break; - - case DLL_THREAD_ATTACH: - - if (lpSharedData != NULL) - { - if (lpSharedData->m_bInitialize == FALSE) - { - // Initialize oRTP - ortp_init(); - - // Start the scheduler - //ortp_scheduler_init(); - - lpSharedData->m_bInitialize = TRUE; - } - } - break; - - case DLL_THREAD_DETACH: - break; - - case DLL_PROCESS_DETACH: - - if (lpSharedData != NULL) - { - OutputDebugString("--> dll_entry.c - oRTP.dll - Binding\n"); - lpSharedData->m_nReference--; - - if (lpSharedData->m_nReference == 0) - { - OutputDebugString("--> dll_entry.c - oRTP.dll - Detaching\n"); - - ortp_exit(); - UnregisterLog(&dwoRTPLogLevel, "LOG_ORTP"); - - - // Unmap shared memory from the process's address space. - UnmapViewOfFile(lpSharedData); - lpSharedData = NULL; - - // Close the process's handle to the file-mapping object. - CloseHandle(hMapObject); - hMapObject = INVALID_HANDLE_VALUE; - } - } - break; - } - - return TRUE; // Successful DLL_PROCESS_ATTACH. -} diff --git a/linphone/oRTP/src/event.c b/linphone/oRTP/src/event.c deleted file mode 100644 index 00718e2e7..000000000 --- a/linphone/oRTP/src/event.c +++ /dev/null @@ -1,116 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/event.h" -#include "ortp/ortp.h" - -RtpEndpoint *rtp_endpoint_new(struct sockaddr *addr, socklen_t addrlen){ - RtpEndpoint *ep=ortp_new(RtpEndpoint,1); - if (sizeof(ep->addr)addr,addr,addrlen); - ep->addrlen=addrlen; - return ep; -} - -void rtp_endpoint_destroy(RtpEndpoint *ep){ - ortp_free(ep); -} - -RtpEndpoint *rtp_endpoint_dup(const RtpEndpoint *ep){ - return rtp_endpoint_new((struct sockaddr*)&ep->addr,ep->addrlen); -} - -OrtpEvent * ortp_event_new(unsigned long type){ - const int size=sizeof(OrtpEventType)+sizeof(OrtpEventData); - mblk_t *m=allocb(size,0); - memset(m->b_wptr,0,size); - *((OrtpEventType*)m->b_wptr)=type; - return m; -} - -OrtpEvent *ortp_event_dup(OrtpEvent *ev){ -#if 0 - OrtpEvent *nev=dupb(ev); -#else - OrtpEvent *nev = ortp_event_new(ortp_event_get_type(ev)); - OrtpEventData * ed = ortp_event_get_data(ev); - OrtpEventData * edv = ortp_event_get_data(nev); - - if (ed->ep) edv->ep = rtp_endpoint_dup(ed->ep); - if (ed->packet) edv->packet = copymsg(ed->packet); - edv->info.telephone_event = ed->info.telephone_event; -#endif - return nev; -} - -OrtpEventType ortp_event_get_type(const OrtpEvent *ev){ - return ((OrtpEventType*)ev->b_rptr)[0]; -} - -OrtpEventData * ortp_event_get_data(OrtpEvent *ev){ - return (OrtpEventData*)(ev->b_rptr+sizeof(OrtpEventType)); -} - -void ortp_event_destroy(OrtpEvent *ev){ - OrtpEventData *d=ortp_event_get_data(ev); - if (ev->b_datap->db_ref==1){ - if (d->packet) freemsg(d->packet); - if (d->ep) rtp_endpoint_destroy(d->ep); - } - freemsg(ev); -} - -OrtpEvQueue * ortp_ev_queue_new(){ - OrtpEvQueue *q=ortp_new(OrtpEvQueue,1); - qinit(&q->q); - ortp_mutex_init(&q->mutex,NULL); - return q; -} - -void ortp_ev_queue_flush(OrtpEvQueue * qp){ - OrtpEvent *ev; - while((ev=ortp_ev_queue_get(qp))!=NULL){ - ortp_event_destroy(ev); - } -} - -OrtpEvent * ortp_ev_queue_get(OrtpEvQueue *q){ - OrtpEvent *ev; - ortp_mutex_lock(&q->mutex); - ev=getq(&q->q); - ortp_mutex_unlock(&q->mutex); - return ev; -} - -void ortp_ev_queue_destroy(OrtpEvQueue * qp){ - ortp_ev_queue_flush(qp); - ortp_mutex_destroy(&qp->mutex); - ortp_free(qp); -} - -void ortp_ev_queue_put(OrtpEvQueue *q, OrtpEvent *ev){ - ortp_mutex_lock(&q->mutex); - putq(&q->q,ev); - ortp_mutex_unlock(&q->mutex); -} - diff --git a/linphone/oRTP/src/jitterctl.c b/linphone/oRTP/src/jitterctl.c deleted file mode 100644 index 0ee9dd4ca..000000000 --- a/linphone/oRTP/src/jitterctl.c +++ /dev/null @@ -1,182 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/*************************************************************************** - * jitterctl.c - * - * Mon Nov 8 11:53:21 2004 - * Copyright 2004 Simon MORLAT - * Email simon.morlat@linphone.org - ****************************************************************************/ - -#include "ortp/rtpsession.h" -#include "ortp/payloadtype.h" -#include "ortp/ortp.h" -#include "utils.h" -#include "rtpsession_priv.h" -#include - -#define JC_BETA 0.01 -#define JC_GAMMA (JC_BETA) - -#include "jitterctl.h" - -void jitter_control_init(JitterControl *ctl, int base_jiitt_time, PayloadType *payload){ - ctl->count=0; - ctl->slide=0; - ctl->prev_slide=0; - ctl->jitter=0; - ctl->inter_jitter=0; - ctl->slide=0; - if (base_jiitt_time!=-1) ctl->jitt_comp = base_jiitt_time; - /* convert in timestamp unit: */ - if (payload!=NULL){ - jitter_control_set_payload(ctl,payload); - } - ctl->adapt_jitt_comp_ts=ctl->jitt_comp_ts; - ctl->corrective_slide=0; -} - -void jitter_control_enable_adaptive(JitterControl *ctl, bool_t val){ - ctl->adaptive=val; -} - -void jitter_control_set_payload(JitterControl *ctl, PayloadType *pt){ - ctl->jitt_comp_ts = - (int) (((double) ctl->jitt_comp / 1000.0) * (pt->clock_rate)); - ctl->corrective_step=(160 * 8000 )/pt->clock_rate; /* This formula got to me after some beers */ - ctl->adapt_jitt_comp_ts=ctl->jitt_comp_ts; -} - - -void jitter_control_dump_stats(JitterControl *ctl){ - ortp_message("JitterControl:\n\tslide=%g,jitter=%g,count=%i", - (double)ctl->slide,ctl->jitter, ctl->count); -} - -/*the goal of this method is to compute "corrective_slide": a timestamp unit'd value to be added - to recv timestamp to make them reflect the instant they are delivered by the jitter buffer. */ -void jitter_control_update_corrective_slide(JitterControl *ctl){ - int tmp; - tmp=(int)(ctl->slide)-ctl->prev_slide; - if (tmp>ctl->corrective_step) { - ctl->corrective_slide+=ctl->corrective_step; - ctl->prev_slide=ctl->slide+ctl->corrective_step; - } - else if (tmp<-ctl->corrective_step) { - ctl->corrective_slide-=ctl->corrective_step; - ctl->prev_slide=ctl->slide-ctl->corrective_step; - } -} - -/* - The algorithm computes two values: - slide: an average of difference between the expected and the socket-received timestamp - jitter: an average of the absolute value of the difference between socket-received timestamp and slide. - slide is used to make clock-slide detection and correction. - jitter is added to the initial jitt_comp_time value. It compensates bursty packets arrival (packets - not arriving at regular interval ). -*/ -void jitter_control_new_packet(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts){ - int64_t diff=(int64_t)packet_ts - (int64_t)cur_str_ts; - double gap,slide; - int d; - //printf("diff=%g\n",diff); - if (ctl->count==0){ - slide=ctl->slide=ctl->prev_slide=diff; - ctl->olddiff=diff; - ctl->jitter=0; - }else{ - slide=((double)ctl->slide*(1-JC_BETA)) + ((double)diff*JC_BETA); - } - gap=(double)diff - slide; - gap=gap<0 ? -gap : 0; /*compute only for late packets*/ - ctl->jitter=(float) ((ctl->jitter*(1-JC_GAMMA)) + (gap*JC_GAMMA)); - d=diff-ctl->olddiff; - ctl->inter_jitter=(float) (ctl->inter_jitter+ (( (float)abs(d) - ctl->inter_jitter)*(1/16.0))); - ctl->olddiff=diff; - ctl->count++; - if (ctl->adaptive){ - - if (ctl->count%50==0) { - ctl->adapt_jitt_comp_ts=(int) MAX(ctl->jitt_comp_ts,2*ctl->jitter); - /*jitter_control_dump_stats(ctl);*/ - } - - ctl->slide=slide; - }else { - /*ctl->slide and jitter size are not updated*/ - } - return ; -} - - - - - -/** - *rtp_session_set_jitter_compensation: - *@session: a RtpSession - *@milisec: the time interval in milisec to be jitter compensed. - * - * Sets the time interval for which packet are buffered instead of being delivered to the - * application. - **/ -void -rtp_session_set_jitter_compensation (RtpSession * session, int milisec) -{ - PayloadType *payload=NULL; - if (session->rcv.pt!=-1) { - payload = rtp_profile_get_payload (session->rcv.profile,session->rcv.pt); - }/*else not set yet */ - jitter_control_init(&session->rtp.jittctl,milisec,payload); -} - -void rtp_session_enable_adaptive_jitter_compensation(RtpSession *session, bool_t val){ - jitter_control_enable_adaptive(&session->rtp.jittctl,val); -} - -bool_t rtp_session_adaptive_jitter_compensation_enabled(RtpSession *session){ - return session->rtp.jittctl.adaptive; -} - -void rtp_session_enable_jitter_buffer(RtpSession *session, bool_t enabled){ - session->rtp.jittctl.enabled=enabled; - session->flags|=RTP_SESSION_RECV_SYNC; -} - -bool_t rtp_session_jitter_buffer_enabled(const RtpSession *session){ - return session->rtp.jittctl.enabled; -} - -void rtp_session_set_jitter_buffer_params(RtpSession *session, const JBParameters *par){ - /* FIXME min_size and max_size to be implemented */ - rtp_session_set_jitter_compensation(session,par->nom_size); - jitter_control_enable_adaptive(&session->rtp.jittctl,par->adaptive); - session->rtp.max_rq_size=par->max_packets; -} - -void rtp_session_get_jitter_buffer_params(RtpSession *session, JBParameters *par){ - int nom_size=session->rtp.jittctl.jitt_comp; - par->min_size=nom_size; - par->nom_size=nom_size; - par->max_size=-1; - par->adaptive=session->rtp.jittctl.adaptive; - par->max_packets=session->rtp.max_rq_size; -} - diff --git a/linphone/oRTP/src/jitterctl.h b/linphone/oRTP/src/jitterctl.h deleted file mode 100644 index 713756118..000000000 --- a/linphone/oRTP/src/jitterctl.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/*************************************************************************** - * jitterctl.c - * - * Mon Nov 8 11:53:21 2004 - * Copyright 2004 Simon MORLAT - * Email simon.morlat@linphone.org - ****************************************************************************/ - -#ifndef JITTERCTL_H -#define JITTERCTL_H - - -void jitter_control_init(JitterControl *ctl, int base_jiitt_time, PayloadType *pt); -void jitter_control_enable_adaptive(JitterControl *ctl, bool_t val); -void jitter_control_new_packet(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts); -#define jitter_control_adaptive_enabled(ctl) ((ctl)->adaptive) -void jitter_control_set_payload(JitterControl *ctl, PayloadType *pt); -void jitter_control_update_corrective_slide(JitterControl *ctl); -static inline uint32_t jitter_control_get_compensated_timestamp(JitterControl *obj , uint32_t user_ts){ - return user_ts+obj->slide-obj->adapt_jitt_comp_ts; -} - -#endif diff --git a/linphone/oRTP/src/master b/linphone/oRTP/src/master deleted file mode 100644 index ded8bca41..000000000 --- a/linphone/oRTP/src/master +++ /dev/null @@ -1,33 +0,0 @@ -*############################################################ -*# -*# $Header: /sources/linphone/linphone/oRTP/src/master,v 1.1 2002/02/25 08:41:53 smorlat Exp $ -*# -*# $Source: /sources/linphone/linphone/oRTP/src/master,v $ -*# $Revision: 1.1 $ -*# $Locker: $ -*# -*############################################################ -$VERSION -1 -$$$ - -$DRIVER_INSTALL -oRTP -1 -1 -$$$ - -$LOADABLE -$$$ - -$INTERFACE -base -$$$ - -$DRIVER_DEPENDENCY -$$$ - -$TYPE -oRTP wsio_class pseudo pmi -1 -1 -$$$ - -$TUNABLE -$$$ diff --git a/linphone/oRTP/src/ortp-config-win32.h b/linphone/oRTP/src/ortp-config-win32.h deleted file mode 100644 index d98265ee7..000000000 --- a/linphone/oRTP/src/ortp-config-win32.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -/* ortp-config-win32.h. Generated manually... */ -#define ORTP_VERSION "0.8.2" -#define ORTP_MAJOR_VERSION 0 -#define ORTP_MINOR_VERSION 8 -#define ORTP_MICRO_VERSION 2 -#define ORTP_EXTRA_VERSION - -/* define the debug mode */ -#define RTP_DEBUG 1 - -#define HAVE_SRTP 1 - -/* enables SO_REUSEADDR socket option in the rtp_session_set_local_addr() function */ -#define SO_REUSE_ADDR 1 diff --git a/linphone/oRTP/src/ortp.c b/linphone/oRTP/src/ortp.c deleted file mode 100644 index 4edd91a4d..000000000 --- a/linphone/oRTP/src/ortp.c +++ /dev/null @@ -1,379 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#if defined(WIN32) || defined(_WIN32_WCE) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif -#include "ortp/ortp.h" -#include "scheduler.h" - -rtp_stats_t ortp_global_stats; - -#ifdef ENABLE_MEMCHECK -int ortp_allocations=0; -#endif - - -RtpScheduler *__ortp_scheduler; - - - -extern void av_profile_init(RtpProfile *profile); - -static void init_random_number_generator(){ - struct timeval t; - gettimeofday(&t,NULL); - srandom(t.tv_usec+t.tv_sec); -} - - -#ifdef WIN32 -static bool_t win32_init_sockets(void){ - WORD wVersionRequested; - WSADATA wsaData; - int i; - - wVersionRequested = MAKEWORD(2,0); - if( (i = WSAStartup(wVersionRequested, &wsaData))!=0) - { - ortp_error("Unable to initialize windows socket api, reason: %d (%s)",i,getWinSocketError(i)); - return FALSE; - } - return TRUE; -} -#endif - -/** - * Initialize the oRTP library. You should call this function first before using - * oRTP API. -**/ -void ortp_init() -{ - static bool_t initialized=FALSE; - if (initialized) return; - initialized=TRUE; - -#ifdef WIN32 - win32_init_sockets(); -#endif - - av_profile_init(&av_profile); - ortp_global_stats_reset(); - init_random_number_generator(); - ortp_message("oRTP-" ORTP_VERSION " initialized."); -} - - -/** - * Initialize the oRTP scheduler. You only have to do that if you intend to use the - * scheduled mode of the #RtpSession in your application. - * -**/ -void ortp_scheduler_init() -{ - static bool_t initialized=FALSE; - if (initialized) return; - initialized=TRUE; -#ifdef __hpux - /* on hpux, we must block sigalrm on the main process, because signal delivery - is ?random?, well, sometimes the SIGALRM goes to both the main thread and the - scheduler thread */ - sigset_t set; - sigemptyset(&set); - sigaddset(&set,SIGALRM); - sigprocmask(SIG_BLOCK,&set,NULL); -#endif /* __hpux */ - - __ortp_scheduler=rtp_scheduler_new(); - rtp_scheduler_start(__ortp_scheduler); - //sleep(1); -} - - -/** - * Gracefully uninitialize the library, including shutdowning the scheduler if it was started. - * -**/ -void ortp_exit() -{ - if (__ortp_scheduler!=NULL) - { - rtp_scheduler_destroy(__ortp_scheduler); - __ortp_scheduler=NULL; - } -} - -RtpScheduler * ortp_get_scheduler() -{ - if (__ortp_scheduler==NULL) ortp_error("Cannot use the scheduled mode: the scheduler is not " - "started. Call ortp_scheduler_init() at the begginning of the application."); - return __ortp_scheduler; -} - - -static FILE *__log_file=0; - -/** - *@param file a FILE pointer where to output the ortp logs. - * -**/ -void ortp_set_log_file(FILE *file) -{ - __log_file=file; -} - -static void __ortp_logv_out(OrtpLogLevel lev, const char *fmt, va_list args); - -OrtpLogFunc ortp_logv_out=__ortp_logv_out; - -/** - *@param func: your logging function, compatible with the OrtpLogFunc prototype. - * -**/ -void ortp_set_log_handler(OrtpLogFunc func){ - ortp_logv_out=func; -} - - -unsigned int __ortp_log_mask=ORTP_WARNING|ORTP_ERROR|ORTP_FATAL; - -/** - * @ param levelmask a mask of ORTP_DEBUG, ORTP_MESSAGE, ORTP_WARNING, ORTP_ERROR - * ORTP_FATAL . -**/ -void ortp_set_log_level_mask(int levelmask){ - __ortp_log_mask=levelmask; -} - -char * ortp_strdup_vprintf(const char *fmt, va_list ap) -{ - /* Guess we need no more than 100 bytes. */ - int n, size = 200; - char *p,*np; -#ifdef __linux - va_list cap;/*copy of our argument list: a va_list cannot be re-used (SIGSEGV on linux 64 bits)*/ -#endif - if ((p = (char *) ortp_malloc (size)) == NULL) - return NULL; - while (1) - { - /* Try to print in the allocated space. */ -#ifdef __linux - va_copy(cap,ap); - n = vsnprintf (p, size, fmt, cap); - va_end(cap); -#else - /*this works on 32 bits, luckily*/ - n = vsnprintf (p, size, fmt, ap); -#endif - /* If that worked, return the string. */ - if (n > -1 && n < size) - return p; - //printf("Reallocing space.\n"); - /* Else try again with more space. */ - if (n > -1) /* glibc 2.1 */ - size = n + 1; /* precisely what is needed */ - else /* glibc 2.0 */ - size *= 2; /* twice the old size */ - if ((np = (char *) ortp_realloc (p, size)) == NULL) - { - free(p); - return NULL; - } - else - { - p = np; - } - } -} - -char *ortp_strdup_printf(const char *fmt,...){ - char *ret; - va_list args; - va_start (args, fmt); - ret=ortp_strdup_vprintf(fmt, args); - va_end (args); - return ret; -} - -#if defined(WIN32) || defined(_WIN32_WCE) -#define ENDLINE "\r\n" -#else -#define ENDLINE "\n" -#endif - -#if defined(WIN32) || defined(_WIN32_WCE) -void ortp_logv(int level, const char *fmt, va_list args) -{ - if (ortp_logv_out!=NULL && ortp_log_level_enabled(level)) - ortp_logv_out(level,fmt,args); -#if !defined(_WIN32_WCE) - if ((level)==ORTP_FATAL) abort(); -#endif -} -#endif - -static void __ortp_logv_out(OrtpLogLevel lev, const char *fmt, va_list args){ - const char *lname="undef"; - char *msg; - if (__log_file==NULL) __log_file=stderr; - switch(lev){ - case ORTP_DEBUG: - lname="debug"; - break; - case ORTP_MESSAGE: - lname="message"; - break; - case ORTP_WARNING: - lname="warning"; - break; - case ORTP_ERROR: - lname="error"; - break; - case ORTP_FATAL: - lname="fatal"; - break; - default: - ortp_fatal("Bad level !"); - } - msg=ortp_strdup_vprintf(fmt,args); -#if defined(_MSC_VER) && !defined(_WIN32_WCE) - OutputDebugString(msg); - OutputDebugString("\r\n"); -#else - fprintf(__log_file,"ortp-%s-%s" ENDLINE,lname,msg); - fflush(__log_file); -#endif - - ortp_free(msg); -} - -/** - * Display global statistics (cumulative for all RtpSession) -**/ -void ortp_global_stats_display() -{ - rtp_stats_display(&ortp_global_stats,"Global statistics"); -#ifdef ENABLE_MEMCHECK - printf("Unfreed allocations: %i\n",ortp_allocations); -#endif -} - -/** - * Print RTP statistics. -**/ -void rtp_stats_display(const rtp_stats_t *stats, const char *header) -{ -#ifndef WIN32 - ortp_log(ORTP_MESSAGE, - "oRTP-stats:\n %s :", - header); - ortp_log(ORTP_MESSAGE, - " number of rtp packet sent=%lld", - (long long)stats->packet_sent); - ortp_log(ORTP_MESSAGE, - " number of rtp bytes sent=%lld bytes", - (long long)stats->sent); - ortp_log(ORTP_MESSAGE, - " number of rtp packet received=%lld", - (long long)stats->packet_recv); - ortp_log(ORTP_MESSAGE, - " number of rtp bytes received=%lld bytes", - (long long)stats->hw_recv); - ortp_log(ORTP_MESSAGE, - " number of incoming rtp bytes successfully delivered to the application=%lld ", - (long long)stats->recv); - ortp_log(ORTP_MESSAGE, - " number of times the application queried a packet that didn't exist=%lld ", - (long long)stats->unavaillable); - ortp_log(ORTP_MESSAGE, - " number of rtp packet lost=%lld", - (long long) stats->cum_packet_loss); - ortp_log(ORTP_MESSAGE, - " number of rtp packets received too late=%lld", - (long long)stats->outoftime); - ortp_log(ORTP_MESSAGE, - " number of bad formatted rtp packets=%lld", - (long long)stats->bad); - ortp_log(ORTP_MESSAGE, - " number of packet discarded because of queue overflow=%lld", - (long long)stats->discarded); -#else - ortp_log(ORTP_MESSAGE, - "oRTP-stats:\n %s :", - header); - ortp_log(ORTP_MESSAGE, - " number of rtp packet sent=%I64d", - (uint64_t)stats->packet_sent); - ortp_log(ORTP_MESSAGE, - " number of rtp bytes sent=%I64d bytes", - (uint64_t)stats->sent); - ortp_log(ORTP_MESSAGE, - " number of rtp packet received=%I64d", - (uint64_t)stats->packet_recv); - ortp_log(ORTP_MESSAGE, - " number of rtp bytes received=%I64d bytes", - (uint64_t)stats->hw_recv); - ortp_log(ORTP_MESSAGE, - " number of incoming rtp bytes successfully delivered to the application=%I64d ", - (uint64_t)stats->recv); - ortp_log(ORTP_MESSAGE, - " number of times the application queried a packet that didn't exist=%I64d ", - (uint64_t)stats->unavaillable); - ortp_log(ORTP_MESSAGE, - " number of rtp packet lost=%I64d", - (uint64_t) stats->cum_packet_loss); - ortp_log(ORTP_MESSAGE, - " number of rtp packets received too late=%I64d", - (uint64_t)stats->outoftime); - ortp_log(ORTP_MESSAGE, - " number of bad formatted rtp packets=%I64d", - (uint64_t)stats->bad); - ortp_log(ORTP_MESSAGE, - " number of packet discarded because of queue overflow=%I64d", - (uint64_t)stats->discarded); -#endif -} - -void ortp_global_stats_reset(){ - memset(&ortp_global_stats,0,sizeof(rtp_stats_t)); -} - -rtp_stats_t *ortp_get_global_stats(){ - return &ortp_global_stats; -} - -void rtp_stats_reset(rtp_stats_t *stats){ - memset((void*)stats,0,sizeof(rtp_stats_t)); -} - - -/** - * This function give the opportunity to programs to check if the libortp they link to - * has the minimum version number they need. - * - * Returns: true if ortp has a version number greater or equal than the required one. -**/ -bool_t ortp_min_version_required(int major, int minor, int micro){ - return ((major*1000000) + (minor*1000) + micro) <= - ((ORTP_MAJOR_VERSION*1000000) + (ORTP_MINOR_VERSION*1000) + ORTP_MICRO_VERSION); -} diff --git a/linphone/oRTP/src/payloadtype.c b/linphone/oRTP/src/payloadtype.c deleted file mode 100644 index bae1b0776..000000000 --- a/linphone/oRTP/src/payloadtype.c +++ /dev/null @@ -1,363 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/ortp.h" -#include "ortp/payloadtype.h" -#include "utils.h" - -char *payload_type_get_rtpmap(PayloadType *pt) -{ - int len=(int)strlen(pt->mime_type)+15; - char *rtpmap=(char *) ortp_malloc(len); - if (pt->channels>0) - snprintf(rtpmap,len,"%s/%i/%i",pt->mime_type,pt->clock_rate,pt->channels); - else - snprintf(rtpmap,len,"%s/%i",pt->mime_type,pt->clock_rate); - return rtpmap; -} - -PayloadType *payload_type_new() -{ - PayloadType *newpayload=(PayloadType *)ortp_new0(PayloadType,1); - newpayload->flags|=PAYLOAD_TYPE_ALLOCATED; - return newpayload; -} - - -PayloadType *payload_type_clone(PayloadType *payload) -{ - PayloadType *newpayload=(PayloadType *)ortp_new0(PayloadType,1); - memcpy(newpayload,payload,sizeof(PayloadType)); - newpayload->mime_type=ortp_strdup(payload->mime_type); - if (payload->recv_fmtp!=NULL) { - newpayload->recv_fmtp=ortp_strdup(payload->recv_fmtp); - } - if (payload->send_fmtp!=NULL){ - newpayload->send_fmtp=ortp_strdup(payload->send_fmtp); - } - newpayload->flags|=PAYLOAD_TYPE_ALLOCATED; - return newpayload; -} - -static bool_t canWrite(PayloadType *pt){ - if (!(pt->flags & PAYLOAD_TYPE_ALLOCATED)) { - ortp_error("Cannot change parameters of statically defined payload types: make your" - " own copy using payload_type_clone() first."); - return FALSE; - } - return TRUE; -} - -/** - * Sets a recv parameters (fmtp) for the PayloadType. - * This method is provided for applications using RTP with SDP, but - * actually the ftmp information is not used for RTP processing. -**/ -void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->recv_fmtp!=NULL) ortp_free(pt->recv_fmtp); - if (fmtp!=NULL) pt->recv_fmtp=ortp_strdup(fmtp); - else pt->recv_fmtp=NULL; - } -} - -/** - * Sets a send parameters (fmtp) for the PayloadType. - * This method is provided for applications using RTP with SDP, but - * actually the ftmp information is not used for RTP processing. -**/ -void payload_type_set_send_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->send_fmtp!=NULL) ortp_free(pt->send_fmtp); - if (fmtp!=NULL) pt->send_fmtp=ortp_strdup(fmtp); - else pt->send_fmtp=NULL; - } -} - - - -void payload_type_append_recv_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->recv_fmtp==NULL) - pt->recv_fmtp=ortp_strdup(fmtp); - else{ - char *tmp=ortp_strdup_printf("%s;%s",pt->recv_fmtp,fmtp); - ortp_free(pt->recv_fmtp); - pt->recv_fmtp=tmp; - } - } -} - -void payload_type_append_send_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->send_fmtp==NULL) - pt->send_fmtp=ortp_strdup(fmtp); - else{ - char *tmp=ortp_strdup_printf("%s;%s",pt->send_fmtp,fmtp); - ortp_free(pt->send_fmtp); - pt->send_fmtp=tmp; - } - } -} - - -/** - * Frees a PayloadType. -**/ -void payload_type_destroy(PayloadType *pt) -{ - if (pt->mime_type) ortp_free(pt->mime_type); - if (pt->recv_fmtp) ortp_free(pt->recv_fmtp); - if (pt->send_fmtp) ortp_free(pt->send_fmtp); - ortp_free(pt); -} - -/** - * Parses a fmtp string such as "profile=0;level=10", finds the value matching - * parameter param_name, and writes it into result. - * Despite fmtp strings are not used anywhere within oRTP, this function can - * be useful for people using RTP streams described from SDP. - * @param fmtp the fmtp line (format parameters) - * @param param_name the parameter to search for - * @param result the value given for the parameter (if found) - * @param result_len the size allocated to hold the result string - * @return TRUE if the parameter was found, else FALSE. -**/ -bool_t fmtp_get_value(const char *fmtp, const char *param_name, char *result, size_t result_len){ - const char *pos=strstr(fmtp,param_name); - memset(result, '\0', result_len); - if (pos){ - const char *equal=strchr(pos,'='); - if (equal){ - int copied; - const char *end=strchr(equal+1,';'); - if (end==NULL) end=fmtp+strlen(fmtp); /*assuming this is the last param */ - copied=MIN(result_len-1,end-(equal+1)); - strncpy(result,equal+1,copied); - result[copied]='\0'; - return TRUE; - } - } - return FALSE; -} - - -int rtp_profile_get_payload_number_from_mime(RtpProfile *profile,const char *mime) -{ - PayloadType *pt; - int i; - for (i=0;imime_type,mime)==0){ - return i; - } - } - } - return -1; -} - -int rtp_profile_find_payload_number(RtpProfile*profile,const char *mime,int rate,int channels) -{ - int i; - PayloadType *pt; - for (i=0;imime_type,mime)==0 && - pt->clock_rate==rate && - (pt->channels==channels || channels<=0 || pt->channels<=0)) { - /*we don't look at channels if it is undefined - ie a negative or zero value*/ - - return i; - } - } - } - return -1; -} - -int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile,const char *rtpmap) -{ - int clock_rate, channels, ret; - char* subtype = ortp_strdup( rtpmap ); - char* rate_str = NULL; - char* chan_str = NULL; - - - /* find the slash after the subtype */ - rate_str = strchr(subtype, '/'); - if (rate_str && strlen(rate_str)>1) { - *rate_str = 0; - rate_str++; - - /* Look for another slash */ - chan_str = strchr(rate_str, '/'); - if (chan_str && strlen(chan_str)>1) { - *chan_str = 0; - chan_str++; - } else { - chan_str = NULL; - } - } else { - rate_str = NULL; - } - - // Use default clock rate if none given - if (rate_str) clock_rate = atoi(rate_str); - else clock_rate = 8000; - - // Use default number of channels if none given - if (chan_str) channels = atoi(chan_str); - else channels = -1; - - //printf("Searching for payload %s at freq %i with %i channels\n",subtype,clock_rate,ch1annels); - ret=rtp_profile_find_payload_number(profile,subtype,clock_rate,channels); - ortp_free(subtype); - return ret; -} - -PayloadType * rtp_profile_find_payload(RtpProfile *prof,const char *mime,int rate,int channels) -{ - int i; - i=rtp_profile_find_payload_number(prof,mime,rate,channels); - if (i>=0) return rtp_profile_get_payload(prof,i); - return NULL; -} - - -PayloadType * rtp_profile_get_payload_from_mime(RtpProfile *profile,const char *mime) -{ - int pt; - pt=rtp_profile_get_payload_number_from_mime(profile,mime); - if (pt==-1) return NULL; - else return rtp_profile_get_payload(profile,pt); -} - - -PayloadType * rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap) -{ - int pt = rtp_profile_get_payload_number_from_rtpmap(profile,rtpmap); - if (pt==-1) return NULL; - else return rtp_profile_get_payload(profile,pt); -} - -int rtp_profile_move_payload(RtpProfile *prof,int oldpos,int newpos){ - prof->payload[newpos]=prof->payload[oldpos]; - prof->payload[oldpos]=NULL; - return 0; -} - -RtpProfile * rtp_profile_new(const char *name) -{ - RtpProfile *prof=(RtpProfile*)ortp_new0(RtpProfile,1); - rtp_profile_set_name(prof,name); - return prof; -} - -/** - * Assign payload type number index to payload type desribed in pt for the RTP profile profile. - * @param profile a RTP profile - * @param idx the payload type number - * @param pt the payload type description - * -**/ -void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType *pt){ - if (idx<0 || idx>=RTP_PROFILE_MAX_PAYLOADS) { - ortp_error("Bad index %i",idx); - return; - } - prof->payload[idx]=pt; -} - -/** - * Initialize the profile to the empty profile (all payload type are unassigned). - *@param profile a RTP profile - * -**/ -void rtp_profile_clear_all(RtpProfile *obj){ - int i; - for (i=0;ipayload[i]=0; - } -} - - -/** - * Set a name to the rtp profile. (This is not required) - * @param profile a rtp profile object - * @param nm a string - * -**/ -void rtp_profile_set_name(RtpProfile *obj, const char *name){ - if (obj->name!=NULL) ortp_free(obj->name); - obj->name=ortp_strdup(name); -} - -/* ! payload are not cloned*/ -RtpProfile * rtp_profile_clone(RtpProfile *prof) -{ - int i; - PayloadType *pt; - RtpProfile *newprof=rtp_profile_new(prof->name); - for (i=0;iname); - for (i=0;iname) { - ortp_free(prof->name); - prof->name = NULL; - } - for (i=0;iflags & PAYLOAD_TYPE_ALLOCATED)) - payload_type_destroy(payload); - } - ortp_free(prof); -} diff --git a/linphone/oRTP/src/port.c b/linphone/oRTP/src/port.c deleted file mode 100644 index 15a324091..000000000 --- a/linphone/oRTP/src/port.c +++ /dev/null @@ -1,532 +0,0 @@ - -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#if defined(WIN32) || defined(_WIN32_WCE) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif -#include "ortp/port.h" -#include "ortp/ortp.h" -#include "utils.h" - -#if defined(_WIN32) && !defined(_WIN32_WCE) -#include -#endif - -static void *ortp_libc_malloc(size_t sz){ - return malloc(sz); -} - -static void *ortp_libc_realloc(void *ptr, size_t sz){ - return realloc(ptr,sz); -} - -static void ortp_libc_free(void*ptr){ - free(ptr); -} - -static bool_t allocator_used=FALSE; - -static OrtpMemoryFunctions ortp_allocator={ - ortp_libc_malloc, - ortp_libc_realloc, - ortp_libc_free -}; - -void ortp_set_memory_functions(OrtpMemoryFunctions *functions){ - if (allocator_used){ - ortp_fatal("ortp_set_memory_functions() must be called before " - "first use of ortp_malloc or ortp_realloc"); - return; - } - ortp_allocator=*functions; -} - -void* ortp_malloc(size_t sz){ - allocator_used=TRUE; - return ortp_allocator.malloc_fun(sz); -} - -void* ortp_realloc(void *ptr, size_t sz){ - allocator_used=TRUE; - return ortp_allocator.realloc_fun(ptr,sz); -} - -void ortp_free(void* ptr){ - ortp_allocator.free_fun(ptr); -} - -void * ortp_malloc0(size_t size){ - void *ptr=ortp_malloc(size); - memset(ptr,0,size); - return ptr; -} - -char * ortp_strdup(const char *tmp){ - size_t sz; - char *ret; - if (tmp==NULL) - return NULL; - sz=strlen(tmp)+1; - ret=(char*)ortp_malloc(sz); - strcpy(ret,tmp); - ret[sz-1]='\0'; - return ret; -} - -/* - * this method is an utility method that calls fnctl() on UNIX or - * ioctlsocket on Win32. - * int retrun the result of the system method - */ -int set_non_blocking_socket (ortp_socket_t sock) -{ - - -#if !defined(_WIN32) && !defined(_WIN32_WCE) - return fcntl (sock, F_SETFL, O_NONBLOCK); -#else - unsigned long nonBlock = 1; - return ioctlsocket(sock, FIONBIO , &nonBlock); -#endif -} - - -/* - * this method is an utility method that calls close() on UNIX or - * closesocket on Win32. - * int retrun the result of the system method - */ -int close_socket(ortp_socket_t sock){ -#if !defined(_WIN32) && !defined(_WIN32_WCE) - return close (sock); -#else - return closesocket(sock); -#endif -} - -#if defined (_WIN32_WCE) || defined(_MSC_VER) -int ortp_file_exist(const char *pathname) { - FILE* fd; - if (pathname==NULL) return -1; - fd=fopen(pathname,"r"); - if (fd==NULL) { - return -1; - } else { - fclose(fd); - return 0; - } -} -#else -int ortp_file_exist(const char *pathname) { - return access(pathname,F_OK); -} -#endif /*_WIN32_WCE*/ - -#if !defined(_WIN32) && !defined(_WIN32_WCE) - /* Use UNIX inet_aton method */ -#else - int inet_aton (const char * cp, struct in_addr * addr) - { - unsigned long retval; - - retval = inet_addr (cp); - - if (retval == INADDR_NONE) - { - return -1; - } - else - { - addr->S_un.S_addr = retval; - return 1; - } - } -#endif - -char *ortp_strndup(const char *str,int n){ - int min=MIN((int)strlen(str),n)+1; - char *ret=(char*)ortp_malloc(min); - strncpy(ret,str,n); - ret[min-1]='\0'; - return ret; -} - -#if !defined(_WIN32) && !defined(_WIN32_WCE) -int __ortp_thread_join(ortp_thread_t thread, void **ptr){ - int err=pthread_join(thread,ptr); - if (err!=0) { - ortp_error("pthread_join error: %s",strerror(err)); - } - return err; -} - -int __ortp_thread_create(pthread_t *thread, pthread_attr_t *attr, void * (*routine)(void*), void *arg){ - pthread_attr_t my_attr; - pthread_attr_init(&my_attr); - if (attr) - my_attr = *attr; -#ifdef ORTP_DEFAULT_THREAD_STACK_SIZE - if (ORTP_DEFAULT_THREAD_STACK_SIZE!=0) - pthread_attr_setstacksize(&my_attr, ORTP_DEFAULT_THREAD_STACK_SIZE); -#endif - return pthread_create(thread, &my_attr, routine, arg); -} - -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) - -int WIN_mutex_init(ortp_mutex_t *mutex, void *attr) -{ - *mutex=CreateMutex(NULL, FALSE, NULL); - return 0; -} - -int WIN_mutex_lock(ortp_mutex_t * hMutex) -{ - WaitForSingleObject(*hMutex, INFINITE); /* == WAIT_TIMEOUT; */ - return 0; -} - -int WIN_mutex_unlock(ortp_mutex_t * hMutex) -{ - ReleaseMutex(*hMutex); - return 0; -} - -int WIN_mutex_destroy(ortp_mutex_t * hMutex) -{ - CloseHandle(*hMutex); - return 0; -} - -typedef struct thread_param{ - void * (*func)(void *); - void * arg; -}thread_param_t; - -static unsigned WINAPI thread_starter(void *data){ - thread_param_t *params=(thread_param_t*)data; - void *ret=params->func(params->arg); - ortp_free(data); - return (DWORD)ret; -} - -#if defined _WIN32_WCE -# define _beginthreadex CreateThread -# define _endthreadex ExitThread -#endif - -int WIN_thread_create(ortp_thread_t *th, void *attr, void * (*func)(void *), void *data) -{ - thread_param_t *params=ortp_new(thread_param_t,1); - params->func=func; - params->arg=data; - *th=(HANDLE)_beginthreadex( NULL, 0, (LPTHREAD_START_ROUTINE)thread_starter, params, 0, NULL); - return 0; -} - -int WIN_thread_join(ortp_thread_t thread_h, void **unused) -{ - if (thread_h!=NULL) - { - WaitForSingleObject(thread_h, INFINITE); - CloseHandle(thread_h); - } - return 0; -} - -int WIN_cond_init(ortp_cond_t *cond, void *attr) -{ - *cond=CreateEvent(NULL, FALSE, FALSE, NULL); - return 0; -} - -int WIN_cond_wait(ortp_cond_t* hCond, ortp_mutex_t * hMutex) -{ - //gulp: this is not very atomic ! bug here ? - WIN_mutex_unlock(hMutex); - WaitForSingleObject(*hCond, INFINITE); - WIN_mutex_lock(hMutex); - return 0; -} - -int WIN_cond_signal(ortp_cond_t * hCond) -{ - SetEvent(*hCond); - return 0; -} - -int WIN_cond_broadcast(ortp_cond_t * hCond) -{ - WIN_cond_signal(hCond); - return 0; -} - -int WIN_cond_destroy(ortp_cond_t * hCond) -{ - CloseHandle(*hCond); - return 0; -} - - -#if defined(_WIN32_WCE) -#include - -const char * ortp_strerror(DWORD value) { - static TCHAR msgBuf[256]; - FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - value, - 0, // Default language - (LPTSTR) &msgBuf, - 0, - NULL - ); - return (const char *)msgBuf; -} - -int -gettimeofday (struct timeval *tv, void *tz) -{ - DWORD timemillis = GetTickCount(); - tv->tv_sec = timemillis/1000; - tv->tv_usec = (timemillis - (tv->tv_sec*1000)) * 1000; - return 0; -} - -#else - -int gettimeofday (struct timeval *tv, void* tz) -{ - union - { - __int64 ns100; /*time since 1 Jan 1601 in 100ns units */ - FILETIME fileTime; - } now; - - GetSystemTimeAsFileTime (&now.fileTime); - tv->tv_usec = (long) ((now.ns100 / 10LL) % 1000000LL); - tv->tv_sec = (long) ((now.ns100 - 116444736000000000LL) / 10000000LL); - return (0); -} - -#endif - -const char *getWinSocketError(int error) -{ - static char buf[80]; - - switch (error) - { - case WSANOTINITIALISED: return "Windows sockets not initialized : call WSAStartup"; - case WSAEADDRINUSE: return "Local Address already in use"; - case WSAEADDRNOTAVAIL: return "The specified address is not a valid address for this machine"; - case WSAEINVAL: return "The socket is already bound to an address."; - case WSAENOBUFS: return "Not enough buffers available, too many connections."; - case WSAENOTSOCK: return "The descriptor is not a socket."; - case WSAECONNRESET: return "Connection reset by peer"; - - default : - sprintf(buf, "Error code : %d", error); - return buf; - break; - } - - return buf; -} - -#ifdef _WORKAROUND_MINGW32_BUGS -char * WSAAPI gai_strerror(int errnum){ - return (char*)getWinSocketError(errnum); -} -#endif - -#endif - -#ifndef WIN32 - -#include -#include -#include -#include - -static char *make_pipe_name(const char *name){ - return ortp_strdup_printf("/tmp/%s",name); -} - -/* portable named pipes */ -ortp_socket_t ortp_server_pipe_create(const char *name){ - struct sockaddr_un sa; - char *pipename=make_pipe_name(name); - ortp_socket_t sock; - sock=socket(AF_UNIX,SOCK_STREAM,0); - sa.sun_family=AF_UNIX; - strncpy(sa.sun_path,pipename,sizeof(sa.sun_path)-1); - unlink(pipename);/*in case we didn't finished properly previous time */ - ortp_free(pipename); - fchmod(sock,S_IRUSR|S_IWUSR); - if (bind(sock,(struct sockaddr*)&sa,sizeof(sa))!=0){ - ortp_error("Failed to bind command unix socket: %s",strerror(errno)); - return -1; - } - listen(sock,1); - return sock; -} - -ortp_socket_t ortp_server_pipe_accept_client(ortp_socket_t server){ - struct sockaddr_un su; - socklen_t ssize=sizeof(su); - ortp_socket_t client_sock=accept(server,(struct sockaddr*)&su,&ssize); - return client_sock; -} - -int ortp_server_pipe_close_client(ortp_socket_t client){ - return close(client); -} - -int ortp_server_pipe_close(ortp_socket_t spipe){ - return close(spipe); -} - -ortp_socket_t ortp_client_pipe_connect(const char *name){ - struct sockaddr_un sa; - char *pipename=make_pipe_name(name); - ortp_socket_t sock=socket(AF_UNIX,SOCK_STREAM,0); - sa.sun_family=AF_UNIX; - strncpy(sa.sun_path,pipename,sizeof(sa.sun_path)-1); - ortp_free(pipename); - if (connect(sock,(struct sockaddr*)&sa,sizeof(sa))!=0){ - close(sock); - return -1; - } - return sock; -} - -int ortp_pipe_read(ortp_socket_t p, uint8_t *buf, int len){ - return read(p,buf,len); -} - -int ortp_pipe_write(ortp_socket_t p, const uint8_t *buf, int len){ - return write(p,buf,len); -} - -int ortp_client_pipe_close(ortp_socket_t sock){ - return close(sock); -} - - -#elif defined(WIN32) && !defined(_WIN32_WCE) - -static char *make_pipe_name(const char *name){ - return ortp_strdup_printf("\\\\.\\pipe\\%s",name); -} - -static HANDLE event=NULL; - -/* portable named pipes */ -ortp_pipe_t ortp_server_pipe_create(const char *name){ - ortp_pipe_t h; - char *pipename=make_pipe_name(name); - h=CreateNamedPipe(pipename,PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,PIPE_TYPE_MESSAGE|PIPE_WAIT,1, - 32768,32768,0,NULL); - ortp_free(pipename); - if (h==INVALID_HANDLE_VALUE){ - ortp_error("Fail to create named pipe %s",pipename); - } - if (event==NULL) event=CreateEvent(NULL,TRUE,FALSE,NULL); - return h; -} - - -/*this function is a bit complex because we need to wakeup someday -even if nobody connects to the pipe. -ortp_server_pipe_close() makes this function to exit. -*/ -ortp_pipe_t ortp_server_pipe_accept_client(ortp_pipe_t server){ - OVERLAPPED ol; - DWORD undef; - HANDLE handles[2]; - memset(&ol,0,sizeof(ol)); - ol.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL); - ConnectNamedPipe(server,&ol); - handles[0]=ol.hEvent; - handles[1]=event; - WaitForMultipleObjects(2,handles,FALSE,INFINITE); - if (GetOverlappedResult(server,&ol,&undef,FALSE)){ - CloseHandle(ol.hEvent); - return server; - } - CloseHandle(ol.hEvent); - return INVALID_HANDLE_VALUE; -} - -int ortp_server_pipe_close_client(ortp_pipe_t server){ - return DisconnectNamedPipe(server)==TRUE ? 0 : -1; -} - -int ortp_server_pipe_close(ortp_pipe_t spipe){ - SetEvent(event); - //CancelIoEx(spipe,NULL); /*vista only*/ - return CloseHandle(spipe); -} - -ortp_pipe_t ortp_client_pipe_connect(const char *name){ - char *pipename=make_pipe_name(name); - ortp_pipe_t hpipe = CreateFile( - pipename, // pipe name - GENERIC_READ | // read and write access - GENERIC_WRITE, - 0, // no sharing - NULL, // default security attributes - OPEN_EXISTING, // opens existing pipe - 0, // default attributes - NULL); // no template file - ortp_free(pipename); - return hpipe; -} - -int ortp_pipe_read(ortp_pipe_t p, uint8_t *buf, int len){ - DWORD ret=0; - if (ReadFile(p,buf,len,&ret,NULL)) - return ret; - /*ortp_error("Could not read from pipe: %s",strerror(GetLastError()));*/ - return -1; -} - -int ortp_pipe_write(ortp_pipe_t p, const uint8_t *buf, int len){ - DWORD ret=0; - if (WriteFile(p,buf,len,&ret,NULL)) - return ret; - /*ortp_error("Could not write to pipe: %s",strerror(GetLastError()));*/ - return -1; -} - - -int ortp_client_pipe_close(ortp_pipe_t sock){ - return CloseHandle(sock); -} - - -#endif diff --git a/linphone/oRTP/src/posixtimer.c b/linphone/oRTP/src/posixtimer.c deleted file mode 100644 index 6330da00b..000000000 --- a/linphone/oRTP/src/posixtimer.c +++ /dev/null @@ -1,177 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if defined(WIN32) || defined(_WIN32_WCE) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif - -#include "ortp/ortp.h" -#include "rtptimer.h" - -#if !defined(_WIN32) && !defined(_WIN32_WCE) - -#ifdef __linux__ -#include -#endif - -#include -#include -#include - - -static struct timeval orig,cur; -static uint32_t posix_timer_time=0; /*in milisecond */ - -void posix_timer_init() -{ - posix_timer.state=RTP_TIMER_RUNNING; - gettimeofday(&orig,NULL); - posix_timer_time=0; -} - - - - -void posix_timer_do() -{ - int diff,time; - struct timeval tv; - gettimeofday(&cur,NULL); - time=((cur.tv_usec-orig.tv_usec)/1000 ) + ((cur.tv_sec-orig.tv_sec)*1000 ); - if ( (diff=time-posix_timer_time)>50){ - ortp_warning("Must catchup %i miliseconds.",diff); - } - while((diff = posix_timer_time-time) > 0) - { - tv.tv_sec = diff/1000; - tv.tv_usec = (diff%1000)*1000; -#if defined(_WIN32) || defined(_WIN32_WCE) - /* this kind of select is not supported on windows */ - Sleep(tv.tv_usec/1000 + tv.tv_sec * 1000); -#else - select(0,NULL,NULL,NULL,&tv); -#endif - gettimeofday(&cur,NULL); - time=((cur.tv_usec-orig.tv_usec)/1000 ) + ((cur.tv_sec-orig.tv_sec)*1000 ); - } - posix_timer_time+=POSIXTIMER_INTERVAL/1000; - -} - -void posix_timer_uninit() -{ - posix_timer.state=RTP_TIMER_STOPPED; -} - -RtpTimer posix_timer={ 0, - posix_timer_init, - posix_timer_do, - posix_timer_uninit, - {0,POSIXTIMER_INTERVAL}}; - - -#else //WIN32 - - -#include -#include - - -MMRESULT timerId; -HANDLE TimeEvent; -int late_ticks; - - -static DWORD posix_timer_time; -static DWORD offset_time; - - -#define TIME_INTERVAL 50 -#define TIME_RESOLUTION 10 -#define TIME_TIMEOUT 100 - - - -void CALLBACK timerCb(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) -{ - // Check timerId - if (timerId == uID) - { - SetEvent(TimeEvent); - posix_timer_time += TIME_INTERVAL; - } -} - - -void win_timer_init(void) -{ - timerId = timeSetEvent(TIME_INTERVAL,10,timerCb,0,TIME_PERIODIC | TIME_CALLBACK_FUNCTION); - TimeEvent = CreateEvent(NULL,FALSE,FALSE,NULL); - - late_ticks = 0; - - offset_time = GetTickCount(); - posix_timer_time=0; -} - - -void win_timer_do(void) -{ - DWORD diff; - - // If timer have expired while we where out of this method - // Try to run after lost time. - if (late_ticks > 0) - { - late_ticks--; - posix_timer_time+=TIME_INTERVAL; - return; - } - - - diff = GetTickCount() - posix_timer_time - offset_time; - if( diff>TIME_INTERVAL && (diff<(1<<31))) - { - late_ticks = diff/TIME_INTERVAL; - ortp_warning("we must catchup %i ticks.",late_ticks); - return; - } - - WaitForSingleObject(TimeEvent,TIME_TIMEOUT); - return; -} - - -void win_timer_close(void) -{ - timeKillEvent(timerId); -} - -RtpTimer toto; - -RtpTimer posix_timer={ 0, - win_timer_init, - win_timer_do, - win_timer_close, - {0,TIME_INTERVAL * 1000}}; - - -#endif // _WIN32 diff --git a/linphone/oRTP/src/rtcp.c b/linphone/oRTP/src/rtcp.c deleted file mode 100644 index 2d14813d5..000000000 --- a/linphone/oRTP/src/rtcp.c +++ /dev/null @@ -1,412 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/*************************************************************************** - * rtcp.c - * - * Wed Dec 1 11:45:30 2004 - * Copyright 2004 Simon Morlat - * Email simon dot morlat at linphone dot org - ****************************************************************************/ -#include "ortp/ortp.h" -#include "ortp/rtpsession.h" -#include "ortp/rtcp.h" -#include "utils.h" -#include "rtpsession_priv.h" - -#define rtcp_bye_set_ssrc(b,pos,ssrc) (b)->ssrc[pos]=htonl(ssrc) -#define rtcp_bye_get_ssrc(b,pos) ntohl((b)->ssrc[pos]) - - -void rtcp_common_header_init(rtcp_common_header_t *ch, RtpSession *s,int type, int rc, int bytes_len){ - rtcp_common_header_set_version(ch,2); - rtcp_common_header_set_padbit(ch,0); - rtcp_common_header_set_packet_type(ch,type); - rtcp_common_header_set_rc(ch,rc); /* as we don't yet support multi source receiving */ - rtcp_common_header_set_length(ch,(bytes_len/4)-1); -} - -static mblk_t *sdes_chunk_new(uint32_t ssrc){ - mblk_t *m=allocb(RTCP_SDES_CHUNK_DEFAULT_SIZE,0); - sdes_chunk_t *sc=(sdes_chunk_t*)m->b_rptr; - sc->csrc=htonl(ssrc); - m->b_wptr+=sizeof(sc->csrc); - return m; -} - - -static mblk_t * sdes_chunk_append_item(mblk_t *m, rtcp_sdes_type_t sdes_type, const char *content) -{ - if ( content ) - { - sdes_item_t si; - si.item_type=sdes_type; - si.len=(uint8_t) MIN(strlen(content),RTCP_SDES_MAX_STRING_SIZE); - m=appendb(m,(char*)&si,RTCP_SDES_ITEM_HEADER_SIZE,FALSE); - m=appendb(m,content,si.len,FALSE); - } - return m; -} - -static void sdes_chunk_set_ssrc(mblk_t *m, uint32_t ssrc){ - sdes_chunk_t *sc=(sdes_chunk_t*)m->b_rptr; - sc->csrc=htonl(ssrc); -} - -#define sdes_chunk_get_ssrc(m) ntohl(((sdes_chunk_t*)((m)->b_rptr))->csrc) - -static mblk_t * sdes_chunk_pad(mblk_t *m){ - return appendb(m,"",1,TRUE); -} - -/** - * Set session's SDES item for automatic sending of RTCP compound packets. - * If some items are not specified, use NULL. -**/ -void rtp_session_set_source_description(RtpSession *session, - const char *cname, const char *name, const char *email, const char *phone, - const char *loc, const char *tool, const char *note){ - mblk_t *chunk = sdes_chunk_new(session->snd.ssrc); - mblk_t *m=chunk; - const char *_cname=cname; - if (_cname==NULL) - { - _cname="Unknown"; - } - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_CNAME, _cname); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_NAME, name); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_EMAIL, email); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_PHONE, phone); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_LOC, loc); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_TOOL, tool); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_NOTE, note); - chunk=sdes_chunk_pad(chunk); - if (session->sd!=NULL) freemsg(session->sd); - session->sd=m; -} - -void -rtp_session_add_contributing_source(RtpSession *session, uint32_t csrc, - const char *cname, const char *name, const char *email, const char *phone, - const char *loc, const char *tool, const char *note) -{ - mblk_t *chunk = sdes_chunk_new(csrc); - mblk_t *m=chunk; - char *_cname=(char*)cname; - if (_cname==NULL) - { - _cname="toto"; - } - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_CNAME, cname); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_NAME, name); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_EMAIL, email); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_PHONE, phone); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_LOC, loc); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_TOOL, tool); - chunk=sdes_chunk_append_item(chunk, RTCP_SDES_NOTE, note); - chunk=sdes_chunk_pad(chunk); - putq(&session->contributing_sources,m); -} - - - -mblk_t* rtp_session_create_rtcp_sdes_packet(RtpSession *session) -{ - mblk_t *mp=allocb(sizeof(rtcp_common_header_t),0); - rtcp_common_header_t *rtcp; - mblk_t *tmp,*m=mp; - queue_t *q; - int rc=0; - rtcp = (rtcp_common_header_t*)mp->b_wptr; - mp->b_wptr+=sizeof(rtcp_common_header_t); - - /* concatenate all sdes chunks */ - sdes_chunk_set_ssrc(session->sd,session->snd.ssrc); - m=concatb(m,dupmsg(session->sd)); - rc++; - - q=&session->contributing_sources; - for (tmp=qbegin(q); !qend(q,tmp); tmp=qnext(q,mp)){ - m=concatb(m,dupmsg(tmp)); - rc++; - } - rtcp_common_header_init(rtcp,session,RTCP_SDES,rc,msgdsize(mp)); - return mp; -} - - -mblk_t *rtcp_create_simple_bye_packet(uint32_t ssrc, const char *reason) -{ - int packet_size; - int strsize = 0; - int strpadding = 0; - mblk_t *mp; - rtcp_bye_t *rtcp; - - packet_size = RTCP_BYE_HEADER_SIZE; - if (reason!=NULL) { - strsize=(int)MIN(strlen(reason),RTCP_BYE_REASON_MAX_STRING_SIZE); - if (strsize > 0) { - strpadding = 3 - (strsize % 4); - packet_size += 1 + strsize + strpadding; - } - } - mp = allocb(packet_size, 0); - - rtcp = (rtcp_bye_t*)mp->b_rptr; - rtcp_common_header_init(&rtcp->ch,NULL,RTCP_BYE,1,packet_size); - rtcp->ssrc[0] = htonl(ssrc); - mp->b_wptr += RTCP_BYE_HEADER_SIZE; - /* append the reason if any*/ - if (reason!=NULL) { - const char pad[] = {0, 0, 0}; - unsigned char strsize_octet = (unsigned char)strsize; - - appendb(mp, (const char*)&strsize_octet, 1, FALSE); - appendb(mp, reason,strsize, FALSE); - appendb(mp, pad,strpadding, FALSE); - } - return mp; -} - -void rtp_session_remove_contributing_sources(RtpSession *session, uint32_t ssrc) -{ - queue_t *q=&session->contributing_sources; - mblk_t *tmp; - for (tmp=qbegin(q); !qend(q,tmp); tmp=qnext(q,tmp)){ - uint32_t csrc=sdes_chunk_get_ssrc(tmp); - if (csrc==ssrc) { - remq(q,tmp); - break; - } - } - tmp=rtcp_create_simple_bye_packet(ssrc, NULL); - rtp_session_rtcp_send(session,tmp); -} - -static void sender_info_init(sender_info_t *info, RtpSession *session){ - struct timeval tv; - uint32_t tmp; - gettimeofday(&tv,NULL); - info->ntp_timestamp_msw=htonl(tv.tv_sec + 0x83AA7E80); /* 0x83AA7E80 is the number of seconds from 1900 to 1970 */ -#if defined(_WIN32_WCE) - tmp=(uint32_t)((double)tv.tv_usec*(double)(((uint64_t)1)<<32)*1.0e-6); -#else - tmp=(uint32_t)((double)tv.tv_usec*(double)(1LL<<32)*1.0e-6); -#endif - info->ntp_timestamp_lsw=htonl(tmp); - info->rtp_timestamp=htonl(session->rtp.snd_last_ts); - info->senders_packet_count=(uint32_t) htonl((u_long) session->rtp.stats.packet_sent); - info->senders_octet_count=(uint32_t) htonl((u_long) session->rtp.sent_payload_bytes); - session->rtp.last_rtcp_packet_count=session->rtp.stats.packet_sent; -} - - - -static void report_block_init(report_block_t *b, RtpSession *session){ - int packet_loss=0; - uint8_t loss_fraction=0; - RtpStream *stream=&session->rtp; - uint32_t delay_snc_last_sr=0; - uint32_t fl_cnpl; - - /* compute the statistics */ - /*printf("hwrcv_extseq.one=%u, hwrcv_seq_at_last_SR=%u hwrcv_since_last_SR=%u\n", - stream->hwrcv_extseq.one, - stream->hwrcv_seq_at_last_SR, - stream->hwrcv_since_last_SR - );*/ - if (stream->hwrcv_seq_at_last_SR!=0){ - packet_loss=(stream->hwrcv_extseq - stream->hwrcv_seq_at_last_SR) - stream->hwrcv_since_last_SR; - if (packet_loss<0) - packet_loss=0; - stream->stats.cum_packet_loss+=packet_loss; - loss_fraction=(int)(256.0*(float)packet_loss/(float)stream->hwrcv_since_last_SR); - } - /* reset them */ - stream->hwrcv_since_last_SR=0; - stream->hwrcv_seq_at_last_SR=stream->hwrcv_extseq; - - if (stream->last_rcv_SR_time.tv_sec!=0){ - struct timeval now; - float delay; - gettimeofday(&now,NULL); - delay=(float) ((now.tv_sec-stream->last_rcv_SR_time.tv_sec)*1e6 ) + (now.tv_usec-stream->last_rcv_SR_time.tv_usec); - delay=(float) (delay*65536*1e-6); - delay_snc_last_sr=(uint32_t) delay; - } - - b->ssrc=htonl(session->rcv.ssrc); - fl_cnpl=((loss_fraction&0xFF)<<24) | (stream->stats.cum_packet_loss & 0xFFFFFF); - b->fl_cnpl=htonl(fl_cnpl); - b->interarrival_jitter=htonl((uint32_t) stream->jittctl.inter_jitter); - b->ext_high_seq_num_rec=htonl(stream->hwrcv_extseq); - b->lsr=htonl(stream->last_rcv_SR_ts); - b->delay_snc_last_sr=htonl(delay_snc_last_sr); -} - - - -static int rtcp_sr_init(RtpSession *session, uint8_t *buf, int size){ - rtcp_sr_t *sr=(rtcp_sr_t*)buf; - int rr=(session->rtp.stats.packet_recv>0); - int sr_size=sizeof(rtcp_sr_t)-sizeof(report_block_t)+(rr*sizeof(report_block_t)); - if (sizech,session,RTCP_SR,rr,sr_size); - sr->ssrc=htonl(session->snd.ssrc); - sender_info_init(&sr->si,session); - /*only include a report block if packets were received*/ - if (rr) - report_block_init(&sr->rb[0],session); - return sr_size; -} - -static int rtcp_rr_init(RtpSession *session, uint8_t *buf, int size){ - rtcp_rr_t *rr=(rtcp_rr_t*)buf; - if (sizech,session,RTCP_RR,1,sizeof(rtcp_rr_t)); - rr->ssrc=htonl(session->snd.ssrc); - report_block_init(&rr->rb[0],session); - return sizeof(rtcp_rr_t); -} - -static int rtcp_app_init(RtpSession *session, uint8_t *buf, uint8_t subtype, const char *name, int size){ - rtcp_app_t *app=(rtcp_app_t*)buf; - if (sizech,session,RTCP_APP,subtype,size); - app->ssrc=htonl(session->snd.ssrc); - memset(app->name,0,4); - strncpy(app->name,name,4); - return sizeof(rtcp_app_t); -} - -static mblk_t * make_rr(RtpSession *session){ - mblk_t *cm=NULL; - mblk_t *sdes=NULL; - - cm=allocb(sizeof(rtcp_sr_t),0); - cm->b_wptr+=rtcp_rr_init(session,cm->b_wptr,sizeof(rtcp_rr_t)); - /* make a SDES packet */ - if (session->sd!=NULL) - sdes=rtp_session_create_rtcp_sdes_packet(session); - /* link them */ - cm->b_cont=sdes; - return cm; -} - - -static mblk_t * make_sr(RtpSession *session){ - mblk_t *cm=NULL; - mblk_t *sdes=NULL; - - cm=allocb(sizeof(rtcp_sr_t),0); - cm->b_wptr+=rtcp_sr_init(session,cm->b_wptr,sizeof(rtcp_sr_t)); - /* make a SDES packet */ - if (session->sd!=NULL) - sdes=rtp_session_create_rtcp_sdes_packet(session); - /* link them */ - cm->b_cont=sdes; - return cm; -} - -void rtp_session_rtcp_process_send(RtpSession *session){ - RtpStream *st=&session->rtp; - mblk_t *m; - if (st->rcv_last_app_ts - st->last_rtcp_report_snt_r > st->rtcp_report_snt_interval - || st->snd_last_ts - st->last_rtcp_report_snt_s > st->rtcp_report_snt_interval){ - st->last_rtcp_report_snt_r=st->rcv_last_app_ts; - st->last_rtcp_report_snt_s=st->snd_last_ts; - m=make_sr(session); - /* send the compound packet */ - rtp_session_rtcp_send(session,m); - ortp_debug("Rtcp compound message sent."); - } -} - -void rtp_session_rtcp_process_recv(RtpSession *session){ - RtpStream *st=&session->rtp; - mblk_t *m=NULL; - if (st->rcv_last_app_ts - st->last_rtcp_report_snt_r > st->rtcp_report_snt_interval - || st->snd_last_ts - st->last_rtcp_report_snt_s > st->rtcp_report_snt_interval){ - st->last_rtcp_report_snt_r=st->rcv_last_app_ts; - st->last_rtcp_report_snt_s=st->snd_last_ts; - - if (session->rtp.last_rtcp_packet_countrtp.stats.packet_sent){ - m=make_sr(session); - session->rtp.last_rtcp_packet_count=session->rtp.stats.packet_sent; - }else if (session->rtp.stats.packet_recv>0){ - /*don't send RR when no packet are received yet*/ - m=make_rr(session); - } - if (m!=NULL){ - /* send the compound packet */ - rtp_session_rtcp_send(session,m); - ortp_debug("Rtcp compound message sent."); - } - } -} - -void rtp_session_send_rtcp_APP(RtpSession *session, uint8_t subtype, const char *name, const uint8_t *data, int datalen){ - mblk_t *h=allocb(sizeof(rtcp_app_t),0); - mblk_t *d; - h->b_wptr+=rtcp_app_init(session,h->b_wptr,subtype,name,datalen+sizeof(rtcp_app_t)); - d=esballoc((uint8_t*)data,datalen,0,NULL); - h->b_cont=d; - rtp_session_rtcp_send(session,h); -} - -/** - * Sends a RTCP bye packet. - *@param session RtpSession - *@param reason the reason phrase. -**/ -int -rtp_session_bye(RtpSession *session, const char *reason) -{ - mblk_t *cm; - mblk_t *sdes = NULL; - mblk_t *bye = NULL; - int ret; - - /* Make a BYE packet (will be on the end of the compund packet). */ - bye = rtcp_create_simple_bye_packet(session->snd.ssrc, reason); - - /* SR or RR is determined by the fact whether stream was sent*/ - if (session->rtp.stats.packet_sent>0) - { - cm = allocb(sizeof(rtcp_sr_t), 0); - cm->b_wptr += rtcp_sr_init(session,cm->b_wptr, sizeof(rtcp_sr_t)); - /* make a SDES packet */ - sdes = rtp_session_create_rtcp_sdes_packet(session); - /* link them */ - concatb(concatb(cm, sdes), bye); - } else if (session->rtp.stats.packet_recv>0){ - /* make a RR packet */ - cm = allocb(sizeof(rtcp_rr_t), 0); - cm->b_wptr += rtcp_rr_init(session, cm->b_wptr, sizeof(rtcp_rr_t)); - /* link them */ - cm->b_cont = bye; - }else cm=bye; - - /* Send compound packet. */ - ret = rtp_session_rtcp_send(session, cm); - - return ret; -} - diff --git a/linphone/oRTP/src/rtcpparse.c b/linphone/oRTP/src/rtcpparse.c deleted file mode 100644 index 64df2c776..000000000 --- a/linphone/oRTP/src/rtcpparse.c +++ /dev/null @@ -1,541 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include "ortp/ortp.h" -#include "utils.h" - - -/*in case of coumpound packet, set read pointer of m to the beginning of the next RTCP -packet */ -bool_t rtcp_next_packet(mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch){ - int nextlen=sizeof(rtcp_common_header_t)+ - (rtcp_common_header_get_length(ch)*4); - if (m->b_rptr+nextlenb_wptr){ - m->b_rptr+=nextlen; - return TRUE; - } - } - return FALSE; -} - -void rtcp_rewind(mblk_t *m){ - m->b_rptr=m->b_datap->db_base; -} - -/* get common header; this function will also check the sanity of the packet*/ -const rtcp_common_header_t * rtcp_get_common_header(const mblk_t *m){ - int size=msgdsize(m); - rtcp_common_header_t *ch; - if (m->b_cont!=NULL){ - ortp_fatal("RTCP parser does not work on fragmented mblk_t. Use msgpullup() before to re-assemble the packet."); - return NULL; - } - if (sizeb_rptr; - return ch; -} - -bool_t rtcp_is_SR(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch!=NULL && rtcp_common_header_get_packet_type(ch)==RTCP_SR){ - if (msgdsize(m)b_rptr; - return ntohl(sr->ssrc); -} - -const sender_info_t * rtcp_SR_get_sender_info(const mblk_t *m){ - rtcp_sr_t *sr=(rtcp_sr_t*)m->b_rptr; - return &sr->si; -} - -const report_block_t * rtcp_SR_get_report_block(const mblk_t *m, int idx){ - rtcp_sr_t *sr=(rtcp_sr_t*)m->b_rptr; - report_block_t *rb=&sr->rb[idx]; - int size=sizeof(rtcp_common_header_t)+(4*rtcp_common_header_get_length(&sr->ch)); - if ( ( (uint8_t*)rb)+sizeof(report_block_t) <= m->b_rptr + size ) { - return rb; - }else{ - if (idxch)){ - ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.",idx); - } - } - return NULL; -} - -/*Receiver report accessors*/ -bool_t rtcp_is_RR(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch!=NULL && rtcp_common_header_get_packet_type(ch)==RTCP_RR){ - if (msgdsize(m)b_rptr; - return ntohl(rr->ssrc); -} - -const report_block_t * rtcp_RR_get_report_block(const mblk_t *m,int idx){ - rtcp_rr_t *rr=(rtcp_rr_t*)m->b_rptr; - report_block_t *rb=&rr->rb[idx]; - int size=sizeof(rtcp_common_header_t)+(4*rtcp_common_header_get_length(&rr->ch)); - if ( ( (uint8_t*)rb)+sizeof(report_block_t) <= (m->b_rptr + size ) ){ - return rb; - }else{ - if (idxch)){ - ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.",idx); - } - } - return NULL; -} - -/*SDES accessors */ -bool_t rtcp_is_SDES(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch && rtcp_common_header_get_packet_type(ch)==RTCP_SDES){ - if (msgdsize(m)b_rptr+sizeof(rtcp_common_header_t); - const rtcp_common_header_t *ch=(rtcp_common_header_t*)m->b_rptr; - uint8_t *end=rptr+sizeof(rtcp_common_header_t)+ - (4*rtcp_common_header_get_length(ch)); - uint32_t ssrc=0; - int nchunk=0; - bool_t chunk_start=TRUE; - - if (end>(uint8_t*)m->b_wptr) end=(uint8_t*)m->b_wptr; - - while(rptrb_rptr; - int rc=rtcp_common_header_get_rc(&bye->ch); - int len=rtcp_common_header_get_length(&bye->ch); - if (idxssrc[idx]<=(m->b_rptr - +sizeof(rtcp_common_header_t)+len-4)) { - *ssrc=ntohl(bye->ssrc[idx]); - return TRUE; - }else{ - ortp_warning("RTCP BYE should contain %i ssrc, but there is not enough room for it."); - } - } - return FALSE; -} - -bool_t rtcp_BYE_get_reason(const mblk_t *m, const char **reason, int *reason_len){ - rtcp_bye_t *bye=(rtcp_bye_t*)m->b_rptr; - int rc=rtcp_common_header_get_rc(&bye->ch); - int len=rtcp_common_header_get_length(&bye->ch); - uint8_t *rptr=(uint8_t*)m->b_rptr+sizeof(rtcp_common_header_t)+rc*4; - uint8_t *end=(uint8_t*)(m->b_rptr+sizeof(rtcp_common_header_t)+len); - if (rptrb_rptr; - return rtcp_common_header_get_rc(&app->ch); -} - -uint32_t rtcp_APP_get_ssrc(const mblk_t *m){ - rtcp_app_t *app=(rtcp_app_t*)m->b_rptr; - return ntohl(app->ssrc); -} -/* name argument is supposed to be at least 4 characters (note: no '\0' written)*/ -void rtcp_APP_get_name(const mblk_t *m, char *name){ - rtcp_app_t *app=(rtcp_app_t*)m->b_rptr; - memcpy(name,app->name,4); -} -/* retrieve the data. when returning, data points directly into the mblk_t */ -void rtcp_APP_get_data(const mblk_t *m, uint8_t **data, int *len){ - rtcp_app_t *app=(rtcp_app_t*)m->b_rptr; - int datalen=sizeof(rtcp_common_header_t)+rtcp_common_header_get_length(&app->ch)-8; - if (datalen>0){ - *data=(uint8_t*)m->b_rptr+sizeof(rtcp_app_t); - *len=datalen; - }else{ - *len=0; - *data=NULL; - } -} - -/*old functions: deprecated, but some useful code parts can be reused */ -/* Start from now this source code file was written by Nicola Baldo as an extension of - the oRTP library. Copyright (C) 2005 Nicola Baldo nicola@baldo.biz*/ - -void report_block_parse(RtpSession *session, report_block_t *rb, struct timeval rcv_time_tv) -{ - rb->ssrc = ntohl(rb->ssrc); - - if ( rb->ssrc != session->snd.ssrc ) - - { - ortp_debug("Received rtcp report block related to unknown ssrc (not from us)... discarded"); - return; - } - - else - - { - uint32_t rcv_time_msw; - uint32_t rcv_time_lsw; - uint32_t rcv_time; - double rtt; - - rcv_time_msw = rcv_time_tv.tv_sec; -#if defined(_WIN32_WCE) - rcv_time_lsw = (uint32_t) ((double)rcv_time_tv.tv_usec*(double)(((uint64_t)1)<<32)*1.0e-6); -#else - rcv_time_lsw = (uint32_t) ((double)rcv_time_tv.tv_usec*(double)(1LL<<32)*1.0e-6); -#endif - rcv_time = (rcv_time_msw<<16) | (rcv_time_lsw >> 16); - -/* - rb->cum_num_packet_lost = ntoh24(rb->cum_num_packet_lost); - rb->ext_high_seq_num_rec = ntohl(rb->ext_high_seq_num_rec); - rb->interarrival_jitter = ntohl(rb->interarrival_jitter); - rb->lsr = ntohl(rb->lsr); - rb->delay_snc_last_sr = ntohl(rb->delay_snc_last_sr); -*/ - - /* calculating Round Trip Time*/ - if (rb->lsr != 0) - { - rtt = (double) (rcv_time - rb->delay_snc_last_sr - rb->lsr); - rtt = rtt/65536; - //printf("RTT = %f s\n",rtt); - } - - } - -} - -void rtp_session_rtcp_parse(RtpSession *session, mblk_t *mp) -{ - rtcp_common_header_t *rtcp; - int msgsize; - int rtcp_pk_size; - RtpStream *rtpstream=&session->rtp; - struct timeval rcv_time_tv; - - - gettimeofday(&rcv_time_tv,NULL); - - return_if_fail(mp!=NULL); - - msgsize=(int) (mp->b_wptr-mp->b_rptr); - - if (msgsize < RTCP_COMMON_HEADER_SIZE) - { - ortp_debug("Receiving too short rtcp packet... discarded"); - return; - } - - rtcp=(rtcp_common_header_t *)mp->b_rptr; - - /* compound rtcp packet can be composed by more than one rtcp message */ - while (msgsize >= RTCP_COMMON_HEADER_SIZE) - { - - if (rtcp->version!=2) - { - ortp_debug("Receiving rtcp packet with version number !=2...discarded"); - return; - } - - /* convert header data from network order to host order */ - rtcp->length = ntohs(rtcp->length); - - /* compute length */ - rtcp_pk_size = (rtcp->length + 1) * 4; - /* Sanity check of simple RTCP packet length. */ - if (rtcp_pk_size > msgsize) - { - ortp_debug("Receiving rtcp packet shorter than the specified length.. discared"); - return; - } - - switch (rtcp->packet_type) - - { - - case RTCP_SR: - - { - rtcp_sr_t *sr = (rtcp_sr_t *) rtcp; - report_block_t *rb; - int i; - - if ( ntohl(sr->ssrc) != session->rcv.ssrc ) - { - ortp_debug("Receiving rtcp sr packet from unknown ssrc.. discarded"); - return; - } - - if (msgsize < RTCP_COMMON_HEADER_SIZE + RTCP_SSRC_FIELD_SIZE + RTCP_SENDER_INFO_SIZE + (RTCP_REPORT_BLOCK_SIZE*sr->ch.rc)) - { - ortp_debug("Receiving too short rtcp sr packet... discarded"); - return; - } - - /* parsing RTCP Sender Info */ - sr->si.ntp_timestamp_msw = ntohl(sr->si.ntp_timestamp_msw); - sr->si.ntp_timestamp_lsw = ntohl(sr->si.ntp_timestamp_lsw); - sr->si.rtp_timestamp = ntohl(sr->si.rtp_timestamp); - sr->si.senders_packet_count = ntohl(sr->si.senders_packet_count); - sr->si.senders_octet_count = ntohl(sr->si.senders_octet_count); - - /* saving data to fill LSR and DLSR field in next RTCP report to be transmitted */ - rtpstream->last_rcv_SR_ts = (sr->si.ntp_timestamp_msw << 16) | (sr->si.ntp_timestamp_lsw >> 16); - rtpstream->last_rcv_SR_time.tv_usec = rcv_time_tv.tv_usec; - rtpstream->last_rcv_SR_time.tv_sec = rcv_time_tv.tv_sec; - - - /* parsing all RTCP report blocks */ - for (i=0; ich.rc; i++) - { - rb = &(sr->rb[i]); - report_block_parse(session, rb, rcv_time_tv); - } - - } - break; - - - - case RTCP_RR: - - { - rtcp_rr_t *rr = (rtcp_rr_t *) rtcp; - report_block_t *rb; - int i; - - if (session->rcv.ssrc == 0) - { - /* rcv.ssrc is not set, so we adopt the incoming one */ - session->rcv.ssrc = ntohl(rr->ssrc); - } - else if ( ntohl(rr->ssrc) != session->rcv.ssrc ) - { - ortp_debug("Receiving rtcp rr packet from unknown ssrc.. discarded"); - return; - } - - if (msgsize < RTCP_COMMON_HEADER_SIZE + RTCP_SSRC_FIELD_SIZE + (RTCP_REPORT_BLOCK_SIZE*rr->ch.rc)) - { - ortp_debug("Receiving too short rtcp sr packet... discarded"); - return; - } - - /* parsing all RTCP report blocks */ - for (i=0; ich.rc; i++) - { - rb = &(rr->rb[i]); - report_block_parse(session, rb, rcv_time_tv); - } - - } - break; - - - case RTCP_SDES: - /* to be implemented */ - break; - - - case RTCP_BYE: - { - rtcp_bye_t *bye = (rtcp_bye_t *) rtcp; - unsigned sclen = bye->ch.rc * 4; - int reason_space_len = rtcp_pk_size - - sizeof (rtcp_common_header_t) - - sclen; - int i; - char *reason = NULL; - bool_t rcv_ssrc_match = FALSE; - - if (reason_space_len < 0) { - ortp_debug("Receiving too short RTCP BYE packet... discarded"); - return; - } - for (i = 0; i < bye->ch.rc; i++) { - if (ntohl(bye->ssrc[i]) == session->rcv.ssrc) { - rcv_ssrc_match = TRUE; - break; - } - } - if (rcv_ssrc_match) { - if (session->on_rtcp_bye.count > 0) { - /* Get reason. */ - if (reason_space_len > 1) { - uint8_t *reasonbuf = (uint8_t *) rtcp - + sizeof (rtcp_common_header_t) - + sclen; - if (reasonbuf[0] <= reason_space_len-1) - reason = ortp_strndup((char *)(reasonbuf+1), reasonbuf[0]); - else - ortp_debug("Incorrect RTCP BYE reason length"); - } - rtp_signal_table_emit2(&session->on_rtcp_bye, - (long)reason); - if (reason) - ortp_free(reason); - } else { - ortp_debug("Got RTCP BYE without RTCP BYE handler"); - } - } else { - ortp_debug("No SSRC in the BYE packet matched our rcv.ssrc."); - } - break; - } - - case RTCP_APP: - /* to be implemented */ - break; - - - default: - - ortp_debug("Receiving unknown rtcp packet type... discarded"); - return; - - } - - - msgsize -= rtcp_pk_size; /* size of unparsed portion of UDP packet, in octets */ - rtcp = (rtcp_common_header_t *) (rtcp_pk_size + (char *) rtcp); /* pointer to next RTCP packet in current UDP packet */ - - } - - /* The function did not failed sanity checks, write down the RTPC/RTCP - reception time. */ - session->last_recv_time = rcv_time_tv; -} diff --git a/linphone/oRTP/src/rtpparse.c b/linphone/oRTP/src/rtpparse.c deleted file mode 100644 index 9a15ab9db..000000000 --- a/linphone/oRTP/src/rtpparse.c +++ /dev/null @@ -1,236 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include -#include "jitterctl.h" -#include "utils.h" -#include "rtpsession_priv.h" - -#define SSRC_CHANGED_THRESHOLD 50 - -static void queue_packet(queue_t *q, int maxrqsz, mblk_t *mp, rtp_header_t *rtp, int *discarded) -{ - mblk_t *tmp; - int header_size; - *discarded=0; - header_size=RTP_FIXED_HEADER_SIZE+ (4*rtp->cc); - if ((mp->b_wptr - mp->b_rptr)==header_size){ - ortp_debug("Rtp packet contains no data."); - (*discarded)++; - freemsg(mp); - return; - } - /* and then add the packet to the queue */ - - rtp_putq(q,mp); - /* make some checks: q size must not exceed RtpStream::max_rq_size */ - while (q->q_mcount > maxrqsz) - { - /* remove the oldest mblk_t */ - tmp=getq(q); - if (mp!=NULL) - { - ortp_debug("rtp_putq: Queue is full. Discarding message with ts=%i",((rtp_header_t*)mp->b_rptr)->timestamp); - freemsg(tmp); - (*discarded)++; - } - } -} - -void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen) -{ - int i; - rtp_header_t *rtp; - int msgsize; - RtpStream *rtpstream=&session->rtp; - rtp_stats_t *stats=&rtpstream->stats; - - msgsize=mp->b_wptr-mp->b_rptr; - - if (msgsizestats.bad++; - ortp_global_stats.bad++; - freemsg(mp); - return; - } - rtp=(rtp_header_t*)mp->b_rptr; - if (rtp->version!=2) - { - /* try to see if it is a STUN packet */ - uint16_t stunlen=*((uint16_t*)(mp->b_rptr + sizeof(uint16_t))); - stunlen = ntohs(stunlen); - if (stunlen+20==mp->b_wptr-mp->b_rptr){ - /* this looks like a stun packet */ - if (session->eventqs!=NULL){ - OrtpEvent *ev=ortp_event_new(ORTP_EVENT_STUN_PACKET_RECEIVED); - OrtpEventData *ed=ortp_event_get_data(ev); - ed->packet=mp; - ed->ep=rtp_endpoint_new(addr,addrlen); - rtp_session_dispatch_event(session,ev); - return; - } - } - /* discard in two case: the packet is not stun OR nobody is interested by STUN (no eventqs) */ - ortp_debug("Receiving rtp packet with version number !=2...discarded"); - stats->bad++; - ortp_global_stats.bad++; - freemsg(mp); - return; - } - - /* only count non-stun packets. */ - ortp_global_stats.packet_recv++; - stats->packet_recv++; - ortp_global_stats.hw_recv+=msgsize; - stats->hw_recv+=msgsize; - session->rtp.hwrcv_since_last_SR++; - - - /* convert all header data from network order to host order */ - rtp->seq_number=ntohs(rtp->seq_number); - rtp->timestamp=ntohl(rtp->timestamp); - rtp->ssrc=ntohl(rtp->ssrc); - /* convert csrc if necessary */ - if (rtp->cc*sizeof(uint32_t) > (uint32_t) (msgsize-RTP_FIXED_HEADER_SIZE)){ - ortp_debug("Receiving too short rtp packet."); - stats->bad++; - ortp_global_stats.bad++; - freemsg(mp); - return; - } - -#ifndef PERF - /* Write down the last RTP/RTCP packet reception time. */ - gettimeofday(&session->last_recv_time, NULL); -#endif - - for (i=0;icc;i++) - rtp->csrc[i]=ntohl(rtp->csrc[i]); - /*the goal of the following code is to lock on an incoming SSRC to avoid - receiving "mixed streams"*/ - if (session->ssrc_set){ - /*the ssrc is set, so we must check it */ - if (session->rcv.ssrc!=rtp->ssrc){ - if (session->inc_ssrc_candidate==rtp->ssrc){ - session->inc_same_ssrc_count++; - }else{ - session->inc_same_ssrc_count=0; - session->inc_ssrc_candidate=rtp->ssrc; - } - if (session->inc_same_ssrc_count>SSRC_CHANGED_THRESHOLD){ - - /* store the sender rtp address to do symmetric RTP */ - if (!session->use_connect){ - if (session->rtp.socket>0 && session->symmetric_rtp){ - /* store the sender rtp address to do symmetric RTP */ - memcpy(&session->rtp.rem_addr,addr,addrlen); - session->rtp.rem_addrlen=addrlen; - } - } - session->rtp.rcv_last_ts = rtp->timestamp; - session->rcv.ssrc=rtp->ssrc; - rtp_signal_table_emit(&session->on_ssrc_changed); - }else{ - /*discard the packet*/ - ortp_debug("Receiving packet with unknown ssrc."); - stats->bad++; - ortp_global_stats.bad++; - freemsg(mp); - return; - } - } - else{ - /* The SSRC change must not happen if we still receive - ssrc from the initial source. */ - session->inc_same_ssrc_count=0; - } - - }else{ - session->ssrc_set=TRUE; - session->rcv.ssrc=rtp->ssrc; - - if (!session->use_connect){ - if (session->rtp.socket>0 && session->symmetric_rtp){ - /* store the sender rtp address to do symmetric RTP */ - memcpy(&session->rtp.rem_addr,addr,addrlen); - session->rtp.rem_addrlen=addrlen; - } - } - } - - /* update some statistics */ - { - poly32_t *extseq=(poly32_t*)&rtpstream->hwrcv_extseq; - if (rtp->seq_number>extseq->split.lo){ - extseq->split.lo=rtp->seq_number; - }else if (rtp->seq_number<200 && extseq->split.lo>((1<<16) - 200)){ - /* this is a check for sequence number looping */ - extseq->split.lo=rtp->seq_number; - extseq->split.hi++; - } - } - - /* check for possible telephone events */ - if (rtp->paytype==session->rcv.telephone_events_pt){ - queue_packet(&session->rtp.tev_rq,session->rtp.max_rq_size,mp,rtp,&i); - stats->discarded+=i; - ortp_global_stats.discarded+=i; - return; - } - - /* check for possible payload type change, in order to update accordingly our clock-rate dependant - parameters */ - if (session->hw_recv_pt!=rtp->paytype){ - rtp_session_update_payload_type(session,rtp->paytype); - } - - jitter_control_new_packet(&session->rtp.jittctl,rtp->timestamp,local_str_ts); - - if (session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED) { - /* detect timestamp important jumps in the future, to workaround stupid rtp senders */ - if (RTP_TIMESTAMP_IS_NEWER_THAN(rtp->timestamp,session->rtp.rcv_last_ts+session->rtp.ts_jump)){ - ortp_debug("rtp_parse: timestamp jump ?"); - rtp_signal_table_emit2(&session->on_timestamp_jump,(long)&rtp->timestamp); - } - else if (RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts,rtp->timestamp)){ - /* don't queue packets older than the last returned packet to the application*/ - /* Call timstamp jumb in case of - * large negative Ts jump or if ts is set to 0 - */ - - if ( RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts, rtp->timestamp + session->rtp.ts_jump) ){ - ortp_warning("rtp_parse: negative timestamp jump"); - rtp_signal_table_emit2(&session->on_timestamp_jump, - (long)&rtp->timestamp); - } - ortp_debug("rtp_parse: discarding too old packet (ts=%i)",rtp->timestamp); - freemsg(mp); - stats->outoftime++; - ortp_global_stats.outoftime++; - return; - } - } - - queue_packet(&session->rtp.rq,session->rtp.max_rq_size,mp,rtp,&i); - stats->discarded+=i; - ortp_global_stats.discarded+=i; -} - diff --git a/linphone/oRTP/src/rtpsession.c b/linphone/oRTP/src/rtpsession.c deleted file mode 100644 index 795a35983..000000000 --- a/linphone/oRTP/src/rtpsession.c +++ /dev/null @@ -1,1608 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#if defined(WIN32) || defined(_WIN32_WCE) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif - -#include "ortp/ortp.h" -#include "ortp/telephonyevents.h" -#include "ortp/rtcp.h" -#include "jitterctl.h" -#include "scheduler.h" -#include "utils.h" -#include "rtpsession_priv.h" - -extern mblk_t *rtcp_create_simple_bye_packet(uint32_t ssrc, const char *reason); -extern int rtcp_sr_init(RtpSession *session, char *buf, int size); -extern int rtcp_rr_init(RtpSession *session, char *buf, int size); - - - -/* this function initialize all session parameter's that depend on the payload type */ -static void payload_type_changed(RtpSession *session, PayloadType *pt){ - jitter_control_set_payload(&session->rtp.jittctl,pt); - session->rtp.rtcp_report_snt_interval=RTCP_DEFAULT_REPORT_INTERVAL*pt->clock_rate; - rtp_session_set_time_jump_limit(session,session->rtp.time_jump); - if (pt->type==PAYLOAD_VIDEO){ - session->permissive=TRUE; - ortp_message("Using permissive algorithm"); - } - else session->permissive=FALSE; -} - -void wait_point_init(WaitPoint *wp){ - ortp_mutex_init(&wp->lock,NULL); - ortp_cond_init(&wp->cond,NULL); - wp->time=0; - wp->wakeup=FALSE; -} -void wait_point_uninit(WaitPoint *wp){ - ortp_cond_destroy(&wp->cond); - ortp_mutex_destroy(&wp->lock); -} - -#define wait_point_lock(wp) ortp_mutex_lock(&(wp)->lock) -#define wait_point_unlock(wp) ortp_mutex_unlock(&(wp)->lock) - -void wait_point_wakeup_at(WaitPoint *wp, uint32_t t, bool_t dosleep){ - wp->time=t; - wp->wakeup=TRUE; - if (dosleep) ortp_cond_wait(&wp->cond,&wp->lock); -} - - -bool_t wait_point_check(WaitPoint *wp, uint32_t t){ - bool_t ok=FALSE; - - if (wp->wakeup){ - if (TIME_IS_NEWER_THAN(t,wp->time)){ - wp->wakeup=FALSE; - ok=TRUE; - - } - } - return ok; -} -#define wait_point_wakeup(wp) ortp_cond_signal(&(wp)->cond); - -extern void rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts, - struct sockaddr *addr, socklen_t addrlen); - - -static uint32_t uint32_t_random(){ - return random(); -} - - -#define RTP_SEQ_IS_GREATER(seq1,seq2)\ - ((uint16_t)((uint16_t)(seq1) - (uint16_t)(seq2))< (uint16_t)(1<<15)) - -/* put an rtp packet in queue. It is called by rtp_parse()*/ -void rtp_putq(queue_t *q, mblk_t *mp) -{ - mblk_t *tmp; - rtp_header_t *rtp=(rtp_header_t*)mp->b_rptr,*tmprtp; - /* insert message block by increasing time stamp order : the last (at the bottom) - message of the queue is the newest*/ - ortp_debug("rtp_putq(): Enqueuing packet with ts=%i and seq=%i",rtp->timestamp,rtp->seq_number); - - if (qempty(q)) { - putq(q,mp); - return; - } - tmp=qlast(q); - /* we look at the queue from bottom to top, because enqueued packets have a better chance - to be enqueued at the bottom, since there are surely newer */ - while (!qend(q,tmp)) - { - tmprtp=(rtp_header_t*)tmp->b_rptr; - ortp_debug("rtp_putq(): Seeing packet with seq=%i",tmprtp->seq_number); - - if (rtp->seq_number == tmprtp->seq_number) - { - /* this is a duplicated packet. Don't queue it */ - ortp_debug("rtp_putq: duplicated message."); - freemsg(mp); - return; - }else if (RTP_SEQ_IS_GREATER(rtp->seq_number,tmprtp->seq_number)){ - - insq(q,tmp->b_next,mp); - return; - } - tmp=tmp->b_prev; - } - /* this packet is the oldest, it has to be - placed on top of the queue */ - insq(q,qfirst(q),mp); - -} - - - -mblk_t *rtp_getq(queue_t *q,uint32_t timestamp, int *rejected) -{ - mblk_t *tmp,*ret=NULL,*old=NULL; - rtp_header_t *tmprtp; - uint32_t ts_found=0; - - *rejected=0; - ortp_debug("rtp_getq(): Timestamp %i wanted.",timestamp); - - if (qempty(q)) - { - /*ortp_debug("rtp_getq: q is empty.");*/ - return NULL; - } - /* return the packet with ts just equal or older than the asked timestamp */ - /* packets with older timestamps are discarded */ - while ((tmp=qfirst(q))!=NULL) - { - tmprtp=(rtp_header_t*)tmp->b_rptr; - ortp_debug("rtp_getq: Seeing packet with ts=%i",tmprtp->timestamp); - if ( RTP_TIMESTAMP_IS_NEWER_THAN(timestamp,tmprtp->timestamp) ) - { - if (ret!=NULL && tmprtp->timestamp==ts_found) { - /* we've found two packets with same timestamp. return the first one */ - break; - } - if (old!=NULL) { - ortp_debug("rtp_getq: discarding too old packet with ts=%i",ts_found); - (*rejected)++; - freemsg(old); - } - ret=getq(q); /* dequeue the packet, since it has an interesting timestamp*/ - ts_found=tmprtp->timestamp; - ortp_debug("rtp_getq: Found packet with ts=%i",tmprtp->timestamp); - old=ret; - } - else - { - break; - } - } - return ret; -} - -mblk_t *rtp_getq_permissive(queue_t *q,uint32_t timestamp, int *rejected) -{ - mblk_t *tmp,*ret=NULL; - rtp_header_t *tmprtp; - - *rejected=0; - ortp_debug("rtp_getq_permissive(): Timestamp %i wanted.",timestamp); - - if (qempty(q)) - { - /*ortp_debug("rtp_getq: q is empty.");*/ - return NULL; - } - /* return the packet with the older timestamp (provided that it is older than - the asked timestamp) */ - tmp=qfirst(q); - tmprtp=(rtp_header_t*)tmp->b_rptr; - ortp_debug("rtp_getq_permissive: Seeing packet with ts=%i",tmprtp->timestamp); - if ( RTP_TIMESTAMP_IS_NEWER_THAN(timestamp,tmprtp->timestamp) ) - { - ret=getq(q); /* dequeue the packet, since it has an interesting timestamp*/ - ortp_debug("rtp_getq_permissive: Found packet with ts=%i",tmprtp->timestamp); - } - return ret; -} - - -void -rtp_session_init (RtpSession * session, int mode) -{ - JBParameters jbp; - if (session == NULL) - { - ortp_debug("rtp_session_init: Invalid paramter (session=NULL)"); - return; - } - memset (session, 0, sizeof (RtpSession)); - session->mode = (RtpSessionMode) mode; - if ((mode == RTP_SESSION_RECVONLY) || (mode == RTP_SESSION_SENDRECV)) - { - rtp_session_set_flag (session, RTP_SESSION_RECV_SYNC); - rtp_session_set_flag (session, RTP_SESSION_RECV_NOT_STARTED); - - } - if ((mode == RTP_SESSION_SENDONLY) || (mode == RTP_SESSION_SENDRECV)) - { - rtp_session_set_flag (session, RTP_SESSION_SEND_NOT_STARTED); - session->snd.ssrc=uint32_t_random(); - /* set default source description */ - rtp_session_set_source_description(session,"unknown@unknown",NULL,NULL, - NULL,NULL,"oRTP-" ORTP_VERSION,"This is free sofware (LGPL) !"); - } - session->snd.telephone_events_pt=-1; /* not defined a priori */ - session->rcv.telephone_events_pt=-1; /* not defined a priori */ - rtp_session_set_profile (session, &av_profile); /*the default profile to work with */ - session->rtp.socket=-1; - session->rtcp.socket=-1; -#ifndef WIN32 - session->rtp.snd_socket_size=0; /*use OS default value unless on windows where they are definitely too short*/ - session->rtp.rcv_socket_size=0; -#else - session->rtp.snd_socket_size=session->rtp.rcv_socket_size=65536; -#endif - session->dscp=RTP_DEFAULT_DSCP; - session->multicast_ttl=RTP_DEFAULT_MULTICAST_TTL; - session->multicast_loopback=RTP_DEFAULT_MULTICAST_LOOPBACK; - qinit(&session->rtp.rq); - qinit(&session->rtp.tev_rq); - qinit(&session->contributing_sources); - session->eventqs=NULL; - /* init signal tables */ - rtp_signal_table_init (&session->on_ssrc_changed, session,"ssrc_changed"); - rtp_signal_table_init (&session->on_payload_type_changed, session,"payload_type_changed"); - rtp_signal_table_init (&session->on_telephone_event, session,"telephone-event"); - rtp_signal_table_init (&session->on_telephone_event_packet, session,"telephone-event_packet"); - rtp_signal_table_init (&session->on_timestamp_jump,session,"timestamp_jump"); - rtp_signal_table_init (&session->on_network_error,session,"network_error"); - rtp_signal_table_init (&session->on_rtcp_bye,session,"rtcp_bye"); - wait_point_init(&session->snd.wp); - wait_point_init(&session->rcv.wp); - /*defaults send payload type to 0 (pcmu)*/ - rtp_session_set_send_payload_type(session,0); - /*sets supposed recv payload type to undefined */ - rtp_session_set_recv_payload_type(session,-1); - /* configure jitter buffer with working default parameters */ - jbp.min_size=RTP_DEFAULT_JITTER_TIME; - jbp.nom_size=RTP_DEFAULT_JITTER_TIME; - jbp.max_size=-1; - jbp.max_packets= 100;/* maximum number of packet allowed to be queued */ - jbp.adaptive=TRUE; - rtp_session_enable_jitter_buffer(session,TRUE); - rtp_session_set_jitter_buffer_params(session,&jbp); - rtp_session_set_time_jump_limit(session,5000); - rtp_session_enable_rtcp(session,TRUE); - session->recv_buf_size = UDP_MAX_SIZE; - session->symmetric_rtp = FALSE; - session->permissive=FALSE; - msgb_allocator_init(&session->allocator); -} - - -/** - * Creates a new rtp session. - * If the session is able to send data (RTP_SESSION_SENDONLY or - * RTP_SESSION_SENDRECV), then a random SSRC number is choosed for - * the outgoing stream. - * @param mode One of the RtpSessionMode flags. - * - * @return the newly created rtp session. -**/ -RtpSession * -rtp_session_new (int mode) -{ - RtpSession *session; - session = (RtpSession *) ortp_malloc (sizeof (RtpSession)); - if (session == NULL) - { - ortp_error("rtp_session_new: Memory allocation failed"); - return NULL; - } - rtp_session_init (session, mode); - return session; -} - -/** - * Sets the scheduling mode of the rtp session. If @yesno is TRUE, the rtp session is in - * the scheduled mode, that means that you can use session_set_select() to block until it's time - * to receive or send on this session according to the timestamp passed to the respective functions. - * You can also use blocking mode (see rtp_session_set_blocking_mode() ), to simply block within - * the receive and send functions. - * If @yesno is FALSE, the ortp scheduler will not manage those sessions, meaning that blocking mode - * and the use of session_set_select() for this session are disabled. - *@param session a rtp session. - *@param yesno a boolean to indicate the scheduling mode. - * - * -**/ -void -rtp_session_set_scheduling_mode (RtpSession * session, int yesno) -{ - if (yesno) - { - RtpScheduler *sched; - sched = ortp_get_scheduler (); - if (sched != NULL) - { - rtp_session_set_flag (session, RTP_SESSION_SCHEDULED); - session->sched = sched; - rtp_scheduler_add_session (sched, session); - } - else - ortp_warning - ("rtp_session_set_scheduling_mode: Cannot use scheduled mode because the " - "scheduler is not started. Use ortp_scheduler_init() before."); - } - else - rtp_session_unset_flag (session, RTP_SESSION_SCHEDULED); -} - - -/** - * This function implicitely enables the scheduling mode if yesno is TRUE. - * rtp_session_set_blocking_mode() defines the behaviour of the rtp_session_recv_with_ts() and - * rtp_session_send_with_ts() functions. If @yesno is TRUE, rtp_session_recv_with_ts() - * will block until it is time for the packet to be received, according to the timestamp - * passed to the function. After this time, the function returns. - * For rtp_session_send_with_ts(), it will block until it is time for the packet to be sent. - * If @yesno is FALSE, then the two functions will return immediately. - * - * @param session a rtp session - * @param yesno a boolean -**/ -void -rtp_session_set_blocking_mode (RtpSession * session, int yesno) -{ - if (yesno){ - rtp_session_set_scheduling_mode(session,TRUE); - rtp_session_set_flag (session, RTP_SESSION_BLOCKING_MODE); - }else - rtp_session_unset_flag (session, RTP_SESSION_BLOCKING_MODE); -} - -/** - * Set the RTP profile to be used for the session. By default, all session are created by - * rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application - * can set any other profile instead using that function. - * - * @param session a rtp session - * @param profile a rtp profile -**/ - -void -rtp_session_set_profile (RtpSession * session, RtpProfile * profile) -{ - session->snd.profile = profile; - session->rcv.profile = profile; - rtp_session_telephone_events_supported(session); -} - -/** - * By default oRTP automatically sends RTCP SR or RR packets. If - * yesno is set to FALSE, the RTCP sending of packet is disabled. - * This functionnality might be needed for some equipments that do not - * support RTCP, leading to a traffic of ICMP errors on the network. - * It can also be used to save bandwidth despite the RTCP bandwidth is - * actually and usually very very low. -**/ -void rtp_session_enable_rtcp(RtpSession *session, bool_t yesno){ - session->rtcp.enabled=yesno; -} - -/** - * Set the RTP profile to be used for the sending by this session. By default, all session are created by - * rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application - * can set any other profile instead using that function. - * @param session a rtp session - * @param profile a rtp profile - * -**/ - -void -rtp_session_set_send_profile (RtpSession * session, RtpProfile * profile) -{ - session->snd.profile = profile; - rtp_session_send_telephone_events_supported(session); -} - - - -/** - * Set the RTP profile to be used for the receiveing by this session. By default, all session are created by - * rtp_session_new() are initialized with the AV profile, as defined in RFC 3551. The application - * can set any other profile instead using that function. - * - * @param session a rtp session - * @param profile a rtp profile -**/ - -void -rtp_session_set_recv_profile (RtpSession * session, RtpProfile * profile) -{ - session->rcv.profile = profile; - rtp_session_recv_telephone_events_supported(session); -} - -/** - *@param session a rtp session - * - * DEPRECATED! Returns current send profile. - * Use rtp_session_get_send_profile() or rtp_session_get_recv_profile() - * -**/ -RtpProfile *rtp_session_get_profile(RtpSession *session){ - return session->snd.profile; -} - - -/** - *@param session a rtp session - * - * Returns current send profile. - * -**/ -RtpProfile *rtp_session_get_send_profile(RtpSession *session){ - return session->snd.profile; -} - -/** - *@param session a rtp session - * - * Returns current receive profile. - * -**/ -RtpProfile *rtp_session_get_recv_profile(RtpSession *session){ - return session->rcv.profile; -} - -/** - * The default value is UDP_MAX_SIZE bytes, a value which is working for mostly everyone. - * However if your application can make assumption on the sizes of received packet, - * it can be interesting to set it to a lower value in order to save memory. - * - * @param session a rtp session - * @param bufsize max size in bytes for receiving packets -**/ -void rtp_session_set_recv_buf_size(RtpSession *session, int bufsize){ - session->recv_buf_size=bufsize; -} - -/** - * Set kernel send maximum buffer size for the rtp socket. - * A value of zero defaults to the operating system default. -**/ -void rtp_session_set_rtp_socket_send_buffer_size(RtpSession * session, unsigned int size){ - session->rtp.snd_socket_size=size; -} - -/** - * Set kernel recv maximum buffer size for the rtp socket. - * A value of zero defaults to the operating system default. -**/ -void rtp_session_set_rtp_socket_recv_buffer_size(RtpSession * session, unsigned int size){ - session->rtp.rcv_socket_size=size; -} - -/** - * This function provides the way for an application to be informed of various events that - * may occur during a rtp session. @signal is a string identifying the event, and @cb is - * a user supplied function in charge of processing it. The application can register - * several callbacks for the same signal, in the limit of #RTP_CALLBACK_TABLE_MAX_ENTRIES. - * Here are name and meaning of supported signals types: - * - * "ssrc_changed" : the SSRC of the incoming stream has changed. - * - * "payload_type_changed" : the payload type of the incoming stream has changed. - * - * "telephone-event_packet" : a telephone-event rtp packet (RFC2833) is received. - * - * "telephone-event" : a telephone event has occured. This is a high-level shortcut for "telephone-event_packet". - * - * "network_error" : a network error happened on a socket. Arguments of the callback functions are - * a const char * explaining the error, an int errno error code and the user_data as usual. - * - * "timestamp_jump" : we have received a packet with timestamp in far future compared to last timestamp received. - * The farness of far future is set by rtp_sesssion_set_time_jump_limit() - * "rtcp_bye": we have received a RTCP bye packet. Arguments of the callback - * functions are a const char * containing the leaving reason and - * the user_data. - * - * Returns: 0 on success, -EOPNOTSUPP if the signal does not exists, -1 if no more callbacks - * can be assigned to the signal type. - * - * @param session a rtp session - * @param signal_name the name of a signal - * @param cb a RtpCallback - * @param user_data a pointer to any data to be passed when invoking the callback. - * -**/ -int -rtp_session_signal_connect (RtpSession * session, const char *signal_name, - RtpCallback cb, unsigned long user_data) -{ - OList *elem; - for (elem=session->signal_tables;elem!=NULL;elem=o_list_next(elem)){ - RtpSignalTable *s=(RtpSignalTable*) elem->data; - if (strcmp(signal_name,s->signal_name)==0){ - return rtp_signal_table_add(s,cb,user_data); - } - } - ortp_warning ("rtp_session_signal_connect: inexistant signal %s",signal_name); - return -1; -} - - -/** - * Removes callback function @cb to the list of callbacks for signal @signal. - * - * @param session a rtp session - * @param signal_name a signal name - * @param cb a callback function. - * @return: 0 on success, a negative value if the callback was not found. -**/ -int -rtp_session_signal_disconnect_by_callback (RtpSession * session, const char *signal_name, - RtpCallback cb) -{ - OList *elem; - for (elem=session->signal_tables;elem!=NULL;elem=o_list_next(elem)){ - RtpSignalTable *s=(RtpSignalTable*) elem->data; - if (strcmp(signal_name,s->signal_name)==0){ - return rtp_signal_table_remove_by_callback(s,cb); - } - } - ortp_warning ("rtp_session_signal_connect: inexistant signal %s",signal_name); - return -1; -} - - -/** - * sets the initial sequence number of a sending session. - * @param session a rtp session freshly created. - * @param addr a 16 bit unsigned number. - * -**/ -void rtp_session_set_seq_number(RtpSession *session, uint16_t seq){ - session->rtp.snd_seq=seq; -} - - -uint16_t rtp_session_get_seq_number(RtpSession *session){ - return session->rtp.snd_seq; -} - - -/** - * Sets the SSRC for the outgoing stream. - * If not done, a random ssrc is used. - * - * @param session a rtp session. - * @param ssrc an unsigned 32bit integer representing the synchronisation source identifier (SSRC). -**/ -void -rtp_session_set_ssrc (RtpSession * session, uint32_t ssrc) -{ - session->snd.ssrc = ssrc; -} - - -void rtp_session_update_payload_type(RtpSession *session, int paytype){ - /* check if we support this payload type */ - PayloadType *pt=rtp_profile_get_payload(session->rcv.profile,paytype); - if (pt!=0){ - session->hw_recv_pt=paytype; - ortp_message ("payload type changed to %i(%s) !", - paytype,pt->mime_type); - payload_type_changed(session,pt); - }else{ - ortp_warning("Receiving packet with unknown payload type %i.",paytype); - } -} -/** - * Sets the payload type of the rtp session. It decides of the payload types written in the - * of the rtp header for the outgoing stream, if the session is SENDRECV or SENDONLY. - * For payload type in incoming packets, the application can be informed by registering - * for the "payload_type_changed" signal, so that it can make the necessary changes - * on the downstream decoder that deals with the payload of the packets. - * - * @param session a rtp session - * @param paytype the payload type number - * @return 0 on success, -1 if the payload is not defined. -**/ - -int -rtp_session_set_send_payload_type (RtpSession * session, int paytype) -{ - session->snd.pt=paytype; - return 0; -} - -/** - *@param session a rtp session - * - *@return the payload type currently used in outgoing rtp packets -**/ -int rtp_session_get_send_payload_type(const RtpSession *session){ - return session->snd.pt; -} - -/** - * - * Sets the expected payload type for incoming packets. - * If the actual payload type in incoming packets is different that this expected payload type, thus - * the "payload_type_changed" signal is emitted. - * - *@param session a rtp session - *@param paytype the payload type number - *@return 0 on success, -1 if the payload is not defined. -**/ - -int -rtp_session_set_recv_payload_type (RtpSession * session, int paytype) -{ - PayloadType *pt; - session->rcv.pt=paytype; - session->hw_recv_pt=paytype; - pt=rtp_profile_get_payload(session->rcv.profile,paytype); - if (pt!=NULL){ - payload_type_changed(session,pt); - } - return 0; -} - -/** - *@param session a rtp session - * - * @return the payload type currently used in incoming rtp packets -**/ -int rtp_session_get_recv_payload_type(const RtpSession *session){ - return session->rcv.pt; -} - -/** - * Sets the expected payload type for incoming packets and payload type to be used for outgoing packets. - * If the actual payload type in incoming packets is different that this expected payload type, thus - * the "payload_type_changed" signal is emitted. - * - * @param session a rtp session - * @param paytype the payload type number - * @return 0 on success, -1 if the payload is not defined. -**/ -int rtp_session_set_payload_type(RtpSession *session, int pt){ - if (rtp_session_set_send_payload_type(session,pt)<0) return -1; - if (rtp_session_set_recv_payload_type(session,pt)<0) return -1; - return 0; -} - - -static void rtp_header_init_from_session(rtp_header_t *rtp, RtpSession *session){ - rtp->version = 2; - rtp->padbit = 0; - rtp->extbit = 0; - rtp->markbit= 0; - rtp->cc = 0; - rtp->paytype = session->snd.pt; - rtp->ssrc = session->snd.ssrc; - rtp->timestamp = 0; /* set later, when packet is sended */ - /* set a seq number */ - rtp->seq_number=session->rtp.snd_seq; -} - -/** - * Allocates a new rtp packet. In the header, ssrc and payload_type according to the session's - * context. Timestamp is not set, it will be set when the packet is going to be - * sent with rtp_session_sendm_with_ts(). Sequence number is initalized to previous sequence number sent + 1 - * If payload_size is zero, thus an empty packet (just a RTP header) is returned. - * - *@param session a rtp session. - *@param header_size the rtp header size. For standart size (without extensions), it is RTP_FIXED_HEADER_SIZE - *@param payload data to be copied into the rtp packet. - *@param payload_size size of data carried by the rtp packet. - *@return a rtp packet in a mblk_t (message block) structure. -**/ -mblk_t * rtp_session_create_packet(RtpSession *session,int header_size, const uint8_t *payload, int payload_size) -{ - mblk_t *mp; - int msglen=header_size+payload_size; - rtp_header_t *rtp; - - mp=allocb(msglen,BPRI_MED); - rtp=(rtp_header_t*)mp->b_rptr; - rtp_header_init_from_session(rtp,session); - /*copy the payload, if any */ - mp->b_wptr+=header_size; - if (payload_size){ - memcpy(mp->b_wptr,payload,payload_size); - mp->b_wptr+=payload_size; - } - return mp; -} - -/** - * Creates a new rtp packet using the given payload buffer (no copy). The header will be allocated separetely. - * In the header, ssrc and payload_type according to the session's - * context. Timestamp and seq number are not set, there will be set when the packet is going to be - * sent with rtp_session_sendm_with_ts(). - * oRTP will send this packet using libc's sendmsg() (if this function is availlable!) so that there will be no - * packet concatenation involving copies to be done in user-space. - * @freefn can be NULL, in that case payload will be kept untouched. - * - * @param session a rtp session. - * @param payload the data to be sent with this packet - * @param payload_size size of data - * @param freefn a function that will be called when the payload buffer is no more needed. - * @return: a rtp packet in a mblk_t (message block) structure. -**/ - -mblk_t * rtp_session_create_packet_with_data(RtpSession *session, uint8_t *payload, int payload_size, void (*freefn)(void*)) -{ - mblk_t *mp,*mpayload; - int header_size=RTP_FIXED_HEADER_SIZE; /* revisit when support for csrc is done */ - rtp_header_t *rtp; - - mp=allocb(header_size,BPRI_MED); - rtp=(rtp_header_t*)mp->b_rptr; - rtp_header_init_from_session(rtp,session); - mp->b_wptr+=header_size; - /* create a mblk_t around the user supplied payload buffer */ - mpayload=esballoc(payload,payload_size,BPRI_MED,freefn); - mpayload->b_wptr+=payload_size; - /* link it with the header */ - mp->b_cont=mpayload; - return mp; -} - - -/** - * Creates a new rtp packet using the buffer given in arguments (no copy). - * In the header, ssrc and payload_type according to the session's - *context. Timestamp and seq number are not set, there will be set when the packet is going to be - * sent with rtp_session_sendm_with_ts(). - * @freefn can be NULL, in that case payload will be kept untouched. - * - * @param session a rtp session. - * @param buffer a buffer that contains first just enough place to write a RTP header, then the data to send. - * @param size the size of the buffer - * @param freefn a function that will be called once the buffer is no more needed (the data has been sent). - * @return a rtp packet in a mblk_t (message block) structure. -**/ -mblk_t * rtp_session_create_packet_in_place(RtpSession *session,uint8_t *buffer, int size, void (*freefn)(void*) ) -{ - mblk_t *mp; - rtp_header_t *rtp; - - mp=esballoc(buffer,size,BPRI_MED,freefn); - - rtp=(rtp_header_t*)mp->b_rptr; - rtp_header_init_from_session(rtp,session); - return mp; -} - - -int -__rtp_session_sendm_with_ts (RtpSession * session, mblk_t *mp, uint32_t packet_ts, uint32_t send_ts) -{ - rtp_header_t *rtp; - uint32_t packet_time; - int error = 0; - int packsize; - RtpScheduler *sched=session->sched; - RtpStream *stream=&session->rtp; - - if (session->flags & RTP_SESSION_SEND_NOT_STARTED) - { - session->rtp.snd_ts_offset = send_ts; - /* Set initial last_rcv_time to first send time. */ - if ((session->flags & RTP_SESSION_RECV_NOT_STARTED) - || session->mode == RTP_SESSION_SENDONLY) - { - gettimeofday(&session->last_recv_time, NULL); - } - if (session->flags & RTP_SESSION_SCHEDULED) - { - session->rtp.snd_time_offset = sched->time_; - } - rtp_session_unset_flag (session,RTP_SESSION_SEND_NOT_STARTED); - } - /* if we are in blocking mode, then suspend the process until the scheduler it's time to send the - * next packet */ - /* if the timestamp of the packet queued is older than current time, then you we must - * not block */ - if (session->flags & RTP_SESSION_SCHEDULED) - { - wait_point_lock(&session->snd.wp); - packet_time = - rtp_session_ts_to_time (session, - send_ts - - session->rtp.snd_ts_offset) + - session->rtp.snd_time_offset; - /*ortp_message("rtp_session_send_with_ts: packet_time=%i time=%i",packet_time,sched->time_);*/ - if (TIME_IS_STRICTLY_NEWER_THAN (packet_time, sched->time_)) - { - wait_point_wakeup_at(&session->snd.wp,packet_time,(session->flags & RTP_SESSION_BLOCKING_MODE)!=0); - session_set_clr(&sched->w_sessions,session); /* the session has written */ - } - else session_set_set(&sched->w_sessions,session); /*to indicate select to return immediately */ - wait_point_unlock(&session->snd.wp); - } - - if(mp==NULL) {/*for people who just want to be blocked but - do not want to send anything.*/ - session->rtp.snd_last_ts = packet_ts; - return 0; - } - - rtp=(rtp_header_t*)mp->b_rptr; - - packsize = msgdsize(mp) ; - - rtp->timestamp=packet_ts; - if (session->snd.telephone_events_pt==rtp->paytype) - { - rtp->seq_number = session->rtp.snd_seq; - session->rtp.snd_seq++; - } - else - session->rtp.snd_seq=rtp->seq_number+1; - session->rtp.snd_last_ts = packet_ts; - - - ortp_global_stats.sent += packsize; - stream->sent_payload_bytes+=packsize-RTP_FIXED_HEADER_SIZE; - stream->stats.sent += packsize; - ortp_global_stats.packet_sent++; - stream->stats.packet_sent++; - - error = rtp_session_rtp_send (session, mp); - /*send RTCP packet if needed */ - rtp_session_rtcp_process_send(session); - /* receives rtcp packet if session is send-only*/ - /*otherwise it is done in rtp_session_recvm_with_ts */ - if (session->mode==RTP_SESSION_SENDONLY) rtp_session_rtcp_recv(session); - return error; -} - -/** - * Send the rtp datagram @mp to the destination set by rtp_session_set_remote_addr() - * with timestamp @timestamp. For audio data, the timestamp is the number - * of the first sample resulting of the data transmitted. See rfc1889 for details. - * The packet (@mp) is freed once it is sended. - * - *@param session a rtp session. - *@param mp a rtp packet presented as a mblk_t. - *@param timestamp the timestamp of the data to be sent. - * @return the number of bytes sent over the network. -**/ - -int rtp_session_sendm_with_ts(RtpSession *session, mblk_t *packet, uint32_t timestamp){ - return __rtp_session_sendm_with_ts(session,packet,timestamp,timestamp); -} - - - - -/** - * Send a rtp datagram to the destination set by rtp_session_set_remote_addr() containing - * the data from @buffer with timestamp @userts. This is a high level function that uses - * rtp_session_create_packet() and rtp_session_sendm_with_ts() to send the data. - * - *@param session a rtp session. - *@param buffer a buffer containing the data to be sent in a rtp packet. - *@param len the length of the data buffer, in bytes. - *@param userts the timestamp of the data to be sent. Refer to the rfc to know what it is. - * - *@param return the number of bytes sent over the network. -**/ -int -rtp_session_send_with_ts (RtpSession * session, const uint8_t * buffer, int len, - uint32_t userts) -{ - mblk_t *m; - int err; -#ifdef USE_SENDMSG - m=rtp_session_create_packet_with_data(session,(uint8_t*)buffer,len,NULL); -#else - m = rtp_session_create_packet(session,RTP_FIXED_HEADER_SIZE,(uint8_t*)buffer,len); -#endif - err=rtp_session_sendm_with_ts(session,m,userts); - return err; -} - - - -extern void rtcp_parse(RtpSession *session, mblk_t *mp); - - - -static void payload_type_changed_notify(RtpSession *session, int paytype){ - PayloadType *pt = rtp_profile_get_payload(session->rcv.profile,paytype); - if (pt) { - session->rcv.pt = paytype; - rtp_signal_table_emit (&session->on_payload_type_changed); - } -} - - -/** - * Try to get a rtp packet presented as a mblk_t structure from the rtp session. - * The @user_ts parameter is relative to the first timestamp of the incoming stream. In other - * words, the application does not have to know the first timestamp of the stream, it can - * simply call for the first time this function with @user_ts=0, and then incrementing it - * as it want. The RtpSession takes care of synchronisation between the stream timestamp - * and the user timestamp given here. - * - * This function returns the entire packet (with header). - * - * The behaviour of this function has changed since version 0.15.0. Previously the payload data could be - * accessed using mblk_t::b_cont::b_rptr field of the returned mblk_t. - * This is no more the case. - * The convenient way of accessing the payload data is to use rtp_get_payload() : - * @code - * unsigned char *payload; - * int payload_size; - * payload_size=rtp_get_payload(mp,&payload); - * @endcode - * OR simply skip the header this way, the data is then comprised between mp->b_rptr and mp->b_wptr: - * @code - * rtp_get_payload(mp,&mp->b_rptr); - * @endcode - * - * - * @param session a rtp session. - * @param user_ts a timestamp. - * - * @return a rtp packet presented as a mblk_t. -**/ - -mblk_t * -rtp_session_recvm_with_ts (RtpSession * session, uint32_t user_ts) -{ - mblk_t *mp = NULL; - rtp_header_t *rtp; - uint32_t ts; - uint32_t packet_time; - RtpScheduler *sched=session->sched; - RtpStream *stream=&session->rtp; - int rejected=0; - bool_t read_socket=TRUE; - - /* if we are scheduled, remember the scheduler time at which the application has - * asked for its first timestamp */ - - if (session->flags & RTP_SESSION_RECV_NOT_STARTED) - { - session->rtp.rcv_query_ts_offset = user_ts; - /* Set initial last_rcv_time to first recv time. */ - if ((session->flags & RTP_SESSION_SEND_NOT_STARTED) - || session->mode == RTP_SESSION_RECVONLY){ - gettimeofday(&session->last_recv_time, NULL); - } - if (session->flags & RTP_SESSION_SCHEDULED) - { - session->rtp.rcv_time_offset = sched->time_; - //ortp_message("setting snd_time_offset=%i",session->rtp.snd_time_offset); - } - rtp_session_unset_flag (session,RTP_SESSION_RECV_NOT_STARTED); - }else{ - /*prevent reading from the sockets when two - consecutives calls for a same timestamp*/ - if (user_ts==session->rtp.rcv_last_app_ts) - read_socket=FALSE; - } - session->rtp.rcv_last_app_ts = user_ts; - if (read_socket){ - rtp_session_rtp_recv (session, user_ts); - rtp_session_rtcp_recv(session); - } - /* check for telephone event first */ - mp=getq(&session->rtp.tev_rq); - if (mp!=NULL){ - int msgsize=msgdsize(mp); - ortp_global_stats.recv += msgsize; - stream->stats.recv += msgsize; - rtp_signal_table_emit2(&session->on_telephone_event_packet,(long)mp); - rtp_session_check_telephone_events(session,mp); - freemsg(mp); - mp=NULL; - } - - /* then now try to return a media packet, if possible */ - /* first condition: if the session is starting, don't return anything - * until the queue size reaches jitt_comp */ - - if (session->flags & RTP_SESSION_RECV_SYNC) - { - queue_t *q = &session->rtp.rq; - if (qempty(q)) - { - ortp_debug ("Queue is empty."); - goto end; - } - rtp = (rtp_header_t *) qfirst(q)->b_rptr; - session->rtp.rcv_ts_offset = rtp->timestamp; - session->rtp.rcv_last_ret_ts = user_ts; /* just to have an init value */ - session->rcv.ssrc = rtp->ssrc; - /* delete the recv synchronisation flag */ - rtp_session_unset_flag (session, RTP_SESSION_RECV_SYNC); - } - - /*calculate the stream timestamp from the user timestamp */ - ts = jitter_control_get_compensated_timestamp(&session->rtp.jittctl,user_ts); - if (session->rtp.jittctl.enabled==TRUE){ - if (session->permissive) - mp = rtp_getq_permissive(&session->rtp.rq, ts,&rejected); - else{ - mp = rtp_getq(&session->rtp.rq, ts,&rejected); - } - }else mp=getq(&session->rtp.rq);/*no jitter buffer at all*/ - - stream->stats.outoftime+=rejected; - ortp_global_stats.outoftime+=rejected; - - goto end; - - end: - if (mp != NULL) - { - int msgsize = msgdsize (mp); /* evaluate how much bytes (including header) is received by app */ - uint32_t packet_ts; - ortp_global_stats.recv += msgsize; - stream->stats.recv += msgsize; - rtp = (rtp_header_t *) mp->b_rptr; - packet_ts=rtp->timestamp; - ortp_debug("Returning mp with ts=%i", packet_ts); - /* check for payload type changes */ - if (session->rcv.pt != rtp->paytype) - { - payload_type_changed_notify(session, rtp->paytype); - } - /* update the packet's timestamp so that it corrected by the - adaptive jitter buffer mechanism */ - if (session->rtp.jittctl.adaptive){ - uint32_t changed_ts; - /* only update correction offset between packets of different - timestamps*/ - if (packet_ts!=session->rtp.rcv_last_ts) - jitter_control_update_corrective_slide(&session->rtp.jittctl); - changed_ts=packet_ts+session->rtp.jittctl.corrective_slide; - rtp->timestamp=changed_ts; - /*ortp_debug("Returned packet has timestamp %u, with clock slide compensated it is %u",packet_ts,rtp->timestamp);*/ - } - session->rtp.rcv_last_ts = packet_ts; - if (!(session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED)){ - rtp_session_set_flag(session,RTP_SESSION_FIRST_PACKET_DELIVERED); - } - } - else - { - ortp_debug ("No mp for timestamp queried"); - stream->stats.unavaillable++; - ortp_global_stats.unavaillable++; - } - rtp_session_rtcp_process_recv(session); - - if (session->flags & RTP_SESSION_SCHEDULED) - { - /* if we are in blocking mode, then suspend the calling process until timestamp - * wanted expires */ - /* but we must not block the process if the timestamp wanted by the application is older - * than current time */ - wait_point_lock(&session->rcv.wp); - packet_time = - rtp_session_ts_to_time (session, - user_ts - - session->rtp.rcv_query_ts_offset) + - session->rtp.rcv_time_offset; - ortp_debug ("rtp_session_recvm_with_ts: packet_time=%i, time=%i",packet_time, sched->time_); - - if (TIME_IS_STRICTLY_NEWER_THAN (packet_time, sched->time_)) - { - wait_point_wakeup_at(&session->rcv.wp,packet_time, (session->flags & RTP_SESSION_BLOCKING_MODE)!=0); - session_set_clr(&sched->r_sessions,session); - } - else session_set_set(&sched->r_sessions,session); /*to unblock _select() immediately */ - wait_point_unlock(&session->rcv.wp); - } - return mp; -} - - -/** - * NOTE: use of this function is discouraged when sending payloads other than - * pcm/pcmu/pcma/adpcm types. - * rtp_session_recvm_with_ts() does better job. - * - * Tries to read the bytes of the incoming rtp stream related to timestamp ts. In case - * where the user supplied buffer @buffer is not large enough to get all the data - * related to timestamp ts, then *( have_more) is set to 1 to indicate that the application - * should recall the function with the same timestamp to get more data. - * - * When the rtp session is scheduled (see rtp_session_set_scheduling_mode() ), and the - * blocking mode is on (see rtp_session_set_blocking_mode() ), then the calling thread - * is suspended until the timestamp given as argument expires, whatever a received packet - * fits the query or not. - * - * Important note: it is clear that the application cannot know the timestamp of the first - * packet of the incoming stream, because it can be random. The @ts timestamp given to the - * function is used relatively to first timestamp of the stream. In simple words, 0 is a good - * value to start calling this function. - * - * This function internally calls rtp_session_recvm_with_ts() to get a rtp packet. The content - * of this packet is then copied into the user supplied buffer in an intelligent manner: - * the function takes care of the size of the supplied buffer and the timestamp given in - * argument. Using this function it is possible to read continous audio data (e.g. pcma,pcmu...) - * with for example a standart buffer of size of 160 with timestamp incrementing by 160 while the incoming - * stream has a different packet size. - * - *Returns: if a packet was availlable with the corresponding timestamp supplied in argument - * then the number of bytes written in the user supplied buffer is returned. If no packets - * are availlable, either because the sender has not started to send the stream, or either - * because silence packet are not transmitted, or either because the packet was lost during - * network transport, then the function returns zero. - *@param session a rtp session. - *@param buffer a user supplied buffer to write the data. - *@param len the length in bytes of the user supplied buffer. - *@param ts the timestamp wanted. - *@param have_more the address of an integer to indicate if more data is availlable for the given timestamp. - * -**/ -int rtp_session_recv_with_ts (RtpSession * session, uint8_t * buffer, - int len, uint32_t ts, int * have_more){ - mblk_t *mp=NULL; - int plen,blen=0; - *have_more=0; - while(1){ - if (session->pending){ - mp=session->pending; - session->pending=NULL; - }else { - mp=rtp_session_recvm_with_ts(session,ts); - if (mp!=NULL) rtp_get_payload(mp,&mp->b_rptr); - } - if (mp){ - plen=mp->b_wptr-mp->b_rptr; - if (plen<=len){ - memcpy(buffer,mp->b_rptr,plen); - buffer+=plen; - blen+=plen; - len-=plen; - freemsg(mp); - mp=NULL; - }else{ - memcpy(buffer,mp->b_rptr,len); - mp->b_rptr+=len; - buffer+=len; - blen+=len; - len=0; - session->pending=mp; - *have_more=1; - break; - } - }else break; - } - return blen; -} -/** - * When the rtp session is scheduled and has started to send packets, this function - * computes the timestamp that matches to the present time. Using this function can be - * usefull when sending discontinuous streams. Some time can be elapsed between the end - * of a stream burst and the begin of a new stream burst, and the application may be not - * not aware of this elapsed time. In order to get a valid (current) timestamp to pass to - * #rtp_session_send_with_ts() or #rtp_session_sendm_with_ts(), the application may - * use rtp_session_get_current_send_ts(). - * - * @param session a rtp session. - * @return the current send timestamp for the rtp session. -**/ -uint32_t rtp_session_get_current_send_ts(RtpSession *session) -{ - uint32_t userts; - uint32_t session_time; - RtpScheduler *sched=session->sched; - PayloadType *payload; - payload=rtp_profile_get_payload(session->snd.profile,session->snd.pt); - return_val_if_fail(payload!=NULL, 0); - if ( (session->flags & RTP_SESSION_SCHEDULED)==0 ){ - ortp_warning("can't guess current timestamp because session is not scheduled."); - return 0; - } - session_time=sched->time_-session->rtp.snd_time_offset; - userts= (uint32_t)( ( (double)(session_time) * (double) payload->clock_rate )/ 1000.0) - + session->rtp.snd_ts_offset; - return userts; -} - -/** - * Same thing as rtp_session_get_current_send_ts() except that it's for an incoming stream. - * Works only on scheduled mode. - * - * @param session a rtp session. - * @return the theoritical that would have to be receive now. - * -**/ -uint32_t rtp_session_get_current_recv_ts(RtpSession *session){ - uint32_t userts; - uint32_t session_time; - RtpScheduler *sched=ortp_get_scheduler(); - PayloadType *payload; - payload=rtp_profile_get_payload(session->rcv.profile,session->rcv.pt); - return_val_if_fail(payload!=NULL, 0); - if ( (session->flags & RTP_SESSION_SCHEDULED)==0 ){ - ortp_warning("can't guess current timestamp because session is not scheduled."); - return 0; - } - session_time=sched->time_-session->rtp.rcv_time_offset; - userts= (uint32_t)( ( (double)(session_time) * (double) payload->clock_rate )/ 1000.0) - + session->rtp.rcv_ts_offset; - return userts; -} - -/** - * oRTP has the possibility to inform the application through a callback registered - * with rtp_session_signal_connect about crazy incoming RTP stream that jumps from - * a timestamp N to N+some_crazy_value. This lets the opportunity for the application - * to reset the session in order to resynchronize, or any other action like stopping the call - * and reporting an error. - * @param session the rtp session - * @param ts_step a time interval in miliseconds - * -**/ -void rtp_session_set_time_jump_limit(RtpSession *session, int milisecs){ - uint32_t ts; - session->rtp.time_jump=milisecs; - ts=rtp_session_time_to_ts(session,milisecs); - if (ts==0) session->rtp.ts_jump=1<<31; /* do not detect ts jump */ - else session->rtp.ts_jump=ts; -} - -/** - * Closes the rtp and rtcp sockets. -**/ -void rtp_session_release_sockets(RtpSession *session){ - if (session->rtp.socket>=0) close_socket (session->rtp.socket); - if (session->rtcp.socket>=0) close_socket (session->rtcp.socket); - session->rtp.socket=-1; - session->rtcp.socket=-1; - - session->rtp.tr = 0; - session->rtcp.tr = 0; - - /* don't discard remote addresses, then can be preserved for next use. - session->rtp.rem_addrlen=0; - session->rtcp.rem_addrlen=0; - */ -} - -ortp_socket_t rtp_session_get_rtp_socket(const RtpSession *session){ - return rtp_session_using_transport(session, rtp) ? (session->rtp.tr->t_getsocket)(session->rtp.tr) : session->rtp.socket; -} - -ortp_socket_t rtp_session_get_rtcp_socket(const RtpSession *session){ - return rtp_session_using_transport(session, rtcp) ? (session->rtcp.tr->t_getsocket)(session->rtcp.tr) : session->rtcp.socket; -} - -/** - * Register an event queue. - * An application can use an event queue to get informed about various RTP events. -**/ -void rtp_session_register_event_queue(RtpSession *session, OrtpEvQueue *q){ - session->eventqs=o_list_append(session->eventqs,q); -} - -void rtp_session_unregister_event_queue(RtpSession *session, OrtpEvQueue *q){ - session->eventqs=o_list_remove(session->eventqs,q); -} - -void rtp_session_dispatch_event(RtpSession *session, OrtpEvent *ev){ - OList *it; - int i; - for(i=0,it=session->eventqs;it!=NULL;it=it->next,++i){ - ortp_ev_queue_put((OrtpEvQueue*)it->data,ortp_event_dup(ev)); - } - ortp_event_destroy(ev); -} - - -void rtp_session_uninit (RtpSession * session) -{ - /* first of all remove the session from the scheduler */ - if (session->flags & RTP_SESSION_SCHEDULED) - { - rtp_scheduler_remove_session (session->sched,session); - } - /*flush all queues */ - flushq(&session->rtp.rq, FLUSHALL); - flushq(&session->rtp.tev_rq, FLUSHALL); - - if (session->eventqs!=NULL) o_list_free(session->eventqs); - /* close sockets */ - rtp_session_release_sockets(session); - - wait_point_uninit(&session->snd.wp); - wait_point_uninit(&session->rcv.wp); - if (session->current_tev!=NULL) freemsg(session->current_tev); - if (session->rtp.cached_mp!=NULL) freemsg(session->rtp.cached_mp); - if (session->rtcp.cached_mp!=NULL) freemsg(session->rtcp.cached_mp); - if (session->sd!=NULL) freemsg(session->sd); - - session->signal_tables = o_list_free(session->signal_tables); - msgb_allocator_uninit(&session->allocator); -} - -/** - * Resynchronize to the incoming RTP streams. - * This can be useful to handle discoutinuous timestamps. - * For example, call this function from the timestamp_jump signal handler. - * @param session the rtp session -**/ -void rtp_session_resync(RtpSession *session){ - flushq (&session->rtp.rq, FLUSHALL); - rtp_session_set_flag(session, RTP_SESSION_RECV_SYNC); - rtp_session_unset_flag(session,RTP_SESSION_FIRST_PACKET_DELIVERED); - jitter_control_init(&session->rtp.jittctl,-1,NULL); -} - -/** - * Reset the session: local and remote addresses are kept. It resets timestamp, sequence - * number, and calls rtp_session_resync(). - * - * @param session a rtp session. -**/ -void rtp_session_reset (RtpSession * session) -{ - rtp_session_set_flag (session, RTP_SESSION_RECV_NOT_STARTED); - rtp_session_set_flag (session, RTP_SESSION_SEND_NOT_STARTED); - //session->ssrc=0; - session->rtp.snd_time_offset = 0; - session->rtp.snd_ts_offset = 0; - session->rtp.snd_rand_offset = 0; - session->rtp.snd_last_ts = 0; - session->rtp.rcv_time_offset = 0; - session->rtp.rcv_ts_offset = 0; - session->rtp.rcv_query_ts_offset = 0; - session->rtp.rcv_last_ts = 0; - session->rtp.rcv_last_app_ts = 0; - session->rtp.hwrcv_extseq = 0; - session->rtp.hwrcv_since_last_SR=0; - session->rtp.snd_seq = 0; - session->rtp.sent_payload_bytes=0; - rtp_session_clear_send_error_code(session); - rtp_session_clear_recv_error_code(session); - rtp_stats_reset(&session->rtp.stats); - rtp_session_resync(session); - session->ssrc_set=FALSE; -} - -/** - * Retrieve the session's statistics. -**/ -const rtp_stats_t * rtp_session_get_stats(const RtpSession *session){ - return &session->rtp.stats; -} - -void rtp_session_reset_stats(RtpSession *session){ - memset(&session->rtp.stats,0,sizeof(rtp_stats_t)); -} - -/** - * Stores some application specific data into the session, so that it is easy to retrieve it from the signal callbacks using rtp_session_get_data(). - * @param session a rtp session - * @param data an opaque pointer to be stored in the session -**/ - -void rtp_session_set_data(RtpSession *session, void *data){ - session->user_data=data; -} - -/** - * @param session a rtp session - * @return the void pointer previously set using rtp_session_set_data() -**/ -void *rtp_session_get_data(const RtpSession *session){ - return session->user_data; -} - -/** - * Enable or disable the "rtp symmetric" hack which consists of the following: - * after the first packet is received, the source address of the packet - * is set to be the destination address for all next packets. - * This is useful to pass-through firewalls. - * @param session a rtp session - * @param yesno a boolean to enable or disable the feature - * -**/ -void -rtp_session_set_symmetric_rtp (RtpSession * session, bool_t yesno) -{ - session->symmetric_rtp =yesno; -} - -/** - * If yesno is TRUE, thus a connect() syscall is done on the socket to - * the destination address set by rtp_session_set_remote_addr(), or - * if the session does symmetric rtp (see rtp_session_set_symmetric_rtp()) - * a the connect() is done to the source address of the first packet received. - * Connecting a socket has effect of rejecting all incoming packets that - * don't come from the address specified in connect(). - * It also makes ICMP errors (such as connection refused) available to the - * application. - * @param session a rtp session - * @param yesno a boolean to enable or disable the feature - * -**/ -void rtp_session_set_connected_mode(RtpSession *session, bool_t yesno){ - session->use_connect=yesno; -} - -static float compute_bw(struct timeval *orig, unsigned int bytes){ - struct timeval current; - float bw; - float time; - if (bytes==0) return 0; - gettimeofday(¤t,NULL); - time=(float)(current.tv_sec - orig->tv_sec) + - ((float)(current.tv_usec - orig->tv_usec)*1e-6); - bw=((float)bytes)*8/(time+0.001); - /*+0.0001 avoids a division by zero without changing the results significatively*/ - return bw; -} - -float rtp_session_compute_recv_bandwidth(RtpSession *session){ - float bw; - bw=compute_bw(&session->rtp.recv_bw_start,session->rtp.recv_bytes); - session->rtp.recv_bytes=0; - return bw; -} - -float rtp_session_compute_send_bandwidth(RtpSession *session){ - float bw; - bw=compute_bw(&session->rtp.send_bw_start,session->rtp.sent_bytes); - session->rtp.sent_bytes=0; - return bw; -} - -int rtp_session_get_last_send_error_code(RtpSession *session){ - return session->rtp.send_errno; -} - -void rtp_session_clear_send_error_code(RtpSession *session){ - session->rtp.send_errno=0; -} - -int rtp_session_get_last_recv_error_code(RtpSession *session){ - return session->rtp.recv_errno; -} - -void rtp_session_clear_recv_error_code(RtpSession *session){ - session->rtp.send_errno=0; -} - -/** - * Destroys a rtp session. - * All memory allocated for the RtpSession is freed. - * - * @param session a rtp session. -**/ -void rtp_session_destroy (RtpSession * session) -{ - rtp_session_uninit (session); - ortp_free (session); -} - -void rtp_session_make_time_distorsion(RtpSession *session, int milisec) -{ - session->rtp.snd_time_offset+=milisec; -} - - -/* packet api */ - -void rtp_add_csrc(mblk_t *mp, uint32_t csrc) -{ - rtp_header_t *hdr=(rtp_header_t*)mp->b_rptr; - hdr->csrc[hdr->cc]=csrc; - hdr->cc++; -} - -/** - * Get a pointer to the beginning of the payload data of the RTP packet. - * @param packet a RTP packet represented as a mblk_t - * @param start a pointer to the beginning of the payload data, pointing inside the packet. - * @return the length of the payload data. -**/ -int rtp_get_payload(mblk_t *packet, unsigned char **start){ - unsigned char *tmp; - int header_len=RTP_FIXED_HEADER_SIZE+(rtp_get_cc(packet)*4); - tmp=packet->b_rptr+header_len; - if (tmp>packet->b_wptr){ - if (packet->b_cont!=NULL){ - tmp=packet->b_cont->b_rptr+(header_len- (packet->b_wptr-packet->b_rptr)); - if (tmp<=packet->b_cont->b_wptr){ - *start=tmp; - return packet->b_cont->b_wptr-tmp; - } - } - ortp_warning("Invalid RTP packet"); - return -1; - } - *start=tmp; - return packet->b_wptr-tmp; -} - - -/** - * Gets last time a valid RTP or RTCP packet was received. - * @param session RtpSession to get last receive time from. - * @param tv Pointer to struct timeval to fill. - * -**/ -void -rtp_session_get_last_recv_time(RtpSession *session, struct timeval *tv) -{ -#ifdef PERF - ortp_error("rtp_session_get_last_recv_time() feature disabled."); -#else - *tv = session->last_recv_time; -#endif -} - - - -uint32_t rtp_session_time_to_ts(RtpSession *session, int millisecs){ - PayloadType *payload; - payload = - rtp_profile_get_payload (session->snd.profile, - session->snd.pt); - if (payload == NULL) - { - ortp_warning - ("rtp_session_ts_to_t: use of unsupported payload type %d.", session->snd.pt); - return 0; - } - /* the return value is in milisecond */ - return (uint32_t) (payload->clock_rate*(double) (millisecs/1000.0f)); -} - -/* function used by the scheduler only:*/ -uint32_t rtp_session_ts_to_time (RtpSession * session, uint32_t timestamp) -{ - PayloadType *payload; - payload = - rtp_profile_get_payload (session->snd.profile, - session->snd.pt); - if (payload == NULL) - { - ortp_warning - ("rtp_session_ts_to_t: use of unsupported payload type %d.", session->snd.pt); - return 0; - } - /* the return value is in milisecond */ - return (uint32_t) (1000.0 * - ((double) timestamp / - (double) payload->clock_rate)); -} - - -/* time is the number of miliseconds elapsed since the start of the scheduler */ -void rtp_session_process (RtpSession * session, uint32_t time, RtpScheduler *sched) -{ - wait_point_lock(&session->snd.wp); - if (wait_point_check(&session->snd.wp,time)){ - session_set_set(&sched->w_sessions,session); - wait_point_wakeup(&session->snd.wp); - } - wait_point_unlock(&session->snd.wp); - - wait_point_lock(&session->rcv.wp); - if (wait_point_check(&session->rcv.wp,time)){ - session_set_set(&sched->r_sessions,session); - wait_point_wakeup(&session->rcv.wp); - } - wait_point_unlock(&session->rcv.wp); -} - diff --git a/linphone/oRTP/src/rtpsession_inet.c b/linphone/oRTP/src/rtpsession_inet.c deleted file mode 100644 index 0ec5a7526..000000000 --- a/linphone/oRTP/src/rtpsession_inet.c +++ /dev/null @@ -1,1034 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/ortp.h" -#include "utils.h" -#include "ortp/rtpsession.h" -#include "rtpsession_priv.h" - - -#if defined(WIN32) || defined(_WIN32_WCE) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" /*needed for HAVE_SYS_UIO_H */ -#endif - -#ifdef HAVE_SYS_UIO_H -#include -#define USE_SENDMSG 1 -#endif - -#define can_connect(s) ( (s)->use_connect && !(s)->symmetric_rtp) - -static bool_t try_connect(int fd, const struct sockaddr *dest, socklen_t addrlen){ - if (connect(fd,dest,addrlen)<0){ - ortp_warning("Could not connect() socket: %s",getSocketError()); - return FALSE; - } - return TRUE; -} - -static ortp_socket_t create_and_bind(const char *addr, int port, int *sock_family, bool_t reuse_addr){ - int err; - int optval = 1; - ortp_socket_t sock=-1; - -#ifdef ORTP_INET6 - char num[8]; - struct addrinfo hints, *res0, *res; -#else - struct sockaddr_in saddr; -#endif - -#ifdef ORTP_INET6 - - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - snprintf(num, sizeof(num), "%d",port); - err = getaddrinfo(addr,num, &hints, &res0); - if (err!=0) { - ortp_warning ("Error in getaddrinfo on (addr=%s port=%i): %s", addr, port, gai_strerror(err)); - return -1; - } - - for (res = res0; res; res = res->ai_next) { - sock = socket(res->ai_family, res->ai_socktype, 0); - if (sock==-1) - continue; - - if (reuse_addr){ - err = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, - (SOCKET_OPTION_VALUE)&optval, sizeof (optval)); - if (err < 0) - { - ortp_warning ("Fail to set rtp address reusable: %s.", getSocketError()); - } - } - - *sock_family=res->ai_family; - err = bind (sock, res->ai_addr, res->ai_addrlen); - if (err != 0){ - ortp_warning ("Fail to bind rtp socket to (addr=%s port=%i) : %s.", addr,port, getSocketError()); - close_socket (sock); - sock=-1; - continue; - } -#ifndef __hpux - switch (res->ai_family) - { - case AF_INET: - if (IN_MULTICAST(ntohl(((struct sockaddr_in *) res->ai_addr)->sin_addr.s_addr))) - { - struct ip_mreq mreq; - mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *) res->ai_addr)->sin_addr.s_addr; - mreq.imr_interface.s_addr = INADDR_ANY; - err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (SOCKET_OPTION_VALUE) &mreq, sizeof(mreq)); - if (err < 0){ - ortp_warning ("Fail to join address group: %s.", getSocketError()); - close_socket (sock); - sock=-1; - continue; - } - } - break; - case AF_INET6: - if (IN6_IS_ADDR_MULTICAST(&(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr))) - { - struct ipv6_mreq mreq; - mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; - mreq.ipv6mr_interface = 0; - err = setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, (SOCKET_OPTION_VALUE)&mreq, sizeof(mreq)); - if (err < 0) - { - ortp_warning ("Fail to join address group: %s.", getSocketError()); - close_socket (sock); - sock=-1; - continue; - } - } - break; - } -#endif /*hpux*/ - break; - } - freeaddrinfo(res0); -#else - saddr.sin_family = AF_INET; - *sock_family=AF_INET; - err = inet_aton (addr, &saddr.sin_addr); - if (err < 0) - { - ortp_warning ("Error in socket address:%s.", getSocketError()); - return -1; - } - saddr.sin_port = htons (port); - - sock = socket (PF_INET, SOCK_DGRAM, 0); - if (sock==-1) return -1; - - if (reuse_addr){ - err = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, - (SOCKET_OPTION_VALUE)&optval, sizeof (optval)); - if (err < 0) - { - ortp_warning ("Fail to set rtp address reusable: %s.",getSocketError()); - } - } - - err = bind (sock, - (struct sockaddr *) &saddr, - sizeof (saddr)); - - if (err != 0) - { - ortp_warning ("Fail to bind rtp socket to port %i: %s.", port, getSocketError()); - close_socket (sock); - return -1; - } -#endif - if (sock!=-1){ - set_non_blocking_socket (sock); - } - return sock; -} - -static void set_socket_sizes(int sock, unsigned int sndbufsz, unsigned int rcvbufsz){ - int err; - bool_t done=FALSE; - if (sndbufsz>0){ -#ifdef SO_SNDBUFFORCE - err = setsockopt(sock, SOL_SOCKET, SO_SNDBUFFORCE, (void *)&sndbufsz, sizeof(sndbufsz)); - if (err == -1) { - ortp_error("Fail to increase socket's send buffer size with SO_SNDBUFFORCE: %s.", getSocketError()); - }else done=TRUE; -#endif - if (!done){ - err = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *)&sndbufsz, sizeof(sndbufsz)); - if (err == -1) { - ortp_error("Fail to increase socket's send buffer size with SO_SNDBUF: %s.", getSocketError()); - } - } - } - done=FALSE; - if (rcvbufsz>0){ -#ifdef SO_RCVBUFFORCE - err = setsockopt(sock, SOL_SOCKET, SO_RCVBUFFORCE, (void *)&rcvbufsz, sizeof(rcvbufsz)); - if (err == -1) { - ortp_error("Fail to increase socket's recv buffer size with SO_RCVBUFFORCE: %s.", getSocketError()); - } -#endif - if (!done){ - err = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbufsz, sizeof(rcvbufsz)); - if (err == -1) { - ortp_error("Fail to increase socket's recv buffer size with SO_RCVBUF: %s.", getSocketError()); - } - } - - } -} - -static ortp_socket_t create_and_bind_random(const char *localip, int *sock_family, int *port){ - int retry; - ortp_socket_t sock = -1; - for (retry=0;retry<100;retry++) - { - int localport; - do - { - localport = (rand () + 5000) & 0xfffe; - } - while ((localport < 5000) || (localport > 0xffff)); - /*do not set REUSEADDR in case of random allocation */ - sock = create_and_bind(localip, localport, sock_family,FALSE); - if (sock!=-1) { - *port=localport; - return sock; - } - } - ortp_warning("create_and_bind_random: Could not find a random port for %s !",localip); - return -1; -} - -/** - *rtp_session_set_local_addr: - *@session: a rtp session freshly created. - *@addr: a local IP address in the xxx.xxx.xxx.xxx form. - *@port: a local port or -1 to let oRTP choose the port randomly - * - * Specify the local addr to be use to listen for rtp packets or to send rtp packet from. - * In case where the rtp session is send-only, then it is not required to call this function: - * when calling rtp_session_set_remote_addr(), if no local address has been set, then the - * default INADRR_ANY (0.0.0.0) IP address with a random port will be used. Calling - * rtp_sesession_set_local_addr() is mandatory when the session is recv-only or duplex. - * - * Returns: 0 on success. -**/ - -int -rtp_session_set_local_addr (RtpSession * session, const char * addr, int port) -{ - ortp_socket_t sock; - int sockfamily; - bool_t reuse_addr; - if (session->rtp.socket>=0){ - /* don't rebind, but close before*/ - rtp_session_release_sockets(session); - } -#ifdef SO_REUSE_ADDR - reuse_addr=TRUE; -#else - reuse_addr=FALSE; -#endif - /* try to bind the rtp port */ - if (port>0) - sock=create_and_bind(addr,port,&sockfamily,reuse_addr); - else - sock=create_and_bind_random(addr,&sockfamily,&port); - if (sock!=-1){ - set_socket_sizes(sock,session->rtp.snd_socket_size,session->rtp.rcv_socket_size); - session->rtp.sockfamily=sockfamily; - session->rtp.socket=sock; - session->rtp.loc_port=port; - /*try to bind rtcp port */ - sock=create_and_bind(addr,port+1,&sockfamily,reuse_addr); - if (sock!=-1){ - session->rtcp.sockfamily=sockfamily; - session->rtcp.socket=sock; - }else{ - ortp_warning("Could not create and bind rtcp socket."); - } - - /* set socket options (but don't change chosen states) */ - rtp_session_set_dscp( session, -1 ); - rtp_session_set_multicast_ttl( session, -1 ); - rtp_session_set_multicast_loopback( session, -1 ); - - return 0; - } - return -1; -} - - -/** - *rtp_session_set_multicast_ttl: - *@session: a rtp session - *@ttl: desired Multicast Time-To-Live - * - * Sets the TTL (Time-To-Live) for outgoing multicast packets. - * - * Returns: 0 on success. - * -**/ -int rtp_session_set_multicast_ttl(RtpSession *session, int ttl) -{ - int retval; - - // Store new TTL if one is specified - if (ttl>0) session->multicast_ttl = ttl; - - // Don't do anything if socket hasn't been created yet - if (session->rtp.socket < 0) return 0; - - switch (session->rtp.sockfamily) { - case AF_INET: { - - retval= setsockopt(session->rtp.socket, IPPROTO_IP, IP_MULTICAST_TTL, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); - - if (retval<0) break; - - retval= setsockopt(session->rtcp.socket, IPPROTO_IP, IP_MULTICAST_TTL, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); - - } break; -#ifdef ORTP_INET6 - case AF_INET6: { - - retval= setsockopt(session->rtp.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); - - if (retval<0) break; - - retval= setsockopt(session->rtcp.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); - - } break; -#endif - default: - retval=-1; - } - - if (retval<0) - ortp_warning("Failed to set multicast TTL on socket."); - - - return retval; -} - - -/** - *rtp_session_get_multicast_ttl: - *@session: a rtp session - * - * Returns the TTL (Time-To-Live) for outgoing multicast packets. - * -**/ -int rtp_session_get_multicast_ttl(RtpSession *session) -{ - return session->multicast_ttl; -} - - -/** - *rtp_session_set_multicast_loopback: - *@session: a rtp session - *@ttl: desired Multicast Time-To-Live - * - * Sets the TTL (Time-To-Live) for outgoing multicast packets. - * - * Returns: 0 on success. - * -**/ -int rtp_session_set_multicast_loopback(RtpSession *session, int yesno) -{ - int retval; - - // Store new loopback state if one is specified - if (yesno==0) { - // Don't loop back - session->multicast_loopback = 0; - } else if (yesno>0) { - // Do loop back - session->multicast_loopback = 1; - } - - // Don't do anything if socket hasn't been created yet - if (session->rtp.socket < 0) return 0; - - switch (session->rtp.sockfamily) { - case AF_INET: { - - retval= setsockopt(session->rtp.socket, IPPROTO_IP, IP_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); - - if (retval<0) break; - - retval= setsockopt(session->rtcp.socket, IPPROTO_IP, IP_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); - - } break; -#ifdef ORTP_INET6 - case AF_INET6: { - - retval= setsockopt(session->rtp.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); - - if (retval<0) break; - - retval= setsockopt(session->rtcp.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); - - } break; -#endif - default: - retval=-1; - } - - if (retval<0) - ortp_warning("Failed to set multicast loopback on socket."); - - - return retval; -} - - -/** - *rtp_session_get_multicast_loopback: - *@session: a rtp session - * - * Returns the multicast loopback state of rtp session (true or false). - * -**/ -int rtp_session_get_multicast_loopback(RtpSession *session) -{ - return session->multicast_loopback; -} - -/** - *rtp_session_set_dscp: - *@session: a rtp session - *@dscp: desired DSCP PHB value - * - * Sets the DSCP (Differentiated Services Code Point) for outgoing RTP packets. - * - * Returns: 0 on success. - * -**/ -int rtp_session_set_dscp(RtpSession *session, int dscp){ - int retval=0; - int tos; - - // Store new DSCP value if one is specified - if (dscp>=0) session->dscp = dscp; - - // Don't do anything if socket hasn't been created yet - if (session->rtp.socket < 0) return 0; - - // DSCP value is in the upper six bits of the TOS field - tos = (session->dscp << 2) & 0xFC; - switch (session->rtp.sockfamily) { - case AF_INET: - retval = setsockopt(session->rtp.socket, IPPROTO_IP, IP_TOS, (SOCKET_OPTION_VALUE)&tos, sizeof(tos)); - break; -#ifdef ORTP_INET6 - case AF_INET6: -# ifdef IPV6_TCLASS /*seems not defined by my libc*/ - retval = setsockopt(session->rtp.socket, IPPROTO_IPV6, IPV6_TCLASS, - (SOCKET_OPTION_VALUE)&tos, sizeof(tos)); -# else - /*in case that works:*/ - retval = setsockopt(session->rtp.socket, IPPROTO_IPV6, IP_TOS, - (SOCKET_OPTION_VALUE)&tos, sizeof(tos)); -#endif - break; -#endif - default: - retval=-1; - } - if (retval<0) - ortp_warning("Failed to set DSCP value on socket."); - - return retval; -} - - -/** - *rtp_session_get_dscp: - *@session: a rtp session - * - * Returns the DSCP (Differentiated Services Code Point) for outgoing RTP packets. - * -**/ -int rtp_session_get_dscp(const RtpSession *session) -{ - return session->dscp; -} - - -/** - *rtp_session_get_local_port: - *@session: a rtp session for which rtp_session_set_local_addr() or rtp_session_set_remote_addr() has been called - * - * This function can be useful to retrieve the local port that was randomly choosen by - * rtp_session_set_remote_addr() when rtp_session_set_local_addr() was not called. - * - * Returns: the local port used to listen for rtp packets, -1 if not set. -**/ - -int rtp_session_get_local_port(const RtpSession *session){ - return (session->rtp.loc_port>0) ? session->rtp.loc_port : -1; -} - - -static char * ortp_inet_ntoa(struct sockaddr *addr, int addrlen, char *dest, int destlen){ -#ifdef ORTP_INET6 - int err; - dest[0]=0; - err=getnameinfo(addr,addrlen,dest,destlen,NULL,0,NI_NUMERICHOST); - if (err!=0){ - ortp_warning("getnameinfo error: %s",gai_strerror(err)); - } -#else - char *tmp=inet_ntoa(((struct sockaddr_in*)addr)->sin_addr); - strncpy(dest,tmp,destlen); - dest[destlen-1]='\0'; -#endif - return dest; -} - -/** - *rtp_session_set_remote_addr: - *@session: a rtp session freshly created. - *@addr: a local IP address in the xxx.xxx.xxx.xxx form. - *@port: a local port. - * - * Sets the remote address of the rtp session, ie the destination address where rtp packet - * are sent. If the session is recv-only or duplex, it also sets the origin of incoming RTP - * packets. Rtp packets that don't come from addr:port are discarded. - * - * Returns: 0 on success. -**/ -int -rtp_session_set_remote_addr (RtpSession * session, const char * addr, int port){ - return rtp_session_set_remote_addr_full (session, addr, port, port+1); -} - -/** - *rtp_session_set_remote_addr_full: - *@session: a rtp session freshly created. - *@addr: a local IP address in the xxx.xxx.xxx.xxx form. - *@rtp_port: a local rtp port. - *@rtcp_port: a local rtcp port. - * - * Sets the remote address of the rtp session, ie the destination address where rtp packet - * are sent. If the session is recv-only or duplex, it also sets the origin of incoming RTP - * packets. Rtp packets that don't come from addr:port are discarded. - * - * Returns: 0 on success. -**/ - -int -rtp_session_set_remote_addr_full (RtpSession * session, const char * addr, int rtp_port, int rtcp_port) -{ - int err; -#ifdef ORTP_INET6 - struct addrinfo hints, *res0, *res; - char num[8]; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - snprintf(num, sizeof(num), "%d", rtp_port); - err = getaddrinfo(addr, num, &hints, &res0); - if (err) { - ortp_warning ("Error in socket address: %s", gai_strerror(err)); - return -1; - } -#endif - if (session->rtp.socket == -1){ - /* the session has not its socket bound, do it */ - ortp_message ("Setting random local addresses."); -#ifdef ORTP_INET6 - /* bind to an address type that matches the destination address */ - if (res0->ai_addr->sa_family==AF_INET6) - err = rtp_session_set_local_addr (session, "::", -1); - else err=rtp_session_set_local_addr (session, "0.0.0.0", -1); -#else - err = rtp_session_set_local_addr (session, "0.0.0.0", -1); -#endif - if (err<0) return -1; - } - -#ifdef ORTP_INET6 - err=1; - for (res = res0; res; res = res->ai_next) { - /* set a destination address that has the same type as the local address */ - if (res->ai_family==session->rtp.sockfamily ) { - memcpy( &session->rtp.rem_addr, res->ai_addr, res->ai_addrlen); - session->rtp.rem_addrlen=res->ai_addrlen; - err=0; - break; - } - } - freeaddrinfo(res0); - if (err) { - ortp_warning("Could not set destination for RTP socket to %s:%i.",addr,rtp_port); - return -1; - } - - memset(&hints, 0, sizeof(hints)); - hints.ai_family = PF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; - snprintf(num, sizeof(num), "%d", rtcp_port); - err = getaddrinfo(addr, num, &hints, &res0); - if (err) { - ortp_warning ("Error: %s", gai_strerror(err)); - return err; - } - err=1; - for (res = res0; res; res = res->ai_next) { - /* set a destination address that has the same type as the local address */ - if (res->ai_family==session->rtp.sockfamily ) { - err=0; - memcpy( &session->rtcp.rem_addr, res->ai_addr, res->ai_addrlen); - session->rtcp.rem_addrlen=res->ai_addrlen; - break; - } - } - freeaddrinfo(res0); - if (err) { - ortp_warning("Could not set destination for RCTP socket to %s:%i.",addr,rtcp_port); - return -1; - } -#else - session->rtp.rem_addrlen=sizeof(session->rtp.rem_addr); - session->rtp.rem_addr.sin_family = AF_INET; - - err = inet_aton (addr, &session->rtp.rem_addr.sin_addr); - if (err < 0) - { - ortp_warning ("Error in socket address:%s.", getSocketError()); - return err; - } - session->rtp.rem_addr.sin_port = htons (rtp_port); - - memcpy (&session->rtcp.rem_addr, &session->rtp.rem_addr, - sizeof (struct sockaddr_in)); - session->rtcp.rem_addr.sin_port = htons (rtcp_port); - session->rtcp.rem_addrlen=sizeof(session->rtcp.rem_addr); -#endif - if (can_connect(session)){ - if (try_connect(session->rtp.socket,(struct sockaddr*)&session->rtp.rem_addr,session->rtp.rem_addrlen)) - session->flags|=RTP_SOCKET_CONNECTED; - if (session->rtcp.socket>=0){ - if (try_connect(session->rtcp.socket,(struct sockaddr*)&session->rtcp.rem_addr,session->rtcp.rem_addrlen)) - session->flags|=RTCP_SOCKET_CONNECTED; - } - }else if (session->flags & RTP_SOCKET_CONNECTED){ - /*must dissolve association done by connect(). - See connect(2) manpage*/ - struct sockaddr sa; - sa.sa_family=AF_UNSPEC; - if (connect(session->rtp.socket,&sa,sizeof(sa))<0){ - ortp_error("Cannot dissolve connect() association for rtp socket: %s", getSocketError()); - } - if (connect(session->rtcp.socket,&sa,sizeof(sa))<0){ - ortp_error("Cannot dissolve connect() association for rtcp socket: %s", getSocketError()); - } - session->flags&=~RTP_SOCKET_CONNECTED; - session->flags&=~RTCP_SOCKET_CONNECTED; - } - return 0; -} - -int -rtp_session_set_remote_addr_and_port(RtpSession * session, const char * addr, int rtp_port, int rtcp_port){ - return rtp_session_set_remote_addr_full(session,addr,rtp_port,rtcp_port); -} - -void rtp_session_set_sockets(RtpSession *session, int rtpfd, int rtcpfd) -{ - if (rtpfd>=0) set_non_blocking_socket(rtpfd); - if (rtcpfd>=0) set_non_blocking_socket(rtcpfd); - session->rtp.socket=rtpfd; - session->rtcp.socket=rtcpfd; - if (rtpfd>=0 || rtcpfd>=0 ) - session->flags|=(RTP_SESSION_USING_EXT_SOCKETS|RTP_SOCKET_CONNECTED|RTCP_SOCKET_CONNECTED); - else session->flags&=~(RTP_SESSION_USING_EXT_SOCKETS|RTP_SOCKET_CONNECTED|RTCP_SOCKET_CONNECTED); -} - -void rtp_session_set_transports(RtpSession *session, struct _RtpTransport *rtptr, struct _RtpTransport *rtcptr) -{ - session->rtp.tr = rtptr; - session->rtcp.tr = rtcptr; - if (rtptr) - rtptr->session=session; - if (rtcptr) - rtcptr->session=session; - - if (rtptr || rtcptr ) - session->flags|=(RTP_SESSION_USING_TRANSPORT); - else session->flags&=~(RTP_SESSION_USING_TRANSPORT); -} - - - -/** - *rtp_session_flush_sockets: - *@session: a rtp session - * - * Flushes the sockets for all pending incoming packets. - * This can be usefull if you did not listen to the stream for a while - * and wishes to start to receive again. During the time no receive is made - * packets get bufferised into the internal kernel socket structure. - * -**/ -void rtp_session_flush_sockets(RtpSession *session){ - unsigned char trash[4096]; -#ifdef ORTP_INET6 - struct sockaddr_storage from; -#else - struct sockaddr from; -#endif - socklen_t fromlen=sizeof(from); - if (rtp_session_using_transport(session, rtp)) - { - mblk_t *trashmp=esballoc(trash,sizeof(trash),0,NULL); - - while (session->rtp.tr->t_recvfrom(session->rtp.tr,trashmp,0,(struct sockaddr *)&from,&fromlen)>0){}; - - if (session->rtcp.tr) - while (session->rtcp.tr->t_recvfrom(session->rtcp.tr,trashmp,0,(struct sockaddr *)&from,&fromlen)>0){}; - freemsg(trashmp); - return; - } - - if (session->rtp.socket>=0){ - while (recvfrom(session->rtp.socket,(char*)trash,sizeof(trash),0,(struct sockaddr *)&from,&fromlen)>0){}; - } - if (session->rtcp.socket>=0){ - while (recvfrom(session->rtcp.socket,(char*)trash,sizeof(trash),0,(struct sockaddr*)&from,&fromlen)>0){}; - } -} - - -#ifdef USE_SENDMSG -#define MAX_IOV 30 -static int rtp_sendmsg(int sock,mblk_t *m, struct sockaddr *rem_addr, int addr_len){ - int error; - struct msghdr msg; - struct iovec iov[MAX_IOV]; - int iovlen; - for(iovlen=0; iovlenb_cont,iovlen++){ - iov[iovlen].iov_base=m->b_rptr; - iov[iovlen].iov_len=m->b_wptr-m->b_rptr; - } - if (iovlen==MAX_IOV){ - ortp_error("Too long msgb, didn't fit into iov, end discarded."); - } - msg.msg_name=(void*)rem_addr; - msg.msg_namelen=addr_len; - msg.msg_iov=&iov[0]; - msg.msg_iovlen=iovlen; - msg.msg_control=NULL; - msg.msg_controllen=0; - msg.msg_flags=0; - error=sendmsg(sock,&msg,0); - return error; -} -#endif - -#define IP_UDP_OVERHEAD (20+8) - -static void update_sent_bytes(RtpSession*s, int nbytes){ - if (s->rtp.sent_bytes==0){ - gettimeofday(&s->rtp.send_bw_start,NULL); - } - s->rtp.sent_bytes+=nbytes+IP_UDP_OVERHEAD; -} - -static void update_recv_bytes(RtpSession*s, int nbytes){ - if (s->rtp.recv_bytes==0){ - gettimeofday(&s->rtp.recv_bw_start,NULL); - } - s->rtp.recv_bytes+=nbytes+IP_UDP_OVERHEAD; -} - -int -rtp_session_rtp_send (RtpSession * session, mblk_t * m) -{ - int error; - int i; - rtp_header_t *hdr; - struct sockaddr *destaddr=(struct sockaddr*)&session->rtp.rem_addr; - socklen_t destlen=session->rtp.rem_addrlen; - ortp_socket_t sockfd=session->rtp.socket; - - hdr = (rtp_header_t *) m->b_rptr; - /* perform host to network conversions */ - hdr->ssrc = htonl (hdr->ssrc); - hdr->timestamp = htonl (hdr->timestamp); - hdr->seq_number = htons (hdr->seq_number); - for (i = 0; i < hdr->cc; i++) - hdr->csrc[i] = htonl (hdr->csrc[i]); - - if (session->flags & RTP_SOCKET_CONNECTED) { - destaddr=NULL; - destlen=0; - } - - if (rtp_session_using_transport(session, rtp)){ - error = (session->rtp.tr->t_sendto) (session->rtp.tr,m,0,destaddr,destlen); - }else{ -#ifdef USE_SENDMSG - error=rtp_sendmsg(sockfd,m,destaddr,destlen); -#else - if (m->b_cont!=NULL) - msgpullup(m,-1); - error = sendto (sockfd, (char*)m->b_rptr, (int) (m->b_wptr - m->b_rptr), - 0,destaddr,destlen); -#endif - } - if (error < 0){ - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,(long)"Error sending RTP packet",INT_TO_POINTER(getSocketErrorCode())); - }else ortp_warning ("Error sending rtp packet: %s ; socket=%i", getSocketError(), sockfd); - session->rtp.send_errno=getSocketErrorCode(); - }else{ - update_sent_bytes(session,error); - } - freemsg (m); - return error; -} - -int -rtp_session_rtcp_send (RtpSession * session, mblk_t * m) -{ - int error=0; - ortp_socket_t sockfd=session->rtcp.socket; - struct sockaddr *destaddr=(struct sockaddr*)&session->rtcp.rem_addr; - socklen_t destlen=session->rtcp.rem_addrlen; - bool_t using_connected_socket=(session->flags & RTCP_SOCKET_CONNECTED)!=0; - - if (using_connected_socket) { - destaddr=NULL; - destlen=0; - } - - if (session->rtcp.enabled && - ( (sockfd>=0 && (session->rtcp.rem_addrlen>0 ||using_connected_socket)) - || rtp_session_using_transport(session, rtcp) ) ){ - if (rtp_session_using_transport(session, rtcp)){ - error = (session->rtcp.tr->t_sendto) (session->rtcp.tr, m, 0, - destaddr, destlen); - } - else{ -#ifdef USE_SENDMSG - error=rtp_sendmsg(sockfd,m,destaddr, destlen); -#else - if (m->b_cont!=NULL){ - msgpullup(m,-1); - } - error = sendto (sockfd, (char*)m->b_rptr, - (int) (m->b_wptr - m->b_rptr), 0, - destaddr, destlen); -#endif - } - if (error < 0){ - char host[65]; - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,(long)"Error sending RTCP packet",INT_TO_POINTER(getSocketErrorCode())); - }else ortp_warning ("Error sending rtcp packet: %s ; socket=%i; addr=%s", getSocketError(), session->rtcp.socket, ortp_inet_ntoa((struct sockaddr*)&session->rtcp.rem_addr,session->rtcp.rem_addrlen,host,sizeof(host)) ); - } - }else ortp_message("Not sending rtcp report: sockfd=%i, rem_addrlen=%i, connected=%i",sockfd,session->rtcp.rem_addrlen,using_connected_socket); - freemsg (m); - return error; -} - -int -rtp_session_rtp_recv (RtpSession * session, uint32_t user_ts) -{ - int error; - ortp_socket_t sockfd=session->rtp.socket; -#ifdef ORTP_INET6 - struct sockaddr_storage remaddr; -#else - struct sockaddr remaddr; -#endif - socklen_t addrlen = sizeof (remaddr); - mblk_t *mp; - - if ((sockfd<0) && !rtp_session_using_transport(session, rtp)) return -1; /*session has no sockets for the moment*/ - - while (1) - { - int bufsz; - bool_t sock_connected=!!(session->flags & RTP_SOCKET_CONNECTED); - - if (session->rtp.cached_mp==NULL) - session->rtp.cached_mp = msgb_allocator_alloc(&session->allocator,session->recv_buf_size); - mp=session->rtp.cached_mp; - bufsz=(int) (mp->b_datap->db_lim - mp->b_datap->db_base); - if (sock_connected){ - error=recv(sockfd,(char*)mp->b_wptr,bufsz,0); - }else if (rtp_session_using_transport(session, rtp)) - error = (session->rtp.tr->t_recvfrom)(session->rtp.tr, mp, 0, - (struct sockaddr *) &remaddr, - &addrlen); - else error = recvfrom(sockfd, (char*)mp->b_wptr, - bufsz, 0, - (struct sockaddr *) &remaddr, - &addrlen); - if (error > 0){ - if (session->symmetric_rtp && !sock_connected){ - if (session->use_connect){ - /* store the sender rtp address to do symmetric RTP */ - memcpy(&session->rtp.rem_addr,&remaddr,addrlen); - session->rtp.rem_addrlen=addrlen; - if (try_connect(sockfd,(struct sockaddr*)&remaddr,addrlen)) - session->flags|=RTP_SOCKET_CONNECTED; - } - } - /* then parse the message and put on queue */ - mp->b_wptr+=error; - rtp_session_rtp_parse (session, mp, user_ts, (struct sockaddr*)&remaddr,addrlen); - session->rtp.cached_mp=NULL; - /*for bandwidth measurements:*/ - update_recv_bytes(session,error); - } - else - { - int errnum=getSocketErrorCode(); - if (error == 0){ - /*0 can be returned by RtpTransport functions in case of EWOULDBLOCK*/ - /*we ignore it*/ - /*ortp_warning - ("rtp_recv: strange... recv() returned zero.");*/ - } - else if (!is_would_block_error(errnum)) - { - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,(long)"Error receiving RTP packet",INT_TO_POINTER(getSocketErrorCode())); - }else ortp_warning("Error receiving RTP packet: %s.",getSocketError()); - } - /* don't free the cached_mp, it will be reused next time */ - return -1; /* avoids an infinite loop ! */ - } - } - return error; -} - -void rtp_session_notify_inc_rtcp(RtpSession *session, mblk_t *m){ - if (session->eventqs!=NULL){ - OrtpEvent *ev=ortp_event_new(ORTP_EVENT_RTCP_PACKET_RECEIVED); - OrtpEventData *d=ortp_event_get_data(ev); - d->packet=m; - rtp_session_dispatch_event(session,ev); - } - else freemsg(m); /* avoid memory leak */ -} - -int -rtp_session_rtcp_recv (RtpSession * session) -{ - int error; -#ifdef ORTP_INET6 - struct sockaddr_storage remaddr; -#else - struct sockaddr remaddr; -#endif - socklen_t addrlen=0; - mblk_t *mp; - - if (session->rtcp.socket<0 && !rtp_session_using_transport(session, rtcp)) return -1; /*session has no rtcp sockets for the moment*/ - - - while (1) - { - bool_t sock_connected=!!(session->flags & RTCP_SOCKET_CONNECTED); - if (session->rtcp.cached_mp==NULL) - session->rtcp.cached_mp = allocb (RTCP_MAX_RECV_BUFSIZE, 0); - - mp=session->rtcp.cached_mp; - if (sock_connected){ - error=recv(session->rtcp.socket,(char*)mp->b_wptr,RTCP_MAX_RECV_BUFSIZE,0); - }else { - addrlen=sizeof (remaddr); - - if (rtp_session_using_transport(session, rtcp)) - error=(session->rtcp.tr->t_recvfrom)(session->rtcp.tr, mp, 0, - (struct sockaddr *) &remaddr, - &addrlen); - else - error=recvfrom (session->rtcp.socket,(char*) mp->b_wptr, - RTCP_MAX_RECV_BUFSIZE, 0, - (struct sockaddr *) &remaddr, - &addrlen); - } - if (error > 0) - { - mp->b_wptr += error; - /* post an event to notify the application*/ - { - rtp_session_notify_inc_rtcp(session,mp); - } - session->rtcp.cached_mp=NULL; - if (session->symmetric_rtp && !sock_connected){ - /* store the sender rtp address to do symmetric RTP */ - memcpy(&session->rtcp.rem_addr,&remaddr,addrlen); - session->rtcp.rem_addrlen=addrlen; - if (session->use_connect){ - if (try_connect(session->rtcp.socket,(struct sockaddr*)&remaddr,addrlen)) - session->flags|=RTCP_SOCKET_CONNECTED; - } - } - } - else - { - int errnum=getSocketErrorCode(); - - if (error == 0) - { - ortp_warning - ("rtcp_recv: strange... recv() returned zero."); - } - else if (!is_would_block_error(errnum)) - { - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,(long)"Error receiving RTCP packet",INT_TO_POINTER(errnum)); - }else ortp_warning("Error receiving RTCP packet: %s.",getSocketError()); - session->rtp.recv_errno=errnum; - } - /* don't free the cached_mp, it will be reused next time */ - return -1; /* avoids an infinite loop ! */ - } - } - return error; -} - diff --git a/linphone/oRTP/src/rtpsession_priv.h b/linphone/oRTP/src/rtpsession_priv.h deleted file mode 100644 index 24e955669..000000000 --- a/linphone/oRTP/src/rtpsession_priv.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef rtpsession_priv_h -#define rtpsession_priv_h - -#include "ortp/rtpsession.h" - -typedef enum { - RTP_SESSION_RECV_SYNC=1, /* the rtp session is synchronising in the incoming stream */ - RTP_SESSION_FIRST_PACKET_DELIVERED=1<<1, - RTP_SESSION_SCHEDULED=1<<2,/* the scheduler controls this session*/ - RTP_SESSION_BLOCKING_MODE=1<<3, /* in blocking mode */ - RTP_SESSION_RECV_NOT_STARTED=1<<4, /* the application has not started to try to recv */ - RTP_SESSION_SEND_NOT_STARTED=1<<5, /* the application has not started to send something */ - RTP_SESSION_IN_SCHEDULER=1<<6, /* the rtp session is in the scheduler list */ - RTP_SESSION_USING_EXT_SOCKETS=1<<7, /* the session is using externaly supplied sockets */ - RTP_SOCKET_CONNECTED=1<<8, - RTCP_SOCKET_CONNECTED=1<<9, - RTP_SESSION_USING_TRANSPORT=1<<10 -}RtpSessionFlags; - -#define rtp_session_using_transport(s, stream) (((s)->flags & RTP_SESSION_USING_TRANSPORT) && (s->stream.tr != 0)) - -void rtp_session_update_payload_type(RtpSession * session, int pt); -void rtp_putq(queue_t *q, mblk_t *mp); -mblk_t * rtp_getq(queue_t *q, uint32_t ts, int *rejected); -int rtp_session_rtp_recv(RtpSession * session, uint32_t ts); -int rtp_session_rtcp_recv(RtpSession * session); -int rtp_session_rtp_send (RtpSession * session, mblk_t * m); -int rtp_session_rtcp_send (RtpSession * session, mblk_t * m); - -void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen); -void rtp_session_rtcp_parse(RtpSession *session, mblk_t *mp); - -void rtp_session_dispatch_event(RtpSession *session, OrtpEvent *ev); - -#endif diff --git a/linphone/oRTP/src/rtpsignaltable.c b/linphone/oRTP/src/rtpsignaltable.c deleted file mode 100644 index 14d8587b9..000000000 --- a/linphone/oRTP/src/rtpsignaltable.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - - -#include -#include "utils.h" - - -void rtp_signal_table_init(RtpSignalTable *table,RtpSession *session, const char *signal_name) -{ - memset(table,0,sizeof(RtpSignalTable)); - table->session=session; - table->signal_name=signal_name; - session->signal_tables=o_list_append(session->signal_tables,(void*)table); -} - -int rtp_signal_table_add(RtpSignalTable *table,RtpCallback cb, unsigned long user_data) -{ - int i; - - for (i=0;icallback[i]==NULL){ - table->callback[i]=cb; - table->user_data[i]=user_data; - table->count++; - return 0; - } - } - return -1; -} - -void rtp_signal_table_emit(RtpSignalTable *table) -{ - int i,c; - - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,table->user_data[i]); - } - } -} - -void rtp_signal_table_emit2(RtpSignalTable *table,unsigned long arg) -{ - int i,c; - - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,arg,table->user_data[i]); - } - } -} - -void rtp_signal_table_emit3(RtpSignalTable *table, unsigned long arg1, unsigned long arg2) -{ - int i,c; - - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,arg1,arg2,table->user_data[i]); - } - } -} - -int rtp_signal_table_remove_by_callback(RtpSignalTable *table,RtpCallback cb) -{ - int i; - - for (i=0;icallback[i]==cb){ - table->callback[i]=NULL; - table->user_data[i]=0; - table->count--; - return 0; - } - } - return -1; -} diff --git a/linphone/oRTP/src/rtptimer.c b/linphone/oRTP/src/rtptimer.c deleted file mode 100644 index 261be48ff..000000000 --- a/linphone/oRTP/src/rtptimer.c +++ /dev/null @@ -1,33 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/ortp.h" -#include "rtptimer.h" - -void rtp_timer_set_interval(RtpTimer *timer, struct timeval *interval) -{ - if (timer->state==RTP_TIMER_RUNNING){ - ortp_warning("Cannot change timer interval while it is running.\n"); - return; - } - timer->interval.tv_sec=interval->tv_sec; - timer->interval.tv_usec=interval->tv_usec; -} - - diff --git a/linphone/oRTP/src/rtptimer.h b/linphone/oRTP/src/rtptimer.h deleted file mode 100644 index c4a01a456..000000000 --- a/linphone/oRTP/src/rtptimer.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef RTPTIMER_H -#define RTPTIMER_H - -#if !defined(_WIN32) && !defined(_WIN32_WCE) -#include -#else -#include -#include "winsock2.h" -#endif - -#include - - -typedef void (*RtpTimerFunc)(void); - -struct _RtpTimer -{ - int state; -#define RTP_TIMER_RUNNING 1 -#define RTP_TIMER_STOPPED 0 - RtpTimerFunc timer_init; - RtpTimerFunc timer_do; - RtpTimerFunc timer_uninit; - struct timeval interval; -}; - -typedef struct _RtpTimer RtpTimer; - -void rtp_timer_set_interval(RtpTimer *timer, struct timeval *interval); - -extern RtpTimer posix_timer; - -#endif diff --git a/linphone/oRTP/src/scheduler.c b/linphone/oRTP/src/scheduler.c deleted file mode 100644 index 0e53c7bfb..000000000 --- a/linphone/oRTP/src/scheduler.c +++ /dev/null @@ -1,212 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include "utils.h" -#include "scheduler.h" -#include "rtpsession_priv.h" - -// To avoid warning during compile -extern void rtp_session_process (RtpSession * session, uint32_t time, RtpScheduler *sched); - - -void rtp_scheduler_init(RtpScheduler *sched) -{ - sched->list=0; - sched->time_=0; - /* default to the posix timer */ - rtp_scheduler_set_timer(sched,&posix_timer); - ortp_mutex_init(&sched->lock,NULL); - ortp_cond_init(&sched->unblock_select_cond,NULL); - sched->max_sessions=sizeof(SessionSet)*8; - session_set_init(&sched->all_sessions); - sched->all_max=0; - session_set_init(&sched->r_sessions); - sched->r_max=0; - session_set_init(&sched->w_sessions); - sched->w_max=0; - session_set_init(&sched->e_sessions); - sched->e_max=0; -} - -RtpScheduler * rtp_scheduler_new() -{ - RtpScheduler *sched=(RtpScheduler *) ortp_malloc(sizeof(RtpScheduler)); - memset(sched,0,sizeof(RtpScheduler)); - rtp_scheduler_init(sched); - return sched; -} - -void rtp_scheduler_set_timer(RtpScheduler *sched,RtpTimer *timer) -{ - if (sched->thread_running){ - ortp_warning("Cannot change timer while the scheduler is running !!"); - return; - } - sched->timer=timer; - /* report the timer increment */ - sched->timer_inc=(timer->interval.tv_usec/1000) + (timer->interval.tv_sec*1000); -} - -void rtp_scheduler_start(RtpScheduler *sched) -{ - if (sched->thread_running==0){ - sched->thread_running=1; - ortp_mutex_lock(&sched->lock); - ortp_thread_create(&sched->thread, NULL, rtp_scheduler_schedule,(void*)sched); - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); - ortp_mutex_unlock(&sched->lock); - } - else ortp_warning("Scheduler thread already running."); - -} -void rtp_scheduler_stop(RtpScheduler *sched) -{ - if (sched->thread_running==1) - { - sched->thread_running=0; - ortp_thread_join(sched->thread, NULL); - } - else ortp_warning("Scheduler thread is not running."); -} - -void rtp_scheduler_destroy(RtpScheduler *sched) -{ - if (sched->thread_running) rtp_scheduler_stop(sched); - ortp_mutex_destroy(&sched->lock); - //g_mutex_free(sched->unblock_select_mutex); - ortp_cond_destroy(&sched->unblock_select_cond); - ortp_free(sched); -} - -void * rtp_scheduler_schedule(void * psched) -{ - RtpScheduler *sched=(RtpScheduler*) psched; - RtpTimer *timer=sched->timer; - RtpSession *current; - - /* take this lock to prevent the thread to start until g_thread_create() returns - because we need sched->thread to be initialized */ - ortp_mutex_lock(&sched->lock); - ortp_cond_signal(&sched->unblock_select_cond); /* unblock the starting thread */ - ortp_mutex_unlock(&sched->lock); - timer->timer_init(); - while(sched->thread_running) - { - /* do the processing here: */ - ortp_mutex_lock(&sched->lock); - - current=sched->list; - /* processing all scheduled rtp sessions */ - while (current!=NULL) - { - ortp_debug("scheduler: processing session=0x%x.\n",current); - rtp_session_process(current,sched->time_,sched); - current=current->next; - } - /* wake up all the threads that are sleeping in _select() */ - ortp_cond_broadcast(&sched->unblock_select_cond); - ortp_mutex_unlock(&sched->lock); - - /* now while the scheduler is going to sleep, the other threads can compute their - result mask and see if they have to leave, or to wait for next tick*/ - //ortp_message("scheduler: sleeping."); - timer->timer_do(); - sched->time_+=sched->timer_inc; - } - /* when leaving the thread, stop the timer */ - timer->timer_uninit(); - return NULL; -} - -void rtp_scheduler_add_session(RtpScheduler *sched, RtpSession *session) -{ - RtpSession *oldfirst; - int i; - if (session->flags & RTP_SESSION_IN_SCHEDULER){ - /* the rtp session is already scheduled, so return silently */ - return; - } - rtp_scheduler_lock(sched); - /* enqueue the session to the list of scheduled sessions */ - oldfirst=sched->list; - sched->list=session; - session->next=oldfirst; - if (sched->max_sessions==0){ - ortp_error("rtp_scheduler_add_session: max_session=0 !"); - } - /* find a free pos in the session mask*/ - for (i=0;imax_sessions;i++){ - if (!ORTP_FD_ISSET(i,&sched->all_sessions.rtpset)){ - session->mask_pos=i; - session_set_set(&sched->all_sessions,session); - /* make a new session scheduled not blockable if it has not started*/ - if (session->flags & RTP_SESSION_RECV_NOT_STARTED) - session_set_set(&sched->r_sessions,session); - if (session->flags & RTP_SESSION_SEND_NOT_STARTED) - session_set_set(&sched->w_sessions,session); - if (i>sched->all_max){ - sched->all_max=i; - } - break; - } - } - - rtp_session_set_flag(session,RTP_SESSION_IN_SCHEDULER); - rtp_scheduler_unlock(sched); -} - -void rtp_scheduler_remove_session(RtpScheduler *sched, RtpSession *session) -{ - RtpSession *tmp; - int cond=1; - return_if_fail(session!=NULL); - if (!(session->flags & RTP_SESSION_IN_SCHEDULER)){ - /* the rtp session is not scheduled, so return silently */ - return; - } - - rtp_scheduler_lock(sched); - tmp=sched->list; - if (tmp==session){ - sched->list=tmp->next; - rtp_session_unset_flag(session,RTP_SESSION_IN_SCHEDULER); - session_set_clr(&sched->all_sessions,session); - rtp_scheduler_unlock(sched); - return; - } - /* go the position of session in the list */ - while(cond){ - if (tmp!=NULL){ - if (tmp->next==session){ - tmp->next=tmp->next->next; - cond=0; - } - else tmp=tmp->next; - }else { - /* the session was not found ! */ - ortp_warning("rtp_scheduler_remove_session: the session was not found in the scheduler list!"); - cond=0; - } - } - rtp_session_unset_flag(session,RTP_SESSION_IN_SCHEDULER); - /* delete the bit in the mask */ - session_set_clr(&sched->all_sessions,session); - rtp_scheduler_unlock(sched); -} diff --git a/linphone/oRTP/src/scheduler.h b/linphone/oRTP/src/scheduler.h deleted file mode 100644 index 5e15751a2..000000000 --- a/linphone/oRTP/src/scheduler.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef SCHEDULER_H -#define SCHEDULER_H - -#include "ortp/rtpsession.h" -#include "ortp/sessionset.h" -#include "rtptimer.h" - - -struct _RtpScheduler { - - RtpSession *list; /* list of scheduled sessions*/ - SessionSet all_sessions; /* mask of scheduled sessions */ - int all_max; /* the highest pos in the all mask */ - SessionSet r_sessions; /* mask of sessions that have a recv event */ - int r_max; - SessionSet w_sessions; /* mask of sessions that have a send event */ - int w_max; - SessionSet e_sessions; /* mask of session that have error event */ - int e_max; - int max_sessions; /* the number of position in the masks */ - /* GMutex *unblock_select_mutex; */ - ortp_cond_t unblock_select_cond; - ortp_mutex_t lock; - ortp_thread_t thread; - int thread_running; - struct _RtpTimer *timer; - uint32_t time_; /*number of miliseconds elapsed since the start of the thread */ - uint32_t timer_inc; /* the timer increment in milisec */ -}; - -typedef struct _RtpScheduler RtpScheduler; - -RtpScheduler * rtp_scheduler_new(void); -void rtp_scheduler_set_timer(RtpScheduler *sched,RtpTimer *timer); -void rtp_scheduler_start(RtpScheduler *sched); -void rtp_scheduler_stop(RtpScheduler *sched); -void rtp_scheduler_destroy(RtpScheduler *sched); - -void rtp_scheduler_add_session(RtpScheduler *sched, RtpSession *session); -void rtp_scheduler_remove_session(RtpScheduler *sched, RtpSession *session); - -void * rtp_scheduler_schedule(void * sched); - -#define rtp_scheduler_lock(sched) ortp_mutex_lock(&(sched)->lock) -#define rtp_scheduler_unlock(sched) ortp_mutex_unlock(&(sched)->lock) - -/* void rtp_scheduler_add_set(RtpScheduler *sched, SessionSet *set); */ - -RtpScheduler * ortp_get_scheduler(void); -#endif diff --git a/linphone/oRTP/src/sessionset.c b/linphone/oRTP/src/sessionset.c deleted file mode 100644 index 49bee0e8d..000000000 --- a/linphone/oRTP/src/sessionset.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include "scheduler.h" - - -/** - * Allocates and initialize a new empty session set. - * - * @return the empty session set. -**/ -SessionSet * session_set_new() -{ - SessionSet *set=(SessionSet *) ortp_malloc(sizeof(SessionSet)); - session_set_init(set); - return set; -} - - -/** - * Destroys a session set. - * -**/ - -void session_set_destroy(SessionSet *set) -{ - ortp_free(set); -} - -int session_set_and(SessionSet *sched_set, int maxs, SessionSet *user_set, SessionSet *result_set) -{ - uint32_t *mask1,*mask2,*mask3; - int i=0; - int j,ret=0; - mask1=(uint32_t*)(void*)&sched_set->rtpset; - mask2=(uint32_t*)(void*)&user_set->rtpset; - mask3=(uint32_t*)(void*)&result_set->rtpset; - while(i>j) & 1){ - ret++; - } - } - } - i+=32; - mask1++; - mask2++; - mask3++; - } - //printf("session_set_and: ret=%i\n",ret); - return ret; -} - -/** - * This function performs similarly as libc select() function, but performs on #RtpSession - * instead of file descriptors. - * session_set_select() suspends the calling process until some events arrive on one of the - * three sets passed in argument. Two of the sets can be NULL. - * The first set @recvs is interpreted as a set of RtpSession waiting for receive events: - * a new buffer (perhaps empty) is availlable on one or more sessions of the set, or the last - * receive operation with rtp_session_recv_with_ts() would have finished if it were in - * blocking mode. - * The second set is interpreted as a set of RtpSession waiting for send events, i.e. the last - * rtp_session_send_with_ts() call on a session would have finished if it were in blocking mode. - * - * When some events arrived on some of sets, then the function returns and sets are changed - * to indicate the sessions where events happened. - * Sessions can be added to sets using session_set_set(), a session has to be tested to be - * part of a set using session_set_is_set(). - * - * @param recvs a set of rtp sessions to be watched for read events - * @param sends a set of rtp sessions to be watched for write events - * @param errors a set of rtp sessions to be watched for errors - * @return: the number of sessions on which the selected events happened. -**/ -int session_set_select(SessionSet *recvs, SessionSet *sends, SessionSet *errors) -{ - int ret=0,bits; - SessionSet temp; - RtpScheduler *sched=ortp_get_scheduler(); - - /*lock the scheduler to not read the masks while they are being modified by the scheduler*/ - rtp_scheduler_lock(sched); - - while(1){ - /* computes the SessionSet intersection (in the other words mask intersection) between - the mask given by the user and scheduler masks */ - if (recvs!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->r_sessions,sched->all_max,recvs,&temp); - ret+=bits; - /* copy the result set in the given user set (might be empty) */ - if (ret>0) session_set_copy(recvs,&temp); - } - if (sends!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->w_sessions,sched->all_max,sends,&temp); - ret+=bits; - if (ret>0){ - /* copy the result set in the given user set (might be empty)*/ - session_set_copy(sends,&temp); - } - } - if (errors!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->e_sessions,sched->all_max,errors,&temp); - ret+=bits; - if (ret>0){ - /* copy the result set in the given user set */ - session_set_copy(errors,&temp); - } - } - if (ret>0){ - /* there are set file descriptors, return immediately */ - //printf("There are %i sessions set, returning.\n",ret); - rtp_scheduler_unlock(sched); - return ret; - } - //printf("There are %i sessions set.\n",ret); - /* else we wait until the next loop of the scheduler*/ - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); - } - - return -1; -} - -int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout) -{ - int ret=0,bits; - int remainingTime; // duration in ms - SessionSet temp; - RtpScheduler *sched; - if (timeout==NULL) - return session_set_select(recvs, sends, errors); - sched=ortp_get_scheduler(); - remainingTime = timeout->tv_usec/1000 + timeout->tv_sec*1000; - - /*lock the scheduler to not read the masks while they are being modified by the scheduler*/ - rtp_scheduler_lock(sched); - - do { - /* computes the SessionSet intersection (in the other words mask intersection) between - the mask given by the user and scheduler masks */ - if (recvs!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->r_sessions,sched->all_max,recvs,&temp); - ret+=bits; - /* copy the result set in the given user set (might be empty) */ - if (ret>0) session_set_copy(recvs,&temp); - } - if (sends!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->w_sessions,sched->all_max,sends,&temp); - ret+=bits; - if (ret>0){ - /* copy the result set in the given user set (might be empty)*/ - session_set_copy(sends,&temp); - } - } - if (errors!=NULL){ - session_set_init(&temp); - bits=session_set_and(&sched->e_sessions,sched->all_max,errors,&temp); - ret+=bits; - if (ret>0){ - /* copy the result set in the given user set */ - session_set_copy(errors,&temp); - } - } - if (ret>0){ - /* there are set file descriptors, return immediately */ - //printf("There are %i sessions set, returning.\n",ret); - rtp_scheduler_unlock(sched); - return ret; - } - //printf("There are %i sessions set.\n",ret); - /* else we wait until the next loop of the scheduler*/ - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); - remainingTime -= sched->timer_inc; - } while (remainingTime>0); - - return -1; -} diff --git a/linphone/oRTP/src/srtp.c b/linphone/oRTP/src/srtp.c deleted file mode 100644 index 444831d60..000000000 --- a/linphone/oRTP/src/srtp.c +++ /dev/null @@ -1,203 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if defined(_MSC_VER) && (defined(WIN32) || defined(_WIN32_WCE)) -#include "ortp-config-win32.h" -#else -#include "ortp-config.h" -#endif -#include "ortp/ortp.h" - -#ifdef HAVE_SRTP - -#undef PACKAGE_NAME -#undef PACKAGE_STRING -#undef PACKAGE_TARNAME -#undef PACKAGE_VERSION - -#include "ortp/srtp.h" - -#define SRTP_PAD_BYTES 64 /*?? */ - -static int srtp_sendto(RtpTransport *t, mblk_t *m, int flags, const struct sockaddr *to, socklen_t tolen){ - srtp_t srtp=(srtp_t)t->data; - int slen; - err_status_t err; - /* enlarge the buffer for srtp to write its data */ - msgpullup(m,msgdsize(m)+SRTP_PAD_BYTES); - slen=m->b_wptr-m->b_rptr; - err=srtp_protect(srtp,m->b_rptr,&slen); - if (err==err_status_ok){ - return sendto(t->session->rtp.socket,m->b_rptr,slen,flags,to,tolen); - } - ortp_error("srtp_protect() failed"); - return -1; -} - -static int srtp_recvfrom(RtpTransport *t, mblk_t *m, int flags, struct sockaddr *from, socklen_t *fromlen){ - srtp_t srtp=(srtp_t)t->data; - int err; - int slen; - err=recvfrom(t->session->rtp.socket,m->b_wptr,m->b_datap->db_lim-m->b_datap->db_base,flags,from,fromlen); - if (err>0){ - - /* keep NON-RTP data unencrypted */ - rtp_header_t *rtp; - if (err>=RTP_FIXED_HEADER_SIZE) - { - rtp = (rtp_header_t*)m->b_wptr; - if (rtp->version!=2) - { - return err; - } - } - - slen=err; - if (srtp_unprotect(srtp,m->b_wptr,&slen)==err_status_ok) - return slen; - else { - ortp_error("srtp_unprotect() failed"); - return -1; - } - } - return err; -} - -static int srtcp_sendto(RtpTransport *t, mblk_t *m, int flags, const struct sockaddr *to, socklen_t tolen){ - srtp_t srtp=(srtp_t)t->data; - int slen; - /* enlarge the buffer for srtp to write its data */ - msgpullup(m,msgdsize(m)+SRTP_PAD_BYTES); - slen=m->b_wptr-m->b_rptr; - if (srtp_protect_rtcp(srtp,m->b_rptr,&slen)==err_status_ok){ - return sendto(t->session->rtcp.socket,m->b_rptr,slen,flags,to,tolen); - } - ortp_error("srtp_protect_rtcp() failed"); - return -1; -} - -static int srtcp_recvfrom(RtpTransport *t, mblk_t *m, int flags, struct sockaddr *from, socklen_t *fromlen){ - srtp_t srtp=(srtp_t)t->data; - int err; - int slen; - err=recvfrom(t->session->rtcp.socket,m->b_wptr,m->b_datap->db_lim-m->b_datap->db_base,flags,from,fromlen); - if (err>0){ - slen=err; - if (srtp_unprotect_rtcp(srtp,m->b_wptr,&slen)==err_status_ok) - return slen; - else { - ortp_error("srtp_unprotect_rtcp() failed"); - return -1; - } - } - return err; -} - -ortp_socket_t -srtp_getsocket(RtpTransport *t) -{ - return t->session->rtp.socket; -} - -ortp_socket_t -srtcp_getsocket(RtpTransport *t) -{ - return t->session->rtcp.socket; -} - -/** - * Creates a pair of Secure-RTP/Secure-RTCP RtpTransport's. - * oRTP relies on libsrtp (see http://srtp.sf.net ) for secure RTP encryption. - * This function creates a RtpTransport object to be used to the RtpSession using - * rtp_session_set_transport(). - * @srtp: the srtp_t session to be used - * -**/ -int srtp_transport_new(srtp_t srtp, RtpTransport **rtpt, RtpTransport **rtcpt ){ - if (rtpt) { - (*rtpt)=ortp_new(RtpTransport,1); - (*rtpt)->data=srtp; - (*rtpt)->t_getsocket=srtp_getsocket; - (*rtpt)->t_sendto=srtp_sendto; - (*rtpt)->t_recvfrom=srtp_recvfrom; - } - if (rtcpt) { - (*rtcpt)=ortp_new(RtpTransport,1); - (*rtcpt)->data=srtp; - (*rtcpt)->t_getsocket=srtcp_getsocket; - (*rtcpt)->t_sendto=srtcp_sendto; - (*rtcpt)->t_recvfrom=srtcp_recvfrom; - } - return 0; -} - -err_status_t ortp_srtp_init(void) -{ - return srtp_init(); -} - -err_status_t ortp_srtp_create(srtp_t *session, const srtp_policy_t *policy) -{ - int i; - i = srtp_create(session, policy); - return i; -} - -err_status_t ortp_srtp_dealloc(srtp_t session) -{ - return srtp_dealloc(session); -} - -err_status_t ortp_srtp_add_stream(srtp_t session, const srtp_policy_t *policy) -{ - return srtp_add_stream(session, policy); -} - -bool_t ortp_srtp_supported(void){ - return TRUE; -} - -#else - -int srtp_transport_new(void *i, RtpTransport **rtpt, RtpTransport **rtcpt ){ - ortp_error("srtp_transport_new: oRTP has not been compiled with SRTP support."); - return -1; -} - -bool_t ortp_srtp_supported(void){ - return FALSE; -} - -int ortp_srtp_create(void *i, const void *policy) -{ - return -1; -} - -int ortp_srtp_dealloc(void *session) -{ - return -1; -} - -int ortp_srtp_add_stream(void *session, const void *policy) -{ - return -1; -} - -#endif - diff --git a/linphone/oRTP/src/str_utils.c b/linphone/oRTP/src/str_utils.c deleted file mode 100644 index a38620b30..000000000 --- a/linphone/oRTP/src/str_utils.c +++ /dev/null @@ -1,339 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/ortp.h" -#include "ortp/rtp.h" -#include "ortp/str_utils.h" -#include "utils.h" - -void qinit(queue_t *q){ - mblk_init(&q->_q_stopper); - q->_q_stopper.b_next=&q->_q_stopper; - q->_q_stopper.b_prev=&q->_q_stopper; - q->q_mcount=0; -} - -void mblk_init(mblk_t *mp) -{ - mp->b_cont=mp->b_prev=mp->b_next=NULL; - mp->b_rptr=mp->b_wptr=NULL; - mp->reserved1=0; - mp->reserved2=0; -} - -dblk_t *datab_alloc(int size){ - dblk_t *db; - int total_size=sizeof(dblk_t)+size; - db=(dblk_t *) ortp_malloc(total_size); - db->db_base=(uint8_t*)db+sizeof(dblk_t); - db->db_lim=db->db_base+size; - db->db_ref=1; - db->db_freefn=NULL; /* the buffer pointed by db_base must never be freed !*/ - return db; -} - -static inline void datab_ref(dblk_t *d){ - d->db_ref++; -} - -static inline void datab_unref(dblk_t *d){ - d->db_ref--; - if (d->db_ref==0){ - if (d->db_freefn!=NULL) - d->db_freefn(d->db_base); - ortp_free(d); - } -} - - -mblk_t *allocb(int size, int pri) -{ - mblk_t *mp; - dblk_t *datab; - - mp=(mblk_t *) ortp_malloc(sizeof(mblk_t)); - mblk_init(mp); - datab=datab_alloc(size); - - mp->b_datap=datab; - mp->b_rptr=mp->b_wptr=datab->db_base; - mp->b_next=mp->b_prev=mp->b_cont=NULL; - return mp; -} - -mblk_t *esballoc(uint8_t *buf, int size, int pri, void (*freefn)(void*) ) -{ - mblk_t *mp; - dblk_t *datab; - - mp=(mblk_t *) ortp_malloc(sizeof(mblk_t)); - mblk_init(mp); - datab=(dblk_t *) ortp_malloc(sizeof(dblk_t)); - - - datab->db_base=buf; - datab->db_lim=buf+size; - datab->db_ref=1; - datab->db_freefn=freefn; - - mp->b_datap=datab; - mp->b_rptr=mp->b_wptr=buf; - mp->b_next=mp->b_prev=mp->b_cont=NULL; - return mp; -} - - -void freeb(mblk_t *mp) -{ - return_if_fail(mp->b_datap!=NULL); - return_if_fail(mp->b_datap->db_base!=NULL); - - datab_unref(mp->b_datap); - ortp_free(mp); -} - -void freemsg(mblk_t *mp) -{ - mblk_t *tmp1,*tmp2; - tmp1=mp; - while(tmp1!=NULL) - { - tmp2=tmp1->b_cont; - freeb(tmp1); - tmp1=tmp2; - } -} - -mblk_t *dupb(mblk_t *mp) -{ - mblk_t *newm; - return_val_if_fail(mp->b_datap!=NULL,NULL); - return_val_if_fail(mp->b_datap->db_base!=NULL,NULL); - - datab_ref(mp->b_datap); - newm=(mblk_t *) ortp_malloc(sizeof(mblk_t)); - mblk_init(newm); - newm->reserved1=mp->reserved1; - newm->reserved2=mp->reserved2; - newm->b_datap=mp->b_datap; - newm->b_rptr=mp->b_rptr; - newm->b_wptr=mp->b_wptr; - return newm; -} - -/* duplicates a complex mblk_t */ -mblk_t *dupmsg(mblk_t* m) -{ - mblk_t *newm=NULL,*mp,*prev; - prev=newm=dupb(m); - m=m->b_cont; - while (m!=NULL){ - mp=dupb(m); - prev->b_cont=mp; - prev=mp; - m=m->b_cont; - } - return newm; -} - -void putq(queue_t *q,mblk_t *mp) -{ - q->_q_stopper.b_prev->b_next=mp; - mp->b_prev=q->_q_stopper.b_prev; - mp->b_next=&q->_q_stopper; - q->_q_stopper.b_prev=mp; - q->q_mcount++; -} - -mblk_t *getq(queue_t *q) -{ - mblk_t *tmp; - tmp=q->_q_stopper.b_next; - if (tmp==&q->_q_stopper) return NULL; - q->_q_stopper.b_next=tmp->b_next; - tmp->b_next->b_prev=&q->_q_stopper; - tmp->b_prev=NULL; - tmp->b_next=NULL; - q->q_mcount--; - return tmp; -} - -mblk_t * peekq(queue_t *q){ - mblk_t *tmp; - tmp=q->_q_stopper.b_next; - if (tmp==&q->_q_stopper) return NULL; - return tmp; -} - -/* insert mp in q just before emp */ -void insq(queue_t *q,mblk_t *emp, mblk_t *mp) -{ - if (emp==NULL){ - putq(q,mp); - return; - } - q->q_mcount++; - emp->b_prev->b_next=mp; - mp->b_prev=emp->b_prev; - emp->b_prev=mp; - mp->b_next=emp; -} - -void remq(queue_t *q, mblk_t *mp){ - q->q_mcount--; - mp->b_prev->b_next=mp->b_next; - mp->b_next->b_prev=mp->b_prev; - mp->b_next=NULL; - mp->b_prev=NULL; -} - -/* remove and free all messages in the q */ -void flushq(queue_t *q, int how) -{ - mblk_t *mp; - - while ((mp=getq(q))!=NULL) - { - freemsg(mp); - } -} - -int msgdsize(const mblk_t *mp) -{ - int msgsize=0; - while(mp!=NULL){ - msgsize+=(int) (mp->b_wptr-mp->b_rptr); - mp=mp->b_cont; - } - return msgsize; -} - -void msgpullup(mblk_t *mp,int len) -{ - mblk_t *firstm=mp; - dblk_t *db; - int wlen=0; - - if (mp->b_cont==NULL && len==-1) return; /*nothing to do, message is not fragmented */ - - if (len==-1) len=msgdsize(mp); - db=datab_alloc(len); - while(wlenb_wptr-mp->b_rptr; - if (mlen<=remain){ - memcpy(&db->db_base[wlen],mp->b_rptr,mlen); - wlen+=mlen; - mp=mp->b_cont; - }else{ - memcpy(&db->db_base[wlen],mp->b_rptr,remain); - wlen+=remain; - } - } - /*set firstm to point to the new datab */ - freemsg(firstm->b_cont); - firstm->b_cont=NULL; - datab_unref(firstm->b_datap); - firstm->b_datap=db; - firstm->b_rptr=db->db_base; - firstm->b_wptr=firstm->b_rptr+wlen; -} - - -mblk_t *copyb(mblk_t *mp) -{ - mblk_t *newm; - int len=(int) (mp->b_wptr-mp->b_rptr); - newm=allocb(len,BPRI_MED); - memcpy(newm->b_wptr,mp->b_rptr,len); - newm->b_wptr+=len; - return newm; -} - -mblk_t *copymsg(mblk_t *mp) -{ - mblk_t *newm=0,*m; - m=newm=copyb(mp); - mp=mp->b_cont; - while(mp!=NULL){ - m->b_cont=copyb(mp); - m=m->b_cont; - mp=mp->b_cont; - } - return newm; -} - -mblk_t * appendb(mblk_t *mp, const char *data, int size, bool_t pad){ - int padcnt=0; - int i; - if (pad){ - padcnt= (int)(4L-( (long)(((long)mp->b_wptr)+size) % 4L)) % 4L; - } - if ((mp->b_wptr + size +padcnt) > mp->b_datap->db_lim){ - /* buffer is not large enough: append a new block (with the same size ?)*/ - int plen=(int)((char*)mp->b_datap->db_lim - (char*) mp->b_datap->db_base); - mp->b_cont=allocb(MAX(plen,size),0); - mp=mp->b_cont; - } - if (size) memcpy(mp->b_wptr,data,size); - mp->b_wptr+=size; - for (i=0;ib_wptr[0]=0; - mp->b_wptr++; - } - return mp; -} - -void msgappend(mblk_t *mp, const char *data, int size, bool_t pad){ - while(mp->b_cont!=NULL) mp=mp->b_cont; - appendb(mp,data,size,pad); -} - -mblk_t *concatb(mblk_t *mp, mblk_t *newm){ - while (mp->b_cont!=NULL) mp=mp->b_cont; - mp->b_cont=newm; - while(newm->b_cont!=NULL) newm=newm->b_cont; - return newm; -} - -void msgb_allocator_init(msgb_allocator_t *a){ - qinit(&a->q); -} - -mblk_t *msgb_allocator_alloc(msgb_allocator_t *a, int size){ - queue_t *q=&a->q; - mblk_t *m,*found=NULL; - - /*lookup for an unused msgb (data block with ref count ==1)*/ - for(m=qbegin(q);!qend(q,m);m=qnext(q,m)){ - if (m->b_datap->db_ref==1 && m->b_datap->db_lim-m->b_datap->db_base>=size){ - found=m; - break; - } - } - if (found==NULL){ - found=allocb(size,0); - putq(q,found); - } - return dupb(found); -} - -void msgb_allocator_uninit(msgb_allocator_t *a){ - flushq(&a->q,-1); -} diff --git a/linphone/oRTP/src/stun.c b/linphone/oRTP/src/stun.c deleted file mode 100644 index a5d2eb787..000000000 --- a/linphone/oRTP/src/stun.c +++ /dev/null @@ -1,2884 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* ==================================================================== - * The Vovida Software License, Version 1.0 - * - * Copyright (c) 2000 Vovida Networks, 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 names "VOCAL", "Vovida Open Communication Application Library", - * and "Vovida Open Communication Application Library (VOCAL)" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact vocal@vovida.org. - * - * 4. Products derived from this software may not be called "VOCAL", nor - * may "VOCAL" appear in their name, without prior written - * permission of Vovida Networks, Inc. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND - * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA - * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES - * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (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 Vovida - * Networks, Inc. and many individuals on behalf of Vovida Networks, - * Inc. For more information on Vovida Networks, Inc., please see - * . - * - */ - -#ifdef HAVE_CONFIG_H -#include "ortp-config.h" -#endif - -#ifndef _WIN32_WCE -#include -#endif - -#include - -#if defined(WIN32) || defined(_WIN32_WCE) -#include -#include -/* #include */ -#include -#include /*for isdigit() */ -#else - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif - - -#if !defined(HAVE_OPENSSL_HMAC_H) || !defined(HAVE_OPENSSL_MD5_H) -#define NOSSL 1 -#endif - -#include "ortp/stun_udp.h" -#include "ortp/stun.h" -#include "ortp/ortp.h" - -static char *ipaddr(const StunAddress4 *addr) -{ - static char tmp[512]; - struct in_addr inaddr; - char *atmp; - inaddr.s_addr = htonl(addr->addr); - atmp = (char *)inet_ntoa(inaddr); - - snprintf(tmp, 512, "%s:%i", atmp, addr->port); - return tmp; -} - -static bool_t -stunParseAtrAddress( char* body, unsigned int hdrLen, StunAtrAddress4 *result ) -{ - if ( hdrLen != 8 ) - { - ortp_error("stun: hdrLen wrong for Address\n"); - return FALSE; - } - result->pad = *body++; - result->family = *body++; - if (result->family == IPv4Family) - { - uint16_t nport; - uint32_t naddr; - memcpy(&nport, body, 2); body+=2; - result->ipv4.port = ntohs(nport); - - memcpy(&naddr, body, 4); body+=4; - result->ipv4.addr = ntohl(naddr); - return TRUE; - } - else if (result->family == IPv6Family) - { - ortp_error("stun: ipv6 not supported\n"); - } - else - { - ortp_error("stun: bad address family: %i\n", result->family); - } - - return FALSE; -} - -static bool_t -stunParseAtrChangeRequest( char* body, unsigned int hdrLen, StunAtrChangeRequest *result ) -{ - if ( hdrLen != 4 ) - { - /* ortp_error("stun: hdr length = %i expecting %i\n",hdrLen, sizeof(result)); */ - - ortp_error("stun: Incorrect size for SA_CHANGEREQUEST"); - return FALSE; - } - else - { - memcpy(&result->value, body, 4); - result->value = ntohl(result->value); - return TRUE; - } -} - -static bool_t -stunParseAtrError( char* body, unsigned int hdrLen, StunAtrError *result ) -{ - if ( hdrLen < 4 || hdrLen >= 128+4) - { - ortp_error("stun: Incorrect size for SA_ERRORCODE"); - return FALSE; - } - else - { - memcpy(&result->pad, body, 2); body+=2; - result->pad = ntohs(result->pad); - result->errorClass = *body++; - result->number = *body++; - - result->sizeReason = hdrLen - 4; - memcpy(&result->reason, body, result->sizeReason); - result->reason[result->sizeReason] = 0; - return TRUE; - } -} - -static bool_t -stunParseAtrUnknown( char* body, unsigned int hdrLen, StunAtrUnknown *result ) -{ - if ( hdrLen >= sizeof(result) ) - { - ortp_error("stun: Incorrect size for SA_UNKNOWNATTRIBUTE"); - return FALSE; - } - else - { - int i; - if (hdrLen % 4 != 0) return FALSE; - result->numAttributes = hdrLen / 4; - for (i=0; inumAttributes; i++) - { - memcpy(&result->attrType[i], body, 2); body+=2; - result->attrType[i] = ntohs(result->attrType[i]); - } - return TRUE; - } -} - -static bool_t -stunParseAtrString( char* body, unsigned int hdrLen, StunAtrString *result ) -{ - if ( hdrLen >= STUN_MAX_STRING ) - { - ortp_error("stun: String is too large"); - return FALSE; - } - else - { - result->sizeValue = hdrLen; - memcpy(&result->value, body, hdrLen); - result->value[hdrLen] = 0; - return TRUE; - } -} - - -static bool_t -stunParseAtrIntegrity( char* body, unsigned int hdrLen, StunAtrIntegrity *result ) -{ - if ( hdrLen != 20) - { - ortp_error("stun: SA_MESSAGEINTEGRITY must be 20 bytes"); - return FALSE; - } - else - { - memcpy(&result->hash, body, hdrLen); - return TRUE; - } -} - -static bool_t -turnParseAtrChannelNumber( char* body, unsigned int hdrLen, TurnAtrChannelNumber *result ) -{ - if ( hdrLen >= sizeof(result) ) - { - ortp_error("stun: Incorrect size for TA_CHANNELNUMBER"); - return FALSE; - } - else - { - if (hdrLen % 4 != 0) return FALSE; - memcpy(&result->channelNumber, body, 2); - body+=2; - result->channelNumber = ntohs(result->channelNumber); - memcpy(&result->rffu, body, 2); - body+=2; - result->rffu = ntohs(result->rffu); - return TRUE; - } -} - -static bool_t -turnParseAtrLifetime( char* body, unsigned int hdrLen, TurnAtrLifetime *result ) -{ - if ( hdrLen != sizeof(result) ) - { - ortp_error("stun: Incorrect size for TA_LIFETIME"); - return FALSE; - } - else - { - memcpy(&result->lifetime, body, 4); - result->lifetime = ntohl(result->lifetime); - return TRUE; - } -} - -static bool_t -turnParseAtrData( char* body, unsigned int hdrLen, TurnAtrData *result ) -{ - if ( hdrLen >= 1500 ) - { - ortp_error("stun: Incorrect size for TA_DATA"); - return FALSE; - } - else - { - result->sizeValue = hdrLen; - memcpy(&result->value, body, hdrLen); - result->value[hdrLen] = 0; - return TRUE; - } -} - -static bool_t -turnParseAtrRequestedTransport( char* body, unsigned int hdrLen, TurnAtrRequestedTransport *result ) -{ - if ( hdrLen != 4 ) - { - ortp_error("stun: Incorrect size for TA_REQUESTEDTRANSPORT"); - return FALSE; - } - result->proto = *body++; - result->pad1 = *body++; - result->pad2 = *body++; - result->pad3 = *body++; - return TRUE; -} - -#if defined(htonq) -#elif defined(ORTP_BIGENDIAN) -#define htonq(n) n -#define ntohq(n) n -#else /* little endian */ -static inline uint64_t -htonq (uint64_t v) -{ - return htonl ((uint32_t) (v >> 32)) - | (uint64_t) htonl ((uint32_t) v) << 32; -} -static inline uint64_t -ntohq (uint64_t v) -{ - return ntohl ((uint32_t) (v >> 32)) - | (uint64_t) ntohl ((uint32_t) v) << 32; -} -#endif /* little endian */ - -static bool_t -turnParseAtrReservationToken( char* body, unsigned int hdrLen, TurnAtrReservationToken *result ) -{ - if ( hdrLen != 8 ) - { - ortp_error("stun: Incorrect size for TA_RESERVATIONTOKEN"); - return FALSE; - } - memcpy(&result->value, body, 8); - result->value = ntohq(result->value); - return TRUE; -} - -static bool_t -stunParseAtrFingerprint( char* body, unsigned int hdrLen, StunAtrFingerprint *result ) -{ - if ( hdrLen != 4 ) - { - ortp_error("stun: Incorrect size for SA_FINGERPRINT"); - return FALSE; - } - - memcpy(&result->fingerprint, body, 4); - result->fingerprint = ntohl(result->fingerprint); - return TRUE; -} - -static bool_t -iceParseAtrPriority( char* body, unsigned int hdrLen, IceAtrPriority *result ) -{ - if ( hdrLen != 4 ) - { - ortp_error("stun: Incorrect size for ICEA_PRIORITY"); - return FALSE; - } - - memcpy(&result->priority, body, 4); - result->priority = ntohl(result->priority); - return TRUE; -} - -static bool_t -iceParseAtrIceControll( char* body, unsigned int hdrLen, IceAtrIceControll *result ) -{ - if ( hdrLen != 8 ) - { - ortp_error("stun: Incorrect size for ICEA_ICECONTROLLED/ICEA_ICECONTROLLING"); - return FALSE; - } - memcpy(&result->value, body, 8); - result->value = ntohq(result->value); - return TRUE; -} - -bool_t -stunParseMessage( char* buf, unsigned int bufLen, StunMessage *msg) -{ - char* body; - unsigned int size; - ortp_debug("stun: Received stun message: %i bytes\n", bufLen); - memset(msg, 0, sizeof(msg)); - - if (sizeof(StunMsgHdr) > bufLen) - { - ortp_warning("stun: message too short\n"); - return FALSE; - } - - memcpy(&msg->msgHdr, buf, sizeof(StunMsgHdr)); - msg->msgHdr.msgType = ntohs(msg->msgHdr.msgType); - msg->msgHdr.msgLength = ntohs(msg->msgHdr.msgLength); - - if (msg->msgHdr.msgLength + sizeof(StunMsgHdr) != bufLen) - { - ortp_warning("stun: Message header length doesn't match message size: %i - %i\n", msg->msgHdr.msgLength, bufLen); - return FALSE; - } - - body = buf + sizeof(StunMsgHdr); - size = msg->msgHdr.msgLength; - - /*ortp_message("stun: bytes after header = %i\n", size); */ - - while ( size > 0 ) - { - /* !jf! should check that there are enough bytes left in the buffer */ - - StunAtrHdr* attr = (StunAtrHdr*)body; /*reinterpret_cast(body);*/ - - unsigned int attrLen = ntohs(attr->length); - int atrType = ntohs(attr->type); - - if ( attrLen+4 > size ) - { - ortp_error("stun: claims attribute is larger than size of message (attribute type=%i)\n", atrType); - return FALSE; - } - - body += 4; /* skip the length and type in attribute header */ - size -= 4; - - if (atrType == SA_MAPPEDADDRESS) - { - msg->hasMappedAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->mappedAddress )== FALSE ) - { - ortp_error("stun: problem parsing SA_MAPPEDADDRESS\n"); - return FALSE; - } - else - { - ortp_debug("stun: SA_MAPPEDADDRESS = %s\n", ipaddr(&msg->mappedAddress.ipv4)); - } - - } - else if (atrType == SA_RESPONSEADDRESS) - { - msg->hasResponseAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->responseAddress )== FALSE ) - { - ortp_error("stun: problem parsing SA_RESPONSEADDRESS"); - return FALSE; - } - else - { - ortp_debug("stun: SA_RESPONSEADDRESS = %s\n", ipaddr(&msg->responseAddress.ipv4)); - } - } - else if (atrType == SA_CHANGEREQUEST) - { - msg->hasChangeRequest = TRUE; - if (stunParseAtrChangeRequest( body, attrLen, &msg->changeRequest) == FALSE) - { - ortp_error("stun: problem parsing SA_CHANGEREQUEST\n"); - return FALSE; - } - else - { - ortp_debug("stun: SA_CHANGEREQUEST = %i\n", msg->changeRequest.value); - } - } - else if (atrType == SA_SOURCEADDRESS) - { - msg->hasSourceAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->sourceAddress )== FALSE ) - { - ortp_error("stun: problem parsing SA_SOURCEADDRESS\n"); - return FALSE; - } - else - { - ortp_debug("stun: SA_SOURCEADDRESS = %s\n", ipaddr(&msg->sourceAddress.ipv4) ); - } - } - else if (atrType == SA_CHANGEDADDRESS) - { - msg->hasChangedAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->changedAddress )== FALSE ) - { - ortp_error("stun: problem parsing SA_CHANGEDADDRESS\n"); - return FALSE; - } - else - { - ortp_debug("stun: SA_CHANGEDADDRESS = %s\n", ipaddr(&msg->changedAddress.ipv4)); - } - } - else if (atrType == SA_USERNAME) - { - msg->hasUsername = TRUE; - if (stunParseAtrString( body, attrLen, &msg->username) == FALSE) - { - ortp_error("stun: problem parsing SA_USERNAME"); - return FALSE; - } - else - { - ortp_debug("stun: SA_USERNAME = %s\n", msg->username.value ); - } - } - else if (atrType == SA_PASSWORD) - { - msg->hasPassword = TRUE; - if (stunParseAtrString( body, attrLen, &msg->password) == FALSE) - { - ortp_error("stun: problem parsing SA_PASSWORD"); - return FALSE; - } - else - { - ortp_debug("stun: SA_PASSWORD = %s\n", msg->password.value ); - } - } - else if (atrType == SA_MESSAGEINTEGRITY) - { - msg->hasMessageIntegrity = TRUE; - if (stunParseAtrIntegrity( body, attrLen, &msg->messageIntegrity) == FALSE) - { - ortp_error("stun: problem parsing SA_MESSAGEINTEGRITY"); - return FALSE; - } - } - else if (atrType == SA_ERRORCODE) - { - msg->hasErrorCode = TRUE; - if (stunParseAtrError(body, attrLen, &msg->errorCode) == FALSE) - { - ortp_error("stun: problem parsing SA_ERRORCODE"); - return FALSE; - } - else - { - ortp_debug("stun: SA_ERRORCODE = %i %i %s\n", - msg->errorCode.errorClass , - msg->errorCode.number , - msg->errorCode.reason ); - } - - } - else if (atrType == SA_UNKNOWNATTRIBUTE) - { - msg->hasUnknownAttributes = TRUE; - if (stunParseAtrUnknown(body, attrLen, &msg->unknownAttributes) == FALSE) - { - ortp_error("stun: problem parsing SA_UNKNOWNATTRIBUTE"); - return FALSE; - } - } - else if (atrType == SA_REFLECTEDFROM) - { - msg->hasReflectedFrom = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->reflectedFrom ) == FALSE ) - { - ortp_error("stun: problem parsing SA_REFLECTEDFROM"); - return FALSE; - } - } - else if (atrType == SA_REALM) - { - msg->hasRealm = TRUE; - if (stunParseAtrString( body, attrLen, &msg->realmName) == FALSE) - { - ortp_error("stun: problem parsing SA_REALM"); - return FALSE; - } - else - { - ortp_debug("stun: SA_REALM = %s\n", msg->realmName.value ); - } - } - else if (atrType == SA_NONCE) - { - msg->hasNonce = TRUE; - if (stunParseAtrString( body, attrLen, &msg->nonceName) == FALSE) - { - ortp_error("stun: problem parsing SA_NONCE"); - return FALSE; - } - else - { - ortp_debug("stun: SA_NONCE = %s\n", msg->nonceName.value ); - } - } - else if (atrType == SA_XORMAPPEDADDRESS || atrType == SA_XORMAPPEDADDRESS2) - { - msg->hasXorMappedAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->xorMappedAddress ) == FALSE ) - { - ortp_error("stun: problem parsing SA_XORMAPPEDADDRESS"); - return FALSE; - } - else - { - ortp_debug("stun: SA_XORMAPPEDADDRESS = %s\n", ipaddr(&msg->xorMappedAddress.ipv4) ); - } - } - else if (atrType == SA_XORONLY) - { - ortp_warning("stun: SA_XORONLY - non standard extension ignored\n" ); - } - else if (atrType == SA_SECONDARYADDRESS) - { - ortp_debug("stun: SA_SECONDARYADDRESS - non standard extension ignored\n" ); - } - else if (atrType == SA_SOFTWARE) - { - msg->hasSoftware = TRUE; - if (stunParseAtrString( body, attrLen, &msg->softwareName) == FALSE) - { - ortp_error("stun: problem parsing SA_SOFTWARE"); - return FALSE; - } - else - { - ortp_debug("stun: SA_SOFTWARE = %s\n", msg->softwareName.value ); - } - } - else if (atrType == TA_CHANNELNUMBER) - { - msg->hasChannelNumberAttributes = TRUE; - if (turnParseAtrChannelNumber(body, attrLen, &msg->channelNumberAttributes) == FALSE) - { - ortp_error("stun: problem parsing TA_CHANNELNUMBER"); - return FALSE; - } - } - else if (atrType == TA_LIFETIME) - { - msg->hasLifetimeAttributes = TRUE; - if (turnParseAtrLifetime(body, attrLen, &msg->lifetimeAttributes) == FALSE) - { - ortp_error("stun: problem parsing TA_LIFETIME"); - return FALSE; - } - } - else if (atrType == TA_DEPRECATEDBANDWIDTH) - { - ortp_warning("stun: deprecated attribute TA_DEPRECATEDBANDWIDTH"); - } - else if (atrType == TA_XORPEERADDRESS) - { - msg->hasXorPeerAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->xorPeerAddress )== FALSE ) - { - ortp_error("stun: problem parsing SA_XORPEERADDRESS\n"); - return FALSE; - } - else - { - ortp_debug("stun: SA_XORPEERADDRESS = %s\n", ipaddr(&msg->xorPeerAddress.ipv4)); - } - } - else if (atrType == TA_DATA) - { - msg->hasData = TRUE; - if (turnParseAtrData( body, attrLen, &msg->data) == FALSE) - { - ortp_error("stun: problem parsing TA_DATA"); - return FALSE; - } - else - { - } - } - else if (atrType == TA_XORRELAYEDADDRESS) - { - msg->hasXorRelayedAddress = TRUE; - if ( stunParseAtrAddress( body, attrLen, &msg->xorRelayedAddress )== FALSE ) - { - ortp_error("stun: problem parsing TA_XORRELAYEDADDRESS\n"); - return FALSE; - } - else - { - ortp_debug("stun: TA_XORRELAYEDADDRESS = %s\n", ipaddr(&msg->xorRelayedAddress.ipv4)); - } - } - else if (atrType == TA_EVENPORT) - { - ortp_warning("stun: do we need this... TA_EVENPORT"); - } - else if (atrType == TA_REQUESTEDTRANSPORT) - { - msg->hasRequestedTransport = TRUE; - if ( turnParseAtrRequestedTransport( body, attrLen, &msg->requestedTransport )== FALSE ) - { - ortp_error("stun: problem parsing TA_REQUESTEDTRANSPORT\n"); - return FALSE; - } - } - else if (atrType == TA_DONTFRAGMENT) - { - msg->hasDontFragment = TRUE; - } - else if (atrType == TA_DEPRECATEDTIMERVAL) - { - ortp_warning("stun: deprecated attribute TA_DEPRECATEDTIMERVAL"); - } - else if (atrType == TA_RESERVATIONTOKEN) - { - msg->hasReservationToken = TRUE; - if ( turnParseAtrReservationToken( body, attrLen, &msg->reservationToken)== FALSE ) - { - ortp_error("stun: problem parsing TA_RESERVATIONTOKEN\n"); - return FALSE; - } - } - else if (atrType == SA_FINGERPRINT) - { - msg->hasFingerprint = TRUE; - if ( stunParseAtrFingerprint( body, attrLen, &msg->fingerprint)== FALSE ) - { - ortp_error("stun: problem parsing SA_FINGERPRINT\n"); - return FALSE; - } - } - else if (atrType == ICEA_PRIORITY) - { - msg->hasPriority = TRUE; - if (iceParseAtrPriority(body, attrLen, &msg->priority) == FALSE) - { - ortp_error("stun: problem parsing ICEA_PRIORITY"); - return FALSE; - } - } - else if (atrType == ICEA_USECANDIDATE) - { - msg->hasUseCandidate = TRUE; - } - else if (atrType == ICEA_ICECONTROLLED) - { - msg->hasIceControlled = TRUE; - if (iceParseAtrIceControll(body, attrLen, &msg->iceControlled) == FALSE) - { - ortp_error("stun: problem parsing ICEA_ICECONTROLLED"); - return FALSE; - } - } - else if (atrType == ICEA_ICECONTROLLING) - { - msg->hasIceControlling = TRUE; - if (iceParseAtrIceControll(body, attrLen, &msg->iceControlling) == FALSE) - { - ortp_error("stun: problem parsing ICEA_ICECONTROLLING"); - return FALSE; - } - } - else - { - if ( atrType <= 0x7FFF ) - { - ortp_error("stun: Unknown Comprehension-Required attribute: %04x\n", atrType ); - return FALSE; - } - else - ortp_warning("stun: Unknown attribute: %04x\n", atrType ); - } - - if (attrLen%4>0) - attrLen += (4-(attrLen%4)); - - body += attrLen; - size -= attrLen; - } - - return TRUE; -} - - -static char* -encode16(char* buf, uint16_t data) -{ - uint16_t ndata = htons(data); - memcpy(buf, &ndata, sizeof(uint16_t)); - return buf + sizeof(uint16_t); -} - -static char* -encode32(char* buf, uint32_t data) -{ - uint32_t ndata = htonl(data); - memcpy(buf, &ndata, sizeof(uint32_t)); - return buf + sizeof(uint32_t); -} - -static char* -encode64(char* buf, uint64_t data) -{ - uint64_t ndata = htonq(data); - memcpy(buf, &ndata, sizeof(uint64_t)); - return buf + sizeof(uint64_t); -} - -static char* -encode(char* buf, const char* data, unsigned int length) -{ - memcpy(buf, data, length); - return buf + length; -} - - -static char* -encodeAtrAddress4(char* ptr, uint16_t type, const StunAtrAddress4 *atr) -{ - ptr = encode16(ptr, type); - ptr = encode16(ptr, 8); - *ptr++ = atr->pad; - *ptr++ = IPv4Family; - ptr = encode16(ptr, atr->ipv4.port); - ptr = encode32(ptr, atr->ipv4.addr); - - return ptr; -} - -static char* -encodeAtrChangeRequest(char* ptr, const StunAtrChangeRequest *atr) -{ - ptr = encode16(ptr, SA_CHANGEREQUEST); - ptr = encode16(ptr, 4); - ptr = encode32(ptr, atr->value); - return ptr; -} - -static char* -encodeAtrError(char* ptr, const StunAtrError *atr) -{ - int padding; - int i; - - ptr = encode16(ptr, SA_ERRORCODE); - ptr = encode16(ptr, 4 + atr->sizeReason); - ptr = encode16(ptr, atr->pad); - *ptr++ = atr->errorClass; - *ptr++ = atr->number; - ptr = encode(ptr, atr->reason, atr->sizeReason); - - padding = (atr->sizeReason+4) % 4; - if (padding>0) - { - for (i=0;i<4-padding;i++) - { - *ptr++ = 0; - } - } - return ptr; -} - - -static char* -encodeAtrUnknown(char* ptr, const StunAtrUnknown *atr) -{ - int i; - ptr = encode16(ptr, SA_UNKNOWNATTRIBUTE); - ptr = encode16(ptr, 2+2*atr->numAttributes); - for (i=0; inumAttributes; i++) - { - ptr = encode16(ptr, atr->attrType[i]); - } - return ptr; -} - -static char* -encodeAtrString(char* ptr, uint16_t type, const StunAtrString *atr) -{ - int padding; - int i; - - ptr = encode16(ptr, type); - ptr = encode16(ptr, atr->sizeValue); - ptr = encode(ptr, atr->value, atr->sizeValue); - - padding = atr->sizeValue % 4; - if (padding>0) - { - for (i=0;i<4-padding;i++) - { - *ptr++ = 0; - } - } - return ptr; -} - - -static char* -encodeAtrIntegrity(char* ptr, const StunAtrIntegrity *atr) -{ - ptr = encode16(ptr, SA_MESSAGEINTEGRITY); - ptr = encode16(ptr, 20); - ptr = encode(ptr, atr->hash, sizeof(atr->hash)); - return ptr; -} - -static char* -encodeAtrFingerprint(char* ptr, const StunAtrFingerprint *atr) -{ - uint32_t val; - ptr = encode16(ptr, SA_FINGERPRINT); - ptr = encode16(ptr, 4); - - val = atr->fingerprint; - val ^= 0x5354554E; - ptr = encode32(ptr, val); - return ptr; -} - -static char* -encodeAtrRequestedTransport(char* ptr, const TurnAtrRequestedTransport *atr) -{ - ptr = encode16(ptr, TA_REQUESTEDTRANSPORT); - ptr = encode16(ptr, 4); - *ptr++ = atr->proto; - *ptr++ = atr->pad1; - *ptr++ = atr->pad2; - *ptr++ = atr->pad3; - return ptr; -} - -static char* -encodeAtrLifeTime(char* ptr, const TurnAtrLifetime *atr) -{ - ptr = encode16(ptr, TA_LIFETIME); - ptr = encode16(ptr, 4); - ptr = encode32(ptr, atr->lifetime); - return ptr; -} - -static char* -encodeAtrDontFragment(char* ptr) -{ - ptr = encode16(ptr, TA_DONTFRAGMENT); - ptr = encode16(ptr, 0); - return ptr; -} - -static char* -encodeAtrUseCandidate(char* ptr) -{ - ptr = encode16(ptr, ICEA_USECANDIDATE); - ptr = encode16(ptr, 0); - return ptr; -} - -static char* -encodeAtrPriority(char* ptr, const IceAtrPriority *atr) -{ - ptr = encode16(ptr, ICEA_PRIORITY); - ptr = encode16(ptr, 4); - ptr = encode32(ptr, atr->priority); - return ptr; -} - -static char* -encodeAtrIceControll(char* ptr, uint16_t type, const IceAtrIceControll *atr) -{ - ptr = encode16(ptr, type); - ptr = encode16(ptr, 8); - ptr = encode64(ptr, atr->value); - return ptr; -} - -unsigned int -stunEncodeMessage( const StunMessage *msg, - char* buf, - unsigned int bufLen, - const StunAtrString *password) -{ - char* ptr = buf; - char* lengthp; - ptr = encode16(ptr, msg->msgHdr.msgType); - lengthp = ptr; - ptr = encode16(ptr, 0); - ptr = encode32(ptr, msg->msgHdr.magic_cookie); - ptr = encode(ptr, (const char*)msg->msgHdr.tr_id.octet, sizeof(msg->msgHdr.tr_id)); - - ortp_debug("stun: Encoding stun message: "); - - if (msg->hasRequestedTransport) - { - ortp_debug("stun: Encoding TA_REQUESTEDTRANSPORT: %i\n", msg->requestedTransport.proto ); - ptr = encodeAtrRequestedTransport (ptr, &msg->requestedTransport); - } - if (msg->hasLifetimeAttributes) - { - ortp_debug("stun: Encoding TA_LIFETIME: %i\n", msg->lifetimeAttributes.lifetime ); - ptr = encodeAtrLifeTime (ptr, &msg->lifetimeAttributes); - } - if (msg->hasDontFragment) - { - ortp_debug("stun: Encoding TA_DONTFRAGMENT: DF\n"); - ptr = encodeAtrDontFragment (ptr); - } - if (msg->hasMappedAddress) - { - ortp_debug("stun: Encoding SA_MAPPEDADDRESS: %s\n", ipaddr(&msg->mappedAddress.ipv4) ); - ptr = encodeAtrAddress4 (ptr, SA_MAPPEDADDRESS, &msg->mappedAddress); - } - if (msg->hasResponseAddress) - { - ortp_debug("stun: Encoding SA_RESPONSEADDRESS: %s\n", ipaddr(&msg->responseAddress.ipv4) ); - ptr = encodeAtrAddress4(ptr, SA_RESPONSEADDRESS, &msg->responseAddress); - } - if (msg->hasChangeRequest) - { - ortp_debug("stun: Encoding SA_CHANGEREQUEST: %i\n", msg->changeRequest.value ); - ptr = encodeAtrChangeRequest(ptr, &msg->changeRequest); - } - if (msg->hasSourceAddress) - { - ortp_debug("stun: Encoding SA_SOURCEADDRESS: %s\n", ipaddr(&msg->sourceAddress.ipv4) ); - ptr = encodeAtrAddress4(ptr, SA_SOURCEADDRESS, &msg->sourceAddress); - } - if (msg->hasChangedAddress) - { - ortp_debug("stun: Encoding SA_CHANGEDADDRESS: %s\n", ipaddr(&msg->changedAddress.ipv4) ); - ptr = encodeAtrAddress4(ptr, SA_CHANGEDADDRESS, &msg->changedAddress); - } - if (msg->hasUsername) - { - ortp_debug("stun: Encoding SA_USERNAME: %s\n", msg->username.value ); - ptr = encodeAtrString(ptr, SA_USERNAME, &msg->username); - } - //if (msg->hasPassword) - //{ - // ortp_debug("stun: Encoding SA_PASSWORD: %s\n", msg->password.value ); - // ptr = encodeAtrString(ptr, SA_PASSWORD, &msg->password); - //} - if (msg->hasErrorCode) - { - ortp_debug("stun: Encoding SA_ERRORCODE: class=%i number=%i reason=%s\n" - , msg->errorCode.errorClass - , msg->errorCode.number - , msg->errorCode.reason ); - - ptr = encodeAtrError(ptr, &msg->errorCode); - } - if (msg->hasUnknownAttributes) - { - ortp_debug("stun: Encoding SA_UNKNOWNATTRIBUTE: ???"); - ptr = encodeAtrUnknown(ptr, &msg->unknownAttributes); - } - if (msg->hasReflectedFrom) - { - ortp_debug("stun: Encoding SA_REFLECTEDFROM: %s\n", ipaddr(&msg->reflectedFrom.ipv4) ); - ptr = encodeAtrAddress4(ptr, SA_REFLECTEDFROM, &msg->reflectedFrom); - } - if (msg->hasNonce) - { - ortp_debug("stun: Encoding SA_NONCE: %s\n", msg->nonceName.value ); - ptr = encodeAtrString(ptr, SA_NONCE, &msg->nonceName); - } - if (msg->hasRealm) - { - ortp_debug("stun: Encoding SA_REALM: %s\n", msg->realmName.value ); - ptr = encodeAtrString(ptr, SA_REALM, &msg->realmName); - } - - if (msg->hasXorMappedAddress) - { - ortp_debug("stun: Encoding SA_XORMAPPEDADDRESS: %s\n", ipaddr(&msg->xorMappedAddress.ipv4) ); - ptr = encodeAtrAddress4 (ptr, SA_XORMAPPEDADDRESS, &msg->xorMappedAddress); - } - - if (msg->hasPriority) - { - ortp_debug("stun: Encoding ICEA_PRIORITY\n"); - ptr = encodeAtrPriority (ptr, &msg->priority); - } - if (msg->hasUseCandidate) - { - ortp_debug("stun: Encoding ICEA_USECANDIDATE\n"); - ptr = encodeAtrUseCandidate (ptr); - } - if (msg->hasIceControlled) - { - ortp_debug("stun: Encoding ICEA_ICECONTROLLED\n"); - ptr = encodeAtrIceControll (ptr, ICEA_ICECONTROLLED, &msg->iceControlled); - } - if (msg->hasIceControlling) - { - ortp_debug("stun: Encoding ICEA_ICECONTROLLING\n"); - ptr = encodeAtrIceControll (ptr, ICEA_ICECONTROLLING, &msg->iceControlling); - } - - if (msg->hasSoftware) - { - ortp_debug("stun: Encoding SA_SOFTWARE: %s\n", msg->softwareName.value ); - ptr = encodeAtrString(ptr, SA_SOFTWARE, &msg->softwareName); - } - - if (msg->hasMessageIntegrity - &&password!=NULL && password->sizeValue > 0 - &&msg->username.sizeValue>0 - &&msg->realmName.sizeValue>0) - { - StunAtrIntegrity integrity; - //ortp_debug("stun: HMAC with password: %s\n", password->value ); - - encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+24)); - stunCalculateIntegrity_longterm(integrity.hash, buf, (int)(ptr-buf) , - msg->username.value, msg->realmName.value, password->value); - ptr = encodeAtrIntegrity(ptr, &integrity); - } - else if (msg->hasMessageIntegrity - &&password!=NULL && password->sizeValue > 0 - &&msg->username.sizeValue>0) - { - StunAtrIntegrity integrity; - //ortp_debug("stun: HMAC with password: %s\n", password->value ); - - encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+24)); - stunCalculateIntegrity_shortterm(integrity.hash, buf, (int)(ptr-buf) , - password->value); - ptr = encodeAtrIntegrity(ptr, &integrity); - } - - if (msg->hasFingerprint) - { - StunAtrFingerprint fingerprint; - //ortp_debug("stun: HMAC with password: %s\n", password->value ); - - encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+8)); - fingerprint.fingerprint = stunCalculateFingerprint(buf, (int)(ptr-buf)); - ptr = encodeAtrFingerprint(ptr, &fingerprint); - } - encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr))); - return (int)(ptr - buf); -} - -int -stunRand(void) -{ - /* return 32 bits of random stuff */ - /* assert( sizeof(int) == 4 ); */ - static bool_t init=FALSE; - if ( !init ) - { - uint64_t tick; - int seed; - init = TRUE; - -#if defined(_WIN32_WCE) - tick = GetTickCount (); -#elif defined(_MSC_VER) - { - volatile unsigned int lowtick=0,hightick=0; - __asm - { - rdtsc - mov lowtick, eax - mov hightick, edx - } - tick = hightick; - tick <<= 32; - tick |= lowtick; - } -#elif defined(__MACH__) - { - int fd=open("/dev/random",O_RDONLY); - read(fd,&tick,sizeof(tick)); - closesocket(fd); - } -#elif defined(__GNUC__) && ( defined(__i686__) || defined(__i386__) ) - asm("rdtsc" : "=A" (tick)); -#elif defined(__GNUC__) && defined(__amd64__) - asm("rdtsc" : "=A" (tick)); -#elif defined (__SUNPRO_CC) && defined( __sparc__ ) - tick = gethrtime(); -#elif defined(__linux) || defined(HAVE_DEV_RANDOM) - { - fd_set fdSet; - int maxFd=0; - struct timeval tv; - int e; - - int fd=open("/dev/random",O_RDONLY); - - if (fd<0) - { - ortp_message("stun: Failed to open random device\n"); - return random(); - } - FD_ZERO(&fdSet); - FD_SET(fd,&fdSet); - maxFd=fd+1; - - tv.tv_sec = 0; - tv.tv_usec = 500; - - e = select( maxFd, &fdSet, NULL,NULL, &tv ); - if (e <= 0) - { - ortp_error("stun: Failed to get data from random device\n"); - closesocket(fd); - return random(); - } - read(fd,&tick,sizeof(tick)); - closesocket(fd); - } -#else -# error Need some way to seed the random number generator -#endif - seed = (int)(tick); -#if defined(_WIN32) || defined(_WIN32_WCE) - srand(seed); -#else - srandom(seed); -#endif - } - -#if defined(_WIN32) || defined(_WIN32_WCE) - /* assert( RAND_MAX == 0x7fff ); */ - { - int r1 = rand(); - int r2 = rand(); - int ret = (r1<<16) + r2; - - return ret; - } -#else - return random(); -#endif -} - - -/* return a random number to use as a port */ -static int -randomPort() -{ - int min=0x4000; - int max=0x7FFF; - - int ret = stunRand(); - ret = ret|min; - ret = ret&max; - - return ret; -} - - -#ifdef NOSSL -void -stunCalculateIntegrity_longterm(char* hmac, const char* input, int length, - const char *username, const char *realm, const char *password) -{ - strncpy(hmac,"hmac-not-implemented",20); -} -void -stunCalculateIntegrity_shortterm(char* hmac, const char* input, int length, const char* key) -{ - strncpy(hmac,"hmac-not-implemented",20); -} - -#else -#include -#include - -void -stunCalculateIntegrity_longterm(char* hmac, const char* input, int length, - const char *username, const char *realm, const char *password) -{ - unsigned int resultSize=0; - unsigned char HA1[16]; - char HA1_text[1024]; - - snprintf(HA1_text, sizeof(HA1_text), "%s:%s:%s", username, realm, password); - MD5((unsigned char *)HA1_text, strlen(HA1_text), HA1); - - HMAC(EVP_sha1(), - HA1, 16, - (const unsigned char*) input, length, - (unsigned char*)hmac, &resultSize); -} - -void -stunCalculateIntegrity_shortterm(char* hmac, const char* input, int length, const char* key) -{ - unsigned int resultSize=0; - HMAC(EVP_sha1(), - key, strlen(key), - (const unsigned char*) input, length, - (unsigned char*)hmac, &resultSize); -} - -#endif - -uint32_t -stunCalculateFingerprint(const char* input, int length) -{ - /*- - 2 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or - 3 * code or tables extracted from it, as desired without restriction. - 4 */ - static uint32_t crc32_tab[] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d - }; - const uint8_t *p = (uint8_t*)input; - uint32_t crc; - - crc = ~0U; - while (length--) - crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); - return crc ^ ~0U; -} - -uint64_t -stunGetSystemTimeSecs(void) -{ - uint64_t time=0; -#if defined(_WIN32) || defined(_WIN32_WCE) - SYSTEMTIME t; - /* CJ TODO - this probably has bug on wrap around every 24 hours */ - GetSystemTime( &t ); - time = (t.wHour*60+t.wMinute)*60+t.wSecond; -#else - struct timeval now; - gettimeofday( &now , NULL ); - /* assert( now ); */ - time = now.tv_sec; -#endif - return time; -} - - -/* returns TRUE if it scucceeded */ -bool_t -stunParseHostName( const char* peerName, - uint32_t* ip, - uint16_t* portVal, - uint16_t defaultPort ) -{ - struct in_addr sin_addr; - - char host[512]; - char* port = NULL; - int portNum = defaultPort; - char* sep; - struct hostent* h; - - strncpy(host,peerName,512); - host[512-1]='\0'; - - /* pull out the port part if present. */ - sep = strchr(host,':'); - - if ( sep == NULL ) - { - portNum = defaultPort; - } - else - { - char* endPtr=NULL; - *sep = '\0'; - port = sep + 1; - /* set port part */ - - - portNum = strtol(port,&endPtr,10); - - if ( endPtr != NULL ) - { - if ( *endPtr != '\0' ) - { - portNum = defaultPort; - } - } - } - - if ( portNum < 1024 ) return FALSE; - if ( portNum >= 0xFFFF ) return FALSE; - - /* figure out the host part */ - -#if defined(_WIN32) || defined(_WIN32_WCE) - /* assert( strlen(host) >= 1 ); */ - if ( isdigit( host[0] ) ) - { - /* assume it is a ip address */ - unsigned long a = inet_addr(host); - /* cerr << "a=0x" << hex << a << dec ); */ - - *ip = ntohl( a ); - } - else - { - /* assume it is a host name */ - h = gethostbyname( host ); - - if ( h == NULL ) - { - /*int err = getErrno();*/ - - /* ortp_message("stun: error was %i\n", err); */ - /* std::cerr << "error was " << err << std::endl; */ - /* assert( err != WSANOTINITIALISED ); */ - - *ip = ntohl( 0x7F000001L ); - - return FALSE; - } - else - { - sin_addr = *(struct in_addr*)h->h_addr; - *ip = ntohl( sin_addr.s_addr ); - } - } - -#else - h = gethostbyname( host ); - if ( h == NULL ) - { - /* - int err = getErrno(); - ortp_message("stun: error was %i\n", err); - */ - *ip = ntohl( 0x7F000001L ); - return FALSE; - } - else - { - sin_addr = *(struct in_addr*)h->h_addr; - *ip = ntohl( sin_addr.s_addr ); - } -#endif - - *portVal = portNum; - - return TRUE; -} - - -bool_t -stunParseServerName( const char* name, StunAddress4 *addr) -{ - /* assert(name); */ - - /* TODO - put in DNS SRV stuff. */ - - bool_t ret = stunParseHostName( name, &addr->addr, &addr->port, 3478); - if ( ret != TRUE ) - { - addr->port=0xFFFF; - } - return ret; -} - - -static void -stunCreateErrorResponse(StunMessage *response, int cl, int number, const char* msg) -{ - response->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_ERR_RESP); - response->hasErrorCode = TRUE; - response->errorCode.errorClass = cl; - response->errorCode.number = number; - strcpy(response->errorCode.reason, msg); -} - -#if 0 -static void -stunCreateSharedSecretErrorResponse(StunMessage& response, int cl, int number, const char* msg) -{ - response.msgHdr.msgType = SharedSecretErrorResponseMsg; - response.hasErrorCode = TRUE; - response.errorCode.errorClass = cl; - response.errorCode.number = number; - strcpy(response.errorCode.reason, msg); -} -#endif - -#if 0 -static void -stunCreateSharedSecretResponse(const StunMessage *request, const StunAddress4 *source, StunMessage *response) -{ - response->msgHdr.msgType = SharedSecretResponseMsg; - response->msgHdr.tr_id = request->msgHdr.tr_id; - - response->hasUsername = TRUE; - stunCreateUserName( source, &response->username); - - response->hasPassword = TRUE; - stunCreatePassword( &response->username, &response->password); -} -#endif - -/* This funtion takes a single message sent to a stun server, parses - and constructs an apropriate repsonse - returns TRUE if message is - valid */ -bool_t -stunServerProcessMsg( char* buf, - unsigned int bufLen, - StunAddress4 *from, - StunAddress4 *myAddr, - StunAddress4 *altAddr, - StunMessage *resp, - StunAddress4 *destination, - StunAtrString *hmacPassword, - bool_t* changePort, - bool_t* changeIp) -{ - int i; - StunMessage req; - StunAddress4 mapped; - StunAddress4 respondTo; - uint32_t flags; - bool_t ok; - /* set up information for default response */ - - memset( &req, 0 , sizeof(req) ); - memset( resp, 0 , sizeof(*resp) ); - - *changeIp = FALSE; - *changePort = FALSE; - - ok = stunParseMessage( buf,bufLen, &req); - - if (!ok) /* Complete garbage, drop it on the floor */ - { - ortp_error("stun: Request did not parse"); - return FALSE; - } - //ortp_debug("stun: Request parsed ok"); - - mapped = req.mappedAddress.ipv4; - respondTo = req.responseAddress.ipv4; - flags = req.changeRequest.value; - - if (req.msgHdr.msgType==(STUN_METHOD_BINDING|STUN_REQUEST)) - { - if (!req.hasMessageIntegrity) - { - //ortp_debug("stun: BindRequest does not contain SA_MESSAGEINTEGRITY"); - - if (0) /* !jf! mustAuthenticate */ - { - ortp_error("stun: Received BindRequest with no SA_MESSAGEINTEGRITY. Sending 401."); - stunCreateErrorResponse(resp, 4, 1, "Missing SA_MESSAGEINTEGRITY"); - return TRUE; - } - } - else - { - if (!req.hasUsername) - { - ortp_error("stun: No UserName. Send 432."); - stunCreateErrorResponse(resp, 4, 32, "No UserName and contains SA_MESSAGEINTEGRITY"); - return TRUE; - } - else - { - //ortp_debug("stun: Validating username: %s", req.username.value ); - /* !jf! could retrieve associated password from provisioning here */ - if (strcmp(req.username.value, "test") == 0) - { - if (0) - { - /* !jf! if the credentials are stale */ - stunCreateErrorResponse(resp, 4, 30, "Stale credentials on BindRequest"); - return TRUE; - } - else - { - unsigned char hmac[20]; - //ortp_debug("stun: Validating SA_MESSAGEINTEGRITY"); - /* need access to shared secret */ - -#ifndef NOSSL - { - unsigned int hmacSize=20; - - HMAC(EVP_sha1(), - "1234", 4, - (const unsigned char*) buf, bufLen-20-4, - hmac, &hmacSize); - } -#endif - - if (memcmp(buf, hmac, 20) != 0) - { - ortp_error("stun: SA_MESSAGEINTEGRITY is bad. Sending "); - stunCreateErrorResponse(resp, 4, 3, "Unknown username. Try test with password 1234"); - return TRUE; - } - - /* need to compute this later after message is filled in */ - resp->hasMessageIntegrity = TRUE; - /* assert(req.hasUsername); */ - resp->hasUsername = TRUE; - resp->username = req.username; /* copy username in */ - } - } - else - { - ortp_error("stun: Invalid username: %s Send 430", req.username.value); - } - } - } - - /* TODO !jf! should check for unknown attributes here and send 420 listing the - unknown attributes. */ - - if ( respondTo.port == 0 ) - { - /* respondTo = from; */ - memcpy(&respondTo, from, sizeof(StunAddress4)); - } - if ( mapped.port == 0 ) - { - /* mapped = from; */ - memcpy(&mapped, from, sizeof(StunAddress4)); - } - - *changeIp = ( flags & ChangeIpFlag )?TRUE:FALSE; - *changePort = ( flags & ChangePortFlag )?TRUE:FALSE; - - //ortp_debug("stun: Request is valid:\n"); - //ortp_debug("stun: \t flags= %i\n", flags ); - //ortp_debug("stun: \t changeIp= %i\n", *changeIp ); - //ortp_debug("stun: \t changePort=%i\n", *changePort ); - //ortp_debug("stun: \t from= %i\n", from->addr ); - //ortp_debug("stun: \t respond to= %i\n", respondTo.addr ); - //ortp_debug("stun: \t mapped= %i\n", mapped.addr ); - - /* form the outgoing message */ - resp->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP); - resp->msgHdr.magic_cookie = ntohl(req.msgHdr.magic_cookie); - for (i=0; i<12; i++ ) - { - resp->msgHdr.tr_id.octet[i] = req.msgHdr.tr_id.octet[i]; - } - - if (1) /* do xorMapped address or not */ - { - uint32_t cookie = 0x2112A442; - resp->hasXorMappedAddress = TRUE; - resp->xorMappedAddress.ipv4.port = mapped.port^(cookie>>16); - resp->xorMappedAddress.ipv4.addr = mapped.addr^cookie; - } - - resp->hasSourceAddress = TRUE; - resp->sourceAddress.ipv4.port = (*changePort) ? altAddr->port : myAddr->port; - resp->sourceAddress.ipv4.addr = (*changeIp) ? altAddr->addr : myAddr->addr; - - resp->hasChangedAddress = TRUE; - resp->changedAddress.ipv4.port = altAddr->port; - resp->changedAddress.ipv4.addr = altAddr->addr; - - if ( req.hasUsername && req.username.sizeValue > 0 ) - { - /* copy username in */ - resp->hasUsername = TRUE; - /* assert( req.username.sizeValue % 4 == 0 ); */ - /* assert( req.username.sizeValue < STUN_MAX_STRING ); */ - memcpy( resp->username.value, req.username.value, req.username.sizeValue ); - resp->username.sizeValue = req.username.sizeValue; - } - - if (1) /* add ServerName */ - { - const char serverName[] = "oRTP " STUN_VERSION; /* must pad to mult of 4 */ - resp->hasSoftware = TRUE; - - /* assert( sizeof(serverName) < STUN_MAX_STRING ); */ - /* cerr << "sizeof serverName is " << sizeof(serverName) ); */ - /* assert( sizeof(serverName)%4 == 0 ); */ - memcpy( resp->softwareName.value, serverName, sizeof(serverName)); - resp->softwareName.sizeValue = sizeof(serverName); - } - -#if 0 - if ( req.hasMessageIntegrity & req.hasUsername ) - { - /* this creates the password that will be used in the HMAC when then */ - /* messages is sent */ - stunCreatePassword( &req.username, hmacPassword ); - } -#endif - - if (req.hasUsername && (req.username.sizeValue > 64 ) ) - { - uint32_t source; - /* assert( sizeof(int) == sizeof(uint32_t) ); */ - - sscanf(req.username.value, "%x", &source); - resp->hasReflectedFrom = TRUE; - resp->reflectedFrom.ipv4.port = 0; - resp->reflectedFrom.ipv4.addr = source; - } - - destination->port = respondTo.port; - destination->addr = respondTo.addr; - - return TRUE; - } - else - { - ortp_error("stun: Unknown or unsupported request "); - return FALSE; - } - - /* assert(0); */ - return FALSE; -} - -bool_t -stunInitServer(StunServerInfo *info, const StunAddress4 *myAddr, const StunAddress4 *altAddr, int startMediaPort) -{ - /* assert( myAddr.port != 0 ); */ - /* assert( altAddr.port!= 0 ); */ - /* assert( myAddr.addr != 0 ); */ - /* assert( altAddr.addr != 0 ); */ - - /* info->myAddr = myAddr; */ - info->myAddr.port = myAddr->port; - info->myAddr.addr = myAddr->addr; - - /* info->altAddr = altAddr; */ - info->altAddr.port = altAddr->port; - info->altAddr.addr = altAddr->addr; - - info->myFd = INVALID_SOCKET; - info->altPortFd = INVALID_SOCKET; - info->altIpFd = INVALID_SOCKET; - info->altIpPortFd = INVALID_SOCKET; - - memset(info->relays, 0, sizeof(info->relays)); - if (startMediaPort > 0) - { - int i; - info->relay = TRUE; - - for (i=0; irelays[i]; - relay->relayPort = startMediaPort+i; - relay->fd = 0; - relay->expireTime = 0; - } - } - else - { - info->relay = FALSE; - } - - if ((info->myFd = openPort(myAddr->port, myAddr->addr)) == INVALID_SOCKET) - { - ortp_error("stun: Can't open %i\n", myAddr->addr ); - stunStopServer(info); - - return FALSE; - } - - if ((info->altPortFd = openPort(altAddr->port,myAddr->addr)) == INVALID_SOCKET) - { - ortp_error("stun: Can't open %i\n", myAddr->addr ); - stunStopServer(info); - return FALSE; - } - - - info->altIpFd = INVALID_SOCKET; - if ( altAddr->addr != 0 ) - { - if ((info->altIpFd = openPort( myAddr->port, altAddr->addr)) == INVALID_SOCKET) - { - ortp_error("stun: Can't open %i\n", altAddr->addr ); - stunStopServer(info); - return FALSE; - } - } - - info->altIpPortFd = INVALID_SOCKET; - if ( altAddr->addr != 0 ) - { if ((info->altIpPortFd = openPort(altAddr->port, altAddr->addr)) == INVALID_SOCKET) - { - ortp_error("stun: Can't open %i\n", altAddr->addr ); - stunStopServer(info); - return FALSE; - } - } - - return TRUE; -} - -void -stunStopServer(StunServerInfo *info) -{ - if (info->myFd > 0) closesocket(info->myFd); - if (info->altPortFd > 0) closesocket(info->altPortFd); - if (info->altIpFd > 0) closesocket(info->altIpFd); - if (info->altIpPortFd > 0) closesocket(info->altIpPortFd); - - if (info->relay) - { - int i; - for (i=0; irelays[i]; - if (relay->fd) - { - closesocket(relay->fd); - relay->fd = 0; - } - } - } -} - -int -stunFindLocalInterfaces(uint32_t* addresses,int maxRet) -{ -#if defined(WIN32) || defined(_WIN32_WCE) || defined(__sparc__) - return 0; -#else - struct ifconf ifc; - int e; - - int s = socket( AF_INET, SOCK_DGRAM, 0 ); - int len = 100 * sizeof(struct ifreq); - - char buf[ 100 * sizeof(struct ifreq) ]; - char *ptr; - int tl; - int count=0; - - ifc.ifc_len = len; - ifc.ifc_buf = buf; - - e = ioctl(s,SIOCGIFCONF,&ifc); - ptr = buf; - tl = ifc.ifc_len; - - while ( (tl > 0) && ( count < maxRet) ) - { - struct ifreq* ifr = (struct ifreq *)ptr; - struct ifreq ifr2; - struct sockaddr a; - struct sockaddr_in* addr; - - uint32_t ai; - int si = sizeof(ifr->ifr_name) + sizeof(struct sockaddr); - tl -= si; - ptr += si; - /* char* name = ifr->ifr_ifrn.ifrn_name; */ - /* cerr << "name = " << name ); */ - - ifr2 = *ifr; - - e = ioctl(s,SIOCGIFADDR,&ifr2); - if ( e == -1 ) - { - break; - } - - /* cerr << "ioctl addr e = " << e ; */ - - a = ifr2.ifr_addr; - addr = (struct sockaddr_in*) &a; - - ai = ntohl( addr->sin_addr.s_addr ); - if ((int)((ai>>24)&0xFF) != 127) - { - addresses[count++] = ai; - } - - } - - closesocket(s); - - return count; -#endif -} - - -void -stunBuildReqSimple( StunMessage* msg, - const StunAtrString *username, - bool_t changePort, bool_t changeIp, unsigned int id ) -{ - int i; - /* assert( msg ); */ - memset( msg , 0 , sizeof(*msg) ); - - msg->msgHdr.msgType = (STUN_METHOD_BINDING|STUN_REQUEST); - - msg->msgHdr.magic_cookie = 0x2112A442; - for ( i=0; i<12; i=i+4 ) - { - /* assert(i+3<16); */ - int r = stunRand(); - msg->msgHdr.tr_id.octet[i+0]= r>>0; - msg->msgHdr.tr_id.octet[i+1]= r>>8; - msg->msgHdr.tr_id.octet[i+2]= r>>16; - msg->msgHdr.tr_id.octet[i+3]= r>>24; - } - - if ( id != 0 ) - { - msg->msgHdr.tr_id.octet[0] = id; - } - - if (changePort==TRUE || changeIp==TRUE) - { - msg->hasChangeRequest = TRUE; - msg->changeRequest.value =(changeIp?ChangeIpFlag:0) | - (changePort?ChangePortFlag:0); - } - - if ( username!=NULL && username->sizeValue > 0 ) - { - msg->hasUsername = TRUE; - /* msg->username = username; */ - memcpy(&msg->username, username, sizeof(StunAtrString)); - } -} - - -static void -stunSendTest( Socket myFd, StunAddress4 *dest, - const StunAtrString *username, const StunAtrString *password, - int testNum ) -{ - /* assert( dest.addr != 0 ); */ - /* assert( dest.port != 0 ); */ - - bool_t changePort=FALSE; - bool_t changeIP=FALSE; - bool_t discard=FALSE; - - StunMessage req; - char buf[STUN_MAX_MESSAGE_SIZE]; - int len = STUN_MAX_MESSAGE_SIZE; - - switch (testNum) - { - case 1: - case 10: - case 11: - break; - case 2: - /* changePort=TRUE; */ - changeIP=TRUE; - break; - case 3: - changePort=TRUE; - break; - case 4: - changeIP=TRUE; - break; - case 5: - discard=TRUE; - break; - default: - ortp_error("stun: Test %i is unkown\n", testNum); - return ; /* error */ - } - - memset(&req, 0, sizeof(StunMessage)); - - stunBuildReqSimple( &req, username, - changePort , changeIP , - testNum ); - - len = stunEncodeMessage( &req, buf, len, password ); - - //ortp_debug("stun: About to send msg of len %i to %s\n", len, ipaddr(dest) ); - - sendMessage( myFd, buf, len, dest->addr, dest->port ); - - /* add some delay so the packets don't get sent too quickly */ -#if defined(_WIN32_WCE) - Sleep (10); -#elif defined(WIN32)/* !cj! TODO - should fix this up in windows */ - { - clock_t now = clock(); - /* assert( CLOCKS_PER_SEC == 1000 ); */ - while ( clock() <= now+10 ) { }; - } -#else - usleep(10*1000); -#endif - -} - - -#if 0 -void -stunGetUserNameAndPassword( const StunAddress4 *dest, - StunAtrString* username, - StunAtrString* password) -{ - /* !cj! This is totally bogus - need to make TLS connection to dest and get a */ - /* username and password to use */ - stunCreateUserName(dest, username); - stunCreatePassword(username, password); -} -#endif - -int -stunTest( StunAddress4 *dest, int testNum, StunAddress4* sAddr , StunAddress4 *sMappedAddr, StunAddress4* sChangedAddr) -{ - /* assert( dest.addr != 0 ); */ - /* assert( dest.port != 0 ); */ - - int port = randomPort(); - uint32_t interfaceIp=0; - Socket myFd; - StunAtrString username; - StunAtrString password; - char msg[STUN_MAX_MESSAGE_SIZE]; - int msgLen = STUN_MAX_MESSAGE_SIZE; - StunAddress4 from; - StunMessage resp; - bool_t ok; - - if (sAddr) - { - interfaceIp = sAddr->addr; - if ( sAddr->port != 0 ) - { - port = sAddr->port; - } - } - myFd = openPort(port,interfaceIp); - if ( myFd == INVALID_SOCKET) - return -1; - - username.sizeValue = 0; - password.sizeValue = 0; - -#if 0 - stunGetUserNameAndPassword( dest, &username, &password ); -#endif - - stunSendTest( myFd, dest, &username, &password, testNum ); - - ok = getMessage( myFd, - msg, - &msgLen, - &from.addr, - &from.port ); - closesocket(myFd); - if (!ok) - return -1; - - memset(&resp, 0, sizeof(StunMessage)); - - //ortp_debug("stun: Got a response"); - ok = stunParseMessage( msg,msgLen, &resp ); - - //ortp_debug("stun: \t ok=%i\n", ok ); - //ortp_debug("stun: \t SA_MAPPEDADDRESS=%i\n", resp.mappedAddress.ipv4.addr ); - //ortp_debug("stun: \t SA_CHANGEDADDRESS=%i\n", resp.changedAddress.ipv4.addr ); - - if (sAddr) - { - sAddr->port = port; - } - - if (sMappedAddr) - { - sMappedAddr->port = resp.mappedAddress.ipv4.port; - sMappedAddr->addr = resp.mappedAddress.ipv4.addr; - } - - if (sChangedAddr) - { - sChangedAddr->port = resp.changedAddress.ipv4.port; - sChangedAddr->addr = resp.changedAddress.ipv4.addr; - } - - if (ok) - return 0; - else - return -1; -} - - - - -NatType -stunNatType( StunAddress4 *dest, - bool_t* preservePort, /* if set, is return for if NAT preservers ports or not */ - bool_t* hairpin, /* if set, is the return for if NAT will hairpin packets */ - int port, /* port to use for the test, 0 to choose random port */ - StunAddress4* sAddr /* NIC to use */ - ) -{ - /* assert( dest.addr != 0 ); */ - /* assert( dest.port != 0 ); */ - uint32_t interfaceIp=0; - Socket myFd1; - Socket myFd2; - - bool_t respTestI=FALSE; - bool_t isNat=TRUE; - StunAddress4 testIchangedAddr; - StunAddress4 testImappedAddr; - bool_t respTestI2=FALSE; - bool_t mappedIpSame = TRUE; - StunAddress4 testI2mappedAddr; - /* StunAddress4 testI2dest=dest; */ - StunAddress4 testI2dest; - bool_t respTestII=FALSE; - bool_t respTestIII=FALSE; - bool_t respTestHairpin=FALSE; - StunAtrString username; - StunAtrString password; - int count=0; - uint64_t second_started; - uint64_t second_elapsed; - Socket s; - - if ( hairpin ) - { - *hairpin = FALSE; - } - - if ( port == 0 ) - { - port = randomPort(); - } - - if (sAddr) - { - interfaceIp = sAddr->addr; - } - myFd1 = openPort(port,interfaceIp); - myFd2 = openPort(port+1,interfaceIp); - - if ( ( myFd1 == INVALID_SOCKET) || ( myFd2 == INVALID_SOCKET) ) - { - ortp_error("stun: Some problem opening port/interface to send on\n"); - return StunTypeFailure; - } - - /* assert( myFd1 != INVALID_SOCKET ); */ - /* assert( myFd2 != INVALID_SOCKET ); */ - - memcpy(&testI2dest, dest, sizeof(StunAddress4)); - - memset(&testImappedAddr,0,sizeof(testImappedAddr)); - - username.sizeValue = 0; - password.sizeValue = 0; - -#if 0 - stunGetUserNameAndPassword( dest, username, password ); -#endif - - /* stunSendTest( myFd1, dest, username, password, 1 ); */ - - - second_started = stunGetSystemTimeSecs(); - second_elapsed = 1; - - while ( count < 3 && second_elapsed < 5) - { - struct timeval tv; - fd_set fdSet; - int err; - int e; - -#if defined(WIN32) || defined(_WIN32_WCE) - unsigned int fdSetSize; -#else - int fdSetSize; -#endif - - second_elapsed = stunGetSystemTimeSecs() - second_started ; - - FD_ZERO(&fdSet); fdSetSize=0; - FD_SET(myFd1,&fdSet); fdSetSize = (myFd1+1>fdSetSize) ? myFd1+1 : fdSetSize; - FD_SET(myFd2,&fdSet); fdSetSize = (myFd2+1>fdSetSize) ? myFd2+1 : fdSetSize; - tv.tv_sec=0; - tv.tv_usec=500*1000; /* 150 ms */ - if ( count == 0 ) tv.tv_usec=0; - - err = select(fdSetSize, &fdSet, NULL, NULL, &tv); - e = getErrno(); - if ( err == SOCKET_ERROR ) - { - /* error occured */ -#if !defined(_WIN32_WCE) - ortp_error("stun: Error %i %s in select\n", e, strerror(e)); -#else - ortp_error("stun: Error %i in select\n", e); -#endif - closesocket(myFd1); /* AMD */ - closesocket(myFd2); /* AMD */ - return StunTypeFailure; - } - else if ( err == 0 ) - { - /* timeout occured */ - count++; - if ( !respTestI ) - { - stunSendTest( myFd1, dest, &username, &password, 1 ); - } - - if ( (!respTestI2) && respTestI ) - { - /* check the address to send to if valid */ - if ( ( testI2dest.addr != 0 ) && - ( testI2dest.port != 0 ) ) - { - stunSendTest( myFd1, &testI2dest, &username, &password, 10 ); - } - } - - if ( !respTestII ) - { - stunSendTest( myFd2, dest, &username, &password, 2 ); - } - - if ( !respTestIII ) - { - stunSendTest( myFd2, dest, &username, &password, 3 ); - } - - if ( respTestI && (!respTestHairpin) ) - { - if ( ( testImappedAddr.addr != 0 ) && - ( testImappedAddr.port != 0 ) ) - { - stunSendTest( myFd1, &testImappedAddr, &username, &password, 11 ); - } - } - - } - else - { - int i; - /* data is avialbe on some fd */ - - for ( i=0; i<2; i++) - { - Socket myFd; - if ( i==0 ) - { - myFd=myFd1; - } - else - { - myFd=myFd2; - } - - if ( myFd!=INVALID_SOCKET ) - { - if ( FD_ISSET(myFd,&fdSet) ) - { - char msg[STUN_MAX_MESSAGE_SIZE]; - int msgLen = sizeof(msg); - - StunAddress4 from; - StunMessage resp; - - getMessage( myFd, - msg, - &msgLen, - &from.addr, - &from.port ); - - memset(&resp, 0, sizeof(StunMessage)); - - stunParseMessage( msg,msgLen, &resp ); - - //ortp_debug("stun: Received message of type %i id=%i\n", - //resp.msgHdr.msgType, - //(int)(resp.msgHdr.tr_id.octet[0]) ); - - switch( resp.msgHdr.tr_id.octet[0] ) - { - case 1: - { - if ( !respTestI ) - { - - testIchangedAddr.addr = resp.changedAddress.ipv4.addr; - testIchangedAddr.port = resp.changedAddress.ipv4.port; - testImappedAddr.addr = resp.mappedAddress.ipv4.addr; - testImappedAddr.port = resp.mappedAddress.ipv4.port; - - if ( preservePort ) - { - *preservePort = ( testImappedAddr.port == port ); - } - - testI2dest.addr = resp.changedAddress.ipv4.addr; - - if (sAddr) - { - sAddr->port = testImappedAddr.port; - sAddr->addr = testImappedAddr.addr; - } - - count = 0; - } - respTestI=TRUE; - } - break; - case 2: - { - respTestII=TRUE; - } - break; - case 3: - { - respTestIII=TRUE; - } - break; - case 10: - { - if ( !respTestI2 ) - { - testI2mappedAddr.addr = resp.mappedAddress.ipv4.addr; - testI2mappedAddr.port = resp.mappedAddress.ipv4.port; - - mappedIpSame = FALSE; - if ( (testI2mappedAddr.addr == testImappedAddr.addr ) && - (testI2mappedAddr.port == testImappedAddr.port )) - { - mappedIpSame = TRUE; - } - - - } - respTestI2=TRUE; - } - break; - case 11: - { - - if ( hairpin ) - { - *hairpin = TRUE; - } - respTestHairpin = TRUE; - } - break; - } - } - } - } - } - } - - closesocket(myFd1); /* AMD */ - closesocket(myFd2); /* AMD */ - - /* see if we can bind to this address */ - /* cerr << "try binding to " << testImappedAddr ); */ - s = openPort( 0/*use ephemeral*/, testImappedAddr.addr ); - if ( s != INVALID_SOCKET ) - { - isNat = FALSE; - /* cerr << "binding worked"); */ - } - else - { - isNat = TRUE; - /* cerr << "binding failed"); */ - } - - closesocket(s); /* AMD */ - - //ortp_debug("stun: test I = %i\n", respTestI ); - //ortp_debug("stun: test II = %i\n", respTestII ); - //ortp_debug("stun: test III = %i\n", respTestIII ); - //ortp_debug("stun: test I(2) = %i\n", respTestI2 ); - ortp_debug("stun: is nat = %i\n", isNat); - ortp_debug("stun: mapped IP same = %i\n", mappedIpSame ); - - /* implement logic flow chart from draft RFC */ - if ( respTestI ) - { - if ( isNat ) - { - if (respTestII) - { - return StunTypeConeNat; - } - else - { - if ( mappedIpSame ) - { - if ( respTestIII ) - { - return StunTypeRestrictedNat; - } - else - { - return StunTypePortRestrictedNat; - } - } - else - { - return StunTypeSymNat; - } - } - } - else - { - if (respTestII) - { - return StunTypeOpen; - } - else - { - return StunTypeSymFirewall; - } - } - } - else - { - return StunTypeBlocked; - } - - return StunTypeUnknown; -} - -int -stunOpenSocket( StunAddress4 *dest, StunAddress4* mapAddr, - int port, StunAddress4* srcAddr ) -{ - /* assert( dest.addr != 0 ); */ - /* assert( dest.port != 0 ); */ - /* assert( mapAddr );*/ - unsigned int interfaceIp = 0; - Socket myFd; - char msg[STUN_MAX_MESSAGE_SIZE]; - int msgLen = sizeof(msg); - - StunAtrString username; - StunAtrString password; - - StunAddress4 from; - StunMessage resp; - bool_t ok; - StunAddress4 mappedAddr; - - if ( port == 0 ) - { - port = randomPort(); - } - - if ( srcAddr ) - { - interfaceIp = srcAddr->addr; - } - - myFd = openPort(port,interfaceIp); - if (myFd == INVALID_SOCKET) - { - return myFd; - } - - username.sizeValue = 0; - password.sizeValue = 0; - -#if 0 - stunGetUserNameAndPassword( dest, username, password ); -#endif - - stunSendTest(myFd, dest, &username, &password, 1 ); - - getMessage( myFd, msg, &msgLen, &from.addr, &from.port ); - - memset(&resp, 0, sizeof(StunMessage)); - - ok = stunParseMessage( msg, msgLen, &resp ); - if (!ok) - { - closesocket(myFd); - return -1; - } - - if (resp.hasXorMappedAddress==TRUE) - { - uint32_t cookie = 0x2112A442; - uint16_t cookie16 = 0x2112A442 >> 16; - mappedAddr.port = resp.xorMappedAddress.ipv4.port^cookie16; - mappedAddr.addr = resp.xorMappedAddress.ipv4.addr^cookie; - } - else - mappedAddr = resp.mappedAddress.ipv4; - - /* - ortp_message("stun: --- stunOpenSocket --- "); - ortp_message("stun: \treq id=" << req.id ); - ortp_message("stun: \tresp id=" << id ); - ortp_message("stun: \tmappedAddr=" << mappedAddr ); - */ - - *mapAddr = mappedAddr; - - return myFd; -} - - -bool_t -stunOpenSocketPair(StunAddress4 *dest, - StunAddress4* mapAddr_rtp, - StunAddress4* mapAddr_rtcp, - int* fd1, int* fd2, - int port, StunAddress4* srcAddr ) -{ - /* assert( dest.addr!= 0 ); */ - /* assert( dest.port != 0 ); */ - /* assert( mapAddr ); */ - - const int NUM=2; - char msg[STUN_MAX_MESSAGE_SIZE]; - int msgLen =sizeof(msg); - - StunAddress4 from; - int fd[2/*NUM*/]; - int i; - - unsigned int interfaceIp = 0; - - StunAtrString username; - StunAtrString password; - - StunAddress4 mappedAddr[2/*NUM*/]; - - if ( port == 0 ) - { - port = randomPort(); - } - - *fd1=-1; - *fd2=-1; - - if ( srcAddr ) - { - interfaceIp = srcAddr->addr; - } - - for( i=0; i 0) - { - closesocket(fd[--i]); - } - return FALSE; - } - } - - username.sizeValue = 0; - password.sizeValue = 0; - -#if 0 - stunGetUserNameAndPassword( dest, username, password ); -#endif - - for( i=0; i> 16; - mappedAddr[i].port = resp.xorMappedAddress.ipv4.port^cookie16; - mappedAddr[i].addr = resp.xorMappedAddress.ipv4.addr^cookie; - } - else - mappedAddr[i] = resp.mappedAddress.ipv4; - } - - //ortp_debug("stun: --- stunOpenSocketPair --- \n"); - for( i=0; isizeValue>0 - && password!=NULL && password->sizeValue>0 - && resp->hasRealm==TRUE - && resp->hasNonce==TRUE) - { - req.hasUsername = TRUE; - memcpy( req.username.value, username->value, username->sizeValue ); - req.username.sizeValue = username->sizeValue; - - req.hasNonce = TRUE; - memcpy( &req.nonceName, &resp->nonceName, sizeof(resp->nonceName)); - - req.hasRealm = TRUE; - memcpy( &req.realmName, &resp->realmName, sizeof(resp->realmName)); - - req.hasMessageIntegrity = TRUE; - } - - len = stunEncodeMessage( &req, buf, len, password ); - - ortp_debug("stun: About to send msg of len %i to %s\n", len, ipaddr(dest) ); - - sendMessage( myFd, buf, len, dest->addr, dest->port); - - /* add some delay so the packets don't get sent too quickly */ -#if defined(_WIN32_WCE) - Sleep (10); -#elif defined(WIN32)/* !cj! TODO - should fix this up in windows */ - { - clock_t now = clock(); - /* assert( CLOCKS_PER_SEC == 1000 ); */ - while ( clock() <= now+10 ) { }; - } -#else - usleep(10*1000); -#endif -} - -bool_t -turnAllocateSocketPair(StunAddress4 *dest, - StunAddress4* mapAddr_rtp, - StunAddress4* mapAddr_rtcp, - int* fd1, int* fd2, - int port, StunAddress4* srcAddr) -{ - const int NUM=2; - char msg[STUN_MAX_MESSAGE_SIZE]; - int msgLen =sizeof(msg); - - StunAddress4 from; - int fd[2/*NUM*/]; - int i; - - unsigned int interfaceIp = 0; - - StunAtrString username; - StunAtrString password; - - StunAddress4 mappedAddr[2/*NUM*/]; - - if ( port == 0 ) - { - port = randomPort(); - } - - *fd1=-1; - *fd2=-1; - - if ( srcAddr ) - { - interfaceIp = srcAddr->addr; - } - - for( i=0; i 0) - { - closesocket(fd[--i]); - } - return FALSE; - } - } - - snprintf(username.value, sizeof(username.value), "antisip"); - username.sizeValue = strlen(username.value); - snprintf(password.value, sizeof(password.value), "exosip"); - password.sizeValue = strlen(password.value); - - for( i=0; i> 16; - mappedAddr[i].port = resp.xorRelayedAddress.ipv4.port^cookie16; - mappedAddr[i].addr = resp.xorRelayedAddress.ipv4.addr^cookie; - } - else - { - for( i=0; i. - * - */ - -#include -#include -#include -#if !defined(WIN32) && !defined(_WIN32_WCE) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif -#include - -#include - -#if defined(WIN32) || defined(_WIN32_WCE) - -#include -#include -/* #include */ - -#else - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif - -#include - -#include "ortp/stun_udp.h" -#include "ortp/ortp.h" - -#if !defined(WIN32) && !defined(_WIN32_WCE) -int getErrno() { return errno; } -#else -int getErrno() { return WSAGetLastError(); } -#endif - -Socket -openPort( unsigned short port, unsigned int interfaceIp ) -{ - struct sockaddr_in addr; - Socket fd; - - fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); - if ( fd == INVALID_SOCKET ) - { - ortp_error("stun_udp: Could not create a UDP socket"); - return INVALID_SOCKET; - } - - memset((char*) &(addr),0, sizeof((addr))); - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_port = htons(port); - - if ( (interfaceIp != 0) && - ( interfaceIp != 0x100007f ) ) - { - addr.sin_addr.s_addr = htonl(interfaceIp); - //ortp_debug("Binding to interface 0x%lu\n",(unsigned long) htonl(interfaceIp)); - } - - if ( bind( fd,(struct sockaddr*)&addr, sizeof(addr)) != 0 ) - { - int e = getErrno(); - - switch (e) - { - case 0: - { - ortp_error("stun_udp: Could not bind socket");; - return INVALID_SOCKET; - } - case EADDRINUSE: - { - ortp_error("stun_udp: Port %i for receiving UDP is in use", port); - return INVALID_SOCKET; - } - break; - case EADDRNOTAVAIL: - { - ortp_error("stun_udp: Cannot assign requested address"); - return INVALID_SOCKET; - } - break; - default: - { -#if !defined(_WIN32_WCE) - ortp_error("stun_udp: Could not bind UDP receive port Error=%i %s", - e, strerror(e)); -#else - ortp_error("stun_udp: Could not bind UDP receive port Error=%i", - e); -#endif - return INVALID_SOCKET; - } - break; - } - } - - ortp_debug("stun: opened port %i with fd %i\n", port, fd); - - /* assert( fd != INVALID_SOCKET ); */ - - return fd; -} - - -bool_t -getMessage( Socket fd, char* buf, int* len, - unsigned int* srcIp, unsigned short* srcPort) -{ - /* assert( fd != INVALID_SOCKET ); */ - - int originalSize = *len; - struct sockaddr_in from; - int fromLen = sizeof(from); - - - int err; - struct timeval tv; - fd_set fdSet; -#if defined(WIN32) || defined(_WIN32_WCE) - unsigned int fdSetSize; -#else - int fdSetSize; -#endif - - if (originalSize <= 0) - { - return FALSE; - } - - tv.tv_sec=1; - tv.tv_usec=0; /* 150 ms */ - FD_ZERO(&fdSet); fdSetSize=0; - FD_SET(fd,&fdSet); fdSetSize = fd+1; - - err = select(fdSetSize, &fdSet, NULL, NULL, &tv); - if ( err == SOCKET_ERROR ) - { - int e = getErrno(); - switch (e) - { - case ENOTSOCK: - ortp_error("stun_udp: Error fd not a socket"); - break; - case ECONNRESET: - ortp_error("stun_udp: Error connection reset - host not reachable"); - break; - - default: - ortp_error("stun_udp: Socket Error=%i", e); - } - return FALSE; - } - - if (err==0) - { - ortp_error("stun_udp: Connection timeout with stun server!"); - *len = 0; - return FALSE; - } - - if (FD_ISSET (fd, &fdSet)) - { - *len = recvfrom(fd, - buf, - originalSize, - 0, - (struct sockaddr *)&from, - (socklen_t*)&fromLen); - - if ( *len == SOCKET_ERROR ) - { - int e = getErrno(); - - switch (e) - { - case ENOTSOCK: - ortp_error("stun_udp: Error fd not a socket"); - break; - case ECONNRESET: - ortp_error("stun_udp: Error connection reset - host not reachable"); - break; - - default: - ortp_error("stun_udp: Socket Error=%i", e); - } - - return FALSE; - } - - if ( *len < 0 ) - { - ortp_error("stun_udp: socket closed? negative len"); - return FALSE; - } - - if ( *len == 0 ) - { - ortp_error("stun_udp: socket closed? zero len"); - return FALSE; - } - - *srcPort = ntohs(from.sin_port); - *srcIp = ntohl(from.sin_addr.s_addr); - - if ( (*len)+1 >= originalSize ) - { - ortp_error("stun_udp: Received a message that was too large"); - return FALSE; - } - buf[*len]=0; - - return TRUE; - } - return FALSE; -} - - -bool_t -sendMessage( Socket fd, char* buf, int l, - unsigned int dstIp, unsigned short dstPort) -{ - int s; - - if (fd == INVALID_SOCKET) - return FALSE; - - if ( dstPort == 0 ) - { - /* sending on a connected port */ - s = send(fd,buf,l,0); - } - else - { - struct sockaddr_in to; - int toLen = sizeof(to); - if (dstIp == 0) - { - ortp_error("stun_udp: invalid IP provided (dstIP==0)"); - return FALSE; - } - - memset(&to,0,toLen); - - to.sin_family = AF_INET; - to.sin_port = htons(dstPort); - to.sin_addr.s_addr = htonl(dstIp); - - s = sendto(fd, buf, l, 0,(struct sockaddr*)&to, toLen); - } - - if ( s == SOCKET_ERROR ) - { - int e = getErrno(); - switch (e) - { - case ECONNREFUSED: - case EHOSTDOWN: - case EHOSTUNREACH: - { - /* quietly ignore this */ - } - break; - case EAFNOSUPPORT: - { - ortp_error("stun_udp: err EAFNOSUPPORT in send"); - } - break; - default: - { -#if !defined(_WIN32_WCE) - ortp_error("stun_udp: err %i %s in send", e, strerror(e)); -#else - ortp_error("stun_udp: err %i in send", e); -#endif - } - } - return FALSE; - } - - if ( s == 0 ) - { - ortp_error("stun_udp: no data sent in send"); - return FALSE; - } - - if ( s != l ) - { - ortp_error("stun_udp: only %i out of %i bytes sent", s, l); - return FALSE; - } - - return TRUE; -} - - -void -initNetwork() -{ -#if defined(WIN32) || defined(_WIN32_WCE) - WORD wVersionRequested = MAKEWORD( 2, 2 ); - WSADATA wsaData; - int err; - - err = WSAStartup( wVersionRequested, &wsaData ); - if ( err != 0 ) - { - /* could not find a usable WinSock DLL */ - ortp_error("stun_udp: Could not load winsock"); - } - - /* Confirm that the WinSock DLL supports 2.2.*/ - /* Note that if the DLL supports versions greater */ - /* than 2.2 in addition to 2.2, it will still return */ - /* 2.2 in wVersion since that is the version we */ - /* requested. */ - - if ( LOBYTE( wsaData.wVersion ) != 2 || - HIBYTE( wsaData.wVersion ) != 2 ) - { - /* Tell the user that we could not find a usable */ - /* WinSock DLL. */ - WSACleanup( ); - ortp_error("stun_udp: Wrong winsock (!= 2.2) version"); - } -#endif -} - - -/* ==================================================================== - * The Vovida Software License, Version 1.0 - * - * Copyright (c) 2000 Vovida Networks, 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 names "VOCAL", "Vovida Open Communication Application Library", - * and "Vovida Open Communication Application Library (VOCAL)" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact vocal@vovida.org. - * - * 4. Products derived from this software may not be called "VOCAL", nor - * may "VOCAL" appear in their name, without prior written - * permission of Vovida Networks, Inc. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND - * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA - * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES - * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (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 Vovida - * Networks, Inc. and many individuals on behalf of Vovida Networks, - * Inc. For more information on Vovida Networks, Inc., please see - * . - * - */ - -/* Local Variables: - mode:c - c-file-style:"ellemtel" - c-file-offsets:((case-label . +)) - indent-tabs-mode:nil - End: -*/ diff --git a/linphone/oRTP/src/system b/linphone/oRTP/src/system deleted file mode 100644 index 50dcc4375..000000000 --- a/linphone/oRTP/src/system +++ /dev/null @@ -1,15 +0,0 @@ -*############################################################ -*# -*# $Header: /sources/linphone/linphone/oRTP/src/system,v 1.1 2002/02/25 08:41:53 smorlat Exp $ -*# -*# $Source: /sources/linphone/linphone/oRTP/src/system,v $ -*# $Revision: 1.1 $ -*# $Locker: $ -*# -*############################################################ -$VERSION 1 -$CONFIGURE Y -$LOADABLE Y -$TUNABLE -$$$ - diff --git a/linphone/oRTP/src/telephonyevents.c b/linphone/oRTP/src/telephonyevents.c deleted file mode 100644 index 538bdba4e..000000000 --- a/linphone/oRTP/src/telephonyevents.c +++ /dev/null @@ -1,421 +0,0 @@ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc1889) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include "utils.h" -#include "rtpsession_priv.h" -#include - -PayloadType payload_type_telephone_event={ - PAYLOAD_AUDIO_PACKETIZED, /*type */ - 8000, /*clock rate */ - 0, /* bytes per sample N/A */ - NULL, /* zero pattern N/A*/ - 0, /*pattern_length N/A */ - 0, /* normal_bitrate */ - "telephone-event", /* MIME subtype */ - 0, /* Audio Channels N/A */ - 0 /*flags */ -}; - -/** - * Tells whether telephony events payload type is supported within the - * context of the rtp session. - * @param session a rtp session - * - * @return the payload type number used for telephony events if found, -1 if not found. -**/ -int rtp_session_telephone_events_supported(RtpSession *session) -{ - /* search for a telephony event payload in the current profile */ - session->snd.telephone_events_pt=rtp_profile_get_payload_number_from_mime(session->snd.profile,"telephone-event"); - session->rcv.telephone_events_pt=rtp_profile_get_payload_number_from_mime(session->rcv.profile,"telephone-event"); - /*printf("Telephone event pt is %i\n",session->telephone_events_pt);*/ - return session->snd.telephone_events_pt; -} - - -/** - * Tells whether telephone event payload type is supported for send within the - * context of the rtp session. - * @param session a rtp session - * - * @return the payload type number used for telephony events if found, -1 if not found. -**/ -int rtp_session_send_telephone_events_supported(RtpSession *session) -{ - /* search for a telephony event payload in the current profile */ - session->snd.telephone_events_pt=rtp_profile_get_payload_number_from_mime(session->snd.profile,"telephone-event"); - /*printf("Telephone event pt is %i\n",session->telephone_events_pt);*/ - return session->snd.telephone_events_pt; -} - -/** - * Tells whether telephone event payload type is supported for receiving within the - * context of the rtp session. - * @param session a rtp session - * - * @return the payload type number used for telephony events if found, -1 if not found. -**/int rtp_session_recv_telephone_events_supported(RtpSession *session) -{ - /* search for a telephony event payload in the current profile */ - session->rcv.telephone_events_pt=rtp_profile_get_payload_number_from_mime(session->rcv.profile,"telephone-event"); - /*printf("Telephone event pt is %i\n",session->telephone_events_pt);*/ - return session->snd.telephone_events_pt; -} - - -/** - * Allocates a new rtp packet to be used to add named telephony events. The application can use - * then rtp_session_add_telephone_event() to add named events to the packet. - * Finally the packet has to be sent with rtp_session_sendm_with_ts(). - * - * @param session a rtp session. - * @param start boolean to indicate if the marker bit should be set. - * - * @return a message block containing the rtp packet if successfull, NULL if the rtp session - *cannot support telephony event (because the rtp profile it is bound to does not include - *a telephony event payload type). -**/ -mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start) -{ - mblk_t *mp; - rtp_header_t *rtp; - - return_val_if_fail(session->snd.telephone_events_pt!=-1,NULL); - - mp=allocb(RTP_FIXED_HEADER_SIZE+TELEPHONY_EVENTS_ALLOCATED_SIZE,BPRI_MED); - if (mp==NULL) return NULL; - rtp=(rtp_header_t*)mp->b_rptr; - rtp->version = 2; - rtp->markbit=start; - rtp->padbit = 0; - rtp->extbit = 0; - rtp->cc = 0; - rtp->ssrc = session->snd.ssrc; - /* timestamp set later, when packet is sended */ - /*seq number set later, when packet is sended */ - - /*set the payload type */ - rtp->paytype=session->snd.telephone_events_pt; - - /*copy the payload */ - mp->b_wptr+=RTP_FIXED_HEADER_SIZE; - return mp; -} - - -/** - *@param session a rtp session. - *@param packet a rtp packet as a mblk_t - *@param event the event type as described in rfc2833, ie one of the TEV_* macros. - *@param end a boolean to indicate if the end bit should be set. (end of tone) - *@param volume the volume of the telephony tone, as described in rfc2833 - *@param duration the duration of the telephony tone, in timestamp unit. - * - * Adds a named telephony event to a rtp packet previously allocated using - * rtp_session_create_telephone_event_packet(). - * - *@return 0 on success. -**/ -int rtp_session_add_telephone_event(RtpSession *session, - mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration) -{ - mblk_t *mp=packet; - telephone_event_t *event_hdr; - - - /* find the place where to add the new telephony event to the packet */ - while(mp->b_cont!=NULL) mp=mp->b_cont; - /* see if we need to allocate a new mblk_t */ - if ( ( mp->b_wptr) >= (mp->b_datap->db_lim)){ - mblk_t *newm=allocb(TELEPHONY_EVENTS_ALLOCATED_SIZE,BPRI_MED); - mp->b_cont=newm; - mp=mp->b_cont; - } - if (mp==NULL) return -1; - event_hdr=(telephone_event_t*)mp->b_wptr; - event_hdr->event=event; - event_hdr->R=0; - event_hdr->E=end; - event_hdr->volume=volume; - event_hdr->duration=htons(duration); - mp->b_wptr+=sizeof(telephone_event_t); - return 0; -} -/** - * This functions creates telephony events packets for dtmf and sends them. - * It uses rtp_session_create_telephone_event_packet() and - * rtp_session_add_telephone_event() to create them and finally - * rtp_session_sendm_with_ts() to send them. - * - * @param session a rtp session - * @param dtmf a character meaning the dtmf (ex: '1', '#' , '9' ...) - * @param userts the timestamp - * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not valid. -**/ -int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts) -{ - return rtp_session_send_dtmf2(session, dtmf, userts, 480); -} - -/** - * A variation of rtp_session_send_dtmf() with duration specified. - * - * @param session a rtp session - * @param dtmf a character meaning the dtmf (ex: '1', '#' , '9' ...) - * @param userts the timestamp - * @param duration duration of the dtmf in timestamp units - * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not valid. -**/ -int rtp_session_send_dtmf2(RtpSession *session, char dtmf, uint32_t userts, int duration) -{ - mblk_t *m1,*m2,*m3; - int tev_type; - int durationtier = duration/3; - - /* create the first telephony event packet */ - switch (dtmf){ - case '1': - tev_type=TEV_DTMF_1; - break; - case '2': - tev_type=TEV_DTMF_2; - break; - case '3': - tev_type=TEV_DTMF_3; - break; - case '4': - tev_type=TEV_DTMF_4; - break; - case '5': - tev_type=TEV_DTMF_5; - break; - case '6': - tev_type=TEV_DTMF_6; - break; - case '7': - tev_type=TEV_DTMF_7; - break; - case '8': - tev_type=TEV_DTMF_8; - break; - case '9': - tev_type=TEV_DTMF_9; - break; - case '*': - tev_type=TEV_DTMF_STAR; - break; - case '0': - tev_type=TEV_DTMF_0; - break; - case '#': - tev_type=TEV_DTMF_POUND; - break; - - case 'A': - case 'a': - tev_type=TEV_DTMF_A; - break; - - - case 'B': - case 'b': - tev_type=TEV_DTMF_B; - break; - - case 'C': - case 'c': - tev_type=TEV_DTMF_C; - break; - - case 'D': - case 'd': - tev_type=TEV_DTMF_D; - break; - - case '!': - tev_type=TEV_FLASH; - break; - - - default: - ortp_warning("Bad dtmf: %c.",dtmf); - return -1; - } - - m1=rtp_session_create_telephone_event_packet(session,1); - if (m1==NULL) return -1; - rtp_session_add_telephone_event(session,m1,tev_type,0,10,durationtier); - /* create a second packet */ - m2=rtp_session_create_telephone_event_packet(session,0); - if (m2==NULL) return -1; - rtp_session_add_telephone_event(session,m2,tev_type,0,10, durationtier+durationtier); - - /* create a third and final packet */ - m3=rtp_session_create_telephone_event_packet(session,0); - if (m3==NULL) return -1; - rtp_session_add_telephone_event(session,m3,tev_type,1,10,duration); - - /* and now sends them */ - rtp_session_sendm_with_ts(session,m1,userts); - rtp_session_sendm_with_ts(session,m2,userts); - /* the last packet is sent three times in order to improve reliability*/ - m1=copymsg(m3); - m2=copymsg(m3); - /* NOTE: */ - /* we need to copymsg() instead of dupmsg() because the buffers are modified when - the packet is sended because of the host-to-network conversion of timestamp,ssrc, csrc, and - seq number. - */ - rtp_session_sendm_with_ts(session,m3,userts); - session->rtp.snd_seq--; - rtp_session_sendm_with_ts(session,m1,userts); - session->rtp.snd_seq--; - rtp_session_sendm_with_ts(session,m2,userts); - return 0; -} - - -/** - * Reads telephony events from a rtp packet. *@tab points to the beginning of the event buffer. - * - * @param session a rtp session from which telephony events are received. - * @param packet a rtp packet as a mblk_t. - * @param tab the address of a pointer. - * @return the number of events in the packet if successfull, 0 if the packet did not contain telephony events. -**/ -int rtp_session_read_telephone_event(RtpSession *session, - mblk_t *packet,telephone_event_t **tab) -{ - int datasize; - int num; - int i; - telephone_event_t *tev; - rtp_header_t *hdr=(rtp_header_t*)packet->b_rptr; - unsigned char *payload; - if (hdr->paytype!=session->rcv.telephone_events_pt) return 0; /* this is not tel ev.*/ - datasize=rtp_get_payload(packet,&payload); - tev=*tab=(telephone_event_t*)payload; - /* convert from network to host order what should be */ - num=datasize/sizeof(telephone_event_t); - for (i=0;ion_telephone_event,(long)(long)event[0].event); - if (session->eventqs!=NULL){ - ev=ortp_event_new(ORTP_EVENT_TELEPHONE_EVENT); - evd=ortp_event_get_data(ev); - evd->packet=dupmsg(session->current_tev); - evd->info.telephone_event=event[0].event; - rtp_session_dispatch_event(session,ev); - } -} - -static void notify_events_ended(RtpSession *session, telephone_event_t *events, int num){ - int i; - for (i=0;ib_rptr; - - datasize=rtp_get_payload(m0,&payload); - - num=datasize/sizeof(telephone_event_t); - events=(telephone_event_t*)payload; - - - if (hdr->markbit==1) - { - /* this is a start of new events. Store the event buffer for later use*/ - if (session->current_tev!=NULL) { - freemsg(session->current_tev); - session->current_tev=NULL; - } - session->current_tev=copymsg(m0); - /* handle the case where the events are short enough to end within the packet that has the marker bit*/ - notify_events_ended(session,events,num); - } - /* whatever there is a markbit set or not, we parse the packet and compare it to previously received one */ - cur_tev=session->current_tev; - if (cur_tev!=NULL) - { - /* first compare timestamp, they must be identical */ - if (((rtp_header_t*)cur_tev->b_rptr)->timestamp== - ((rtp_header_t*)m0->b_rptr)->timestamp) - { - datasize=rtp_get_payload(cur_tev,&payload); - num2=datasize/sizeof(telephone_event_t); - evbuf=(telephone_event_t*)payload; - for (i=0;icurrent_tev!=NULL) { - freemsg(session->current_tev); - session->current_tev=NULL; - } - session->current_tev=copymsg(m0); - notify_events_ended(session,events,num); - } - } - else - { - /* there is no pending events, but we did not received marked bit packet - either the sending implementation is not compliant, either it has been lost, - we must deal with it anyway.*/ - session->current_tev=copymsg(m0); - /* inform the application if there are tone ends */ - notify_events_ended(session,events,num); - } -} diff --git a/linphone/oRTP/src/tests/.gitignore b/linphone/oRTP/src/tests/.gitignore deleted file mode 100644 index 4f1b0f522..000000000 --- a/linphone/oRTP/src/tests/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -Makefile -Makefile.in -.deps -.libs -*.lo -*.la -mrtprecv -mrtpsend -rtpmemtest -rtprecv -rtpsend -test_timer -tevmrtprecv -tevrtprecv -tevrtpsend -rtpsend_stupid diff --git a/linphone/oRTP/src/tests/Makefile.am b/linphone/oRTP/src/tests/Makefile.am deleted file mode 100644 index 793312b0d..000000000 --- a/linphone/oRTP/src/tests/Makefile.am +++ /dev/null @@ -1,32 +0,0 @@ -SUBDIRS=win_receiver win_sender - -if BUILD_TESTS - -noinst_PROGRAMS= rtpsend rtprecv mrtpsend mrtprecv test_timer rtpmemtest tevrtpsend tevrtprecv tevmrtprecv rtpsend_stupid - -rtpsend_SOURCES= rtpsend.c - -rtprecv_SOURCES= rtprecv.c - -mrtpsend_SOURCES= mrtpsend.c - -mrtprecv_SOURCES= mrtprecv.c - -rtpmemtest_SOURCES= rtpmemtest.c - -test_timer_SOURCES= test_timer.c - -tevrtpsend_SOURCES= tevrtpsend.c - -tevrtprecv_SOURCES= tevrtprecv.c - -tevmrtprecv_SOURCES= tevmrtprecv.c - -rtpsend_stupid_SOURCES=rtpsend_stupid.c - -endif - -AM_CFLAGS= -D_ORTP_SOURCE $(PTHREAD_CFLAGS) -AM_LDFLAGS= $(PTHREAD_LDFLAGS) -LDADD=$(top_builddir)/src/libortp.la $(SRTP_LIBS) $(SSL_LIBS) -INCLUDES=-I$(top_srcdir)/include/ diff --git a/linphone/oRTP/src/tests/mrtprecv.c b/linphone/oRTP/src/tests/mrtprecv.c deleted file mode 100644 index 22f5fdff7..000000000 --- a/linphone/oRTP/src/tests/mrtprecv.c +++ /dev/null @@ -1,159 +0,0 @@ -/* - The oRTP LinPhone RTP library intends to provide basics for a RTP stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* this program shows how to receive streams in paralel using the SessionSet api - and two threads only. */ - -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include - -#include -#include -#include -#endif - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; - -#define STREAMS_COUNT 1000 - -/* malloc'd in order to detect buffer overflows with efence */ -static uint8_t* recvbuf=0; - -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,recvbuf,160,ts,&havemore); - if (havemore) printf("warning: havemore=%i!\n",havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); - /* to indicate that (for the application) the stream has started, so we can start - recording on disk */ - } - if (session->user_data != NULL) { - size_t ret = write(fd,recvbuf,err); - assert( ret == err ); - } - } - return 0; -} - - -int main(int argc, char *argv[]) -{ - RtpSession *session[STREAMS_COUNT]; - int i; - int filefd[STREAMS_COUNT]; - int port; - uint32_t user_ts=0; - int channels; - SessionSet *set; - char *filename; - - if (argc<4){ - printf("%s",help); - return -1; - } - - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); - return -1; - } - - ortp_init(); - ortp_scheduler_init(); - - port=atoi(argv[2]); - recvbuf=ortp_malloc(160); - - for (i=0;i -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#endif - - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: mrtpsend filename ip port nstreams [--packet-size size] [--ts-inc value]\n"; - -#define STREAMS_COUNT 1000 - - - -int main(int argc, char *argv[]) -{ - RtpSession *session[STREAMS_COUNT]; - unsigned char *buffer; - int packet_size=160; - int ts_inc=160; - int i; - FILE *infile; - char *ssrc; - int port; - uint32_t user_ts=0; - int channels; - SessionSet *set; - - if (argc<5){ - printf("%s",help); - return -1; - } - - channels=atoi(argv[4]); - if (channels==0){ - printf("%s",help); - return -1; - } - - /* look at command line options */ - for (i=5;i0) && (runcond) ) - { - int k; - //ortp_message("Sending packet."); - for (k=0;k -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#include -#include -#include -#else -//#include -#endif - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; - -#define STREAMS_COUNT 1000 - -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ - unsigned char buffer[160]; - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); - /* to indicate that (for the application) the stream has started, so we can start - recording on disk */ - } - if (session->user_data != NULL) { - size_t ret = write(fd,buffer,err); - assert( ret == err ); - } - } - return 0; -} - - -int main(int argc, char *argv[]) -{ - RtpSession *session[STREAMS_COUNT]; - int i; - int filefd[STREAMS_COUNT]; - int port; - uint32_t user_ts=0; - int channels; - SessionSet *set; - char *filename; - - argc=4; - argv[1]="/tmp/output"; - argv[2]="8000"; - argv[3]="100"; - - if (argc<4){ - printf("%s",help); - return -1; - } - - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); - return -1; - } - - ortp_init(); - ortp_scheduler_init(); - - port=atoi(argv[2]); - for (i=0;isetflags=%i\n",session[k]->setflags); - } - /* and then suspend the process by selecting() */ - session_set_select(set,NULL,NULL); - for (k=0;k -#include -#include -#ifndef _WIN32 -#include -#include -#include -#endif - -int cond=1; - -void stop_handler(int signum) -{ - cond=0; -} - -void ssrc_cb(RtpSession *session) -{ - printf("hey, the ssrc has changed !\n"); -} - -static char *help="usage: rtprecv filename loc_port [--format format] [--soundcard] [--noadapt] [--with-jitter ]\n"; - -#define MULAW 0 -#define ALAW 1 - -#if defined(__hpux) && HAVE_SYS_AUDIO_H - -#include - -int sound_init(int format) -{ - int fd; - fd=open("/dev/audio",O_WRONLY); - if (fd<0){ - perror("Can't open /dev/audio"); - return -1; - } - ioctl(fd,AUDIO_RESET,0); - ioctl(fd,AUDIO_SET_SAMPLE_RATE,8000); - ioctl(fd,AUDIO_SET_CHANNELS,1); - if (format==MULAW) - ioctl(fd,AUDIO_SET_DATA_FORMAT,AUDIO_FORMAT_ULAW); - else ioctl(fd,AUDIO_SET_DATA_FORMAT,AUDIO_FORMAT_ALAW); - return fd; -} -#else -int sound_init(int format) -{ - return -1; -} -#endif - -int main(int argc, char*argv[]) -{ - RtpSession *session; - unsigned char buffer[160]; - int err; - uint32_t ts=0; - int stream_received=0; - FILE *outfile; - int local_port; - int have_more; - int i; - int format=0; - int soundcard=0; - int sound_fd=0; - int jittcomp=40; - bool_t adapt=TRUE; - - /* init the lib */ - if (argc<3){ - printf("%s",help); - return -1; - } - local_port=atoi(argv[2]); - if (local_port<=0) { - printf("%s",help); - return -1; - } - for (i=3;i0) stream_received=1; - /* this is to avoid to write to disk some silence before the first RTP packet is returned*/ - if ((stream_received) && (err>0)) { - size_t ret = fwrite(buffer,1,err,outfile); - if (sound_fd>0) - ret = write(sound_fd,buffer,err); - } - } - ts+=160; - //ortp_message("Receiving packet."); - } - - rtp_session_destroy(session); - ortp_exit(); - - ortp_global_stats_display(); - - return 0; -} diff --git a/linphone/oRTP/src/tests/rtpsend.c b/linphone/oRTP/src/tests/rtpsend.c deleted file mode 100644 index d1fefe830..000000000 --- a/linphone/oRTP/src/tests/rtpsend.c +++ /dev/null @@ -1,128 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#endif - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static const char *help="usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-jitter ]\n"; - -int main(int argc, char *argv[]) -{ - RtpSession *session; - unsigned char buffer[160]; - int i; - FILE *infile; - char *ssrc; - uint32_t user_ts=0; - int clockslide=0; - int jitter=0; - if (argc<4){ - printf("%s", help); - return -1; - } - for(i=4;i=argc) { - printf("%s", help); - return -1; - } - clockslide=atoi(argv[i]); - ortp_message("Using clockslide of %i milisecond every 50 packets.",clockslide); - }else if (strcmp(argv[i],"--with-jitter")==0){ - ortp_message("Jitter will be added to outgoing stream."); - i++; - if (i>=argc) { - printf("%s", help); - return -1; - } - jitter=atoi(argv[i]); - } - } - - ortp_init(); - ortp_scheduler_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR); - session=rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_connected_mode(session,TRUE); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_payload_type(session,0); - - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); - } - - #ifndef _WIN32 - infile=fopen(argv[1],"r"); - #else - infile=fopen(argv[1],"rb"); - #endif - - if (infile==NULL) { - perror("Cannot open file"); - return -1; - } - - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - rtp_session_send_with_ts(session,buffer,i,user_ts); - user_ts+=160; - if (clockslide!=0 && user_ts%(160*50)==0){ - ortp_message("Clock sliding of %i miliseconds now",clockslide); - rtp_session_make_time_distorsion(session,clockslide); - } - /*this will simulate a burst of late packets */ - if (jitter && (user_ts%(8000)==0)) { - struct timespec pausetime, remtime; - ortp_message("Simulating late packets now (%i milliseconds)",jitter); - pausetime.tv_sec=jitter/1000; - pausetime.tv_nsec=(jitter%1000)*1000000; - while(nanosleep(&pausetime,&remtime)==-1 && errno==EINTR){ - pausetime=remtime; - } - } - } - - fclose(infile); - rtp_session_destroy(session); - ortp_exit(); - ortp_global_stats_display(); - - return 0; -} diff --git a/linphone/oRTP/src/tests/rtpsend_stupid.c b/linphone/oRTP/src/tests/rtpsend_stupid.c deleted file mode 100644 index 80db79a28..000000000 --- a/linphone/oRTP/src/tests/rtpsend_stupid.c +++ /dev/null @@ -1,126 +0,0 @@ - /* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#endif -/*defined in library, but not declared in public headers (this method is only useful for tests)*/ -extern int __rtp_session_sendm_with_ts(RtpSession *session, mblk_t *packet, uint32_t packet_ts, uint32_t send_ts); - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-ptime ]\n"; - -int main(int argc, char *argv[]) -{ - RtpSession *session; - unsigned char buffer[160]; - int i; - FILE *infile; - char *ssrc; - uint32_t packet_ts=0,send_ts=0; - uint32_t send_ts_inc=160; - int clockslide=0; - int jitter=0; - if (argc<4){ - printf("%s",help); - return -1; - } - for(i=4;i=argc) { - printf("%s",help); - return -1; - } - clockslide=atoi(argv[i]); - ortp_message("Using clockslide of %i milisecond every 50 packets.",clockslide); - }else if (strcmp(argv[i],"--with-ptime")==0){ - ortp_message("Ptime related jitter will be added to outgoing stream."); - i++; - if (i>=argc) { - printf("%s",help); - return -1; - } - jitter=atoi(argv[i]); - send_ts_inc=jitter*8; - } - } - - ortp_init(); - ortp_scheduler_init(); - ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR); - session=rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_connected_mode(session,TRUE); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_payload_type(session,0); - - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); - } - - #ifndef _WIN32 - infile=fopen(argv[1],"r"); - #else - infile=fopen(argv[1],"rb"); - #endif - - if (infile==NULL) { - perror("Cannot open file"); - return -1; - } - - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - mblk_t *m=rtp_session_create_packet(session,RTP_FIXED_HEADER_SIZE,buffer,i); - __rtp_session_sendm_with_ts(session,m,packet_ts,send_ts); - packet_ts+=160; - if ((send_ts+send_ts_inc)<=packet_ts){ - send_ts+=send_ts_inc; - } - if (clockslide!=0 && send_ts%(160*50)==0){ - ortp_message("Clock sliding of %i miliseconds now",clockslide); - rtp_session_make_time_distorsion(session,clockslide); - } - } - - fclose(infile); - rtp_session_destroy(session); - ortp_exit(); - ortp_global_stats_display(); - - return 0; -} diff --git a/linphone/oRTP/src/tests/test_timer.c b/linphone/oRTP/src/tests/test_timer.c deleted file mode 100644 index 48f4d0da2..000000000 --- a/linphone/oRTP/src/tests/test_timer.c +++ /dev/null @@ -1,43 +0,0 @@ - /* - The oRTP LinPhone RTP library intends to provide basics for a RTP stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include "../rtptimer.h" -#include - -int main(int argc, char *argv[]) -{ - RtpTimer *timer=&posix_timer; - int i; - struct timeval interval; - - interval.tv_sec=0; - interval.tv_usec=500000; - - rtp_timer_set_interval(timer,&interval); - - timer->timer_init(); - for (i=0;i<10;i++) - { - printf("doing something...\n"); - timer->timer_do(); - } - timer->timer_uninit(); - return 0; -} diff --git a/linphone/oRTP/src/tests/tevmrtprecv.c b/linphone/oRTP/src/tests/tevmrtprecv.c deleted file mode 100644 index 023bec798..000000000 --- a/linphone/oRTP/src/tests/tevmrtprecv.c +++ /dev/null @@ -1,175 +0,0 @@ - /* - The oRTP LinPhone RTP library intends to provide basics for a RTP stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* this program shows how to receive streams in paralel using the SessionSet api - and two threads only. */ - -#include -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#include -#include -#include - -#else -//#include -#endif - -#include - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; - -static int *p_channel_id; - -int dtmf_count=0; - -static char *help="usage: tevmrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams with telephone events on local_port+2*k, k={0..number_of_streams}\n"; - -#define STREAMS_COUNT 1000 - - -void recv_tev_cb(RtpSession *session,int type,long user_data) -{ - //printf("Receiving telephony event:%i\n",type); - if (type<16) printf("This is dtmf %c on channel %d\n",dtmf_tab[type],*(int *)user_data); - dtmf_count++; -} - -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ - unsigned char buffer[160]; - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); - /* to indicate that (for the application) the stream has started, so we can start - recording on disk */ - } - if (session->user_data != NULL) { - size_t ret = write(fd,buffer,err); - assert( ret == err ); - } - } - return 0; -} - - -int main(int argc, char *argv[]) -{ - RtpSession *session[STREAMS_COUNT]; - int i; - int filefd[STREAMS_COUNT]; - int port; - uint32_t user_ts=0; - int channels; - SessionSet *set; - char *filename; - - if (argc<4){ - printf("%s",help); - return -1; - } - - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); - return -1; - } - - ortp_init(); - ortp_scheduler_init(); - - /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); - - port=atoi(argv[2]); - p_channel_id = (int *)ortp_malloc(channels*sizeof(int)); - for (i=0;i -#include -#include -#include -#include -#include -#ifndef _WIN32 -#include -#else -#include -#endif -#include - -int runcond=1; - -static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: test_tevrecv filename loc_port\n"; - -int dtmf_count=0; - -void recv_tev_cb(RtpSession *session,int type,long user_data) -{ - printf("Receiving telephony event:%i\n",type); - if (type<16) printf("This is dtmf %c\n",dtmf_tab[type]); - dtmf_count++; -} - -int main(int argc, char *argv[]) -{ - RtpSession *session; - unsigned char buffer[160]; - int err; - FILE *outfile; - uint32_t ts=0; - int have_more; - - if (argc<3){ - printf("%s",help); - return -1; - } - - ortp_init(); - ortp_scheduler_init(); - - /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); - - session=rtp_session_new(RTP_SESSION_RECVONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_local_addr(session,"0.0.0.0",atoi(argv[2])); - rtp_session_set_payload_type(session,0); - - /* register for telephony events */ - rtp_session_signal_connect(session,"telephone-event",(RtpCallback)recv_tev_cb,0); - - outfile=fopen(argv[1],"wb"); - if (outfile==NULL) { - perror("Cannot open file"); - return -1; - } - signal(SIGINT,stophandler); - while(runcond) - { - have_more=1; - while (have_more){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&have_more); - if (err>0) { - size_t ret = fwrite(buffer,1,err,outfile); - assert( ret == err ); - } - } - ts+=160; - //ortp_message("Receiving packet."); - } - fclose(outfile); - rtp_session_destroy(session); - ortp_exit(); - ortp_global_stats_display(); - printf("Total dtmf events received: %i\n",dtmf_count); - return 0; -} diff --git a/linphone/oRTP/src/tests/tevrtpsend.c b/linphone/oRTP/src/tests/tevrtpsend.c deleted file mode 100644 index 185db8ff0..000000000 --- a/linphone/oRTP/src/tests/tevrtpsend.c +++ /dev/null @@ -1,99 +0,0 @@ -/* - The oRTP LinPhone RTP library intends to provide basics for a RTP stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include -#include -#ifndef _WIN32 -#include -#else -#include -#endif -#include - -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; -} - -static char *help="usage: test_tevsend filename dest_ip4addr dest_port\n"; - -int main(int argc, char *argv[]) -{ - RtpSession *session; - unsigned char buffer[160]; - int i; - FILE *infile; - char *ssrc; - uint32_t user_ts=0; - int tel=0; - - if (argc<4){ - printf("%s",help); - return -1; - } - - ortp_init(); - ortp_scheduler_init(); - - /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); - - session=rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_send_payload_type(session,0); - - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); - } - - infile=fopen(argv[1],"rb"); - if (infile==NULL) { - perror("Cannot open file"); - return -1; - } - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - //ortp_message("Sending packet."); - rtp_session_send_with_ts(session,buffer,i,user_ts); - user_ts+=160; - tel++; - if (tel==50){ - tel=0; - ortp_message("Sending telephony event packet."); - rtp_session_send_dtmf(session,'*',user_ts); - user_ts+=160+160+160; /* the duration of the dtmf */ - } - } - fclose(infile); - rtp_session_destroy(session); - ortp_exit(); - ortp_global_stats_display(); - return 0; -} diff --git a/linphone/oRTP/src/tests/win_receiver/.gitignore b/linphone/oRTP/src/tests/win_receiver/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/oRTP/src/tests/win_receiver/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/oRTP/src/tests/win_receiver/Makefile.am b/linphone/oRTP/src/tests/win_receiver/Makefile.am deleted file mode 100644 index e7e00556f..000000000 --- a/linphone/oRTP/src/tests/win_receiver/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=RTPReceiver.cpp RTPReceiver.vcproj - diff --git a/linphone/oRTP/src/tests/win_receiver/RTPReceiver.cpp b/linphone/oRTP/src/tests/win_receiver/RTPReceiver.cpp deleted file mode 100644 index 8701508f8..000000000 --- a/linphone/oRTP/src/tests/win_receiver/RTPReceiver.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#define STREAMS_COUNT 1000 - -BOOL m_bExit = FALSE; - -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; - - -void ProductVersion() -{ - char strBuffer[255]; - - printf("====================================\n"); - printf("Author : Simon Morlat =\n"); - printf("Porting : Yann STEPHAN =\n"); - printf("====================================\n"); - - memset(&strBuffer, 0x0, sizeof(strBuffer)); - - sprintf((char *) &strBuffer, "= RTPReceiver V1.0 - Date : %s - %s\n", __DATE__, __TIME__); - printf(strBuffer); - - printf("====================================\n"); -} - -BOOL ctrlHandlerFunction(DWORD fdwCtrlType) -{ - switch (fdwCtrlType) - { - // Handle the CTRL+C signal. - // CTRL+CLOSE: confirm that the user wants to exit. - case CTRL_C_EVENT: - case CTRL_CLOSE_EVENT: - case CTRL_BREAK_EVENT: - case CTRL_LOGOFF_EVENT: - case CTRL_SHUTDOWN_EVENT: - m_bExit = TRUE; - return TRUE; - - default: - return FALSE; - } -} - -int rtp2disk(RtpSession *session,uint32_t ts, FILE * fd) -{ - char buffer[160]; - int err,havemore=1; - - while (havemore) - { - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - - if (havemore) - printf("==> Warning: havemore=1!\n"); - - if (err>0) - { - rtp_session_set_data(session,(void*)1); - /* to indicate that (for the application) the stream has started, so we can start - recording on disk */ - } - - if (session->user_data != NULL) - { - fwrite(&buffer,1,160, fd); - } - } - return 0; -} - -int GetSystemInformation() -{ - SYSTEM_INFO SystemInfo; - - GetSystemInfo(&SystemInfo); - - return SystemInfo.dwNumberOfProcessors; -} - -int __cdecl main(int argc, char *argv[]) -{ - RtpSession * session[STREAMS_COUNT]; - FILE * filefd[STREAMS_COUNT]; - SessionSet * set; - - uint32_t user_ts = 0; - - int port = 0; - int channels = 0; - int i = 0; - int nCPUCount = 0; - int nSchedulerCPU = 2; - - char strFilename[MAX_PATH]; - - ProductVersion(); - - if (argc<4) - { - printf(help); - return -1; - } - - channels=atoi(argv[3]); - if (channels==0){ - printf(help); - return -1; - } - - // Now it's time to use the power of multiple CPUs - nCPUCount = GetSystemInformation(); - - printf("==> # of CPU detected : %d\n", nCPUCount); - - ortp_init(); - ortp_scheduler_init(); - - if (nCPUCount > 1) - { - if (nCPUCount > 2) - { - nSchedulerCPU = 3; - } - -/* if (ortp_bind_scheduler_to_cpu(nSchedulerCPU) != -1) - { - printf("==> Scheduler has been binded to CPU %d\n", nSchedulerCPU); - } - else - { - printf("==> Scheduler still binded to CPU 1\n"); - } -*/ - } - - port=atoi(argv[2]); - - for (i=0;i Cannot handle the CTRL-C...\n"); - } - - /* create a set */ - set=session_set_new(); - printf("==> RTP Receiver started\n"); - - while(m_bExit == FALSE) - { - int k; - - for (k=0;k Warning: session_set_select() is returning 0...\n"); - } - - for (k=0;k Session_set_is_set %d\n", k); - } - else - { - //printf("warning: session %i is not set !\n",k); - } - } - user_ts+=160; - } - - printf("==> Exiting\n"); - - for (i=0;i - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/oRTP/src/tests/win_sender/.gitignore b/linphone/oRTP/src/tests/win_sender/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/oRTP/src/tests/win_sender/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile diff --git a/linphone/oRTP/src/tests/win_sender/Makefile.am b/linphone/oRTP/src/tests/win_sender/Makefile.am deleted file mode 100644 index 3af05d969..000000000 --- a/linphone/oRTP/src/tests/win_sender/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -EXTRA_DIST=RTPSender.cpp RTPSender.vcproj - diff --git a/linphone/oRTP/src/tests/win_sender/RTPSender.cpp b/linphone/oRTP/src/tests/win_sender/RTPSender.cpp deleted file mode 100644 index 95630b079..000000000 --- a/linphone/oRTP/src/tests/win_sender/RTPSender.cpp +++ /dev/null @@ -1,265 +0,0 @@ -#include -#include - -#define STREAMS_COUNT 1000 - -enum -{ - EVENT_STOP, - EVENT_RTP, - EVENT_COUNT // Always last -}; - - -RtpSession * m_Session[STREAMS_COUNT]; - -int m_nPacket_Size = 160; -int m_nTimestamp_Inc = 160; - -char * m_pBuffer = NULL; -char * m_SSRC = NULL; - -int m_nChannels = 0; -int m_nPort = 0; - -HANDLE m_hEvents[EVENT_COUNT]; - -BOOL m_bExit = FALSE; - -static char *help="usage: mrtpsend filename ip port nstreams [--packet-size size] [--ts-inc value]\n"; - -BOOL ctrlHandlerFunction(DWORD fdwCtrlType) -{ - switch (fdwCtrlType) - { - // Handle the CTRL+C signal. - // CTRL+CLOSE: confirm that the user wants to exit. - case CTRL_C_EVENT: - case CTRL_CLOSE_EVENT: - case CTRL_BREAK_EVENT: - case CTRL_LOGOFF_EVENT: - case CTRL_SHUTDOWN_EVENT: - m_bExit = TRUE; - SetEvent(m_hEvents[EVENT_STOP]); - return TRUE; - - default: - return FALSE; - } -} - -int GetCommandArguments(int argc, char *argv[]) -{ - int nCounter; - - // Check the number of arguments - if (argc<5) - { - printf(help); - return -1; - } - - m_nChannels = atoi(argv[4]); - - // Get the number of channels - if (m_nChannels == 0) - { - printf(help); - return -1; - } - - /* look at command line options */ - for (nCounter=5; nCounter Sorry dude...\n"); - Sleep(1000); - return -1; - } - - printf("==> Starting the RTP Sender test\n"); - - - // =============== INSTALL THE CONTROL HANDLER =============== - if (SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ctrlHandlerFunction, TRUE) == 0) - { - printf("==> Cannot handle the CTRL-C...\n"); - } - - - printf("==> Timestamp increment will be %i\n" , m_nTimestamp_Inc); - printf("==> Packet size will be %i\n" , m_nPacket_Size); - - m_pBuffer = (char *) ortp_malloc(m_nPacket_Size); - - ortp_init(); - ortp_scheduler_init(); - printf("==> Scheduler initialized\n"); - - m_SSRC = getenv("SSRC"); - m_nPort = atoi(argv[3]); - - for (nCounter=0; nCounter < m_nChannels; nCounter++) - { - //printf("==> Channel [#%d]\n", nCounter); - - m_Session[nCounter] = rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(m_Session[nCounter],1); - rtp_session_set_blocking_mode(m_Session[nCounter],0); - rtp_session_set_remote_addr(m_Session[nCounter],argv[2], m_nPort); - rtp_session_set_send_payload_type(m_Session[nCounter],0); - - if (m_SSRC != NULL) - { - rtp_session_set_ssrc(m_Session[nCounter],atoi(m_SSRC)); - } - - m_nPort+=2; - } - - infile=fopen(argv[1],"rb"); - - if (infile==NULL) - { - printf("==> Cannot open file !!!!"); - Sleep(1000); - return -1; - } - -// printf("==> Open file\n"); - - /* Create a set */ - pSessionSet = session_set_new(); -// printf("==> Session set\n"); - - while( ((nCounter= (int) fread(m_pBuffer,1,m_nPacket_Size,infile))>0) && (m_bExit == FALSE) ) - { - int k; - //g_message("Sending packet."); - for (k=0;k Session set set %d\n", k); - } - /* and then suspend the process by selecting() */ - session_set_select(NULL,pSessionSet,NULL); - //printf("==> Session set select\n"); - - for (k=0;k Session set is set %d\n", k); - rtp_session_send_with_ts(m_Session[k],m_pBuffer,nCounter,m_nUser_Timestamp); - //g_message("packet sended !"); - } - } - m_nUser_Timestamp+=m_nTimestamp_Inc; - } - - fclose(infile); - printf("==> Close file\n"); - - - - for(nCounter=0;nCounter Remove the CTRL-C handler...\n"); - SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ctrlHandlerFunction, FALSE); - - // Wait for an input key - printf("Waiting for exit : "); - - for (nCounter = 0; nCounter < 4*5; nCounter++) - { - printf("."); - Sleep(250); - } - - return 0; -} - diff --git a/linphone/oRTP/src/tests/win_sender/RTPSender.vcproj b/linphone/oRTP/src/tests/win_sender/RTPSender.vcproj deleted file mode 100644 index 32b054186..000000000 --- a/linphone/oRTP/src/tests/win_sender/RTPSender.vcproj +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/linphone/oRTP/src/utils.c b/linphone/oRTP/src/utils.c deleted file mode 100644 index 436e2a2c2..000000000 --- a/linphone/oRTP/src/utils.c +++ /dev/null @@ -1,86 +0,0 @@ -/*************************************************************************** - * utils.c - * - * Wed Feb 23 14:15:36 2005 - * Copyright 2005 Simon Morlat - * Email simon.morlat@linphone.org - ****************************************************************************/ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ortp/port.h" -#include "utils.h" - -OList *o_list_new(void *data){ - OList *new_elem=(OList*)ortp_new0(OList,1); - new_elem->data=data; - return new_elem; -} - -OList * o_list_append(OList *elem, void * data){ - OList *new_elem=o_list_new(data); - OList *it=elem; - if (elem==NULL) return new_elem; - while (it->next!=NULL) it=o_list_next(it); - it->next=new_elem; - new_elem->prev=it; - return elem; -} - -OList * o_list_free(OList *list){ - OList *elem = list; - OList *tmp; - return_val_if_fail(list, list); - while(elem->next!=NULL) { - tmp = elem; - elem = elem->next; - ortp_free(tmp); - } - ortp_free(elem); - return NULL; -} - -OList *o_list_remove_link(OList *list, OList *elem){ - OList *ret; - if (elem==list){ - ret=elem->next; - elem->prev=NULL; - elem->next=NULL; - if (ret!=NULL) ret->prev=NULL; - ortp_free(elem); - return ret; - } - elem->prev->next=elem->next; - if (elem->next!=NULL) elem->next->prev=elem->prev; - elem->next=NULL; - elem->prev=NULL; - ortp_free(elem); - return list; -} - -OList * o_list_remove(OList *list, void *data){ - OList *it; - for(it=list;it!=NULL;it=it->next){ - if (it->data==data){ - return o_list_remove_link(list,it); - } - } - return list; -} - diff --git a/linphone/oRTP/src/utils.h b/linphone/oRTP/src/utils.h deleted file mode 100644 index 0a50fcf0f..000000000 --- a/linphone/oRTP/src/utils.h +++ /dev/null @@ -1,91 +0,0 @@ -/*************************************************************************** - * utils.h - * - * Wed Feb 23 14:15:36 2005 - * Copyright 2005 Simon Morlat - * Email simon.morlat@linphone.org - ****************************************************************************/ -/* - The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack. - Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef UTILS_H -#define UTILS_H - -#include "ortp/event.h" - -struct _OList { - struct _OList *next; - struct _OList *prev; - void *data; -}; - -typedef struct _OList OList; - - -#define o_list_next(elem) ((elem)->next) - -OList * o_list_append(OList *elem, void * data); -OList * o_list_remove(OList *list, void *data); -OList * o_list_free(OList *elem); - -#ifndef MIN -#define MIN(a,b) (((a)>(b)) ? (b) : (a)) -#endif -#ifndef MAX -#define MAX(a,b) (((a)>(b)) ? (a) : (b)) -#endif - -#define return_if_fail(expr) if (!(expr)) {printf("%s:%i- assertion"#expr "failed\n",__FILE__,__LINE__); return;} -#define return_val_if_fail(expr,ret) if (!(expr)) {printf("%s:%i- assertion" #expr "failed\n",__FILE__,__LINE__); return (ret);} - - -#define INT_TO_POINTER(truc) ((long)(long)(truc)) -#define POINTER_TO_INT(truc) ((int)(long)(truc)) - -typedef struct _dwsplit_t{ -#ifdef ORTP_BIGENDIAN - uint16_t hi; - uint16_t lo; -#else - uint16_t lo; - uint16_t hi; -#endif -} dwsplit_t; - -typedef union{ - dwsplit_t split; - uint32_t one; -} poly32_t; - -#ifdef ORTP_BIGENDIAN -#define hton24(x) (x) -#else -#define hton24(x) ((( (x) & 0x00ff0000) >>16) | (( (x) & 0x000000ff) <<16) | ( (x) & 0x0000ff00) ) -#endif -#define ntoh24(x) hton24(x) - -#if defined(WIN32) || defined(_WIN32_WCE) -#define is_would_block_error(errnum) (errnum==WSAEWOULDBLOCK) -#else -#define is_would_block_error(errnum) (errnum==EWOULDBLOCK || errnum==EAGAIN) -#endif - -void ortp_ev_queue_put(OrtpEvQueue *q, OrtpEvent *ev); - -#endif diff --git a/linphone/pixmaps/.gitignore b/linphone/pixmaps/.gitignore deleted file mode 100644 index 282522db0..000000000 --- a/linphone/pixmaps/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile -Makefile.in diff --git a/linphone/share/cs/.gitignore b/linphone/share/cs/.gitignore deleted file mode 100644 index 3dda72986..000000000 --- a/linphone/share/cs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Makefile.in -Makefile 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/mediastreamer2 b/mediastreamer2 new file mode 160000 index 000000000..d32cda045 --- /dev/null +++ b/mediastreamer2 @@ -0,0 +1 @@ +Subproject commit d32cda04540a3a2b0604a3184a5fec8dbc6d7b18 diff --git a/oRTP b/oRTP new file mode 160000 index 000000000..305f3368f --- /dev/null +++ b/oRTP @@ -0,0 +1 @@ +Subproject commit 305f3368f583102d1f8a788592dbabb92798edf1 diff --git a/p2pproxy/.classpath b/p2pproxy/.classpath deleted file mode 100644 index d4307deff..000000000 --- a/p2pproxy/.classpath +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/p2pproxy/.cvsignore b/p2pproxy/.cvsignore deleted file mode 100644 index da41270a3..000000000 --- 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 1084bf2f2..000000000 --- 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 fbea50776..000000000 --- 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 e69de29bb..000000000 diff --git a/p2pproxy/COPYING b/p2pproxy/COPYING deleted file mode 100644 index 94a9ed024..000000000 --- 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 e69de29bb..000000000 diff --git a/p2pproxy/INSTALL b/p2pproxy/INSTALL deleted file mode 100644 index 8b82ade08..000000000 --- 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 aaa51ae78..000000000 --- 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 e69de29bb..000000000 diff --git a/p2pproxy/README b/p2pproxy/README deleted file mode 100644 index e69de29bb..000000000 diff --git a/p2pproxy/autogen.sh b/p2pproxy/autogen.sh deleted file mode 100755 index d342f286b..000000000 --- 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 f1fc5f0c8..000000000 --- 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 1598057d7..000000000 --- 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 21eaf9330..000000000 --- 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 91f319160..000000000 --- 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 02d3a759f..000000000 --- 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 fffaf614f..000000000 --- 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 bf83df66c..000000000 --- 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 ce06b603c..000000000 --- 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 71452ad2f..000000000 --- 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 8e780dcc0..000000000 --- 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 04436dd7c..000000000 --- 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 bdb84acfe..000000000 --- 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 252e96052..000000000 --- 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 2c1f1ef7f..000000000 --- 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 a8109cfd1..000000000 --- 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 8c55d7806..000000000 --- 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 d20278976..000000000 --- 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 7aa7df3d7..000000000 --- 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 679a193d9..000000000 --- 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 e29831431..000000000 --- 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 40c73bd0b..000000000 --- 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 070d7d8d0..000000000 --- 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 04f1abb8b..000000000 --- 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 4ddd49229..000000000 --- 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 1afaec7b1..000000000 --- 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 1e6dab58b..000000000 --- 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 f4a9fa498..000000000 --- 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 1b7a2cfe6..000000000 --- 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 d5192ef28..000000000 --- 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 1dca91b47..000000000 --- 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 abaab15eb..000000000 --- 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 4f940adfe..000000000 --- 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 37e20f846..000000000 --- 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 76a6c17e7..000000000 --- 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 b72ffe7c2..000000000 --- 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 22dd58fb5..000000000 --- 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 502528c5b..000000000 --- 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 46ad1a0ef..000000000 --- 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 91c2d88e9..000000000 --- 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 d6f65fa75..000000000 --- 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 4f467d1c9..000000000 --- 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 f6604de0f..000000000 --- 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 e5183e820..000000000 --- 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 e9f7516ff..000000000 --- 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 75a45844a..000000000 --- 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 5e7c94d75..000000000 --- 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 1d1f7bbd9..000000000 --- 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 7b4aa9a5a..000000000 --- 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 081e8364c..000000000 --- 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 9a42252bd..000000000 --- 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 16bc378d1..000000000 --- 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 8e57de9a7..000000000 --- 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 e8c83c968..000000000 --- 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 4c201736b..000000000 --- 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 0c6cdabf3..000000000 --- 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 f3d47e7dd..000000000 --- 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 62ce541f7..000000000 --- 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 c304dd162..000000000 --- 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 88b88c8ef..000000000 --- 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 aa870cdfd..000000000 --- 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 eee489008..000000000 --- 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 1d746627b..000000000 --- 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 04b6c9194..000000000 --- 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 016d8f1bb..000000000 --- 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 dba00eee9..000000000 --- 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 2131e16d5..000000000 --- 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 c3e9734fc..000000000 --- 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 b73bd8d7f..000000000 --- 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 70e71ab7a..000000000 --- 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 bcee2c9fd..000000000 --- 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 c044aacb7..000000000 --- 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 73e19ddd7..000000000 --- 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 74154edd3..000000000 --- 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 0a3b07da7..000000000 --- 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 701a5b18c..000000000 --- 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 9ad6c2c6a..000000000 --- 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 304602cc2..000000000 --- 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 fda5b2753..000000000 --- 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 a1742ab6f..000000000 --- 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 c816cee9b..000000000 --- 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 1424da1e6..000000000 --- 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 091ffc8ee..000000000 --- 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 e579d09e2..000000000 --- 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 d81cba5eb..000000000 --- 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 ff8607ebf..000000000 --- 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 f2892b7e2..000000000 --- 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 38beb6621..000000000 --- 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 e804f579c..000000000 --- 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 a61d3cc9e..000000000 --- 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 27a8bf3c3..000000000 --- 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 16b30edc6..000000000 --- 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 4ebc94e02..000000000 --- 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 134699a84..000000000 --- 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 5c004c975..000000000 --- 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 1fd9d76d1..000000000 --- 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 d105c2a48..000000000 --- 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 766e20a6f..000000000 --- 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 84fad1982..000000000 --- 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 36584caea..000000000 --- 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 34b163370..000000000 --- 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 bcf4b6a1b..000000000 --- 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 09896027e..000000000 --- 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 df7c1cd6a..000000000 --- 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 47133f16d..000000000 --- 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 9b458e14e..000000000 --- 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 432542434..000000000 --- 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 763c257d8..000000000 --- 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 4f866a1d3..000000000 --- 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 995c7570d..000000000 --- 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 e28c3297d..000000000 --- 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 707fc0fa6..000000000 --- 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 83bbbe58e..000000000 --- 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 70b6078b2..000000000 --- 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 f7cab0846..000000000 --- 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 01ad8dc70..000000000 --- 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 297fc4925..000000000 --- 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 feb4c5fb4..000000000 --- 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 11b792275..000000000 --- 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 bd5317427..000000000 --- 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 1fd5f0176..000000000 --- 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 44f52d8f4..000000000 --- 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 8e2297a12..000000000 --- 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 80fa3c21d..000000000 --- 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 cb6f438d8..000000000 --- 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 2e98afe45..000000000 --- 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 85423115a..000000000 --- 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 b1624cd98..000000000 --- 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 d2b0468fc..000000000 --- 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 8f1973654..000000000 --- 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 24a2322ec..000000000 --- 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 398d20584..000000000 --- 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 993ca71b7..000000000 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 44e272ccf..000000000 --- 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 befd0941a..000000000 --- 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 ca4df0438..000000000 --- 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 06acba896..000000000 --- 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 b0d459ef5..000000000 --- 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 59ffc1f18..000000000 --- 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 3be7ab2b1..000000000 --- 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 cf593fa67..000000000 --- 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 69645fe8c..000000000 --- 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 a7655f633..000000000 --- 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 aa5875bd3..000000000 --- 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 5e565e25e..000000000 --- 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 7e72fa150..000000000 --- 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 72ac4e232..000000000 --- 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 dc046f319..000000000 --- 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 e731cd15b..000000000 --- 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 fbd517a77..000000000 --- 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 6f08b77fd..000000000 --- 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 0ac3b92b4..000000000 --- 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 f148a0ab6..000000000 --- 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 0d36f16c4..000000000 --- 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 fa72befc9..000000000 --- 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 67dff0323..000000000 --- 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 df66d6d61..000000000 --- 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 7e900561d..000000000 --- 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 bc182e5a6..000000000 --- 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 5835fff90..000000000 --- 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 a8cac02d7..000000000 --- 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 155ccd1ff..000000000 --- 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 2e20ff4c7..000000000 --- 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 6a8b25f5b..000000000 --- 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 7c5c1cd01..000000000 --- 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 a5705c1c6..000000000 --- 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 579249f04..000000000 --- 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 67eba550c..000000000 --- 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 90b157e86..000000000 --- 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 e4e1518cf..000000000 --- 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 6c508fb4a..000000000 --- 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 17d3ae2ce..000000000 --- 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 5d0379566..000000000 --- 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 67ffaaff2..000000000 --- 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 97d3503d0..000000000 --- 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 bfca65585..000000000 --- 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 3dc18b5c9..000000000 --- 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 b11b9e0f1..000000000 --- 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 c839dfd07..000000000 --- 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 6964fafbd..000000000 --- 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 05cea09c9..000000000 --- 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 6d5930c01..000000000 --- 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 7e49fdc0f..000000000 --- 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 1934ecfed..000000000 --- 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 15f7e936c..000000000 --- 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 5b9120841..000000000 --- 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 9ffc16bcf..000000000 --- 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 7049b0a7c..000000000 --- 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 3a94ce021..000000000 --- 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 5dfa38c59..000000000 --- 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 a1db26916..000000000 --- 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 727af617d..000000000 --- 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 8af488304..000000000 --- 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 1ad545aee..000000000 --- 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 2eb7734fa..000000000 --- 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 ea12ce67a..000000000 --- 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 6748e78cd..000000000 --- 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 bde492659..000000000 --- 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 7bf0777f1..000000000 --- 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 d76b330c0..000000000 --- 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 297f5362a..000000000 --- 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 391fd8fac..000000000 --- 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 30c198219..000000000 --- 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 22f51f4f7..000000000 --- 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 fb1486aa0..000000000 --- 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 ed6adf0e8..000000000 --- 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 18c77425d..000000000 --- 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 ce1e7e3a3..000000000 --- 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 7d63e4788..000000000 --- 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 57ad88857..000000000 --- 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 bff38674a..000000000 --- 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 321f0b58f..000000000 --- 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 791c05c05..000000000 --- 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 fdb70fec4..000000000 --- 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 a248abb02..000000000 --- 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 429e1c09e..000000000 --- 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 470065b77..000000000 --- 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 0296f0148..000000000 --- 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 749dd74ec..000000000 --- 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 bae578a31..000000000 --- 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 7ad728b8f..000000000 --- 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 63f1fc276..000000000 --- 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 66d16b784..000000000 --- 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 0714118b9..000000000 --- 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 128c3e878..000000000 --- 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 9d9171f96..000000000 --- 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 7d6057f6a..000000000 --- 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 41ffcd2e4..000000000 --- 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 f1b121d29..000000000 --- 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 6321ff5ab..000000000 --- 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 ca927c5c5..000000000 --- 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 2f94f6393..000000000 --- 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 effe1f6e7..000000000 --- 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 962ff3b3e..000000000 --- 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 c6e2d5840..000000000 --- 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 95c2ad775..000000000 --- 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 8c738c756..000000000 --- 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 ca73a2a0b..000000000 --- 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 85a7bb00e..000000000 --- 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 7bbb041bd..000000000 --- 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 28740206b..000000000 --- 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 f68676653..000000000 --- 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 0fafb7980..000000000 --- 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 22baaedf2..000000000 --- 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 df384c008..000000000 --- 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 c80de5efe..000000000 --- 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 7fb109e96..000000000 --- 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 f02363ffd..000000000 --- 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 f32e88dd8..000000000 --- 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 c4c1b99d2..000000000 --- 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 d665d8055..000000000 --- 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 1efce7a41..000000000 --- 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 443209e1c..000000000 --- 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 d056a1201..000000000 --- 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 0b61d9452..000000000 --- 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 1cd8292ed..000000000 --- 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 1762978f3..000000000 --- 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 2ffec1b64..000000000 --- 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 0f7e55fbb..000000000 --- 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 f66f65a2a..000000000 --- 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 4140ad2a5..000000000 --- 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 90177d2a5..000000000 --- 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 dccb3f1a8..000000000 --- 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 724bf3b5e..000000000 --- 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 241d8c71b..000000000 --- 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 ef76db6ff..000000000 --- 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 925ad7bb2..000000000 --- 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 f4849d112..000000000 --- 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 f88f5ffb4..000000000 --- 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 3dd7e6ef7..000000000 --- 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 4562ef6c8..000000000 --- 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 c225a79da..000000000 --- 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 d10ca0876..000000000 --- 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 796eb0634..000000000 --- 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 ba9116dc1..000000000 --- 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 01aa3c94f..000000000 --- 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 4dc0f944b..000000000 --- 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 af632e998..000000000 --- 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 915de2e7e..000000000 --- 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 a1daaf15d..000000000 --- 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 d3db1125a..000000000 --- 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 8cc33d7f2..000000000 --- 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 2a5c25fbe..000000000 --- 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 60aafbf66..000000000 --- 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 6084fd323..000000000 --- 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 37d0748db..000000000 --- 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 a11949487..000000000 --- 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 92e358763..000000000 --- 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 135c07d0d..000000000 --- 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 7ca0bd15a..000000000 --- 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 5d132c0ec..000000000 --- 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 142d33af3..000000000 --- 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 4d04e184c..000000000 --- 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 c502900fc..000000000 --- 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 b3f4614a5..000000000 --- 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 dc6809b40..000000000 --- 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 ee7456a52..000000000 --- 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 720eb008e..000000000 --- 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 fac60ea89..000000000 --- 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 109dbca68..000000000 --- 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 48dffd201..000000000 --- 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 754a0ced8..000000000 --- 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 4c08d2221..000000000 --- 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 28dccf3bb..000000000 --- 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 6ee9e4ec2..000000000 --- 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 250398abe..000000000 --- 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 5a2153c7f..000000000 --- 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 8bf71be1e..000000000 --- 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 8a0dfd9ae..000000000 --- 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 0fc088141..000000000 --- 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 c679feaae..000000000 --- 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 6bce09d21..000000000 --- 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 acd637cf9..000000000 --- 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 ab5ac489b..000000000 --- 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 3c3b3e261..000000000 --- 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 c62b150c8..000000000 --- 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 a89eee42d..000000000 --- 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 51188fe80..000000000 --- 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 8c7ed3403..000000000 --- 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 e731a7b6b..000000000 --- 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 27af78225..000000000 --- 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 1db223848..000000000 --- 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 febf54e41..000000000 --- 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 012e8fbe1..000000000 --- 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 ccf0ec267..000000000 --- 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 6f3cfd173..000000000 --- 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 7b9245f58..000000000 --- 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 a20925afd..000000000 --- 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 62dba7060..000000000 --- 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 ad8ab55d1..000000000 --- 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 72b07d075..000000000 --- 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 8a1a7093e..000000000 --- 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 3d72bf21d..000000000 --- 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 fa19f8544..000000000 --- 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 7a5ac9cce..000000000 --- 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 496d9f078..000000000 --- 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 da61b40a8..000000000 --- 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 ead443f6f..000000000 --- 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 c31034974..000000000 --- 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 5215f08f1..000000000 --- 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 cbebd9f43..000000000 --- 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 ab11a5b08..000000000 --- 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 a3e80dd58..000000000 --- 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 2cfd15733..000000000 --- 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 4e80d913d..000000000 --- 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 a38e1b814..000000000 --- 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 b1fc8cf4f..000000000 --- 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 4190d5a73..000000000 --- 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 3f2e70ca7..000000000 --- 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 2fc3bb68f..000000000 --- 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 1af8e6afb..000000000 --- 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 ca544b60e..000000000 --- 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 1d09ff673..000000000 --- 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 3e8b02752..000000000 --- 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 0cb944182..000000000 --- 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 4c790c2ad..000000000 --- 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 ed5f0f4f5..000000000 --- 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 d1d0ceb54..000000000 --- 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 a87ef04d7..000000000 --- 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 a1603cc94..000000000 --- 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 bd11b932e..000000000 --- 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 480d2dc35..000000000 --- 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 d655ee7e6..000000000 --- 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 5fdeda5be..000000000 --- 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 c61fca925..000000000 --- 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 ca7cc2c25..000000000 --- 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 c51c8bf94..000000000 --- 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 0a9a647cc..000000000 --- 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 ad3b42191..000000000 --- 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 57d2bdf33..000000000 --- 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 2f56ff626..000000000 --- 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 eed81a107..000000000 --- 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 616345c9d..000000000 --- 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 4ba50ed3e..000000000 --- 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 92d25b20c..000000000 --- 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 f7ea4da13..000000000 --- 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 689dedee1..000000000 --- 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 dc0f6b23e..000000000 --- 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 fd45a2f14..000000000 --- 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 f1266d38b..000000000 --- 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 a06006720..000000000 --- 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 101def961..000000000 --- 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 480115dab..000000000 --- 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 f49346740..000000000 --- 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 596e83d2f..000000000 --- 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 ca1f2108e..000000000 --- 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 39dcc8c7a..000000000 --- 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 59477bd5a..000000000 --- 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 0ffe37efe..000000000 --- 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 7556f18c0..000000000 --- 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 66295ebdf..000000000 --- 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 a2f133062..000000000 --- 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 f06ea65e2..000000000 --- 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 9163b7106..000000000 --- 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 468349983..000000000 --- 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 241ec06be..000000000 --- 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 e6807a711..000000000 --- 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 cd11469bc..000000000 --- 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 d2a05b220..000000000 --- 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 ae78841b3..000000000 --- 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 45054eb19..000000000 --- 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 ab61af508..000000000 --- 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 145312164..000000000 --- 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 34e85e71d..000000000 --- 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 39a49f8c1..000000000 --- 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 42b79195e..000000000 --- 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 37720c12b..000000000 --- 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 21a2475f6..000000000 --- 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 0775320cc..000000000 --- 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 2c386bbad..000000000 --- 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 d1c6cf9b6..000000000 --- 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 b578083dd..000000000 --- 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 0916f0049..000000000 --- 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 cf48a89ba..000000000 --- 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 3d28b78bb..000000000 --- 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 0a6de2e14..000000000 --- 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 559a61caa..000000000 --- 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 11c544b61..000000000 --- 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 b108b3f52..000000000 --- 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 9e923a7b7..000000000 --- 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 9b6180ff4..000000000 --- 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 485de10ab..000000000 --- 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 1bf6794f4..000000000 --- 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 cbf2f50ac..000000000 --- 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 b4a996037..000000000 --- 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 4f43a1137..000000000 --- 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 b0e98e521..000000000 --- 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 4d25c7bad..000000000 --- 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 509bc0cbe..000000000 --- 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 a574e119c..000000000 --- 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 db5075de4..000000000 --- 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 479d94a4b..000000000 --- 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 c249f030e..000000000 --- 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 965e4a420..000000000 --- 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 0772e7983..000000000 --- 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 f9ddfeffe..000000000 --- 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 5f5c87516..000000000 --- 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 a92d4857d..000000000 --- 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 dad252ec8..000000000 --- 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 a1ebefe4c..000000000 --- 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 91b9a7086..000000000 --- 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 9f6dee07f..000000000 --- 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 d8f1fae3e..000000000 --- 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 72a2ac936..000000000 --- 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 285e3a848..000000000 --- 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 ed74338c5..000000000 --- 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 33c259bd9..000000000 --- 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 e08308b90..000000000 --- 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 bc3f0a960..000000000 --- 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 08b83b46c..000000000 --- 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 b35dacbf9..000000000 --- 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 ad4a684a8..000000000 --- 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 f7deb2260..000000000 --- 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 7d6adfee7..000000000 --- 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 f41793501..000000000 --- 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 c35b9ce41..000000000 --- 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 86deacfd0..000000000 --- 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 9a304434c..000000000 --- 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 0c318380b..000000000 --- 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 eccf5342c..000000000 --- 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 93023f1cc..000000000 --- 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 71bd0f1d5..000000000 --- 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 768bb15ba..000000000 --- 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 e36833d0b..000000000 --- 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 b36266911..000000000 --- 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 8bdaae84c..000000000 --- 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 15775068c..000000000 --- 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 e6abfb4f8..000000000 --- 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 22dbbe381..000000000 --- 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 c976b54d2..000000000 --- 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 b4d52dd8c..000000000 --- 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 d6d6946ea..000000000 --- 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 adb8fb925..000000000 --- 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 d10a85e16..000000000 --- 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 6e5a9d5ae..000000000 --- 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 3c3dbee5f..000000000 --- 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 bfeba1baa..000000000 --- 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 6eef38cc9..000000000 --- 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 e253c968a..000000000 --- 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 ae3607866..000000000 --- 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 b0297458c..000000000 --- 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 57b3d747e..000000000 --- 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 0575bd2b2..000000000 --- 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 6dea104d0..000000000 --- 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 39c8a0a69..000000000 --- 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 c700407da..000000000 --- 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 c46845954..000000000 --- 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 1d2929177..000000000 --- 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 5a54cb380..000000000 --- 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 ca0916c9c..000000000 --- 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 10e82bfc5..000000000 --- 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 181d0fb64..000000000 --- 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 05d12b56d..000000000 --- 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 b743e16b3..000000000 --- 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 8707da7f7..000000000 --- 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 ac1ce0078..000000000 --- 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 211d772ed..000000000 --- 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 e061b8f04..000000000 --- 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 fd233626a..000000000 --- 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 9afedf377..000000000 --- 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 22a60fe14..000000000 --- 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 b37fc0fc9..000000000 --- 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 7e890e7ae..000000000 --- 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 cd15ebad7..000000000 --- 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 9574bd1c2..000000000 --- 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 81e1cd9fe..000000000 --- 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 7d651b8c9..000000000 --- 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 9d3ff3924..000000000 --- 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 dab9789dd..000000000 --- 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 86508571f..000000000 --- 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 369cd9640..000000000 --- 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 ace7add16..000000000 --- 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 a1c2103c9..000000000 --- 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 518a75e89..000000000 --- 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 3696b13a2..000000000 --- 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 f0c1153f9..000000000 --- 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 8d7b0d376..000000000 --- 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 1c22185d2..000000000 --- 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 62b3cba44..000000000 --- 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 ebfc19e8f..000000000 --- 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 8404161b8..000000000 --- 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 7a7abe75f..000000000 --- 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 554fba6d5..000000000 --- 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 9893ec9b9..000000000 --- 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 bebb827ee..000000000 --- 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 bb7d7de3b..000000000 --- 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 ff9d91277..000000000 --- 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 921f0f03c..000000000 --- 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 a0919e5cf..000000000 --- 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 89421caf9..000000000 --- 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 4059bba4e..000000000 --- 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 398985541..000000000 --- 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 719c0f0e4..000000000 --- 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 d2e56f663..000000000 --- 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 07e2cc93f..000000000 --- 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 25c82181f..000000000 --- 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 44b006d83..000000000 --- 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 27a259462..000000000 --- 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 fab64a4db..000000000 --- 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 023bc5ea9..000000000 --- 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 cdad84e88..000000000 --- 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 08a737114..000000000 --- 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 99b089813..000000000 --- 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 59c707a59..000000000 --- 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 7ce022e3c..000000000 --- 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 f456b30ec..000000000 --- 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 03171ed60..000000000 --- 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 e505e26bc..000000000 --- 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 c3e9bcb02..000000000 --- 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 595f57130..000000000 --- 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 c326f1965..000000000 --- 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 5b6cd6ace..000000000 --- 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 e50e03aaf..000000000 --- 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 f08337c7e..000000000 --- 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 e9eac4bf2..000000000 --- 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 a52885521..000000000 --- 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 a6d7b1250..000000000 --- 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 ae75b1de5..000000000 --- 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 f455fc8e3..000000000 --- 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 19530b3b1..000000000 --- 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 de4b98a16..000000000 --- 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 fb705e57b..000000000 --- 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 0bb9a5ddb..000000000 --- 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 bdc6a90e1..000000000 --- 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 45815f43f..000000000 --- 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 97e93588c..000000000 --- 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 b9bbe67bc..000000000 --- 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 656a34645..000000000 --- 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 f2bf45f4f..000000000 --- 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 cea4bf09d..000000000 --- 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 b7399deec..000000000 --- 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 ab25ff809..000000000 --- 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 40fa9bbb6..000000000 --- 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 e5b29e555..000000000 --- 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 ea9eaff40..000000000 --- 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 f2f357a69..000000000 --- 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 4df5507fe..000000000 --- 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 c58fdf185..000000000 --- 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 10cf02c76..000000000 --- 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 1d10121b6..000000000 --- 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 e48ee64ed..000000000 --- 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 81fb365ba..000000000 --- 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 084276d07..000000000 --- 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 7f0cdbddb..000000000 --- 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 b505ebbe9..000000000 --- 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 019ce2d0c..000000000 --- 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 e9b20319c..000000000 --- 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 eec3b0042..000000000 --- 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 41c229213..000000000 --- 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 d0f711af9..000000000 --- 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 835f95a81..000000000 --- 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 25b8a576f..000000000 --- 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 ee6564ab7..000000000 --- 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 006640af9..000000000 --- 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 f460de78b..000000000 --- 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 34f12d491..000000000 --- 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 ab92b1383..000000000 --- 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 b2562e1a2..000000000 --- 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 5c510cc46..000000000 --- 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 b0462cfa9..000000000 --- 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 f61a1951f..000000000 --- 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 0ebf76460..000000000 --- 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 34f0b4068..000000000 --- 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 80b5afd2b..000000000 --- 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 5233416bd..000000000 --- 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 f6129632e..000000000 --- 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 6ddf13f9b..000000000 --- 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 9fdb2f628..000000000 --- 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 4b13995f3..000000000 --- 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 b7f21a9c9..000000000 --- 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 8091cd09e..000000000 --- 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 7b775f9f0..000000000 --- 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 b4b3074a4..000000000 --- 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 3291128be..000000000 --- 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 958e456f7..000000000 --- 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 fe04d57ca..000000000 --- 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 5d4359744..000000000 --- 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 d475410e4..000000000 --- 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 4ad7990f9..000000000 --- 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 c4cb52003..000000000 --- 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 f36fa2b45..000000000 --- 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 5b7b0e959..000000000 --- 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 0f4c887ec..000000000 --- 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 bd3c4839e..000000000 --- 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 6541bb1f0..000000000 --- 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 059a9456d..000000000 --- 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 d0f4d5d07..000000000 --- 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 6af7fe3fd..000000000 --- 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 17be80a6e..000000000 --- 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 8fe768228..000000000 --- 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 cdddff9cc..000000000 --- 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 9aa8e354c..000000000 --- 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 b27a81097..000000000 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 e8a967c32..000000000 --- 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 d2dee6f9b..000000000 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 4d220efea..000000000 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 ff5d1888f..000000000 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 ceb0e5ceb..000000000 --- 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 6279e5206..000000000 --- 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 dde997210..000000000 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 db8d0811b..000000000 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 a8e988416..000000000 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 a080fffa3..000000000 --- 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 a6611c769..000000000 --- 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 cf9890a0a..000000000 --- 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 488bd5f75..000000000 --- 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 9685c7609..000000000 --- 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 bb7a3d533..000000000 --- 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 1b13571ac..000000000 --- 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 f3d7000d3..000000000 --- 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 a6f15d484..000000000 --- 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 d37522418..000000000 --- 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 6246aeb1d..000000000 --- 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 1bfdcf486..000000000 --- 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 a47d2326f..000000000 --- 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 810010b5b..000000000 --- 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 05574c55f..000000000 --- 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 158f014df..000000000 --- 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 43ab871a0..000000000 --- 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 5b8495a27..000000000 --- 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 7faccef96..000000000 --- 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 15a023097..000000000 --- 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 f325156bb..000000000 --- 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 2ebeb322c..000000000 --- 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 c2732430e..000000000 --- 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 6ec39cc8e..000000000 --- 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 d8159d6cf..000000000 --- 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 d2ee5b5a7..000000000 --- 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 e3ba5ac6b..000000000 --- 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 f628e00e8..000000000 --- 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 56950b0e9..000000000 --- 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 bc70b5ded..000000000 --- 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 186cd29b5..000000000 --- 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 21b7698d8..000000000 --- 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 f5fab0aca..000000000 --- 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 351fc9ce2..000000000 --- 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 21f400244..000000000 --- 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 117fac451..000000000 --- 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 a36dc9847..000000000 --- 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 d35cf3ffb..000000000 --- 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 9598ba218..000000000 --- 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 82f15fc3b..000000000 --- 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 29bc46d54..000000000 --- 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 6a508f3c9..000000000 --- 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 9f5694d51..000000000 --- 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 beda4b18d..000000000 --- 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 364dd6623..000000000 --- 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 b5a982929..000000000 --- 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 9db1c993e..000000000 --- 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 7240a216f..000000000 --- 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 626444223..000000000 --- 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 5a887112c..000000000 --- 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 a809879cf..000000000 --- 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 fa71f7385..000000000 --- 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 6f0b5ae36..000000000 --- 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 36da0dc28..000000000 --- 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 312b89961..000000000 --- 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 4bc2f3eb5..000000000 --- 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 c40069791..000000000 --- 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 7a0b793db..000000000 --- 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 3761b885f..000000000 --- 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 7bf52c510..000000000 --- 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 106cf1b16..000000000 --- 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 c1afd50ce..000000000 --- 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 9f8fc1fa3..000000000 --- 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 9f49887af..000000000 --- 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 0660a7789..000000000 --- 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 0618b45d8..000000000 --- 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 5907c1ea0..000000000 --- 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 f30cf8884..000000000 --- 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 444c265f3..000000000 --- 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 93c55ebd2..000000000 --- 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 2e7f1d40b..000000000 --- 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 d83526fb1..000000000 --- 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 86904dd87..000000000 --- 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 7d246d0a3..000000000 --- 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 adcfc0e88..000000000 --- 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 f03c39734..000000000 --- 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 9a86b8a95..000000000 --- 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 ca553b184..000000000 --- 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 fcc16ce3e..000000000 --- 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 0efaacb35..000000000 --- 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 882d185b0..000000000 --- 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 666612239..000000000 --- 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 0dd6ba3d7..000000000 --- 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 328ff3893..000000000 --- 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 04a4d8dae..000000000 --- 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 4e6821977..000000000 --- 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 fd68158cb..000000000 --- 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 910da9b62..000000000 --- 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 07e2e261c..000000000 --- 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 2892902de..000000000 --- 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 10261cb28..000000000 --- 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 36951c140..000000000 --- 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 9f6f2d797..000000000 --- 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 8101fedd3..000000000 --- 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 e78dbc0cc..000000000 --- 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 3ef51d0b7..000000000 --- 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 837845b48..000000000 --- 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 075af0cdb..000000000 --- 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 e354b7379..000000000 --- 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 0c53f2fa6..000000000 --- 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 e2347347d..000000000 --- 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 32c5c447a..000000000 --- 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 add0cde6e..000000000 --- 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 fddfbb17c..000000000 --- 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 eefbe34ad..000000000 --- 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