From kawas at dev.open-bio.org Mon Nov 3 14:47:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 3 Nov 2008 14:47:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811031947.mA3Jlk6x016280@dev.open-bio.org> kawas Mon Nov 3 14:47:45 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv16245/src/main/org/biomoby/service/dashboard Modified Files: PerlMoSeSPanel.java Log Message: once in a while, a null pointer exception occurs because a button isnt created but a method is called on it [fixed]. moby-live/Java/src/main/org/biomoby/service/dashboard PerlMoSeSPanel.java,1.13,1.14 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java 2008/09/02 18:48:23 1.13 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java 2008/11/03 19:47:45 1.14 @@ -892,7 +892,8 @@ boolean updateFailed = false; public Object construct() { - generateBtn.setEnabled(false); + if (generateBtn != null) + generateBtn.setEnabled(false); propertyChannel.fire(DP_STATUS_MSG, "Synchronizing Perl-MoSeS Datatype Cache..."); console.setEnabledAppendMode(false); From kawas at dev.open-bio.org Thu Nov 6 13:32:33 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:33 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWXv3025548@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY Modified Files: Makefile.PL Changes Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY Makefile.PL,1.9,1.10 Changes,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/10/30 21:25:51 1.9 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/06 18:32:33 1.10 @@ -21,7 +21,7 @@ requires 'Log::Log4perl' => 1.12; requires 'Template' => 1.11; requires 'Config::Simple' => 4.58; - requires 'IO::Stringy' => 2.110; + requires 'IO::String' => 1.08; requires 'Unicode::String' => 2.09; requires 'File::HomeDir' => 0.65; requires 'File::ShareDir' => 0.05; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/10/30 21:27:34 1.8 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/06 18:32:33 1.9 @@ -12,6 +12,14 @@ for async modules. * added another service table for async services - added a missing use statement for DateTime in Base.pm + - swapped IO::Scalar with IO::String (for performance + reasons) + - applied patch to Utils.pm (thanks to Kenny Billiau). + patch caches file paths once found instead of looking + repeatedly for them. + - MOSES::MOBY::Cache::Registries::init used to do a file + read each time a new Registries object was instantiated. + Not the case anymore. .86 Sun May 11 - fixed a bug in one of the test cases. From kawas at dev.open-bio.org Thu Nov 6 13:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYlM025602@dev.open-bio.org> kawas Thu Nov 6 13:32:34 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache Modified Files: Registries.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache Registries.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm 2008/04/29 19:29:54 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm 2008/11/06 18:32:33 1.5 @@ -15,144 +15,174 @@ use vars qw /$VERSION/; $VERSION = sprintf "%d.%02d", q$Revision$ =~ /: (\d+)\.(\d+)/; -#----------------------------------------------------------------- -# A hard-coded list of the known registries. -# -# Please fill all details if you are adding new registry here. -# -# Do not create synonyms starting with 'http://' (they are in the -# roles of the hash keys) - this is how some methods distinguish -# between synonym and endpoint. -# -#----------------------------------------------------------------- - -my %REGISTRIES = - ( iCAPTURE => { endpoint => 'http://moby.ucalgary.ca/moby/MOBY-Central.pl', - namespace => 'http://moby.ucalgary.ca/MOBY/Central', - name => 'Sun Centre of Excellence, Calgary', - contact => 'Edward Kawas (edward.kawas at gmail.com)', - public => 'yes', - text => 'A curated public registry hosted at U of C, Calgary', - }, - IRRI => { endpoint => 'http://cropwiki.irri.org/cgi-bin/MOBY-Central.pl', - namespace => 'http://cropwiki.irri.org/MOBY/Central', - name => 'IRRI, Philippines', - contact => 'Mylah Rystie Anacleto (m.anacleto at cgiar.org)', - public => 'yes', - text => 'The MOBY registry at the International Rice Research Institute (IRRI) is intended mostly for Generation Challenge Program (GCP) developers. It allows the registration of experimental moby entities within GCP.', - }, - testing => { endpoint => 'http://bioinfo.icapture.ubc.ca/cgi-bin/mobycentral/MOBY-Central.pl', - namespace => 'http://bioinfo.icapture.ubc.ca/MOBY/Central', - name => 'Testing BioMoby registry', - contact => 'Edward Kawas (edward.kawas at gmail.com)', - public => 'yes', - }, - ); +use vars qw/ %REGISTRIES /; + +BEGIN { + our (%REGISTRIES); + my $already_init = 0; + + sub is_init { + return $already_init++; + } + + sub init_reg { + #----------------------------------------------------------------- + # A hard-coded list of the known registries. + # + # Please fill all details if you are adding new registry here. + # + # Do not create synonyms starting with 'http://' (they are in the + # roles of the hash keys) - this is how some methods distinguish + # between synonym and endpoint. + # + #----------------------------------------------------------------- + %REGISTRIES = ( + iCAPTURE => { + endpoint => 'http://moby.ucalgary.ca/moby/MOBY-Central.pl', + namespace => 'http://moby.ucalgary.ca/MOBY/Central', + name => 'Sun Centre of Excellence, Calgary', + contact => 'Edward Kawas (edward.kawas at gmail.com)', + public => 'yes', + text => 'A curated public registry hosted at U of C, Calgary', + }, + IRRI => { + endpoint => 'http://cropwiki.irri.org/cgi-bin/MOBY-Central.pl', + namespace => 'http://cropwiki.irri.org/MOBY/Central', + name => 'IRRI, Philippines', + contact => 'Mylah Rystie Anacleto (m.anacleto at cgiar.org)', + public => 'yes', + text => 'The MOBY registry at the International Rice Research Institute (IRRI) is intended mostly for Generation Challenge Program (GCP) developers. It allows the registration of experimental moby entities within GCP.', + }, + testing => { + endpoint => 'http://bioinfo.icapture.ubc.ca/cgi-bin/mobycentral/MOBY-Central.pl', + namespace => 'http://bioinfo.icapture.ubc.ca/MOBY/Central', + name => 'Testing BioMoby registry', + contact => 'Edward Kawas (edward.kawas at gmail.com)', + public => 'yes', + }, + ); + + # create a default registry + $REGISTRIES{default} = $REGISTRIES{iCAPTURE}; -$REGISTRIES{default} = $REGISTRIES{iCAPTURE}; + # read from config file user registries + # add user_registries + eval { + do { + + # is this the best way? + use lib $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR + || "/make/believe"; + use vars qw( %USER_REGISTRIES ); + require $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + if defined $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME; + foreach my $key ( sort keys %USER_REGISTRIES ) { + + # script if key exists + next if exists $REGISTRIES{$key}; + $REGISTRIES{$key} = $USER_REGISTRIES{$key}; + } + } + }; + unshift @INC, "/make/believe" if $@; + } +} #----------------------------------------------------------------- # init #----------------------------------------------------------------- sub init { - my $self = shift; - my %cloned = %REGISTRIES; - # add user_registries - eval { - do { - # is this the best way? - use lib $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || "/make/believe"; - use vars qw( %USER_REGISTRIES ); - require $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME - if defined $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME; - foreach my $key (sort keys %USER_REGISTRIES) { - # script if key exists - next if exists $cloned{$key}; - $cloned{$key} = $USER_REGISTRIES{$key} - } - } - }; - unshift @INC, "/make/believe" if $@; - $self->{registries} = \%cloned; + my $self = shift; + init_reg() unless is_init(); + my %cloned = %REGISTRIES; + $self->{registries} = \%cloned; } #----------------------------------------------------------------- # list #----------------------------------------------------------------- sub list { - my $self = shift; - return sort keys %{ $self->{registries} } if ref $self; + my $self = shift; + return sort keys %{ $self->{registries} } if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->list(); + return MOSES::MOBY::Cache::Registries->new()->list(); } #----------------------------------------------------------------- # get #----------------------------------------------------------------- sub get { - my ($self, $abbrev) = @_; - $abbrev ||= 'default'; - return $self->{registries}->{$abbrev} if ref $self; + my ( $self, $abbrev ) = @_; + $abbrev ||= 'default'; + return $self->{registries}->{$abbrev} if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->get($abbrev); + return MOSES::MOBY::Cache::Registries->new()->get($abbrev); } #----------------------------------------------------------------- # all #----------------------------------------------------------------- sub all { - my $self = shift; - return $self->{registries} if ref $self; + my $self = shift; + return $self->{registries} if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->all; + return MOSES::MOBY::Cache::Registries->new()->all; } #----------------------------------------------------------------- # add #----------------------------------------------------------------- sub add { - my ($self, %reg) = @_; + my ( $self, %reg ) = @_; # add using object methods ... - return MOSES::MOBY::Cache::Registries->new()->add(%reg) unless ref $self; - + return MOSES::MOBY::Cache::Registries->new()->add(%reg) unless ref $self; + # check for force my $force = exists $reg{force}; - + # check %reg hash for conformance and existance return -1 - unless defined $reg{namespace} and defined $reg{endpoint} - and defined $reg{synonym} and defined $reg{text} - and defined $reg{name} and defined $reg{contact} - and defined $reg{public}; - + unless defined $reg{namespace} + and defined $reg{endpoint} + and defined $reg{synonym} + and defined $reg{text} + and defined $reg{name} + and defined $reg{contact} + and defined $reg{public}; + $reg{public} = 'yes' - unless $reg{public} eq 'yes' || $reg{public} eq 'no'; - + unless $reg{public} eq 'yes' || $reg{public} eq 'no'; + return -1 - if $reg{synonym} =~ m"^http://"; - + if $reg{synonym} =~ m"^http://"; + return -2 - unless ((not defined $self->{registries}->{$reg{synonym}}) or $force); - + unless ( ( not defined $self->{registries}->{ $reg{synonym} } ) + or $force ); + # call update ... do { - eval { - $self->_update_user_registries(%reg); - }; - $LOG->warn ("Error updating user registries: $@") - if ($LOG->is_warn) and $@; - # return 0 if $@; # removed because we should be able to - + eval { $self->_update_user_registries(%reg); }; + $LOG->warn("Error updating user registries: $@") + if ( $LOG->is_warn ) + and $@; + + # return 0 if $@; # removed because we should be able to + #update $self->{registries} - $self->{registries}->{$reg{synonym}} = { - endpoint => $reg{endpoint}, - namespace => $reg{namespace}, - name => $reg{name}, - contact => $reg{contact}, - public => $reg{public}, - text => $reg{text}, + $self->{registries}->{ $reg{synonym} } = { + endpoint => $reg{endpoint}, + namespace => $reg{namespace}, + name => $reg{name}, + contact => $reg{contact}, + public => $reg{public}, + text => $reg{text}, }; + # return success return 0 if $@; return 1; @@ -163,120 +193,150 @@ # remove #----------------------------------------------------------------- sub remove { - my ($self, $name) = @_; + my ( $self, $name ) = @_; # add using object methods ... - return MOSES::MOBY::Cache::Registries->new()->remove($name) unless ref $self; - return 1 unless defined $self->{registries}->{$name}; + return MOSES::MOBY::Cache::Registries->new()->remove($name) + unless ref $self; + return 1 unless defined $self->{registries}->{$name}; + # do the remove do { eval { + # remove from file - my %args = - ( # some default values - user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), - user_reg_table => ($MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME || 'USER_REGISTRIES'), - ); - die "Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" - if $args{user_reg_dir} eq ''; - - # read the current user registry table - unshift (@INC, $args{user_reg_dir}); # place where USER_REGISTRIES could be - use vars qw ( %USER_REGISTRIES ); - eval { require $args{user_reg_table} }; - my $file_with_table; - if ($@) { - $LOG->warn ("Cannot find table of USER_REGISTRIES '" . $args{user_reg_table} . "': $@"); - $file_with_table = File::Spec->catfile ($args{user_reg_dir}, $args{user_reg_table}); - } else { + my %args = ( # some default values + user_reg_dir => + ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), + user_reg_table => ( + $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + || 'USER_REGISTRIES' + ), + ); + die +"Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" + if $args{user_reg_dir} eq ''; + + # read the current user registry table + unshift( @INC, $args{user_reg_dir} ) + ; # place where USER_REGISTRIES could be + use vars qw ( %USER_REGISTRIES ); + eval { require $args{user_reg_table} }; + my $file_with_table; + if ($@) { + $LOG->warn( "Cannot find table of USER_REGISTRIES '" + . $args{user_reg_table} + . "': $@" ); + $file_with_table = File::Spec->catfile( $args{user_reg_dir}, + $args{user_reg_table} ); + } else { $file_with_table = $INC{ $args{user_reg_table} }; - } - - # remove from user regs table - delete $USER_REGISTRIES{$name}; - # ...and write it back to a disk - require Data::Dumper; - open DISPATCH, ">$file_with_table" - or $self->throw ("Cannot open for writing '$file_with_table': $!\n"); - print DISPATCH Data::Dumper->Dump ( [\%USER_REGISTRIES], ['*USER_REGISTRIES'] ) - or $self->throw ("cannot write to '$file_with_table': $!\n"); - close DISPATCH; - $LOG->info ("\nUpdated user reg table '$file_with_table'. New contents:\n" . - $self->toString (\%USER_REGISTRIES)); + } + + # remove from user regs table + delete $USER_REGISTRIES{$name}; + + # ...and write it back to a disk + require Data::Dumper; + open DISPATCH, ">$file_with_table" + or + $self->throw("Cannot open for writing '$file_with_table': $!\n"); + print DISPATCH Data::Dumper->Dump( [ \%USER_REGISTRIES ], + ['*USER_REGISTRIES'] ) + or $self->throw("cannot write to '$file_with_table': $!\n"); + close DISPATCH; + $LOG->info( + "\nUpdated user reg table '$file_with_table'. New contents:\n" + . $self->toString( \%USER_REGISTRIES ) ); }; - $LOG->warn ("Error removing user registries: $@") - if ($LOG->is_warn) and $@; - + $LOG->warn("Error removing user registries: $@") + if ( $LOG->is_warn ) + and $@; + #update $self->{registries} delete $self->{registries}->{$name}; + # could remove from persistent store return 0 if $@; + # return success return 1; } if ref $self; } - #----------------------------------------------------------------- # _update_user_registries #----------------------------------------------------------------- sub _update_user_registries { - my ($self, @args) = @_; - my %args = - ( # some default values - user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), - user_reg_table => ($MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME || 'USER_REGISTRIES'), - - # and the real parameters - @args ); - die "Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" - if $args{user_reg_dir} eq ''; - - # check %args for the right parameters, endpoint, namespace, name, synonym, contact, text, public + my ( $self, @args ) = @_; + my %args = ( # some default values + user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), + user_reg_table => ( + $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + || 'USER_REGISTRIES' + ), + + # and the real parameters + @args + ); + die +"Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" + if $args{user_reg_dir} eq ''; + +# check %args for the right parameters, endpoint, namespace, name, synonym, contact, text, public die "Arguments to update user registries are incomplete." - unless defined $args{namespace} and defined $args{endpoint} - and defined $args{synonym} and defined $args{text} - and defined $args{name} and defined $args{contact} - and defined $args{public}; - + unless defined $args{namespace} + and defined $args{endpoint} + and defined $args{synonym} + and defined $args{text} + and defined $args{name} + and defined $args{contact} + and defined $args{public}; + die "Registry synonyms should not start with http ..." - if $args{synonym} =~ m"^http://"; - - my $outdir = File::Spec->rel2abs ($args{user_reg_dir}); - $LOG->debug ("Arguments for generating user registries table: " . $self->toString (\%args)) - if ($LOG->is_debug); - - # read the current user registry table - unshift (@INC, $args{user_reg_dir}); # place where USER_REGISTRIES could be - use vars qw ( %USER_REGISTRIES ); - eval { require $args{user_reg_table} }; - my $file_with_table; - if ($@) { - $LOG->warn ("Cannot find table of USER_REGISTRIES '" . $args{user_reg_table} . "': $@"); - $file_with_table = File::Spec->catfile ($args{user_reg_dir}, $args{user_reg_table}); - } else { - $file_with_table = $INC{ $args{user_reg_table} }; - } - - # update user regs table - $USER_REGISTRIES{$args{synonym}} = { - endpoint => $args{endpoint}, - namespace => $args{namespace}, - name => $args{name}, - contact => $args{contact}, - public => $args{public}, - text => $args{text}, - }; - # ...and write it back to a disk - require Data::Dumper; - open DISPATCH, ">$file_with_table" - or $self->throw ("Cannot open for writing '$file_with_table': $!\n"); - print DISPATCH Data::Dumper->Dump ( [\%USER_REGISTRIES], ['*USER_REGISTRIES'] ) - or $self->throw ("cannot write to '$file_with_table': $!\n"); - close DISPATCH; - $LOG->info ("\nUpdated user reg table '$file_with_table'. New contents:\n" . - $self->toString (\%USER_REGISTRIES)); + if $args{synonym} =~ m"^http://"; + + my $outdir = File::Spec->rel2abs( $args{user_reg_dir} ); + $LOG->debug( "Arguments for generating user registries table: " + . $self->toString( \%args ) ) + if ( $LOG->is_debug ); + + # read the current user registry table + unshift( @INC, $args{user_reg_dir} ); # place where USER_REGISTRIES could be + use vars qw ( %USER_REGISTRIES ); + eval { require $args{user_reg_table} }; + my $file_with_table; + if ($@) { + $LOG->warn( "Cannot find table of USER_REGISTRIES '" + . $args{user_reg_table} + . "': $@" ); + $file_with_table = + File::Spec->catfile( $args{user_reg_dir}, $args{user_reg_table} ); + } else { + $file_with_table = $INC{ $args{user_reg_table} }; + } + + # update user regs table + $USER_REGISTRIES{ $args{synonym} } = { + endpoint => $args{endpoint}, + namespace => $args{namespace}, + name => $args{name}, + contact => $args{contact}, + public => $args{public}, + text => $args{text}, + }; + + # ...and write it back to a disk + require Data::Dumper; + open DISPATCH, ">$file_with_table" + or $self->throw("Cannot open for writing '$file_with_table': $!\n"); + print DISPATCH Data::Dumper->Dump( [ \%USER_REGISTRIES ], + ['*USER_REGISTRIES'] ) + or $self->throw("cannot write to '$file_with_table': $!\n"); + close DISPATCH; + $LOG->info( "\nUpdated user reg table '$file_with_table'. New contents:\n" + . $self->toString( \%USER_REGISTRIES ) ); } 1; From kawas at dev.open-bio.org Thu Nov 6 13:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYRV025584@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY Modified Files: Base.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY Base.pm,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm 2008/10/30 21:26:38 1.5 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm 2008/11/06 18:32:33 1.6 @@ -632,14 +632,14 @@ my $DUMPER; BEGIN { use Dumpvalue; - use IO::Scalar; + use IO::String; $DUMPER = Dumpvalue->new(); # $DUMPER->set (veryCompact => 1); } sub as_string { my $self = shift; my $dump_str; - my $io = IO::Scalar->new (\$dump_str); + my $io = IO::String->new (\$dump_str); my $oio = select ($io); $DUMPER->dumpValue (\$self); select ($oio); From kawas at dev.open-bio.org Thu Nov 6 13:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYM2025566@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators Modified Files: Utils.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators Utils.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm 2008/04/29 19:45:10 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm 2008/11/06 18:32:33 1.5 @@ -61,17 +61,29 @@ =cut +my %full_path_of = (); + sub find_file { my ($self, $default_start, @names) = @_; my $fixed_part = File::Spec->catfile (@names); + return $full_path_of{ $fixed_part } if exists $full_path_of{ $fixed_part }; + my $result = File::Spec->catfile ($default_start, $fixed_part); - return $result if -e $result; + if (-e $result) { + $full_path_of{ $fixed_part } = $result; + return $result; + } foreach my $idx (0 .. $#INC) { - $result = File::Spec->catfile ($INC[$idx], $fixed_part); - return $result if -e $result; + $result = File::Spec->catfile ($INC[$idx], $fixed_part); + if (-e $result) { + $full_path_of{ $fixed_part } = $result; + return $result; + } } - return File::Spec->catfile ($default_start, $fixed_part); + $result = File::Spec->catfile ($default_start, $fixed_part); + $full_path_of{ $fixed_part } = $result; + return $result; } 1; From kawas at dev.open-bio.org Thu Nov 6 13:41:40 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:41:40 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061841.mA6IfeXw025750@dev.open-bio.org> kawas Thu Nov 6 13:41:40 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data In directory dev.open-bio.org:/tmp/cvs-serv25715/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data Modified Files: DateTime.pm Log Message: synopsis had incorrect usage information ('MobyDateTime' should have read 'DateTime') moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data DateTime.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm 2008/04/29 19:35:57 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm 2008/11/06 18:41:40 1.5 @@ -24,8 +24,8 @@ use MOSES::MOBY::Data::DateTime; # create a Moby DateTime - my $data = MOSES::MOBY::Data::MobyDateTime->new (value => '1994-11-05T08:15:30-05:00'); - my $data = MOSES::MOBY::Data::MobyDateTime->new ('1994-11-05T08:15:30-05:00'); + my $data = MOSES::MOBY::Data::DateTime->new (value => '1994-11-05T08:15:30-05:00'); + my $data = MOSES::MOBY::Data::DateTime->new ('1994-11-05T08:15:30-05:00'); =head1 DESCRIPTION From kawas at dev.open-bio.org Fri Nov 7 12:26:35 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Fri, 7 Nov 2008 12:26:35 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811071726.mA7HQZpU029854@dev.open-bio.org> kawas Fri Nov 7 12:26:34 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder In directory dev.open-bio.org:/tmp/cvs-serv29819/src/main/org/biomoby/client/rdf/builder Modified Files: ServiceInstanceRDF.java Log Message: added code to allow either a hash or forward slash in our URIs. (Preference for forward slash). For instance, if you provide http://somedomain.com/serviceinstance as a URI, it will now either make the URI http://somedomain.com/serviceinstance/ <- prefered or http://somedomain.com/serviceinstance# moby-live/Java/src/main/org/biomoby/client/rdf/builder ServiceInstanceRDF.java,1.37,1.38 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java 2008/02/20 16:58:59 1.37 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java 2008/11/07 17:26:34 1.38 @@ -1,7 +1,9 @@ package org.biomoby.client.rdf.builder; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.util.HashMap; +import java.io.InputStream; +import java.security.MessageDigest; import java.util.Map; import org.apache.commons.logging.Log; @@ -19,6 +21,7 @@ import org.biomoby.shared.MobyResourceRef; import org.biomoby.shared.MobySecondaryData; import org.biomoby.shared.MobyService; +import org.biomoby.shared.MobyUnitTest; import org.biomoby.shared.data.MobyDataSecondaryInstance; import com.hp.hpl.jena.rdf.model.Model; @@ -44,6 +47,7 @@ *

* email me at edward.kawas at gmail.com */ + at SuppressWarnings("unchecked") public class ServiceInstanceRDF { // some URIs @@ -58,28 +62,21 @@ + " " + System.getProperty("line.separator") + ""; - private static Map URI_MAP = new HashMap(); - private static Log log = LogFactory.getLog(ServiceInstanceRDF.class); - private static final String DCP = DC_PROTEGE.getURI(); - - private Registry registry = null; - private CentralImpl central = null; // character is a has - private String trailing_character = "#"; - + private String[] trailing_characters = new String[]{"/","#"}; + + private static String PREFERED_TRAILING_CHARACTER = null; + private String OBJ; private String SRV; private String NS; - private String MP = "http://biomoby.org/RESOURCES/MOBY-S/Predicates" - + trailing_character; - private String SI; public final String getLatestLSID(String uri, String name, String lsid) { @@ -106,7 +103,9 @@ } public static void main(String[] args) throws Exception { - System.out.println(new ServiceInstanceRDF().findService("bioinfo.icapture.ubc.ca", "", false)); + System.out.println(new ServiceInstanceRDF().findService( + //"bioinfo.icapture.ubc.ca", "getGoTerm", true)); + "atidb.org", "getInsertionsWithOffsetAsGFFByAGICode", true)); } /** @@ -190,44 +189,52 @@ * if there is a problem communicating with the registry */ public ServiceInstanceRDF(Registry reg) throws MobyException { - registry = reg; central = new CentralImpl(reg.getEndpoint(), reg.getNamespace()); MobyResourceRef[] refs = central.getResourceRefs(); for (MobyResourceRef ref : refs) { if (ref.getResourceName().equals( CentralImpl.DATA_TYPES_RESOURCE_NAME)) { OBJ = ref.getResourceLocation().toString(); - if (!OBJ.endsWith(trailing_character)) - OBJ = OBJ + trailing_character; + OBJ = validateUri(OBJ); } else if (ref.getResourceName().equals( CentralImpl.SERVICE_INSTANCES_RESOURCE_NAME)) { SI = ref.getResourceLocation().toString(); - if (!SI.endsWith(trailing_character)) - SI = SI + trailing_character; + SI = validateUri(SI); } else if (ref.getResourceName().equals( CentralImpl.NAMESPACES_RESOURCE_NAME)) { NS = ref.getResourceLocation().toString(); - if (!NS.endsWith(trailing_character)) - NS = NS + trailing_character; + NS = validateUri(NS); } else if (ref.getResourceName().equals( CentralImpl.SERVICE_TYPES_RESOURCE_NAME)) { SRV = ref.getResourceLocation().toString(); - if (!SRV.endsWith(trailing_character)) - SRV = SRV + trailing_character; + SRV = validateUri(SRV); } } } - /* - * method that actually creates the rdf based on one or more services - * contained in the array services - */ - private final String createRDF(MobyService[] services) { - Model model = createRDFModel(ModelFactory.createDefaultModel(), - services, true); - return serializeModel(model); + private String validateUri(String string) { + boolean isValid = false; + for (String s : trailing_characters) { + if (string.endsWith(s)) { + isValid = true; + if (PREFERED_TRAILING_CHARACTER == null) + PREFERED_TRAILING_CHARACTER = s; + break; + } + } + // our default trailing char + String trailer = "/"; + if (PREFERED_TRAILING_CHARACTER != null) + trailer = PREFERED_TRAILING_CHARACTER; + return isValid ? string : string + trailer; } - + + /** + * + * @param model + * a jena model + * @return a string of RDF/XML-ABBREV representing the RDF model + */ public final String serializeModel(Model model) { FilteredStream stream = new FilteredStream(new ByteArrayOutputStream()); RDFWriter writer = model.getWriter("RDF/XML-ABBREV"); @@ -264,7 +271,7 @@ model = ModelFactory.createDefaultModel(); } // set up the prefixes/namespaces - Map map = model.getNsPrefixMap(); + Map map = model.getNsPrefixMap(); map.put("mobyService", SRV); map.put("mobyNamespace", NS); map.put("mobyObject", OBJ); @@ -290,17 +297,17 @@ services[i].getDescription()); subject.addProperty(FetaVocabulary.hasServiceNameText, services[i] .getName()); + if (useLSIDs) subject.addProperty(DC_PROTEGE.identifier, services[i] .getLSID()); - /* - * subject.addProperty(ServiceDescriptionPredicates.hasServiceType, - * services[i] .getType()); - */ // create the organization node - Resource publishedBy = model - .createResource(FetaVocabulary.organisation); + Resource publishedBy = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.providedBy.getURI())); + publishedBy.addProperty(RDF.type, FetaVocabulary.organisation); publishedBy.addProperty(DC_PROTEGE.creator, services[i] .getEmailContact()); publishedBy.addProperty(DC_PROTEGE.publisher, services[i] @@ -310,16 +317,22 @@ subject.addProperty(FetaVocabulary.providedBy, publishedBy); // add the inputs/outputs - Resource hasOperation = model - .createResource(FetaVocabulary.operation); + Resource hasOperation = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.hasOperation.getURI())); + hasOperation.addProperty(RDF.type, FetaVocabulary.operation); // add the hasOperation to the resource subject.addProperty(FetaVocabulary.hasOperation, hasOperation); hasOperation.addProperty(FetaVocabulary.hasOperationNameText, services[i].getName()); // add the performsTask information - Resource performs = model - .createResource(FetaVocabulary.operationTask); + Resource performs = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.performsTask.getURI())); + performs.addProperty(RDF.type, FetaVocabulary.performsTask); // if service type is lsid, dont append to URI try { new LSID(services[i].getServiceType().getName()); @@ -333,66 +346,129 @@ hasOperation.addProperty(FetaVocabulary.performsTask, performs); + // add any unit test information now + if (services[i].getUnitTest() != null) { + MobyUnitTest mobyUnitTest = services[i].getUnitTest(); + Resource unitTest = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/" + + FetaVocabulary.unitTest.getURI())); + unitTest.addProperty(RDF.type, FetaVocabulary.unitTest); + // add the example input if defined + if (!mobyUnitTest.getExampleInput().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.exampleInput, mobyUnitTest.getExampleInput()); + } + // add the valid output xml if defined + if (!mobyUnitTest.getValidOutputXML().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validOutputXML, mobyUnitTest.getValidOutputXML()); + } + // add the valid regex if defined + if (!mobyUnitTest.getValidREGEX().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validREGEX, mobyUnitTest.getValidREGEX()); + } + // add the xpath expression if defined + if (!mobyUnitTest.getValidXPath().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validXPath, mobyUnitTest.getValidXPath()); + } + // add node to the graph + hasOperation.addProperty(FetaVocabulary.hasUnitTest, unitTest); + } + + + if (primaryInputs.length > 0) { for (int j = 0; j < primaryInputs.length; j++) { if (primaryInputs[j] instanceof MobyPrimaryDataSimple) { MobyPrimaryDataSimple simpleData = (MobyPrimaryDataSimple) primaryInputs[j]; - Resource parameter = model - .createResource(FetaVocabulary.parameter); + Resource parameter = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + "/" + + simpleData.getName())); + parameter.addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, simpleData .getName()); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.simpleParameter)); - // if object is lsid, dont append to URI + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + simpleData.getName())); + pType.addProperty(RDF.type, + FetaVocabulary.simpleParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); + boolean isLSID = false; try { - // an lsid - Resource bnode = model.createResource(); new LSID(simpleData.getDataType().getName()); - bnode.addProperty(RDF.type, model - .createResource(simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - } catch (MalformedLSIDException e) { - // not an lsid - Resource bnode = model.createResource(); - bnode.addProperty(RDF.type, model - .createResource(OBJ - + simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - + isLSID = true; + } catch (MalformedLSIDException e1) { + isLSID = false; } + // create the resource + Resource bnode = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + "/" + + simpleData.getName() + "/" + + simpleData.getDataType().getName())); + bnode.addProperty(RDF.type, model + .createResource(isLSID ? simpleData + .getDataType().getName() : OBJ + + simpleData.getDataType().getName())); + parameter + .addProperty(FetaVocabulary.object_type, bnode); MobyNamespace[] namespaces = simpleData.getNamespaces(); if (namespaces.length > 0) { - // Resource parameterNamespace = model - // .createResource(FetaVocabulary.parameterNamespace); - // parameter.addProperty(FetaVocabulary.inNamespaces, - // parameterNamespace); for (int k = 0; k < namespaces.length; k++) { // if namespace is lsid, dont append to URI Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + simpleData + .getName() + + "/" + + namespaces[k] + .getName())); + parameterNamespace.addProperty(RDF.type, + FetaVocabulary.parameterNamespace); parameter.addProperty( FetaVocabulary.inNamespaces, parameterNamespace); + isLSID = false; try { new LSID(namespaces[k].getName()); - parameterNamespace.addProperty(RDF.type, - model.createResource(namespaces[k] - .getName())); + isLSID = true; } catch (MalformedLSIDException e) { - parameterNamespace.addProperty(RDF.type, - model.createResource(NS - + namespaces[k].getName())); + isLSID = false; } + parameterNamespace.addProperty(RDF.type, model + .createResource(isLSID ? namespaces[k] + .getName() : NS + + namespaces[k].getName())); } } hasOperation.addProperty(FetaVocabulary.inputParameter, @@ -408,7 +484,21 @@ for (int k = 0; k < setOfSimpleData.length; k++) { if (setOfSimpleData[k] instanceof MobyPrimaryDataSimple) { Resource parameter = model - .createResource(FetaVocabulary.parameter); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName)) + .addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, collectionName); @@ -416,11 +506,41 @@ .addProperty( FetaVocabulary.hasParameterType, model - .createResource(FetaVocabulary.collectionParameter)); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.hasParameterType + .getURI() + + "/" + + collectionName)) + .addProperty( + RDF.type, + FetaVocabulary.collectionParameter)); // if object is lsid, dont append to URI try { - - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); new LSID(setOfSimpleData[k].getDataType() .getName()); bnode.addProperty(RDF.type, model @@ -430,7 +550,23 @@ FetaVocabulary.object_type, bnode); } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + +"/" + + setOfSimpleData[k] + .getDataType() + .getName())); bnode.addProperty(RDF.type, model .createResource(OBJ + setOfSimpleData[k] @@ -443,21 +579,32 @@ MobyNamespace[] namespaces = setOfSimpleData[k] .getNamespaces(); if (namespaces.length > 0) { - /* - * Resource parameterNamespace = model - * .createResource(FetaVocabulary.parameterNamespace); - */ for (int index = 0; index < namespaces.length; index++) { // if namespace is lsid, dont // append to URI Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); - parameter.addProperty( - FetaVocabulary.inNamespaces, - parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + + "/" + + namespaces[k] + .getName())); + parameterNamespace + .addProperty( + RDF.type, + FetaVocabulary.parameterNamespace); try { - LSID theLSID = new LSID( - namespaces[index].getName()); + new LSID(namespaces[index] + .getName()); parameterNamespace .addProperty( RDF.type, @@ -473,6 +620,9 @@ + namespaces[index] .getName())); } + parameter.addProperty( + FetaVocabulary.inNamespaces, + parameterNamespace); } /* @@ -503,13 +653,39 @@ for (int j = 0; j < secondaryInputs.length; j++) { if (secondaryInputs[j] instanceof MobySecondaryData) { MobySecondaryData data = (MobySecondaryData) secondaryInputs[j]; - Resource _li = model - .createResource(FetaVocabulary.parameter); + Resource _li = model.createResource( + SI + + MD5Checksum.md5(services[i] + .getAuthority() + + "/" + + services[i].getName() + + "/isSecondaryInputParameter/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + data.getName())).addProperty( + RDF.type, FetaVocabulary.parameter); _li .addProperty( FetaVocabulary.hasParameterType, model - .createResource(FetaVocabulary.secondaryParameter)); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSecondary/" + + FetaVocabulary.hasParameterType + .getURI() + + "/" + + data + .getName())) + .addProperty( + RDF.type, + FetaVocabulary.secondaryParameter)); if (!data.getName().equals("")) _li @@ -565,53 +741,77 @@ for (int j = 0; j < outputs.length; j++) { if (outputs[j] instanceof MobyPrimaryDataSimple) { MobyPrimaryDataSimple simpleData = (MobyPrimaryDataSimple) outputs[j]; - Resource parameter = model - .createResource(FetaVocabulary.parameter); + Resource parameter = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + "/" + + simpleData.getName())); parameter.addProperty( FetaVocabulary.hasParameterNameText, simpleData .getName()); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.simpleParameter)); - // if object is lsid, dont append to URI + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + simpleData.getName())); + pType.addProperty(RDF.type, + FetaVocabulary.simpleParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); + + boolean isLSID = false; try { - Resource bnode = model.createResource(); new LSID(simpleData.getDataType().getName()); - bnode.addProperty(RDF.type, model - .createResource(simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); - bnode.addProperty(RDF.type, model - .createResource(OBJ - + simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); + isLSID = true; + } catch (MalformedLSIDException e1) { + isLSID = false; } + // create the resource + Resource bnode = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + "/" + + simpleData.getName() + "/" + + simpleData.getDataType().getName())); + bnode.addProperty(RDF.type, model + .createResource(isLSID ? simpleData + .getDataType().getName() : OBJ + + simpleData.getDataType().getName())); + parameter + .addProperty(FetaVocabulary.object_type, bnode); MobyNamespace[] namespaces = simpleData.getNamespaces(); if (namespaces.length > 0) { - /* - * Resource parameterNamespace = - * model.createResource(ModelFactory - * .createDefaultModel().createProperty( - * FetaVocabulary.getURI() + "parameterNamespace")); - * parameter.addProperty(FetaVocabulary.inNamespaces, - * parameterNamespace); - */ for (int k = 0; k < namespaces.length; k++) { // if namespace is lsid, dont append to URI Resource parameterNamespace = model - .createResource(ModelFactory - .createDefaultModel() - .createProperty( - FetaVocabulary.getURI() - + "parameterNamespace")); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + simpleData + .getName() + + "/" + + namespaces[k] + .getName())); + parameterNamespace.addProperty(RDF.type, + FetaVocabulary.parameterNamespace); parameter.addProperty( FetaVocabulary.inNamespaces, parameterNamespace); @@ -640,18 +840,55 @@ for (int k = 0; k < setOfSimpleData.length; k++) { if (setOfSimpleData[k] instanceof MobyPrimaryDataSimple) { Resource parameter = model - .createResource(FetaVocabulary.parameter); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName)) + .addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, collectionName); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.collectionParameter)); + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isCollection/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + collectionName)); + pType.addProperty(RDF.type, + FetaVocabulary.collectionParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); // if object is lsid, dont append to URI try { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); new LSID(setOfSimpleData[k].getDataType() .getName()); bnode.addProperty(RDF.type, model @@ -660,7 +897,23 @@ parameter.addProperty( FetaVocabulary.object_type, bnode); } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); bnode.addProperty(RDF.type, model .createResource(OBJ + setOfSimpleData[k] @@ -679,10 +932,28 @@ */ for (int index = 0; index < namespaces.length; index++) { Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + namespaces[k] + .getName())); + parameterNamespace + .addProperty( + RDF.type, + FetaVocabulary.parameterNamespace); try { - LSID theLSID = new LSID( - namespaces[index].getName()); + new LSID(namespaces[index] + .getName()); parameterNamespace .addProperty( RDF.type, @@ -730,6 +1001,39 @@ return model; } + private static class MD5Checksum { + + private static byte[] createChecksum(String msg) { + try { + InputStream fis = new ByteArrayInputStream(msg.getBytes()); + byte[] buffer = new byte[1024]; + MessageDigest complete = MessageDigest.getInstance("MD5"); + int numRead; + do { + numRead = fis.read(buffer); + if (numRead > 0) { + complete.update(buffer, 0, numRead); + } + } while (numRead != -1); + fis.close(); + return complete.digest(); + } catch (Exception e) { + + } + return "".getBytes(); + } + + public static String md5(String msg) { + byte[] b = createChecksum(msg); + String result = ""; + for (int i = 0; i < b.length; i++) { + result += Integer.toString((b[i] & 0xff) + 0x100, 16) + .substring(1); + } + return result; + } + } + /** * * PRE: name is either a valid name or null @@ -737,7 +1041,7 @@ * POST: If authorURI is a valid authority, then a RDF containing all * of the service instances will be returned. If authorURI and name are * valid then a single RDF containing just the service instance identified - * by name is returned. + * by name is returned. *

* * @param authorURI - @@ -751,13 +1055,14 @@ * if name and authorURI are valid. If name and/or authorURI are * invalid an empty rdf document is returned. */ - public final String findService(String authorURI, String name, boolean useLSIDs) { + public final String findService(String authorURI, String name, + boolean useLSIDs) { if (name == null || name.trim().equals("")) { - return (useLSIDs ? getAllServices(authorURI) - : getAllServices(authorURI, false)); + return (useLSIDs ? getAllServices(authorURI) : getAllServices( + authorURI, false)); } else { - return (useLSIDs ? getService(authorURI, name) - : getService(authorURI, name, false)); + return (useLSIDs ? getService(authorURI, name) : getService( + authorURI, name, false)); } } @@ -955,7 +1260,7 @@ * a method that retrieves all of the service instances based on an * authoriy. */ - private final String getAllServices(String URI,boolean useLSIDs) { + private final String getAllServices(String URI, boolean useLSIDs) { // variables needed MobyService service = null; MobyService[] services = null; @@ -998,7 +1303,7 @@ MobyService service = null; MobyService[] services = null; Central central = getCentralImpl(); - + // set up the query service service = new MobyService(name); service.setCategory(""); @@ -1029,7 +1334,7 @@ MobyService service = null; MobyService[] services = null; Central central = getCentralImpl(); - + // set up the query service service = new MobyService(name); service.setCategory(""); From gordonp at dev.open-bio.org Fri Nov 14 10:53:20 2008 From: gordonp at dev.open-bio.org (Paul Gordon) Date: Fri, 14 Nov 2008 10:53:20 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811141553.mAEFrKUb006218@dev.open-bio.org> gordonp Fri Nov 14 10:53:19 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data In directory dev.open-bio.org:/tmp/cvs-serv6182/src/main/org/biomoby/shared/data Modified Files: MobyDataSecondaryInstance.java Log Message: Made default value the value of a new secondary data instance moby-live/Java/src/main/org/biomoby/shared/data MobyDataSecondaryInstance.java,1.10,1.11 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java 2007/12/06 16:44:04 1.10 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java 2008/11/14 15:53:19 1.11 @@ -23,7 +23,7 @@ } /** - * Basically clones the input parameter + * Basically clones the input parameter, and sets the value to the default value. */ public MobyDataSecondaryInstance(MobySecondaryData type){ super(type.getName()); @@ -35,6 +35,7 @@ } setAllowedValues(type.getAllowedValues()); setDefaultValue(type.getDefaultValue()); + setValue(type.getDefaultValue()); setMinValue(type.getMinValue()); setMaxValue(type.getMaxValue()); setDescription(type.getDescription()); From gordonp at dev.open-bio.org Fri Nov 14 15:32:02 2008 From: gordonp at dev.open-bio.org (Paul Gordon) Date: Fri, 14 Nov 2008 15:32:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811142032.mAEKW2nP008348@dev.open-bio.org> gordonp Fri Nov 14 15:32:02 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client In directory dev.open-bio.org:/tmp/cvs-serv8312/src/main/org/biomoby/client Modified Files: MobyRequest.java Log Message: Added convenience method for secondaries, javadocs moby-live/Java/src/main/org/biomoby/client MobyRequest.java,1.39,1.40 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java,v retrieving revision 1.39 retrieving revision 1.40 diff -u -r1.39 -r1.40 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/10/30 02:33:25 1.39 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/14 20:32:02 1.40 @@ -224,6 +224,13 @@ public MobyContentInstance getInput(){ return inputData; } + + /** + * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) + */ + public void setSecondaryInput(Collection secondaryData) throws MobyException{ + setSecondaryInput(secondaryData.toArray(new MobyDataSecondaryInstance[secondaryData.size()])); + } /** * This method will assign the provided secondary parameters to all primary input data currently @@ -274,7 +281,8 @@ * are properly defined according to the Web service definition, * a SOAP request will be sent to the remote server, and the method * will return one or more MOBY objects (synchronous). - * Call this method after calling setService, and setInput. + * Call this method after calling setService, and setInput. If you do not call + * setSecondaryInput, the default secondary parameter values will be used. * * @return the results of the remote Web service in response to the give input * From kawas at dev.open-bio.org Mon Nov 17 10:24:32 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:24:32 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171524.mAHFOWPT003137@dev.open-bio.org> kawas Mon Nov 17 10:24:31 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv3106/Perl/MOBY-Server/lib/MOBY/Client Added Files: MobyUnitTest.pm Log Message: new module for unit testing moby services in perl. one subroutine is not finished (get_xml_differences). moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,NONE,1.1 From kawas at dev.open-bio.org Mon Nov 17 10:25:10 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:25:10 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171525.mAHFPABT003183@dev.open-bio.org> kawas Mon Nov 17 10:25:10 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv3144/Perl/MOBY-Server Modified Files: Makefile.PL Changes Log Message: added changes to reflect new module MobyUnitTest.pm moby-live/Perl/MOBY-Server Makefile.PL,1.9,1.10 Changes,1.14,1.15 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL 2008/09/02 13:17:25 1.9 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL 2008/11/17 15:25:10 1.10 @@ -27,6 +27,8 @@ requires 'LS' => '1.1.7'; requires 'DBI' => '0.01'; requires 'DBD::mysql' => '0.01'; + # used in MobyUnitTest + requires 'XML::Simple' => '2.18'; # MOBY::Async requires requires 'WSRF::Lite' => '0.8.2.3'; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/10/31 15:12:45 1.14 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:25:10 1.15 @@ -18,6 +18,10 @@ - Added "no warnings 'redefine';" to MOBY::Async::WSRF to suppress redefinition warnings. - Added Unit test predicates to FETA.pm + - Created module that can be used to test Moby services. This module is + MOBY::Client::MobyUnitTest. Methods for determining whether differences + exist are complete. Currently, the method to obtain differences is + unfinished. 1.05 From kawas at dev.open-bio.org Mon Nov 17 10:27:02 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:27:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171527.mAHFR2du003295@dev.open-bio.org> kawas Mon Nov 17 10:27:02 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority In directory dev.open-bio.org:/tmp/cvs-serv3260/Perl/MOBY-Server/lib/MOBY/lsid/authority Modified Files: MobyMetadataResolver.pm Log Message: fixed the URI component in the isLatest RDF returned by the lsid resolver. moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority MobyMetadataResolver.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm 2008/09/02 13:11:53 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm 2008/11/17 15:27:02 1.4 @@ -115,13 +115,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::Namespaces->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Namespaces#$object"; my $data = < - + The Namespace described by the LSID: $lsid has since been modified. Please update your lsid. $latest @@ -333,13 +335,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::ServiceTypes->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Services#$object"; my $data = < - + The ServiceType described by the LSID: $lsid has since been modified. Please update your lsid. $latest @@ -549,13 +553,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::Objects->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Objects#$object"; my $data = < - + The Datatype described by the LSID: $lsid has since been modified. Please update your lsid. $latest From kawas at dev.open-bio.org Mon Nov 17 10:28:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:28:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171528.mAHFSk4D003335@dev.open-bio.org> kawas Mon Nov 17 10:28:46 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv3300/Perl/MOBY-Server Modified Files: Changes Log Message: updated changes to reflect the MobyMetadataResolver.pm change to uri moby-live/Perl/MOBY-Server Changes,1.15,1.16 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:25:10 1.15 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:28:46 1.16 @@ -22,6 +22,9 @@ MOBY::Client::MobyUnitTest. Methods for determining whether differences exist are complete. Currently, the method to obtain differences is unfinished. + - Fixed the uri in the RDF returned in MobyMetadataResolver.pm when + the resolver is attempting to let you know what the latest lsid is + for the given entity. 1.05 From kawas at dev.open-bio.org Mon Nov 17 10:30:55 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:30:55 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171530.mAHFUtXx003527@dev.open-bio.org> kawas Mon Nov 17 10:30:55 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv3484/Perl/MOBY-Client Modified Files: Makefile.PL populate_libs.pl Changes Log Message: added changes to reflect new module MobyUnitTest.pm updated the makefile and populate_libs. moby-live/Perl/MOBY-Client Makefile.PL,1.8,1.9 populate_libs.pl,1.6,1.7 Changes,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL 2008/05/16 15:07:55 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL 2008/11/17 15:30:55 1.9 @@ -4,7 +4,7 @@ # all_from 'lib/MOBY/Client/Central.pm'; author 'Mark Wilkinson '; -version '1.02'; +version '1.03'; license 'perl'; abstract 'This distribution is for communicating with a MOBY Central registry'; @@ -19,76 +19,14 @@ requires 'HTTP::Request::Common' => 0; requires 'URI::Escape' => 0; requires 'RDF::Core' => '0.51'; +# MOBY::Client::MobyUnitTest depends +requires 'XML::Simple' => '2.18'; # MOBY::CommonSubs depends requires 'HTML::Entities' => 0; # MOBY::Async requires -if ( not( $^O =~ /MSWin32|Windows_NT/i ) ) { - - # check for WSRF - eval "require WSRF::Lite"; - if ($@) { - # WSRF not installed ... tell them where to get it - print STDOUT <<'END_OF_TEXT'; - -################### IMPORTANT ################### - - WSRF lite is not installed on your system. - Unfortunately, at this time, this Makefile - cannot automatically find and install it for - you. You will have to install it manually. - - The last known URL of where you could find - this package is @ - http://www.rcs.manchester.ac.uk/research/wsrflite - - If that url does not exist, please search with - google using the phrase 'WSRF-Lite'. - - Sorry for any inconvenience caused! - -################################################## - -END_OF_TEXT - - - } - requires 'WSRF::Lite' => '0.008.2.2'; - requires 'XML::DOM' => ''; - requires 'DateTime::Format::Epoch' => ''; - requires 'DateTime::Format::W3CDTF' => ''; - requires 'HTTP::Daemon' => ''; - requires 'HTTP::Daemon::SSL' => ''; - requires 'MIME::Base64' => ''; - requires 'Digest::SHA1' => ''; - requires 'Crypt::OpenSSL::RSA' => ''; - requires 'XML::CanonicalizeXML' => '0.02'; - requires 'Sys::Hostname::Long' => ''; - requires 'Crypt::OpenSSL::X509' => '0'; -} else { - print STDOUT <<'END_OF_TEXT'; - -################### IMPORTANT ################### - - Windows is not a suitable platform for those - wishing to construct asynchronous moby services - due to the lack of support for that platform of - some of the required libraries. - - The libraries in question are as follows: - WSRF-Lite & Crypt-OpenSSL-X509 - - Sorry for any inconvenience caused! - -################################################## - -END_OF_TEXT - -} - -# dont want to install the test services ... better just to document that they are here -#install_share 'share'; +requires 'WSRF::Lite' => '0.8.2.2.3'; auto_install; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/08/06 14:47:54 1.6 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/17 15:30:55 1.7 @@ -10,7 +10,7 @@ my @MOBY = qw ( Async.pm CommonSubs.pm CrossReference.pm MobyXMLConstants.pm ); my @Async = qw ( LSAE.pm Service.pm SimpleServer.pm WSRF.pm ); -my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm ); +my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm MobyUnitTest.pm ); my @Exception = qw ( MobyException.pm MobyExceptionCodes.pm ); my @RDF = qw ( Utils.pm ); my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm); @@ -100,6 +100,7 @@ # ? ? ServiceInstance.pm # ? ? SimpleArticle.pm # ? ? SimpleInput.pm +# ? ? MobyUnitTest.pm # ? ? # ? +---Exception # ? MobyException.pm =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Changes,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/05/16 15:07:55 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/17 15:30:55 1.4 @@ -1,5 +1,10 @@ Revision history for MOBY-Client +1.03 + * changes to makefile reflecting the cpan addition of wsrf + * added MOBY/Async.pm to the module + * added MOBY/Client/MobyUnitTest for unit testing our services. + 1.02 16 May 2008 * fixed bug in MOBY::Client::Central::DUMP that resulted in an error ('Not an ARRAY reference at From kawas at dev.open-bio.org Mon Nov 17 10:35:21 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:35:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171535.mAHFZLBP003654@dev.open-bio.org> kawas Mon Nov 17 10:35:21 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv3619/Perl/MOBY-Client Modified Files: README Log Message: update the README to remove the section on wsrf (since it is cpan now) moby-live/Perl/MOBY-Client README,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/README,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Client/README 2008/02/21 00:14:33 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/README 2008/11/17 15:35:21 1.2 @@ -26,25 +26,6 @@ each dependency independently and install them as per their installation instructions. -WRSF::Lite - -If module 'WSRF::Lite' is not installed and you are -thinking about developing BioMOBY Asynchronous service, -then following is for you! - -Unfortunately, this module is not available on CPAN -and must be manually installed. Some of the -dependencies are beta and as such, may not be stable. - -Try downloading it from the following link: - -http://www.rcs.manchester.ac.uk/research/projects/wsrflite - -or you can try searching the net with Google using the keywords: - - 'perl WSRF::Lite' - - COPYRIGHT AND LICENCE Copyright (C) 2003 BioMoby Developers Group (www.biomoby.org) From senger at dev.open-bio.org Tue Nov 18 01:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eBCN006092@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv6073/docs Modified Files: ChangeLog Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/docs ChangeLog,1.93,1.94 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/ChangeLog,v retrieving revision 1.93 retrieving revision 1.94 diff -u -r1.93 -r1.94 --- /home/repository/moby/moby-live/Java/docs/ChangeLog 2008/10/25 14:28:18 1.93 +++ /home/repository/moby/moby-live/Java/docs/ChangeLog 2008/11/18 06:40:11 1.94 @@ -1,3 +1,8 @@ +2008-11-18 Martin Senger + + * Added new properties to dashboard.properties allowing to limit + the list of known registries + 2008-10-25 Martin Senger * Fixed: Ant's task creating jMoby jar file now does not include From senger at dev.open-bio.org Tue Nov 18 01:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eB3f006112@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/src/config/dashboard In directory dev.open-bio.org:/tmp/cvs-serv6073/src/config/dashboard Modified Files: dashboard.properties Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/src/config/dashboard dashboard.properties,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties 2006/02/19 18:42:55 1.5 +++ /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties 2008/11/18 06:40:11 1.6 @@ -66,3 +66,17 @@ # panel) simpleclient.service.edit.bgcolor = beige + +# ----------------------------------------- +# --- Registry browser panel properties --- +# ----------------------------------------- + +# -- a name or a comma-separated list of names of BioMoby registry +# -- synonyms that will be displayed in the RegistryPanel. If this +# -- property is missing, the list is taken from the hard-coded known +# -- registries in the Java source file + +#dashboard.wanted.registries = default,Calgary,IRRI,INAB,testing + +# -- a name (synonym) of a default BioMoby registry +dashboard.default.registry = default From senger at dev.open-bio.org Tue Nov 18 01:40:12 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:12 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eCV6006164@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv6073/xmls Modified Files: project-dashboard.pom Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/xmls project-dashboard.pom,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom 2008/08/08 11:12:58 1.1 +++ /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom 2008/11/18 06:40:11 1.2 @@ -2,7 +2,7 @@ 4.0.0 org.biomoby jmoby-dashboard - 1.1.0 + 1.1.1 jMoby Dashboard From senger at dev.open-bio.org Tue Nov 18 01:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eBtW006140@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv6073/src/main/org/biomoby/service/dashboard Modified Files: DashboardConfig.java DashboardProperties.java RegistryPanel.java Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/src/main/org/biomoby/service/dashboard DashboardConfig.java,1.1,1.2 DashboardProperties.java,1.28,1.29 RegistryPanel.java,1.30,1.31 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java 2008/03/02 12:45:26 1.1 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java 2008/11/18 06:40:11 1.2 @@ -244,6 +244,34 @@ } /************************************************************************** + * Almost the same functionality as {@link #getString getString} + * method. The different is the return value: this method allows + * to return several values of the same property. In the + * configuration file, a property can be repeated, or can have + * several comma-separated values.

+ * + * By the way, the importance of a comma in a property value also + * means that any 'normal' (the one not meant as a value + * separator) commas in property values, must be escaped by + * backslashes.

+ * + * @return all values of the given property, or - if such property + * does not exist - return a one-element array with the + * 'defaultValue' unless the 'defaultValue' is also null in which + * case return an empty array + **************************************************************************/ + public static String[] getStrings (String key, + String defaultValue) { + String[] values = get().getStringArray (key); + if (values.length > 0) return values; + + if (defaultValue == null) + return ArrayUtils.EMPTY_STRING_ARRAY; + else + return new String[] { defaultValue }; + } + + /************************************************************************** * Get an integer value associated with the given configuration * key, or - if not found or not of integer value - get the given * default value.

=================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java,v retrieving revision 1.28 retrieving revision 1.29 diff -u -r1.28 -r1.29 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/05/14 20:37:10 1.28 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/18 06:40:11 1.29 @@ -203,4 +203,23 @@ */ static final String DP_REGISTRY_CACHE_DIR = "registry.cache.dir"; + /** A property name. Its value contains a name or a + * comma-separated list of names of BioMoby registries that will + * be displayed in the RegistryPanel. If this property is missing, + * the list is taken from the hard-coded known registries in the + * Java source file.

+ * + * The names (values of this property) are equivalent to the + * 'synonym' attribute of the Registry class. + */ + static final String DP_WANTED_REGISTRIES = "dashboard.wanted.registries"; + + /** A property name. Its value contains a name (synonym) of a + * default BioMoby registry. By default, the default registry is + * taken either from the first element in {@link + * #DP_WANTED_REGISTRIES} or from + * Registries.DEFAULT_REGISTRY_SYNONYM. + */ + static final String DP_DEFAULT_REGISTRY = "dashboard.default.registry"; + } =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java,v retrieving revision 1.30 retrieving revision 1.31 diff -u -r1.30 -r1.31 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java 2008/03/02 16:19:15 1.30 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java 2008/11/18 06:40:11 1.31 @@ -38,6 +38,8 @@ import java.awt.event.ItemListener; import java.io.File; +import java.util.List; +import java.util.ArrayList; /** * A panel displaying contents of a Biomoby registry. It also select @@ -421,10 +423,10 @@ showReg.setToolTipText ("Each time you select a registry, an info appears in console window"); final Registries regs = RegistriesList.getInstance(); - JComboBox regList = new JComboBox (regs.list()); + JComboBox regList = new JComboBox (getOnlyWantedRegistries (regs.list())); regList.setToolTipText ("A selection will fill text fields below"); - regList.setSelectedItem (getPrefValue (DP_REGISTRY_SYNONYM, - Registries.DEFAULT_REGISTRY_SYNONYM)); + final String defaultRegistry = getDefaultRegistrySynonym(); + regList.setSelectedItem (getPrefValue (DP_REGISTRY_SYNONYM, defaultRegistry)); regList.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) { String contents = (String)((JComboBox)e.getSource()).getSelectedItem(); @@ -434,9 +436,9 @@ theReg = regs.get (contents); } catch (MobyException ee) { try { - theReg = regs.get (null); + theReg = regs.get (defaultRegistry); } catch (MobyException ee2) { - log.error ("List of registries does not contain a default registry."); + log.error ("List of registries does not contain the default registry."); } } if (theReg != null) { @@ -458,6 +460,69 @@ } /************************************************************************** + * Filter the given list of known registry by an optional + * properties. Return the filtered result, or the same list if + * there is no relevant property. Check if the wanted registries + * are also registered ones and ignore (with warning) those that + * are not. + **************************************************************************/ + protected static String[] getOnlyWantedRegistries (String[] regs) { + String[] wantedRegs = DashboardConfig.getStrings (DP_WANTED_REGISTRIES, null); + + if (wantedRegs.length == 0) + return regs; + + // check if all of the wanted registries are also known ones + List registeredAndWanted = new ArrayList(); + for (String wantedReg: wantedRegs) { + boolean found = false; + for (String knownReg: regs) { + if (wantedReg.equals (knownReg)) { + found = true; + break; + } + } + if (found) { + registeredAndWanted.add (wantedReg); + } else { + log.warn ("An unknown registry synonym found in the property " + + DP_WANTED_REGISTRIES + ": " + wantedReg); + } + } + if (registeredAndWanted.size() > 0) { + return registeredAndWanted.toArray (new String[] {}); + } else { + return regs; + } + } + + /************************************************************************** + * Return a synonym of the default registry. It is retrieved (in + * this order): + * + * - from the property DP_DEFAULT_REGISTRY; + * - from Registries.DEFAULT_REGISTRY_SYNONYM. + * + * Log warning if the returned default registry is not in the list + * of wanted registries. + **************************************************************************/ + protected static String getDefaultRegistrySynonym() { + + String defaultReg = DashboardConfig.getString (DP_DEFAULT_REGISTRY, null); + if (defaultReg == null) + defaultReg = Registries.DEFAULT_REGISTRY_SYNONYM; + + String[] wantedRegs = + getOnlyWantedRegistries (RegistriesList.getInstance().list()); + for (String wantedReg: wantedRegs) { + if (defaultReg.equals (wantedReg)) + return defaultReg; + } + log.warn ("Default registry '" + defaultReg + "' is not found in wanted registries."); + return defaultReg; + } + + /************************************************************************** * Panel for registry. **************************************************************************/ protected JPanel getRegistryLocation() { From kawas at dev.open-bio.org Wed Nov 19 09:24:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 09:24:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191424.mAJEOEsB009759@dev.open-bio.org> kawas Wed Nov 19 09:24:14 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates In directory dev.open-bio.org:/tmp/cvs-serv9702/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates Modified Files: service.tt Log Message: bug fix: when using service that consumes/outputs a primitive, certain 'use' statements are missing and service dies. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates service.tt,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt 2008/03/31 18:05:17 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt 2008/11/19 14:24:14 1.5 @@ -50,7 +50,68 @@ ), [%- END %] [%- END -%] + + [%- MACRO get_use_statements (inputs, outputs) BLOCK %] + [%- SET use_statements = [] -%] + [%- FOREACH input IN inputs -%] + [%- IF NOT is_simple (input) -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == input.elements.0.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (input.elements.0.datatype.name) -%] + [%- get_use_statement(input.elements.0.datatype.name) -%] + [%- END -%] + [%- ELSE -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == input.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (input.datatype.name) -%] + [%- get_use_statement(input.datatype.name) -%] + [%- END -%] + [%- END -%] + [%- END -%] + [%- FOREACH output IN outputs -%] + [%- IF NOT is_simple (output) -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == output.elements.0.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (output.elements.0.datatype.name) -%] + [%- get_use_statement(output.elements.0.datatype.name) -%] + [%- END -%] + [%- ELSE -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == output.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (output.datatype.name) -%] + [%- get_use_statement(output.datatype.name) -%] + [%- END -%] + [%- END -%] + [%- END -%] + [%- END -%] + + [%- MACRO get_use_statement(datatype) BLOCK %] + [%- IF datatype == 'String' %]use MOSES::MOBY::Data::String; + + [%- ELSIF datatype == 'Integer' %]use MOSES::MOBY::Data::Integer; + + [%- ELSIF datatype == 'Float' %]use MOSES::MOBY::Data::Float; + [%- ELSIF datatype == 'Boolean' %]use MOSES::MOBY::Data::Boolean; + + [%- ELSIF datatype == 'DateTime' %]use MOSES::MOBY::Data::DateTime; + + [%- END -%] + [%- END -%] + + [%- MACRO no_children (datatype, value) BLOCK %] [%- IF datatype == 'String' %]value => "this is a value [% value %]", # TO BE EDITED [%- ELSIF datatype == 'Integer' %]value => 42, # TO BE EDITED @@ -143,6 +204,9 @@ use MOSES::MOBY::ServiceException; use strict; +[%# here we output use statements for our primitives %] +[%- get_use_statements(base.inputs, base.outputs) -%] + my %valid_namespaces = ( [% FOREACH ns IN input_ns %] '[%ns%]'=>1, [% END %]); #----------------------------------------------------------------- # process_it From kawas at dev.open-bio.org Wed Nov 19 09:24:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 09:24:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191424.mAJEOEiD009741@dev.open-bio.org> kawas Wed Nov 19 09:24:13 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY In directory dev.open-bio.org:/tmp/cvs-serv9702/Perl/MOSES-MOBY Modified Files: Makefile.PL Changes Log Message: bug fix: when using service that consumes/outputs a primitive, certain 'use' statements are missing and service dies. moby-live/Perl/MOSES-MOBY Makefile.PL,1.10,1.11 Changes,1.9,1.10 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/06 18:32:33 1.10 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/19 14:24:13 1.11 @@ -6,7 +6,7 @@ # Define metadata name 'MOSES-MOBY'; - version '0.86'; + version '0.87'; license 'perl'; abstract 'This distribution aids in the creation of BioMOBY perl based web services.'; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/06 18:32:33 1.9 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/19 14:24:13 1.10 @@ -20,6 +20,9 @@ - MOSES::MOBY::Cache::Registries::init used to do a file read each time a new Registries object was instantiated. Not the case anymore. + - fixed bug: + Services that consume/output primitives didn't have the + proper 'use' statements. .86 Sun May 11 - fixed a bug in one of the test cases. From groscurt at dev.open-bio.org Wed Nov 19 10:28:03 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:28:03 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191528.mAJFS3Sw010138@dev.open-bio.org> groscurt Wed Nov 19 10:28:03 EST 2008 Update of /home/repository/moby/moby-live/Java/src/config/dashboard In directory dev.open-bio.org:/tmp/cvs-serv10107/Java/src/config/dashboard Added Files: dashboard.jnlp.template Log Message: A template file for the JNLP file used in the Dashboard Webstart application moby-live/Java/src/config/dashboard dashboard.jnlp.template,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 19 10:28:43 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:28:43 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191528.mAJFShLf010198@dev.open-bio.org> groscurt Wed Nov 19 10:28:43 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10167/Java/docs Added Files: DashboardWebstart.html Log Message: HTML documentation of the DashboardWebstart process moby-live/Java/docs DashboardWebstart.html,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 19 10:29:04 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:29:04 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191529.mAJFT4cC010241@dev.open-bio.org> groscurt Wed Nov 19 10:29:04 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10206/Java/docs Modified Files: index.html Log Message: added the link to the DashboardWebstart.html moby-live/Java/docs index.html,1.35,1.36 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.35 retrieving revision 1.36 diff -u -r1.35 -r1.36 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/10/30 02:02:59 1.35 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/19 15:29:04 1.36 @@ -102,6 +102,7 @@

  • How to change Ant's build.xml
  • RDF Agent +
  • The Dashboard as Webstart From groscurt at dev.open-bio.org Wed Nov 19 10:29:32 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:29:32 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191529.mAJFTWeI010284@dev.open-bio.org> groscurt Wed Nov 19 10:29:32 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv10249/Java/xmls Modified Files: dashboardBuild.xml Log Message: added the tasks for the Dashboard Webstart application moby-live/Java/xmls dashboardBuild.xml,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml 2008/03/02 12:45:27 1.5 +++ /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml 2008/11/19 15:29:32 1.6 @@ -71,4 +71,262 @@ + + + + + + The following information is required to create keystore with which the jars for the webstart application will be signed. + + + + + + + + + + + + + + + + + + + + + + + + + + The keystore was successfully created and can be found under + ${dashboard.keystore.location}. + + + + + + + + + + + Enter the absolute path of the keystore (it has to be a valid and accessible path ! e.g. /usr/local/user/mykeystore). + If you want to use an existing one, type the location of the keystore, otherwise a new one will be created. + If you want recreate the keystore you have to do delete the existing one before ! + + + + + + You must provide a path for the keystore ! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This task will build the BioMoby dashboard as a JavaWebStart application. + + For that it has to sign the jars which dashboard requires. For this, several information is needed to establish a 'keystore'. + In any case you already have a valid keystore, you are free to use this. + Otherwise the task will create a new one. + + Please fill out all information which is needed to build a working WebStart application. + Please FIRST read carefully the instructions and information in the /docs/DashboardWebstart.html !. + + Thank you :) (Press RETURN to continue) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Please type in the base URL where the dashboard web start will be accessible. + This must be a publicly available URL (like http://mydomain.com/dashboard) + + + + + You have to provide a URL to procceed ! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${path.convert.lib} + + + + ]]> + + + + + + + + + + + ]]> + + + + + + + + Please enter a at least 6 character password for the keystore (mandatory !) + (if you already created the keystore then please retype your password ! + if you cant remember your password, delete keystore file and re-run the task again !) + + + + + + You must provide a password for the signature of the key for the + dashboard webstart ! + + + + Enter the key password (RETURN if same as keystore password) + (if you already created the keystore then please retype the password or return if its the same as the keystore password) + + + + + . + From groscurt at dev.open-bio.org Wed Nov 19 10:43:18 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:43:18 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191543.mAJFhIC8010411@dev.open-bio.org> groscurt Wed Nov 19 10:43:18 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10376/Java/docs Modified Files: DashboardWebstart.html Log Message: some typos... moby-live/Java/docs DashboardWebstart.html,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html 2008/11/19 15:28:43 1.1 +++ /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html 2008/11/19 15:43:18 1.2 @@ -6,7 +6,7 @@ the existing Ant-based project. " /> @@ -35,12 +35,12 @@
  • As Java Webstart is provided over the internet you need to deploy it on an web server (such as the Apache httpd server).
    So please ensure that you or someone you trust has access to the document root directory of you web server.
    -Furthermore please ensure that the following line is in the mime.types file found at /your/web/server/conf/mime.types: +Furthermore please ensure that the following line is in the mime.types file found at /your/web/server/conf:
     application/x-java-jnlp-file    jnlp
     
    -This let the web server know to handle the jnlp file correctly. If this entry has not been in your mime.types please restart your webserver. +This lets the web server know how to handle the jnlp file correctly. If this entry has not been in your mime.types please restart your webserver.
  • @@ -83,7 +83,7 @@ ant install - +
    Creating the Dashboard Webstart application is as easy as getting wet on a rainy day.
    Just run

    @@ -105,7 +105,7 @@

    Creating a keystore

    If you entered a keystore which does not exists, the process will ask you several information about who you are and where you from. -
    Keep in mind that this information is really important as people who start you Dashboard JavaWebstart have to accept that the application gets access to their harddrives. +
    Keep in mind that this information is really important as people who start your Dashboard JavaWebstart have to accept that the application gets access to their harddrives. The values you enter here are shown to the user and they are asked if they trust the person offering the Webstart application. So please enter the correct information about you.
    At the end you have to give a password which is at least 6 characters long for the keystore. This password will be always required in case you add another key to the keystore, so dont forget this one.
    After that you are free to enter the password for the key you are about to create. If you want to use the same password as for the keystore itself, just hit RETURN. Otherwise enter your password. From groscurt at dev.open-bio.org Wed Nov 19 11:34:15 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 11:34:15 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191634.mAJGYFbu010480@dev.open-bio.org> groscurt Wed Nov 19 11:34:15 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10445/Java/docs Modified Files: Dashboard.html Log Message: added information about the changes in the dashboard.properties file and how to add new repositories moby-live/Java/docs Dashboard.html,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/Dashboard.html,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Java/docs/Dashboard.html 2008/02/14 06:13:34 1.8 +++ /home/repository/moby/moby-live/Java/docs/Dashboard.html 2008/11/19 16:34:15 1.9 @@ -29,6 +29,7 @@
  • How to start Dashboard
  • How to use Dashboard
  • Dashboard Panels Gallery +
  • Customize the available repositories / Adding a new Repository
  • Plans and issues
  • Dashboard for developers
      @@ -225,6 +226,33 @@

      + +

      Customize the available repositories / Adding a new Repository

      +This explains how you can manipulate the available repositories in your Dashboard. +

      Customize the available repositories

      +To manipulate which repositories shall be available in your Dashboard application you can edit the moby-live/Java/src/config/dashboard/dashboard.properties file.
      +Search for the dashboard.wanted.registries, which is per default not active. If you activate it by removing the # before the line you can remove the repositories by deleting the corresponding entry.
      +For example this is the original one: +
      +
      +#dashboard.wanted.registries = default,Calgary,INB,IRRI,testing
      +
      +
      +if you now want only to have the official BioMoby central and its test repository: +
      +
      +dashboard.wanted.registries = default,Calgary,testing
      +
      +
      +after that just start dashboard again with ant dashboard + +

      Adding a new Repository

      +

      IMPORTANT: We do not encourage people to set up their own repository as every can use the official BioMoby central repository. But if in any case you have to set up an own repository this explains how to make it visible in Dashboard.

      +The easiest way is to type the URL and the URI in the Endpoint and Namespace (URI) input fields in Dashboard, respectively. Dashboard does remember your inputs and you can select your entries later again. +

      If you want to have it as an entry in the dropdown box you have to edit the moby-live/Java/src/org/biomoby/registry/meta/RegistriesList.java file and add there your repository based on the template of the others. This should be only done if you know what you are doing !
      +After that you should add the name of your repository also to the dashboard.wanted.registries property inside the moby-live/Java/src/config/dashboard/dashboard.properties.

      +If you then restart dashboard you will see now your repository coming up. +

      Plans and issues

      From kawas at dev.open-bio.org Wed Nov 19 16:29:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 16:29:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811192129.mAJLTEv2011305@dev.open-bio.org> kawas Wed Nov 19 16:29:14 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv11270/Perl/MOBY-Server/lib/MOBY/Client Modified Files: CollectionArticle.pm Log Message: fixed documentation type moby-live/Perl/MOBY-Server/lib/MOBY/Client CollectionArticle.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm 2008/09/02 13:11:40 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm 2008/11/19 21:29:14 1.4 @@ -130,7 +130,7 @@ =head2 addSimple - Usage : $namespaces = $IN->addNamespace($SimpleArticle) + Usage : $simples = $IN->addSimple($SimpleArticle) Function : add another SimpleArticle Returns : arrayref of MOBY::Client::SimpleArticle's or 0 if argument was not a MOBY::Client::SimpleArticle (or other failure) From kawas at dev.open-bio.org Wed Nov 19 16:31:21 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 16:31:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811192131.mAJLVLdL011381@dev.open-bio.org> kawas Wed Nov 19 16:31:21 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv11346/Perl/MOBY-Server/lib/MOBY/Client Modified Files: MobyUnitTest.pm Log Message: fixed whitespace that killed the perldoc for the module. moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/17 15:24:31 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/19 21:31:21 1.2 @@ -264,7 +264,6 @@ $text =~ s/^\s+//; $text =~ s/\s+$//; return $text; - } #----------------------------------------------------------------- @@ -346,7 +345,7 @@ parameters (all optional) include: =over - + =item C - example input to pass to our service when testing it =item C - service output xml that is expected given the example input From kawas at dev.open-bio.org Thu Nov 20 12:01:06 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 12:01:06 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201701.mAKH16E3013056@dev.open-bio.org> kawas Thu Nov 20 12:01:06 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv13021/Perl/MOBY-Server/lib/MOBY/Client Modified Files: ServiceInstance.pm Log Message: added method to get/set unit test info moby-live/Perl/MOBY-Server/lib/MOBY/Client ServiceInstance.pm,1.2,1.3 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm 2008/09/02 13:11:40 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm 2008/11/20 17:01:05 1.3 @@ -2,6 +2,7 @@ use strict; use Carp; use vars qw($AUTOLOAD @ISA); +use MOBY::Client::MobyUnitTest; use vars qw /$VERSION/; $VERSION = sprintf "%d.%02d", q$Revision$ =~ /: (\d+)\.(\d+)/; @@ -216,6 +217,15 @@ =cut +=head2 unitTest + + Title : unitTest + Usage : $test = $Service->unitTest() + Function : get/set the MobyUnitTest for this service + Returns : a MOBY::Client::MobyUnitTest object for this service + +=cut + { # Encapsulated: @@ -224,23 +234,22 @@ #ATTRIBUTES my %_attr_data = # DEFAULT ACCESSIBILITY ( - authority => [ undef, 'read/write' ], - signatureURL => [ undef, 'read/write' ], - name => [ undef, 'read/write' ], - type => [ undef, 'read/write' ], - input => [ undef, 'read/write' ] - , # listref of Simple and Collection articles - output => [ undef, 'read/write' ] - , # listref of Simple and Collection articles - secondary => [ undef, 'read/write' ], # listref of SecondaryArticles - category => [ undef, 'read/write' ], - description => [ undef, 'read/write' ], + authority => [ undef, 'read/write' ], + signatureURL => [ undef, 'read/write' ], + name => [ undef, 'read/write' ], + type => [ undef, 'read/write' ], + input => [ undef, 'read/write' ], # listref of Simple and Collection articles + output => [ undef, 'read/write' ], # listref of Simple and Collection articles + secondary => [ undef, 'read/write' ], # listref of SecondaryArticles + category => [ undef, 'read/write' ], + description => [ undef, 'read/write' ], registry => [ 'MOBY_Central', 'read/write' ], XML => [ undef, 'read/write' ], authoritative => [ undef, 'read/write' ], URL => [ undef, 'read/write' ], contactEmail => [ undef, 'read/write' ], - LSID => [ undef, 'read/write'] + LSID => [ undef, 'read/write'], + unitTest => [ undef, 'read/write'], # a reference to a MobyUnitTest object ); #_____________________________________________________________ @@ -282,6 +291,7 @@ $self->input( [] ) unless $self->input; $self->output( [] ) unless $self->output; $self->secondary( [] ) unless $self->secondary; + $self->unitTest( new MOBY::Client::MobyUnitTest ) unless $self->unitTest; return $self; } From kawas at dev.open-bio.org Thu Nov 20 12:02:24 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 12:02:24 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201702.mAKH2OAJ013110@dev.open-bio.org> kawas Thu Nov 20 12:02:24 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv13079/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Added Files: ServiceParser.pm Log Message: preliminary service instance RDF parser. missing unit testing information. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers ServiceParser.pm,NONE,1.1 From kawas at dev.open-bio.org Thu Nov 20 14:35:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:35:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201935.mAKJZkL5013304@dev.open-bio.org> kawas Thu Nov 20 14:35:46 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv13269/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Modified Files: ServiceParser.pm Log Message: *added the unit test parsing to this module *added a warning telling users not to try and parse the whole service instance ontology moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers ServiceParser.pm,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 17:02:24 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 19:35:46 1.2 @@ -61,6 +61,13 @@ =cut +=head1 WARNING + +Do not attempt to parse service instance RDF containing more than a few hundred services because the RDF is +parsed and held in memory. + +=cut + =head1 AUTHORS Edward Kawas (edward.kawas [at] gmail [dot] com) @@ -228,43 +235,45 @@ $providedBy = [] unless @$providedBy; $providedBy = $$providedBy[0] if ref($providedBy) eq 'ARRAY' and $$providedBy[0]; + if ($providedBy) { - # set the authoritative - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the authoritative + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::FETA ->authoritative - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->authoritative( + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->authoritative( MOBY::RDF::Utils::trim($val) =~ m/true/i ? 1 : 0 ); - # set the contact email - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the contact email + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE ->creator - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->contactEmail( MOBY::RDF::Utils::trim($val) ); + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->contactEmail( MOBY::RDF::Utils::trim($val) ); - # set the authority uri - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the authority uri + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE ->publisher - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->authority( MOBY::RDF::Utils::trim($val) ); + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->authority( MOBY::RDF::Utils::trim($val) ); + } # no longer need the providedBy node $providedBy = undef; @@ -281,6 +290,9 @@ $hasOperation = $$hasOperation[0] if ref($hasOperation) eq 'ARRAY' and $$hasOperation[0]; + # if this is missing ... what's the point? + next unless $hasOperation; + # process any inputs my $inputs = $model->getObjects( $hasOperation, @@ -454,6 +466,7 @@ } elsif ( $val eq MOBY::RDF::Predicates::FETA->secondaryParameter ) { my $param = MOBY::Client::SecondaryArticle->new; + # get the articlename $val = $model->getObjects( @@ -761,7 +774,72 @@ $performs = undef; # process any unit test information - #TODO + my $unit_test = + $model->getObjects( + $hasOperation, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->hasUnitTest + ) + ); + $unit_test = [] unless @$unit_test; + foreach my $ut (@$unit_test) { + my $unit = new MOBY::Client::MobyUnitTest; + + # get example input + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->exampleInput + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->example_input( MOBY::RDF::Utils::trim($val) ); + + # get example output + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA + ->validOutputXML + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->expected_output( MOBY::RDF::Utils::trim($val) ); + + # get regex + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->validREGEX + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->regex( MOBY::RDF::Utils::trim($val) ); + + # get xpath + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->validXPath + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->xpath( MOBY::RDF::Utils::trim($val) ); + + # set the unit test in the service + $instance->unitTest($unit); + + # should only be one ... so last; + last; + } # this service is done ... push @{$services}, $instance; From kawas at dev.open-bio.org Thu Nov 20 14:37:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:37:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201937.mAKJbggm013344@dev.open-bio.org> kawas Thu Nov 20 14:37:42 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv13309/Perl/MOBY-Client Modified Files: populate_libs.pl Log Message: added the service rdf parser to the list of libs moby-live/Perl/MOBY-Client populate_libs.pl,1.7,1.8 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/17 15:30:55 1.7 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/20 19:37:42 1.8 @@ -13,7 +13,7 @@ my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm MobyUnitTest.pm ); my @Exception = qw ( MobyException.pm MobyExceptionCodes.pm ); my @RDF = qw ( Utils.pm ); -my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm); +my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm ServiceParser.pm ); my @predicates = qw ( DC_PROTEGE.pm MOBY_PREDICATES.pm OMG_LSID.pm RDF.pm RDFS.pm FETA.pm OWL.pm ); # current working directory ... @@ -112,6 +112,8 @@ # ? +---Parsers # ? ? ServiceTypeParser.pm # ? ? NamespaceParser.pm +# ? ? ServiceParser.pm +# ? ? DatatypeParser.pm # ? ? # ? +---Predicates # ? DC_PROTEGE.pm From kawas at dev.open-bio.org Thu Nov 20 14:39:02 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:39:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201939.mAKJd247013385@dev.open-bio.org> kawas Thu Nov 20 14:39:01 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv13350/Perl/MOBY-Client Modified Files: MANIFEST Log Message: added MobyUnitTest and ServiceParser to the MANIFEST moby-live/Perl/MOBY-Client MANIFEST,1.10,1.11 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST 2008/08/06 14:48:49 1.10 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST 2008/11/20 19:39:01 1.11 @@ -28,12 +28,14 @@ lib/MOBY/Client/ServiceInstance.pm lib/MOBY/Client/SimpleArticle.pm lib/MOBY/Client/SimpleInput.pm +lib/MOBY/Client/MobyUnitTest.pm lib/MOBY/CommonSubs.pm lib/MOBY/CrossReference.pm lib/MOBY/MobyXMLConstants.pm lib/MOBY/RDF/Parsers/DatatypeParser.pm lib/MOBY/RDF/Parsers/NamespaceParser.pm lib/MOBY/RDF/Parsers/ServiceTypeParser.pm +lib/MOBY/RDF/Parsers/ServiceParser.pm lib/MOBY/RDF/Predicates/DC_PROTEGE.pm lib/MOBY/RDF/Predicates/FETA.pm lib/MOBY/RDF/Predicates/MOBY_PREDICATES.pm From kawas at dev.open-bio.org Thu Nov 20 14:39:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:39:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201939.mAKJdgTs013443@dev.open-bio.org> kawas Thu Nov 20 14:39:42 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF In directory dev.open-bio.org:/tmp/cvs-serv13408/Perl/MOBY-Server/lib/MOBY/RDF Modified Files: Utils.pm Log Message: added a trim function moby-live/Perl/MOBY-Server/lib/MOBY/RDF Utils.pm,1.6,1.7 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/09/02 13:13:20 1.6 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/20 19:39:42 1.7 @@ -130,7 +130,7 @@ sub getHttpRequestByURL { my ( $self, $url ) = @_; my $ua = LWP::UserAgent->new; - $ua->agent( "pMOBY/Central/1.0"); + $ua->agent( "pMOBY/Central/$VERSION"); my $req = HTTP::Request->new( GET => @@ -171,5 +171,22 @@ END_OF_RDF } +=head2 trim + +trims whitespace from the begining and end of a string + +=cut + +sub trim { + my ($self, $text) = @_; + $text = $self + unless (ref($self) == 'Moby::RDF::Utils') and defined($text); + $text =~ s/^\s+//; + $text =~ s/\s+$//; + return $text; +} + + + 1; __END__ From kawas at dev.open-bio.org Thu Nov 20 14:40:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:40:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201940.mAKJegcJ013483@dev.open-bio.org> kawas Thu Nov 20 14:40:41 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv13448/Perl/MOBY-Server Modified Files: MANIFEST Log Message: added MobyUnitTest and ServiceParser to the MANIFEST moby-live/Perl/MOBY-Server MANIFEST,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST 2008/07/07 18:32:25 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST 2008/11/20 19:40:41 1.9 @@ -43,6 +43,7 @@ lib/MOBY/Client/ServiceInstance.pm lib/MOBY/Client/SimpleArticle.pm lib/MOBY/Client/SimpleInput.pm +lib/MOBY/Client/MobyUnitTest.pm lib/MOBY/collection_input.pm lib/MOBY/collection_output.pm lib/MOBY/CommonSubs.pm @@ -67,6 +68,7 @@ lib/MOBY/RDF/Parsers/DatatypeParser.pm lib/MOBY/RDF/Parsers/NamespaceParser.pm lib/MOBY/RDF/Parsers/ServiceTypeParser.pm +lib/MOBY/RDF/Parsers/ServiceParser.pm lib/MOBY/RDF/Predicates/DC_PROTEGE.pm lib/MOBY/RDF/Predicates/FETA.pm lib/MOBY/RDF/Predicates/MOBY_PREDICATES.pm From kawas at dev.open-bio.org Mon Nov 24 09:38:33 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 24 Nov 2008 09:38:33 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811241438.mAOEcXWE010637@dev.open-bio.org> kawas Mon Nov 24 09:38:32 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies In directory dev.open-bio.org:/tmp/cvs-serv10602/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies Modified Files: Services.pm Log Message: added unit test information to the RDF that is outputted by this module. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies Services.pm,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm 2008/10/31 18:40:37 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm 2008/11/24 14:38:32 1.9 @@ -125,21 +125,21 @@ $self->{datatype_uri} = $CONF->{mobyobject}->{resourceURL} || ''; $self->{namespace_uri} = $CONF->{mobynamespace}->{resourceURL} || ''; } unless $args{endpoint}; - + # save the endpoint/namespace/uri if passed in $self->{endpoint} = $args{endpoint} if $args{endpoint}; $self->{namespace} = $args{endpoint} if $args{namespace}; unless ( $self->{instance_uri} ) { - my $moby = MOBY::Client::Central->new( + my $moby = + MOBY::Client::Central->new( Registries => { mobycentral => { URL => $self->{endpoint}, URI => 'http://mobycentral.cbr.nrc.ca/MOBY/Central' } } - ) - if $self->{endpoint}; + ) if $self->{endpoint}; # otherwise use default one $moby = MOBY::Client::Central->new() unless $self->{endpoint}; @@ -176,10 +176,13 @@ $self->{namespace_uri} = $self->{namespace_uri} . "/" unless $self->{namespace_uri} =~ m/^.*(\/{1})$/; $self->{datatype_uri} = $self->{datatype_uri} . "/" - unless $self->{datatype_uri} =~ m/^.*(\/{1})$/; + unless $self->{datatype_uri} =~ m/^.*(\/{1})$/; #set the isAlive path - $self->{is_alive_path} = $CONF->{mobycentral}->{service_tester_path} if $ENV{MOBY_SERVER} and $self->{endpoint} and $ENV{MOBY_SERVER} eq $self->{endpoint}; + $self->{is_alive_path} = $CONF->{mobycentral}->{service_tester_path} + if $ENV{MOBY_SERVER} + and $self->{endpoint} + and $ENV{MOBY_SERVER} eq $self->{endpoint}; # done return $self; @@ -208,20 +211,20 @@ my $authURI = $hash->{authURI} || ''; my $name = $hash->{serviceName} || ''; my $prettyPrint = $hash->{prettyPrint} ? $hash->{prettyPrint} : 'yes'; - my $addIsAlive = $hash->{isAlive} ? $hash->{isAlive} : 'yes'; - my $services = []; + my $addIsAlive = $hash->{isAlive} ? $hash->{isAlive} : 'yes'; + my $services = []; my $RegObject; # use the passed in endpoint if applicable - my $moby = MOBY::Client::Central->new( + my $moby = + MOBY::Client::Central->new( Registries => { mobycentral => { URL => $self->{endpoint}, URI => 'http://mobycentral.cbr.nrc.ca/MOBY/Central' } } - ) - if $self->{endpoint}; + ) if $self->{endpoint}; # otherwise use default one $moby = MOBY::Client::Central->new() unless $self->{endpoint}; @@ -230,7 +233,8 @@ ( $services, $RegObject ) = $moby->findService( authURI => $authURI, serviceName => $name ); - } else { + } + else { my (@URIS) = $moby->retrieveServiceProviders(); foreach my $provider (@URIS) { my ( $instances, $RegObject ) = @@ -265,13 +269,13 @@ my $node_factory = new RDF::Core::NodeFactory(); foreach my $SI (@$services) { + # used for computing checksums - my $service_name = $SI->name; + my $service_name = $SI->name; my $service_authority = $SI->authority; - my $resource = - new RDF::Core::Resource( $self->{instance_uri}, - $SI->authority . "," . $SI->name ); + my $resource = new RDF::Core::Resource( $self->{instance_uri}, + $SI->authority . "," . $SI->name ); $model->addStmt( new RDF::Core::Statement( $resource, @@ -329,14 +333,18 @@ new RDF::Core::Literal( $SI->name ) ) ); - eval{ + eval { do { + # add is alive information if necessary - if ( $self->{is_alive_path} and -e $self->{is_alive_path} and -r $self->{is_alive_path} ."/isAliveStats.xml") { + if ( $self->{is_alive_path} + and -e $self->{is_alive_path} + and -r $self->{is_alive_path} . "/isAliveStats.xml" ) + { my $parser = XML::LibXML->new(); - my $doc = + my $doc = $parser->parse_file( - $self->{is_alive_path} . '/isAliveStats.xml' ); + $self->{is_alive_path} . '/isAliveStats.xml' ); my $value = "true"; my $id = $SI->authority . "," . $SI->name; my @nodelist = $doc->getElementsByTagName("service"); @@ -346,30 +354,41 @@ last; } $model->addStmt( - new RDF::Core::Statement( - $resource, - $resource->new( MOBY::RDF::Predicates::FETA->isAlive ), - new RDF::Core::Literal($value) - ) + new RDF::Core::Statement( + $resource, + $resource->new( + MOBY::RDF::Predicates::FETA->isAlive + ), + new RDF::Core::Literal($value) + ) ); - } else { - + } + else { + # by default, state the service is alive ... $model->addStmt( - new RDF::Core::Statement( - $resource, - $resource->new( MOBY::RDF::Predicates::FETA->isAlive ), - new RDF::Core::Literal('true') - ) + new RDF::Core::Statement( + $resource, + $resource->new( + MOBY::RDF::Predicates::FETA->isAlive + ), + new RDF::Core::Literal('true') + ) ); } - } unless $addIsAlive =~ /no/i; + } unless $addIsAlive =~ /no/i; }; + # add the authoring statements - my $bnode = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->providedBy ) - ); #$node_factory->newResource; + my $bnode = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->providedBy + ) + ); #$node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $resource, @@ -401,20 +420,25 @@ ) ); $model->addStmt( - new RDF::Core::Statement( - $bnode, - $resource->new( MOBY::RDF::Predicates::RDF->type ), - new RDF::Core::Resource( - MOBY::RDF::Predicates::FETA->organisation - ) - ) + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->organisation + ) + ) ); # add parameter statements - my $operation = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->hasOperation) - ); # $node_factory->newResource; + my $operation = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->hasOperation + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $resource, @@ -440,9 +464,12 @@ ) ); $bnode = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->performsTask) - ); # $node_factory->newResource; + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA->performsTask + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -460,26 +487,107 @@ ) ); $model->addStmt( - new RDF::Core::Statement( - $bnode, - $resource->new( MOBY::RDF::Predicates::RDF->type ), - new RDF::Core::Resource( - $self->{service_uri} . $SI->type + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( $self->{service_uri} . $SI->type ) ) - ) ); + # add unit test data here ... + if ( $SI->unitTest ) { + my $unit_test = $SI->unitTest; + $bnode = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->unitTest + ) + ); + + # add the type + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->unitTest + ) + ) + ); + + # add the example input if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->exampleInput ), + new RDF::Core::Literal( $unit_test->example_input ) + ) + ) + if $unit_test->example_input + and $unit_test->example_input ne ''; + + # add the valid output xml if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( + MOBY::RDF::Predicates::FETA->validOutputXML + ), + new RDF::Core::Literal( $unit_test->expected_output ) + ) + ) + if $unit_test->expected_output + and $unit_test->expected_output ne ''; + + # add the valid regex if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->validREGEX ), + new RDF::Core::Literal( $unit_test->regex ) + ) + ) + if $unit_test->regex + and $unit_test->regex ne ''; + + # add the valid xpath expression if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->validXPath ), + new RDF::Core::Literal( $unit_test->xpath ) + ) + ) + if $unit_test->xpath + and $unit_test->xpath ne ''; + + $model->addStmt( + new RDF::Core::Statement( + $operation, + $resource->new( MOBY::RDF::Predicates::FETA->hasUnitTest ), + $bnode + ) + ); + } + my $inputs = $SI->input; foreach (@$inputs) { - my $inputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName) - ); # $node_factory->newResource; + my $inputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -509,18 +617,17 @@ ) ); - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $_->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter . "/" + . $_->articleName . "/" + . $_->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -535,22 +642,21 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $_->objectType + $self->{datatype_uri} . $_->objectType ) #TODO check for lsid ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -571,17 +677,18 @@ ); my $namespaces = $_->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -605,13 +712,13 @@ $inNamespaces, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); } - } elsif ( $_->isCollection ) { + } + elsif ( $_->isCollection ) { $model->addStmt( new RDF::Core::Statement( @@ -632,16 +739,16 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -663,18 +770,18 @@ my $simples = $_->Simples; foreach my $simp (@$simples) { - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $simp->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $simp->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -689,24 +796,26 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $simp->objectType + $self->{datatype_uri} . $simp->objectType ) #TODO check for lsid ) ); my $namespaces = $simp->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -735,8 +844,7 @@ MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); @@ -749,15 +857,17 @@ foreach (@$secondaries) { next unless $_->isSecondary; - my $inputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . "isSecondaryInputParameter/" - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName) - ); #$node_factory->newResource; + my $inputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . "isSecondaryInputParameter/" + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName + ) + ); #$node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -777,16 +887,17 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . "isSecondary/" - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . "isSecondary/" + . MOBY::RDF::Predicates::FETA->hasParameterType + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -822,8 +933,7 @@ $resource->new( MOBY::RDF::Predicates::FETA->min ), new RDF::Core::Literal( $_->min ) ) - ) - if defined( $_->min ); + ) if defined( $_->min ); $model->addStmt( new RDF::Core::Statement( @@ -831,8 +941,7 @@ $resource->new( MOBY::RDF::Predicates::FETA->max ), new RDF::Core::Literal( $_->max ) ) - ) - if defined( $_->max ); + ) if defined( $_->max ); $model->addStmt( new RDF::Core::Statement( @@ -852,8 +961,7 @@ ), new RDF::Core::Literal( $_->default ) ) - ) - if defined( $_->default ); + ) if defined( $_->default ); $model->addStmt( new RDF::Core::Statement( @@ -875,15 +983,18 @@ my $outputs = $SI->output; foreach (@$outputs) { - my $outputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName) - ); # $node_factory->newResource; + my $outputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -913,18 +1024,17 @@ ) ); - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $_->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter . "/" + . $_->articleName . "/" + . $_->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -939,22 +1049,21 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $_->objectType + $self->{datatype_uri} . $_->objectType ) #TODO check for lsid ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -975,17 +1084,18 @@ ); my $namespaces = $_->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1009,13 +1119,13 @@ $inNamespaces, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); } - } elsif ( $_->isCollection ) { + } + elsif ( $_->isCollection ) { $model->addStmt( new RDF::Core::Statement( @@ -1036,16 +1146,16 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1067,18 +1177,18 @@ my $simples = $_->Simples; foreach my $simp (@$simples) { - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $simp->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $simp->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1093,24 +1203,26 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $simp->objectType + $self->{datatype_uri} . $simp->objectType ) #TODO check for lsid ) ); my $namespaces = $simp->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1139,8 +1251,7 @@ MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); @@ -1150,11 +1261,12 @@ } } my $xml = ''; - my $serializer = new RDF::Core::Model::Serializer( - Model => $model, - Output => \$xml, - BaseURI => 'URI://BASE/', - ); + my $serializer = + new RDF::Core::Model::Serializer( + Model => $model, + Output => \$xml, + BaseURI => 'URI://BASE/', + ); $serializer->serialize; return $xml; } From kawas at dev.open-bio.org Mon Nov 24 09:40:04 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 24 Nov 2008 09:40:04 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811241440.mAOEe4DW010678@dev.open-bio.org> kawas Mon Nov 24 09:40:03 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv10643/Perl/MOBY-Server Modified Files: Changes Log Message: updated to reflect changes to Services.pm (added unit test information to rdf) moby-live/Perl/MOBY-Server Changes,1.16,1.17 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.16 retrieving revision 1.17 diff -u -r1.16 -r1.17 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:28:46 1.16 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/24 14:40:03 1.17 @@ -25,6 +25,8 @@ - Fixed the uri in the RDF returned in MobyMetadataResolver.pm when the resolver is attempting to let you know what the latest lsid is for the given entity. + - RDF for service instances now includes unit test information if unit + test information is available for the service instance. 1.05 From kawas at dev.open-bio.org Tue Nov 25 12:29:55 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 12:29:55 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251729.mAPHTti8015447@dev.open-bio.org> kawas Tue Nov 25 12:29:54 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv15412/Perl/MOBY-Server/lib/MOBY/Client Modified Files: MobyUnitTest.pm Log Message: fixed the way that i was using the hash references. moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,1.2,1.3 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/19 21:31:21 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/25 17:29:54 1.3 @@ -195,15 +195,15 @@ # for each doc and remove from current level of hash for my $key ( keys %$control ) { next unless $key =~ m/^xmlns[:]?/; - $control_ns->{''} = %$control->{$key} if $key eq 'xmlns'; - $control_ns->{$1} = %$control->{$key} if $key =~ m/xmlns\:(.*)$/g; - delete %$control->{$key}; + $control_ns->{''} = ${$control}->{$key} if $key eq 'xmlns'; + $control_ns->{$1} = ${$control}->{$key} if $key =~ m/xmlns\:(.*)$/g; + delete $$control->{$key}; } for my $key ( keys %$test ) { next unless $key =~ m/^xmlns[:]?/; - $test_ns->{''} = %$test->{$key} if $key eq 'xmlns'; - $test_ns->{$1} = %$test->{$key} if $key =~ m/xmlns\:(.*)$/g; - delete %$test->{$key}; + $test_ns->{''} = ${$test}->{$key} if $key eq 'xmlns'; + $test_ns->{$1} = ${$test}->{$key} if $key =~ m/xmlns\:(.*)$/g; + delete ${$test}->{$key}; } # compare current level number of keys @@ -223,27 +223,27 @@ { # are we dealing with scalar values now or more nesting? - if ( ref( %$control->{$key} ) eq 'ARRAY' ) { + if ( ref( ${$control}->{$key} ) eq 'ARRAY' ) { # both items should be an array - next unless ref(%$test->{$test_key}) eq 'ARRAY'; + next unless ref(${$test}->{$test_key}) eq 'ARRAY'; # array sizes should match here ... - next unless @{%$control->{$key}} == @{%$test->{$test_key}}; + next unless @{${$control}->{$key}} == @{${$test}->{$test_key}}; # more nesting try matching child nodes my $child_matches = 0; - foreach my $child ( @{ %$control->{$key} } ) { + foreach my $child ( @{ ${$control}->{$key} } ) { my $matched = undef; - foreach my $test_child ( @{ %$test->{$test_key} } ) { + foreach my $test_child ( @{ ${$test}->{$test_key} } ) { $matched = $self->_compare_current_level( $child, $test_child, $control_ns, $test_ns ); $child_matches++ if $matched; last if $matched; } # end inner foreach - $matching_nodes++ if @{ %$control->{$key} } == $child_matches; + $matching_nodes++ if @{ ${$control}->{$key} } == $child_matches; } } else { # compare scalar values now # we dont care about whitespace, so we need to trim the text - my $c_text = $self->_clear_whitespace(%$control->{$key}); - my $t_text = $self->_clear_whitespace(%$test->{$test_key}); + my $c_text = $self->_clear_whitespace(${$control}->{$key}); + my $t_text = $self->_clear_whitespace(${$test}->{$test_key}); $matching_nodes++ if $c_text eq $t_text; last if $c_text eq $t_text; } @@ -332,6 +332,8 @@ croak "not yet implemented ...\n"; } +sub DESTROY { } + 1; __END__ From kawas at dev.open-bio.org Tue Nov 25 13:05:44 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 13:05:44 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251805.mAPI5iUF015600@dev.open-bio.org> kawas Tue Nov 25 13:05:44 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv15553/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Modified Files: NamespaceParser.pm ServiceParser.pm DatatypeParser.pm ServiceTypeParser.pm Log Message: array and hash refs werent generated/returned properly. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers NamespaceParser.pm,1.3,1.4 ServiceParser.pm,1.2,1.3 DatatypeParser.pm,1.2,1.3 ServiceTypeParser.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm 2008/09/02 13:12:58 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm 2008/11/25 18:05:44 1.4 @@ -110,8 +110,8 @@ sub getNamespaces { my ($self, $url) = @_; - -return \{} unless $url; +my %hash; +return \%hash unless $url; # download string from url my $rdf = undef; @@ -120,7 +120,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -135,7 +135,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $namespace = $statement->getSubject->getLocalValue; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 19:35:46 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/25 18:05:44 1.3 @@ -118,15 +118,15 @@ sub getServices { my ( $self, $url ) = @_; - - return \[] unless $url; + my @services; + return \@services unless $url; # download string from url my $rdf = undef; # 'try/catch' eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; - return \[] unless $rdf; + return \@services unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -149,7 +149,6 @@ ) ) ); - my $services = []; my $statement = $enumerator->getFirst; while ( defined $statement ) { my $instance = MOBY::Client::ServiceInstance->new; @@ -842,15 +841,15 @@ } # this service is done ... - push @{$services}, $instance; + push @services, $instance; # next if any $statement = $enumerator->getNext; } $enumerator->close; - # return hash - return \$services; + # return array ref + return \@services; } =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm 2008/09/02 13:12:58 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm 2008/11/25 18:05:44 1.3 @@ -135,8 +135,8 @@ sub getDatatypes { my ($self, $url) = @_; - -return \{} unless $url; +my %hash = (); +return \%hash unless $url; # download string from url my $rdf = undef; @@ -145,7 +145,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -160,7 +160,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $datatype = $statement->getSubject->getLocalValue; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm 2008/09/02 13:12:58 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm 2008/11/25 18:05:44 1.4 @@ -110,8 +110,8 @@ sub getServiceTypes { my ($self, $url) = @_; - -return \{} unless $url; +my %hash; +return \%hash unless $url; # download string from url my $rdf = undef; @@ -120,7 +120,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate @@ -136,7 +136,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $servicetype = $statement->getSubject->getLocalValue; From kawas at dev.open-bio.org Tue Nov 25 13:05:59 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 13:05:59 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251805.mAPI5x1w015640@dev.open-bio.org> kawas Tue Nov 25 13:05:59 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF In directory dev.open-bio.org:/tmp/cvs-serv15605/Perl/MOBY-Server/lib/MOBY/RDF Modified Files: Utils.pm Log Message: moby-live/Perl/MOBY-Server/lib/MOBY/RDF Utils.pm,1.7,1.8 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/20 19:39:42 1.7 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/25 18:05:59 1.8 @@ -180,7 +180,7 @@ sub trim { my ($self, $text) = @_; $text = $self - unless (ref($self) == 'Moby::RDF::Utils') and defined($text); + unless (ref($self) eq 'Moby::RDF::Utils') and defined($text); $text =~ s/^\s+//; $text =~ s/\s+$//; return $text; From kawas at dev.open-bio.org Tue Nov 25 14:37:10 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:37:10 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251937.mAPJbA0r015753@dev.open-bio.org> kawas Tue Nov 25 14:37:10 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi In directory dev.open-bio.org:/tmp/cvs-serv15718/Perl/MOBY-Server/share/cgi Modified Files: service_tester.pl Log Message: added $TIMEOUT to the cgi call for web services moby-live/Perl/MOBY-Server/share/cgi service_tester.pl,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl 2008/06/17 16:19:39 1.5 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl 2008/11/25 19:37:10 1.6 @@ -154,6 +154,7 @@ # test cgi services do { my $ua = LWP::UserAgent->new; + $ua->timeout($TIMEOUT); my $req = POST $url, [ data => $input]; $req = $ua->request($req); $out = $req->content if $req->is_success; From kawas at dev.open-bio.org Tue Nov 25 14:39:36 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:39:36 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251939.mAPJdaMR015808@dev.open-bio.org> kawas Tue Nov 25 14:39:36 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi In directory dev.open-bio.org:/tmp/cvs-serv15777/Perl/MOBY-Server/share/cgi Added Files: service_unit_tester.pl Log Message: first crack at an 'agent' that can do unit testing of moby services. basically: script gets all sig urls services extracted from urls any service that defines a unit test is tested and results stored. moby-live/Perl/MOBY-Server/share/cgi service_unit_tester.pl,NONE,1.1 From kawas at dev.open-bio.org Tue Nov 25 14:47:24 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:47:24 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251947.mAPJlNY0015848@dev.open-bio.org> kawas Tue Nov 25 14:47:23 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts In directory dev.open-bio.org:/tmp/cvs-serv15813/Perl/MOBY-Server/bin/scripts Modified Files: moby-s-install.pl Log Message: added a check for XML::Simple and added a copy statement for service_unit_tester.pl moby-live/Perl/MOBY-Server/bin/scripts moby-s-install.pl,1.13,1.14 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl 2008/09/02 13:19:13 1.13 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl 2008/11/25 19:47:23 1.14 @@ -76,6 +76,7 @@ DBI DBD::mysql LS + XML::Simple ) ) { @@ -1393,7 +1394,7 @@ } $answer = pprompt( -"Would you like to auxillary scripts? These include the service pinger, a test page for the rdf agent, an RDF generator page, etc? [y] ", +"Would you like to auxillary scripts? These include the service pinger, unit tester, a test page for the rdf agent, an RDF generator page, etc? [y] ", -ynd => 'y' ); if ($answer eq 'y') { @@ -1442,7 +1443,19 @@ { '#!/usr/bin/perl -w' => "#!$perl_exec", } ); say -'Please don\'t forget to place the service pinger on a cron! TODO - explain how to do that!'; +'Please don\'t forget to place the service pinger on a cron!'; + + # copy the service unit tester script + file_from_template( + "$service_tester_path/service_unit_tester.pl", + File::ShareDir::dist_file( + 'MOBY', 'cgi/service_unit_tester.pl' + ), + 'MOBY-Central service unit tester script', + { '#!/usr/bin/perl -w' => "#!$perl_exec", } + ); + say +'Please don\'t forget to place the service unit tester on a cron!'; #copy the other scripts now file_from_template( From kawas at dev.open-bio.org Tue Nov 25 14:49:38 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:49:38 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251949.mAPJncdW015888@dev.open-bio.org> kawas Tue Nov 25 14:49:38 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv15853/Perl/MOBY-Server Modified Files: Changes Log Message: updated the changes to reflect addition of the service_unit_tester script and some bug fixes moby-live/Perl/MOBY-Server Changes,1.17,1.18 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/24 14:40:03 1.17 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/25 19:49:38 1.18 @@ -27,6 +27,8 @@ for the given entity. - RDF for service instances now includes unit test information if unit test information is available for the service instance. + - fixed how references were created in MOBY::RDF::Ontologies::* + - added a unit testing script for services to the shared/cgi dir. 1.05 From kawas at dev.open-bio.org Tue Nov 25 14:51:19 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:51:19 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251951.mAPJpJmF015928@dev.open-bio.org> kawas Tue Nov 25 14:51:19 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv15893/Perl/MOBY-Client Modified Files: Changes Log Message: moby-live/Perl/MOBY-Client Changes,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Changes,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/17 15:30:55 1.4 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/25 19:51:18 1.5 @@ -4,6 +4,9 @@ * changes to makefile reflecting the cpan addition of wsrf * added MOBY/Async.pm to the module * added MOBY/Client/MobyUnitTest for unit testing our services. + * RDF for service instances now includes unit test information if unit + test information is available for the service instance. + * fixed how references were created in MOBY::RDF::Ontologies::* 1.02 16 May 2008 * fixed bug in MOBY::Client::Central::DUMP that resulted From groscurt at dev.open-bio.org Wed Nov 26 03:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRmW017272@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg added to the repository moby-live/Java/src/main/de/mpg - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRfs017255@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de added to the repository moby-live/Java/src/main/de - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:51:37 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:37 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pb0G017378@dev.open-bio.org> groscurt Wed Nov 26 03:51:37 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv17347/src/main/de/mpg/mpiz_koeln/featureClient Added Files: FeatureClientResult.java FeatureClientException.java FeatureClient.java ServiceCallFactory.java Log Message: package for the featureClient moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient FeatureClientResult.java,NONE,1.1 FeatureClientException.java,NONE,1.1 FeatureClient.java,NONE,1.1 ServiceCallFactory.java,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 03:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRsA017291@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg/mpiz_koeln Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:51:28 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:28 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRBG017310@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg/mpiz_koeln/featureClient Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:52:05 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:52:05 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260852.mAQ8q5mp017420@dev.open-bio.org> groscurt Wed Nov 26 03:52:05 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test In directory dev.open-bio.org:/tmp/cvs-serv17386/src/main/de/mpg/mpiz_koeln/featureClient/test Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:52:20 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:52:20 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260852.mAQ8qKRs017480@dev.open-bio.org> groscurt Wed Nov 26 03:52:20 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test In directory dev.open-bio.org:/tmp/cvs-serv17449/src/main/de/mpg/mpiz_koeln/featureClient/test Added Files: FeatureClientFactory.java SimpleSingleCall.java SingleCallWithParameters.java MultiCallWithParameters.java MultiCallByDefinition.java ComplexSingleCall.java SingleCallDefinition.java SimpleMultiCall.java SingleMultiServiceCall.java Log Message: test classes for feature client moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test FeatureClientFactory.java,NONE,1.1 SimpleSingleCall.java,NONE,1.1 SingleCallWithParameters.java,NONE,1.1 MultiCallWithParameters.java,NONE,1.1 MultiCallByDefinition.java,NONE,1.1 ComplexSingleCall.java,NONE,1.1 SingleCallDefinition.java,NONE,1.1 SimpleMultiCall.java,NONE,1.1 SingleMultiServiceCall.java,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 03:56:44 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:56:44 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260856.mAQ8uiLj017675@dev.open-bio.org> groscurt Wed Nov 26 03:56:44 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv17640/docs Modified Files: index.html Added Files: FeatureClient.html Log Message: docs for the featureClient moby-live/Java/docs FeatureClient.html,NONE,1.1 index.html,1.36,1.37 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.36 retrieving revision 1.37 diff -u -r1.36 -r1.37 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/11/19 15:29:04 1.36 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/26 08:56:43 1.37 @@ -138,7 +138,9 @@ href="CmdLineClients.html">Command-line clients
    • How to use the BioMoby plugin in -Taverna

      +Taverna +

    • The Feature Client (an extended MOBY client)

    • Using generated object (MoSeS)
        From groscurt at dev.open-bio.org Wed Nov 26 06:06:51 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:06:51 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261106.mAQB6pOY018427@dev.open-bio.org> groscurt Wed Nov 26 06:06:50 EST 2008 Update of /home/repository/moby/moby-live/Java/src/support/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18393/src/support/featureClient Log Message: Directory /home/repository/moby/moby-live/Java/src/support/featureClient added to the repository moby-live/Java/src/support/featureClient - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 06:07:02 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB72Ep018487@dev.open-bio.org> groscurt Wed Nov 26 06:07:02 EST 2008 Update of /home/repository/moby/moby-live/Java/src/support/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18456/src/support/featureClient Added Files: README Log Message: README for the featureClient moby-live/Java/src/support/featureClient README,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 06:07:57 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:57 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB7vXv018551@dev.open-bio.org> groscurt Wed Nov 26 06:07:57 EST 2008 Update of /home/repository/moby/moby-live/Java In directory dev.open-bio.org:/tmp/cvs-serv18516 Modified Files: build.xml Log Message: ant files changed or added for the featureclient moby-live/Java build.xml,1.75,1.76 =================================================================== RCS file: /home/repository/moby/moby-live/Java/build.xml,v retrieving revision 1.75 retrieving revision 1.76 diff -u -r1.75 -r1.76 --- /home/repository/moby/moby-live/Java/build.xml 2008/10/25 14:28:18 1.75 +++ /home/repository/moby/moby-live/Java/build.xml 2008/11/26 11:07:57 1.76 @@ -14,6 +14,7 @@ + ]> @@ -123,7 +124,8 @@ - + + @@ -145,6 +147,7 @@ &dashboardBuild; &seahawkBuild; &mobysyncBuild; + &featureClientBuild; @@ -362,7 +365,7 @@ + From groscurt at dev.open-bio.org Wed Nov 26 06:07:57 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:57 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB7vFa018567@dev.open-bio.org> groscurt Wed Nov 26 06:07:57 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv18516/xmls Added Files: featureClientBuild.xml Log Message: ant files changed or added for the featureclient moby-live/Java/xmls featureClientBuild.xml,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 09:56:19 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 09:56:19 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261456.mAQEuJBe018903@dev.open-bio.org> groscurt Wed Nov 26 09:56:19 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18868/src/main/de/mpg/mpiz_koeln/featureClient Modified Files: FeatureClient.java Log Message: typo moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient FeatureClient.java,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java 2008/11/26 08:51:37 1.1 +++ /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java 2008/11/26 14:56:19 1.2 @@ -598,7 +598,7 @@ * @param user the user * @param password his/her password */ - public void setAuthentification(String user, String password) { + public void setAuthentication(String user, String password) { this.user = user; this.password = password; } From groscurt at dev.open-bio.org Fri Nov 28 07:05:03 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Fri, 28 Nov 2008 07:05:03 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811281205.mASC533i030271@dev.open-bio.org> groscurt Fri Nov 28 07:05:02 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv30216/docs Modified Files: index.html Log Message: updated to point to secure web service documentation moby-live/Java/docs index.html,1.37,1.38 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/11/26 08:56:43 1.37 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/28 12:05:02 1.38 @@ -102,7 +102,8 @@
      • How to change Ant's build.xml
      • RDF Agent -
      • The Dashboard as Webstart +
      • The Dashboard as Webstart
    @@ -139,7 +140,8 @@
  • How to use the BioMoby plugin in Taverna -
  • The Feature Client (an extended MOBY client)

  • Using generated object (MoSeS) @@ -173,7 +175,8 @@
  • MoSeS - Moby Services Support
  • Biomoby Dashboard -
  • An Alternative jMoby Step-by-Step Guide +
  • An Alternative jMoby Step-by-Step Guide
  • Code Examples

    @@ -189,6 +192,9 @@

  • The org.biomoby.shared.data package "In Anger": creating data instances
  • +
  • How to setup and create secure BioMoby web services
  • + From senger at dev.open-bio.org Sun Nov 30 05:33:17 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Sun, 30 Nov 2008 05:33:17 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811301033.mAUAXHEa020365@dev.open-bio.org> senger Sun Nov 30 05:33:17 EST 2008 Update of /home/repository/moby/jars-archive In directory dev.open-bio.org:/tmp/cvs-serv20346 Modified Files: README Log Message: remove not-anymore-needed jar files jars-archive README,1.3,1.4 =================================================================== RCS file: /home/repository/moby/jars-archive/README,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/jars-archive/README 2005/06/10 14:07:45 1.3 +++ /home/repository/moby/jars-archive/README 2008/11/30 10:33:17 1.4 @@ -1,45 +1,6 @@ -Purpose -------- - -This module serves just one purpose: to store commonly (or less -commonly) used third-party Java libraries (jar files) in order to -share them by several other CVS modules without the need to include -them separately in all those CVS modules. - -I guess that the purpose is similar to the CVS-native notion of the -module dependencies. Or similar what one can get from sites like -www.ibiblio.org. - -The idea is that various projects (mainly those dealing with and using -Java) can have in their build.xml a target "gather" (or whatever name) -that will use HTTP protocol to fetch the third-party libraries the -first time it builds everything. An example can be found in the -moby-live module (subdirectory Java). - -It started as a BioMoby initiative so it is located as a module within -the 'moby' CVS repository. But it can used by others, as well - one -does not use it as a CVS module, but like a normal HTTP resource. Only -when you want to add a new library, or to update an existing one, you -need to check-out it as usual. - - -Directory structure -------------------- - -current - It contains (usually) the latest version of the third-party -libraries. This is the most convenient place to fetch all the jars -files from because your build.xml can use just one property pointing -here. - However, if you need special (older or newer) version of a -third-party libraries for a particular project, create a new directory -(e.g. a directory jMoby for libraries that are specific for the -BioMoby in Java). - -licenses - Put here licenses for various third-party libraries that are -included in this module. Also, when adding new libraries make sure -that you are not breaking any licenses. +This directory of jar files was replaced by using Maven. Please update +to the latest jMoby and you will not need to use this module. Except +for other puposes, like getting jMoby's web applications (war files). ---------------------------------------------------------------------- Started by: Martin Senger (martin.senger at gmail.com), June 2005 From senger at dev.open-bio.org Sun Nov 30 05:33:07 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Sun, 30 Nov 2008 05:33:07 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811301033.mAUAX7cT020333@dev.open-bio.org> senger Sun Nov 30 05:33:06 EST 2008 Update of /home/repository/moby/jars-archive/current In directory dev.open-bio.org:/tmp/cvs-serv20246 Removed Files: FastInfoset.jar activation.jar adenine.jar alltools.jar alltools2.jar axis-ant.jar axis.jar castor-0.9.5.jar commons-codec-1.3.jar commons-collections-2.1.jar commons-dbcp-1.1.jar commons-discovery-0.2.jar commons-httpclient-3.0-rc2.jar commons-io-1.3.1.jar commons-lang-2.1.jar commons-logging-1.0.4.jar commons-pool-1.1.jar concurrent.jar dnsjava-1.3.2.jar fetaEngine.jar http.jar icis-pedigree.jar icu4j.jar jakarta-oro-2.0.5.jar jaxb-api.jar jaxb-impl.jar jaxb-xjc.jar jaxen-core.jar jaxen-jdom.jar jaxrpc.jar jaxws-api.jar jaxws-rt.jar jaxws-tools.jar jcalendar.jar jdom.jar jena.jar jfcunit.jar jodconverter-2.2.1.jar jsr173_api.jar jsr181-api.jar jsr250-api.jar juh-2.3.0.jar junit.jar jurt-2.3.0.jar log4j-1.2.12.jar lsid-client-1.1.2.jar lsid-server-1.1.2.jar mail.jar mailapi_1_3_1.jar mysql-connector-java-3.1.7-bin.jar rdf-api-2001-01-19.jar resolver.jar ridl-2.3.0.jar saaj-api.jar saaj-impl.jar saaj.jar saxpath.jar seahawk.jar servlet.jar sjsxp.jar slf4j-api-1.4.3.jar slf4j-jdk14-1.4.3.jar stax-ex.jar streambuffer.jar taverna.jar unoil-2.3.0.jar wsdl4j-1.5.1.jar xalan.jar xercesImpl.jar xercesSamples.jar xml-apis.jar xmlParserAPIs.jar Log Message: remove not-anymore-needed jar files jars-archive/current FastInfoset.jar,1.1,NONE activation.jar,1.3,NONE adenine.jar,1.1,NONE alltools.jar,1.1,NONE alltools2.jar,1.10,NONE axis-ant.jar,1.2,NONE axis.jar,1.2,NONE castor-0.9.5.jar,1.1,NONE commons-codec-1.3.jar,1.1,NONE commons-collections-2.1.jar,1.1,NONE commons-dbcp-1.1.jar,1.1,NONE commons-discovery-0.2.jar,1.1,NONE commons-httpclient-3.0-rc2.jar,1.1,NONE commons-io-1.3.1.jar,1.1,NONE commons-lang-2.1.jar,1.1,NONE commons-logging-1.0.4.jar,1.1,NONE commons-pool-1.1.jar,1.1,NONE concurrent.jar,1.1,NONE dnsjava-1.3.2.jar,1.1,NONE fetaEngine.jar,1.1,NONE http.jar,1.1,NONE icis-pedigree.jar,1.1,NONE icu4j.jar,1.1,NONE jakarta-oro-2.0.5.jar,1.1,NONE jaxb-api.jar,1.1,NONE jaxb-impl.jar,1.1,NONE jaxb-xjc.jar,1.1,NONE jaxen-core.jar,1.1,NONE jaxen-jdom.jar,1.1,NONE jaxrpc.jar,1.2,NONE jaxws-api.jar,1.1,NONE jaxws-rt.jar,1.1,NONE jaxws-tools.jar,1.1,NONE jcalendar.jar,1.1,NONE jdom.jar,1.2,NONE jena.jar,1.1,NONE jfcunit.jar,1.1,NONE jodconverter-2.2.1.jar,1.1,NONE j! sr173_api.jar,1.1,NONE jsr181-api.jar,1.1,NONE jsr250-api.jar,1.1,NONE juh-2.3.0.jar,1.1,NONE junit.jar,1.1,NONE jurt-2.3.0.jar,1.1,NONE log4j-1.2.12.jar,1.1,NONE lsid-client-1.1.2.jar,1.1,NONE lsid-server-1.1.2.jar,1.1,NONE mail.jar,1.1,NONE mailapi_1_3_1.jar,1.1,NONE mysql-connector-java-3.1.7-bin.jar,1.1,NONE rdf-api-2001-01-19.jar,1.1,NONE resolver.jar,1.1,NONE ridl-2.3.0.jar,1.1,NONE saaj-api.jar,1.1,NONE saaj-impl.jar,1.1,NONE saaj.jar,1.2,NONE saxpath.jar,1.1,NONE seahawk.jar,1.2,NONE servlet.jar,1.2,NONE sjsxp.jar,1.1,NONE slf4j-api-1.4.3.jar,1.1,NONE slf4j-jdk14-1.4.3.jar,1.1,NONE stax-ex.jar,1.1,NONE streambuffer.jar,1.1,NONE taverna.jar,1.1,NONE unoil-2.3.0.jar,1.1,NONE wsdl4j-1.5.1.jar,1.1,NONE xalan.jar,1.1,NONE xercesImpl.jar,1.2,NONE xercesSamples.jar,1.1,NONE xml-apis.jar,1.1,NONE xmlParserAPIs.jar,1.2,NONE rcsdiff: /home/repository/moby/jars-archive/current/RCS/FastInfoset.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/activation.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/adenine.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/alltools.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/alltools2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/axis-ant.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/axis.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/castor-0.9.5.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-codec-1.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-collections-2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-dbcp-1.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-discovery-0.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-httpclient-3.0-rc2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-io-1.3.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-lang-2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-logging-1.0.4.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-pool-1.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/concurrent.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/dnsjava-1.3.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/fetaEngine.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/http.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/icis-pedigree.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/icu4j.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jakarta-oro-2.0.5.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-impl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-xjc.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxen-core.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxen-jdom.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxrpc.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-rt.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-tools.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jcalendar.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jdom.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jena.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jfcunit.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jodconverter-2.2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr173_api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr181-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr250-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/juh-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/junit.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jurt-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/log4j-1.2.12.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/lsid-client-1.1.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/lsid-server-1.1.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mail.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mailapi_1_3_1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mysql-connector-java-3.1.7-bin.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/rdf-api-2001-01-19.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/resolver.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/ridl-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj-impl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saxpath.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/seahawk.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/servlet.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/sjsxp.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/slf4j-api-1.4.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/slf4j-jdk14-1.4.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/stax-ex.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/streambuffer.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/taverna.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/unoil-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/wsdl4j-1.5.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xalan.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xercesImpl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xercesSamples.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xml-apis.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xmlParserAPIs.jar,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 03:53:43 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:53:43 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260853.mAQ8rhFs017531@dev.open-bio.org> groscurt Wed Nov 26 03:53:43 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client In directory dev.open-bio.org:/tmp/cvs-serv17488/src/main/org/biomoby/client Modified Files: MobyRequest.java CentralImpl.java BaseClient.java Log Message: changes done enabling the authentication for services moby-live/Java/src/main/org/biomoby/client MobyRequest.java,1.40,1.41 CentralImpl.java,1.57,1.58 BaseClient.java,1.12,1.13 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java,v retrieving revision 1.40 retrieving revision 1.41 diff -u -r1.40 -r1.41 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/14 20:32:02 1.40 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/26 08:53:43 1.41 @@ -1,1019 +1,1028 @@ -package org.biomoby.client; - -import java.io.*; -import java.util.*; - -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.rpc.Service; -import javax.xml.transform.TransformerException; - -import org.apache.axis.client.Call; -import org.apache.axis.message.MessageElement; -import org.apache.xml.utils.PrefixResolver; -import org.apache.xml.utils.PrefixResolverDefault; -import org.apache.xpath.XPath; -import org.apache.xpath.XPathContext; -import org.apache.xpath.objects.XNodeSet; -import org.apache.xpath.objects.XObject; - -import org.biomoby.shared.*; -import org.biomoby.shared.data.*; -import org.biomoby.shared.parser.MobyTags; // defined the Moby XML element names -import org.biomoby.w3c.addressing.EndpointReference; -import org.omg.lsae.notifications.AnalysisEvent; - -import org.w3c.dom.*; - -/** - * This class handles the WSDL transaction to request a response - * from a remote SOAP Web service that handles the - * MOBY format. It depends on - * having already retrieved the definition of the Web service via - * the MOBY central registry using the - * jMOBY API, - * and for now it uses the - * Apache - * Axis Web services framework, as well as Apache Xalan. There are code comments for the - * few lines that rely on Axis classes rather than the JAX-RPC interfaces. - * - * @author Paul Gordon gordonp at ucalgary.ca - */ -public class MobyRequest{ - - protected MobyService mobyService = null; - protected MobyContentInstance inputData = null; - protected MobyContentInstance outputData = null; - protected Central mobyCentral = null; - protected PrefixResolver mobyPrefixResolver = null; - - protected Hashtable wsdlCache = null; - protected String lastWsdlCacheKey = null; - protected DocumentBuilder docBuilder = null; - protected Service service = null; - - protected Class stringType; - protected static boolean debug = false; - protected PrintStream debugPS = System.err; - protected XPathContext xpath_context; - protected String responseString = null; - - private XPath stringEncodedXPath; - private XPath base64EncodedXPath; - private XPath simpleChildXPath; - private XPath collectionChildXPath; - - private int autoID = 0; - - // Used as invocation callback if MobyRequest is acting as a server, - // or is executing services as a client asynchronously - private Vector eventHandlers; - - /** - * Default constructor. You should have a Central instance around since you're going to - * be retrieving MobyServices to pass into here. Lets reuse it. - * - * @param central An instance of a Moby central object so we can make requests about object types, etc. - * @throws ParserConfigurationException if JAXP doesn't have any valid DOM-building XML parsers set up for use - */ - public MobyRequest(Central central) throws ParserConfigurationException{ - mobyCentral = central; - wsdlCache = new Hashtable(); - - eventHandlers = new Vector(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - - try{ - stringType = Class.forName("java.lang.String"); - }catch(ClassNotFoundException classe){ - debugPS.println("WARNING: Something is very wrong, could not find Class definition of String: " + classe); - } - - xpath_context = new XPathContext(); - mobyPrefixResolver = new MobyPrefixResolver(); - - // Now compile the XPath statements that will be used fetch data from the server response - try{ - base64EncodedXPath = new XPath("//*[starts-with(substring-after(@"+ - MobyPrefixResolver.XSI1999_PREFIX+ - ":type, ':'), \"base64\") or starts-with(substring-after(@"+ - MobyPrefixResolver.XSI2001_PREFIX+ - ":type, ':'), \"base64\")]", null, - mobyPrefixResolver, XPath.SELECT); - stringEncodedXPath = new XPath("//*[substring-after(@"+ - MobyPrefixResolver.XSI1999_PREFIX+ - ":type, ':')=\"string\" or substring-after(@"+ - MobyPrefixResolver.XSI2001_PREFIX+ - ":type, ':')=\"string\"] | //"+ - MobyPrefixResolver.SOAP_ENC_PREFIX+":string", null, - mobyPrefixResolver, XPath.SELECT); - simpleChildXPath = new XPath("moby:Simple | Simple", null, - mobyPrefixResolver, XPath.SELECT); - collectionChildXPath = new XPath("moby:Collection | Collection", null, - mobyPrefixResolver, XPath.SELECT); - } - catch(TransformerException te){ - debugPS.println("Syntax error encountered while compiling XPath " + - "statements for internal use (code bug?): " + te); - } - setDebugMode(System.getProperty("moby.debug") != null); - } - - /** - * @param mode if true, debugging information is printed to the stream returned by getDebugOutputStream - */ - public void setDebugMode(boolean mode){ - debug = mode; - } - - /** - * Standard error is used unless this method is called. - * - * @param ps the OutputStream to which debugging information is sent. - * @throws IllegalArgumentException if the stream is null - */ - public void setDebugPrintStream(PrintStream ps) throws IllegalArgumentException{ - if(ps == null){ - throw new IllegalArgumentException("The OutputStream specified to MobyRequest was null"); - } - debugPS = ps; - } - - /** - * @return the instance of the class implementing Central that we are using - */ - public Central getCentralImpl(){ - return mobyCentral; - } - - /** - * @param mobyservice the MobyService that should be executed when invokeService is called - */ - public void setService(MobyService mobyservice){ - if(mobyservice == null){ - mobyService = null; - } - else if(mobyService == null || !mobyservice.equals(mobyService)){ - mobyService = mobyservice; - } - } - - /** - * @return the MobyService that will be executed when invokeService is called - */ - public MobyService getService(){ - return mobyService; - } - - /** - * @return the Raw MOBY XML response as a string - */ - public String getResponseXML(){ - return responseString; - } - - /** - * Sets the input data for the MOBY service request. The length of the input array, and the - * number of input parameters required by the service must be equal when invokeService() is called. - * This method strictly enforces that the input be of the appropriate type for the service. - * - * Note that there is no requirement to use MobyDataInstance.setXmlMode() before passing in - * data, this class will temporarily set the XML mode of the data when it is required. - * - * @throws IllegalArgumentException if the input does not fit the criteria of the service (e.g. wrong data type) - */ - public void setInput(MobyContentInstance data) throws MobyException{ - inputData = data; - } - - /** - * Takes the data in the array, with their current articleNames, as input for the service - */ - public void setInput(MobyDataInstance[] data) throws MobyException{ - MobyDataJob job = new MobyDataJob(); - for(MobyDataInstance param: data){ - job.put(param.getName(), param); - } - inputData = new MobyContentInstance(); - inputData.put(job); - } - - /** - * Convenience method to run services that take one argument. If the service - * requires the input to have a name, it will be automatically assigned. - */ - public void setInput(MobyDataInstance datum) throws MobyException{ - setInput(datum, ""); - } - - /** - * Convenience method to run services that take one named argument. - */ - public void setInput(MobyDataInstance datum, String paramName) throws MobyException{ - inputData = new MobyContentInstance(datum, paramName); - } - - /** - * @return the MobyService that will be executed when invokeService is called - */ - public MobyContentInstance getInput(){ - return inputData; - } - - /** - * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) - */ - public void setSecondaryInput(Collection secondaryData) throws MobyException{ - setSecondaryInput(secondaryData.toArray(new MobyDataSecondaryInstance[secondaryData.size()])); - } - - /** - * This method will assign the provided secondary parameters to all primary input data currently - * in this object. This is covenient if you are running 100 seqs through BLAST and only want to set - * the parameters once. If you instead want to set secondary input differently for all primary inputs, you'll - * need to create a custom MobyContentInstance as input to setInput(). - * - * @throws MobyException if a parameter name is blank, or overrides a primary parameter - */ - public void setSecondaryInput(MobyDataSecondaryInstance[] secondaryData) throws MobyException{ - - Iterator queryNames = inputData.keySet().iterator(); - // For each query - while(queryNames.hasNext()){ - MobyDataJob queryParams = inputData.get(queryNames.next()); - // Set all the secondary params (overwrites any old ones) - for(int i = 0; i < secondaryData.length; i++){ - String secName = secondaryData[i].getName(); - if(secName == null || secName.length() == 0){ - throw new MobyException("A secondary parameter cannot have a blank name (array index " + i + ")"); - } - if(queryParams.containsKey(secName) && queryParams.get(secName) instanceof MobyPrimaryData){ - throw new MobyException("A secondary parameter cannot override an existing primary parameter " + - "with the same name (" + secName + ")"); - } - queryParams.put(secName, secondaryData[i]); - } - } - } - - /** - * @return a vector of MobyDataInstance[], each element of the vector is the collection of response objects for the correspondingly indexed input request. - * - * @throws MobyException if you try to get the results before calling InvokeService - */ - public MobyContentInstance getOutput() throws MobyException{ - if(outputData == null){ - throw new MobyException("Trying to access MOBY service results " + - "before the service is invoked"); - } - else{ - return outputData; - } - } - - /** - * The main method of the class. If all of the MOBY input objects - * are properly defined according to the Web service definition, - * a SOAP request will be sent to the remote server, and the method - * will return one or more MOBY objects (synchronous). - * Call this method after calling setService, and setInput. If you do not call - * setSecondaryInput, the default secondary parameter values will be used. - * - * @return the results of the remote Web service in response to the give input - * - * @throws MobyException i.e. there was something wrong with the input, output or remote service's logic - * @throws SOAPException i.e. there was a problem with the underlying transaction/transport layer - */ - public MobyContentInstance invokeService() throws Exception, MobyException, SOAPException, NoSuccessException{ - return mobyService.isAsynchronous() ? invokeService(inputData, new StringBuffer()) : invokeService(inputData, (StringBuffer) null); - } - - // Used internally for asynchronous thread calls that all need the XML data - // and can't rely on the answer from thread-insensitive getResponseXML() - private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML) - throws Exception, MobyException, SOAPException, NoSuccessException{ - return invokeService(inData, contentsXML, null, 0); - } - - private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML, MobyRequestEventHandler handler, int requestId) - throws Exception, MobyException, SOAPException, NoSuccessException{ - - if(mobyService == null){ - throw new MobyException("Tried to invoke null service from MobyRequest (call setService first)"); - } - - Element mobyDOM = null; - if(mobyService.isAsynchronous()){ - // Async is "simpler", because it had to merge DOMs together into a single MobyContentInstance anyway - MobyContentInstance mci = performAsyncSOAPRequest(mobyService, inData, handler, requestId); - StringWriter writer = new StringWriter(); - MobyDataUtils.toXMLDocument(writer, mci); - contentsXML.append(writer.toString()); - return mci; - } - else{ - String mobyXML = convertMOBYDataToMOBYRequest(inData); - Call call = getServiceFromWSDL(); - mobyDOM = performSOAPRequest(call, mobyXML, contentsXML); - // The following parses the DOM and extracts all the appropriate jMOBY objects to represent the XML in Java - return MobyDataUtils.fromXMLDocument(mobyDOM, mobyService.getServiceType().getRegistry()); - } - } - - protected MobyContentInstance performAsyncSOAPRequest(MobyService mservice, MobyContentInstance inData, - MobyRequestEventHandler handler, int requestId) - throws Exception{ - String mobyXML = convertMOBYDataToMOBYRequest(inData); - EndpointReference epr = AsyncClient.sendRequest(mservice, mobyXML); - - // Essentially cloning, so removing ids doesn't change the - // MobyContentInstance "data" (which we will use again later on) - MobyContentInstance finalContents = new MobyContentInstance(); - Set queryIDs = new HashSet(inData.keySet()); - try { - // Should add some timeout here... - while(!queryIDs.isEmpty()){ - // todo: make this setable - Thread.sleep(5000); - - AnalysisEvent[] events = - AsyncClient.poll(epr, queryIDs); - - Vector newDataAvailable = new Vector(); - for(AnalysisEvent event: events){ - if(event != null && event.isCompleted()){ - queryIDs.remove(event.getQueryId()); - newDataAvailable.add(event.getQueryId()); - } - } - - if(newDataAvailable.size() > 0){ - // Parse and merge the new data into the existing contents - InputStream resultStream = AsyncClient.getResultStream(epr, newDataAvailable); - Element mobyDOM = asyncSoapTextToMobyDOM(resultStream); - MobyContentInstance newResults = MobyDataUtils.fromXMLDocument(mobyDOM, mservice.getServiceType().getRegistry()); - // The merge - for(String jobid: newResults.keySet()){ - finalContents.put(jobid, newResults.get(jobid)); - } - - // Inform the handler that some data has been added to the response (for incremental display?) - if(handler != null){ - MobyRequestEvent mre = new MobyRequestEvent(finalContents, this, mservice, null, requestId); - StringWriter xmlWriter = new StringWriter(); - MobyDataUtils.toXMLDocument(xmlWriter, finalContents); - - mre.setContentsXML(xmlWriter.toString()); - if(!queryIDs.isEmpty()){ - // Send an update event only if we aren't finished yet. - // If we are finished, the client is going to get this event as the - // invocation thread finishes up (no need to double up). - handler.processEvent(mre); - } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - AsyncClient.destroy(epr); - throw new Exception("Exception occured while polling the service invocation: " + e); - } - - return finalContents; - } - - private Element asyncSoapTextToMobyDOM(InputStream inStream) throws Exception{ - Element soapDOM = null; - synchronized(docBuilder){ - soapDOM = docBuilder.parse(inStream).getDocumentElement(); - } - final boolean IS_ASYNC_SERVICE_CALL = true; - return decodeSOAPMessage(soapDOM, null, null, IS_ASYNC_SERVICE_CALL); - } - - /** - * Asynchronous call to invokeService. A callback to the passed-in handler will be made when - * the response is ready, or there is an exception. - * - * @return the id that the callback event will return from getID(), allowing a client to distinguish between multiple concurrent invocation callbacks - */ - public synchronized int invokeService(MobyRequestEventHandler handler){ - int id = autoID++; - - Thread t = new InvocationThread(this, inputData, handler, id); // see internal class definition below - t.start(); - - return id; - } - - // This is the class that asynchronously calls the service and does a callback to - // the handler specified in the invocation. - class InvocationThread extends Thread { - MobyContentInstance data; - MobyService mservice; - MobyRequest mobyRequest; - MobyRequestEventHandler handler; - int requestId; - - InvocationThread(MobyRequest mr, MobyContentInstance inData, MobyRequestEventHandler h, int id){ - data = inData; - mobyRequest = mr; - mservice = mobyRequest.getService(); - handler = h; - requestId = id; - - // Name the thread after the service being run, mostly for ease of debugging - setName(mservice.getName()+requestId); - } - - public void run() { - MobyRequestEvent requestEvent = new MobyRequestEvent(data, mobyRequest, mservice, null, requestId); - // Tell the handler we're starting the request, with the given data - handler.start(requestEvent); - - MobyRequestEvent responseEvent = null; - MobyContentInstance content = null; - StringBuffer contentsXML = new StringBuffer(); //to be filled in by the RPC call below - try{ - content = mobyRequest.invokeService(data, contentsXML, handler, requestId); //RPC call... - } - catch(Exception e){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, e, requestId); - } - catch(Error err){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, err, requestId); - } - if(responseEvent == null){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, null, requestId); - } - // We've got the raw XML laying around, so why not provide it unmolested to the callback? - responseEvent.setContentsXML(contentsXML.toString()); - handler.processEvent(responseEvent); - handler.stop(mobyRequest, requestId); - } - } - - public void addEventHandler(MobyRequestEventHandler h){ - eventHandlers.add(h); - } - - public void removeEventHandler(MobyRequestEventHandler h){ - eventHandlers.remove(h); - } - - public void sendResponse(MobyRequestEvent mre){ - // Not yet implemented, need to conform to some web.xml specification here... - } - - /** - * This method retrieves from Moby Central a copy of the WSDL document for the service - * (or uses an internally cached copy from a previous invocation), and sets the variables for the - * SOAP call appropriately so you can consequently call performSOAPRequest. - */ - protected Call getServiceFromWSDL() throws MobyException, NoSuccessException{ -// String wsdl = null; - -// // Since this is how we retrieve a service from Central, use the same values as the key to the hash -// String wsdlCacheKey = mobyService.getName() + "@" + mobyService.getAuthority(); - -// // This is the same call as last time, so we don't need to change the setup -// if(wsdlCacheKey.equals(lastWsdlCacheKey)){ -// return setCallFromWSDL((String) wsdlCache.get(wsdlCacheKey)); -// } -// // We haven't encountered this service yet -// else if(!wsdlCache.containsKey(wsdlCacheKey)){ -// wsdl = mobyCentral.getServiceWSDL(mobyService.getName(), mobyService.getAuthority()); -// wsdlCache.put(wsdlCacheKey, wsdl); -// } -// // We've dealt with this one before -// else{ -// wsdl = (String) wsdlCache.get(wsdlCacheKey); -// } - -// lastWsdlCacheKey = wsdlCacheKey; // Keep track of the last invocation - - // Get ready to do SOAP - return setCallFromWSDL(null); - } - - /** - * Creates the SOAP Call that will be invoked later. This should be based on the WSDL document - * and parameter information from the MobyService, but these are currently not up to snuff. - */ - protected Call setCallFromWSDL(String wsdl) throws MobyException, SOAPException{ - if(service == null){ - service = new org.apache.axis.client.Service(); // AXIS SPECIFIC This acts as a factory for Calls - } - - Call soapCall; - try{ - soapCall = (Call) service.createCall();//create a fresh Call each time - }catch(javax.xml.rpc.ServiceException se){ - throw new SOAPException("Could not instatiate call to SOAP Service: " + se); - } - - // Should initialize endpoint, etc. This call is AXIS SPECIFIC, otherwise you'll - // have to do the call's info setting manually. - //((org.apache.axis.client.Call) soapCall).setSOAPService(soapService); - soapCall.removeAllParameters(); - soapCall.setTargetEndpointAddress(mobyService.getURL()); - soapCall.setPortName(new QName("http://biomoby.org/", - mobyService.getName() + "PortType")); - //soapCall.setOperationName(new QName("http://biomoby.org/", - // mobyService.getName())); - soapCall.setSOAPActionURI("http://biomoby.org/#" + mobyService.getName()); - return soapCall; - } - - /** - * Calls the invoke() method of the JAX-RPC Call interface. - */ - protected Element performSOAPRequest(Call soapCall, String mobyInputXML, StringBuffer contentsXMLOutput) throws SOAPException{ - // First, turn the input objects into a MOBY XML request - String[] mobyXMLInputData = new String[1]; - - //Setup - mobyXMLInputData[0] = mobyInputXML; - - if(debug) - debugPS.println("returnType just before invoke call is " + soapCall.getReturnType()); - Object returnedObject = null; - try{ - returnedObject = soapCall.invoke(new QName("http://biomoby.org/", - mobyService.getName()), mobyXMLInputData); - } - catch(Exception e){ - e.printStackTrace(); - //System.err.println("Input: "+mobyInputXML); - throw new SOAPException("While invoking SOAP Call: " + e); - } - - try{ - if(debug){ - debugPS.println("SOAP Response was:\n"); - debugPS.println(soapCall.getResponseMessage().getSOAPPart().getEnvelope()); - } - Element resultDom = ((MessageElement) soapCall.getResponseMessage().getSOAPPart().getEnvelope()).getAsDOM(); - return decodeSOAPMessage(resultDom, contentsXMLOutput, mobyInputXML); - } catch(Exception e){ - e.printStackTrace(); - throw new SOAPException("Could not get SOAP response as DOM Element: "+ e); - } - - } - - public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML) - throws SOAPException, MobyException{ - return decodeSOAPMessage(n, contentsXMLOutput, inputXML, false); - } - - /** - * Isolates the MOBY Data from the SOAP message returned by the remote service host. - * - * @throws SOAPException if the MOBY payload cannot be found in the SOAP message - * @throws MobyException if the MOBY message is not well-formed XML - * - * @return The root element of the MOBY response DOM - */ - public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML, boolean async) - throws SOAPException, MobyException{ - if(n == null){ - throw new SOAPException("SOAP Message given to decode is null"); - } - - NodeList node_list = null; - XPath responseElementXPath = null; - try{ - if(async){ - responseElementXPath = new XPath("//"+MobyPrefixResolver.WSRP_PREFIX + - ":"+AsyncClient.WSRP_MULTI_PROPERTY_TAG_NAME+"Response", - null, mobyPrefixResolver, XPath.SELECT); - } - else{ - responseElementXPath = new XPath("//"+ MobyPrefixResolver.MOBY_TRANSPORT_PREFIX+ - ":"+mobyService.getName()+"Response | //" + - mobyService.getName()+"Response | " + - "//"+ MobyPrefixResolver.MOBY_TRANSPORT_PREFIX+ - ":"+mobyService.getName() + " | //" + - mobyService.getName(), - null, mobyPrefixResolver, XPath.SELECT); - } - }catch(TransformerException te){ - throw new SOAPException("Cannot select SOAP nodes due to exception "+ - "while compiling XPath statement (code bug?):" +te); - } - try{ - node_list = runXPath(responseElementXPath, n); - }catch(TransformerException te){ - throw new SOAPException("Cannot select SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - - if(node_list == null || node_list.getLength() == 0){ - throw new SOAPException("Could not find a response element in SOAP payload (service " + - mobyService.getName() + ")"); - } - - if(node_list.getLength() > 1){ - throw new SOAPException("Found more than one response element in SOAP payload, " + - "unable to resolve ambiguity of the payload (service provider error?)"); - } - - Node[] responseNodes = null; - if(async){ - Vector nodes = new Vector(); - NodeList resultNodeList = node_list.item(0).getChildNodes(); - for(int i = 0; resultNodeList != null && i < resultNodeList.getLength(); i++){ - if(!(resultNodeList.item(i) instanceof Element)){ - continue; - } - Element resultElement = (Element) resultNodeList.item(i); - if(resultElement.getLocalName().startsWith(AsyncClient.MOBY_RESULT_PROPERTY_PREFIX)){ - nodes.add(resultElement); - } - } - responseNodes = nodes.toArray(new Node[nodes.size()]); - } - else{ - responseNodes = new Node[]{node_list.item(0)}; - } - - Element domRoot = null; // Where the result will be put - - for(Node responseNode: responseNodes){ - // Find base64 encoded elements in the SOAP message using XPath and - // replace them with the real decoded contents - node_list = null; - try{ - node_list = runXPath(base64EncodedXPath, responseNode); - } - catch(TransformerException te){ - throw new SOAPException("Cannot select base64 encoded SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - if(debug && node_list != null){ - debugPS.println("There were " + node_list.getLength() + - " base64 encoded elements in the data"); - } - - // Do decoding for each base64 part found - for(int i = 0; node_list != null && i < node_list.getLength(); i++){ - org.w3c.dom.Node change = node_list.item(i); - /* Make sure the text data is all put into one contiguous piece for decoding*/ - change.normalize(); - - byte[] decodedBytes = org.apache.axis.encoding.Base64.decode(change.getFirstChild().getNodeValue()); - String newText = new String(decodedBytes); - if(debug){ - debugPS.println("New decoded text is" + newText); - } - - // Swap out this node for the decoded data - change.getParentNode().replaceChild(n.getOwnerDocument().createTextNode(new String(decodedBytes)), - change); - } - - // Now see if there are any strings that need decoding - node_list = null; - try{ - node_list = runXPath(stringEncodedXPath, responseNode); - } - catch(TransformerException te){ - throw new SOAPException("Cannot select string encoded SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - - // Do concatenation for each plain string part found - for(int i = 0; node_list != null && i < node_list.getLength(); i++){ - org.w3c.dom.Node change = node_list.item(i); - /* Make sure the text data is all put into one contiguous piece for decoding*/ - change.normalize(); - String plainString = ""; - int j = 0; - for(NodeList children = change.getChildNodes(); - children != null && j < children.getLength(); - j++){ - Node child = children.item(j); - if(child instanceof CDATASection || child instanceof Text){ - plainString += child.getNodeValue(); - if(debug){ - debugPS.println("Plain string is now " + plainString); - } - } - } - - // Swap out this node for the decoded data - change.getParentNode().replaceChild(n.getOwnerDocument().createCDATASection(plainString), change); - } - if(debug && node_list != null){ - debugPS.println("There were " + node_list.getLength() + - " XML Schema string encoded elements in the data"); - } - - // Parse the MOBY XML document payload - responseNode.normalize(); - NodeList children = responseNode.getChildNodes(); - if(children == null){ - throw new MobyException("The MOBY payload has no contents at all"); - } - if(children.getLength() != 1){ - if(debug){ - debugPS.println("Warning: MOBY Payload appears to have more than " + - "just text in it, skipping the non-text sections"); - } - } - - Element predefinedDOM = null; // Choice of ripping DOM Element for moby payload out of SOAP DOM - String localResponseString = ""; // or storing raw XML strings, to be converted to a DOM later - for(int j = 0; j < children.getLength(); j++){ - Node child = children.item(j); - if(child instanceof CDATASection || child instanceof Text){ - // Unescape XML special characters in the string, so we can later on - // parse the payload as regular XML. - // Ignore whitespace-only node - if(child.getNodeValue().matches("^\\s+$")){ - continue; - } - if(debug){ - debugPS.println("Concatenating text in response " + child.getNodeValue()); - } - localResponseString += child.getNodeValue();//.replaceAll("<", "<").replaceAll(">", ">").replaceAll("(&|F)", "&"); - } - if(child instanceof Element && child.getLocalName().equals(MobyTags.MOBY)){ - debugPS.println("Warning: The MOBY contents was found as raw XML inside the SOAP response!\n" + - "This is illegal according to the MOBY-API, please inform the service\n " + - " provider, as parsing such text may not be supported in the future"); - localResponseString = null; - // Store the moby payload root element's DOM represntation, so we don't - // have to serialize it to the localResponseString and then parse it out - // again (that would be wasteful). - predefinedDOM = (Element) child; - break; - } - } - - if(localResponseString != null){ - if(localResponseString.length() == 0){ - throw new MobyException("The MOBY payload has no text contents at all"); - } - if(Character.isWhitespace(localResponseString.charAt(0))){ - localResponseString = localResponseString.trim(); - } - } - - // Check if the payload is an XML document. If not, try a last ditch effort - // by base64 decoding the contents. This is technically not allowable in the - // MOBY spec, but we are being lenient. - if(localResponseString != null && !localResponseString.startsWith("\n"+localResponseString; - debugPS.println("Warning: The MOBY contents was missing an XML declaration, but it is " + - "required by the MOBY API, and may stop working in the future without it. Please " + - "contact the client's provider to correct this."); - } - else{ - String oldResponse = localResponseString; - localResponseString = new String(org.apache.axis.encoding.Base64.decode(localResponseString)); - if(!localResponseString.startsWith(" entry: data.entrySet()){ - String queryName = entry.getKey(); - MobyDataJob query = entry.getValue(); - - // Additionally, we check if they are MobyDataInstances below - Map primaryParams = new HashMap(); - Map secondaryParams = new HashMap(); - - // To store the primary input parameter name as given by the user, - // in case we need it later on for parameter renaming... - String primaryParamName = null; - - for(Map.Entry subentry: query.entrySet()){ - String name = subentry.getKey(); - MobyDataInstance param = subentry.getValue(); - if(param == null){ - throw new MobyException("Query " + queryName + - " contained a null input parameter (" + name + ")"); - } - else if(param instanceof MobyPrimaryData){ - primaryParams.put(name, (MobyPrimaryData) param); - primaryParamName = name; - } - else if(param instanceof MobySecondaryData){ - secondaryParams.put(name, (MobySecondaryData) param); - } - else{ - System.err.println("Input parameter " + name + " (query " + queryName + - ") was not a MobyPrimaryData or MobySecondaryData " + - "as expected, but rather was of class " + param.getClass().getName()); - } - } - - if(inputs != null && inputs.length != primaryParams.size()){ - throw new MobyException("Service " + mobyService.getName() + " was provided " + - primaryParams.size() + - " primary input parameter(s), but takes " + inputs.length + - " (query " + queryName + ")"); - } - if(secondaries != null){ - // If no secondaries provided, fill them in by default - if(secondaries.length != 0){ - for(MobySecondaryData secondary: secondaries){ - if(!secondaryParams.containsKey(secondary.getName())){ - if(debug){ - System.err.println("Setting default secondary param value for missing param " + secondary); - } - query.put(secondary.getName(), new MobyDataSecondaryInstance(secondary)); - } - } - } - if(secondaries.length != secondaryParams.size()){ - throw new MobyException("Service " + mobyService.getName() + " was provided " + - secondaryParams.size() + - " secondary input parameter(s), but takes " + secondaries.length + - " (query " + queryName + "). Extra secondary" + - " parameters must have been specified"); - } - } - - // If there was one anonymous input, assign the name automatically in - // the case the service requires it to be named. This is the only - // unambiguous case in which we can do this. - if(inputs.length == 1){ - String serviceParamName = inputs[0].getName(); // name as req'd by the service - - // name isn't the same as required currently - if(serviceParamName != null && serviceParamName.length() > 0 && - !serviceParamName.equals(primaryParamName)){ - // take out the old parameter - MobyPrimaryData theInputToRename = (MobyPrimaryData) query.remove(primaryParamName); - - // Add in the same parameter, but with the appropriate name - query.put(serviceParamName, (MobyDataInstance) theInputToRename); - } - } - } - - ByteArrayOutputStream mobyRequest = new ByteArrayOutputStream(); - try{ - MobyDataUtils.toXMLDocument(mobyRequest, data); - } - catch(MobyException me){ - throw me; - } - catch(Exception e){ - e.printStackTrace(); - throw new MobyException("Could not create MOBY payload XML from input data: " +e); - } - - if(debug){ - debugPS.println("Input to MOBY Service is:"); - debugPS.print(mobyRequest.toString()); - } - - return mobyRequest.toString(); - } - - /** - * A method that sets up the execution environment for and runs a compiled XPath statement against a DOM node - * You should call releaseXPath when you're done with the results - * @return the list of Nodes that satisfy the XPath in this Node's context - */ - protected NodeList runXPath(XPath xpath, Node n) throws TransformerException{ - NodeList result = null; - int dtm_node_handle = xpath_context.getDTMHandleFromNode(n); - PrefixResolver node_prefix_resolver = new PrefixResolverDefault(n); - XObject xobject = xpath.execute(xpath_context, n, node_prefix_resolver); - if(xobject instanceof XNodeSet){ - result = ((XNodeSet) xobject).nodelist(); - } - else if(debug && xobject != null){ - debugPS.println("Output of XPath was not a XNodeSet as expected, found " + xobject.getClass().getName()); - debugPS.flush(); - } - return result; - } - - protected void releaseXPath(Node n){ - xpath_context.release(xpath_context.getDTM(xpath_context.getDTMHandleFromNode(n)), false); - } -} + +package org.biomoby.client; + +import java.io.*; +import java.util.*; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.rpc.Service; +import javax.xml.transform.TransformerException; + +import org.apache.axis.client.Call; +import org.apache.axis.message.MessageElement; +import org.apache.xml.utils.PrefixResolver; +import org.apache.xml.utils.PrefixResolverDefault; +import org.apache.xpath.XPath; +import org.apache.xpath.XPathContext; +import org.apache.xpath.objects.XNodeSet; +import org.apache.xpath.objects.XObject; + +import org.biomoby.shared.*; +import org.biomoby.shared.data.*; +import org.biomoby.shared.parser.MobyTags; // defined the Moby XML element names +import org.biomoby.w3c.addressing.EndpointReference; +import org.omg.lsae.notifications.AnalysisEvent; + +import org.w3c.dom.*; + +/** + * This class handles the WSDL transaction to request a response from a remote SOAP Web service that handles the MOBY format. It depends on having already retrieved the definition of the Web + * service via the MOBY central registry using the jMOBY + * API, and for now it uses the Apache Axis Web services framework, + * as well as Apache Xalan. There are code comments for the few lines that rely on Axis classes rather than the JAX-RPC + * interfaces. + * + * @author Paul Gordon gordonp at ucalgary.ca + */ +public class MobyRequest { + + protected MobyService mobyService = null; + protected MobyContentInstance inputData = null; + protected MobyContentInstance outputData = null; + protected Central mobyCentral = null; + protected PrefixResolver mobyPrefixResolver = null; + + protected Hashtable wsdlCache = null; + protected String lastWsdlCacheKey = null; + protected DocumentBuilder docBuilder = null; + protected Service service = null; + + protected Class stringType; + protected static boolean debug = false; + protected PrintStream debugPS = System.err; + protected XPathContext xpath_context; + protected String responseString = null; + + private XPath stringEncodedXPath; + private XPath base64EncodedXPath; + private XPath simpleChildXPath; + private XPath collectionChildXPath; + + private int autoID = 0; + + // Used as invocation callback if MobyRequest is acting as a server, + // or is executing services as a client asynchronously + private Vector< MobyRequestEventHandler > eventHandlers; + + private String user; + private String password; + + /** + * Default constructor. You should have a Central instance around since you're going to be retrieving MobyServices + * to pass into here. Lets reuse it. + * + * @param central An instance of a Moby central object so we can make requests about object types, etc. + * @throws ParserConfigurationException if JAXP doesn't have any valid DOM-building XML parsers set up for use + */ + public MobyRequest( Central central ) throws ParserConfigurationException { + mobyCentral = central; + wsdlCache = new Hashtable(); + + eventHandlers = new Vector< MobyRequestEventHandler >(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware( true ); + docBuilder = dbf.newDocumentBuilder(); + + try { + stringType = Class.forName( "java.lang.String" ); + } + catch ( ClassNotFoundException classe ) { + debugPS.println( "WARNING: Something is very wrong, could not find Class definition of String: " + classe ); + } + + xpath_context = new XPathContext(); + mobyPrefixResolver = new MobyPrefixResolver(); + + // Now compile the XPath statements that will be used fetch data from the server response + try { + base64EncodedXPath = new XPath( "//*[starts-with(substring-after(@" + MobyPrefixResolver.XSI1999_PREFIX + + ":type, ':'), \"base64\") or starts-with(substring-after(@" + MobyPrefixResolver.XSI2001_PREFIX + + ":type, ':'), \"base64\")]", null, mobyPrefixResolver, XPath.SELECT ); + stringEncodedXPath = new XPath( "//*[substring-after(@" + MobyPrefixResolver.XSI1999_PREFIX + + ":type, ':')=\"string\" or substring-after(@" + MobyPrefixResolver.XSI2001_PREFIX + + ":type, ':')=\"string\"] | //" + MobyPrefixResolver.SOAP_ENC_PREFIX + ":string", null, + mobyPrefixResolver, XPath.SELECT ); + simpleChildXPath = new XPath( "moby:Simple | Simple", null, mobyPrefixResolver, XPath.SELECT ); + collectionChildXPath = new XPath( "moby:Collection | Collection", null, mobyPrefixResolver, XPath.SELECT ); + } + catch ( TransformerException te ) { + debugPS.println( "Syntax error encountered while compiling XPath " + + "statements for internal use (code bug?): " + te ); + } + setDebugMode( System.getProperty( "moby.debug" ) != null ); + } + + /** + * @param mode if true, debugging information is printed to the stream returned by getDebugOutputStream + */ + public void setDebugMode(boolean mode) { + debug = mode; + } + + /** + * Standard error is used unless this method is called. + * + * @param ps the OutputStream to which debugging information is sent. + * @throws IllegalArgumentException if the stream is null + */ + public void setDebugPrintStream(PrintStream ps) throws IllegalArgumentException { + if ( ps == null ) { + throw new IllegalArgumentException( "The OutputStream specified to MobyRequest was null" ); + } + debugPS = ps; + } + + /** + * @param user the user for a possible service authentication + * @param password the passoword for a possible service authentication + */ + public void setAuthentication(String user, String password) { + this.user = user; + this.password = password; + } + + /** + * @return the instance of the class implementing Central that we are using + */ + public Central getCentralImpl() { + return mobyCentral; + } + + /** + * @param mobyservice the MobyService that should be executed when invokeService is called + */ + public void setService(MobyService mobyservice) { + if ( mobyservice == null ) { + mobyService = null; + } + else if ( mobyService == null || !mobyservice.equals( mobyService ) ) { + mobyService = mobyservice; + } + } + + /** + * @return the MobyService that will be executed when invokeService is called + */ + public MobyService getService() { + return mobyService; + } + + /** + * @return the Raw MOBY XML response as a string + */ + public String getResponseXML() { + return responseString; + } + + /** + * Sets the input data for the MOBY service request. The length of the input array, and the number of input + * parameters required by the service must be equal when invokeService() is called. This method strictly enforces + * that the input be of the appropriate type for the service. + * + * Note that there is no requirement to use MobyDataInstance.setXmlMode() before passing in data, this class will + * temporarily set the XML mode of the data when it is required. + * + * @throws IllegalArgumentException if the input does not fit the criteria of the service (e.g. wrong data type) + */ + public void setInput(MobyContentInstance data) throws MobyException { + inputData = data; + } + + /** + * Takes the data in the array, with their current articleNames, as input for the service + */ + public void setInput(MobyDataInstance[] data) throws MobyException { + MobyDataJob job = new MobyDataJob(); + for ( MobyDataInstance param : data ) { + job.put( param.getName(), param ); + } + inputData = new MobyContentInstance(); + inputData.put( job ); + } + + /** + * Convenience method to run services that take one argument. If the service requires the input to have a name, it + * will be automatically assigned. + */ + public void setInput(MobyDataInstance datum) throws MobyException { + setInput( datum, "" ); + } + + /** + * Convenience method to run services that take one named argument. + */ + public void setInput(MobyDataInstance datum, String paramName) throws MobyException { + inputData = new MobyContentInstance( datum, paramName ); + } + + /** + * @return the MobyService that will be executed when invokeService is called + */ + public MobyContentInstance getInput() { + return inputData; + } + + /** + * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) + */ + public void setSecondaryInput(Collection< MobyDataSecondaryInstance > secondaryData) throws MobyException { + setSecondaryInput( secondaryData.toArray( new MobyDataSecondaryInstance[ secondaryData.size() ] ) ); + } + + /** + * This method will assign the provided secondary parameters to all primary input data currently in this object. + * This is covenient if you are running 100 seqs through BLAST and only want to set the parameters once. If you + * instead want to set secondary input differently for all primary inputs, you'll need to create a custom + * MobyContentInstance as input to setInput(). + * + * @throws MobyException if a parameter name is blank, or overrides a primary parameter + */ + public void setSecondaryInput(MobyDataSecondaryInstance[] secondaryData) throws MobyException { + + Iterator queryNames = inputData.keySet().iterator(); + // For each query + while (queryNames.hasNext()) { + MobyDataJob queryParams = inputData.get( queryNames.next() ); + // Set all the secondary params (overwrites any old ones) + for ( int i = 0; i < secondaryData.length; i++ ) { + String secName = secondaryData[ i ].getName(); + if ( secName == null || secName.length() == 0 ) { + throw new MobyException( "A secondary parameter cannot have a blank name (array index " + i + ")" ); + } + if ( queryParams.containsKey( secName ) && queryParams.get( secName ) instanceof MobyPrimaryData ) { + throw new MobyException( "A secondary parameter cannot override an existing primary parameter " + + "with the same name (" + secName + ")" ); + } + queryParams.put( secName, secondaryData[ i ] ); + } + } + } + + /** + * @return a vector of MobyDataInstance[], each element of the vector is the collection of response objects for the + * correspondingly indexed input request. + * + * @throws MobyException if you try to get the results before calling InvokeService + */ + public MobyContentInstance getOutput() throws MobyException { + if ( outputData == null ) { + throw new MobyException( "Trying to access MOBY service results " + "before the service is invoked" ); + } + else { + return outputData; + } + } + + /** + * The main method of the class. If all of the MOBY input objects are properly defined according to the Web service + * definition, a SOAP request will be sent to the remote server, and the method will return one or more MOBY objects + * (synchronous). Call this method after calling setService, and setInput. If you do not call setSecondaryInput, the + * default secondary parameter values will be used. + * + * @return the results of the remote Web service in response to the give input + * + * @throws MobyException i.e. there was something wrong with the input, output or remote service's logic + * @throws SOAPException i.e. there was a problem with the underlying transaction/transport layer + */ + public MobyContentInstance invokeService() throws Exception, MobyException, SOAPException, NoSuccessException { + return mobyService.isAsynchronous() + ? invokeService( inputData, new StringBuffer() ) + : invokeService( inputData, ( StringBuffer ) null ); + } + + // Used internally for asynchronous thread calls that all need the XML data + // and can't rely on the answer from thread-insensitive getResponseXML() + private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML) throws Exception, + MobyException, SOAPException, NoSuccessException { + return invokeService( inData, contentsXML, null, 0 ); + } + + private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML, + MobyRequestEventHandler handler, int requestId) throws Exception, MobyException, SOAPException, + NoSuccessException { + + if ( mobyService == null ) { + throw new MobyException( "Tried to invoke null service from MobyRequest (call setService first)" ); + } + + Element mobyDOM = null; + if ( mobyService.isAsynchronous() ) { + // Async is "simpler", because it had to merge DOMs together into a single MobyContentInstance anyway + MobyContentInstance mci = performAsyncSOAPRequest( mobyService, inData, handler, requestId ); + StringWriter writer = new StringWriter(); + MobyDataUtils.toXMLDocument( writer, mci ); + contentsXML.append( writer.toString() ); + return mci; + } + else { + String mobyXML = convertMOBYDataToMOBYRequest( inData ); + Call call = getServiceFromWSDL(); + if ( user != null && password != null ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, password ); + } + mobyDOM = performSOAPRequest( call, mobyXML, contentsXML ); + // The following parses the DOM and extracts all the appropriate jMOBY objects to represent the XML in Java + return MobyDataUtils.fromXMLDocument( mobyDOM, mobyService.getServiceType().getRegistry() ); + } + } + + protected MobyContentInstance performAsyncSOAPRequest(MobyService mservice, MobyContentInstance inData, + MobyRequestEventHandler handler, int requestId) throws Exception { + String mobyXML = convertMOBYDataToMOBYRequest( inData ); + EndpointReference epr = AsyncClient.sendRequest( mservice, mobyXML ); + + // Essentially cloning, so removing ids doesn't change the + // MobyContentInstance "data" (which we will use again later on) + MobyContentInstance finalContents = new MobyContentInstance(); + Set< String > queryIDs = new HashSet< String >( inData.keySet() ); + try { + // Should add some timeout here... + while (!queryIDs.isEmpty()) { + // todo: make this setable + Thread.sleep( 5000 ); + + AnalysisEvent[] events = AsyncClient.poll( epr, queryIDs ); + + Vector< String > newDataAvailable = new Vector< String >(); + for ( AnalysisEvent event : events ) { + if ( event != null && event.isCompleted() ) { + queryIDs.remove( event.getQueryId() ); + newDataAvailable.add( event.getQueryId() ); + } + } + + if ( newDataAvailable.size() > 0 ) { + // Parse and merge the new data into the existing contents + InputStream resultStream = AsyncClient.getResultStream( epr, newDataAvailable ); + Element mobyDOM = asyncSoapTextToMobyDOM( resultStream ); + MobyContentInstance newResults = MobyDataUtils.fromXMLDocument( mobyDOM, + mservice.getServiceType() + .getRegistry() ); + // The merge + for ( String jobid : newResults.keySet() ) { + finalContents.put( jobid, newResults.get( jobid ) ); + } + + // Inform the handler that some data has been added to the response (for incremental display?) + if ( handler != null ) { + MobyRequestEvent mre = new MobyRequestEvent( finalContents, this, mservice, null, requestId ); + StringWriter xmlWriter = new StringWriter(); + MobyDataUtils.toXMLDocument( xmlWriter, finalContents ); + + mre.setContentsXML( xmlWriter.toString() ); + if ( !queryIDs.isEmpty() ) { + // Send an update event only if we aren't finished yet. + // If we are finished, the client is going to get this event as the + // invocation thread finishes up (no need to double up). + handler.processEvent( mre ); + } + } + } + } + } + catch ( Exception e ) { + e.printStackTrace(); + AsyncClient.destroy( epr ); + throw new Exception( "Exception occured while polling the service invocation: " + e ); + } + + return finalContents; + } + + private Element asyncSoapTextToMobyDOM(InputStream inStream) throws Exception { + Element soapDOM = null; + synchronized ( docBuilder ) { + soapDOM = docBuilder.parse( inStream ).getDocumentElement(); + } + final boolean IS_ASYNC_SERVICE_CALL = true; + return decodeSOAPMessage( soapDOM, null, null, IS_ASYNC_SERVICE_CALL ); + } + + /** + * Asynchronous call to invokeService. A callback to the passed-in handler will be made when the response is ready, + * or there is an exception. + * + * @return the id that the callback event will return from getID(), allowing a client to distinguish between + * multiple concurrent invocation callbacks + */ + public synchronized int invokeService(MobyRequestEventHandler handler) { + int id = autoID++; + + Thread t = new InvocationThread( this, inputData, handler, id ); // see internal class definition below + t.start(); + + return id; + } + + // This is the class that asynchronously calls the service and does a callback to + // the handler specified in the invocation. + class InvocationThread extends Thread { + MobyContentInstance data; + MobyService mservice; + MobyRequest mobyRequest; + MobyRequestEventHandler handler; + int requestId; + + InvocationThread( MobyRequest mr, MobyContentInstance inData, MobyRequestEventHandler h, int id ) { + data = inData; + mobyRequest = mr; + mservice = mobyRequest.getService(); + handler = h; + requestId = id; + + // Name the thread after the service being run, mostly for ease of debugging + setName( mservice.getName() + requestId ); + } + + public void run() { + MobyRequestEvent requestEvent = new MobyRequestEvent( data, mobyRequest, mservice, null, requestId ); + // Tell the handler we're starting the request, with the given data + handler.start( requestEvent ); + + MobyRequestEvent responseEvent = null; + MobyContentInstance content = null; + StringBuffer contentsXML = new StringBuffer(); // to be filled in by the RPC call below + try { + content = mobyRequest.invokeService( data, contentsXML, handler, requestId ); // RPC call... + } + catch ( Exception e ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, e, requestId ); + } + catch ( Error err ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, err, requestId ); + } + if ( responseEvent == null ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, null, requestId ); + } + // We've got the raw XML laying around, so why not provide it unmolested to the callback? + responseEvent.setContentsXML( contentsXML.toString() ); + handler.processEvent( responseEvent ); + handler.stop( mobyRequest, requestId ); + } + } + + public void addEventHandler(MobyRequestEventHandler h) { + eventHandlers.add( h ); + } + + public void removeEventHandler(MobyRequestEventHandler h) { + eventHandlers.remove( h ); + } + + public void sendResponse(MobyRequestEvent mre) { + // Not yet implemented, need to conform to some web.xml specification here... + } + + /** + * This method retrieves from Moby Central a copy of the WSDL document for the service (or uses an internally cached + * copy from a previous invocation), and sets the variables for the SOAP call appropriately so you can consequently + * call performSOAPRequest. + */ + protected Call getServiceFromWSDL() throws MobyException, NoSuccessException { + // String wsdl = null; + + // // Since this is how we retrieve a service from Central, use the same values as the key to the hash + // String wsdlCacheKey = mobyService.getName() + "@" + mobyService.getAuthority(); + + // // This is the same call as last time, so we don't need to change the setup + // if(wsdlCacheKey.equals(lastWsdlCacheKey)){ + // return setCallFromWSDL((String) wsdlCache.get(wsdlCacheKey)); + // } + // // We haven't encountered this service yet + // else if(!wsdlCache.containsKey(wsdlCacheKey)){ + // wsdl = mobyCentral.getServiceWSDL(mobyService.getName(), mobyService.getAuthority()); + // wsdlCache.put(wsdlCacheKey, wsdl); + // } + // // We've dealt with this one before + // else{ + // wsdl = (String) wsdlCache.get(wsdlCacheKey); + // } + + // lastWsdlCacheKey = wsdlCacheKey; // Keep track of the last invocation + + // Get ready to do SOAP + return setCallFromWSDL( null ); + } + + /** + * Creates the SOAP Call that will be invoked later. This should be based on the WSDL document and parameter + * information from the MobyService, but these are currently not up to snuff. + */ + protected Call setCallFromWSDL(String wsdl) throws MobyException, SOAPException { + if ( service == null ) { + service = new org.apache.axis.client.Service(); // AXIS SPECIFIC This acts as a factory for Calls + } + + Call soapCall; + try { + soapCall = ( Call ) service.createCall();// create a fresh Call each time + } + catch ( javax.xml.rpc.ServiceException se ) { + throw new SOAPException( "Could not instatiate call to SOAP Service: " + se ); + } + + // Should initialize endpoint, etc. This call is AXIS SPECIFIC, otherwise you'll + // have to do the call's info setting manually. + // ((org.apache.axis.client.Call) soapCall).setSOAPService(soapService); + soapCall.removeAllParameters(); + soapCall.setTargetEndpointAddress( mobyService.getURL() ); + soapCall.setPortName( new QName( "http://biomoby.org/", mobyService.getName() + "PortType" ) ); + // soapCall.setOperationName(new QName("http://biomoby.org/", + // mobyService.getName())); + soapCall.setSOAPActionURI( "http://biomoby.org/#" + mobyService.getName() ); + return soapCall; + } + + /** + * Calls the invoke() method of the JAX-RPC Call interface. + */ + protected Element performSOAPRequest(Call soapCall, String mobyInputXML, StringBuffer contentsXMLOutput) + throws SOAPException { + // First, turn the input objects into a MOBY XML request + String[] mobyXMLInputData = new String[ 1 ]; + + // Setup + mobyXMLInputData[ 0 ] = mobyInputXML; + + if ( debug ) + debugPS.println( "returnType just before invoke call is " + soapCall.getReturnType() ); + Object returnedObject = null; + try { + returnedObject = soapCall.invoke( new QName( "http://biomoby.org/", mobyService.getName() ), + mobyXMLInputData ); + } + catch ( Exception e ) { + e.printStackTrace(); + // System.err.println("Input: "+mobyInputXML); + throw new SOAPException( "While invoking SOAP Call: " + e ); + } + + try { + if ( debug ) { + debugPS.println( "SOAP Response was:\n" ); + debugPS.println( soapCall.getResponseMessage().getSOAPPart().getEnvelope() ); + } + Element resultDom = ( ( MessageElement ) soapCall.getResponseMessage().getSOAPPart().getEnvelope() ).getAsDOM(); + return decodeSOAPMessage( resultDom, contentsXMLOutput, mobyInputXML ); + } + catch ( Exception e ) { + e.printStackTrace(); + throw new SOAPException( "Could not get SOAP response as DOM Element: " + e ); + } + + } + + public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML) throws SOAPException, + MobyException { + return decodeSOAPMessage( n, contentsXMLOutput, inputXML, false ); + } + + /** + * Isolates the MOBY Data from the SOAP message returned by the remote service host. + * + * @throws SOAPException if the MOBY payload cannot be found in the SOAP message + * @throws MobyException if the MOBY message is not well-formed XML + * + * @return The root element of the MOBY response DOM + */ + public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML, boolean async) + throws SOAPException, MobyException { + if ( n == null ) { + throw new SOAPException( "SOAP Message given to decode is null" ); + } + + NodeList node_list = null; + XPath responseElementXPath = null; + try { + if ( async ) { + responseElementXPath = new XPath( "//" + MobyPrefixResolver.WSRP_PREFIX + ":" + + AsyncClient.WSRP_MULTI_PROPERTY_TAG_NAME + "Response", null, mobyPrefixResolver, XPath.SELECT ); + } + else { + responseElementXPath = new XPath( "//" + MobyPrefixResolver.MOBY_TRANSPORT_PREFIX + ":" + + mobyService.getName() + "Response | //" + mobyService.getName() + "Response | " + "//" + + MobyPrefixResolver.MOBY_TRANSPORT_PREFIX + ":" + mobyService.getName() + " | //" + + mobyService.getName(), null, mobyPrefixResolver, XPath.SELECT ); + } + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select SOAP nodes due to exception " + + "while compiling XPath statement (code bug?):" + te ); + } + try { + node_list = runXPath( responseElementXPath, n ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select SOAP nodes due to exception " + "while executing XPath statement:" + + te ); + } + + if ( node_list == null || node_list.getLength() == 0 ) { + throw new SOAPException( "Could not find a response element in SOAP payload (service " + + mobyService.getName() + ")" ); + } + + if ( node_list.getLength() > 1 ) { + throw new SOAPException( "Found more than one response element in SOAP payload, " + + "unable to resolve ambiguity of the payload (service provider error?)" ); + } + + Node[] responseNodes = null; + if ( async ) { + Vector< Node > nodes = new Vector< Node >(); + NodeList resultNodeList = node_list.item( 0 ).getChildNodes(); + for ( int i = 0; resultNodeList != null && i < resultNodeList.getLength(); i++ ) { + if ( ! ( resultNodeList.item( i ) instanceof Element ) ) { + continue; + } + Element resultElement = ( Element ) resultNodeList.item( i ); + if ( resultElement.getLocalName().startsWith( AsyncClient.MOBY_RESULT_PROPERTY_PREFIX ) ) { + nodes.add( resultElement ); + } + } + responseNodes = nodes.toArray( new Node[ nodes.size() ] ); + } + else { + responseNodes = new Node[]{node_list.item( 0 )}; + } + + Element domRoot = null; // Where the result will be put + + for ( Node responseNode : responseNodes ) { + // Find base64 encoded elements in the SOAP message using XPath and + // replace them with the real decoded contents + node_list = null; + try { + node_list = runXPath( base64EncodedXPath, responseNode ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select base64 encoded SOAP nodes due to exception " + + "while executing XPath statement:" + te ); + } + if ( debug && node_list != null ) { + debugPS.println( "There were " + node_list.getLength() + " base64 encoded elements in the data" ); + } + + // Do decoding for each base64 part found + for ( int i = 0; node_list != null && i < node_list.getLength(); i++ ) { + org.w3c.dom.Node change = node_list.item( i ); + /* Make sure the text data is all put into one contiguous piece for decoding */ + change.normalize(); + + byte[] decodedBytes = org.apache.axis.encoding.Base64.decode( change.getFirstChild().getNodeValue() ); + String newText = new String( decodedBytes ); + if ( debug ) { + debugPS.println( "New decoded text is" + newText ); + } + + // Swap out this node for the decoded data + change.getParentNode().replaceChild( n.getOwnerDocument().createTextNode( new String( decodedBytes ) ), + change ); + } + + // Now see if there are any strings that need decoding + node_list = null; + try { + node_list = runXPath( stringEncodedXPath, responseNode ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select string encoded SOAP nodes due to exception " + + "while executing XPath statement:" + te ); + } + + // Do concatenation for each plain string part found + for ( int i = 0; node_list != null && i < node_list.getLength(); i++ ) { + org.w3c.dom.Node change = node_list.item( i ); + /* Make sure the text data is all put into one contiguous piece for decoding */ + change.normalize(); + String plainString = ""; + int j = 0; + for ( NodeList children = change.getChildNodes(); children != null && j < children.getLength(); j++ ) { + Node child = children.item( j ); + if ( child instanceof CDATASection || child instanceof Text ) { + plainString += child.getNodeValue(); + if ( debug ) { + debugPS.println( "Plain string is now " + plainString ); + } + } + } + + // Swap out this node for the decoded data + change.getParentNode().replaceChild( n.getOwnerDocument().createCDATASection( plainString ), change ); + } + if ( debug && node_list != null ) { + debugPS.println( "There were " + node_list.getLength() + + " XML Schema string encoded elements in the data" ); + } + + // Parse the MOBY XML document payload + responseNode.normalize(); + NodeList children = responseNode.getChildNodes(); + if ( children == null ) { + throw new MobyException( "The MOBY payload has no contents at all" ); + } + if ( children.getLength() != 1 ) { + if ( debug ) { + debugPS.println( "Warning: MOBY Payload appears to have more than " + + "just text in it, skipping the non-text sections" ); + } + } + + Element predefinedDOM = null; // Choice of ripping DOM Element for moby payload out of SOAP DOM + String localResponseString = ""; // or storing raw XML strings, to be converted to a DOM later + for ( int j = 0; j < children.getLength(); j++ ) { + Node child = children.item( j ); + if ( child instanceof CDATASection || child instanceof Text ) { + // Unescape XML special characters in the string, so we can later on + // parse the payload as regular XML. + // Ignore whitespace-only node + if ( child.getNodeValue().matches( "^\\s+$" ) ) { + continue; + } + if ( debug ) { + debugPS.println( "Concatenating text in response " + child.getNodeValue() ); + } + localResponseString += child.getNodeValue();// .replaceAll("<", "<").replaceAll(">", + // ">").replaceAll("(&|F)", "&"); + } + if ( child instanceof Element && child.getLocalName().equals( MobyTags.MOBY ) ) { + debugPS.println( "Warning: The MOBY contents was found as raw XML inside the SOAP response!\n" + + "This is illegal according to the MOBY-API, please inform the service\n " + + " provider, as parsing such text may not be supported in the future" ); + localResponseString = null; + // Store the moby payload root element's DOM represntation, so we don't + // have to serialize it to the localResponseString and then parse it out + // again (that would be wasteful). + predefinedDOM = ( Element ) child; + break; + } + } + + if ( localResponseString != null ) { + if ( localResponseString.length() == 0 ) { + throw new MobyException( "The MOBY payload has no text contents at all" ); + } + if ( Character.isWhitespace( localResponseString.charAt( 0 ) ) ) { + localResponseString = localResponseString.trim(); + } + } + + // Check if the payload is an XML document. If not, try a last ditch effort + // by base64 decoding the contents. This is technically not allowable in the + // MOBY spec, but we are being lenient. + if ( localResponseString != null && !localResponseString.startsWith( "\n" + localResponseString; + debugPS.println( "Warning: The MOBY contents was missing an XML declaration, but it is " + + "required by the MOBY API, and may stop working in the future without it. Please " + + "contact the client's provider to correct this." ); + } + else { + String oldResponse = localResponseString; + localResponseString = new String( org.apache.axis.encoding.Base64.decode( localResponseString ) ); + if ( !localResponseString.startsWith( " entry : data.entrySet() ) { + String queryName = entry.getKey(); + MobyDataJob query = entry.getValue(); + + // Additionally, we check if they are MobyDataInstances below + Map< String, MobyPrimaryData > primaryParams = new HashMap< String, MobyPrimaryData >(); + Map< String, MobySecondaryData > secondaryParams = new HashMap< String, MobySecondaryData >(); + + // To store the primary input parameter name as given by the user, + // in case we need it later on for parameter renaming... + String primaryParamName = null; + + for ( Map.Entry< String, MobyDataInstance > subentry : query.entrySet() ) { + String name = subentry.getKey(); + MobyDataInstance param = subentry.getValue(); + if ( param == null ) { + throw new MobyException( "Query " + queryName + " contained a null input parameter (" + name + ")" ); + } + else if ( param instanceof MobyPrimaryData ) { + primaryParams.put( name, ( MobyPrimaryData ) param ); + primaryParamName = name; + } + else if ( param instanceof MobySecondaryData ) { + secondaryParams.put( name, ( MobySecondaryData ) param ); + } + else { + System.err.println( "Input parameter " + name + " (query " + queryName + + ") was not a MobyPrimaryData or MobySecondaryData " + + "as expected, but rather was of class " + param.getClass().getName() ); + } + } + + if ( inputs != null && inputs.length != primaryParams.size() ) { + throw new MobyException( "Service " + mobyService.getName() + " was provided " + primaryParams.size() + + " primary input parameter(s), but takes " + inputs.length + " (query " + queryName + ")" ); + } + if ( secondaries != null ) { + // If no secondaries provided, fill them in by default + if ( secondaries.length != 0 ) { + for ( MobySecondaryData secondary : secondaries ) { + if ( !secondaryParams.containsKey( secondary.getName() ) ) { + if ( debug ) { + System.err.println( "Setting default secondary param value for missing param " + + secondary ); + } + query.put( secondary.getName(), new MobyDataSecondaryInstance( secondary ) ); + } + } + } + if ( secondaries.length != secondaryParams.size() ) { + throw new MobyException( "Service " + mobyService.getName() + " was provided " + + secondaryParams.size() + " secondary input parameter(s), but takes " + secondaries.length + + " (query " + queryName + "). Extra secondary" + " parameters must have been specified" ); + } + } + + // If there was one anonymous input, assign the name automatically in + // the case the service requires it to be named. This is the only + // unambiguous case in which we can do this. + if ( inputs.length == 1 ) { + String serviceParamName = inputs[ 0 ].getName(); // name as req'd by the service + + // name isn't the same as required currently + if ( serviceParamName != null && serviceParamName.length() > 0 + && !serviceParamName.equals( primaryParamName ) ) { + // take out the old parameter + MobyPrimaryData theInputToRename = ( MobyPrimaryData ) query.remove( primaryParamName ); + + // Add in the same parameter, but with the appropriate name + query.put( serviceParamName, ( MobyDataInstance ) theInputToRename ); + } + } + } + + ByteArrayOutputStream mobyRequest = new ByteArrayOutputStream(); + try { + MobyDataUtils.toXMLDocument( mobyRequest, data ); + } + catch ( MobyException me ) { + throw me; + } + catch ( Exception e ) { + e.printStackTrace(); + throw new MobyException( "Could not create MOBY payload XML from input data: " + e ); + } + + if ( debug ) { + debugPS.println( "Input to MOBY Service is:" ); + debugPS.print( mobyRequest.toString() ); + } + + return mobyRequest.toString(); + } + + /** + * A method that sets up the execution environment for and runs a compiled XPath statement against a DOM node You + * should call releaseXPath when you're done with the results + * + * @return the list of Nodes that satisfy the XPath in this Node's context + */ + protected NodeList runXPath(XPath xpath, Node n) throws TransformerException { + NodeList result = null; + int dtm_node_handle = xpath_context.getDTMHandleFromNode( n ); + PrefixResolver node_prefix_resolver = new PrefixResolverDefault( n ); + XObject xobject = xpath.execute( xpath_context, n, node_prefix_resolver ); + if ( xobject instanceof XNodeSet ) { + result = ( ( XNodeSet ) xobject ).nodelist(); + } + else if ( debug && xobject != null ) { + debugPS.println( "Output of XPath was not a XNodeSet as expected, found " + xobject.getClass().getName() ); + debugPS.flush(); + } + return result; + } + + protected void releaseXPath(Node n) { + xpath_context.release( xpath_context.getDTM( xpath_context.getDTMHandleFromNode( n ) ), false ); + } +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java,v retrieving revision 1.57 retrieving revision 1.58 diff -u -r1.57 -r1.58 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java 2008/10/30 02:33:25 1.57 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java 2008/11/26 08:53:43 1.58 @@ -1,2139 +1,1957 @@ -// CentralImpl.java -// A default client to the Moby Central service. -// -// senger at ebi.ac.uk -// February 2003 -// - -package org.biomoby.client; - -import org.biomoby.registry.meta.Registry; -import org.biomoby.shared.Central; -import org.biomoby.shared.MobyData; -import org.biomoby.shared.MobyDataType; -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyNamespace; -import org.biomoby.shared.MobyPrimaryDataSet; -import org.biomoby.shared.MobyPrimaryDataSimple; -import org.biomoby.shared.MobyRelationship; -import org.biomoby.shared.MobySecondaryData; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.MobyServiceType; -import org.biomoby.shared.NoSuccessException; -import org.biomoby.shared.PendingCurationException; -import org.biomoby.shared.MobyResourceRef; -import org.biomoby.shared.Utils; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.namespace.QName; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.apache.axis.AxisFault; -import org.apache.axis.client.Call; -import org.apache.axis.client.Service; -import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.HeadMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.PrintStream; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Vector; -import java.util.TreeMap; -import java.util.Comparator; -import java.util.zip.GZIPInputStream; -import java.util.logging.*; - -/** - * A default implementation of the - * interface {@link org.biomoby.shared.Central Central} - * allowing access to a Moby registry. - *

    - * This class is supposed to be used by all other clients that wish - * to communicate with the Moby Registry, but do not want to know - * about all XML details that are necessary for talking with the Moby Central - * directly. This is an example of a client program: - *

    - * import org.biomoby.shared.Central;
    - * import org.biomoby.shared.MobyException;
    - * import org.biomoby.client.CentralImpl;
    - * import java.util.Map;
    - * import java.util.Iterator;
    - *
    - * public class Test {
    - *
    - *    public static void main (String[] args)
    - *       throws MobyException {
    - *
    - *       Central worker = new CentralImpl();
    - *       Map authorities = worker.getServiceNamesByAuthority();
    - *
    - *       for (Iterator it = authorities.entrySet().iterator(); it.hasNext(); ) {
    - *          Map.Entry entry = (Map.Entry)it.next();
    - *          System.out.println (entry.getKey());
    - *          String[] names = (String[])entry.getValue();
    - *          for (int i = 0; i < names.length; i++)
    - *             System.out.println ("\t" + names[i]);
    - *       }
    - *    }
    - * }
    - *
    - * - * @author Martin Senger - * @version $Id$ - */ - -public class CentralImpl - implements Central, SimpleCache { - - private URL endpoint; - private String uri; - protected boolean debug = false; - - /** Common central used to if getDefaultCentral() is called */ - protected static Map defaultCentrals = new HashMap(); - - /** Default location (endpoint) of a Moby registry. */ - public static final String DEFAULT_ENDPOINT = "http://moby.ucalgary.ca/moby/MOBY-Central.pl"; - - /** Default namespace used by the contacted Moby registry. */ - public static final String DEFAULT_NAMESPACE = "http://moby.ucalgary.ca/MOBY/Central"; - - /** - * The META-INF resource file that will be checked to determine what - * default class should be instantiated in order to create a Central Implementation - * when getDefaultCentral() is called. - */ - public static final String CENTRAL_IMPL_RESOURCE_NAME = "org.biomoby.shared.CentralDefaultImpl"; - /** The class to use for getDefaultCentral if all else fails */ - public static final String DEFAULT_CENTRAL_IMPL_CLASSNAME = "org.biomoby.client.CentralDigestCachedImpl"; - private static Logger logger = Logger.getLogger("org.biomoby.client.CentralImpl"); - - /** - * Thread local that gives each thread its own - * DocumentBuilderFactory (since it is not thread-safe). Code taken - * from Apache's JaxpUtils. - */ - public static ThreadLocal DOCUMENT_BUILDER_FACTORIES = new ThreadLocal() { - protected synchronized Object initialValue() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware (true); - return dbf; - } - }; - - - /************************************************************************* - * Default constructor. It connects to a default Moby registry - * (as defined in {@link #DEFAULT_ENDPOINT}) using a default namespace - * (as defined int {@link #DEFAULT_NAMESPACE}). - *************************************************************************/ - public CentralImpl() - throws MobyException { - this (DEFAULT_ENDPOINT, DEFAULT_NAMESPACE); - } - - /************************************************************************* - * Constructor allowing to specify which Moby Registry to use. - * - * @throws MobyException if 'endpoint' is not a valid URL, or if no - * DOM parser is available - *************************************************************************/ - public CentralImpl (String endpoint) - throws MobyException { - this (endpoint, DEFAULT_NAMESPACE); - } - - /************************************************************************* - * Constructor allowing to specify which Moby Registry and what - * namespace to use. If any of the parameters is null, its default - * value is used instead. - *

    - * @throws MobyException if 'endpoint' is not a valid URL, or if no - * DOM parser was found - *************************************************************************/ - public CentralImpl (String endpoint, String namespace) - throws MobyException { - - if (endpoint == null || "".equals (endpoint.trim())) - endpoint = DEFAULT_ENDPOINT; - if (namespace == null || "".equals (namespace.trim())) - namespace = DEFAULT_NAMESPACE; - - try { - this.endpoint = new URL (endpoint); - } catch (MalformedURLException e) { - throw new MobyException ("Bad URL: " + endpoint); - } - this.uri = namespace; - - cache = new Hashtable(); - useCache = true; - } - - /************************************************************************* - * Loads a DOM Document from an InputStream. Uses thread-safe - * mechanism. - *************************************************************************/ - public static Document loadDocument (InputStream input) - throws MobyException { - try { - DocumentBuilderFactory dbf - = (DocumentBuilderFactory)DOCUMENT_BUILDER_FACTORIES.get(); - DocumentBuilder db = dbf.newDocumentBuilder(); - return (db.parse (input)); - } catch (Exception e) { - throw new MobyException ("Problem with reading XML input: " + e.toString(), e); - } - } - - /************************************************************************* - * Call 'method' with 'parameters' and return its result. - *************************************************************************/ - protected Object doCall (String method, Object[] parameters) - throws MobyException { - - Call call = null; - try { - Service service = new Service(); - call = (Call) service.createCall(); - call.setTargetEndpointAddress (endpoint); - call.setTimeout (new Integer (0)); - - call.setSOAPActionURI (uri + "#" + method); - - if (debug) { - System.err.println ("METHOD CALL: " + method); - System.err.println ("------------"); - if (parameters.length > 0) - System.err.println (parameters[0] + "\n"); - System.err.println ("------------\n"); - - Object result = call.invoke (uri, method, parameters); - - System.err.println ("METHOD RETURN:"); - System.err.println ("------------"); - if (result != null) - System.err.println (result + "\n"); - System.err.println ("------------\n"); - - return resultToString (result); - - } else { - return resultToString (call.invoke (uri, method, parameters)); - } - - } catch (AxisFault e) { - throw new MobyException - (formatFault (e, - endpoint.toString(), - (call == null ? null : call.getOperationName())), - e); -// (endpoint.toString()+(call == null ? "" : call.getOperationName()), e); - - } catch (Exception e) { - throw new MobyException (e.toString(), e); -// e.printStackTrace(); - } - } - - - /************************************************************************** - * Parse the given XML sniplet to find tag 'success'. If it has value '1' - * look further for tag 'id' and return it back (or return an empty string - * if ID is not there). Otherwise raise an exception with the 'culprit' - * and with the message from the tag 'message'.

    - * - * The return value is a two-element long array. The first element - * is the ID (given by BioMobe registry), and the second element - * is RDF corresponding with the registered object (BioMoby - * returns this only for service instances, so for other objects - * this will be null).

    - * - * This is how the XML is supposed to look: - * - * - * - * - * - * - * - * Success takes the value "1" to indicate success, "0" to - * indicate failure, and "-1" to indicate "Pending Curation". - *************************************************************************/ - protected String[] checkRegistration (String xml, Object culprit) - throws MobyException, NoSuccessException, PendingCurationException { - - String id = "", success = "0", message = "", rdf = ""; - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (xml.getBytes())); - Element root = document.getDocumentElement(); - - NodeList children = root.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item (i).getNodeType() != Node.ELEMENT_NODE) - continue; - Element elem = (Element)children.item (i); - if (elem.getNodeName().equals ("id")) { - if (elem.getFirstChild() != null) - id = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals("success")) { - if (elem.getFirstChild() != null) - success = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals ("message")) { - if (elem.getFirstChild() != null) - message = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals ("RDF")) { - if (elem.getFirstChild() != null) - rdf = elem.getFirstChild().getNodeValue(); - } - } - - if (success.equals ("0")) - throw new NoSuccessException (message, culprit); - else if (success.equals ("-1")) - throw new PendingCurationException(); - return new String[] { id, rdf }; - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing input - * data types and their usage in the given service. Only data considered - * primary are included. Note that the main job of converting to XML is - * done by instances of MobyPrimaryData. - * - * The returned XML looks like this: - * - * - * - *************************************************************************/ - protected String buildPrimaryInputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] primaryInputs = service.getPrimaryInputs(); - buf.append ("\n"); - for (int i = 0; i < primaryInputs.length; i++) - buf.append (primaryInputs[i].toXML()); - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing input - * data types and their usage in the given service. Only data considered - * secondary are included. Note that the main job of converting to XML is - * done by instances of MobySecondaryData. - * - * The returned XML looks like this: - * - * - * - *************************************************************************/ - protected String buildSecondaryInputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] secInputs = service.getSecondaryInputs(); - buf.append ("\n"); - for (int i = 0; i < secInputs.length; i++) { - buf.append (secInputs[i].toXML()); - } - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing output - * data types and their usage in the given service. Only data considered - * primary are included. Note that the main job of converting to XML is - * done by instances of MobyPrimaryData. - * - * The returned XML looks like this: - * - * - * - * - *************************************************************************/ - protected String buildOutputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] primaryOutputs = service.getPrimaryOutputs(); - buf.append ("\n"); - for (int i = 0; i < primaryOutputs.length; i++) - buf.append (primaryOutputs[i].toXML()); - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML represented a query object (an object used - * to find a service). - * - * The returned XML looks like this: - * - * - * - * - * - * - * - * - * - * - * - * ServiceTypeTerm - * ServiceName - * moby - * http://desired.service.provider; - * 1|0 - * 1|0 - * 1|0 - * - * something - * .... - * .... - * - *************************************************************************/ - protected String buildQueryObject (MobyService service, - String[] keywords, - boolean expandObjects, - boolean expandServices, - boolean authoritative) { - if (service == null) { - service = new MobyService ("dummy"); - service.setCategory (""); - } - StringBuffer buf = new StringBuffer(); - - buf.append ("\n\n"); - MobyData[] pi = service.getPrimaryInputs(); - if (pi.length > 0) { - for (int i = 0; i < pi.length; i++) - buf.append (pi[i].toXML()); - } - buf.append ("\n\n"); - - buf.append ("\n\n"); - MobyData[] po = service.getPrimaryOutputs(); - if (po.length > 0) { - for (int i = 0; i < po.length; i++) - buf.append (po[i].toXML()); - } - buf.append ("\n\n"); - - buf.append ("" + service.getType() + "\n"); - - String name = service.getName(); - if (!name.equals ("") && !name.equals ("dummy") && !name.equals (MobyService.DUMMY_NAME)) - buf.append ("" + service.getName() + "\n"); - - String sigURL = service.getSignatureURL(); - if (!sigURL.equals ("")) - buf.append ("" + sigURL + "\n"); - - buf.append ("" + service.getCategory() + "\n"); - buf.append ("" + service.getAuthority() + "\n"); - - buf.append (""); - buf.append (expandObjects ? "1" : "0"); - buf.append ("\n"); - - buf.append (""); - buf.append (expandServices ? "1" : "0"); - buf.append ("\n"); - - buf.append (""); - buf.append (authoritative ? "1" : "0"); - buf.append ("\n"); - - buf.append ("\n"); - if (keywords != null && keywords.length > 0) { - for (int i = 0; i < keywords.length; i++) { - buf.append (""); - buf.append (keywords[i]); - buf.append ("\n"); - } - } - buf.append ("\n"); - - return new String (buf); - } - - /************************************************************************** - * Extract one or more MobyService objects from the given XML piece. - * The XML should look like this: - *

    -     *  <Services>
    -     *    <Service authURI="authority.URI.here" lsid="..." serviceName="MyService">
    -     *      <serviceType>Service_Ontology_Term</serviceType>
    -     *      <Category>moby</Category> <!-- or 'cgi' or 'soap' -->
    -     *      <contactEmail>your at email.addy.here</contactEmail>
    -     *      <signatureURL>http://service.RDF.here</signatureURL>
    -     *      <URL>http://service.endpoint.here/scriptname</URL>
    -     *      <authoritative>1</authoritative>
    -     *      <Input>
    -     *           <!-- one or more Simple and/or Complex Primary articles -->
    -     *      </Input>
    -     *      <Output>
    -     *           <!-- one or more Simple and/or Complex Primary articles --> 
    -     *      </Output>
    -     *      <secondaryArticles>
    -     *           <!-- one or more Secondary articles -->
    -     *      </secondaryArticles>
    -     *      <Description><![CDATA[free text description here]]></Description>
    -     *    </Service>
    -     *    ...  <!--  one or more Service blocks may be returned -->
    -     *    ...
    -     *    ...
    -     *  </Services>
    -     * 
    - * @throws MobyException if the XML document is invalid - *************************************************************************/ - public MobyService[] extractServices (String xml) - throws MobyException { - - Document document = loadDocument (new ByteArrayInputStream (xml.getBytes())); - NodeList list = document.getElementsByTagName ("Service"); - MobyService[] results = new MobyService [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyService service = new MobyService (elem.getAttribute ("serviceName")); - service.setAuthority (elem.getAttribute ("authURI")); - service.setLSID (elem.getAttribute ("lsid")); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("Description")) { - service.setDescription (getFirstValue (children.item (j))); - } else if (nodeName.equals ("Category")) { - service.setCategory (getFirstValue (children.item (j))); - } else if (nodeName.equals ("URL")) { - service.setURL (getFirstValue (children.item (j))); - } else if (nodeName.equals ("signatureURL")) { - service.setSignatureURL (getFirstValue (children.item (j))); - } else if (nodeName.equals ("contactEmail")) { - service.setEmailContact (getFirstValue (children.item (j))); - } else if (nodeName.equals ("serviceType")) { - service.setType (getFirstValue (children.item (j))); - MobyServiceType mst = new MobyServiceType(service.getType()); - NamedNodeMap map = (children.item (j).getAttributes()); - if (map != null) { - Node node = map.getNamedItemNS(children.item(j).getNamespaceURI(),"lsid"); - if (node != null) - mst.setLSID(node.getNodeValue()); - } - service.setServiceType(mst); - } else if (nodeName.equals ("authoritative")) { - String authoritative = getFirstValue (children.item (j)); - service.setAuthoritative (authoritative.equals ("1") ? true : false); - } else if (nodeName.equals ("Input")) { - // - // - // - // ... - // - // - // ...... - // ...... - // - // - NodeList inputs = children.item (j).getChildNodes(); - for (int k = 0; k < inputs.getLength(); k++) { - if (inputs.item (k).getNodeName().equals ("Simple")) { - MobyPrimaryDataSimple data = new MobyPrimaryDataSimple ((Element)inputs.item (k)); - service.addInput (data); - } else if (inputs.item (k).getNodeName().equals ("Collection")) { - MobyPrimaryDataSet data = new MobyPrimaryDataSet ((Element)inputs.item (k)); - service.addInput (data); - } - } - } else if (nodeName.equals ("Output")) { - // - // - // - NodeList inputs = children.item (j).getChildNodes(); - for (int k = 0; k < inputs.getLength(); k++) { - if (inputs.item (k).getNodeName().equals ("Simple")) { - MobyPrimaryDataSimple data = new MobyPrimaryDataSimple ((Element)inputs.item (k)); - service.addOutput (data); - } else if (inputs.item (k).getNodeName().equals ("Collection")) { - MobyPrimaryDataSet data = new MobyPrimaryDataSet ((Element)inputs.item (k)); - service.addOutput (data); - } - } - - } else if (nodeName.equals ("secondaryArticles")) { - // - // ... - // - NodeList parameters = children.item (j).getChildNodes(); - for (int k = 0; k < parameters.getLength(); k++) { - if (parameters.item (k).getNodeName().equals ("Parameter")) { - MobySecondaryData data = new MobySecondaryData ((Element)parameters.item (k)); - service.addInput (data); - } - } - } - } - results [i] = service; - } - return results; - } - - // protect against null values - protected String getFirstValue (Node child) { - Node node = child.getFirstChild(); - if (node == null) return ""; - String value = node.getNodeValue(); - if (value == null) return ""; - return value; - } - - protected String getFirstValue (NodeList children) { - if (children.item(0) != null && children.item(0).hasChildNodes()) { - children.item(0).normalize(); - return getFirstValue (children.item(0)); - } - return ""; - } - - /************************************************************************** - * - * Implementing SimpleCache interface. - * - * Why to have an interface for such trivial thing? Well, because - * I needed to overwrite the caching mechanism in the subclasses - * so I needed to have all caching functions as separate methods - - * that's why I have collect them in an interface. - * - *************************************************************************/ - private Hashtable cache; // this is the cache itself - private boolean useCache; // this signal that we are actually caching things - - // not used here - public String createId (String rootName, - String semanticType, String syntaxType, - long lastModified, - Properties props) { - return ""; // not used here - } - - // check existence of a cached object - public boolean existsInCache (String id) { - synchronized (cache) { - if (useCache) return cache.containsKey (id); - else return false; - } - } - - // retrieve from cache - public Object getContents (String id) { - synchronized (cache) { - if (useCache) return cache.get (id); - else return null; - } - } - - // cache an object - public void setContents (String id, java.lang.Object data) { - synchronized (cache) { - if (useCache) cache.put (id, data); - } - } - - // in this implementation, it clears the whole cache, regardless - // what 'id' is passed - public void removeFromCache (String id) { - cache.clear(); - } - - /************************************************************************** - * - * And the other methods related to caching (but not part of the - * SimpleCache interface). - * - **************************************************************************/ - - /************************************************************************** - * By default, caching is enabled to reduce network traffic. - * Setting this to false will clear the cache, and not cache any - * further calls unless it is set to true again.

    - * - * @param shouldCache whether retrieveXXX call results should be - * cached in case they are called again (i.e. don't request - * MobyCentral every time) - **************************************************************************/ - public void setCacheMode (boolean shouldCache) { - useCache = shouldCache; - if (! useCache) - removeFromCache (null); - } - - /************************************************************************** - * Find if caching is currently enabled. - * - * @return true if caching is enabled - **************************************************************************/ - public boolean getCacheMode(){ - return useCache; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     * <serviceNames>
    -     *   <serviceName name="serviceName" authURI='authority.info.here'/>
    -     *   ...
    -     *   ...
    -     * </serviceNames>
    -     * 
    - * - * @deprecated Replaced by {@link - * #getServiceNamesByAuthority}. The reason is that this method - * returns a random result if there are more services with the - * same name but belonging to different authorities.

    - * - *************************************************************************/ - public Map getServiceNames() - throws MobyException { - - String result = (String)doCall ("retrieveServiceNames", - new Object[] {}); - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceName"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - results.put (elem.getAttribute ("name"), - elem.getAttribute ("authURI")); - } - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     * <serviceNames>
    -     *   <serviceName name="serviceName" lsid="..." authURI='authority.info.here'/>
    -     *   ...
    -     *   ...
    -     * </serviceNames>
    -     * 
    - * - * @return a Map which has authorities as keys, and String arrays - * with service names as a values. - *************************************************************************/ - public Map getServiceNamesByAuthority() - throws MobyException { - String result = getServiceNamesByAuthorityAsXML(); - return createServicesByAuthorityFromXML (result, true); - } - - /************************************************************************** - * Similar to {@link #getServiceNamesByAuthority} but the - * resulting Map contains slightly more.

    - * - * @return a Map which has authorities as keys, and arrays of - * MobyServices as a values. Each MobyService is filled with its - * name, authority and LSID. - *************************************************************************/ - public Map getServicesByAuthority() - throws MobyException { - String result = getServiceNamesByAuthorityAsXML(); - return createServicesByAuthorityFromXML (result, false); - } - - // - protected String getServiceNamesByAuthorityAsXML() - throws MobyException { - return (String)doCall ("retrieveServiceNames", - new Object[] {}); - } - - // if onlyNames == true - // Map: authority name -> String[] - // (filled with service namea) - // else - // Map: authority name -> MobyService[] - // (filled with service name, authority and lsid) - protected Map createServicesByAuthorityFromXML (String result, - boolean onlyNames) - throws MobyException { - - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceName"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String name = elem.getAttribute ("name"); - String auth = elem.getAttribute ("authURI"); - Vector v = - (results.containsKey (auth) ? (Vector)results.get (auth) : new Vector()); - if (onlyNames) { - v.addElement (name); - } else { - MobyService ms = new MobyService (name); - ms.setAuthority (auth); - ms.setLSID (elem.getAttribute ("lsid")); - v.addElement (ms); - } - results.put (auth, v); - } - - // change values of type Vector to MobyService[] or String[] - for (Iterator it = results.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = (Map.Entry)it.next(); - Vector v = (Vector)entry.getValue(); - if (onlyNames) { - String[] sNames = new String [v.size()]; - v.copyInto (sNames); - entry.setValue (sNames); - } else { - MobyService[] mss = new MobyService [v.size()]; - v.copyInto (mss); - entry.setValue (mss); - } - } - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <serviceProviders>
    -     *     <serviceProvider name="authority.URI.here"/>
    -     *          ...
    -     *          ...
    -     *  </serviceProviders>
    -     * 
    - *************************************************************************/ - public String[] getProviders() - throws MobyException { - - String cacheId = "retrieveServiceProviders"; - String[] cachedResults = (String[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = (String)doCall ("retrieveServiceProviders", - new Object[] {}); - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceProvider"); - String[] results = new String [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) - results[i] = ((Element)list.item (i)).getAttribute ("name"); - - // Add this data to the cache in case we get called again - setContents (cacheId, results); - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <serviceTypes>
    -     *     <serviceType name="serviceName" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *            <contactEmail>...</contactEmail>
    -     *            <authURI>...</authURI>
    -     *     </serviceType>
    -     *          ...
    -     *          ...
    -     *  </serviceTypes>
    -     * 
    - *************************************************************************/ - public Map getServiceTypes() - throws MobyException { - String result = getServiceTypesAsXML(); - Map results = new TreeMap (getStringComparator()); - MobyServiceType[] types = createServiceTypesFromXML (result); - for (int i = 0; i < types.length; i++) { - results.put (types[i].getName(), - types[i].getDescription()); - } - return results; - } - - // - protected String getServiceTypesAsXML() - throws MobyException { - return (String)doCall ("retrieveServiceTypes", - new Object[] {}); - } - - // but be aware that the created MobyServiceTypes are not complete - // - they do not have the relationship information; that's why - // this method is not public; the full service types are available - // from CentralDigest implementations - protected MobyServiceType[] createServiceTypesFromXML (String result) - throws MobyException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceType"); - if (list == null || list.getLength() == 0) - return new MobyServiceType[] {}; - MobyServiceType[] results = new MobyServiceType [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyServiceType st = new MobyServiceType (elem.getAttribute ("name")); - st.setLSID (elem.getAttribute ("lsid")); - st.setDescription (getFirstValue (elem.getElementsByTagName ("Description"))); - st.setEmailContact (getFirstValue (elem.getElementsByTagName ("contactEmail"))); - st.setAuthority (getFirstValue (elem.getElementsByTagName ("authURI"))); - results[i] = st; - } - java.util.Arrays.sort (results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <Namespaces>
    -     *     <Namespace name="namespace" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *            <contactEmail>...</contactEmail>
    -     *            <authURI>...</authURI>
    -     *     </Namespace>
    -     *          ...
    -     *          ...
    -     *  </Namespaces>
    -     * 
    - *************************************************************************/ - public MobyNamespace[] getFullNamespaces() - throws MobyException { - - String result = getNamespacesAsXML(); - return createNamespacesFromXML (result); - } - - // - protected String getNamespacesAsXML() - throws MobyException { - return (String)doCall ("retrieveNamespaces", - new Object[] {}); - } - - // - protected MobyNamespace[] createNamespacesFromXML (String result) - throws MobyException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getDocumentElement().getElementsByTagName ("Namespace"); - if (list == null || list.getLength() == 0) { - return new MobyNamespace[] {}; - } - MobyNamespace[] results = new MobyNamespace [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyNamespace nm = new MobyNamespace (elem.getAttribute ("name")); - nm.setLSID (elem.getAttribute ("lsid")); - nm.setDescription (getFirstValue (elem.getElementsByTagName ("Description"))); - nm.setEmailContact (getFirstValue (elem.getElementsByTagName ("contactEmail"))); - nm.setAuthority (getFirstValue (elem.getElementsByTagName ("authURI"))); - results[i] = nm; - } - - java.util.Arrays.sort (results); - return results; - } - - /************************************************************************** - * - * @deprecated Replaced by {@link #getFullNamespaces} that gives - * more information for the same price.

    - *************************************************************************/ - public Map getNamespaces() - throws MobyException { - - Map results = new TreeMap (getStringComparator()); - MobyNamespace[] namespaces = getFullNamespaces(); - for (int i = 0; i < namespaces.length; i++) { - results.put (namespaces[i].getName(), - namespaces[i].getDescription()); - } - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     *  <objectNames>
    -     *     <Object name="objectName" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *     </Object>
    -     *          ...
    -     *          ...
    -     *  </objectNames>
    -     * 
    - *************************************************************************/ - public Map getDataTypeNames() - throws MobyException { - String result = getDataTypeNamesAsXML(); - return createDataTypeNamesFromXML (result, true); - } - - // - protected String getDataTypeNamesAsXML() - throws MobyException { - return (String)doCall ("retrieveObjectNames", - new Object[] {}); - } - - // if onlyNames == true - // Map: data type name -> description (String) - // else - // Map: data type name -> MobyDataType[] - // (filled with name, description, and lsid) - protected Map createDataTypeNamesFromXML (String result, - boolean onlyNames) - throws MobyException { - - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Object"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String name = elem.getAttribute ("name"); - if (name == null) - continue; // ignore no-named data types - String desc = ""; - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("Description")) { - desc = getFirstValue (children.item (j)); - break; - } - } - if (onlyNames) { - results.put (name, desc); - } else { - MobyDataType dt = new MobyDataType (name); - dt.setDescription (desc); - dt.setLSID (elem.getAttribute ("lsid")); - results.put (name, dt); - } - } - return results; - } - - - /************************************************************************** - * Parses and imports the following XML. An example: - * - *
    -     * <retrieveObjectDefinition>
    -     *   <objectType lsid="...">go_term</objectType>
    -     *   <Description><![CDATA[A very lightweight object holding a GO term name and its definition]]></Description>
    -     *   <authURI>http://www.illuminae.com</authURI>
    -     *   <contactEmail>markw at illuminae.com</contactEmail>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *      <objectType articleName=''>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *   </Relationship>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    -     *      <objectType articleName='Term'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *      <objectType articleName='Definition'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *   </Relationship>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:has'>
    -     *      <objectType articleName='Problems'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *      <objectType articleName='Issues'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *   </Relationship>
    -     * </retrieveObjectDefinition>
    -     * 
    - *************************************************************************/ - public MobyDataType getDataType (String dataTypeName) - throws MobyException, NoSuccessException { - - String result = getDataTypeAsXML (dataTypeName); - return createDataTypeFromXML (result, dataTypeName); - } - - public MobyDataType[] getDataTypes() - throws MobyException, NoSuccessException { - Map datatypeMap = getDataTypeNames(); - MobyDataType[] datatypes = new MobyDataType[datatypeMap.size()]; - int i = 0; - for(String dataTypeName: datatypeMap.keySet()){ - datatypes[i++] = getDataType(dataTypeName); - } - return datatypes; - } - - protected String getDataTypeAsXML (String dataTypeName) - throws MobyException, NoSuccessException { - - return (String)doCall ("retrieveObjectDefinition", - new Object[] { - "" + - "" + dataTypeName + "" + - "" - }); - } - - protected MobyDataType createDataTypeFromXML (String xmlSource, String dataTypeName) - throws MobyException, NoSuccessException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (xmlSource.getBytes())); - NodeList list = document.getElementsByTagName ("retrieveObjectDefinition"); - if (list == null || list.getLength() == 0) - throw new NoSuccessException ("Data Type name was not found.", - dataTypeName); - MobyDataType data = null; - Element elem = (Element)list.item (0); - NodeList children = elem.getChildNodes(); - - // first find the "real" (LSID-ized) data type name - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("objectType")) { - data = new MobyDataType (getFirstValue (children.item (j))); - data.setLSID ( ((Element)children.item (j) ).getAttribute ("lsid")); - break; - } - } - - // if not found (unprobable) use the name given by the caller - if (data == null) - data = new MobyDataType (dataTypeName); - - // now fill the data type object with the rest of attributes - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("Description")) { - data.setDescription (getFirstValue (children.item (j))); - } else if (nodeName.equals ("authURI")) { - data.setAuthority (getFirstValue (children.item (j))); - } else if (nodeName.equals ("contactEmail")) { - data.setEmailContact (getFirstValue (children.item (j))); - } else if (nodeName.equals ("Relationship")) { - String relationshipType = ((Element)children.item (j)).getAttribute ("relationshipType"); - if (relationshipType.endsWith ("isa")) { - - NodeList parents = children.item (j).getChildNodes(); - for (int k = 0; k < parents.getLength(); k++) { - if (parents.item (k).getNodeName().equals ("objectType")) { - data.addParentName (getFirstValue (parents.item (k))); - } - } - } else if (relationshipType.endsWith ("hasa")) { - - NodeList belows = children.item (j).getChildNodes(); - for (int k = 0; k < belows.getLength(); k++) { - if (belows.item (k).getNodeName().equals ("objectType")) { - data.addChild ( ((Element)belows.item (k)).getAttribute ("articleName"), - getFirstValue (belows.item (k)), - Central.iHASA ); - } - } - } else if (relationshipType.endsWith ("has")) { - - NodeList belows = children.item (j).getChildNodes(); - for (int k = 0; k < belows.getLength(); k++) { - if (belows.item (k).getNodeName().equals ("objectType")) { - data.addChild ( ((Element)belows.item (k)).getAttribute ("articleName"), - belows.item (k).getFirstChild().getNodeValue(), - Central.iHAS ); - } - } - } - } - } - return data; - } - - /************************************************************************** - * - *************************************************************************/ - public String getServiceWSDL (String serviceName) - throws MobyException, NoSuccessException { - - Map names = getServiceNames(); - - for (Iterator it = names.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = (Map.Entry)it.next(); - if ( ((String)entry.getKey()).equals (serviceName) ) - return getServiceWSDL (serviceName, (String)entry.getValue()); - } - - throw new NoSuccessException ("Service not found.", serviceName); - } - - /************************************************************************** - * - *************************************************************************/ - public String getServiceWSDL (String serviceName, String authority) - throws MobyException, NoSuccessException { - - String cacheId = "getServiceWSDL" + serviceName + ":" + authority; - String cachedResults = (String)getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("retrieveService", - new Object[] { - "" + - "" + - "" - }); - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - Element service = document.getDocumentElement(); - Node wsdl = service.getFirstChild(); - if (wsdl == null) - throw new NoSuccessException ("Service not found OR WSDL is not available.", - serviceName + " (" + authority + ")"); - - String results = wsdl.getNodeValue(); - setContents (cacheId, results); - return results; - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterDataTypeXML (MobyDataType dataType) { - - // build the ISA tag (expressing hierarchy of data types) - String[] names = dataType.getParentNames(); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < names.length; i++) { - buf.append (""); - buf.append (names[i]); - buf.append (""); - buf.append ("\n"); - } - - // build the HASA/HAS tags (expressing containments of data types) - MobyRelationship[] children = dataType.getChildren(); - StringBuffer buf2 = new StringBuffer(); // for HASA - StringBuffer buf3 = new StringBuffer(); // for HAS - for (int i = 0; i < children.length; i++) { - if (children[i].getRelationshipType() == Central.iHASA) { - buf2.append (""); - buf2.append (children[i].getDataTypeName()); - buf2.append (""); - } else if (children[i].getRelationshipType() == Central.iHAS) { - buf3.append (""); - buf3.append (children[i].getDataTypeName()); - buf3.append (""); - } - } - - return - "" + - "" + dataType.getName() + "" + - "" + - "" + - "" + new String (buf) + - "" + - "" + new String (buf2) + - "" + - "" + new String (buf3) + - "" + - "" + dataType.getAuthority() + "" + - "" + dataType.getEmailContact() + "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerDataType (MobyDataType dataType) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerObjectClass", - new Object[] { getRegisterDataTypeXML (dataType) }); - dataType.setId (checkRegistration (result, dataType)[0]); - } - - /************************************************************************* - * B - *************************************************************************/ - public void unregisterDataType (MobyDataType dataType) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterObjectClass", - new Object[] { - "" + - "" + dataType.getName() + "" + - "" - }); - checkRegistration (result, dataType); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterServiceTypeXML (MobyServiceType serviceType) { - - // build the ISA tag (expressing hierarchy of service types) - String[] names = serviceType.getParentNames(); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < names.length; i++) { - buf.append (""); - buf.append (names[i]); - buf.append (""); - buf.append ("\n"); - } - - return - "" + - "" + serviceType.getName() + "" + - "" + serviceType.getEmailContact() + "" + - "" + serviceType.getAuthority() + "" + - "" + - "" + - "" + new String (buf) + - "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerServiceType (MobyServiceType serviceType) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerServiceType", - new Object[] { getRegisterServiceTypeXML (serviceType) }); - serviceType.setId (checkRegistration (result, serviceType)[0]); - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterServiceType (MobyServiceType serviceType) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterServiceType", - new Object[] { - "" + - "" + serviceType.getName() + "" + - "" - }); - checkRegistration (result, serviceType); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterNamespaceXML (MobyNamespace namespace) { - return - "" + - "" + namespace.getName() + "" + - "" + namespace.getEmailContact() + "" + - "" + namespace.getAuthority() + "" + - "" + - "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerNamespace (MobyNamespace namespace) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("registerNamespace", - new Object[] { getRegisterNamespaceXML (namespace) }); - namespace.setId (checkRegistration (result, namespace)[0]); - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterNamespace (MobyNamespace namespace) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterNamespace", - new Object[] { - "" + - "" + namespace.getName() + "" + - "" - }); - checkRegistration (result, namespace); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterServiceXML (MobyService service) { - return - "" + - "" + service.getCategory() + "" + - "" + service.getName() + "" + - "" + service.getType() + "" + - "" + (service.getLSID() == null ? "" : service.getLSID().trim() )+ "" + - "" + service.getAuthority() + "" + - "" + escapeXML (service.getSignatureURL()) + "" + - "" + escapeXML (service.getURL()) + "" + - "" + service.getEmailContact() + "" + - "" + (service.isAuthoritative() ? "1" : "0") + "" + - "" + - "" + - buildPrimaryInputTag (service) + - buildSecondaryInputTag (service) + - buildOutputTag (service) + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerService (MobyService service) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerService", - new Object[] { getRegisterServiceXML (service) }); - String[] registered = checkRegistration (result, service); - service.setId (registered [0]); - service.setRDF (registered [1]); - String pathToRDF = service.getPathToRDF(); - if ( ! pathToRDF.equals ("") ) { - File fileRDF = new File (pathToRDF); - try { - PrintStream fileout = new PrintStream (new FileOutputStream (fileRDF)); - fileout.println (registered [1]); - fileout.close(); - } catch (IOException e) { - StringBuffer buf = new StringBuffer (100); - buf.append ("Failed to save RDF in '"); - buf.append (fileRDF.getAbsolutePath() + "'. "); - buf.append (e.toString()); - try { - File tmpFile = File.createTempFile (service.getName() + "-", ".rdf"); - PrintStream fileout = new PrintStream (new FileOutputStream (tmpFile)); - fileout.println (registered [1]); - fileout.close(); - buf.append ("\nReturned RDF file was therefore stored in: "); - buf.append (tmpFile.getAbsolutePath()); - } catch (IOException e2) { - buf.append ("\nEven saving in a temporary file failed: "); - buf.append (e2.toString()); - } - throw new MobyException (buf.toString()); - } - } - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterService (MobyService service) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterService", - new Object[] { - "" + - "" + service.getAuthority() + "" + - "" + service.getName() + "" + - "" - }); - checkRegistration (result, service); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (String serviceType) - throws MobyException { - if (serviceType == null) - return new MobyService[] {}; - MobyService pattern = new MobyService ("dummy"); - pattern.setCategory (""); - pattern.setType (serviceType); - return findService (pattern, null); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (String[] keywords) - throws MobyException { - if (keywords == null) - return new MobyService[] {}; - return findService (null, keywords); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (MobyService pattern) - throws MobyException { - if (pattern == null) - return new MobyService[] {}; - return findService (pattern, null); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (MobyService pattern, String[] keywords) - throws MobyException { - return findService (pattern, keywords, true, true); - } - - /************************************************************************** - * All 'findService' methods end up here. - *************************************************************************/ - public MobyService[] findService (MobyService pattern, String[] keywords, - boolean includeChildrenServiceTypes, - boolean includeParentDataTypes) - throws MobyException { - if (pattern == null) { - pattern = new MobyService ("dummy"); - pattern.setCategory (""); - } - - String result = - getServicesAsXML (pattern, keywords, includeChildrenServiceTypes, includeParentDataTypes); - MobyService[] services = extractServices (result); - return services; - } - - // ...actually all 'findService' methods end up here - protected String getServicesAsXML (MobyService pattern, String[] keywords, - boolean includeChildrenServiceTypes, - boolean includeParentDataTypes) - throws MobyException { - String[] query = new String[] { - "" + - buildQueryObject (pattern, keywords, - includeParentDataTypes, - includeChildrenServiceTypes, - false) + - "" - }; - return (String)doCall ("findService", query); - } - - /************************************************************************** - * - *************************************************************************/ - public String call (String methodName, String inputXML) - throws MobyException { - Object result; - if (inputXML == null || inputXML.equals ("")) - result = doCall (methodName, new Object[] { }); - else - result = doCall (methodName, new Object[] { inputXML }); - return (String)result; - } - - /************************************************************************** - * - *************************************************************************/ - protected static String resultToString (Object result) - throws MobyException { - if (result == null) - throw new MobyException ("Returned result is null."); - if (result instanceof String) - return (String)result; - if (result instanceof String[]) { - String[] tmp = (String[])result; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < tmp.length; i++) - buf.append (tmp[i]); - return new String (buf); - } - if (result instanceof byte[]) - return new String ((byte[])result); - - throw new MobyException ("Unknown type of result: " + result.getClass().getName()); - } - - /************************************************************************** - * - *************************************************************************/ - public boolean setDebug (boolean enabled) { - boolean oldMode = debug; - debug = enabled; - return oldMode; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     * <Relationships>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:servicerelation:isa'>
    -     *     <serviceType>urn:lsid:biomoby.org:servicetype:analysis</serviceType>
    -     *     <serviceType>urn:lsid:biomoby.org:servicetype:service</serviceType>
    -     *   </Relationship>
    -     * </Relationships>
    -     * 
    - *************************************************************************/ - public String[] getServiceTypeRelationships (String serviceTypeName, - boolean expand) - throws MobyException { - String result = getServiceTypeRelationshipsAsXML (serviceTypeName, expand); - return createServiceTypeRelationshipsFromXML (result); - } - - // - protected String getServiceTypeRelationshipsAsXML (String serviceTypeName, - boolean expand) - throws MobyException { - return - (String)doCall ("Relationships", - new Object[] { - "" + - "" + serviceTypeName + "" + - "" + Central.ISA + "" + - "" + (expand ? "1" : "0") + "" + - "" - }); - } - - // - protected String[] createServiceTypeRelationshipsFromXML (String result) - throws MobyException { - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("serviceType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - } - String[] results = new String [v.size()]; - v.copyInto (results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *<Relationships>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *  </Relationship>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:integer</objectType>
    -     *  </Relationship>
    -     *</Relationships>
    -     * 
    - * - * Added at Sun Feb 19 19:32:31 PHT 2006: it recognizes also an - * attributes 'lsid' and 'articleName' in <objectType> element. - *************************************************************************/ - public Map getDataTypeRelationships (String dataTypeName) - throws MobyException { - - String cacheId = "getDataTypeRelationships_" + dataTypeName; - Map cachedResults = (Map)getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("Relationships", - new Object[] { - "" + - "" + dataTypeName + "" + - "" + Central.ISA + "" + - "" + Central.HASA + "" + - "" + Central.HAS + "" + - "1" + - "" - }); - - // parse returned XML - Map results = new HashMap(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String relType = elem.getAttribute ("relationshipType"); - NodeList children = elem.getChildNodes(); - Vector v = new Vector(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("objectType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - String[] names = new String [v.size()]; - v.copyInto (names); - results.put (relType, names); - } - - setContents (cacheId, results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *<Relationships>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *  </Relationship>
    -     *</Relationships>
    -     * 
    - *************************************************************************/ - public String[] getDataTypeRelationships (String dataTypeName, - String relationshipType) - throws MobyException { - - String cacheId = "getDataTypeRelationships_" + dataTypeName + ":" + relationshipType; - String[] cachedResults = (String[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("Relationships", - new Object[] { - "" + - "" + dataTypeName + "" + - "" + relationshipType + "" + - "1" + - "" - }); - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - - // it should always be just one element in this list - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("objectType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - } - String[] results = new String [v.size()]; - v.copyInto (results); - - setContents (cacheId, results); - return results; - } - -// /************************************************************************** -// * -// *************************************************************************/ -// public MobyRelationship[] getRelationships (String dataTypeName) -// throws MobyException { -// return null; -// } - - - /************************************************************************** - * - *************************************************************************/ - public String getRegistryEndpoint() { - return endpoint.toString(); - } - - /************************************************************************** - * - *************************************************************************/ - public String getRegistryNamespace() { - return uri; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     * <resourceURLs>
    -     *   <Resource name="Service"         url="..." />
    -     *   <Resource name="Object"          url="..." />
    -     *   <Resource name="Namespace"       url="..." />
    -     *   <Resource name="ServiceInstance" url="..." />
    -     *   <Resource name="Full"            url="..." />
    -     * </resourceURLs>
    -     * 
    - *************************************************************************/ - public MobyResourceRef[] getResourceRefs() - throws MobyException { - - String cacheId = "retrieveResourceURLs"; - MobyResourceRef[] cachedResults = (MobyResourceRef[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = (String)doCall ("retrieveResourceURLs", - new Object[] {}); - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Resource"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - try { - v.addElement - (new MobyResourceRef (elem.getAttribute ("name"), - new URL ((String)elem.getAttribute ("url")), - elem.getAttribute ("type"))); - } catch (MalformedURLException e2) { - if (debug) - System.err.println ("Bad URL: " + elem.getAttribute ("url")); - } - } - - MobyResourceRef[] results = new MobyResourceRef [v.size()]; - v.copyInto (results); - - // Add this data to the cache in case we get called again - setContents (cacheId, results); - - return results; - } - - /************************************************************************** - * - *************************************************************************/ - public InputStream getResource (String resourceName) - throws MobyException { - - MobyResourceRef[] resourceRefs = getResourceRefs(); - for (int i = 0; i < resourceRefs.length; i++) { - if (resourceName.equalsIgnoreCase (resourceRefs[i].getResourceName())) { - return Utils.getInputStream (resourceRefs[i].getResourceLocation()); - } - } - throw new MobyException ("No resource found for '" + resourceName + "'."); - } - - /************************************************************************** - * Return a case-insensitive comparator of Strings. It is used to - * create various TreeMaps where keys are strings. - *************************************************************************/ - protected static Comparator getStringComparator() { - return new Comparator() { - public int compare (Object o1, Object o2) { - return ((String)o1).compareToIgnoreCase ((String)o2); - } - }; - } - - // cache URL/URI so we only check once - private static String CHECKED_URL = null; - private static String CHECKED_URI = null; - - /** - * Using this method to get a Central object will ensure that other parts of the org.biomoby.shared - * class hierarchy that implicitly check the registry will use the same cache. Otherwise, methods - * such as MobyNamespace.getNamespace() must be passed a Central object parameter as well. - * - * @return a CentralImpl using the default Central URI, and currently a class implementing a caching mechanism - */ - public static CentralImpl getDefaultCentral() throws MobyException{ - return getDefaultCentral(null); - } - - public static CentralImpl getDefaultCentral(Registry reg) throws MobyException{ - if(reg == null && defaultCentrals.containsKey("")){ - return defaultCentrals.get(""); - } - else if(reg != null && defaultCentrals.containsKey(reg.getEndpoint())){ - return defaultCentrals.get(reg.getEndpoint()); - } - - String className = DEFAULT_CENTRAL_IMPL_CLASSNAME; - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - URL resURL = classLoader.getResource("META-INF/"+CENTRAL_IMPL_RESOURCE_NAME); - if(resURL != null){ - System.err.println("Loading "+resURL); - try{ - LineNumberReader reader = new LineNumberReader(new InputStreamReader(resURL.openStream())); - for(String line = reader.readLine(); line != null; line = reader.readLine()){ - if(!line.trim().startsWith("#")){ - className = line.trim(); - break; - } - } - } catch(Exception e){ - logger.log(Level.WARNING, - "Error reading " + resURL, - e); - } - } - try{ - System.err.println("Central class is "+className); - Class clazz = Class.forName(className); - if(reg == null){ // should use default nullary c-tor - defaultCentrals.put("", (CentralImpl) clazz.newInstance()); - } - else{ // should have (String endpoint, String namespace) c-tor - for(Constructor ctor: clazz.getDeclaredConstructors()){ - Class[] params = ctor.getParameterTypes(); - if(params.length == 2 && params[0].getName().equals("java.lang.String") && - params[1].getName().equals("java.lang.String") ){ - defaultCentrals.put(reg.getEndpoint(), - (CentralImpl) ctor.newInstance(reg.getEndpoint(), reg.getNamespace())); - break; - } - } - if(!defaultCentrals.containsKey(reg.getEndpoint())){ - logger.log(Level.WARNING, - "Could not find required (String endpoint, String namespace)" + - "constructor for class " + className); - } - } - } catch(Exception e){ - logger.log(Level.WARNING, - "Could not load class " + className, - e); - if(reg == null){ - defaultCentrals.put("", new CentralImpl()); //fallback to this class, no caching, etc. - } - else{ - defaultCentrals.put(reg.getEndpoint(), - new CentralImpl(reg.getEndpoint(), reg.getNamespace())); - } - } - - return defaultCentrals.get(reg == null ? "" : reg.getEndpoint()); - } - - /** - * - * @return a String representing the Default mobycentral endpoint. If the - * system property 'moby.check.default' exists and is set to true, - * then the URL http://biomoby.org/mobycentral is queried and the - * default central endpoint is returned, otherwise DEFAULT_ENDPOINT - * is returned. - */ - public static String getDefaultURL() { - boolean check = false; - try { - check = Boolean.getBoolean("moby.check.default"); - } catch (Exception e) { - - } - - if (check) { - // return the last checked url if we have done this before - if (CHECKED_URL != null && CHECKED_URL.trim() != "") { - return CHECKED_URL; - } - - // create a HttpClient object - HttpClient client = new HttpClient(); - // set up the Head method - HeadMethod method = new HeadMethod("http://biomoby.org/mobycentral"); - // do not follow redirects or we will get a 411 error - method.setFollowRedirects(false); - // retry 3 times - method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false)); - // set the user agent ... should probably make this something more reasonable - method.getParams().setParameter(HttpMethodParams.USER_AGENT,"jMoby/1.0"); - try { - // Execute the method. - int statusCode = client.executeMethod(method); - - if (statusCode != HttpStatus.SC_MOVED_PERMANENTLY) { - System.err.println("Method failed: " - + method.getStatusLine()); - } else { - try { - String location = method.getResponseHeader("location").getValue(); - CHECKED_URL = location; - try { - CHECKED_URI = "http://" + (new URL(CHECKED_URL).getAuthority()) + "/MOBY/Central"; - } catch (MalformedURLException murle ) { - CHECKED_URI = DEFAULT_NAMESPACE; - } - return CHECKED_URL; - } catch (NullPointerException npe) { - return DEFAULT_ENDPOINT; - } - } - } catch (HttpException e) { - System.err.println("Fatal protocol violation: " - + e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - System.err.println("Fatal transport error: " + e.getMessage()); - e.printStackTrace(); - } finally { - // Release the connection. - method.releaseConnection(); - } - - } else { - return DEFAULT_ENDPOINT; - } - return DEFAULT_ENDPOINT; - } - - /** - * - * @return a String representing the default mobycentral uri. If the - * system property 'moby.check.default' exists and is set to true, - * then the URL http://biomoby.org/mobycentral is queried and the - * default central namespace is returned, otherwise DEFAULT_NAMESPACE - * is returned. - */ - public static String getDefaultURI() { - boolean check = false; - try { - check = Boolean.getBoolean("moby.check.default"); - } catch (Exception e) { - - } - if (check) { - if (CHECKED_URI != null && CHECKED_URI.trim() != "") { - return CHECKED_URI; - } - // need to check ... - getDefaultURL(); - return CHECKED_URI; - } else { - return DEFAULT_NAMESPACE; - } - } - /************************************************************************** - * Convert non-suitable characters in a XML string into their - * entity references.

    - * - * Adapted from jDom. - * - * @param str input to be converted - * @return If there were any non-suitable characters, return a new - * string with those characters escaped, otherwise return the - * unmodified input string - * - *************************************************************************/ - public String escapeXML (String str) { - StringBuffer buffer = null; - char ch; - String entity; - for (int i = 0; i < str.length(); i++) { - ch = str.charAt (i); - switch (ch) { - case '<' : - entity = "<"; - break; - case '>' : - entity = ">"; - break; - case '&' : - entity = "&"; - break; - default : - entity = null; - break; - } - if (buffer == null) { - if (entity != null) { - // An entity occurred, so we'll have to use StringBuffer - // (allocate room for it plus a few more entities). - buffer = new StringBuffer (str.length() + 20); - // Copy previous skipped characters and fall through - // to pickup current character - buffer.append (str.substring (0, i)); - buffer.append (entity); - } - } else { - if (entity == null) { - buffer.append (ch); - } else { - buffer.append (entity); - } - } - } - - // If there were any entities, return the escaped characters - // that we put in the StringBuffer. Otherwise, just return - // the unmodified input string. - return (buffer == null) ? str : buffer.toString(); - } - - /************************************************************************* - * Format an exception. - *************************************************************************/ - public static String formatFault (AxisFault e, String endpoint, QName method) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - formatFault (e, new PrintStream (baos), endpoint, method); - return baos.toString(); - } - - /************************************************************************* - * Format an exception. - *************************************************************************/ - public static void formatFault (AxisFault e, PrintStream out, - String endpoint, QName method) { - - out.println ("===ERROR==="); - out.println ("Fault details:"); - // for some obvious errors I do not print all details (with a lenghty trace stack) - String faultString = e.getFaultString(); - if ( (! faultString.startsWith ("java.net.ConnectException")) && - (faultString.indexOf ("Could not find class for the service named:") == -1) - ) { - org.w3c.dom.Element[] details = e.getFaultDetails(); - for (int i = 0; i < details.length; i++) { - String s = details[i].toString().replaceAll ("<", "<"); - s = s.replaceAll (">", ">"); - out.println (s); - } - } - out.println ("Fault string: " + faultString); - out.println ("Fault code: " + e.getFaultCode()); - out.println ("Fault actor: " + e.getFaultActor()); - if (endpoint != null || method != null) - out.println ("When calling:"); - if (endpoint != null) - out.println ("\t" + endpoint); - if (method != null) - out.println ("\t" + method); - out.println ("==========="); - } - - -} +// CentralImpl.java +// A default client to the Moby Central service. +// +// senger at ebi.ac.uk +// February 2003 +// + +package org.biomoby.client; + +import org.biomoby.registry.meta.Registry; +import org.biomoby.shared.Central; +import org.biomoby.shared.MobyData; +import org.biomoby.shared.MobyDataType; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyNamespace; +import org.biomoby.shared.MobyPrimaryDataSet; +import org.biomoby.shared.MobyPrimaryDataSimple; +import org.biomoby.shared.MobyRelationship; +import org.biomoby.shared.MobySecondaryData; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.MobyServiceType; +import org.biomoby.shared.NoSuccessException; +import org.biomoby.shared.PendingCurationException; +import org.biomoby.shared.MobyResourceRef; +import org.biomoby.shared.Utils; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.namespace.QName; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.apache.axis.AxisFault; +import org.apache.axis.client.Call; +import org.apache.axis.client.Service; +import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.HeadMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.PrintStream; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.Vector; +import java.util.TreeMap; +import java.util.Comparator; +import java.util.zip.GZIPInputStream; +import java.util.logging.*; + +/** + * A default implementation of the interface {@link org.biomoby.shared.Central Central} allowing access to a Moby + * registry. + *

    + * This class is supposed to be used by all other clients that wish to communicate with the Moby Registry, but do not + * want to know about all XML details that are necessary for talking with the Moby Central directly. This is an example + * of a client program: + * + *

    + * import org.biomoby.shared.Central;
    + * import org.biomoby.shared.MobyException;
    + * import org.biomoby.client.CentralImpl;
    + * import java.util.Map;
    + * import java.util.Iterator;
    + * 
    + * public class Test {
    + * 
    + *     public static void main( String[] args ) throws MobyException {
    + * 
    + *         Central worker = new CentralImpl();
    + *         Map authorities = worker.getServiceNamesByAuthority();
    + * 
    + *         for ( Iterator it = authorities.entrySet().iterator(); it.hasNext(); ) {
    + *             Map.Entry entry = ( Map.Entry ) it.next();
    + *             System.out.println( entry.getKey() );
    + *             String[] names = ( String[] ) entry.getValue();
    + *             for ( int i = 0; i < names.length; i++ )
    + *                 System.out.println( "\t" + names[ i ] );
    + *         }
    + *     }
    + * }
    + * 
    + * + * @author Martin Senger + * @version $Id$ + */ + +public class CentralImpl implements Central, SimpleCache { + + private URL endpoint; + private String uri; + protected boolean debug = false; + + /** Common central used to if getDefaultCentral() is called */ + protected static Map< String, CentralImpl > defaultCentrals = new HashMap< String, CentralImpl >(); + + /** Default location (endpoint) of a Moby registry. */ + public static final String DEFAULT_ENDPOINT = "http://moby.ucalgary.ca/moby/MOBY-Central.pl"; + + /** Default namespace used by the contacted Moby registry. */ + public static final String DEFAULT_NAMESPACE = "http://moby.ucalgary.ca/MOBY/Central"; + + /** + * The META-INF resource file that will be checked to determine what default class should be instantiated in order + * to create a Central Implementation when getDefaultCentral() is called. + */ + public static final String CENTRAL_IMPL_RESOURCE_NAME = "org.biomoby.shared.CentralDefaultImpl"; + /** The class to use for getDefaultCentral if all else fails */ + public static final String DEFAULT_CENTRAL_IMPL_CLASSNAME = "org.biomoby.client.CentralDigestCachedImpl"; + private static Logger logger = Logger.getLogger( "org.biomoby.client.CentralImpl" ); + + /** + * Thread local that gives each thread its own DocumentBuilderFactory (since it is not thread-safe). Code taken from + * Apache's JaxpUtils. + */ + public static ThreadLocal DOCUMENT_BUILDER_FACTORIES = new ThreadLocal() { + protected synchronized Object initialValue() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware( true ); + return dbf; + } + }; + + /******************************************************************************************************************* + * Default constructor. It connects to a default Moby registry (as defined in {@link #DEFAULT_ENDPOINT}) using a + * default namespace (as defined int {@link #DEFAULT_NAMESPACE}). + ******************************************************************************************************************/ + public CentralImpl() throws MobyException { + this( DEFAULT_ENDPOINT, DEFAULT_NAMESPACE ); + } + + /******************************************************************************************************************* + * Constructor allowing to specify which Moby Registry to use. + * + * @throws MobyException + * if 'endpoint' is not a valid URL, or if no DOM parser is available + ******************************************************************************************************************/ + public CentralImpl( String endpoint ) throws MobyException { + this( endpoint, DEFAULT_NAMESPACE ); + } + + /******************************************************************************************************************* + * Constructor allowing to specify which Moby Registry and what namespace to use. If any of the parameters is null, + * its default value is used instead. + *

    + * + * @throws MobyException + * if 'endpoint' is not a valid URL, or if no DOM parser was found + ******************************************************************************************************************/ + public CentralImpl( String endpoint, String namespace ) throws MobyException { + + if ( endpoint == null || "".equals( endpoint.trim() ) ) endpoint = DEFAULT_ENDPOINT; + if ( namespace == null || "".equals( namespace.trim() ) ) namespace = DEFAULT_NAMESPACE; + + try { + this.endpoint = new URL( endpoint ); + } + catch ( MalformedURLException e ) { + throw new MobyException( "Bad URL: " + endpoint ); + } + this.uri = namespace; + + cache = new Hashtable< String, Object >(); + useCache = true; + } + + /******************************************************************************************************************* + * Loads a DOM Document from an InputStream. Uses thread-safe mechanism. + ******************************************************************************************************************/ + public static Document loadDocument( InputStream input ) throws MobyException { + try { + DocumentBuilderFactory dbf = ( DocumentBuilderFactory ) DOCUMENT_BUILDER_FACTORIES.get(); + DocumentBuilder db = dbf.newDocumentBuilder(); + return ( db.parse( input ) ); + } + catch ( Exception e ) { + throw new MobyException( "Problem with reading XML input: " + e.toString(), e ); + } + } + + /******************************************************************************************************************* + * Call 'method' with 'parameters' and return its result. + ******************************************************************************************************************/ + protected Object doCall( String method, Object[] parameters ) throws MobyException { + + Call call = null; + try { + Service service = new Service(); + call = ( Call ) service.createCall(); + call.setTargetEndpointAddress( endpoint ); + call.setTimeout( new Integer( 0 ) ); + + String user = System.getProperty( "user" ); + String password = System.getProperty( "password" ); + + if ( user != null && password != null ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, password ); + } + + call.setSOAPActionURI( uri + "#" + method ); + + if ( debug ) { + System.err.println( "METHOD CALL: " + method ); + System.err.println( "------------" ); + if ( parameters.length > 0 ) System.err.println( parameters[ 0 ] + "\n" ); + System.err.println( "------------\n" ); + + Object result = call.invoke( uri, method, parameters ); + + System.err.println( "METHOD RETURN:" ); + System.err.println( "------------" ); + if ( result != null ) System.err.println( result + "\n" ); + System.err.println( "------------\n" ); + + return resultToString( result ); + + } + else { + return resultToString( call.invoke( uri, method, parameters ) ); + } + + } + catch ( AxisFault e ) { + throw new MobyException( formatFault( e, endpoint.toString(), ( call == null ? null : call + .getOperationName() ) ), e ); + // (endpoint.toString()+(call == null ? "" : call.getOperationName()), e); + + } + catch ( Exception e ) { + throw new MobyException( e.toString(), e ); + // e.printStackTrace(); + } + } + + /******************************************************************************************************************* + * Parse the given XML sniplet to find tag 'success'. If it has value '1' look further for tag 'id' and return it + * back (or return an empty string if ID is not there). Otherwise raise an exception with the 'culprit' and with the + * message from the tag 'message'. + *

    + * + * The return value is a two-element long array. The first element is the ID (given by BioMobe registry), and the + * second element is RDF corresponding with the registered object (BioMoby returns this only for service instances, + * so for other objects this will be null). + *

    + * + * This is how the XML is supposed to look: + * + * Success takes the value "1" to indicate success, "0" to indicate failure, and "-1" to indicate "Pending + * Curation". + ******************************************************************************************************************/ + protected String[] checkRegistration( String xml, Object culprit ) throws MobyException, NoSuccessException, + PendingCurationException { + + String id = "", success = "0", message = "", rdf = ""; + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( xml.getBytes() ) ); + Element root = document.getDocumentElement(); + + NodeList children = root.getChildNodes(); + for ( int i = 0; i < children.getLength(); i++ ) { + if ( children.item( i ).getNodeType() != Node.ELEMENT_NODE ) continue; + Element elem = ( Element ) children.item( i ); + if ( elem.getNodeName().equals( "id" ) ) { + if ( elem.getFirstChild() != null ) id = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "success" ) ) { + if ( elem.getFirstChild() != null ) success = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "message" ) ) { + if ( elem.getFirstChild() != null ) message = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "RDF" ) ) { + if ( elem.getFirstChild() != null ) rdf = elem.getFirstChild().getNodeValue(); + } + } + + if ( success.equals( "0" ) ) + throw new NoSuccessException( message, culprit ); + else if ( success.equals( "-1" ) ) throw new PendingCurationException(); + return new String[] { id, rdf }; + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing input data types and their usage in the given + * service. Only data considered primary are included. Note that the main job of converting to XML is done by + * instances of MobyPrimaryData. + * + * The returned XML looks like this: + ******************************************************************************************************************/ + protected String buildPrimaryInputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] primaryInputs = service.getPrimaryInputs(); + buf.append( "\n" ); + for ( int i = 0; i < primaryInputs.length; i++ ) + buf.append( primaryInputs[ i ].toXML() ); + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing input data types and their usage in the given + * service. Only data considered secondary are included. Note that the main job of converting to XML is done by + * instances of MobySecondaryData. + * + * The returned XML looks like this: + * + ******************************************************************************************************************/ + protected String buildSecondaryInputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] secInputs = service.getSecondaryInputs(); + buf.append( "\n" ); + for ( int i = 0; i < secInputs.length; i++ ) { + buf.append( secInputs[ i ].toXML() ); + } + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing output data types and their usage in the given + * service. Only data considered primary are included. Note that the main job of converting to XML is done by + * instances of MobyPrimaryData. + * + * The returned XML looks like this: + * + * + ******************************************************************************************************************/ + protected String buildOutputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] primaryOutputs = service.getPrimaryOutputs(); + buf.append( "\n" ); + for ( int i = 0; i < primaryOutputs.length; i++ ) + buf.append( primaryOutputs[ i ].toXML() ); + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML represented a query object (an object used to find a service). + * + * The returned XML looks like this: + * + * + * + * ServiceTypeTerm ServiceName moby + * http://desired.service.provider; 1|0 1|0 + * 1|0 something .... .... + ******************************************************************************************************************/ + protected String buildQueryObject( MobyService service, String[] keywords, boolean expandObjects, + boolean expandServices, boolean authoritative ) { + if ( service == null ) { + service = new MobyService( "dummy" ); + service.setCategory( "" ); + } + StringBuffer buf = new StringBuffer(); + + buf.append( "\n\n" ); + MobyData[] pi = service.getPrimaryInputs(); + if ( pi.length > 0 ) { + for ( int i = 0; i < pi.length; i++ ) + buf.append( pi[ i ].toXML() ); + } + buf.append( "\n\n" ); + + buf.append( "\n\n" ); + MobyData[] po = service.getPrimaryOutputs(); + if ( po.length > 0 ) { + for ( int i = 0; i < po.length; i++ ) + buf.append( po[ i ].toXML() ); + } + buf.append( "\n\n" ); + + buf.append( "" + service.getType() + "\n" ); + + String name = service.getName(); + if ( !name.equals( "" ) && !name.equals( "dummy" ) && !name.equals( MobyService.DUMMY_NAME ) ) + buf.append( "" + service.getName() + "\n" ); + + String sigURL = service.getSignatureURL(); + if ( !sigURL.equals( "" ) ) buf.append( "" + sigURL + "\n" ); + + buf.append( "" + service.getCategory() + "\n" ); + buf.append( "" + service.getAuthority() + "\n" ); + + buf.append( "" ); + buf.append( expandObjects ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "" ); + buf.append( expandServices ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "" ); + buf.append( authoritative ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "\n" ); + if ( keywords != null && keywords.length > 0 ) { + for ( int i = 0; i < keywords.length; i++ ) { + buf.append( "" ); + buf.append( keywords[ i ] ); + buf.append( "\n" ); + } + } + buf.append( "\n" ); + + return new String( buf ); + } + + /******************************************************************************************************************* + * Extract one or more MobyService objects from the given XML piece. The XML should look like this: + * + *

    +     *  <Services>
    +     *    <Service authURI="authority.URI.here" lsid="..." serviceName="MyService">
    +     *      <serviceType>Service_Ontology_Term</serviceType>
    +     *      <Category>moby</Category> <!-- or 'cgi' or 'soap' -->
    +     *      <contactEmail>your at email.addy.here</contactEmail>
    +     *      <signatureURL>http://service.RDF.here</signatureURL>
    +     *      <URL>http://service.endpoint.here/scriptname</URL>
    +     *      <authoritative>1</authoritative>
    +     *      <Input>
    +     *           <!-- one or more Simple and/or Complex Primary articles -->
    +     *      </Input>
    +     *      <Output>
    +     *           <!-- one or more Simple and/or Complex Primary articles --> 
    +     *      </Output>
    +     *      <secondaryArticles>
    +     *           <!-- one or more Secondary articles -->
    +     *      </secondaryArticles>
    +     *      <Description><![CDATA[free text description here]]></Description>
    +     *    </Service>
    +     *    ...  <!--  one or more Service blocks may be returned -->
    +     *    ...
    +     *    ...
    +     *  </Services>
    +     * 
    + * + * @throws MobyException + * if the XML document is invalid + ******************************************************************************************************************/ + public MobyService[] extractServices( String xml ) throws MobyException { + + Document document = loadDocument( new ByteArrayInputStream( xml.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Service" ); + MobyService[] results = new MobyService[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyService service = new MobyService( elem.getAttribute( "serviceName" ) ); + service.setAuthority( elem.getAttribute( "authURI" ) ); + service.setLSID( elem.getAttribute( "lsid" ) ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "Description" ) ) { + service.setDescription( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "Category" ) ) { + service.setCategory( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "URL" ) ) { + service.setURL( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "signatureURL" ) ) { + service.setSignatureURL( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "contactEmail" ) ) { + service.setEmailContact( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "serviceType" ) ) { + service.setType( getFirstValue( children.item( j ) ) ); + MobyServiceType mst = new MobyServiceType( service.getType() ); + NamedNodeMap map = ( children.item( j ).getAttributes() ); + if ( map != null ) { + Node node = map.getNamedItemNS( children.item( j ).getNamespaceURI(), "lsid" ); + if ( node != null ) mst.setLSID( node.getNodeValue() ); + } + service.setServiceType( mst ); + } + else if ( nodeName.equals( "authoritative" ) ) { + String authoritative = getFirstValue( children.item( j ) ); + service.setAuthoritative( authoritative.equals( "1" ) ? true : false ); + } + else if ( nodeName.equals( "Input" ) ) { + // + // + // + // ... + // + // + // ...... + // ...... + // + // + NodeList inputs = children.item( j ).getChildNodes(); + for ( int k = 0; k < inputs.getLength(); k++ ) { + if ( inputs.item( k ).getNodeName().equals( "Simple" ) ) { + MobyPrimaryDataSimple data = new MobyPrimaryDataSimple( ( Element ) inputs.item( k ) ); + service.addInput( data ); + } + else if ( inputs.item( k ).getNodeName().equals( "Collection" ) ) { + MobyPrimaryDataSet data = new MobyPrimaryDataSet( ( Element ) inputs.item( k ) ); + service.addInput( data ); + } + } + } + else if ( nodeName.equals( "Output" ) ) { + // + // + // + NodeList inputs = children.item( j ).getChildNodes(); + for ( int k = 0; k < inputs.getLength(); k++ ) { + if ( inputs.item( k ).getNodeName().equals( "Simple" ) ) { + MobyPrimaryDataSimple data = new MobyPrimaryDataSimple( ( Element ) inputs.item( k ) ); + service.addOutput( data ); + } + else if ( inputs.item( k ).getNodeName().equals( "Collection" ) ) { + MobyPrimaryDataSet data = new MobyPrimaryDataSet( ( Element ) inputs.item( k ) ); + service.addOutput( data ); + } + } + + } + else if ( nodeName.equals( "secondaryArticles" ) ) { + // + // ... + // + NodeList parameters = children.item( j ).getChildNodes(); + for ( int k = 0; k < parameters.getLength(); k++ ) { + if ( parameters.item( k ).getNodeName().equals( "Parameter" ) ) { + MobySecondaryData data = new MobySecondaryData( ( Element ) parameters.item( k ) ); + service.addInput( data ); + } + } + } + } + results[ i ] = service; + } + return results; + } + + // protect against null values + protected String getFirstValue( Node child ) { + Node node = child.getFirstChild(); + if ( node == null ) return ""; + String value = node.getNodeValue(); + if ( value == null ) return ""; + return value; + } + + protected String getFirstValue( NodeList children ) { + if ( children.item( 0 ) != null && children.item( 0 ).hasChildNodes() ) { + children.item( 0 ).normalize(); + return getFirstValue( children.item( 0 ) ); + } + return ""; + } + + /******************************************************************************************************************* + * + * Implementing SimpleCache interface. + * + * Why to have an interface for such trivial thing? Well, because I needed to overwrite the caching mechanism in the + * subclasses so I needed to have all caching functions as separate methods - that's why I have collect them in an + * interface. + * + ******************************************************************************************************************/ + private Hashtable< String, Object > cache; // this is the cache itself + private boolean useCache; // this signal that we are actually caching things + + // not used here + public String createId( String rootName, String semanticType, String syntaxType, long lastModified, Properties props ) { + return ""; // not used here + } + + // check existence of a cached object + public boolean existsInCache( String id ) { + synchronized ( cache ) { + if ( useCache ) + return cache.containsKey( id ); + else + return false; + } + } + + // retrieve from cache + public Object getContents( String id ) { + synchronized ( cache ) { + if ( useCache ) + return cache.get( id ); + else + return null; + } + } + + // cache an object + public void setContents( String id, java.lang.Object data ) { + synchronized ( cache ) { + if ( useCache ) cache.put( id, data ); + } + } + + // in this implementation, it clears the whole cache, regardless + // what 'id' is passed + public void removeFromCache( String id ) { + cache.clear(); + } + + /******************************************************************************************************************* + * + * And the other methods related to caching (but not part of the SimpleCache interface). + * + ******************************************************************************************************************/ + + /******************************************************************************************************************* + * By default, caching is enabled to reduce network traffic. Setting this to false will clear the cache, and not + * cache any further calls unless it is set to true again. + *

    + * + * @param shouldCache + * whether retrieveXXX call results should be cached in case they are called again (i.e. don't request + * MobyCentral every time) + ******************************************************************************************************************/ + public void setCacheMode( boolean shouldCache ) { + useCache = shouldCache; + if ( !useCache ) removeFromCache( null ); + } + + /******************************************************************************************************************* + * Find if caching is currently enabled. + * + * @return true if caching is enabled + ******************************************************************************************************************/ + public boolean getCacheMode() { + return useCache; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     * <serviceNames>
    +     *   <serviceName name="serviceName" authURI='authority.info.here'/>
    +     *   ...
    +     *   ...
    +     * </serviceNames>
    +     * 
    + * + * @deprecated Replaced by {@link #getServiceNamesByAuthority}. The reason is that this method returns a random + * result if there are more services with the same name but belonging to different authorities. + *

    + * + ******************************************************************************************************************/ + public Map< String, String > getServiceNames() throws MobyException { + + String result = ( String ) doCall( "retrieveServiceNames", new Object[] {} ); + // parse returned XML + Map< String, String > results = new TreeMap< String, String >( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceName" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + results.put( elem.getAttribute( "name" ), elem.getAttribute( "authURI" ) ); + } + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     * <serviceNames>
    +     *   <serviceName name="serviceName" lsid="..." authURI='authority.info.here'/>
    +     *   ...
    +     *   ...
    +     * </serviceNames>
    +     * 
    + * + * @return a Map which has authorities as keys, and String arrays with service names as a values. + ******************************************************************************************************************/ + public Map getServiceNamesByAuthority() throws MobyException { + String result = getServiceNamesByAuthorityAsXML(); + return createServicesByAuthorityFromXML( result, true ); + } + + /******************************************************************************************************************* + * Similar to {@link #getServiceNamesByAuthority} but the resulting Map contains slightly more. + *

    + * + * @return a Map which has authorities as keys, and arrays of MobyServices as a values. Each MobyService is filled + * with its name, authority and LSID. + ******************************************************************************************************************/ + public Map getServicesByAuthority() throws MobyException { + String result = getServiceNamesByAuthorityAsXML(); + return createServicesByAuthorityFromXML( result, false ); + } + + // + protected String getServiceNamesByAuthorityAsXML() throws MobyException { + return ( String ) doCall( "retrieveServiceNames", new Object[] {} ); + } + + // if onlyNames == true + // Map: authority name -> String[] + // (filled with service namea) + // else + // Map: authority name -> MobyService[] + // (filled with service name, authority and lsid) + protected Map createServicesByAuthorityFromXML( String result, boolean onlyNames ) throws MobyException { + + // parse returned XML + Map results = new TreeMap( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceName" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String name = elem.getAttribute( "name" ); + String auth = elem.getAttribute( "authURI" ); + Vector< Object > v = ( results.containsKey( auth ) ? ( Vector ) results.get( auth ) + : new Vector< Object >() ); + if ( onlyNames ) { + v.addElement( name ); + } + else { + MobyService ms = new MobyService( name ); + ms.setAuthority( auth ); + ms.setLSID( elem.getAttribute( "lsid" ) ); + v.addElement( ms ); + } + results.put( auth, v ); + } + + // change values of type Vector to MobyService[] or String[] + for ( Iterator it = results.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = ( Map.Entry ) it.next(); + Vector v = ( Vector ) entry.getValue(); + if ( onlyNames ) { + String[] sNames = new String[ v.size() ]; + v.copyInto( sNames ); + entry.setValue( sNames ); + } + else { + MobyService[] mss = new MobyService[ v.size() ]; + v.copyInto( mss ); + entry.setValue( mss ); + } + } + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     *  <serviceProviders>
    +     *     <serviceProvider name="authority.URI.here"/>
    +     *          ...
    +     *          ...
    +     *  </serviceProviders>
    +     * 
    + ******************************************************************************************************************/ + public String[] getProviders() throws MobyException { + + String cacheId = "retrieveServiceProviders"; + String[] cachedResults = ( String[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveServiceProviders", new Object[] {} ); + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceProvider" ); + String[] results = new String[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) + results[ i ] = ( ( Element ) list.item( i ) ).getAttribute( "name" ); + + // Add this data to the cache in case we get called again + setContents( cacheId, results ); + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     *  <serviceTypes>
    +     *     <serviceType name="serviceName" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *            <contactEmail>...</contactEmail>
    +     *            <authURI>...</authURI>
    +     *     </serviceType>
    +     *          ...
    +     *          ...
    +     *  </serviceTypes>
    +     * 
    + ******************************************************************************************************************/ + public Map getServiceTypes() throws MobyException { + String result = getServiceTypesAsXML(); + Map results = new TreeMap( getStringComparator() ); + MobyServiceType[] types = createServiceTypesFromXML( result ); + for ( int i = 0; i < types.length; i++ ) { + results.put( types[ i ].getName(), types[ i ].getDescription() ); + } + return results; + } + + // + protected String getServiceTypesAsXML() throws MobyException { + return ( String ) doCall( "retrieveServiceTypes", new Object[] {} ); + } + + // but be aware that the created MobyServiceTypes are not complete + // - they do not have the relationship information; that's why + // this method is not public; the full service types are available + // from CentralDigest implementations + protected MobyServiceType[] createServiceTypesFromXML( String result ) throws MobyException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceType" ); + if ( list == null || list.getLength() == 0 ) return new MobyServiceType[] {}; + MobyServiceType[] results = new MobyServiceType[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyServiceType st = new MobyServiceType( elem.getAttribute( "name" ) ); + st.setLSID( elem.getAttribute( "lsid" ) ); + st.setDescription( getFirstValue( elem.getElementsByTagName( "Description" ) ) ); + st.setEmailContact( getFirstValue( elem.getElementsByTagName( "contactEmail" ) ) ); + st.setAuthority( getFirstValue( elem.getElementsByTagName( "authURI" ) ) ); + results[ i ] = st; + } + java.util.Arrays.sort( results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     *  <Namespaces>
    +     *     <Namespace name="namespace" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *            <contactEmail>...</contactEmail>
    +     *            <authURI>...</authURI>
    +     *     </Namespace>
    +     *          ...
    +     *          ...
    +     *  </Namespaces>
    +     * 
    + ******************************************************************************************************************/ + public MobyNamespace[] getFullNamespaces() throws MobyException { + + String result = getNamespacesAsXML(); + return createNamespacesFromXML( result ); + } + + // + protected String getNamespacesAsXML() throws MobyException { + return ( String ) doCall( "retrieveNamespaces", new Object[] {} ); + } + + // + protected MobyNamespace[] createNamespacesFromXML( String result ) throws MobyException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getDocumentElement().getElementsByTagName( "Namespace" ); + if ( list == null || list.getLength() == 0 ) { + return new MobyNamespace[] {}; + } + MobyNamespace[] results = new MobyNamespace[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyNamespace nm = new MobyNamespace( elem.getAttribute( "name" ) ); + nm.setLSID( elem.getAttribute( "lsid" ) ); + nm.setDescription( getFirstValue( elem.getElementsByTagName( "Description" ) ) ); + nm.setEmailContact( getFirstValue( elem.getElementsByTagName( "contactEmail" ) ) ); + nm.setAuthority( getFirstValue( elem.getElementsByTagName( "authURI" ) ) ); + results[ i ] = nm; + } + + java.util.Arrays.sort( results ); + return results; + } + + /******************************************************************************************************************* + * + * @deprecated Replaced by {@link #getFullNamespaces} that gives more information for the same price. + *

    + ******************************************************************************************************************/ + public Map getNamespaces() throws MobyException { + + Map results = new TreeMap( getStringComparator() ); + MobyNamespace[] namespaces = getFullNamespaces(); + for ( int i = 0; i < namespaces.length; i++ ) { + results.put( namespaces[ i ].getName(), namespaces[ i ].getDescription() ); + } + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     *  <objectNames>
    +     *     <Object name="objectName" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *     </Object>
    +     *          ...
    +     *          ...
    +     *  </objectNames>
    +     * 
    + ******************************************************************************************************************/ + public Map getDataTypeNames() throws MobyException { + String result = getDataTypeNamesAsXML(); + return createDataTypeNamesFromXML( result, true ); + } + + // + protected String getDataTypeNamesAsXML() throws MobyException { + return ( String ) doCall( "retrieveObjectNames", new Object[] {} ); + } + + // if onlyNames == true + // Map: data type name -> description (String) + // else + // Map: data type name -> MobyDataType[] + // (filled with name, description, and lsid) + protected Map createDataTypeNamesFromXML( String result, boolean onlyNames ) throws MobyException { + + // parse returned XML + Map results = new TreeMap( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Object" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String name = elem.getAttribute( "name" ); + if ( name == null ) continue; // ignore no-named data types + String desc = ""; + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "Description" ) ) { + desc = getFirstValue( children.item( j ) ); + break; + } + } + if ( onlyNames ) { + results.put( name, desc ); + } + else { + MobyDataType dt = new MobyDataType( name ); + dt.setDescription( desc ); + dt.setLSID( elem.getAttribute( "lsid" ) ); + results.put( name, dt ); + } + } + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. An example: + * + *
    +     * <retrieveObjectDefinition>
    +     *   <objectType lsid="...">go_term</objectType>
    +     *   <Description><![CDATA[A very lightweight object holding a GO term name and its definition]]></Description>
    +     *   <authURI>http://www.illuminae.com</authURI>
    +     *   <contactEmail>markw at illuminae.com</contactEmail>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *      <objectType articleName=''>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *   </Relationship>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    +     *      <objectType articleName='Term'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *      <objectType articleName='Definition'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *   </Relationship>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:has'>
    +     *      <objectType articleName='Problems'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *      <objectType articleName='Issues'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *   </Relationship>
    +     * </retrieveObjectDefinition>
    +     * 
    + ******************************************************************************************************************/ + public MobyDataType getDataType( String dataTypeName ) throws MobyException, NoSuccessException { + + String result = getDataTypeAsXML( dataTypeName ); + return createDataTypeFromXML( result, dataTypeName ); + } + + public MobyDataType[] getDataTypes() throws MobyException, NoSuccessException { + Map< String, String > datatypeMap = getDataTypeNames(); + MobyDataType[] datatypes = new MobyDataType[ datatypeMap.size() ]; + int i = 0; + for ( String dataTypeName : datatypeMap.keySet() ) { + datatypes[ i++ ] = getDataType( dataTypeName ); + } + return datatypes; + } + + protected String getDataTypeAsXML( String dataTypeName ) throws MobyException, NoSuccessException { + + return ( String ) doCall( "retrieveObjectDefinition", new Object[] { "" + + "" + dataTypeName + "" + "" } ); + } + + protected MobyDataType createDataTypeFromXML( String xmlSource, String dataTypeName ) throws MobyException, + NoSuccessException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( xmlSource.getBytes() ) ); + NodeList list = document.getElementsByTagName( "retrieveObjectDefinition" ); + if ( list == null || list.getLength() == 0 ) + throw new NoSuccessException( "Data Type name was not found.", dataTypeName ); + MobyDataType data = null; + Element elem = ( Element ) list.item( 0 ); + NodeList children = elem.getChildNodes(); + + // first find the "real" (LSID-ized) data type name + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "objectType" ) ) { + data = new MobyDataType( getFirstValue( children.item( j ) ) ); + data.setLSID( ( ( Element ) children.item( j ) ).getAttribute( "lsid" ) ); + break; + } + } + + // if not found (unprobable) use the name given by the caller + if ( data == null ) data = new MobyDataType( dataTypeName ); + + // now fill the data type object with the rest of attributes + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "Description" ) ) { + data.setDescription( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "authURI" ) ) { + data.setAuthority( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "contactEmail" ) ) { + data.setEmailContact( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "Relationship" ) ) { + String relationshipType = ( ( Element ) children.item( j ) ).getAttribute( "relationshipType" ); + if ( relationshipType.endsWith( "isa" ) ) { + + NodeList parents = children.item( j ).getChildNodes(); + for ( int k = 0; k < parents.getLength(); k++ ) { + if ( parents.item( k ).getNodeName().equals( "objectType" ) ) { + data.addParentName( getFirstValue( parents.item( k ) ) ); + } + } + } + else if ( relationshipType.endsWith( "hasa" ) ) { + + NodeList belows = children.item( j ).getChildNodes(); + for ( int k = 0; k < belows.getLength(); k++ ) { + if ( belows.item( k ).getNodeName().equals( "objectType" ) ) { + data.addChild( ( ( Element ) belows.item( k ) ).getAttribute( "articleName" ), + getFirstValue( belows.item( k ) ), Central.iHASA ); + } + } + } + else if ( relationshipType.endsWith( "has" ) ) { + + NodeList belows = children.item( j ).getChildNodes(); + for ( int k = 0; k < belows.getLength(); k++ ) { + if ( belows.item( k ).getNodeName().equals( "objectType" ) ) { + data.addChild( ( ( Element ) belows.item( k ) ).getAttribute( "articleName" ), belows.item( + k ).getFirstChild().getNodeValue(), Central.iHAS ); + } + } + } + } + } + return data; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getServiceWSDL( String serviceName ) throws MobyException, NoSuccessException { + + Map names = getServiceNames(); + + for ( Iterator it = names.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = ( Map.Entry ) it.next(); + if ( ( ( String ) entry.getKey() ).equals( serviceName ) ) + return getServiceWSDL( serviceName, ( String ) entry.getValue() ); + } + + throw new NoSuccessException( "Service not found.", serviceName ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getServiceWSDL( String serviceName, String authority ) throws MobyException, NoSuccessException { + + String cacheId = "getServiceWSDL" + serviceName + ":" + authority; + String cachedResults = ( String ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveService", + new Object[] { "" + "" + "" } ); + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + Element service = document.getDocumentElement(); + Node wsdl = service.getFirstChild(); + if ( wsdl == null ) + throw new NoSuccessException( "Service not found OR WSDL is not available.", serviceName + " (" + authority + + ")" ); + + String results = wsdl.getNodeValue(); + setContents( cacheId, results ); + return results; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterDataTypeXML( MobyDataType dataType ) { + + // build the ISA tag (expressing hierarchy of data types) + String[] names = dataType.getParentNames(); + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < names.length; i++ ) { + buf.append( "" ); + buf.append( names[ i ] ); + buf.append( "" ); + buf.append( "\n" ); + } + + // build the HASA/HAS tags (expressing containments of data types) + MobyRelationship[] children = dataType.getChildren(); + StringBuffer buf2 = new StringBuffer(); // for HASA + StringBuffer buf3 = new StringBuffer(); // for HAS + for ( int i = 0; i < children.length; i++ ) { + if ( children[ i ].getRelationshipType() == Central.iHASA ) { + buf2.append( "" ); + buf2.append( children[ i ].getDataTypeName() ); + buf2.append( "" ); + } + else if ( children[ i ].getRelationshipType() == Central.iHAS ) { + buf3.append( "" ); + buf3.append( children[ i ].getDataTypeName() ); + buf3.append( "" ); + } + } + + return "" + "" + dataType.getName() + "" + + "" + "" + + "" + new String( buf ) + "" + + "" + new String( buf2 ) + "" + + "" + new String( buf3 ) + "" + "" + + dataType.getAuthority() + "" + "" + dataType.getEmailContact() + + "" + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerDataType( MobyDataType dataType ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerObjectClass", new Object[] { getRegisterDataTypeXML( dataType ) } ); + dataType.setId( checkRegistration( result, dataType )[ 0 ] ); + } + + /******************************************************************************************************************* + * B + ******************************************************************************************************************/ + public void unregisterDataType( MobyDataType dataType ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterObjectClass", new Object[] { "" + + "" + dataType.getName() + "" + "" } ); + checkRegistration( result, dataType ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterServiceTypeXML( MobyServiceType serviceType ) { + + // build the ISA tag (expressing hierarchy of service types) + String[] names = serviceType.getParentNames(); + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < names.length; i++ ) { + buf.append( "" ); + buf.append( names[ i ] ); + buf.append( "" ); + buf.append( "\n" ); + } + + return "" + "" + serviceType.getName() + "" + "" + + serviceType.getEmailContact() + "" + "" + serviceType.getAuthority() + + "" + "" + "" + + "" + new String( buf ) + "" + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerServiceType( MobyServiceType serviceType ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerServiceType", + new Object[] { getRegisterServiceTypeXML( serviceType ) } ); + serviceType.setId( checkRegistration( result, serviceType )[ 0 ] ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterServiceType( MobyServiceType serviceType ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterServiceType", new Object[] { "" + + "" + serviceType.getName() + "" + "" } ); + checkRegistration( result, serviceType ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterNamespaceXML( MobyNamespace namespace ) { + return "" + "" + namespace.getName() + "" + "" + + namespace.getEmailContact() + "" + "" + namespace.getAuthority() + + "" + "" + "" + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerNamespace( MobyNamespace namespace ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "registerNamespace", new Object[] { getRegisterNamespaceXML( namespace ) } ); + namespace.setId( checkRegistration( result, namespace )[ 0 ] ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterNamespace( MobyNamespace namespace ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterNamespace", new Object[] { "" + + "" + namespace.getName() + "" + "" } ); + checkRegistration( result, namespace ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterServiceXML( MobyService service ) { + return "" + "" + service.getCategory() + "" + "" + + service.getName() + "" + "" + service.getType() + "" + + "" + ( service.getLSID() == null ? "" : service.getLSID().trim() ) + "" + + "" + service.getAuthority() + "" + "" + + escapeXML( service.getSignatureURL() ) + "" + "" + escapeXML( service.getURL() ) + + "" + "" + service.getEmailContact() + "" + + "" + ( service.isAuthoritative() ? "1" : "0" ) + "" + + "" + "" + + buildPrimaryInputTag( service ) + buildSecondaryInputTag( service ) + buildOutputTag( service ) + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerService( MobyService service ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerService", new Object[] { getRegisterServiceXML( service ) } ); + String[] registered = checkRegistration( result, service ); + service.setId( registered[ 0 ] ); + service.setRDF( registered[ 1 ] ); + String pathToRDF = service.getPathToRDF(); + if ( !pathToRDF.equals( "" ) ) { + File fileRDF = new File( pathToRDF ); + try { + PrintStream fileout = new PrintStream( new FileOutputStream( fileRDF ) ); + fileout.println( registered[ 1 ] ); + fileout.close(); + } + catch ( IOException e ) { + StringBuffer buf = new StringBuffer( 100 ); + buf.append( "Failed to save RDF in '" ); + buf.append( fileRDF.getAbsolutePath() + "'. " ); + buf.append( e.toString() ); + try { + File tmpFile = File.createTempFile( service.getName() + "-", ".rdf" ); + PrintStream fileout = new PrintStream( new FileOutputStream( tmpFile ) ); + fileout.println( registered[ 1 ] ); + fileout.close(); + buf.append( "\nReturned RDF file was therefore stored in: " ); + buf.append( tmpFile.getAbsolutePath() ); + } + catch ( IOException e2 ) { + buf.append( "\nEven saving in a temporary file failed: " ); + buf.append( e2.toString() ); + } + throw new MobyException( buf.toString() ); + } + } + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterService( MobyService service ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterService", new Object[] { "" + "" + + service.getAuthority() + "" + "" + service.getName() + "" + + "" } ); + checkRegistration( result, service ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( String serviceType ) throws MobyException { + if ( serviceType == null ) return new MobyService[] {}; + MobyService pattern = new MobyService( "dummy" ); + pattern.setCategory( "" ); + pattern.setType( serviceType ); + return findService( pattern, null ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( String[] keywords ) throws MobyException { + if ( keywords == null ) return new MobyService[] {}; + return findService( null, keywords ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern ) throws MobyException { + if ( pattern == null ) return new MobyService[] {}; + return findService( pattern, null ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern, String[] keywords ) throws MobyException { + return findService( pattern, keywords, true, true ); + } + + /******************************************************************************************************************* + * All 'findService' methods end up here. + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern, String[] keywords, boolean includeChildrenServiceTypes, + boolean includeParentDataTypes ) throws MobyException { + if ( pattern == null ) { + pattern = new MobyService( "dummy" ); + pattern.setCategory( "" ); + } + + String result = getServicesAsXML( pattern, keywords, includeChildrenServiceTypes, includeParentDataTypes ); + MobyService[] services = extractServices( result ); + return services; + } + + // ...actually all 'findService' methods end up here + protected String getServicesAsXML( MobyService pattern, String[] keywords, boolean includeChildrenServiceTypes, + boolean includeParentDataTypes ) throws MobyException { + String[] query = new String[] { "" + + buildQueryObject( pattern, keywords, includeParentDataTypes, includeChildrenServiceTypes, false ) + + "" }; + return ( String ) doCall( "findService", query ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String call( String methodName, String inputXML ) throws MobyException { + Object result; + if ( inputXML == null || inputXML.equals( "" ) ) + result = doCall( methodName, new Object[] {} ); + else + result = doCall( methodName, new Object[] { inputXML } ); + return ( String ) result; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected static String resultToString( Object result ) throws MobyException { + if ( result == null ) throw new MobyException( "Returned result is null." ); + if ( result instanceof String ) return ( String ) result; + if ( result instanceof String[] ) { + String[] tmp = ( String[] ) result; + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < tmp.length; i++ ) + buf.append( tmp[ i ] ); + return new String( buf ); + } + if ( result instanceof byte[] ) return new String( ( byte[] ) result ); + + throw new MobyException( "Unknown type of result: " + result.getClass().getName() ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public boolean setDebug( boolean enabled ) { + boolean oldMode = debug; + debug = enabled; + return oldMode; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * <Relationships>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:servicerelation:isa'>
    +     *     <serviceType>urn:lsid:biomoby.org:servicetype:analysis</serviceType>
    +     *     <serviceType>urn:lsid:biomoby.org:servicetype:service</serviceType>
    +     *   </Relationship>
    +     * </Relationships>
    +     * 
    + ******************************************************************************************************************/ + public String[] getServiceTypeRelationships( String serviceTypeName, boolean expand ) throws MobyException { + String result = getServiceTypeRelationshipsAsXML( serviceTypeName, expand ); + return createServiceTypeRelationshipsFromXML( result ); + } + + // + protected String getServiceTypeRelationshipsAsXML( String serviceTypeName, boolean expand ) throws MobyException { + return ( String ) doCall( "Relationships", new Object[] { "" + "" + serviceTypeName + + "" + "" + Central.ISA + "" + + "" + ( expand ? "1" : "0" ) + "" + "" } ); + } + + // + protected String[] createServiceTypeRelationshipsFromXML( String result ) throws MobyException { + + // parse returned XML + Vector< String > v = new Vector< String >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "serviceType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + } + String[] results = new String[ v.size() ]; + v.copyInto( results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * lt;Relationships>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *  </Relationship>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:integer</objectType>
    +     *  </Relationship>
    +     * lt;/Relationships>
    +     * 
    + * + * Added at Sun Feb 19 19:32:31 PHT 2006: it recognizes also an attributes 'lsid' and 'articleName' in + * <objectType> element. + ******************************************************************************************************************/ + public Map getDataTypeRelationships( String dataTypeName ) throws MobyException { + + String cacheId = "getDataTypeRelationships_" + dataTypeName; + Map cachedResults = ( Map ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "Relationships", new Object[] { "" + "" + + dataTypeName + "" + "" + Central.ISA + "" + + "" + Central.HASA + "" + "" + Central.HAS + + "" + "1" + "" } ); + + // parse returned XML + Map results = new HashMap(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String relType = elem.getAttribute( "relationshipType" ); + NodeList children = elem.getChildNodes(); + Vector< String > v = new Vector< String >(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "objectType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + String[] names = new String[ v.size() ]; + v.copyInto( names ); + results.put( relType, names ); + } + + setContents( cacheId, results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * lt;Relationships>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *  </Relationship>
    +     * lt;/Relationships>
    +     * 
    + ******************************************************************************************************************/ + public String[] getDataTypeRelationships( String dataTypeName, String relationshipType ) throws MobyException { + + String cacheId = "getDataTypeRelationships_" + dataTypeName + ":" + relationshipType; + String[] cachedResults = ( String[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "Relationships", new Object[] { "" + "" + + dataTypeName + "" + "" + relationshipType + "" + + "1" + "" } ); + + // parse returned XML + Vector< String > v = new Vector< String >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + + // it should always be just one element in this list + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "objectType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + } + String[] results = new String[ v.size() ]; + v.copyInto( results ); + + setContents( cacheId, results ); + return results; + } + + // /************************************************************************** + // * + // *************************************************************************/ + // public MobyRelationship[] getRelationships (String dataTypeName) + // throws MobyException { + // return null; + // } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegistryEndpoint() { + return endpoint.toString(); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegistryNamespace() { + return uri; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * <resourceURLs>
    +     *   <Resource name="Service"         url="..." />
    +     *   <Resource name="Object"          url="..." />
    +     *   <Resource name="Namespace"       url="..." />
    +     *   <Resource name="ServiceInstance" url="..." />
    +     *   <Resource name="Full"            url="..." />
    +     * </resourceURLs>
    +     * 
    + ******************************************************************************************************************/ + public MobyResourceRef[] getResourceRefs() throws MobyException { + + String cacheId = "retrieveResourceURLs"; + MobyResourceRef[] cachedResults = ( MobyResourceRef[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveResourceURLs", new Object[] {} ); + + // parse returned XML + Vector< MobyResourceRef > v = new Vector< MobyResourceRef >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Resource" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + try { + v.addElement( new MobyResourceRef( elem.getAttribute( "name" ), new URL( ( String ) elem + .getAttribute( "url" ) ), elem.getAttribute( "type" ) ) ); + } + catch ( MalformedURLException e2 ) { + if ( debug ) System.err.println( "Bad URL: " + elem.getAttribute( "url" ) ); + } + } + + MobyResourceRef[] results = new MobyResourceRef[ v.size() ]; + v.copyInto( results ); + + // Add this data to the cache in case we get called again + setContents( cacheId, results ); + + return results; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public InputStream getResource( String resourceName ) throws MobyException { + + MobyResourceRef[] resourceRefs = getResourceRefs(); + for ( int i = 0; i < resourceRefs.length; i++ ) { + if ( resourceName.equalsIgnoreCase( resourceRefs[ i ].getResourceName() ) ) { + return Utils.getInputStream( resourceRefs[ i ].getResourceLocation() ); + } + } + throw new MobyException( "No resource found for '" + resourceName + "'." ); + } + + /******************************************************************************************************************* + * Return a case-insensitive comparator of Strings. It is used to create various TreeMaps where keys are strings. + ******************************************************************************************************************/ + protected static Comparator getStringComparator() { + return new Comparator() { + public int compare( Object o1, Object o2 ) { + return ( ( String ) o1 ).compareToIgnoreCase( ( String ) o2 ); + } + }; + } + + // cache URL/URI so we only check once + private static String CHECKED_URL = null; + private static String CHECKED_URI = null; + + /** + * Using this method to get a Central object will ensure that other parts of the org.biomoby.shared class hierarchy + * that implicitly check the registry will use the same cache. Otherwise, methods such as + * MobyNamespace.getNamespace() must be passed a Central object parameter as well. + * + * @return a CentralImpl using the default Central URI, and currently a class implementing a caching mechanism + */ + public static CentralImpl getDefaultCentral() throws MobyException { + return getDefaultCentral( null ); + } + + public static CentralImpl getDefaultCentral( Registry reg ) throws MobyException { + if ( reg == null && defaultCentrals.containsKey( "" ) ) { + return defaultCentrals.get( "" ); + } + else if ( reg != null && defaultCentrals.containsKey( reg.getEndpoint() ) ) { + return defaultCentrals.get( reg.getEndpoint() ); + } + + String className = DEFAULT_CENTRAL_IMPL_CLASSNAME; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + URL resURL = classLoader.getResource( "META-INF/" + CENTRAL_IMPL_RESOURCE_NAME ); + if ( resURL != null ) { + System.err.println( "Loading " + resURL ); + try { + LineNumberReader reader = new LineNumberReader( new InputStreamReader( resURL.openStream() ) ); + for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { + if ( !line.trim().startsWith( "#" ) ) { + className = line.trim(); + break; + } + } + } + catch ( Exception e ) { + logger.log( Level.WARNING, "Error reading " + resURL, e ); + } + } + try { + System.err.println( "Central class is " + className ); + Class clazz = Class.forName( className ); + if ( reg == null ) { // should use default nullary c-tor + defaultCentrals.put( "", ( CentralImpl ) clazz.newInstance() ); + } + else { // should have (String endpoint, String namespace) c-tor + for ( Constructor ctor : clazz.getDeclaredConstructors() ) { + Class[] params = ctor.getParameterTypes(); + if ( params.length == 2 && params[ 0 ].getName().equals( "java.lang.String" ) + && params[ 1 ].getName().equals( "java.lang.String" ) ) { + defaultCentrals.put( reg.getEndpoint(), ( CentralImpl ) ctor.newInstance( reg.getEndpoint(), + reg.getNamespace() ) ); + break; + } + } + if ( !defaultCentrals.containsKey( reg.getEndpoint() ) ) { + logger.log( Level.WARNING, "Could not find required (String endpoint, String namespace)" + + "constructor for class " + className ); + } + } + } + catch ( Exception e ) { + logger.log( Level.WARNING, "Could not load class " + className, e ); + if ( reg == null ) { + defaultCentrals.put( "", new CentralImpl() ); // fallback to this class, no caching, etc. + } + else { + defaultCentrals.put( reg.getEndpoint(), new CentralImpl( reg.getEndpoint(), reg.getNamespace() ) ); + } + } + + return defaultCentrals.get( reg == null ? "" : reg.getEndpoint() ); + } + + /** + * + * @return a String representing the Default mobycentral endpoint. If the system property 'moby.check.default' + * exists and is set to true, then the URL http://biomoby.org/mobycentral is queried and the default central + * endpoint is returned, otherwise DEFAULT_ENDPOINT is returned. + */ + public static String getDefaultURL() { + boolean check = false; + try { + check = Boolean.getBoolean( "moby.check.default" ); + } + catch ( Exception e ) { + + } + + if ( check ) { + // return the last checked url if we have done this before + if ( CHECKED_URL != null && CHECKED_URL.trim() != "" ) { + return CHECKED_URL; + } + + // create a HttpClient object + HttpClient client = new HttpClient(); + // set up the Head method + HeadMethod method = new HeadMethod( "http://biomoby.org/mobycentral" ); + // do not follow redirects or we will get a 411 error + method.setFollowRedirects( false ); + // retry 3 times + method.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, + new DefaultHttpMethodRetryHandler( 3, false ) ); + // set the user agent ... should probably make this something more reasonable + method.getParams().setParameter( HttpMethodParams.USER_AGENT, "jMoby/1.0" ); + try { + // Execute the method. + int statusCode = client.executeMethod( method ); + + if ( statusCode != HttpStatus.SC_MOVED_PERMANENTLY ) { + System.err.println( "Method failed: " + method.getStatusLine() ); + } + else { + try { + String location = method.getResponseHeader( "location" ).getValue(); + CHECKED_URL = location; + try { + CHECKED_URI = "http://" + ( new URL( CHECKED_URL ).getAuthority() ) + "/MOBY/Central"; + } + catch ( MalformedURLException murle ) { + CHECKED_URI = DEFAULT_NAMESPACE; + } + return CHECKED_URL; + } + catch ( NullPointerException npe ) { + return DEFAULT_ENDPOINT; + } + } + } + catch ( HttpException e ) { + System.err.println( "Fatal protocol violation: " + e.getMessage() ); + e.printStackTrace(); + } + catch ( IOException e ) { + System.err.println( "Fatal transport error: " + e.getMessage() ); + e.printStackTrace(); + } + finally { + // Release the connection. + method.releaseConnection(); + } + + } + else { + return DEFAULT_ENDPOINT; + } + return DEFAULT_ENDPOINT; + } + + /** + * + * @return a String representing the default mobycentral uri. If the system property 'moby.check.default' exists and + * is set to true, then the URL http://biomoby.org/mobycentral is queried and the default central namespace + * is returned, otherwise DEFAULT_NAMESPACE is returned. + */ + public static String getDefaultURI() { + boolean check = false; + try { + check = Boolean.getBoolean( "moby.check.default" ); + } + catch ( Exception e ) { + + } + if ( check ) { + if ( CHECKED_URI != null && CHECKED_URI.trim() != "" ) { + return CHECKED_URI; + } + // need to check ... + getDefaultURL(); + return CHECKED_URI; + } + else { + return DEFAULT_NAMESPACE; + } + } + + /******************************************************************************************************************* + * Convert non-suitable characters in a XML string into their entity references. + *

    + * + * Adapted from jDom. + * + * @param str + * input to be converted + * @return If there were any non-suitable characters, return a new string with those characters escaped, otherwise + * return the unmodified input string + * + ******************************************************************************************************************/ + public String escapeXML( String str ) { + StringBuffer buffer = null; + char ch; + String entity; + for ( int i = 0; i < str.length(); i++ ) { + ch = str.charAt( i ); + switch ( ch ) { + case '<': + entity = "<"; + break; + case '>': + entity = ">"; + break; + case '&': + entity = "&"; + break; + default: + entity = null; + break; + } + if ( buffer == null ) { + if ( entity != null ) { + // An entity occurred, so we'll have to use StringBuffer + // (allocate room for it plus a few more entities). + buffer = new StringBuffer( str.length() + 20 ); + // Copy previous skipped characters and fall through + // to pickup current character + buffer.append( str.substring( 0, i ) ); + buffer.append( entity ); + } + } + else { + if ( entity == null ) { + buffer.append( ch ); + } + else { + buffer.append( entity ); + } + } + } + + // If there were any entities, return the escaped characters + // that we put in the StringBuffer. Otherwise, just return + // the unmodified input string. + return ( buffer == null ) ? str : buffer.toString(); + } + + /******************************************************************************************************************* + * Format an exception. + ******************************************************************************************************************/ + public static String formatFault( AxisFault e, String endpoint, QName method ) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + formatFault( e, new PrintStream( baos ), endpoint, method ); + return baos.toString(); + } + + /******************************************************************************************************************* + * Format an exception. + ******************************************************************************************************************/ + public static void formatFault( AxisFault e, PrintStream out, String endpoint, QName method ) { + + out.println( "===ERROR===" ); + out.println( "Fault details:" ); + // for some obvious errors I do not print all details (with a lenghty trace stack) + String faultString = e.getFaultString(); + if ( ( !faultString.startsWith( "java.net.ConnectException" ) ) + && ( faultString.indexOf( "Could not find class for the service named:" ) == -1 ) ) { + org.w3c.dom.Element[] details = e.getFaultDetails(); + for ( int i = 0; i < details.length; i++ ) { + String s = details[ i ].toString().replaceAll( "<", "<" ); + s = s.replaceAll( ">", ">" ); + out.println( s ); + } + } + out.println( "Fault string: " + faultString ); + out.println( "Fault code: " + e.getFaultCode() ); + out.println( "Fault actor: " + e.getFaultActor() ); + if ( endpoint != null || method != null ) out.println( "When calling:" ); + if ( endpoint != null ) out.println( "\t" + endpoint ); + if ( method != null ) out.println( "\t" + method ); + out.println( "===========" ); + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java 2007/05/29 03:51:46 1.12 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java 2008/11/26 08:53:43 1.13 @@ -1,481 +1,429 @@ -// BaseClient.java -// -// Created: August 2005 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.client; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.parser.JDOMUtils; -import org.biomoby.shared.Central; -import org.biomoby.client.CentralImpl; -import org.biomoby.shared.parser.MobyPackage; -import org.biomoby.shared.parser.MobyJob; -import org.biomoby.shared.parser.ServiceException; -import org.biomoby.shared.parser.MobyTags; - -import org.tulsoft.tools.soap.axis.AxisCall; -import org.tulsoft.shared.GException; - -import org.apache.commons.lang.StringUtils; - -import org.jdom.input.SAXBuilder; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.Namespace; - -import java.net.URL; -import java.net.MalformedURLException; -import java.io.StringReader; - -/** - * This is a base class for Biomoby clients. It takes care about - * converting user input into Biomoby XML, sending it in a SOAP - * message to a Biomoby service, waiting for the response and parsing - * it from Biomoby XML. It also divides requests and responses into - * so-called jobs - each of them corresponds to a Biomoby - * query (a Biomoby single network request may contain more - * queries/jobs).

    - * - * Any client can override various methods - but the ones she/he - * must override in a subclass are those telling what service - * to call ({@link #getServiceLocator}), what data to put in a request - * ({@link #fillRequest(MobyJob,MobyPackage) fillRequest}), and what - * to do with a response ({@link #useResponse(MobyJob,MobyPackage) - * useResponse}.

    - * - * @author Martin Senger - * @version $Id$ - */ - -abstract public class BaseClient { - - private static org.apache.commons.logging.Log log = - org.apache.commons.logging.LogFactory.getLog (BaseClient.class); - - /************************************************************************** - * - *************************************************************************/ - static protected boolean notEmpty (String value) { - return StringUtils.isNotBlank (value); - } - static protected boolean isEmpty (String value) { - return StringUtils.isBlank (value); - } - - /************************************************************************** - * The main method that packs input data, invokes a BioMoby - * service and uses its response. Use this method if the input - * data should have just one job (which is a usual case) - - * otherwise use method {@link #process(int)}.

    - * - * @throws MobyException if (a) a sub-class throws it during the - * filling data or using response, or (b) a Biomoby service - * invocation fails - *************************************************************************/ - public void process() - throws MobyException { - process (1); - } - - /************************************************************************** - * The main method that packs input data, invokes a BioMoby - * service and uses its response. The input data may consist from - * more than one job (query) - the 'jobCount' is a suggestion how - * many jobs will be included, but this can be changed by the - * implementing sub-class.

    - * - * Usually a client developer does not need to overwrite this - * method. She or he makes the real input data filling in the - * {@link #fillRequest} method, and uses the response in the - * {@link #useResponse} method.

    - * - * @throws MobyException if (a) a sub-class throws it during the - * filling data or using response, or (b) a Biomoby service - * invocation fails - *************************************************************************/ - public void process (int jobCount) - throws MobyException { - - String xmlResponse = null; - - // input: raw-level processing - String xmlInput = fillRequest(); - if (xmlInput != null) { - if ( (xmlInput = interceptRequest (xmlInput)) == null ) - return; - } - - // input: usual processing (i.e. collect XML in iterations) - else { - MobyPackage mobyInput = new MobyPackage(); - if (! fillRequest (mobyInput, jobCount)) return; - xmlInput = mobyInput.toXML(); - if ( (xmlInput = interceptRequest (xmlInput)) == null ) - return; - } - - // calling service - xmlResponse = callRemoteService (xmlInput); - - // output: raw-level processing - if (! useResponse (xmlResponse)) return; - - // output: usual processing (again by iterations) - MobyPackage mobyResponse = MobyPackage.createFromXML (xmlResponse); - useResponse (mobyResponse); - } - - public String interceptRequest (String xmlInput) - throws MobyException { - return xmlInput; - } - - /************************************************************************** - * Create raw XML input. Override this method if you have already - * an input XML, or you want to create it yourself.

    - * - * @return a full XML input for a Biomoby service (in this case no - * other fillRequest methods will called); return null if - * no XML was created and a usual process to gather it will be used - * - * @throws MobyException if an XML cannot be created - *************************************************************************/ - public String fillRequest() - throws MobyException { - return null; - } - - /************************************************************************** - * - *************************************************************************/ - protected String filterMobyResponseType (Object result) - throws MobyException { - if (result instanceof String) - return (String)result; - else if (result instanceof byte[]) - return new String ((byte[])result); - else - throw new MobyException - ("The Biomoby data should be sent/received either as type String or base64/byte[]. " + - "But they are of type '" + result.getClass().getName() + "'."); - } - - /************************************************************************** - * - *************************************************************************/ - protected String callBiomobyService (MobyServiceLocator locator, - String xmlInput) - throws MobyException { - - - MobyService service = locator.getService(); - String serviceName = service.getName(); - boolean asBytes = locator.isAsBytes(); - String serviceEndpoint = service.getURL(); - int timeout = locator.getSuggestedTimeout(); - - try { - URL target = new URL (serviceEndpoint); - AxisCall call = new AxisCall (target, timeout); - call.getCall().setSOAPActionURI (MobyService.BIOMOBY_SERVICE_URI + "#" + serviceName); - return filterMobyResponseType - (call.doCall (MobyService.BIOMOBY_SERVICE_URI, - serviceName, - new Object[] { sendingFilter (xmlInput, asBytes) })); - } catch (MalformedURLException e) { - throw new MobyException ("Service endpoint '" + serviceEndpoint + - "' is not a valid URL."); - } catch (GException e) { - throw new MobyException (e.getMessage(), e); - } - } - - // - protected Object sendingFilter (String input, boolean asBytes) { - if (asBytes) { - log.debug ("Data sent as a byte array"); - return input.getBytes(); - } else { - return input; - } - } - - /************************************************************************** - * Call a SOAP-based BioMoby service. In order to find what - * service to call and what are its characteristics (such as its - * endpoint) it will call method {@link #getServiceLocator} that - * should be implemented by a sub-class.

    - * - * Once it has the service locator, this class does one of the - * following, in this order:

      - * - *
    • The locator must contain at least a service name. If it - * does not, an exception is raised. - * - *
    • If the locator contains a service endpoint, a call is - * made to this endpoint, using also the service name as a - * method name. - * - *
    • If the locator has a registry endpoint, an enquiry to - * the registry is made to find an endpoint of a service - * corresponding with the given service name. Once found, the - * service is called. - * - *
    • The same as the previous one but using a default - * registry. - * - * @param xmlInput data will be sent to the called Biomoby service - * - * @return service response (still in XML) - * - * @throws MobyException (a) if service call (or a call to - * registry; for example because the registry does not know given - * service) fails, or (b) if the used {@link MobyServiceLocator} - * does not contain a service name. - * - *************************************************************************/ - public String callRemoteService (String xmlInput) - throws MobyException { - - // 1) service name is a must - MobyServiceLocator locator = getServiceLocator(); - MobyService service = locator.getService(); - if (service == null) - throw new MobyException ("MobyService locator returned an empty service object.\n" + - "I do not know what service to call..."); - String serviceName = service.getName(); - if (isEmpty (serviceName) || - MobyService.DUMMY_NAME.equals (serviceName)) - throw new MobyException ("MobyService locator returned an empty service name.\n" + - "I do not know what service to call..."); - - // 2) try service endpoint - String serviceEndpoint = service.getURL(); - if (notEmpty (serviceEndpoint)) - return callBiomobyService (locator, xmlInput); - - // 3) find service endpoint in a Biomoby registry - Central worker = new CentralImpl (locator.getRegistryEndpoint(), - locator.getRegistryNamespace()); - MobyService[] services = worker.findService (service); - if (services == null || services.length == 0) - throw new MobyException ("Service " + service.toShortString() + - " is not known in Biomoby registry: \n" + - "\t" + worker.getRegistryEndpoint() + "\n" + - "\t" + worker.getRegistryNamespace()); - // ...and call the service - serviceEndpoint = services[0].getURL(); - if (notEmpty (serviceEndpoint)) { - service.setURL (serviceEndpoint); - return callBiomobyService (locator, xmlInput); - } - - // what else can I do? - throw new MobyException ("Registry has not returned any URL for service " + - service.toShortString()); - } - - /************************************************************************** - * Fill the whole 'mobyInput' - put there any number of jobs - * (queries) as you wish (you do not need to follow the 'jobCount' - * hint suggesting how many jobs should be put there).

      - * - * Usually there is not need to overwrite this method. It serves - * as an inter-mediator between the main {@link #process} method - * and the individual request fillings (done by a sub-class in - * method {@link #fillRequest(MobyJob,MobyPackage)}).

      - * - * @return false if you wish to cancel whole request (nothing will - * be sent to a Biomoby service); otherwise return true. - * - * @param mobyInput is an empty shell that you are supposed to - * fill with the input data for a Biomoby service execution - * - * @param jobCount is only a suggestion how many requests/job - * should be created (it comes from the {@link #process} method) - - * but it does not need to be obeyed - * - *************************************************************************/ - public boolean fillRequest (MobyPackage mobyInput, int jobCount) - throws MobyException { - - if (jobCount < 0) jobCount = 0; - for (int i = 0; i < jobCount; i++) { - MobyJob request = new MobyJob ("job_" + i); - if (! fillRequest (request, mobyInput)) - break; - mobyInput.addJob (request); - } - return (mobyInput.size() > 0); - } - - /************************************************************************** - * A raw-level processing. Use it if you need access to raw XML - * coming from a service.

      - * - * @param xmlResponse is a raw XML response returned from a - * BioMoby service - * - * @return false if the response should be considered fully - * processed (in this case no other 'useResponse' will be called); - * true indicates that normal processing of the response will - * follow; by default, this class (BaseClient) returns true - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'mobyResponse' is broken - *************************************************************************/ - public boolean useResponse (String xmlResponse) - throws MobyException { - return true; - } - - /************************************************************************** - * A high-level processing. Use it if you need access to all jobs - * (queries) - that returned from a service - in the same time. - * Otherwise use the processing on the job level (method {@link - * #useResponse(MobyJob,MobyPackage)}.

      - * - * @param mobyResponse is a full response returned from a BioMoby - * service - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'mobyResponse' is broken - *************************************************************************/ - public void useResponse (MobyPackage mobyResponse) - throws MobyException { - - // iterate over all input jobs - for (int i = 0; i < mobyResponse.size(); i++) { - if (! useResponse (mobyResponse.getJob (i), - mobyResponse)) - return; - } - } - - /************************************************************************** - * Extracts errors from a raw service response. It is iseful when - * one does not want to create a whole MobyPackage from a - * response, but just find whether a response is good or bad.

      - * - * @param xmlResponse is a full response returned from a BioMoby - * service - * - * @return a slightly formatted list of exceptions (of severity - * error) extracted from the response; or null if there - * are no errors there - *************************************************************************/ - public String errorsInResponse (String xmlResponse) { - try { - StringBuffer buf = new StringBuffer(); - SAXBuilder builder = new SAXBuilder(); - Document doc = - builder.build (new StringReader (xmlResponse)); - Element root = doc.getRootElement(); - Element mobyContent = JDOMUtils.getChild (root, MobyTags.MOBYCONTENT); - Element serviceNotes = JDOMUtils.getChild (mobyContent, MobyTags.SERVICENOTES); - ServiceException[] exceptions = - ServiceException.extractExceptions (serviceNotes); - for (int i = 0; i < exceptions.length; i++) { - if (exceptions[i].getSeverity() != ServiceException.ERROR) - continue; - if (buf.length() > 0) - buf.append ("\n"); - buf.append (exceptions[i].getErrorCodeAsString()); - buf.append (": "); - buf.append (exceptions[i].getMessage()); - } - return (buf.length() == 0 ? null : new String (buf)); - - } catch (Exception e) { - return e.toString(); - } - } - - - // - // Abstract methods - // - - /************************************************************************** - * Return characteristics of a BioMoby service that will be - * called, and that reveal where to find such service.

      - * - * @see #callRemoteService - * - * @return an object defining a location of a BioMoby service - * @throws MobyException if service locator cannot be - * returned/created (e.g. because there is not enough information - * about what service to call) - *************************************************************************/ - abstract public MobyServiceLocator getServiceLocator() - throws MobyException; - - /************************************************************************** - * Crate data (fill them into 'request') for one Moby job - * (query). The request will be sent within given 'inputContext' - - * but it is not yet there (because you may wish not to put it - * there - see the return value), and it is not the task of this - * method to put it there (just fill the 'request').

      - * - * This is a method that should be implemented by a client - * developer, and it is the place where the client's business - * logic sits.

      - * - * @return true if this request should be included into the input - * data (package) that will be sent to a biomoby service; or - * return false if you do not wish to create any more requests for - * this particular package (also this 'request' will not be used) - * - * @param request is an object that you are supposed to fill with - * input data for one service invocation; it already has a name - * (so called 'query id' in the BioMoby speak) but you are free to change it - * - * @param inputContext is an envelope where all requests will be - * stored and sent to a Biomoby service; you do not need to do - * anything with it here unless you wish; note that all already - * created requests are there, but not the one you are just - * creating in this method - * - * @throws MobyException if you need so (from whatever reason in - * your business logic); if thrown then nothing will be sent to a - * Biomoby service - * - *************************************************************************/ - abstract public boolean fillRequest (MobyJob request, MobyPackage inputContext) - throws MobyException; - - /************************************************************************** - * Process a single job returned from a BioMoby service.

      - * - * This is a method that should be implemented by a client - * developer, and it is the place where the client's business - * logic using the response sits.

      - * - * @param response is an object that you are supposed to use - * - * @param responseContext is an envelope where the full response - * (all its jobs) is located; you do not need to do anything with - * it here unless you wish (e.g. it gives you knowledge about how - * many jobs are in the full response, or it gives you access to - * the so-called 'service notes') - * - * @return false if you do not wish to get any more - * responses/jobs; otherwise return true - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'response' is broken - * - *************************************************************************/ - abstract public boolean useResponse (MobyJob response, - MobyPackage responseContext) - throws MobyException; - -} +// BaseClient.java +// +// Created: August 2005 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.client; + +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.axis.client.Call; +import org.apache.commons.lang.StringUtils; +import org.biomoby.shared.Central; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.parser.JDOMUtils; +import org.biomoby.shared.parser.MobyJob; +import org.biomoby.shared.parser.MobyPackage; +import org.biomoby.shared.parser.MobyTags; +import org.biomoby.shared.parser.ServiceException; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; +import org.tulsoft.shared.GException; +import org.tulsoft.tools.soap.axis.AxisCall; + +/** + * This is a base class for Biomoby clients. It takes care about converting user input into Biomoby XML, sending it in a + * SOAP message to a Biomoby service, waiting for the response and parsing it from Biomoby XML. It also divides requests + * and responses into so-called jobs - each of them corresponds to a Biomoby query (a Biomoby single network + * request may contain more queries/jobs). + *

      + * + * Any client can override various methods - but the ones she/he must override in a subclass are those + * telling what service to call ({@link #getServiceLocator}), what data to put in a request ({@link #fillRequest(MobyJob,MobyPackage) fillRequest}), + * and what to do with a response ({@link #useResponse(MobyJob,MobyPackage) useResponse}. + *

      + * + * @author Martin Senger + * @version $Id$ + */ + +abstract public class BaseClient { + private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( BaseClient.class ); + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + static protected boolean notEmpty(String value) { + return StringUtils.isNotBlank( value ); + } + static protected boolean isEmpty(String value) { + return StringUtils.isBlank( value ); + } + + /******************************************************************************************************************* + * The main method that packs input data, invokes a BioMoby service and uses its response. Use this method if the + * input data should have just one job (which is a usual case) - otherwise use method {@link #process(int)}. + *

      + * + * @throws MobyException if (a) a sub-class throws it during the filling data or using response, or (b) a Biomoby + * service invocation fails + ******************************************************************************************************************/ + public void process() throws MobyException { + process( 1 ); + } + + /******************************************************************************************************************* + * The main method that packs input data, invokes a BioMoby service and uses its response. The input data may + * consist from more than one job (query) - the 'jobCount' is a suggestion how many jobs will be included, but this + * can be changed by the implementing sub-class. + *

      + * + * Usually a client developer does not need to overwrite this method. She or he makes the real input data filling in + * the {@link #fillRequest} method, and uses the response in the {@link #useResponse} method. + *

      + * + * @throws MobyException if (a) a sub-class throws it during the filling data or using response, or (b) a Biomoby + * service invocation fails + ******************************************************************************************************************/ + public void process(int jobCount) throws MobyException { + + String xmlResponse = null; + + // input: raw-level processing + String xmlInput = fillRequest(); + if ( xmlInput != null ) { + if ( ( xmlInput = interceptRequest( xmlInput ) ) == null ) + return; + } + + // input: usual processing (i.e. collect XML in iterations) + else { + MobyPackage mobyInput = new MobyPackage(); + if ( !fillRequest( mobyInput, jobCount ) ) + return; + xmlInput = mobyInput.toXML(); + if ( ( xmlInput = interceptRequest( xmlInput ) ) == null ) + return; + } + + // calling service + xmlResponse = callRemoteService( xmlInput ); + + // output: raw-level processing + if ( !useResponse( xmlResponse ) ) + return; + + // output: usual processing (again by iterations) + MobyPackage mobyResponse = MobyPackage.createFromXML( xmlResponse ); + useResponse( mobyResponse ); + } + + public String interceptRequest(String xmlInput) throws MobyException { + return xmlInput; + } + + /******************************************************************************************************************* + * Create raw XML input. Override this method if you have already an input XML, or you want to create it yourself. + *

      + * + * @return a full XML input for a Biomoby service (in this case no other fillRequest methods will + * called); return null if no XML was created and a usual process to gather it will be used + * + * @throws MobyException if an XML cannot be created + ******************************************************************************************************************/ + public String fillRequest() throws MobyException { + return null; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected String filterMobyResponseType(Object result) throws MobyException { + if ( result instanceof String ) + return ( String ) result; + else if ( result instanceof byte[] ) + return new String( ( byte[] ) result ); + else + throw new MobyException( + "The Biomoby data should be sent/received either as type String or base64/byte[]. " + + "But they are of type '" + result.getClass().getName() + "'." ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected String callBiomobyService(MobyServiceLocator locator, String xmlInput) throws MobyException { + + MobyService service = locator.getService(); + String serviceName = service.getName(); + boolean asBytes = locator.isAsBytes(); + String serviceEndpoint = service.getURL(); + int timeout = locator.getSuggestedTimeout(); + + try { + URL target = new URL( serviceEndpoint ); + AxisCall call = new AxisCall( target, timeout ); + // to allow service calls which need authentication + setAuthentication( call.getCall() ); + call.getCall().setSOAPActionURI( MobyService.BIOMOBY_SERVICE_URI + "#" + serviceName ); + + return filterMobyResponseType( call.doCall( MobyService.BIOMOBY_SERVICE_URI, serviceName, + new Object[]{sendingFilter( xmlInput, asBytes )} ) ); + } + catch ( MalformedURLException e ) { + throw new MobyException( "Service endpoint '" + serviceEndpoint + "' is not a valid URL." ); + } + catch ( GException e ) { + throw new MobyException( e.getMessage(), e ); + } + } + + /** + * Sets the authentication for the call. The default implementation does not do anything ! + * + * @param call + */ + protected void setAuthentication(Call call) { + return; + } + + // + protected Object sendingFilter(String input, boolean asBytes) { + if ( asBytes ) { + log.debug( "Data sent as a byte array" ); + return input.getBytes(); + } + else { + return input; + } + } + + /******************************************************************************************************************* + * Call a SOAP-based BioMoby service. In order to find what service to call and what are its characteristics (such + * as its endpoint) it will call method {@link #getServiceLocator} that should be implemented by a sub-class. + *

      + * + * Once it has the service locator, this class does one of the following, in this order: + *

        + * + *
      • The locator must contain at least a service name. If it does not, an exception is raised. + * + *
      • If the locator contains a service endpoint, a call is made to this endpoint, using also the service name as + * a method name. + * + *
      • If the locator has a registry endpoint, an enquiry to the registry is made to find an endpoint of a service + * corresponding with the given service name. Once found, the service is called. + * + *
      • The same as the previous one but using a default registry. + * + * @param xmlInput data will be sent to the called Biomoby service + * + * @return service response (still in XML) + * + * @throws MobyException (a) if service call (or a call to registry; for example because the registry does not know + * given service) fails, or (b) if the used {@link MobyServiceLocator} does not contain a service name. + * + ******************************************************************************************************************/ + public String callRemoteService(String xmlInput) throws MobyException { + + // 1) service name is a must + MobyServiceLocator locator = getServiceLocator(); + MobyService service = locator.getService(); + if ( service == null ) + throw new MobyException( "MobyService locator returned an empty service object.\n" + + "I do not know what service to call..." ); + String serviceName = service.getName(); + if ( isEmpty( serviceName ) || MobyService.DUMMY_NAME.equals( serviceName ) ) + throw new MobyException( "MobyService locator returned an empty service name.\n" + + "I do not know what service to call..." ); + + // 2) try service endpoint + String serviceEndpoint = service.getURL(); + if ( notEmpty( serviceEndpoint ) ) + return callBiomobyService( locator, xmlInput ); + + // 3) find service endpoint in a Biomoby registry + Central worker = new CentralImpl( locator.getRegistryEndpoint(), locator.getRegistryNamespace() ); + MobyService[] services = worker.findService( service ); + if ( services == null || services.length == 0 ) + throw new MobyException( "Service " + service.toShortString() + " is not known in Biomoby registry: \n" + + "\t" + worker.getRegistryEndpoint() + "\n" + "\t" + worker.getRegistryNamespace() ); + // ...and call the service + serviceEndpoint = services[ 0 ].getURL(); + if ( notEmpty( serviceEndpoint ) ) { + service.setURL( serviceEndpoint ); + return callBiomobyService( locator, xmlInput ); + } + + // what else can I do? + throw new MobyException( "Registry has not returned any URL for service " + service.toShortString() ); + } + + /******************************************************************************************************************* + * Fill the whole 'mobyInput' - put there any number of jobs (queries) as you wish (you do not need to follow the + * 'jobCount' hint suggesting how many jobs should be put there). + *

        + * + * Usually there is not need to overwrite this method. It serves as an inter-mediator between the main + * {@link #process} method and the individual request fillings (done by a sub-class in method + * {@link #fillRequest(MobyJob,MobyPackage)}). + *

        + * + * @return false if you wish to cancel whole request (nothing will be sent to a Biomoby service); otherwise return + * true. + * + * @param mobyInput is an empty shell that you are supposed to fill with the input data for a Biomoby service + * execution + * + * @param jobCount is only a suggestion how many requests/job should be created (it comes from the {@link #process} + * method) - but it does not need to be obeyed + * + ******************************************************************************************************************/ + public boolean fillRequest(MobyPackage mobyInput, int jobCount) throws MobyException { + + if ( jobCount < 0 ) + jobCount = 0; + for ( int i = 0; i < jobCount; i++ ) { + MobyJob request = new MobyJob( "job_" + i ); + if ( !fillRequest( request, mobyInput ) ) + break; + mobyInput.addJob( request ); + } + return ( mobyInput.size() > 0 ); + } + + /******************************************************************************************************************* + * A raw-level processing. Use it if you need access to raw XML coming from a service. + *

        + * + * @param xmlResponse is a raw XML response returned from a BioMoby service + * + * @return false if the response should be considered fully processed (in this case no other 'useResponse' will be + * called); true indicates that normal processing of the response will follow; by default, this class (BaseClient) + * returns true + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'mobyResponse' is broken + ******************************************************************************************************************/ + public boolean useResponse(String xmlResponse) throws MobyException { + return true; + } + + /******************************************************************************************************************* + * A high-level processing. Use it if you need access to all jobs (queries) - that returned from a service - in the + * same time. Otherwise use the processing on the job level (method {@link #useResponse(MobyJob,MobyPackage)}. + *

        + * + * @param mobyResponse is a full response returned from a BioMoby service + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'mobyResponse' is broken + ******************************************************************************************************************/ + public void useResponse(MobyPackage mobyResponse) throws MobyException { + + // iterate over all input jobs + for ( int i = 0; i < mobyResponse.size(); i++ ) { + if ( !useResponse( mobyResponse.getJob( i ), mobyResponse ) ) + return; + } + } + + /******************************************************************************************************************* + * Extracts errors from a raw service response. It is iseful when one does not want to create a whole + * MobyPackage from a response, but just find whether a response is good or bad. + *

        + * + * @param xmlResponse is a full response returned from a BioMoby service + * + * @return a slightly formatted list of exceptions (of severity error) extracted from the response; or + * null if there are no errors there + ******************************************************************************************************************/ + public String errorsInResponse(String xmlResponse) { + try { + StringBuffer buf = new StringBuffer(); + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build( new StringReader( xmlResponse ) ); + Element root = doc.getRootElement(); + Element mobyContent = JDOMUtils.getChild( root, MobyTags.MOBYCONTENT ); + Element serviceNotes = JDOMUtils.getChild( mobyContent, MobyTags.SERVICENOTES ); + ServiceException[] exceptions = ServiceException.extractExceptions( serviceNotes ); + for ( int i = 0; i < exceptions.length; i++ ) { + if ( exceptions[ i ].getSeverity() != ServiceException.ERROR ) + continue; + if ( buf.length() > 0 ) + buf.append( "\n" ); + buf.append( exceptions[ i ].getErrorCodeAsString() ); + buf.append( ": " ); + buf.append( exceptions[ i ].getMessage() ); + } + return ( buf.length() == 0 ? null : new String( buf ) ); + + } + catch ( Exception e ) { + return e.toString(); + } + } + + // + // Abstract methods + // + + /******************************************************************************************************************* + * Return characteristics of a BioMoby service that will be called, and that reveal where to find such service. + *

        + * + * @see #callRemoteService + * + * @return an object defining a location of a BioMoby service + * @throws MobyException if service locator cannot be returned/created (e.g. because there is not enough information + * about what service to call) + ******************************************************************************************************************/ + abstract public MobyServiceLocator getServiceLocator() throws MobyException; + + /******************************************************************************************************************* + * Crate data (fill them into 'request') for one Moby job (query). The request will be sent within given + * 'inputContext' - but it is not yet there (because you may wish not to put it there - see the return value), and + * it is not the task of this method to put it there (just fill the 'request'). + *

        + * + * This is a method that should be implemented by a client developer, and it is the place where the client's + * business logic sits. + *

        + * + * @return true if this request should be included into the input data (package) that will be sent to a biomoby + * service; or return false if you do not wish to create any more requests for this particular package (also + * this 'request' will not be used) + * + * @param request is an object that you are supposed to fill with input data for one service invocation; it already + * has a name (so called 'query id' in the BioMoby speak) but you are free to change it + * + * @param inputContext is an envelope where all requests will be stored and sent to a Biomoby service; you do not + * need to do anything with it here unless you wish; note that all already created requests are there, + * but not the one you are just creating in this method + * + * @throws MobyException if you need so (from whatever reason in your business logic); if thrown then nothing will + * be sent to a Biomoby service + * + ******************************************************************************************************************/ + abstract public boolean fillRequest(MobyJob request, MobyPackage inputContext) throws MobyException; + + /******************************************************************************************************************* + * Process a single job returned from a BioMoby service. + *

        + * + * This is a method that should be implemented by a client developer, and it is the place where the client's + * business logic using the response sits. + *

        + * + * @param response is an object that you are supposed to use + * + * @param responseContext is an envelope where the full response (all its jobs) is located; you do not need to do + * anything with it here unless you wish (e.g. it gives you knowledge about how many jobs are in the full + * response, or it gives you access to the so-called 'service notes') + * + * @return false if you do not wish to get any more responses/jobs; otherwise return true + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'response' is broken + * + ******************************************************************************************************************/ + abstract public boolean useResponse(MobyJob response, MobyPackage responseContext) throws MobyException; + +} From groscurt at dev.open-bio.org Wed Nov 26 03:54:21 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:54:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260854.mAQ8sLbO017586@dev.open-bio.org> groscurt Wed Nov 26 03:54:21 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv17543/src/main/org/biomoby/service/dashboard Modified Files: SimpleClientPanel.java ServiceCallerModel.java DashboardProperties.java Log Message: changes done to enable authentication handling moby-live/Java/src/main/org/biomoby/service/dashboard SimpleClientPanel.java,1.12,1.13 ServiceCallerModel.java,1.6,1.7 DashboardProperties.java,1.29,1.30 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java 2008/05/27 16:06:14 1.12 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java 2008/11/26 08:54:21 1.13 @@ -1,774 +1,791 @@ -// SimpleClientPanel.java -// -// Created: December 2005 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.service.dashboard; - -import org.tulsoft.shared.UUtils; -import org.tulsoft.tools.gui.SwingUtils; -import org.tulsoft.tools.gui.AwtUtils; -import org.tulsoft.tools.gui.JFileChooserWithHistory; -import org.tulsoft.tools.gui.JTextFieldWithHistory; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.MobyDataType; -import org.biomoby.service.dashboard.data.ServiceInputPanel; -import org.biomoby.service.dashboard.data.DataContainer; - -import javax.swing.JPanel; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JRadioButton; -import javax.swing.ButtonGroup; -import javax.swing.JCheckBox; -import javax.swing.JSplitPane; -import javax.swing.JComponent; -import javax.swing.Box; -import javax.swing.tree.DefaultMutableTreeNode; - -import java.awt.GridBagLayout; -import java.awt.Component; -import java.awt.Color; -import java.awt.Font; -import java.awt.Insets; -import java.awt.Dimension; -import java.awt.event.KeyEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; - -import java.io.File; -import java.util.Date; - -/** - * A panel allowing to formulate input data and to call an arbitrary - * Biomoby service. Its interface is however not that user-friendly, - * and it is supposed to be used more or less for testing purposes in - * time when a new service is being created and developed.

        - * - * @author Martin Senger - * @version $Id$ - */ - -public class SimpleClientPanel - extends AbstractPanel { - - private static org.apache.commons.logging.Log log = - org.apache.commons.logging.LogFactory.getLog (SimpleClientPanel.class); - - /** A property name. Its value contains a name of color that will - * be used to display service name. - */ - protected static final String P_S_TITLE_COLOR = "simpleclient.service.title.color"; - - /** A property name. Its value contains a name of color that will - * be used as background for editable console with XML input. - */ - protected static final String P_S_EDIT_BGCOLOR = "simpleclient.service.edit.bgcolor"; - - // some texts - protected static final String INIT_SELECT = - "

        Start by selecting a service
        " + - "that you wish to call.
        "; - - protected static final String CALLER_ERROR = - "Sorry, an error happened when calling a service.\n\n"; - - protected static final Insets BREATH_UP = new Insets (6,6,0,6); - protected static final Insets BREATH_DOWN = new Insets (0,6,6,6); - - // associated models working behind the scene - RegistryModel registryModel; - ServiceCallerModel callerModel; - - // components that are used from more methods - JLabel selService; - CommonConsole input; - JFileChooserWithHistory outFile, inFile; - JButton runButton, stopButton; - JCheckBox iShowXML, iFromFile; - JTextFieldWithHistory className, endpoint; - JPanel dataTablesPanel; - ServiceInputPanel inputDataTables; - MySwingWorker runWorker; - ResultsPanel results; - JComponent resultsComp; - JSplitPane resSplit; -// JTextFieldWithHistory recentServices; - - boolean selectionAllowed = false; - - // shared icons - protected static Icon runIcon, runIconDis; - protected static Icon stopIcon, stopIconDis; - protected static Icon addDataIcon, addDataIconDis; - - /********************************************************************* - * Default constructor. - ********************************************************************/ - public SimpleClientPanel() { - super(); - panelIconFileName = "images/debug.gif"; - } - - /********************************************************************* - * Load shared icons. - ********************************************************************/ - protected void loadIcons() { - super.loadIcons(); - - if (runIcon == null) runIcon = loadIcon ("images/smallRun.gif"); - if (runIconDis == null) runIconDis = loadIcon ("images/smallRun_dis.gif"); - - if (stopIcon == null) stopIcon = loadIcon ("images/smallCancel.gif"); - if (stopIconDis == null) stopIconDis = loadIcon ("images/smallCancel_dis.gif"); - - if (addDataIcon == null) addDataIcon = loadIcon ("images/smallAnnotate.gif"); - if (addDataIconDis == null) addDataIconDis = loadIcon ("images/smallAnnonate_dis.gif"); - - } - - /************************************************************************** - * - **************************************************************************/ - public JComponent getComponent (PropertyChannel aPropertyChannel) { - setPropertyChannel (aPropertyChannel); - registryModel = createRegistryModel(); - callerModel = new ServiceCallerModel(); - callerModel.setPropertyChannel (aPropertyChannel); - - if (pComponent != null) return pComponent; - pComponent = new JPanel (new GridBagLayout(), true); - - // result panel - results = new ResultsPanel(); - resultsComp = results.getComponent (aPropertyChannel); - propertyChannel.addPropertyChangeListener (new PropertyChangeListener() { - public void propertyChange (PropertyChangeEvent e) { - if (DP_DETACH_VIEW.equals (e.getPropertyName())) { - - MobyService srv = - (MobyService)propertyChannel.get (DP_SC_SERVICE); - String title = (srv == null ? "Service results" : - srv.getName() + " at " + new Date()); - JComponent current = results.getComponent (propertyChannel); - results.adjustForDetachement(); - JFrame newFrame = - SwingUtils.createSoftMainFrame (current, - title); - Dimension dim = current.getPreferredSize(); - SwingUtils.showMainFrameRelativeTo - (pComponent, newFrame, (int)dim.getWidth(), (int)dim.getHeight()); - results = new ResultsPanel(); - resultsComp = results.getComponent (propertyChannel); - resSplit.setBottomComponent (resultsComp); - } - }}); - - - // panel with all the fields (except for building inputs) - JPanel controls = getControlPanel(); - - // panel with input data - JPanel inputData = getInputPanel(); - updateInputDataPanel (INIT_SELECT); - - // service ontology tree - JPanel sBoard = new JPanel (new GridBagLayout()); -// JLabel lRecent = new JLabel ("Recently called services"); -// recentServices = createText (null, -// DP_SC_SERVICES, -// DP_SC_SERVICES); -// recentServices.addActionListener (new ActionListener() { -// public void actionPerformed (ActionEvent e) { -// String contents = ((JTextFieldWithHistory)e.getSource()).getText(); -// if (! "".equals (contents) && selectionAllowed) { -// System.out.println ("SEL: " + contents); -// selectService (contents); -// } -// } -// }); - - ServicesBoard servicesBoard = - new ServicesBoard (registryModel, - null, - propertyChannel, - new CustomServicesTree (registryModel, - null)); - log.debug ("Services tree update started"); - servicesBoard.updateTree (CommonTree.SORTED_BY_AUTHORITY); -// SwingUtils.addComponent (sBoard, lRecent, 0, 0, 1, 1, NONE, NWEST, 0.0, 0.0, BREATH_UP); -// SwingUtils.addComponent (sBoard, recentServices, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0, BREATH_DOWN); - SwingUtils.addComponent (sBoard, servicesBoard, 0, 2, 1, 1, BOTH, NWEST, 1.0, 1.0); - - // split it into moving panels - JSplitPane split = hSplit (resSplit = vSplit (hSplit (controls, - sBoard, 0.5), - resultsComp, 0.1), - inputData, - 0.5); - - SwingUtils.addComponent (pComponent, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - - // initialize by a last used service name from preferences - String lastServiceName = getPrefValue (DP_SC_SERVICE_NAME, ""); - if (! "".equals (lastServiceName)) - selectService (lastServiceName); - - return pComponent; - } - - /************************************************************************** - * Create a sub-panel for all the controls... - **************************************************************************/ - protected JPanel getControlPanel() { - JPanel p = new JPanel (new GridBagLayout()); - - // (selected) service name - selService = new JLabel(); - selService.setFont (FAT_BORDER_FONT); - selService.setForeground - (GraphColours.getColour (DashboardConfig.getString (P_S_TITLE_COLOR, null), - Color.blue)); - - // how to invoke the service - JPanel howTo = createTitledPanel ("Service invocation"); - endpoint = createText (null, DP_ENDPOINT, DP_ENDPOINT); - className = createText (null, DP_IMPL_CLASS, DP_IMPL_CLASS); - - ButtonGroup group = new ButtonGroup(); - JRadioButton htNone, htRegistry, htEndpoint, htLocal, htNewURL; - group.add (htEndpoint = createHowToButton ("Use service's usual endpoint", DP_CS_URL)); - htNone = createHowToButton ("No real call, just show/echo input", DP_CS_NONE); - htNone.addItemListener( - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - if (enabled) runButton.setText(" Show Input "); - else { - if (propertyChannel.getBoolean(DP_INP_PING, false)){ - runButton.setText(" Ping Service "); - } - else { - runButton.setText(" Call Service "); - } - } - } - }); - group.add (htNone); - group.add (htRegistry = createHowToButton ("Ask registry where service is, and call it", DP_CS_REGISTRY)); - group.add (htNewURL = createHowToButton ("Use this endpoint", DP_CS_NEWURL)); - group.add (htLocal = createHowToButton ("Use this local class", DP_CS_CLASS)); - - // run the service - // determine button text from preferences - boolean usingPing = getPrefValue (DP_INP_PING, false); - boolean usingAsBytes = getPrefValue (DP_INP_ASBYTES, false); - String runLabel = " Call Service "; - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runLabel = " Show Input "; - else if (usingPing) runLabel = " Ping Service "; - - runButton = - createButton (runLabel, - "Invoke selected service", - KeyEvent.VK_C, - new ActionListener() { - public void actionPerformed (ActionEvent e) { - MobyService srv = (MobyService)propertyChannel.get (DP_SC_SERVICE); - if (srv != null) { - runWorker = new MySwingWorker (srv); - runWorker.start(); - } - } - }); - runButton.setIcon (runIcon); - runButton.setDisabledIcon (runIconDis); - runButton.setEnabled (false); // will enable when a service is selected - - stopButton = - createButton (" Stop service ", - "Cancel connection to a running service", - KeyEvent.VK_S, - new ActionListener() { - public void actionPerformed (ActionEvent e) { - if (runWorker != null) { -// runWorker.interrupt(); // no sense with the current Biomoby API - runWorker.cancel(); - } - serviceFinished(); - } - }); - stopButton.setIcon (stopIcon); - stopButton.setDisabledIcon (stopIconDis); - stopButton.setEnabled (false); // will enable when a service is called - - JPanel buttonPanel = createButtonPanel (new JButton[] { runButton, - stopButton }); - - JCheckBox asPing = createCheckBox - ("'Ping' this service", - usingPing, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPropertySelect (enabled, DP_INP_PING); - setPrefValue (DP_INP_PING, enabled); - propertyChannel.put (DP_INP_PING, - new Boolean (enabled).toString()); - if (enabled) { - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runButton.setText(" Show Input "); - else - runButton.setText(" Ping Service "); - } - else { - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runButton.setText(" Show Input "); - else - runButton.setText(" Call Service "); - } - } - }); - setPropertySelect (usingPing, DP_INP_PING); - asPing.setToolTipText ("A Moby 'Ping' is used to determine if the service is responsive " + - "and if it responds in an API-compliant manner."); - Font font = asPing.getFont(); - asPing.setFont (font.deriveFont (Math.max (1, font.getSize2D() - 1))); - - JCheckBox asBytes = createCheckBox - ("Send data to service as a byte array", - usingAsBytes, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPropertySelect (enabled, DP_INP_ASBYTES); - setPrefValue (DP_INP_ASBYTES, enabled); - propertyChannel.put (DP_INP_ASBYTES, - new Boolean (enabled).toString()); - } - }); - setPropertySelect (usingAsBytes, DP_INP_ASBYTES); - asBytes.setToolTipText ("It should not have any effect on result; it is for debugging"); - font = asBytes.getFont(); - asBytes.setFont (font.deriveFont (Math.max (1, font.getSize2D() - 1))); - - - SwingUtils.addComponent (howTo, htEndpoint, 0, 0, 2, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htNewURL, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, endpoint, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htRegistry, 0, 2, 2, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, htLocal, 0, 3, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, className, 1, 3, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htNone, 0, 4, 2, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, asPing, 0, 5, 2, 1, NONE, NWEST, 0.0, 0.0, BREATH_TOP); - SwingUtils.addComponent (howTo, asBytes, 0, 6, 2, 1, NONE, NWEST, 0.0, 0.0); - - - Component glue = Box.createVerticalGlue(); - SwingUtils.addComponent (p, selService, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0); - SwingUtils.addComponent (p, howTo, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (p, buttonPanel, 0, 2, 1, 1, NONE, CENTER, 0.0, 0.0, BREATH_TOP); - SwingUtils.addComponent (p, glue, 0, 3, 1, 1, VERT, NWEST, 0.0, 1.0); - return p; - } - - /************************************************************************** - * Select/unselect using 'send as bytes' or 'ping'... - **************************************************************************/ - protected void setPropertySelect (boolean enabled, String property) { - setPrefValue (property, enabled); - propertyChannel.put (property, new Boolean (enabled).toString()); - } - - /************************************************************************** - * Create a specialized radio button - for various ways how to - * call a service. - **************************************************************************/ - private JRadioButton createHowToButton (String title, String howTo) { - JRadioButton radio = new JRadioButton (title); - radio.setActionCommand (howTo); - radio.addActionListener (howToListener); - String initHowTo = getPrefValue (DP_CALL_SERVICE, DP_CS_NONE); - if (howTo.equals (initHowTo)) { - radio.setSelected (true); - radio.setEnabled (true); - propertyChannel.put (DP_CALL_SERVICE, howTo); - } - endpoint.setEnabled (initHowTo.equals (DP_CS_NEWURL)); - className.setEnabled (initHowTo.equals (DP_CS_CLASS)); - return radio; - } - - // - private ActionListener howToListener = new ActionListener() { - public void actionPerformed (ActionEvent e) { - String howTo = e.getActionCommand(); - setPrefValue (DP_CALL_SERVICE, howTo); - propertyChannel.put (DP_CALL_SERVICE, howTo); - endpoint.setEnabled (howTo.equals (DP_CS_NEWURL)); - className.setEnabled (howTo.equals (DP_CS_CLASS)); - } - }; - - /************************************************************************** - * Create a specialized check box for "what to do with input/output"... - **************************************************************************/ - private JCheckBox createDataBox (String title, - final String preferenceKey, - boolean defaultValue) { - boolean initValue = getPrefValue (preferenceKey, defaultValue); - propertyChannel.put (preferenceKey, - new Boolean (initValue).toString()); - return createCheckBox - (title, initValue, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPrefValue (preferenceKey, enabled); - propertyChannel.put (preferenceKey, - new Boolean (enabled).toString()); - inFile.setEnabled (iFromFile.isSelected()); - } - }); - } - - /************************************************************************** - * Create a sub-panel for service inputs... - **************************************************************************/ - protected JPanel getInputPanel() { - JPanel inputData = new JPanel (new GridBagLayout()); - inputData.setBorder (createFatBorder - ("Service Input Data", - GraphColours.getColour ("cadetblue", Color.blue))); - - // upper part (tables, input file, show-xml check-box) - JPanel upper = new JPanel (new GridBagLayout()); - - dataTablesPanel = new JPanel (new GridBagLayout()); - - iFromFile = createDataBox ("Take an input from this XML file", DP_SC_IN_FILE, false); - inFile = createFileSelector ("Select input XML for calling a service", - "Select", - null, - DP_SC_INPUT_FILE, - DP_SC_INPUT_FILE); - inFile.setEnabled (iFromFile.isSelected()); - - iShowXML = createDataBox ("Show input as XML", DP_INP_SHOWXML, true); - - SwingUtils.addComponent (upper, dataTablesPanel, 0, 0, 2, 1, BOTH, NWEST, 1.0, 1.0); - SwingUtils.addComponent (upper, iFromFile, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (upper, inFile, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (upper, iShowXML, 0, 2, 1, 1, NONE, NWEST, 0.0, 0.0); - - // lower part (console showing/editing input XML) - input = new EditableConsole(); - input.setAppendMode (false); - input.setVerboseMode (false); - - // split upper and lower parts into moving panels - JSplitPane split = vSplit (upper, input, 0.5); - SwingUtils.addComponent (inputData, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - return inputData; - } - - class EditableConsole - extends CommonConsole { - - public EditableConsole() { - super(); - textArea.setEditable (true); - textArea.setBackground - (GraphColours.getColour (DashboardConfig.getString (P_S_EDIT_BGCOLOR, null), - textArea.getBackground())); - } - } - - /************************************************************************** - * Replace the global 'dataTablesPanel' with an information text. - **************************************************************************/ - protected void updateInputDataPanel (String info) { - dataTablesPanel.removeAll(); - AwtUtils.redisplay (dataTablesPanel); - - JLabel text = new JLabel (info); - SwingUtils.addComponent (dataTablesPanel, text, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0); - dataTablesPanel.validate(); - return; - } - - /************************************************************************** - * Replace the global 'dataTablesPanel' with fields defining the - * input data for the given service. - **************************************************************************/ - protected void updateInputDataPanel (MobyService service, - MobyDataType[] dataTypes) { - dataTablesPanel.removeAll(); - - inputDataTables = new ServiceInputPanel (service, dataTypes); - SwingUtils.addComponent (dataTablesPanel, inputDataTables, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - dataTablesPanel.validate(); - } - - /************************************************************************** - * Find 'dataTypeToBeFound in 'dataTypes' and return it. The same - * could be achieved by calling registryModel.getDataType() but - * here I do not want to create yet another swing worker for it. - **************************************************************************/ - protected MobyDataType findDataType (String dataTypeToBeFound, - MobyDataType[] dataTypes) { - for (int i = 0; i < dataTypes.length; i++) { - if (dataTypeToBeFound.equals (dataTypes[i].getName())) - return dataTypes[i]; - } - log.error ("Strange, data type '" + dataTypeToBeFound + - "' was not found in " + dataTypes.length + " data types."); - return null; - } - - /************************************************************************** - * - * A worker that calls the service... - * - **************************************************************************/ - class MySwingWorker - extends SwingWorker { - - MobyException exception = null; - DataContainer data = new DataContainer(); - boolean wasCancelled = false; - MobyService service; - - public MySwingWorker (MobyService service) { - super(); - this.service = service; - data.setMetadata (propertyChannel); - } - - public void cancel() { - wasCancelled = true; - propertyChannel.fire (DP_STATUS_MSG, "Service invocation cancelled."); - } - - public Object construct() { - try { - runButton.setEnabled (false); - propertyChannel.fire (DP_STATUS_MSG, - "Calling service " + service.getName() + "..."); - - // create a data container with input data... - if (propertyChannel.getBoolean (DP_SC_IN_FILE, false)) { - - // ...either from a file - String inputFile = propertyChannel.getString (DP_SC_INPUT_FILE); - if (UUtils.isEmpty (inputFile)) - throw new MobyException ("No input XML file given."); - data.setDataFromFile (new File (inputFile)); - - } else { - data.setData (inputDataTables.toXML()); - } - - // optionally, show XML data: we want to show this XML - // input only (a) if it was explicitly asked for (property - // DP_INP_SHOWXML is true), or (b) if "no real service - // call" was selected (property DP_CALL_SERVICE has value - // DP_CS_NONE) - if ( DP_CS_NONE.equals (propertyChannel.getString (DP_CALL_SERVICE)) || - (propertyChannel.getBoolean (DP_INP_SHOWXML, false)) ) { - input.setText ((String)data.getData()); - } - - // If we are only pinging the service, set the data object to an empty message - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - String emptyMsg = "\n" + - "\n" + - " \n" + - ""; - data.setData(emptyMsg); - input.setText(emptyMsg); - } - - // finally, call the service - stopButton.setEnabled (true); - callerModel.runIt (data); - - } catch (MobyException e) { - exception = e; - - } catch (Error e) { - exception = new MobyException (e.toString()); - } - return null; // not used here - } - - // runs on the event-dispatching thread - public void finished() { - if (wasCancelled) { - // service was interrupted by the Stop button - do - // nothing (the whole GUI should be already in a good - // state - the button 'Stop' took care about it) - return; - } - - if (exception == null) { - - // handle results here (using renderers...) - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - propertyChannel.fire (DP_STATUS_MSG, service.getName()+" isAlive."); - } else { - propertyChannel.fire (DP_STATUS_MSG, "Service invocation finished."); - } - - if (! DP_CS_NONE.equals (propertyChannel.getString (DP_CALL_SERVICE))) { - results.updateComponent (data); - } - - } else { - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - propertyChannel.fire (DP_STATUS_MSG, service.getName()+" is dead."); - results.removeResults(); - } else { - propertyChannel.fire (DP_STATUS_MSG, "Service invocation failed."); - error (CALLER_ERROR, exception); - } - exception.printStackTrace(); - } - serviceFinished(); - } - } - - /************************************************************************** - * Called when a call to a service finished. - **************************************************************************/ - protected void serviceFinished() { - runButton.setEnabled (true); - stopButton.setEnabled (false); - } - - /************************************************************************** - * Called when a service is selected in a service tree (or in a - * 'recently used services' combo box), and also at the beginning - * when a service name is retrieved from user preferences. - * - * Get selected service from a registry model and generate a new - * 'input data panel' to reflect input data of the selected - * service. - **************************************************************************/ - protected void selectService (final String serviceName) { - final Object source = this; - final SwingWorker worker = new SwingWorker() { - MobyService service; - MobyDataType[] dataTypes; - public Object construct() { - try { - service = registryModel.getService (serviceName); - dataTypes = registryModel.getDataTypes (source); - } catch (MobyException e) { - error (ServicesTree.SERVICES_ACCESS_ERROR, e); - } - return service; // not used here - } - - // runs on the event-dispatching thread. - public void finished() { - if (service == null) { - deselectService(); - } else { - updateInputDataPanel (service, dataTypes); - selService.setText (service.getName()); -// selectionAllowed = false; -// recentServices.setText (service.getName()); -// selectionAllowed = true; - propertyChannel.put (DP_SC_SERVICE, service); - runButton.setEnabled (true); - - } - } - }; - worker.start(); - } - - /************************************************************************** - * Called when no service is selected in order to display this - * fact on various places in the panel. - **************************************************************************/ - protected void deselectService() { - selService.setText (""); - updateInputDataPanel (INIT_SELECT); - propertyChannel.remove (DP_SC_SERVICE); - runButton.setEnabled (false); - } - - /************************************************************************** - * - **************************************************************************/ - public String getName() { - return "Simple Client"; - } - - /************************************************************************** - * - **************************************************************************/ - public String getDescription() { - return - "A panel allowing to create input data and to call an arbitrary Biomoby service. " + - "Its purpose is mostly for the service developers to test their new services."; - } - - /************************************************************************** - * - * Customized tree of services... - * - **************************************************************************/ - protected class CustomServicesTree - extends ServicesTree { - - /********************************************************************* - * Construtor - ********************************************************************/ - public CustomServicesTree (RegistryModel model, - CommonConsole console) { - super (model, console); - } - - /********************************************************************* - * - ********************************************************************/ - protected void createPopups (String title) { - super.createPopups (title); - removeFromPopups (AC_RELOAD); - removeSeparatorAfter (AC_COLLAPSE); - } - - /********************************************************************* - * Service selected in a service tree... - ********************************************************************/ - protected void selected (DefaultMutableTreeNode node) { - if (node == null) { - // nothing selected - deselectService(); - return; - } - updateInputDataPanel ("Loading..."); - selService.setText (""); - final CommonNode nodeObject = (CommonNode)node.getUserObject(); - String currentServiceName = nodeObject.getValue(); - selectService (currentServiceName); - setPrefValue (DP_SC_SERVICE_NAME, currentServiceName); - } - } - -} +// SimpleClientPanel.java +// +// Created: December 2005 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.service.dashboard; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.Date; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JRadioButton; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.tree.DefaultMutableTreeNode; + +import org.biomoby.service.dashboard.data.DataContainer; +import org.biomoby.service.dashboard.data.ServiceInputPanel; +import org.biomoby.shared.MobyDataType; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.tulsoft.shared.UUtils; +import org.tulsoft.tools.gui.AwtUtils; +import org.tulsoft.tools.gui.JFileChooserWithHistory; +import org.tulsoft.tools.gui.JTextFieldWithHistory; +import org.tulsoft.tools.gui.SwingUtils; + +/** + * A panel allowing to formulate input data and to call an arbitrary Biomoby service. Its interface is however not that + * user-friendly, and it is supposed to be used more or less for testing purposes in time when a new service is being + * created and developed. + *

        + * + * @author Martin Senger + * @version $Id$ + */ + +public class SimpleClientPanel extends AbstractPanel { + + private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory + .getLog( SimpleClientPanel.class ); + + /** + * A property name. Its value contains a name of color that will be used to display service name. + */ + protected static final String P_S_TITLE_COLOR = "simpleclient.service.title.color"; + + /** + * A property name. Its value contains a name of color that will be used as background for editable console with XML + * input. + */ + protected static final String P_S_EDIT_BGCOLOR = "simpleclient.service.edit.bgcolor"; + + // some texts + protected static final String INIT_SELECT = "

        Start by selecting a service
        " + + "that you wish to call.
        "; + + protected static final String CALLER_ERROR = "Sorry, an error happened when calling a service.\n\n"; + + protected static final Insets BREATH_UP = new Insets( 6, 6, 0, 6 ); + protected static final Insets BREATH_DOWN = new Insets( 0, 6, 6, 6 ); + + // associated models working behind the scene + RegistryModel registryModel; + ServiceCallerModel callerModel; + + // components that are used from more methods + JLabel selService; + CommonConsole input; + JFileChooserWithHistory outFile, inFile; + JButton runButton, stopButton; + JCheckBox iShowXML, iFromFile; + JTextFieldWithHistory className, endpoint; + JPanel dataTablesPanel; + ServiceInputPanel inputDataTables; + MySwingWorker runWorker; + ResultsPanel results; + JComponent resultsComp; + JSplitPane resSplit; + // JTextFieldWithHistory recentServices; + + boolean selectionAllowed = false; + + // shared icons + protected static Icon runIcon, runIconDis; + protected static Icon stopIcon, stopIconDis; + protected static Icon addDataIcon, addDataIconDis; + + /******************************************************************************************************************* + * Default constructor. + ******************************************************************************************************************/ + public SimpleClientPanel() { + super(); + panelIconFileName = "images/debug.gif"; + } + + /******************************************************************************************************************* + * Load shared icons. + ******************************************************************************************************************/ + protected void loadIcons() { + super.loadIcons(); + + if ( runIcon == null ) runIcon = loadIcon( "images/smallRun.gif" ); + if ( runIconDis == null ) runIconDis = loadIcon( "images/smallRun_dis.gif" ); + + if ( stopIcon == null ) stopIcon = loadIcon( "images/smallCancel.gif" ); + if ( stopIconDis == null ) stopIconDis = loadIcon( "images/smallCancel_dis.gif" ); + + if ( addDataIcon == null ) addDataIcon = loadIcon( "images/smallAnnotate.gif" ); + if ( addDataIconDis == null ) addDataIconDis = loadIcon( "images/smallAnnonate_dis.gif" ); + + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public JComponent getComponent( PropertyChannel aPropertyChannel ) { + setPropertyChannel( aPropertyChannel ); + registryModel = createRegistryModel(); + callerModel = new ServiceCallerModel(); + callerModel.setPropertyChannel( aPropertyChannel ); + + if ( pComponent != null ) return pComponent; + pComponent = new JPanel( new GridBagLayout(), true ); + + // result panel + results = new ResultsPanel(); + resultsComp = results.getComponent( aPropertyChannel ); + propertyChannel.addPropertyChangeListener( new PropertyChangeListener() { + public void propertyChange( PropertyChangeEvent e ) { + if ( DP_DETACH_VIEW.equals( e.getPropertyName() ) ) { + + MobyService srv = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + String title = ( srv == null ? "Service results" : srv.getName() + " at " + new Date() ); + JComponent current = results.getComponent( propertyChannel ); + results.adjustForDetachement(); + JFrame newFrame = SwingUtils.createSoftMainFrame( current, title ); + Dimension dim = current.getPreferredSize(); + SwingUtils.showMainFrameRelativeTo( pComponent, newFrame, ( int ) dim.getWidth(), ( int ) dim + .getHeight() ); + results = new ResultsPanel(); + resultsComp = results.getComponent( propertyChannel ); + resSplit.setBottomComponent( resultsComp ); + } + } + } ); + + // panel with all the fields (except for building inputs) + JPanel controls = getControlPanel(); + + // panel with input data + JPanel inputData = getInputPanel(); + updateInputDataPanel( INIT_SELECT ); + + // service ontology tree + JPanel sBoard = new JPanel( new GridBagLayout() ); + // JLabel lRecent = new JLabel ("Recently called services"); + // recentServices = createText (null, + // DP_SC_SERVICES, + // DP_SC_SERVICES); + // recentServices.addActionListener (new ActionListener() { + // public void actionPerformed (ActionEvent e) { + // String contents = ((JTextFieldWithHistory)e.getSource()).getText(); + // if (! "".equals (contents) && selectionAllowed) { + // System.out.println ("SEL: " + contents); + // selectService (contents); + // } + // } + // }); + + ServicesBoard servicesBoard = new ServicesBoard( registryModel, null, propertyChannel, new CustomServicesTree( + registryModel, null ) ); + log.debug( "Services tree update started" ); + servicesBoard.updateTree( CommonTree.SORTED_BY_AUTHORITY ); + // SwingUtils.addComponent (sBoard, lRecent, 0, 0, 1, 1, NONE, NWEST, 0.0, 0.0, BREATH_UP); + // SwingUtils.addComponent (sBoard, recentServices, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0, BREATH_DOWN); + SwingUtils.addComponent( sBoard, servicesBoard, 0, 2, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + + // split it into moving panels + JSplitPane split = hSplit( resSplit = vSplit( hSplit( controls, sBoard, 0.5 ), resultsComp, 0.1 ), inputData, + 0.5 ); + + SwingUtils.addComponent( pComponent, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + + // initialize by a last used service name from preferences + String lastServiceName = getPrefValue( DP_SC_SERVICE_NAME, "" ); + if ( !"".equals( lastServiceName ) ) selectService( lastServiceName ); + + return pComponent; + } + + /******************************************************************************************************************* + * Create a sub-panel for all the controls... + ******************************************************************************************************************/ + protected JPanel getControlPanel() { + JPanel p = new JPanel( new GridBagLayout() ); + + // (selected) service name + selService = new JLabel(); + selService.setFont( FAT_BORDER_FONT ); + selService.setForeground( GraphColours.getColour( DashboardConfig.getString( P_S_TITLE_COLOR, null ), + Color.blue ) ); + + // how to invoke the service + JPanel howTo = createTitledPanel( "Service invocation" ); + endpoint = createText( null, DP_ENDPOINT, DP_ENDPOINT ); + className = createText( null, DP_IMPL_CLASS, DP_IMPL_CLASS ); + + ButtonGroup group = new ButtonGroup(); + JRadioButton htNone, htRegistry, htEndpoint, htLocal, htNewURL; + group.add( htEndpoint = createHowToButton( "Use service's usual endpoint", DP_CS_URL ) ); + htNone = createHowToButton( "No real call, just show/echo input", DP_CS_NONE ); + htNone.addItemListener( new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + if ( enabled ) + runButton.setText( " Show Input " ); + else { + if ( propertyChannel.getBoolean( DP_INP_PING, false ) ) { + runButton.setText( " Ping Service " ); + } + else { + runButton.setText( " Call Service " ); + } + } + } + } ); + group.add( htNone ); + group.add( htRegistry = createHowToButton( "Ask registry where service is, and call it", DP_CS_REGISTRY ) ); + group.add( htNewURL = createHowToButton( "Use this endpoint", DP_CS_NEWURL ) ); + group.add( htLocal = createHowToButton( "Use this local class", DP_CS_CLASS ) ); + + // run the service + // determine button text from preferences + boolean usingPing = getPrefValue( DP_INP_PING, false ); + boolean usingAsBytes = getPrefValue( DP_INP_ASBYTES, false ); + String runLabel = " Call Service "; + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runLabel = " Show Input "; + else if ( usingPing ) runLabel = " Ping Service "; + + runButton = createButton( runLabel, "Invoke selected service", KeyEvent.VK_C, new ActionListener() { + public void actionPerformed( ActionEvent e ) { + MobyService srv = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + if ( srv != null ) { + // if the authentication was selected a dialog opens to ask for the user/password + if ( propertyChannel.getBoolean( DP_AUTHENTICATION, false ) ) { + askForAuthentication(); + } + // if not make sure to remove any previous authentication + else { + propertyChannel.remove( DP_USER_AUTHENTICATION ); + propertyChannel.remove( DP_PASSWORD_AUTHENTICATION ); + } + runWorker = new MySwingWorker( srv ); + runWorker.start(); + } + } + } ); + runButton.setIcon( runIcon ); + runButton.setDisabledIcon( runIconDis ); + runButton.setEnabled( false ); // will enable when a service is selected + + stopButton = createButton( " Stop service ", "Cancel connection to a running service", KeyEvent.VK_S, + new ActionListener() { + public void actionPerformed( ActionEvent e ) { + if ( runWorker != null ) { + // runWorker.interrupt(); // no sense with the current Biomoby API + runWorker.cancel(); + } + serviceFinished(); + } + } ); + stopButton.setIcon( stopIcon ); + stopButton.setDisabledIcon( stopIconDis ); + stopButton.setEnabled( false ); // will enable when a service is called + + JPanel buttonPanel = createButtonPanel( new JButton[] { runButton, stopButton } ); + + JCheckBox asPing = createCheckBox( "'Ping' this service", usingPing, -1, new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPropertySelect( enabled, DP_INP_PING ); + setPrefValue( DP_INP_PING, enabled ); + propertyChannel.put( DP_INP_PING, new Boolean( enabled ).toString() ); + if ( enabled ) { + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runButton.setText( " Show Input " ); + else + runButton.setText( " Ping Service " ); + } + else { + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runButton.setText( " Show Input " ); + else + runButton.setText( " Call Service " ); + } + } + } ); + setPropertySelect( usingPing, DP_INP_PING ); + asPing.setToolTipText( "A Moby 'Ping' is used to determine if the service is responsive " + + "and if it responds in an API-compliant manner." ); + Font font = asPing.getFont(); + asPing.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + JCheckBox asBytes = createCheckBox( "Send data to service as a byte array", usingAsBytes, -1, + new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPropertySelect( enabled, DP_INP_ASBYTES ); + setPrefValue( DP_INP_ASBYTES, enabled ); + propertyChannel.put( DP_INP_ASBYTES, new Boolean( enabled ).toString() ); + } + } ); + setPropertySelect( usingAsBytes, DP_INP_ASBYTES ); + asBytes.setToolTipText( "It should not have any effect on result; it is for debugging" ); + font = asBytes.getFont(); + asBytes.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + JCheckBox authenticationBox = createCheckBox( "Use a user/password for authentication", false, -1, + new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + propertyChannel.put( DP_AUTHENTICATION, e.getStateChange() == ItemEvent.SELECTED ); + } + } ); + authenticationBox.setToolTipText( "If the service requires authentication. " + + "A dialog will open if you call the service to enter the authentication." ); + font = authenticationBox.getFont(); + authenticationBox.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + SwingUtils.addComponent( howTo, htEndpoint, 0, 0, 2, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htNewURL, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, endpoint, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htRegistry, 0, 2, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, htLocal, 0, 3, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, className, 1, 3, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htNone, 0, 4, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, asPing, 0, 5, 2, 1, NONE, NWEST, 0.0, 0.0, BREATH_TOP ); + SwingUtils.addComponent( howTo, asBytes, 0, 6, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, authenticationBox, 0, 7, 2, 1, NONE, NWEST, 0.0, 0.0 ); + + Component glue = Box.createVerticalGlue(); + SwingUtils.addComponent( p, selService, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0 ); + SwingUtils.addComponent( p, howTo, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( p, buttonPanel, 0, 2, 1, 1, NONE, CENTER, 0.0, 0.0, BREATH_TOP ); + SwingUtils.addComponent( p, glue, 0, 3, 1, 1, VERT, NWEST, 0.0, 1.0 ); + return p; + } + + /******************************************************************************************************************* + * Select/unselect using 'send as bytes' or 'ping'... + ******************************************************************************************************************/ + protected void setPropertySelect( boolean enabled, String property ) { + setPrefValue( property, enabled ); + propertyChannel.put( property, new Boolean( enabled ).toString() ); + } + + /******************************************************************************************************************* + * Opens a dialog and asks for webservice authentication + ******************************************************************************************************************/ + private void askForAuthentication() { + final JDialog dialog = new JDialog( new JFrame(), "Authentication", true ); + JPanel panel = new JPanel( new GridBagLayout() ); + panel.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ) ); + + Insets insets = new Insets( 4, 4, 4, 4 ); + + JLabel label = new JLabel( "Please enter your username and password !" ); + SwingUtils.addComponent( panel, label, 0, 0, 2, 1, HORI, CENTER, 1, 0, insets ); + + label = new JLabel( "User: " ); + SwingUtils.addComponent( panel, label, 0, 1, 1, 1, HORI, NWEST, 0, 0, insets ); + + final JTextField userField = new JTextField( propertyChannel.getString( DP_USER_AUTHENTICATION ), 20 ); + SwingUtils.addComponent( panel, userField, 1, 1, 1, 1, HORI, NWEST, 0, 0, insets ); + + label = new JLabel( "Password: " ); + SwingUtils.addComponent( panel, label, 0, 2, 1, 1, HORI, NWEST, 0, 0, insets ); + + final JPasswordField passwordField = new JPasswordField( + propertyChannel.getString( DP_PASSWORD_AUTHENTICATION ), 20 ); + SwingUtils.addComponent( panel, passwordField, 1, 2, 1, 1, HORI, NWEST, 0, 0, insets ); + + JButton button = new JButton( "Enter..." ); + button.addActionListener( new ActionListener() { + public void actionPerformed( ActionEvent e ) { + propertyChannel.put( DP_USER_AUTHENTICATION, userField.getText() ); + propertyChannel.put( DP_PASSWORD_AUTHENTICATION, passwordField.getPassword() ); + + dialog.setVisible( false ); + } + } ); + SwingUtils.addComponent( panel, button, 0, 3, 2, 1, HORI, CENTER, 0, 0, insets ); + + dialog.setContentPane( panel ); + dialog.pack(); + dialog.setLocationRelativeTo( this ); + dialog.setVisible( true ); + } + + /******************************************************************************************************************* + * Create a specialized radio button - for various ways how to call a service. + ******************************************************************************************************************/ + private JRadioButton createHowToButton( String title, String howTo ) { + JRadioButton radio = new JRadioButton( title ); + radio.setActionCommand( howTo ); + radio.addActionListener( howToListener ); + String initHowTo = getPrefValue( DP_CALL_SERVICE, DP_CS_NONE ); + if ( howTo.equals( initHowTo ) ) { + radio.setSelected( true ); + radio.setEnabled( true ); + propertyChannel.put( DP_CALL_SERVICE, howTo ); + } + endpoint.setEnabled( initHowTo.equals( DP_CS_NEWURL ) ); + className.setEnabled( initHowTo.equals( DP_CS_CLASS ) ); + return radio; + } + + // + private ActionListener howToListener = new ActionListener() { + public void actionPerformed( ActionEvent e ) { + String howTo = e.getActionCommand(); + setPrefValue( DP_CALL_SERVICE, howTo ); + propertyChannel.put( DP_CALL_SERVICE, howTo ); + endpoint.setEnabled( howTo.equals( DP_CS_NEWURL ) ); + className.setEnabled( howTo.equals( DP_CS_CLASS ) ); + } + }; + + /******************************************************************************************************************* + * Create a specialized check box for "what to do with input/output"... + ******************************************************************************************************************/ + private JCheckBox createDataBox( String title, final String preferenceKey, boolean defaultValue ) { + boolean initValue = getPrefValue( preferenceKey, defaultValue ); + propertyChannel.put( preferenceKey, new Boolean( initValue ).toString() ); + return createCheckBox( title, initValue, -1, new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPrefValue( preferenceKey, enabled ); + propertyChannel.put( preferenceKey, new Boolean( enabled ).toString() ); + inFile.setEnabled( iFromFile.isSelected() ); + } + } ); + } + + /******************************************************************************************************************* + * Create a sub-panel for service inputs... + ******************************************************************************************************************/ + protected JPanel getInputPanel() { + JPanel inputData = new JPanel( new GridBagLayout() ); + inputData + .setBorder( createFatBorder( "Service Input Data", GraphColours.getColour( "cadetblue", Color.blue ) ) ); + + // upper part (tables, input file, show-xml check-box) + JPanel upper = new JPanel( new GridBagLayout() ); + + dataTablesPanel = new JPanel( new GridBagLayout() ); + + iFromFile = createDataBox( "Take an input from this XML file", DP_SC_IN_FILE, false ); + inFile = createFileSelector( "Select input XML for calling a service", "Select", null, DP_SC_INPUT_FILE, + DP_SC_INPUT_FILE ); + inFile.setEnabled( iFromFile.isSelected() ); + + iShowXML = createDataBox( "Show input as XML", DP_INP_SHOWXML, true ); + + SwingUtils.addComponent( upper, dataTablesPanel, 0, 0, 2, 1, BOTH, NWEST, 1.0, 1.0 ); + SwingUtils.addComponent( upper, iFromFile, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( upper, inFile, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( upper, iShowXML, 0, 2, 1, 1, NONE, NWEST, 0.0, 0.0 ); + + // lower part (console showing/editing input XML) + input = new EditableConsole(); + input.setAppendMode( false ); + input.setVerboseMode( false ); + + // split upper and lower parts into moving panels + JSplitPane split = vSplit( upper, input, 0.5 ); + SwingUtils.addComponent( inputData, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + return inputData; + } + + class EditableConsole extends CommonConsole { + + public EditableConsole() { + super(); + textArea.setEditable( true ); + textArea.setBackground( GraphColours.getColour( DashboardConfig.getString( P_S_EDIT_BGCOLOR, null ), + textArea.getBackground() ) ); + } + } + + /******************************************************************************************************************* + * Replace the global 'dataTablesPanel' with an information text. + ******************************************************************************************************************/ + protected void updateInputDataPanel( String info ) { + dataTablesPanel.removeAll(); + AwtUtils.redisplay( dataTablesPanel ); + + JLabel text = new JLabel( info ); + SwingUtils.addComponent( dataTablesPanel, text, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0 ); + dataTablesPanel.validate(); + return; + } + + /******************************************************************************************************************* + * Replace the global 'dataTablesPanel' with fields defining the input data for the given service. + ******************************************************************************************************************/ + protected void updateInputDataPanel( MobyService service, MobyDataType[] dataTypes ) { + dataTablesPanel.removeAll(); + + inputDataTables = new ServiceInputPanel( service, dataTypes ); + SwingUtils.addComponent( dataTablesPanel, inputDataTables, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + dataTablesPanel.validate(); + } + + /******************************************************************************************************************* + * Find 'dataTypeToBeFound in 'dataTypes' and return it. The same could be achieved by calling + * registryModel.getDataType() but here I do not want to create yet another swing worker for it. + ******************************************************************************************************************/ + protected MobyDataType findDataType( String dataTypeToBeFound, MobyDataType[] dataTypes ) { + for ( int i = 0; i < dataTypes.length; i++ ) { + if ( dataTypeToBeFound.equals( dataTypes[ i ].getName() ) ) return dataTypes[ i ]; + } + log.error( "Strange, data type '" + dataTypeToBeFound + "' was not found in " + dataTypes.length + + " data types." ); + return null; + } + + /******************************************************************************************************************* + * + * A worker that calls the service... + * + ******************************************************************************************************************/ + class MySwingWorker extends SwingWorker { + + MobyException exception = null; + DataContainer data = new DataContainer(); + boolean wasCancelled = false; + MobyService service; + + public MySwingWorker( MobyService service ) { + super(); + this.service = service; + data.setMetadata( propertyChannel ); + } + + public void cancel() { + wasCancelled = true; + propertyChannel.fire( DP_STATUS_MSG, "Service invocation cancelled." ); + } + + public Object construct() { + try { + runButton.setEnabled( false ); + propertyChannel.fire( DP_STATUS_MSG, "Calling service " + service.getName() + "..." ); + + // create a data container with input data... + if ( propertyChannel.getBoolean( DP_SC_IN_FILE, false ) ) { + + // ...either from a file + String inputFile = propertyChannel.getString( DP_SC_INPUT_FILE ); + if ( UUtils.isEmpty( inputFile ) ) throw new MobyException( "No input XML file given." ); + data.setDataFromFile( new File( inputFile ) ); + + } + else { + data.setData( inputDataTables.toXML() ); + } + + // optionally, show XML data: we want to show this XML + // input only (a) if it was explicitly asked for (property + // DP_INP_SHOWXML is true), or (b) if "no real service + // call" was selected (property DP_CALL_SERVICE has value + // DP_CS_NONE) + if ( DP_CS_NONE.equals( propertyChannel.getString( DP_CALL_SERVICE ) ) + || ( propertyChannel.getBoolean( DP_INP_SHOWXML, false ) ) ) { + input.setText( ( String ) data.getData() ); + } + + // If we are only pinging the service, set the data object to an empty message + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + String emptyMsg = "\n" + + "\n" + " \n" + + ""; + data.setData( emptyMsg ); + input.setText( emptyMsg ); + } + + // finally, call the service + stopButton.setEnabled( true ); + callerModel.runIt( data ); + + } + catch ( MobyException e ) { + exception = e; + + } + catch ( Error e ) { + exception = new MobyException( e.toString() ); + } + return null; // not used here + } + + // runs on the event-dispatching thread + public void finished() { + if ( wasCancelled ) { + // service was interrupted by the Stop button - do + // nothing (the whole GUI should be already in a good + // state - the button 'Stop' took care about it) + return; + } + + if ( exception == null ) { + + // handle results here (using renderers...) + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + propertyChannel.fire( DP_STATUS_MSG, service.getName() + " isAlive." ); + } + else { + propertyChannel.fire( DP_STATUS_MSG, "Service invocation finished." ); + } + + if ( !DP_CS_NONE.equals( propertyChannel.getString( DP_CALL_SERVICE ) ) ) { + results.updateComponent( data ); + } + + } + else { + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + propertyChannel.fire( DP_STATUS_MSG, service.getName() + " is dead." ); + results.removeResults(); + } + else { + propertyChannel.fire( DP_STATUS_MSG, "Service invocation failed." ); + error( CALLER_ERROR, exception ); + } + exception.printStackTrace(); + } + serviceFinished(); + } + } + + /******************************************************************************************************************* + * Called when a call to a service finished. + ******************************************************************************************************************/ + protected void serviceFinished() { + runButton.setEnabled( true ); + stopButton.setEnabled( false ); + } + + /******************************************************************************************************************* + * Called when a service is selected in a service tree (or in a 'recently used services' combo box), and also at the + * beginning when a service name is retrieved from user preferences. + * + * Get selected service from a registry model and generate a new 'input data panel' to reflect input data of the + * selected service. + ******************************************************************************************************************/ + protected void selectService( final String serviceName ) { + final Object source = this; + final SwingWorker worker = new SwingWorker() { + MobyService service; + MobyDataType[] dataTypes; + + public Object construct() { + try { + service = registryModel.getService( serviceName ); + dataTypes = registryModel.getDataTypes( source ); + } + catch ( MobyException e ) { + error( ServicesTree.SERVICES_ACCESS_ERROR, e ); + } + return service; // not used here + } + + // runs on the event-dispatching thread. + public void finished() { + if ( service == null ) { + deselectService(); + } + else { + updateInputDataPanel( service, dataTypes ); + selService.setText( service.getName() ); + // selectionAllowed = false; + // recentServices.setText (service.getName()); + // selectionAllowed = true; + propertyChannel.put( DP_SC_SERVICE, service ); + runButton.setEnabled( true ); + + } + } + }; + worker.start(); + } + + /******************************************************************************************************************* + * Called when no service is selected in order to display this fact on various places in the panel. + ******************************************************************************************************************/ + protected void deselectService() { + selService.setText( "" ); + updateInputDataPanel( INIT_SELECT ); + propertyChannel.remove( DP_SC_SERVICE ); + runButton.setEnabled( false ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getName() { + return "Simple Client"; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getDescription() { + return "A panel allowing to create input data and to call an arbitrary Biomoby service. " + + "Its purpose is mostly for the service developers to test their new services."; + } + + /******************************************************************************************************************* + * + * Customized tree of services... + * + ******************************************************************************************************************/ + protected class CustomServicesTree extends ServicesTree { + + /*************************************************************************************************************** + * Construtor + **************************************************************************************************************/ + public CustomServicesTree( RegistryModel model, CommonConsole console ) { + super( model, console ); + } + + /*************************************************************************************************************** + * + **************************************************************************************************************/ + protected void createPopups( String title ) { + super.createPopups( title ); + removeFromPopups( AC_RELOAD ); + removeSeparatorAfter( AC_COLLAPSE ); + } + + /*************************************************************************************************************** + * Service selected in a service tree... + **************************************************************************************************************/ + protected void selected( DefaultMutableTreeNode node ) { + if ( node == null ) { + // nothing selected + deselectService(); + return; + } + updateInputDataPanel( "Loading..." ); + selService.setText( "" ); + final CommonNode nodeObject = ( CommonNode ) node.getUserObject(); + String currentServiceName = nodeObject.getValue(); + selectService( currentServiceName ); + setPrefValue( DP_SC_SERVICE_NAME, currentServiceName ); + } + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java 2008/05/14 20:37:10 1.6 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java 2008/11/26 08:54:21 1.7 @@ -1,168 +1,168 @@ -// ServiceCallerModel.java -// -// Created: February 2006 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.service.dashboard; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.parser.MobyPackage; -import org.biomoby.shared.parser.MobyJob; -import org.biomoby.client.ExtendedProtocolClient; -import org.biomoby.client.MobyServiceLocator; -import org.biomoby.client.ExtendedServiceLocator; -import org.biomoby.service.dashboard.data.DataContainer; - -import org.tulsoft.shared.UUtils; - -/** - * A model that achieves its task by calling (local, remote, or none) - * Biomoby service. It delegates the task of calling a service to a - * true Biomoby client (that extends BaseClient).

        - * - * @author Martin Senger - * @version $Id$ - */ - -public class ServiceCallerModel - extends AbstractModel { - -// private static org.apache.commons.logging.Log log = -// org.apache.commons.logging.LogFactory.getLog (ServiceCallerModel.class); - - /************************************************************************** - * Call a service. This is the main purpose of this model.

        - * - * @param data contains input data and this method replaces them - * by result data - *************************************************************************/ - public void runIt (DataContainer data) - throws MobyException { - SimpleClient worker = new SimpleClient (data); - worker.process(); - } - - /************************************************************************** - * - * A real client - the main worker for this model.. - * - *************************************************************************/ - protected class SimpleClient - extends ExtendedProtocolClient { - - DataContainer data; - - /************************************************************************** - * Constructor. - *************************************************************************/ - public SimpleClient (DataContainer data) { - super(); - this.data = data; - } - - /************************************************************************** - * What service to call and where to find it. - *************************************************************************/ - public MobyServiceLocator getServiceLocator() - throws MobyException { - return new MyServiceLocator(); - } - - /************************************************************************** - * Not used here... - *************************************************************************/ - public boolean fillRequest (MobyJob request, MobyPackage inputContext) - throws MobyException { - return true; - } - - /************************************************************************** - * Not used here... - *************************************************************************/ - public boolean useResponse (MobyJob response, - MobyPackage responseContext) - throws MobyException { - return true; - } - - /************************************************************************** - * Return input XML (from a data container obtained in the - * constructor). - *************************************************************************/ - public String fillRequest() - throws MobyException { - - if (data == null) - throw new MobyException ("No input data given."); - - return (String)data.getData(); - } - - /************************************************************************** - * - *************************************************************************/ - public boolean useResponse (String xmlResponse) - throws MobyException { - - data.setData (xmlResponse); - - // do nothing more if it is just an input echo - if ( ((ExtendedServiceLocator)getServiceLocator()).isLoop()) - return false; - - return false; - } - } - - /************************************************************************** - * - * A service locator filled from the property channel. - * - *************************************************************************/ - protected class MyServiceLocator - extends ExtendedServiceLocator { - - public MyServiceLocator() - throws MobyException { - super(); - - // fill this locator by a service - MobyService selService = (MobyService)propertyChannel.get (DP_SC_SERVICE); - if (selService == null) - throw new MobyException ("No service given."); - MobyService clonedService = new MobyService (selService.getName(), selService.getAuthority()); - clonedService.setURL (selService.getURL()); - setService (clonedService); - - // fill how to call this service - String howToCall = propertyChannel.getString (DP_CALL_SERVICE); - if (DP_CS_NEWURL.equals (howToCall)) { - String sEndpoint = propertyChannel.getString (DP_ENDPOINT); - if (! UUtils.isEmpty (sEndpoint)) - clonedService.setURL (sEndpoint); - - } else if (DP_CS_REGISTRY.equals (howToCall)) { - clonedService.setURL (null); - setRegistryEndpoint (propertyChannel.getString (DP_REGISTRY_ENDPOINT)); - setRegistryNamespace (propertyChannel.getString (DP_REGISTRY_NAMESPACE)); - - } else if (DP_CS_CLASS.equals (howToCall)) { - String localClass = propertyChannel.getString (DP_IMPL_CLASS); - if (UUtils.isEmpty (localClass)) - throw new MobyException ("No local class given."); - setLocalClass (localClass); - - } else if (DP_CS_NONE.equals (howToCall)) { - setLoop (true); - } - - setAsBytes (propertyChannel.getBoolean (DP_INP_ASBYTES, false)); - - } - } - -} +// ServiceCallerModel.java +// +// Created: February 2006 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.service.dashboard; + +import org.apache.axis.client.Call; +import org.biomoby.client.ExtendedProtocolClient; +import org.biomoby.client.ExtendedServiceLocator; +import org.biomoby.client.MobyServiceLocator; +import org.biomoby.service.dashboard.data.DataContainer; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.parser.MobyJob; +import org.biomoby.shared.parser.MobyPackage; +import org.tulsoft.shared.UUtils; + +/** + * A model that achieves its task by calling (local, remote, or none) Biomoby service. It delegates the task of calling + * a service to a true Biomoby client (that extends BaseClient). + *

        + * + * @author Martin Senger + * @version $Id$ + */ + +public class ServiceCallerModel extends AbstractModel { + + // private static org.apache.commons.logging.Log log = + // org.apache.commons.logging.LogFactory.getLog (ServiceCallerModel.class); + + /******************************************************************************************************************* + * Call a service. This is the main purpose of this model. + *

        + * + * @param data + * contains input data and this method replaces them by result data + ******************************************************************************************************************/ + public void runIt( DataContainer data ) throws MobyException { + SimpleClient worker = new SimpleClient( data ); + worker.process(); + } + + /******************************************************************************************************************* + * + * A real client - the main worker for this model.. + * + ******************************************************************************************************************/ + protected class SimpleClient extends ExtendedProtocolClient { + + DataContainer data; + + /*************************************************************************************************************** + * Constructor. + **************************************************************************************************************/ + public SimpleClient( DataContainer data ) { + super(); + this.data = data; + } + + /*************************************************************************************************************** + * What service to call and where to find it. + **************************************************************************************************************/ + public MobyServiceLocator getServiceLocator() throws MobyException { + return new MyServiceLocator(); + } + + /*************************************************************************************************************** + * Not used here... + **************************************************************************************************************/ + public boolean fillRequest( MobyJob request, MobyPackage inputContext ) throws MobyException { + return true; + } + + /*************************************************************************************************************** + * Not used here... + **************************************************************************************************************/ + public boolean useResponse( MobyJob response, MobyPackage responseContext ) throws MobyException { + return true; + } + + /*************************************************************************************************************** + * Return input XML (from a data container obtained in the constructor). + **************************************************************************************************************/ + public String fillRequest() throws MobyException { + + if ( data == null ) throw new MobyException( "No input data given." ); + + return ( String ) data.getData(); + } + + /** + * Sets the authentication for the service call. If the user has checked the corresponding box in the Dashboard + * the values are stored in the propertychannel. + */ + protected void setAuthentication( Call call ) { + String user = propertyChannel.getString( DashboardProperties.DP_USER_AUTHENTICATION ); + if ( !isEmpty( user ) ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, new String( ( char[] ) propertyChannel + .get( DashboardProperties.DP_PASSWORD_AUTHENTICATION ) ) ); + } + } + + /*************************************************************************************************************** + * + **************************************************************************************************************/ + public boolean useResponse( String xmlResponse ) throws MobyException { + + data.setData( xmlResponse ); + + // do nothing more if it is just an input echo + if ( ( ( ExtendedServiceLocator ) getServiceLocator() ).isLoop() ) return false; + + return false; + } + } + + /******************************************************************************************************************* + * + * A service locator filled from the property channel. + * + ******************************************************************************************************************/ + protected class MyServiceLocator extends ExtendedServiceLocator { + + public MyServiceLocator() throws MobyException { + super(); + + // fill this locator by a service + MobyService selService = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + if ( selService == null ) throw new MobyException( "No service given." ); + MobyService clonedService = new MobyService( selService.getName(), selService.getAuthority() ); + clonedService.setURL( selService.getURL() ); + setService( clonedService ); + + // fill how to call this service + String howToCall = propertyChannel.getString( DP_CALL_SERVICE ); + if ( DP_CS_NEWURL.equals( howToCall ) ) { + String sEndpoint = propertyChannel.getString( DP_ENDPOINT ); + if ( !UUtils.isEmpty( sEndpoint ) ) clonedService.setURL( sEndpoint ); + + } + else if ( DP_CS_REGISTRY.equals( howToCall ) ) { + clonedService.setURL( null ); + setRegistryEndpoint( propertyChannel.getString( DP_REGISTRY_ENDPOINT ) ); + setRegistryNamespace( propertyChannel.getString( DP_REGISTRY_NAMESPACE ) ); + + } + else if ( DP_CS_CLASS.equals( howToCall ) ) { + String localClass = propertyChannel.getString( DP_IMPL_CLASS ); + if ( UUtils.isEmpty( localClass ) ) throw new MobyException( "No local class given." ); + setLocalClass( localClass ); + + } + else if ( DP_CS_NONE.equals( howToCall ) ) { + setLoop( true ); + } + + setAsBytes( propertyChannel.getBoolean( DP_INP_ASBYTES, false ) ); + + } + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java,v retrieving revision 1.29 retrieving revision 1.30 diff -u -r1.29 -r1.30 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/18 06:40:11 1.29 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/26 08:54:21 1.30 @@ -9,10 +9,10 @@ package org.biomoby.service.dashboard; /** - * A list of names of most/all recognized properties that can be fired - * by dashboard panels, and a list of names of Java properties that - * can be used to configure the dashboard.

        - * + * A list of names of most/all recognized properties that can be fired by dashboard panels, and a list of names of Java + * properties that can be used to configure the dashboard. + *

        + * * @author Martin Senger * @version $Id$ */ @@ -44,9 +44,9 @@ static final String DP_FL_BIOCASE = "biocase"; static final String DP_FL_HIBERNATE = "hibernate"; - static final String DP_SEL_SERVICES = "selectedServices"; // type: Vector with service/authority name - static final String DP_SEL_AUTHORITIES = "selectedAuthorities"; // type: Vector with authority name - static final String DP_DEPL_SERVICES = "servicesToDeploy"; // type: Map with serviceName => className + static final String DP_SEL_SERVICES = "selectedServices"; // type: Vector with service/authority name + static final String DP_SEL_AUTHORITIES = "selectedAuthorities"; // type: Vector with authority name + static final String DP_DEPL_SERVICES = "servicesToDeploy"; // type: Map with serviceName => className static final String DP_LOCAL_DEPLOY = "use-local-deploy"; static final String DP_TOMCAT_HOME = "tomcatHome"; @@ -82,10 +82,10 @@ static final String DP_DETACH_VIEW = "detachViewers"; -// static final String DP_SC_IN_DATA = "sc-inputData"; + // static final String DP_SC_IN_DATA = "sc-inputData"; static final String DP_SC_IN_FILE = "sc-inputFromFile"; static final String DP_SC_INPUT_FILE = "sc-inputFile"; - static final String DP_SC_SERVICE = "dp-sc-service"; // type: MobyService + static final String DP_SC_SERVICE = "dp-sc-service"; // type: MobyService static final String DP_SC_SERVICE_NAME = "dp-sc-service-name"; static final String DP_SC_SERVICES = "dp-sc-recent-services"; @@ -97,21 +97,21 @@ static final String DP_DATATYPE_NAME = "dp-datatype-name"; // names of properties used in property channel storage - static final String DP_REGISTRY_MODEL = "dp-registry-model"; // type: RegistryModel - static final String DP_ANT_MODEL = "dp-ant-model"; // type: AntModel + static final String DP_REGISTRY_MODEL = "dp-registry-model"; // type: RegistryModel + static final String DP_ANT_MODEL = "dp-ant-model"; // type: AntModel static final String DP_REGISTRY_SYNONYM = "dp-registry-synonym"; - static final String DP_REG_INFO = "dp-reg-info"; // type: Boolean + static final String DP_REG_INFO = "dp-reg-info"; // type: Boolean static final String DP_REGISTRY_ENDPOINT = "dp-registry-endpoint"; static final String DP_REGISTRY_NAMESPACE = "dp-registry-namespace"; static final String DP_CACHE_DIR = "dp-cache-dir"; - static final String DP_USE_CACHE = "dp-use-cache"; // type: Boolean + static final String DP_USE_CACHE = "dp-use-cache"; // type: Boolean static final String DP_REG_DT_NAME = "dp-reg-dt-name"; static final String DP_REG_DT_AUTH = "dp-reg-dt-auth"; static final String DP_REG_DT_EMAIL = "dp-reg-dt-email"; static final String DP_REG_DT_DESC = "dp-reg-dt-desc"; - static final String DP_REG_DT_TREE = "dp-reg-dt-tree"; // type: MobyDataType + static final String DP_REG_DT_TREE = "dp-reg-dt-tree"; // type: MobyDataType static final String DP_REG_NS_NAME = "dp-reg-ns-name"; static final String DP_REG_NS_AUTH = "dp-reg-ns-auth"; @@ -132,94 +132,103 @@ static final String DP_REG_S_RDF_URL = "dp-reg-s-rdf-url"; static final String DP_REG_S_RDF_PATH = "dp-reg-s-rdf-path"; static final String DP_REG_S_XML_PATH = "dp-reg-s-xml-path"; - static final String DP_USE_SIGNATURE = "dp-use-signature"; // type: Boolean - static final String DP_USE_AUTHORITATIVE = "dp-use-auth"; // type: Boolean + static final String DP_USE_SIGNATURE = "dp-use-signature"; // type: Boolean + static final String DP_USE_AUTHORITATIVE = "dp-use-auth"; // type: Boolean static final String DP_REG_S_TYPE = "dp-reg-s-type"; static final String DP_REG_VERBOSE = "dp-reg-verbose"; - static final String DP_S_SELECTED = "dp-s-selected"; // type: MobyService + static final String DP_S_SELECTED = "dp-s-selected"; // type: MobyService - /** A property name. Its value contains a title that will appear - * in big fonts on top of the dashboard. It may be empty if - * property {@link #DP_TITLE_ICON} is defined; otherwise a default - * value will be used. + /** + * A property name. Its value contains a title that will appear in big fonts on top of the dashboard. It may be + * empty if property {@link #DP_TITLE_ICON} is defined; otherwise a default value will be used. */ static final String DP_TITLE = "dashboard.title"; - /** A property name. Its value contains a filename with an icon - * accompanying a dashboard title (defined by property {@link - * #DP_TITLE}. No default value used. Specify here either an - * absolute path (not recommended) or a relative path whose - * beginning can be found somewhere on the CLASSPATH. + /** + * A property name. Its value contains a filename with an icon accompanying a dashboard title (defined by property + * {@link #DP_TITLE}. No default value used. Specify here either an absolute path (not recommended) or a relative + * path whose beginning can be found somewhere on the CLASSPATH. */ static final String DP_TITLE_ICON = "dashboard.title.icon"; - /** A property name. Its value contains a filename with the main - * dashboard icon. Specify here either an absolute path (not - * recommended) or a relative path whose beginning can be found - * somewhere on the CLASSPATH. + /** + * A property name. Its value contains a filename with the main dashboard icon. Specify here either an absolute path + * (not recommended) or a relative path whose beginning can be found somewhere on the CLASSPATH. */ static final String DP_ICON = "dashboard.icon"; - /** A property name. Its value contains a color name used to paint - * main dashboard background. The name can be a color name, or a - * number in various format (see GraphColours for - * details). + /** + * A property name. Its value contains a color name used to paint main dashboard background. The name can be a color + * name, or a number in various format (see GraphColours for details). */ static final String DP_BGCOLOR = "dashboard.bgcolor"; - /** A property name. Its value contains a short description what a - dashboard can do generally. Often, however, it is more - convenient to put the description in a file and to use - property {@link #DP_DESCRIPTION_FILE}. + /** + * A property name. Its value contains a short description what a dashboard can do generally. Often, however, it is + * more convenient to put the description in a file and to use property {@link #DP_DESCRIPTION_FILE}. */ static final String DP_DESCRIPTION = "dashboard.description"; - /** A property name. Its value contains a file name with a short - description what a dashboard can do generally. + /** + * A property name. Its value contains a file name with a short description what a dashboard can do generally. */ static final String DP_DESCRIPTION_FILE = "dashboard.description.file"; - /** A property name. Its value contains a short description of a - project that uses this dashboard. Often, however, it is more - convenient to put the description in a file and to use - property {@link #DP_P_DESCRIPTION_FILE}. + /** + * A property name. Its value contains a short description of a project that uses this dashboard. Often, however, it + * is more convenient to put the description in a file and to use property {@link #DP_P_DESCRIPTION_FILE}. */ static final String DP_P_DESCRIPTION = "project.description"; - /** A property name. Its value contains a file name with a short - description of a project that uses this dashboard. + /** + * A property name. Its value contains a file name with a short description of a project that uses this dashboard. */ static final String DP_P_DESCRIPTION_FILE = "project.description.file"; - /** A property name. Its value contains a name of a contact - person, possibly with an email address. + /** + * A property name. Its value contains a name of a contact person, possibly with an email address. */ static final String DP_CONTACT = "dashboard.contact"; - /** A property name. Its value contains a directory name with the - * local cache of a BiMoby Central registry. + /** + * A property name. Its value contains a directory name with the local cache of a BiMoby Central registry. */ static final String DP_REGISTRY_CACHE_DIR = "registry.cache.dir"; - /** A property name. Its value contains a name or a - * comma-separated list of names of BioMoby registries that will - * be displayed in the RegistryPanel. If this property is missing, - * the list is taken from the hard-coded known registries in the - * Java source file.

        - * - * The names (values of this property) are equivalent to the - * 'synonym' attribute of the Registry class. + /** + * A property name. Its value contains a name or a comma-separated list of names of BioMoby registries that will be + * displayed in the RegistryPanel. If this property is missing, the list is taken from the hard-coded known + * registries in the Java source file. + *

        + * + * The names (values of this property) are equivalent to the 'synonym' attribute of the Registry class. */ static final String DP_WANTED_REGISTRIES = "dashboard.wanted.registries"; - /** A property name. Its value contains a name (synonym) of a - * default BioMoby registry. By default, the default registry is - * taken either from the first element in {@link - * #DP_WANTED_REGISTRIES} or from + /** + * A property name. Its value contains a name (synonym) of a default BioMoby registry. By default, the default + * registry is taken either from the first element in {@link #DP_WANTED_REGISTRIES} or from * Registries.DEFAULT_REGISTRY_SYNONYM. */ static final String DP_DEFAULT_REGISTRY = "dashboard.default.registry"; + /** + * A property name. Its value contains the user name used for the authentication required for the servlet container + * the service is hosted at. + */ + static final String DP_USER_AUTHENTICATION = "service-authentication-user"; + + /** + * A property name. Its value contains the password used for the authentication required for the servlet container + * the service is hosted at. + */ + static final String DP_PASSWORD_AUTHENTICATION = "service-authentication-passwd"; + + /** + * A property name. Its value contains whether authentication is required for the servlet container the service is + * hosted at. + */ + static final String DP_AUTHENTICATION = "service-authentication"; } From kawas at dev.open-bio.org Mon Nov 3 19:47:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 3 Nov 2008 14:47:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811031947.mA3Jlk6x016280@dev.open-bio.org> kawas Mon Nov 3 14:47:45 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv16245/src/main/org/biomoby/service/dashboard Modified Files: PerlMoSeSPanel.java Log Message: once in a while, a null pointer exception occurs because a button isnt created but a method is called on it [fixed]. moby-live/Java/src/main/org/biomoby/service/dashboard PerlMoSeSPanel.java,1.13,1.14 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java 2008/09/02 18:48:23 1.13 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/PerlMoSeSPanel.java 2008/11/03 19:47:45 1.14 @@ -892,7 +892,8 @@ boolean updateFailed = false; public Object construct() { - generateBtn.setEnabled(false); + if (generateBtn != null) + generateBtn.setEnabled(false); propertyChannel.fire(DP_STATUS_MSG, "Synchronizing Perl-MoSeS Datatype Cache..."); console.setEnabledAppendMode(false); From kawas at dev.open-bio.org Thu Nov 6 18:32:33 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:33 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWXv3025548@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY Modified Files: Makefile.PL Changes Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY Makefile.PL,1.9,1.10 Changes,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/10/30 21:25:51 1.9 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/06 18:32:33 1.10 @@ -21,7 +21,7 @@ requires 'Log::Log4perl' => 1.12; requires 'Template' => 1.11; requires 'Config::Simple' => 4.58; - requires 'IO::Stringy' => 2.110; + requires 'IO::String' => 1.08; requires 'Unicode::String' => 2.09; requires 'File::HomeDir' => 0.65; requires 'File::ShareDir' => 0.05; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/10/30 21:27:34 1.8 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/06 18:32:33 1.9 @@ -12,6 +12,14 @@ for async modules. * added another service table for async services - added a missing use statement for DateTime in Base.pm + - swapped IO::Scalar with IO::String (for performance + reasons) + - applied patch to Utils.pm (thanks to Kenny Billiau). + patch caches file paths once found instead of looking + repeatedly for them. + - MOSES::MOBY::Cache::Registries::init used to do a file + read each time a new Registries object was instantiated. + Not the case anymore. .86 Sun May 11 - fixed a bug in one of the test cases. From kawas at dev.open-bio.org Thu Nov 6 18:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYlM025602@dev.open-bio.org> kawas Thu Nov 6 13:32:34 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache Modified Files: Registries.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache Registries.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm 2008/04/29 19:29:54 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Cache/Registries.pm 2008/11/06 18:32:33 1.5 @@ -15,144 +15,174 @@ use vars qw /$VERSION/; $VERSION = sprintf "%d.%02d", q$Revision$ =~ /: (\d+)\.(\d+)/; -#----------------------------------------------------------------- -# A hard-coded list of the known registries. -# -# Please fill all details if you are adding new registry here. -# -# Do not create synonyms starting with 'http://' (they are in the -# roles of the hash keys) - this is how some methods distinguish -# between synonym and endpoint. -# -#----------------------------------------------------------------- - -my %REGISTRIES = - ( iCAPTURE => { endpoint => 'http://moby.ucalgary.ca/moby/MOBY-Central.pl', - namespace => 'http://moby.ucalgary.ca/MOBY/Central', - name => 'Sun Centre of Excellence, Calgary', - contact => 'Edward Kawas (edward.kawas at gmail.com)', - public => 'yes', - text => 'A curated public registry hosted at U of C, Calgary', - }, - IRRI => { endpoint => 'http://cropwiki.irri.org/cgi-bin/MOBY-Central.pl', - namespace => 'http://cropwiki.irri.org/MOBY/Central', - name => 'IRRI, Philippines', - contact => 'Mylah Rystie Anacleto (m.anacleto at cgiar.org)', - public => 'yes', - text => 'The MOBY registry at the International Rice Research Institute (IRRI) is intended mostly for Generation Challenge Program (GCP) developers. It allows the registration of experimental moby entities within GCP.', - }, - testing => { endpoint => 'http://bioinfo.icapture.ubc.ca/cgi-bin/mobycentral/MOBY-Central.pl', - namespace => 'http://bioinfo.icapture.ubc.ca/MOBY/Central', - name => 'Testing BioMoby registry', - contact => 'Edward Kawas (edward.kawas at gmail.com)', - public => 'yes', - }, - ); +use vars qw/ %REGISTRIES /; + +BEGIN { + our (%REGISTRIES); + my $already_init = 0; + + sub is_init { + return $already_init++; + } + + sub init_reg { + #----------------------------------------------------------------- + # A hard-coded list of the known registries. + # + # Please fill all details if you are adding new registry here. + # + # Do not create synonyms starting with 'http://' (they are in the + # roles of the hash keys) - this is how some methods distinguish + # between synonym and endpoint. + # + #----------------------------------------------------------------- + %REGISTRIES = ( + iCAPTURE => { + endpoint => 'http://moby.ucalgary.ca/moby/MOBY-Central.pl', + namespace => 'http://moby.ucalgary.ca/MOBY/Central', + name => 'Sun Centre of Excellence, Calgary', + contact => 'Edward Kawas (edward.kawas at gmail.com)', + public => 'yes', + text => 'A curated public registry hosted at U of C, Calgary', + }, + IRRI => { + endpoint => 'http://cropwiki.irri.org/cgi-bin/MOBY-Central.pl', + namespace => 'http://cropwiki.irri.org/MOBY/Central', + name => 'IRRI, Philippines', + contact => 'Mylah Rystie Anacleto (m.anacleto at cgiar.org)', + public => 'yes', + text => 'The MOBY registry at the International Rice Research Institute (IRRI) is intended mostly for Generation Challenge Program (GCP) developers. It allows the registration of experimental moby entities within GCP.', + }, + testing => { + endpoint => 'http://bioinfo.icapture.ubc.ca/cgi-bin/mobycentral/MOBY-Central.pl', + namespace => 'http://bioinfo.icapture.ubc.ca/MOBY/Central', + name => 'Testing BioMoby registry', + contact => 'Edward Kawas (edward.kawas at gmail.com)', + public => 'yes', + }, + ); + + # create a default registry + $REGISTRIES{default} = $REGISTRIES{iCAPTURE}; -$REGISTRIES{default} = $REGISTRIES{iCAPTURE}; + # read from config file user registries + # add user_registries + eval { + do { + + # is this the best way? + use lib $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR + || "/make/believe"; + use vars qw( %USER_REGISTRIES ); + require $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + if defined $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME; + foreach my $key ( sort keys %USER_REGISTRIES ) { + + # script if key exists + next if exists $REGISTRIES{$key}; + $REGISTRIES{$key} = $USER_REGISTRIES{$key}; + } + } + }; + unshift @INC, "/make/believe" if $@; + } +} #----------------------------------------------------------------- # init #----------------------------------------------------------------- sub init { - my $self = shift; - my %cloned = %REGISTRIES; - # add user_registries - eval { - do { - # is this the best way? - use lib $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || "/make/believe"; - use vars qw( %USER_REGISTRIES ); - require $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME - if defined $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME; - foreach my $key (sort keys %USER_REGISTRIES) { - # script if key exists - next if exists $cloned{$key}; - $cloned{$key} = $USER_REGISTRIES{$key} - } - } - }; - unshift @INC, "/make/believe" if $@; - $self->{registries} = \%cloned; + my $self = shift; + init_reg() unless is_init(); + my %cloned = %REGISTRIES; + $self->{registries} = \%cloned; } #----------------------------------------------------------------- # list #----------------------------------------------------------------- sub list { - my $self = shift; - return sort keys %{ $self->{registries} } if ref $self; + my $self = shift; + return sort keys %{ $self->{registries} } if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->list(); + return MOSES::MOBY::Cache::Registries->new()->list(); } #----------------------------------------------------------------- # get #----------------------------------------------------------------- sub get { - my ($self, $abbrev) = @_; - $abbrev ||= 'default'; - return $self->{registries}->{$abbrev} if ref $self; + my ( $self, $abbrev ) = @_; + $abbrev ||= 'default'; + return $self->{registries}->{$abbrev} if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->get($abbrev); + return MOSES::MOBY::Cache::Registries->new()->get($abbrev); } #----------------------------------------------------------------- # all #----------------------------------------------------------------- sub all { - my $self = shift; - return $self->{registries} if ref $self; + my $self = shift; + return $self->{registries} if ref $self; + # do this so that we can get user defined registries - return MOSES::MOBY::Cache::Registries->new()->all; + return MOSES::MOBY::Cache::Registries->new()->all; } #----------------------------------------------------------------- # add #----------------------------------------------------------------- sub add { - my ($self, %reg) = @_; + my ( $self, %reg ) = @_; # add using object methods ... - return MOSES::MOBY::Cache::Registries->new()->add(%reg) unless ref $self; - + return MOSES::MOBY::Cache::Registries->new()->add(%reg) unless ref $self; + # check for force my $force = exists $reg{force}; - + # check %reg hash for conformance and existance return -1 - unless defined $reg{namespace} and defined $reg{endpoint} - and defined $reg{synonym} and defined $reg{text} - and defined $reg{name} and defined $reg{contact} - and defined $reg{public}; - + unless defined $reg{namespace} + and defined $reg{endpoint} + and defined $reg{synonym} + and defined $reg{text} + and defined $reg{name} + and defined $reg{contact} + and defined $reg{public}; + $reg{public} = 'yes' - unless $reg{public} eq 'yes' || $reg{public} eq 'no'; - + unless $reg{public} eq 'yes' || $reg{public} eq 'no'; + return -1 - if $reg{synonym} =~ m"^http://"; - + if $reg{synonym} =~ m"^http://"; + return -2 - unless ((not defined $self->{registries}->{$reg{synonym}}) or $force); - + unless ( ( not defined $self->{registries}->{ $reg{synonym} } ) + or $force ); + # call update ... do { - eval { - $self->_update_user_registries(%reg); - }; - $LOG->warn ("Error updating user registries: $@") - if ($LOG->is_warn) and $@; - # return 0 if $@; # removed because we should be able to - + eval { $self->_update_user_registries(%reg); }; + $LOG->warn("Error updating user registries: $@") + if ( $LOG->is_warn ) + and $@; + + # return 0 if $@; # removed because we should be able to + #update $self->{registries} - $self->{registries}->{$reg{synonym}} = { - endpoint => $reg{endpoint}, - namespace => $reg{namespace}, - name => $reg{name}, - contact => $reg{contact}, - public => $reg{public}, - text => $reg{text}, + $self->{registries}->{ $reg{synonym} } = { + endpoint => $reg{endpoint}, + namespace => $reg{namespace}, + name => $reg{name}, + contact => $reg{contact}, + public => $reg{public}, + text => $reg{text}, }; + # return success return 0 if $@; return 1; @@ -163,120 +193,150 @@ # remove #----------------------------------------------------------------- sub remove { - my ($self, $name) = @_; + my ( $self, $name ) = @_; # add using object methods ... - return MOSES::MOBY::Cache::Registries->new()->remove($name) unless ref $self; - return 1 unless defined $self->{registries}->{$name}; + return MOSES::MOBY::Cache::Registries->new()->remove($name) + unless ref $self; + return 1 unless defined $self->{registries}->{$name}; + # do the remove do { eval { + # remove from file - my %args = - ( # some default values - user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), - user_reg_table => ($MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME || 'USER_REGISTRIES'), - ); - die "Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" - if $args{user_reg_dir} eq ''; - - # read the current user registry table - unshift (@INC, $args{user_reg_dir}); # place where USER_REGISTRIES could be - use vars qw ( %USER_REGISTRIES ); - eval { require $args{user_reg_table} }; - my $file_with_table; - if ($@) { - $LOG->warn ("Cannot find table of USER_REGISTRIES '" . $args{user_reg_table} . "': $@"); - $file_with_table = File::Spec->catfile ($args{user_reg_dir}, $args{user_reg_table}); - } else { + my %args = ( # some default values + user_reg_dir => + ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), + user_reg_table => ( + $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + || 'USER_REGISTRIES' + ), + ); + die +"Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" + if $args{user_reg_dir} eq ''; + + # read the current user registry table + unshift( @INC, $args{user_reg_dir} ) + ; # place where USER_REGISTRIES could be + use vars qw ( %USER_REGISTRIES ); + eval { require $args{user_reg_table} }; + my $file_with_table; + if ($@) { + $LOG->warn( "Cannot find table of USER_REGISTRIES '" + . $args{user_reg_table} + . "': $@" ); + $file_with_table = File::Spec->catfile( $args{user_reg_dir}, + $args{user_reg_table} ); + } else { $file_with_table = $INC{ $args{user_reg_table} }; - } - - # remove from user regs table - delete $USER_REGISTRIES{$name}; - # ...and write it back to a disk - require Data::Dumper; - open DISPATCH, ">$file_with_table" - or $self->throw ("Cannot open for writing '$file_with_table': $!\n"); - print DISPATCH Data::Dumper->Dump ( [\%USER_REGISTRIES], ['*USER_REGISTRIES'] ) - or $self->throw ("cannot write to '$file_with_table': $!\n"); - close DISPATCH; - $LOG->info ("\nUpdated user reg table '$file_with_table'. New contents:\n" . - $self->toString (\%USER_REGISTRIES)); + } + + # remove from user regs table + delete $USER_REGISTRIES{$name}; + + # ...and write it back to a disk + require Data::Dumper; + open DISPATCH, ">$file_with_table" + or + $self->throw("Cannot open for writing '$file_with_table': $!\n"); + print DISPATCH Data::Dumper->Dump( [ \%USER_REGISTRIES ], + ['*USER_REGISTRIES'] ) + or $self->throw("cannot write to '$file_with_table': $!\n"); + close DISPATCH; + $LOG->info( + "\nUpdated user reg table '$file_with_table'. New contents:\n" + . $self->toString( \%USER_REGISTRIES ) ); }; - $LOG->warn ("Error removing user registries: $@") - if ($LOG->is_warn) and $@; - + $LOG->warn("Error removing user registries: $@") + if ( $LOG->is_warn ) + and $@; + #update $self->{registries} delete $self->{registries}->{$name}; + # could remove from persistent store return 0 if $@; + # return success return 1; } if ref $self; } - #----------------------------------------------------------------- # _update_user_registries #----------------------------------------------------------------- sub _update_user_registries { - my ($self, @args) = @_; - my %args = - ( # some default values - user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), - user_reg_table => ($MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME || 'USER_REGISTRIES'), - - # and the real parameters - @args ); - die "Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" - if $args{user_reg_dir} eq ''; - - # check %args for the right parameters, endpoint, namespace, name, synonym, contact, text, public + my ( $self, @args ) = @_; + my %args = ( # some default values + user_reg_dir => ( $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_DIR || '' ), + user_reg_table => ( + $MOBYCFG::USER_REGISTRIES_USER_REGISTRIES_FILENAME + || 'USER_REGISTRIES' + ), + + # and the real parameters + @args + ); + die +"Couldn't find the location to 'USER_REGISTRIES' in the configuration file!" + if $args{user_reg_dir} eq ''; + +# check %args for the right parameters, endpoint, namespace, name, synonym, contact, text, public die "Arguments to update user registries are incomplete." - unless defined $args{namespace} and defined $args{endpoint} - and defined $args{synonym} and defined $args{text} - and defined $args{name} and defined $args{contact} - and defined $args{public}; - + unless defined $args{namespace} + and defined $args{endpoint} + and defined $args{synonym} + and defined $args{text} + and defined $args{name} + and defined $args{contact} + and defined $args{public}; + die "Registry synonyms should not start with http ..." - if $args{synonym} =~ m"^http://"; - - my $outdir = File::Spec->rel2abs ($args{user_reg_dir}); - $LOG->debug ("Arguments for generating user registries table: " . $self->toString (\%args)) - if ($LOG->is_debug); - - # read the current user registry table - unshift (@INC, $args{user_reg_dir}); # place where USER_REGISTRIES could be - use vars qw ( %USER_REGISTRIES ); - eval { require $args{user_reg_table} }; - my $file_with_table; - if ($@) { - $LOG->warn ("Cannot find table of USER_REGISTRIES '" . $args{user_reg_table} . "': $@"); - $file_with_table = File::Spec->catfile ($args{user_reg_dir}, $args{user_reg_table}); - } else { - $file_with_table = $INC{ $args{user_reg_table} }; - } - - # update user regs table - $USER_REGISTRIES{$args{synonym}} = { - endpoint => $args{endpoint}, - namespace => $args{namespace}, - name => $args{name}, - contact => $args{contact}, - public => $args{public}, - text => $args{text}, - }; - # ...and write it back to a disk - require Data::Dumper; - open DISPATCH, ">$file_with_table" - or $self->throw ("Cannot open for writing '$file_with_table': $!\n"); - print DISPATCH Data::Dumper->Dump ( [\%USER_REGISTRIES], ['*USER_REGISTRIES'] ) - or $self->throw ("cannot write to '$file_with_table': $!\n"); - close DISPATCH; - $LOG->info ("\nUpdated user reg table '$file_with_table'. New contents:\n" . - $self->toString (\%USER_REGISTRIES)); + if $args{synonym} =~ m"^http://"; + + my $outdir = File::Spec->rel2abs( $args{user_reg_dir} ); + $LOG->debug( "Arguments for generating user registries table: " + . $self->toString( \%args ) ) + if ( $LOG->is_debug ); + + # read the current user registry table + unshift( @INC, $args{user_reg_dir} ); # place where USER_REGISTRIES could be + use vars qw ( %USER_REGISTRIES ); + eval { require $args{user_reg_table} }; + my $file_with_table; + if ($@) { + $LOG->warn( "Cannot find table of USER_REGISTRIES '" + . $args{user_reg_table} + . "': $@" ); + $file_with_table = + File::Spec->catfile( $args{user_reg_dir}, $args{user_reg_table} ); + } else { + $file_with_table = $INC{ $args{user_reg_table} }; + } + + # update user regs table + $USER_REGISTRIES{ $args{synonym} } = { + endpoint => $args{endpoint}, + namespace => $args{namespace}, + name => $args{name}, + contact => $args{contact}, + public => $args{public}, + text => $args{text}, + }; + + # ...and write it back to a disk + require Data::Dumper; + open DISPATCH, ">$file_with_table" + or $self->throw("Cannot open for writing '$file_with_table': $!\n"); + print DISPATCH Data::Dumper->Dump( [ \%USER_REGISTRIES ], + ['*USER_REGISTRIES'] ) + or $self->throw("cannot write to '$file_with_table': $!\n"); + close DISPATCH; + $LOG->info( "\nUpdated user reg table '$file_with_table'. New contents:\n" + . $self->toString( \%USER_REGISTRIES ) ); } 1; From kawas at dev.open-bio.org Thu Nov 6 18:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYRV025584@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY Modified Files: Base.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY Base.pm,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm 2008/10/30 21:26:38 1.5 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Base.pm 2008/11/06 18:32:33 1.6 @@ -632,14 +632,14 @@ my $DUMPER; BEGIN { use Dumpvalue; - use IO::Scalar; + use IO::String; $DUMPER = Dumpvalue->new(); # $DUMPER->set (veryCompact => 1); } sub as_string { my $self = shift; my $dump_str; - my $io = IO::Scalar->new (\$dump_str); + my $io = IO::String->new (\$dump_str); my $oio = select ($io); $DUMPER->dumpValue (\$self); select ($oio); From kawas at dev.open-bio.org Thu Nov 6 18:32:34 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:32:34 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061832.mA6IWYM2025566@dev.open-bio.org> kawas Thu Nov 6 13:32:33 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators In directory dev.open-bio.org:/tmp/cvs-serv25509/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators Modified Files: Utils.pm Log Message: bug fixes: * swapped IO::Scalar with IO::String for performance reasons (still searching for better method) * applied patch to Utils.pm (thanks to Kenny Billiau) * MOSES::MOBY::Cache::Registries no longer does a file read each time a new Registries object is instantiated. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators Utils.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm 2008/04/29 19:45:10 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/Utils.pm 2008/11/06 18:32:33 1.5 @@ -61,17 +61,29 @@ =cut +my %full_path_of = (); + sub find_file { my ($self, $default_start, @names) = @_; my $fixed_part = File::Spec->catfile (@names); + return $full_path_of{ $fixed_part } if exists $full_path_of{ $fixed_part }; + my $result = File::Spec->catfile ($default_start, $fixed_part); - return $result if -e $result; + if (-e $result) { + $full_path_of{ $fixed_part } = $result; + return $result; + } foreach my $idx (0 .. $#INC) { - $result = File::Spec->catfile ($INC[$idx], $fixed_part); - return $result if -e $result; + $result = File::Spec->catfile ($INC[$idx], $fixed_part); + if (-e $result) { + $full_path_of{ $fixed_part } = $result; + return $result; + } } - return File::Spec->catfile ($default_start, $fixed_part); + $result = File::Spec->catfile ($default_start, $fixed_part); + $full_path_of{ $fixed_part } = $result; + return $result; } 1; From kawas at dev.open-bio.org Thu Nov 6 18:41:40 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 6 Nov 2008 13:41:40 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811061841.mA6IfeXw025750@dev.open-bio.org> kawas Thu Nov 6 13:41:40 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data In directory dev.open-bio.org:/tmp/cvs-serv25715/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data Modified Files: DateTime.pm Log Message: synopsis had incorrect usage information ('MobyDateTime' should have read 'DateTime') moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data DateTime.pm,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm 2008/04/29 19:35:57 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Data/DateTime.pm 2008/11/06 18:41:40 1.5 @@ -24,8 +24,8 @@ use MOSES::MOBY::Data::DateTime; # create a Moby DateTime - my $data = MOSES::MOBY::Data::MobyDateTime->new (value => '1994-11-05T08:15:30-05:00'); - my $data = MOSES::MOBY::Data::MobyDateTime->new ('1994-11-05T08:15:30-05:00'); + my $data = MOSES::MOBY::Data::DateTime->new (value => '1994-11-05T08:15:30-05:00'); + my $data = MOSES::MOBY::Data::DateTime->new ('1994-11-05T08:15:30-05:00'); =head1 DESCRIPTION From kawas at dev.open-bio.org Fri Nov 7 17:26:35 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Fri, 7 Nov 2008 12:26:35 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811071726.mA7HQZpU029854@dev.open-bio.org> kawas Fri Nov 7 12:26:34 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder In directory dev.open-bio.org:/tmp/cvs-serv29819/src/main/org/biomoby/client/rdf/builder Modified Files: ServiceInstanceRDF.java Log Message: added code to allow either a hash or forward slash in our URIs. (Preference for forward slash). For instance, if you provide http://somedomain.com/serviceinstance as a URI, it will now either make the URI http://somedomain.com/serviceinstance/ <- prefered or http://somedomain.com/serviceinstance# moby-live/Java/src/main/org/biomoby/client/rdf/builder ServiceInstanceRDF.java,1.37,1.38 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java 2008/02/20 16:58:59 1.37 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/rdf/builder/ServiceInstanceRDF.java 2008/11/07 17:26:34 1.38 @@ -1,7 +1,9 @@ package org.biomoby.client.rdf.builder; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.util.HashMap; +import java.io.InputStream; +import java.security.MessageDigest; import java.util.Map; import org.apache.commons.logging.Log; @@ -19,6 +21,7 @@ import org.biomoby.shared.MobyResourceRef; import org.biomoby.shared.MobySecondaryData; import org.biomoby.shared.MobyService; +import org.biomoby.shared.MobyUnitTest; import org.biomoby.shared.data.MobyDataSecondaryInstance; import com.hp.hpl.jena.rdf.model.Model; @@ -44,6 +47,7 @@ *

        * email me at edward.kawas at gmail.com */ + at SuppressWarnings("unchecked") public class ServiceInstanceRDF { // some URIs @@ -58,28 +62,21 @@ + " " + System.getProperty("line.separator") + ""; - private static Map URI_MAP = new HashMap(); - private static Log log = LogFactory.getLog(ServiceInstanceRDF.class); - private static final String DCP = DC_PROTEGE.getURI(); - - private Registry registry = null; - private CentralImpl central = null; // character is a has - private String trailing_character = "#"; - + private String[] trailing_characters = new String[]{"/","#"}; + + private static String PREFERED_TRAILING_CHARACTER = null; + private String OBJ; private String SRV; private String NS; - private String MP = "http://biomoby.org/RESOURCES/MOBY-S/Predicates" - + trailing_character; - private String SI; public final String getLatestLSID(String uri, String name, String lsid) { @@ -106,7 +103,9 @@ } public static void main(String[] args) throws Exception { - System.out.println(new ServiceInstanceRDF().findService("bioinfo.icapture.ubc.ca", "", false)); + System.out.println(new ServiceInstanceRDF().findService( + //"bioinfo.icapture.ubc.ca", "getGoTerm", true)); + "atidb.org", "getInsertionsWithOffsetAsGFFByAGICode", true)); } /** @@ -190,44 +189,52 @@ * if there is a problem communicating with the registry */ public ServiceInstanceRDF(Registry reg) throws MobyException { - registry = reg; central = new CentralImpl(reg.getEndpoint(), reg.getNamespace()); MobyResourceRef[] refs = central.getResourceRefs(); for (MobyResourceRef ref : refs) { if (ref.getResourceName().equals( CentralImpl.DATA_TYPES_RESOURCE_NAME)) { OBJ = ref.getResourceLocation().toString(); - if (!OBJ.endsWith(trailing_character)) - OBJ = OBJ + trailing_character; + OBJ = validateUri(OBJ); } else if (ref.getResourceName().equals( CentralImpl.SERVICE_INSTANCES_RESOURCE_NAME)) { SI = ref.getResourceLocation().toString(); - if (!SI.endsWith(trailing_character)) - SI = SI + trailing_character; + SI = validateUri(SI); } else if (ref.getResourceName().equals( CentralImpl.NAMESPACES_RESOURCE_NAME)) { NS = ref.getResourceLocation().toString(); - if (!NS.endsWith(trailing_character)) - NS = NS + trailing_character; + NS = validateUri(NS); } else if (ref.getResourceName().equals( CentralImpl.SERVICE_TYPES_RESOURCE_NAME)) { SRV = ref.getResourceLocation().toString(); - if (!SRV.endsWith(trailing_character)) - SRV = SRV + trailing_character; + SRV = validateUri(SRV); } } } - /* - * method that actually creates the rdf based on one or more services - * contained in the array services - */ - private final String createRDF(MobyService[] services) { - Model model = createRDFModel(ModelFactory.createDefaultModel(), - services, true); - return serializeModel(model); + private String validateUri(String string) { + boolean isValid = false; + for (String s : trailing_characters) { + if (string.endsWith(s)) { + isValid = true; + if (PREFERED_TRAILING_CHARACTER == null) + PREFERED_TRAILING_CHARACTER = s; + break; + } + } + // our default trailing char + String trailer = "/"; + if (PREFERED_TRAILING_CHARACTER != null) + trailer = PREFERED_TRAILING_CHARACTER; + return isValid ? string : string + trailer; } - + + /** + * + * @param model + * a jena model + * @return a string of RDF/XML-ABBREV representing the RDF model + */ public final String serializeModel(Model model) { FilteredStream stream = new FilteredStream(new ByteArrayOutputStream()); RDFWriter writer = model.getWriter("RDF/XML-ABBREV"); @@ -264,7 +271,7 @@ model = ModelFactory.createDefaultModel(); } // set up the prefixes/namespaces - Map map = model.getNsPrefixMap(); + Map map = model.getNsPrefixMap(); map.put("mobyService", SRV); map.put("mobyNamespace", NS); map.put("mobyObject", OBJ); @@ -290,17 +297,17 @@ services[i].getDescription()); subject.addProperty(FetaVocabulary.hasServiceNameText, services[i] .getName()); + if (useLSIDs) subject.addProperty(DC_PROTEGE.identifier, services[i] .getLSID()); - /* - * subject.addProperty(ServiceDescriptionPredicates.hasServiceType, - * services[i] .getType()); - */ // create the organization node - Resource publishedBy = model - .createResource(FetaVocabulary.organisation); + Resource publishedBy = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.providedBy.getURI())); + publishedBy.addProperty(RDF.type, FetaVocabulary.organisation); publishedBy.addProperty(DC_PROTEGE.creator, services[i] .getEmailContact()); publishedBy.addProperty(DC_PROTEGE.publisher, services[i] @@ -310,16 +317,22 @@ subject.addProperty(FetaVocabulary.providedBy, publishedBy); // add the inputs/outputs - Resource hasOperation = model - .createResource(FetaVocabulary.operation); + Resource hasOperation = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.hasOperation.getURI())); + hasOperation.addProperty(RDF.type, FetaVocabulary.operation); // add the hasOperation to the resource subject.addProperty(FetaVocabulary.hasOperation, hasOperation); hasOperation.addProperty(FetaVocabulary.hasOperationNameText, services[i].getName()); // add the performsTask information - Resource performs = model - .createResource(FetaVocabulary.operationTask); + Resource performs = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + "/" + + services[i].getName() + "/" + + FetaVocabulary.performsTask.getURI())); + performs.addProperty(RDF.type, FetaVocabulary.performsTask); // if service type is lsid, dont append to URI try { new LSID(services[i].getServiceType().getName()); @@ -333,66 +346,129 @@ hasOperation.addProperty(FetaVocabulary.performsTask, performs); + // add any unit test information now + if (services[i].getUnitTest() != null) { + MobyUnitTest mobyUnitTest = services[i].getUnitTest(); + Resource unitTest = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/" + + FetaVocabulary.unitTest.getURI())); + unitTest.addProperty(RDF.type, FetaVocabulary.unitTest); + // add the example input if defined + if (!mobyUnitTest.getExampleInput().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.exampleInput, mobyUnitTest.getExampleInput()); + } + // add the valid output xml if defined + if (!mobyUnitTest.getValidOutputXML().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validOutputXML, mobyUnitTest.getValidOutputXML()); + } + // add the valid regex if defined + if (!mobyUnitTest.getValidREGEX().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validREGEX, mobyUnitTest.getValidREGEX()); + } + // add the xpath expression if defined + if (!mobyUnitTest.getValidXPath().trim().equals("")) { + unitTest.addProperty(FetaVocabulary.validXPath, mobyUnitTest.getValidXPath()); + } + // add node to the graph + hasOperation.addProperty(FetaVocabulary.hasUnitTest, unitTest); + } + + + if (primaryInputs.length > 0) { for (int j = 0; j < primaryInputs.length; j++) { if (primaryInputs[j] instanceof MobyPrimaryDataSimple) { MobyPrimaryDataSimple simpleData = (MobyPrimaryDataSimple) primaryInputs[j]; - Resource parameter = model - .createResource(FetaVocabulary.parameter); + Resource parameter = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + "/" + + simpleData.getName())); + parameter.addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, simpleData .getName()); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.simpleParameter)); - // if object is lsid, dont append to URI + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + simpleData.getName())); + pType.addProperty(RDF.type, + FetaVocabulary.simpleParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); + boolean isLSID = false; try { - // an lsid - Resource bnode = model.createResource(); new LSID(simpleData.getDataType().getName()); - bnode.addProperty(RDF.type, model - .createResource(simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - } catch (MalformedLSIDException e) { - // not an lsid - Resource bnode = model.createResource(); - bnode.addProperty(RDF.type, model - .createResource(OBJ - + simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - + isLSID = true; + } catch (MalformedLSIDException e1) { + isLSID = false; } + // create the resource + Resource bnode = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + "/" + + simpleData.getName() + "/" + + simpleData.getDataType().getName())); + bnode.addProperty(RDF.type, model + .createResource(isLSID ? simpleData + .getDataType().getName() : OBJ + + simpleData.getDataType().getName())); + parameter + .addProperty(FetaVocabulary.object_type, bnode); MobyNamespace[] namespaces = simpleData.getNamespaces(); if (namespaces.length > 0) { - // Resource parameterNamespace = model - // .createResource(FetaVocabulary.parameterNamespace); - // parameter.addProperty(FetaVocabulary.inNamespaces, - // parameterNamespace); for (int k = 0; k < namespaces.length; k++) { // if namespace is lsid, dont append to URI Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSimple/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + simpleData + .getName() + + "/" + + namespaces[k] + .getName())); + parameterNamespace.addProperty(RDF.type, + FetaVocabulary.parameterNamespace); parameter.addProperty( FetaVocabulary.inNamespaces, parameterNamespace); + isLSID = false; try { new LSID(namespaces[k].getName()); - parameterNamespace.addProperty(RDF.type, - model.createResource(namespaces[k] - .getName())); + isLSID = true; } catch (MalformedLSIDException e) { - parameterNamespace.addProperty(RDF.type, - model.createResource(NS - + namespaces[k].getName())); + isLSID = false; } + parameterNamespace.addProperty(RDF.type, model + .createResource(isLSID ? namespaces[k] + .getName() : NS + + namespaces[k].getName())); } } hasOperation.addProperty(FetaVocabulary.inputParameter, @@ -408,7 +484,21 @@ for (int k = 0; k < setOfSimpleData.length; k++) { if (setOfSimpleData[k] instanceof MobyPrimaryDataSimple) { Resource parameter = model - .createResource(FetaVocabulary.parameter); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName)) + .addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, collectionName); @@ -416,11 +506,41 @@ .addProperty( FetaVocabulary.hasParameterType, model - .createResource(FetaVocabulary.collectionParameter)); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.hasParameterType + .getURI() + + "/" + + collectionName)) + .addProperty( + RDF.type, + FetaVocabulary.collectionParameter)); // if object is lsid, dont append to URI try { - - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); new LSID(setOfSimpleData[k].getDataType() .getName()); bnode.addProperty(RDF.type, model @@ -430,7 +550,23 @@ FetaVocabulary.object_type, bnode); } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + +"/" + + setOfSimpleData[k] + .getDataType() + .getName())); bnode.addProperty(RDF.type, model .createResource(OBJ + setOfSimpleData[k] @@ -443,21 +579,32 @@ MobyNamespace[] namespaces = setOfSimpleData[k] .getNamespaces(); if (namespaces.length > 0) { - /* - * Resource parameterNamespace = model - * .createResource(FetaVocabulary.parameterNamespace); - */ for (int index = 0; index < namespaces.length; index++) { // if namespace is lsid, dont // append to URI Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); - parameter.addProperty( - FetaVocabulary.inNamespaces, - parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + collectionName + + "/" + + namespaces[k] + .getName())); + parameterNamespace + .addProperty( + RDF.type, + FetaVocabulary.parameterNamespace); try { - LSID theLSID = new LSID( - namespaces[index].getName()); + new LSID(namespaces[index] + .getName()); parameterNamespace .addProperty( RDF.type, @@ -473,6 +620,9 @@ + namespaces[index] .getName())); } + parameter.addProperty( + FetaVocabulary.inNamespaces, + parameterNamespace); } /* @@ -503,13 +653,39 @@ for (int j = 0; j < secondaryInputs.length; j++) { if (secondaryInputs[j] instanceof MobySecondaryData) { MobySecondaryData data = (MobySecondaryData) secondaryInputs[j]; - Resource _li = model - .createResource(FetaVocabulary.parameter); + Resource _li = model.createResource( + SI + + MD5Checksum.md5(services[i] + .getAuthority() + + "/" + + services[i].getName() + + "/isSecondaryInputParameter/" + + FetaVocabulary.inputParameter + .getURI() + + "/" + + data.getName())).addProperty( + RDF.type, FetaVocabulary.parameter); _li .addProperty( FetaVocabulary.hasParameterType, model - .createResource(FetaVocabulary.secondaryParameter)); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSecondary/" + + FetaVocabulary.hasParameterType + .getURI() + + "/" + + data + .getName())) + .addProperty( + RDF.type, + FetaVocabulary.secondaryParameter)); if (!data.getName().equals("")) _li @@ -565,53 +741,77 @@ for (int j = 0; j < outputs.length; j++) { if (outputs[j] instanceof MobyPrimaryDataSimple) { MobyPrimaryDataSimple simpleData = (MobyPrimaryDataSimple) outputs[j]; - Resource parameter = model - .createResource(FetaVocabulary.parameter); + Resource parameter = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + "/" + + simpleData.getName())); parameter.addProperty( FetaVocabulary.hasParameterNameText, simpleData .getName()); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.simpleParameter)); - // if object is lsid, dont append to URI + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + simpleData.getName())); + pType.addProperty(RDF.type, + FetaVocabulary.simpleParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); + + boolean isLSID = false; try { - Resource bnode = model.createResource(); new LSID(simpleData.getDataType().getName()); - bnode.addProperty(RDF.type, model - .createResource(simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); - } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); - bnode.addProperty(RDF.type, model - .createResource(OBJ - + simpleData.getDataType() - .getName())); - parameter.addProperty(FetaVocabulary.object_type, - bnode); + isLSID = true; + } catch (MalformedLSIDException e1) { + isLSID = false; } + // create the resource + Resource bnode = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + "/" + + simpleData.getName() + "/" + + simpleData.getDataType().getName())); + bnode.addProperty(RDF.type, model + .createResource(isLSID ? simpleData + .getDataType().getName() : OBJ + + simpleData.getDataType().getName())); + parameter + .addProperty(FetaVocabulary.object_type, bnode); MobyNamespace[] namespaces = simpleData.getNamespaces(); if (namespaces.length > 0) { - /* - * Resource parameterNamespace = - * model.createResource(ModelFactory - * .createDefaultModel().createProperty( - * FetaVocabulary.getURI() + "parameterNamespace")); - * parameter.addProperty(FetaVocabulary.inNamespaces, - * parameterNamespace); - */ for (int k = 0; k < namespaces.length; k++) { // if namespace is lsid, dont append to URI Resource parameterNamespace = model - .createResource(ModelFactory - .createDefaultModel() - .createProperty( - FetaVocabulary.getURI() - + "parameterNamespace")); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isSimple/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + simpleData + .getName() + + "/" + + namespaces[k] + .getName())); + parameterNamespace.addProperty(RDF.type, + FetaVocabulary.parameterNamespace); parameter.addProperty( FetaVocabulary.inNamespaces, parameterNamespace); @@ -640,18 +840,55 @@ for (int k = 0; k < setOfSimpleData.length; k++) { if (setOfSimpleData[k] instanceof MobyPrimaryDataSimple) { Resource parameter = model - .createResource(FetaVocabulary.parameter); + .createResource( + SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName)) + .addProperty(RDF.type, + FetaVocabulary.parameter); parameter.addProperty( FetaVocabulary.hasParameterNameText, collectionName); - parameter - .addProperty( - FetaVocabulary.hasParameterType, - model - .createResource(FetaVocabulary.collectionParameter)); + Resource pType = model.createResource(SI + + MD5Checksum.md5(services[i].getAuthority() + + "/" + + services[i].getName() + + "/isCollection/" + + FetaVocabulary.hasParameterType + .getURI() + "/" + + collectionName)); + pType.addProperty(RDF.type, + FetaVocabulary.collectionParameter); + parameter.addProperty(FetaVocabulary.hasParameterType, + pType); // if object is lsid, dont append to URI try { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); new LSID(setOfSimpleData[k].getDataType() .getName()); bnode.addProperty(RDF.type, model @@ -660,7 +897,23 @@ parameter.addProperty( FetaVocabulary.object_type, bnode); } catch (MalformedLSIDException e) { - Resource bnode = model.createResource(); + Resource bnode = model + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + setOfSimpleData[k] + .getDataType() + .getName())); bnode.addProperty(RDF.type, model .createResource(OBJ + setOfSimpleData[k] @@ -679,10 +932,28 @@ */ for (int index = 0; index < namespaces.length; index++) { Resource parameterNamespace = model - .createResource(FetaVocabulary.parameterNamespace); + .createResource(SI + + MD5Checksum + .md5(services[i] + .getAuthority() + + "/" + + services[i] + .getName() + + "/isCollection/" + + FetaVocabulary.outputParameter + .getURI() + + "/" + + collectionName + + "/" + + namespaces[k] + .getName())); + parameterNamespace + .addProperty( + RDF.type, + FetaVocabulary.parameterNamespace); try { - LSID theLSID = new LSID( - namespaces[index].getName()); + new LSID(namespaces[index] + .getName()); parameterNamespace .addProperty( RDF.type, @@ -730,6 +1001,39 @@ return model; } + private static class MD5Checksum { + + private static byte[] createChecksum(String msg) { + try { + InputStream fis = new ByteArrayInputStream(msg.getBytes()); + byte[] buffer = new byte[1024]; + MessageDigest complete = MessageDigest.getInstance("MD5"); + int numRead; + do { + numRead = fis.read(buffer); + if (numRead > 0) { + complete.update(buffer, 0, numRead); + } + } while (numRead != -1); + fis.close(); + return complete.digest(); + } catch (Exception e) { + + } + return "".getBytes(); + } + + public static String md5(String msg) { + byte[] b = createChecksum(msg); + String result = ""; + for (int i = 0; i < b.length; i++) { + result += Integer.toString((b[i] & 0xff) + 0x100, 16) + .substring(1); + } + return result; + } + } + /** * * PRE: name is either a valid name or null @@ -737,7 +1041,7 @@ * POST: If authorURI is a valid authority, then a RDF containing all * of the service instances will be returned. If authorURI and name are * valid then a single RDF containing just the service instance identified - * by name is returned. + * by name is returned. *

        * * @param authorURI - @@ -751,13 +1055,14 @@ * if name and authorURI are valid. If name and/or authorURI are * invalid an empty rdf document is returned. */ - public final String findService(String authorURI, String name, boolean useLSIDs) { + public final String findService(String authorURI, String name, + boolean useLSIDs) { if (name == null || name.trim().equals("")) { - return (useLSIDs ? getAllServices(authorURI) - : getAllServices(authorURI, false)); + return (useLSIDs ? getAllServices(authorURI) : getAllServices( + authorURI, false)); } else { - return (useLSIDs ? getService(authorURI, name) - : getService(authorURI, name, false)); + return (useLSIDs ? getService(authorURI, name) : getService( + authorURI, name, false)); } } @@ -955,7 +1260,7 @@ * a method that retrieves all of the service instances based on an * authoriy. */ - private final String getAllServices(String URI,boolean useLSIDs) { + private final String getAllServices(String URI, boolean useLSIDs) { // variables needed MobyService service = null; MobyService[] services = null; @@ -998,7 +1303,7 @@ MobyService service = null; MobyService[] services = null; Central central = getCentralImpl(); - + // set up the query service service = new MobyService(name); service.setCategory(""); @@ -1029,7 +1334,7 @@ MobyService service = null; MobyService[] services = null; Central central = getCentralImpl(); - + // set up the query service service = new MobyService(name); service.setCategory(""); From gordonp at dev.open-bio.org Fri Nov 14 15:53:20 2008 From: gordonp at dev.open-bio.org (Paul Gordon) Date: Fri, 14 Nov 2008 10:53:20 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811141553.mAEFrKUb006218@dev.open-bio.org> gordonp Fri Nov 14 10:53:19 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data In directory dev.open-bio.org:/tmp/cvs-serv6182/src/main/org/biomoby/shared/data Modified Files: MobyDataSecondaryInstance.java Log Message: Made default value the value of a new secondary data instance moby-live/Java/src/main/org/biomoby/shared/data MobyDataSecondaryInstance.java,1.10,1.11 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java 2007/12/06 16:44:04 1.10 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/shared/data/MobyDataSecondaryInstance.java 2008/11/14 15:53:19 1.11 @@ -23,7 +23,7 @@ } /** - * Basically clones the input parameter + * Basically clones the input parameter, and sets the value to the default value. */ public MobyDataSecondaryInstance(MobySecondaryData type){ super(type.getName()); @@ -35,6 +35,7 @@ } setAllowedValues(type.getAllowedValues()); setDefaultValue(type.getDefaultValue()); + setValue(type.getDefaultValue()); setMinValue(type.getMinValue()); setMaxValue(type.getMaxValue()); setDescription(type.getDescription()); From gordonp at dev.open-bio.org Fri Nov 14 20:32:02 2008 From: gordonp at dev.open-bio.org (Paul Gordon) Date: Fri, 14 Nov 2008 15:32:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811142032.mAEKW2nP008348@dev.open-bio.org> gordonp Fri Nov 14 15:32:02 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client In directory dev.open-bio.org:/tmp/cvs-serv8312/src/main/org/biomoby/client Modified Files: MobyRequest.java Log Message: Added convenience method for secondaries, javadocs moby-live/Java/src/main/org/biomoby/client MobyRequest.java,1.39,1.40 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java,v retrieving revision 1.39 retrieving revision 1.40 diff -u -r1.39 -r1.40 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/10/30 02:33:25 1.39 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/14 20:32:02 1.40 @@ -224,6 +224,13 @@ public MobyContentInstance getInput(){ return inputData; } + + /** + * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) + */ + public void setSecondaryInput(Collection secondaryData) throws MobyException{ + setSecondaryInput(secondaryData.toArray(new MobyDataSecondaryInstance[secondaryData.size()])); + } /** * This method will assign the provided secondary parameters to all primary input data currently @@ -274,7 +281,8 @@ * are properly defined according to the Web service definition, * a SOAP request will be sent to the remote server, and the method * will return one or more MOBY objects (synchronous). - * Call this method after calling setService, and setInput. + * Call this method after calling setService, and setInput. If you do not call + * setSecondaryInput, the default secondary parameter values will be used. * * @return the results of the remote Web service in response to the give input * From kawas at dev.open-bio.org Mon Nov 17 15:24:32 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:24:32 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171524.mAHFOWPT003137@dev.open-bio.org> kawas Mon Nov 17 10:24:31 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv3106/Perl/MOBY-Server/lib/MOBY/Client Added Files: MobyUnitTest.pm Log Message: new module for unit testing moby services in perl. one subroutine is not finished (get_xml_differences). moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,NONE,1.1 From kawas at dev.open-bio.org Mon Nov 17 15:25:10 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:25:10 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171525.mAHFPABT003183@dev.open-bio.org> kawas Mon Nov 17 10:25:10 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv3144/Perl/MOBY-Server Modified Files: Makefile.PL Changes Log Message: added changes to reflect new module MobyUnitTest.pm moby-live/Perl/MOBY-Server Makefile.PL,1.9,1.10 Changes,1.14,1.15 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL 2008/09/02 13:17:25 1.9 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Makefile.PL 2008/11/17 15:25:10 1.10 @@ -27,6 +27,8 @@ requires 'LS' => '1.1.7'; requires 'DBI' => '0.01'; requires 'DBD::mysql' => '0.01'; + # used in MobyUnitTest + requires 'XML::Simple' => '2.18'; # MOBY::Async requires requires 'WSRF::Lite' => '0.8.2.3'; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.14 retrieving revision 1.15 diff -u -r1.14 -r1.15 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/10/31 15:12:45 1.14 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:25:10 1.15 @@ -18,6 +18,10 @@ - Added "no warnings 'redefine';" to MOBY::Async::WSRF to suppress redefinition warnings. - Added Unit test predicates to FETA.pm + - Created module that can be used to test Moby services. This module is + MOBY::Client::MobyUnitTest. Methods for determining whether differences + exist are complete. Currently, the method to obtain differences is + unfinished. 1.05 From kawas at dev.open-bio.org Mon Nov 17 15:27:02 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:27:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171527.mAHFR2du003295@dev.open-bio.org> kawas Mon Nov 17 10:27:02 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority In directory dev.open-bio.org:/tmp/cvs-serv3260/Perl/MOBY-Server/lib/MOBY/lsid/authority Modified Files: MobyMetadataResolver.pm Log Message: fixed the URI component in the isLatest RDF returned by the lsid resolver. moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority MobyMetadataResolver.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm 2008/09/02 13:11:53 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/lsid/authority/MobyMetadataResolver.pm 2008/11/17 15:27:02 1.4 @@ -115,13 +115,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::Namespaces->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Namespaces#$object"; my $data = < - + The Namespace described by the LSID: $lsid has since been modified. Please update your lsid. $latest @@ -333,13 +335,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::ServiceTypes->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Services#$object"; my $data = < - + The ServiceType described by the LSID: $lsid has since been modified. Please update your lsid. $latest @@ -549,13 +553,15 @@ if ( $latest eq "" ); my $object = $lsid->object(); + my $uri = MOBY::RDF::Ontologies::Objects->new(); + $uri = $uri->{uri} || "http://biomoby.org/RESOURCES/MOBY-S/Objects#$object"; my $data = < - + The Datatype described by the LSID: $lsid has since been modified. Please update your lsid. $latest From kawas at dev.open-bio.org Mon Nov 17 15:28:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:28:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171528.mAHFSk4D003335@dev.open-bio.org> kawas Mon Nov 17 10:28:46 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv3300/Perl/MOBY-Server Modified Files: Changes Log Message: updated changes to reflect the MobyMetadataResolver.pm change to uri moby-live/Perl/MOBY-Server Changes,1.15,1.16 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.15 retrieving revision 1.16 diff -u -r1.15 -r1.16 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:25:10 1.15 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:28:46 1.16 @@ -22,6 +22,9 @@ MOBY::Client::MobyUnitTest. Methods for determining whether differences exist are complete. Currently, the method to obtain differences is unfinished. + - Fixed the uri in the RDF returned in MobyMetadataResolver.pm when + the resolver is attempting to let you know what the latest lsid is + for the given entity. 1.05 From kawas at dev.open-bio.org Mon Nov 17 15:30:55 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:30:55 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171530.mAHFUtXx003527@dev.open-bio.org> kawas Mon Nov 17 10:30:55 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv3484/Perl/MOBY-Client Modified Files: Makefile.PL populate_libs.pl Changes Log Message: added changes to reflect new module MobyUnitTest.pm updated the makefile and populate_libs. moby-live/Perl/MOBY-Client Makefile.PL,1.8,1.9 populate_libs.pl,1.6,1.7 Changes,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL 2008/05/16 15:07:55 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Makefile.PL 2008/11/17 15:30:55 1.9 @@ -4,7 +4,7 @@ # all_from 'lib/MOBY/Client/Central.pm'; author 'Mark Wilkinson '; -version '1.02'; +version '1.03'; license 'perl'; abstract 'This distribution is for communicating with a MOBY Central registry'; @@ -19,76 +19,14 @@ requires 'HTTP::Request::Common' => 0; requires 'URI::Escape' => 0; requires 'RDF::Core' => '0.51'; +# MOBY::Client::MobyUnitTest depends +requires 'XML::Simple' => '2.18'; # MOBY::CommonSubs depends requires 'HTML::Entities' => 0; # MOBY::Async requires -if ( not( $^O =~ /MSWin32|Windows_NT/i ) ) { - - # check for WSRF - eval "require WSRF::Lite"; - if ($@) { - # WSRF not installed ... tell them where to get it - print STDOUT <<'END_OF_TEXT'; - -################### IMPORTANT ################### - - WSRF lite is not installed on your system. - Unfortunately, at this time, this Makefile - cannot automatically find and install it for - you. You will have to install it manually. - - The last known URL of where you could find - this package is @ - http://www.rcs.manchester.ac.uk/research/wsrflite - - If that url does not exist, please search with - google using the phrase 'WSRF-Lite'. - - Sorry for any inconvenience caused! - -################################################## - -END_OF_TEXT - - - } - requires 'WSRF::Lite' => '0.008.2.2'; - requires 'XML::DOM' => ''; - requires 'DateTime::Format::Epoch' => ''; - requires 'DateTime::Format::W3CDTF' => ''; - requires 'HTTP::Daemon' => ''; - requires 'HTTP::Daemon::SSL' => ''; - requires 'MIME::Base64' => ''; - requires 'Digest::SHA1' => ''; - requires 'Crypt::OpenSSL::RSA' => ''; - requires 'XML::CanonicalizeXML' => '0.02'; - requires 'Sys::Hostname::Long' => ''; - requires 'Crypt::OpenSSL::X509' => '0'; -} else { - print STDOUT <<'END_OF_TEXT'; - -################### IMPORTANT ################### - - Windows is not a suitable platform for those - wishing to construct asynchronous moby services - due to the lack of support for that platform of - some of the required libraries. - - The libraries in question are as follows: - WSRF-Lite & Crypt-OpenSSL-X509 - - Sorry for any inconvenience caused! - -################################################## - -END_OF_TEXT - -} - -# dont want to install the test services ... better just to document that they are here -#install_share 'share'; +requires 'WSRF::Lite' => '0.8.2.2.3'; auto_install; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/08/06 14:47:54 1.6 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/17 15:30:55 1.7 @@ -10,7 +10,7 @@ my @MOBY = qw ( Async.pm CommonSubs.pm CrossReference.pm MobyXMLConstants.pm ); my @Async = qw ( LSAE.pm Service.pm SimpleServer.pm WSRF.pm ); -my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm ); +my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm MobyUnitTest.pm ); my @Exception = qw ( MobyException.pm MobyExceptionCodes.pm ); my @RDF = qw ( Utils.pm ); my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm); @@ -100,6 +100,7 @@ # ? ? ServiceInstance.pm # ? ? SimpleArticle.pm # ? ? SimpleInput.pm +# ? ? MobyUnitTest.pm # ? ? # ? +---Exception # ? MobyException.pm =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Changes,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/05/16 15:07:55 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/17 15:30:55 1.4 @@ -1,5 +1,10 @@ Revision history for MOBY-Client +1.03 + * changes to makefile reflecting the cpan addition of wsrf + * added MOBY/Async.pm to the module + * added MOBY/Client/MobyUnitTest for unit testing our services. + 1.02 16 May 2008 * fixed bug in MOBY::Client::Central::DUMP that resulted in an error ('Not an ARRAY reference at From kawas at dev.open-bio.org Mon Nov 17 15:35:21 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 17 Nov 2008 10:35:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811171535.mAHFZLBP003654@dev.open-bio.org> kawas Mon Nov 17 10:35:21 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv3619/Perl/MOBY-Client Modified Files: README Log Message: update the README to remove the section on wsrf (since it is cpan now) moby-live/Perl/MOBY-Client README,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/README,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Client/README 2008/02/21 00:14:33 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/README 2008/11/17 15:35:21 1.2 @@ -26,25 +26,6 @@ each dependency independently and install them as per their installation instructions. -WRSF::Lite - -If module 'WSRF::Lite' is not installed and you are -thinking about developing BioMOBY Asynchronous service, -then following is for you! - -Unfortunately, this module is not available on CPAN -and must be manually installed. Some of the -dependencies are beta and as such, may not be stable. - -Try downloading it from the following link: - -http://www.rcs.manchester.ac.uk/research/projects/wsrflite - -or you can try searching the net with Google using the keywords: - - 'perl WSRF::Lite' - - COPYRIGHT AND LICENCE Copyright (C) 2003 BioMoby Developers Group (www.biomoby.org) From senger at dev.open-bio.org Tue Nov 18 06:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eBCN006092@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv6073/docs Modified Files: ChangeLog Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/docs ChangeLog,1.93,1.94 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/ChangeLog,v retrieving revision 1.93 retrieving revision 1.94 diff -u -r1.93 -r1.94 --- /home/repository/moby/moby-live/Java/docs/ChangeLog 2008/10/25 14:28:18 1.93 +++ /home/repository/moby/moby-live/Java/docs/ChangeLog 2008/11/18 06:40:11 1.94 @@ -1,3 +1,8 @@ +2008-11-18 Martin Senger + + * Added new properties to dashboard.properties allowing to limit + the list of known registries + 2008-10-25 Martin Senger * Fixed: Ant's task creating jMoby jar file now does not include From senger at dev.open-bio.org Tue Nov 18 06:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eB3f006112@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/src/config/dashboard In directory dev.open-bio.org:/tmp/cvs-serv6073/src/config/dashboard Modified Files: dashboard.properties Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/src/config/dashboard dashboard.properties,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties 2006/02/19 18:42:55 1.5 +++ /home/repository/moby/moby-live/Java/src/config/dashboard/dashboard.properties 2008/11/18 06:40:11 1.6 @@ -66,3 +66,17 @@ # panel) simpleclient.service.edit.bgcolor = beige + +# ----------------------------------------- +# --- Registry browser panel properties --- +# ----------------------------------------- + +# -- a name or a comma-separated list of names of BioMoby registry +# -- synonyms that will be displayed in the RegistryPanel. If this +# -- property is missing, the list is taken from the hard-coded known +# -- registries in the Java source file + +#dashboard.wanted.registries = default,Calgary,IRRI,INAB,testing + +# -- a name (synonym) of a default BioMoby registry +dashboard.default.registry = default From senger at dev.open-bio.org Tue Nov 18 06:40:12 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:12 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eCV6006164@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv6073/xmls Modified Files: project-dashboard.pom Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/xmls project-dashboard.pom,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom 2008/08/08 11:12:58 1.1 +++ /home/repository/moby/moby-live/Java/xmls/project-dashboard.pom 2008/11/18 06:40:11 1.2 @@ -2,7 +2,7 @@ 4.0.0 org.biomoby jmoby-dashboard - 1.1.0 + 1.1.1 jMoby Dashboard From senger at dev.open-bio.org Tue Nov 18 06:40:11 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Tue, 18 Nov 2008 01:40:11 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811180640.mAI6eBtW006140@dev.open-bio.org> senger Tue Nov 18 01:40:11 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv6073/src/main/org/biomoby/service/dashboard Modified Files: DashboardConfig.java DashboardProperties.java RegistryPanel.java Log Message: allowing to limit the list of known registries in Dashboard moby-live/Java/src/main/org/biomoby/service/dashboard DashboardConfig.java,1.1,1.2 DashboardProperties.java,1.28,1.29 RegistryPanel.java,1.30,1.31 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java 2008/03/02 12:45:26 1.1 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardConfig.java 2008/11/18 06:40:11 1.2 @@ -244,6 +244,34 @@ } /************************************************************************** + * Almost the same functionality as {@link #getString getString} + * method. The different is the return value: this method allows + * to return several values of the same property. In the + * configuration file, a property can be repeated, or can have + * several comma-separated values.

        + * + * By the way, the importance of a comma in a property value also + * means that any 'normal' (the one not meant as a value + * separator) commas in property values, must be escaped by + * backslashes.

        + * + * @return all values of the given property, or - if such property + * does not exist - return a one-element array with the + * 'defaultValue' unless the 'defaultValue' is also null in which + * case return an empty array + **************************************************************************/ + public static String[] getStrings (String key, + String defaultValue) { + String[] values = get().getStringArray (key); + if (values.length > 0) return values; + + if (defaultValue == null) + return ArrayUtils.EMPTY_STRING_ARRAY; + else + return new String[] { defaultValue }; + } + + /************************************************************************** * Get an integer value associated with the given configuration * key, or - if not found or not of integer value - get the given * default value.

        =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java,v retrieving revision 1.28 retrieving revision 1.29 diff -u -r1.28 -r1.29 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/05/14 20:37:10 1.28 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/18 06:40:11 1.29 @@ -203,4 +203,23 @@ */ static final String DP_REGISTRY_CACHE_DIR = "registry.cache.dir"; + /** A property name. Its value contains a name or a + * comma-separated list of names of BioMoby registries that will + * be displayed in the RegistryPanel. If this property is missing, + * the list is taken from the hard-coded known registries in the + * Java source file.

        + * + * The names (values of this property) are equivalent to the + * 'synonym' attribute of the Registry class. + */ + static final String DP_WANTED_REGISTRIES = "dashboard.wanted.registries"; + + /** A property name. Its value contains a name (synonym) of a + * default BioMoby registry. By default, the default registry is + * taken either from the first element in {@link + * #DP_WANTED_REGISTRIES} or from + * Registries.DEFAULT_REGISTRY_SYNONYM. + */ + static final String DP_DEFAULT_REGISTRY = "dashboard.default.registry"; + } =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java,v retrieving revision 1.30 retrieving revision 1.31 diff -u -r1.30 -r1.31 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java 2008/03/02 16:19:15 1.30 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/RegistryPanel.java 2008/11/18 06:40:11 1.31 @@ -38,6 +38,8 @@ import java.awt.event.ItemListener; import java.io.File; +import java.util.List; +import java.util.ArrayList; /** * A panel displaying contents of a Biomoby registry. It also select @@ -421,10 +423,10 @@ showReg.setToolTipText ("Each time you select a registry, an info appears in console window"); final Registries regs = RegistriesList.getInstance(); - JComboBox regList = new JComboBox (regs.list()); + JComboBox regList = new JComboBox (getOnlyWantedRegistries (regs.list())); regList.setToolTipText ("A selection will fill text fields below"); - regList.setSelectedItem (getPrefValue (DP_REGISTRY_SYNONYM, - Registries.DEFAULT_REGISTRY_SYNONYM)); + final String defaultRegistry = getDefaultRegistrySynonym(); + regList.setSelectedItem (getPrefValue (DP_REGISTRY_SYNONYM, defaultRegistry)); regList.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) { String contents = (String)((JComboBox)e.getSource()).getSelectedItem(); @@ -434,9 +436,9 @@ theReg = regs.get (contents); } catch (MobyException ee) { try { - theReg = regs.get (null); + theReg = regs.get (defaultRegistry); } catch (MobyException ee2) { - log.error ("List of registries does not contain a default registry."); + log.error ("List of registries does not contain the default registry."); } } if (theReg != null) { @@ -458,6 +460,69 @@ } /************************************************************************** + * Filter the given list of known registry by an optional + * properties. Return the filtered result, or the same list if + * there is no relevant property. Check if the wanted registries + * are also registered ones and ignore (with warning) those that + * are not. + **************************************************************************/ + protected static String[] getOnlyWantedRegistries (String[] regs) { + String[] wantedRegs = DashboardConfig.getStrings (DP_WANTED_REGISTRIES, null); + + if (wantedRegs.length == 0) + return regs; + + // check if all of the wanted registries are also known ones + List registeredAndWanted = new ArrayList(); + for (String wantedReg: wantedRegs) { + boolean found = false; + for (String knownReg: regs) { + if (wantedReg.equals (knownReg)) { + found = true; + break; + } + } + if (found) { + registeredAndWanted.add (wantedReg); + } else { + log.warn ("An unknown registry synonym found in the property " + + DP_WANTED_REGISTRIES + ": " + wantedReg); + } + } + if (registeredAndWanted.size() > 0) { + return registeredAndWanted.toArray (new String[] {}); + } else { + return regs; + } + } + + /************************************************************************** + * Return a synonym of the default registry. It is retrieved (in + * this order): + * + * - from the property DP_DEFAULT_REGISTRY; + * - from Registries.DEFAULT_REGISTRY_SYNONYM. + * + * Log warning if the returned default registry is not in the list + * of wanted registries. + **************************************************************************/ + protected static String getDefaultRegistrySynonym() { + + String defaultReg = DashboardConfig.getString (DP_DEFAULT_REGISTRY, null); + if (defaultReg == null) + defaultReg = Registries.DEFAULT_REGISTRY_SYNONYM; + + String[] wantedRegs = + getOnlyWantedRegistries (RegistriesList.getInstance().list()); + for (String wantedReg: wantedRegs) { + if (defaultReg.equals (wantedReg)) + return defaultReg; + } + log.warn ("Default registry '" + defaultReg + "' is not found in wanted registries."); + return defaultReg; + } + + /************************************************************************** * Panel for registry. **************************************************************************/ protected JPanel getRegistryLocation() { From kawas at dev.open-bio.org Wed Nov 19 14:24:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 09:24:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191424.mAJEOEsB009759@dev.open-bio.org> kawas Wed Nov 19 09:24:14 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates In directory dev.open-bio.org:/tmp/cvs-serv9702/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates Modified Files: service.tt Log Message: bug fix: when using service that consumes/outputs a primitive, certain 'use' statements are missing and service dies. moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates service.tt,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt 2008/03/31 18:05:17 1.4 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/lib/MOSES/MOBY/Generators/templates/service.tt 2008/11/19 14:24:14 1.5 @@ -50,7 +50,68 @@ ), [%- END %] [%- END -%] + + [%- MACRO get_use_statements (inputs, outputs) BLOCK %] + [%- SET use_statements = [] -%] + [%- FOREACH input IN inputs -%] + [%- IF NOT is_simple (input) -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == input.elements.0.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (input.elements.0.datatype.name) -%] + [%- get_use_statement(input.elements.0.datatype.name) -%] + [%- END -%] + [%- ELSE -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == input.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (input.datatype.name) -%] + [%- get_use_statement(input.datatype.name) -%] + [%- END -%] + [%- END -%] + [%- END -%] + [%- FOREACH output IN outputs -%] + [%- IF NOT is_simple (output) -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == output.elements.0.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (output.elements.0.datatype.name) -%] + [%- get_use_statement(output.elements.0.datatype.name) -%] + [%- END -%] + [%- ELSE -%] + [%- found = 0 -%] + [%- FOREACH e IN use_statements -%] + [%- SET found = 1 IF e == output.datatype.name -%] + [%- END -%] + [%- IF NOT found %] + [%- use_statements.push (output.datatype.name) -%] + [%- get_use_statement(output.datatype.name) -%] + [%- END -%] + [%- END -%] + [%- END -%] + [%- END -%] + + [%- MACRO get_use_statement(datatype) BLOCK %] + [%- IF datatype == 'String' %]use MOSES::MOBY::Data::String; + + [%- ELSIF datatype == 'Integer' %]use MOSES::MOBY::Data::Integer; + + [%- ELSIF datatype == 'Float' %]use MOSES::MOBY::Data::Float; + [%- ELSIF datatype == 'Boolean' %]use MOSES::MOBY::Data::Boolean; + + [%- ELSIF datatype == 'DateTime' %]use MOSES::MOBY::Data::DateTime; + + [%- END -%] + [%- END -%] + + [%- MACRO no_children (datatype, value) BLOCK %] [%- IF datatype == 'String' %]value => "this is a value [% value %]", # TO BE EDITED [%- ELSIF datatype == 'Integer' %]value => 42, # TO BE EDITED @@ -143,6 +204,9 @@ use MOSES::MOBY::ServiceException; use strict; +[%# here we output use statements for our primitives %] +[%- get_use_statements(base.inputs, base.outputs) -%] + my %valid_namespaces = ( [% FOREACH ns IN input_ns %] '[%ns%]'=>1, [% END %]); #----------------------------------------------------------------- # process_it From kawas at dev.open-bio.org Wed Nov 19 14:24:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 09:24:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191424.mAJEOEiD009741@dev.open-bio.org> kawas Wed Nov 19 09:24:13 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOSES-MOBY In directory dev.open-bio.org:/tmp/cvs-serv9702/Perl/MOSES-MOBY Modified Files: Makefile.PL Changes Log Message: bug fix: when using service that consumes/outputs a primitive, certain 'use' statements are missing and service dies. moby-live/Perl/MOSES-MOBY Makefile.PL,1.10,1.11 Changes,1.9,1.10 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/06 18:32:33 1.10 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Makefile.PL 2008/11/19 14:24:13 1.11 @@ -6,7 +6,7 @@ # Define metadata name 'MOSES-MOBY'; - version '0.86'; + version '0.87'; license 'perl'; abstract 'This distribution aids in the creation of BioMOBY perl based web services.'; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/06 18:32:33 1.9 +++ /home/repository/moby/moby-live/Perl/MOSES-MOBY/Changes 2008/11/19 14:24:13 1.10 @@ -20,6 +20,9 @@ - MOSES::MOBY::Cache::Registries::init used to do a file read each time a new Registries object was instantiated. Not the case anymore. + - fixed bug: + Services that consume/output primitives didn't have the + proper 'use' statements. .86 Sun May 11 - fixed a bug in one of the test cases. From groscurt at dev.open-bio.org Wed Nov 19 15:28:03 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:28:03 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191528.mAJFS3Sw010138@dev.open-bio.org> groscurt Wed Nov 19 10:28:03 EST 2008 Update of /home/repository/moby/moby-live/Java/src/config/dashboard In directory dev.open-bio.org:/tmp/cvs-serv10107/Java/src/config/dashboard Added Files: dashboard.jnlp.template Log Message: A template file for the JNLP file used in the Dashboard Webstart application moby-live/Java/src/config/dashboard dashboard.jnlp.template,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 19 15:28:43 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:28:43 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191528.mAJFShLf010198@dev.open-bio.org> groscurt Wed Nov 19 10:28:43 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10167/Java/docs Added Files: DashboardWebstart.html Log Message: HTML documentation of the DashboardWebstart process moby-live/Java/docs DashboardWebstart.html,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 19 15:29:04 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:29:04 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191529.mAJFT4cC010241@dev.open-bio.org> groscurt Wed Nov 19 10:29:04 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10206/Java/docs Modified Files: index.html Log Message: added the link to the DashboardWebstart.html moby-live/Java/docs index.html,1.35,1.36 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.35 retrieving revision 1.36 diff -u -r1.35 -r1.36 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/10/30 02:02:59 1.35 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/19 15:29:04 1.36 @@ -102,6 +102,7 @@

      • How to change Ant's build.xml
      • RDF Agent +
      • The Dashboard as Webstart
    From groscurt at dev.open-bio.org Wed Nov 19 15:29:32 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:29:32 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191529.mAJFTWeI010284@dev.open-bio.org> groscurt Wed Nov 19 10:29:32 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv10249/Java/xmls Modified Files: dashboardBuild.xml Log Message: added the tasks for the Dashboard Webstart application moby-live/Java/xmls dashboardBuild.xml,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml 2008/03/02 12:45:27 1.5 +++ /home/repository/moby/moby-live/Java/xmls/dashboardBuild.xml 2008/11/19 15:29:32 1.6 @@ -71,4 +71,262 @@ + + + + + + The following information is required to create keystore with which the jars for the webstart application will be signed. + + + + + + + + + + + + + + + + + + + + + + + + + + The keystore was successfully created and can be found under + ${dashboard.keystore.location}. + + + + + + + + + + + Enter the absolute path of the keystore (it has to be a valid and accessible path ! e.g. /usr/local/user/mykeystore). + If you want to use an existing one, type the location of the keystore, otherwise a new one will be created. + If you want recreate the keystore you have to do delete the existing one before ! + + + + + + You must provide a path for the keystore ! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This task will build the BioMoby dashboard as a JavaWebStart application. + + For that it has to sign the jars which dashboard requires. For this, several information is needed to establish a 'keystore'. + In any case you already have a valid keystore, you are free to use this. + Otherwise the task will create a new one. + + Please fill out all information which is needed to build a working WebStart application. + Please FIRST read carefully the instructions and information in the /docs/DashboardWebstart.html !. + + Thank you :) (Press RETURN to continue) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Please type in the base URL where the dashboard web start will be accessible. + This must be a publicly available URL (like http://mydomain.com/dashboard) + + + + + You have to provide a URL to procceed ! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${path.convert.lib} + + + + ]]> + + + + + + + + + + + ]]> + + + + + + + + Please enter a at least 6 character password for the keystore (mandatory !) + (if you already created the keystore then please retype your password ! + if you cant remember your password, delete keystore file and re-run the task again !) + + + + + + You must provide a password for the signature of the key for the + dashboard webstart ! + + + + Enter the key password (RETURN if same as keystore password) + (if you already created the keystore then please retype the password or return if its the same as the keystore password) + + + + + . + From groscurt at dev.open-bio.org Wed Nov 19 15:43:18 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 10:43:18 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191543.mAJFhIC8010411@dev.open-bio.org> groscurt Wed Nov 19 10:43:18 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10376/Java/docs Modified Files: DashboardWebstart.html Log Message: some typos... moby-live/Java/docs DashboardWebstart.html,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html 2008/11/19 15:28:43 1.1 +++ /home/repository/moby/moby-live/Java/docs/DashboardWebstart.html 2008/11/19 15:43:18 1.2 @@ -6,7 +6,7 @@ the existing Ant-based project. " /> @@ -35,12 +35,12 @@
  • As Java Webstart is provided over the internet you need to deploy it on an web server (such as the Apache httpd server).
    So please ensure that you or someone you trust has access to the document root directory of you web server.
    -Furthermore please ensure that the following line is in the mime.types file found at /your/web/server/conf/mime.types: +Furthermore please ensure that the following line is in the mime.types file found at /your/web/server/conf:
     application/x-java-jnlp-file    jnlp
     
    -This let the web server know to handle the jnlp file correctly. If this entry has not been in your mime.types please restart your webserver. +This lets the web server know how to handle the jnlp file correctly. If this entry has not been in your mime.types please restart your webserver.
  • @@ -83,7 +83,7 @@ ant install - +
    Creating the Dashboard Webstart application is as easy as getting wet on a rainy day.
    Just run

    @@ -105,7 +105,7 @@

    Creating a keystore

    If you entered a keystore which does not exists, the process will ask you several information about who you are and where you from. -
    Keep in mind that this information is really important as people who start you Dashboard JavaWebstart have to accept that the application gets access to their harddrives. +
    Keep in mind that this information is really important as people who start your Dashboard JavaWebstart have to accept that the application gets access to their harddrives. The values you enter here are shown to the user and they are asked if they trust the person offering the Webstart application. So please enter the correct information about you.
    At the end you have to give a password which is at least 6 characters long for the keystore. This password will be always required in case you add another key to the keystore, so dont forget this one.
    After that you are free to enter the password for the key you are about to create. If you want to use the same password as for the keystore itself, just hit RETURN. Otherwise enter your password. From groscurt at dev.open-bio.org Wed Nov 19 16:34:15 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 19 Nov 2008 11:34:15 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811191634.mAJGYFbu010480@dev.open-bio.org> groscurt Wed Nov 19 11:34:15 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv10445/Java/docs Modified Files: Dashboard.html Log Message: added information about the changes in the dashboard.properties file and how to add new repositories moby-live/Java/docs Dashboard.html,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/Dashboard.html,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Java/docs/Dashboard.html 2008/02/14 06:13:34 1.8 +++ /home/repository/moby/moby-live/Java/docs/Dashboard.html 2008/11/19 16:34:15 1.9 @@ -29,6 +29,7 @@
  • How to start Dashboard
  • How to use Dashboard
  • Dashboard Panels Gallery +
  • Customize the available repositories / Adding a new Repository
  • Plans and issues
  • Dashboard for developers
      @@ -225,6 +226,33 @@

      + +

      Customize the available repositories / Adding a new Repository

      +This explains how you can manipulate the available repositories in your Dashboard. +

      Customize the available repositories

      +To manipulate which repositories shall be available in your Dashboard application you can edit the moby-live/Java/src/config/dashboard/dashboard.properties file.
      +Search for the dashboard.wanted.registries, which is per default not active. If you activate it by removing the # before the line you can remove the repositories by deleting the corresponding entry.
      +For example this is the original one: +
      +
      +#dashboard.wanted.registries = default,Calgary,INB,IRRI,testing
      +
      +
      +if you now want only to have the official BioMoby central and its test repository: +
      +
      +dashboard.wanted.registries = default,Calgary,testing
      +
      +
      +after that just start dashboard again with ant dashboard + +

      Adding a new Repository

      +

      IMPORTANT: We do not encourage people to set up their own repository as every can use the official BioMoby central repository. But if in any case you have to set up an own repository this explains how to make it visible in Dashboard.

      +The easiest way is to type the URL and the URI in the Endpoint and Namespace (URI) input fields in Dashboard, respectively. Dashboard does remember your inputs and you can select your entries later again. +

      If you want to have it as an entry in the dropdown box you have to edit the moby-live/Java/src/org/biomoby/registry/meta/RegistriesList.java file and add there your repository based on the template of the others. This should be only done if you know what you are doing !
      +After that you should add the name of your repository also to the dashboard.wanted.registries property inside the moby-live/Java/src/config/dashboard/dashboard.properties.

      +If you then restart dashboard you will see now your repository coming up. +

      Plans and issues

      From kawas at dev.open-bio.org Wed Nov 19 21:29:14 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 16:29:14 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811192129.mAJLTEv2011305@dev.open-bio.org> kawas Wed Nov 19 16:29:14 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv11270/Perl/MOBY-Server/lib/MOBY/Client Modified Files: CollectionArticle.pm Log Message: fixed documentation type moby-live/Perl/MOBY-Server/lib/MOBY/Client CollectionArticle.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm 2008/09/02 13:11:40 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/CollectionArticle.pm 2008/11/19 21:29:14 1.4 @@ -130,7 +130,7 @@ =head2 addSimple - Usage : $namespaces = $IN->addNamespace($SimpleArticle) + Usage : $simples = $IN->addSimple($SimpleArticle) Function : add another SimpleArticle Returns : arrayref of MOBY::Client::SimpleArticle's or 0 if argument was not a MOBY::Client::SimpleArticle (or other failure) From kawas at dev.open-bio.org Wed Nov 19 21:31:21 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Wed, 19 Nov 2008 16:31:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811192131.mAJLVLdL011381@dev.open-bio.org> kawas Wed Nov 19 16:31:21 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv11346/Perl/MOBY-Server/lib/MOBY/Client Modified Files: MobyUnitTest.pm Log Message: fixed whitespace that killed the perldoc for the module. moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/17 15:24:31 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/19 21:31:21 1.2 @@ -264,7 +264,6 @@ $text =~ s/^\s+//; $text =~ s/\s+$//; return $text; - } #----------------------------------------------------------------- @@ -346,7 +345,7 @@ parameters (all optional) include: =over - + =item C - example input to pass to our service when testing it =item C - service output xml that is expected given the example input From kawas at dev.open-bio.org Thu Nov 20 17:01:06 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 12:01:06 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201701.mAKH16E3013056@dev.open-bio.org> kawas Thu Nov 20 12:01:06 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv13021/Perl/MOBY-Server/lib/MOBY/Client Modified Files: ServiceInstance.pm Log Message: added method to get/set unit test info moby-live/Perl/MOBY-Server/lib/MOBY/Client ServiceInstance.pm,1.2,1.3 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm 2008/09/02 13:11:40 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/ServiceInstance.pm 2008/11/20 17:01:05 1.3 @@ -2,6 +2,7 @@ use strict; use Carp; use vars qw($AUTOLOAD @ISA); +use MOBY::Client::MobyUnitTest; use vars qw /$VERSION/; $VERSION = sprintf "%d.%02d", q$Revision$ =~ /: (\d+)\.(\d+)/; @@ -216,6 +217,15 @@ =cut +=head2 unitTest + + Title : unitTest + Usage : $test = $Service->unitTest() + Function : get/set the MobyUnitTest for this service + Returns : a MOBY::Client::MobyUnitTest object for this service + +=cut + { # Encapsulated: @@ -224,23 +234,22 @@ #ATTRIBUTES my %_attr_data = # DEFAULT ACCESSIBILITY ( - authority => [ undef, 'read/write' ], - signatureURL => [ undef, 'read/write' ], - name => [ undef, 'read/write' ], - type => [ undef, 'read/write' ], - input => [ undef, 'read/write' ] - , # listref of Simple and Collection articles - output => [ undef, 'read/write' ] - , # listref of Simple and Collection articles - secondary => [ undef, 'read/write' ], # listref of SecondaryArticles - category => [ undef, 'read/write' ], - description => [ undef, 'read/write' ], + authority => [ undef, 'read/write' ], + signatureURL => [ undef, 'read/write' ], + name => [ undef, 'read/write' ], + type => [ undef, 'read/write' ], + input => [ undef, 'read/write' ], # listref of Simple and Collection articles + output => [ undef, 'read/write' ], # listref of Simple and Collection articles + secondary => [ undef, 'read/write' ], # listref of SecondaryArticles + category => [ undef, 'read/write' ], + description => [ undef, 'read/write' ], registry => [ 'MOBY_Central', 'read/write' ], XML => [ undef, 'read/write' ], authoritative => [ undef, 'read/write' ], URL => [ undef, 'read/write' ], contactEmail => [ undef, 'read/write' ], - LSID => [ undef, 'read/write'] + LSID => [ undef, 'read/write'], + unitTest => [ undef, 'read/write'], # a reference to a MobyUnitTest object ); #_____________________________________________________________ @@ -282,6 +291,7 @@ $self->input( [] ) unless $self->input; $self->output( [] ) unless $self->output; $self->secondary( [] ) unless $self->secondary; + $self->unitTest( new MOBY::Client::MobyUnitTest ) unless $self->unitTest; return $self; } From kawas at dev.open-bio.org Thu Nov 20 17:02:24 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 12:02:24 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201702.mAKH2OAJ013110@dev.open-bio.org> kawas Thu Nov 20 12:02:24 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv13079/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Added Files: ServiceParser.pm Log Message: preliminary service instance RDF parser. missing unit testing information. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers ServiceParser.pm,NONE,1.1 From kawas at dev.open-bio.org Thu Nov 20 19:35:46 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:35:46 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201935.mAKJZkL5013304@dev.open-bio.org> kawas Thu Nov 20 14:35:46 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv13269/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Modified Files: ServiceParser.pm Log Message: *added the unit test parsing to this module *added a warning telling users not to try and parse the whole service instance ontology moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers ServiceParser.pm,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 17:02:24 1.1 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 19:35:46 1.2 @@ -61,6 +61,13 @@ =cut +=head1 WARNING + +Do not attempt to parse service instance RDF containing more than a few hundred services because the RDF is +parsed and held in memory. + +=cut + =head1 AUTHORS Edward Kawas (edward.kawas [at] gmail [dot] com) @@ -228,43 +235,45 @@ $providedBy = [] unless @$providedBy; $providedBy = $$providedBy[0] if ref($providedBy) eq 'ARRAY' and $$providedBy[0]; + if ($providedBy) { - # set the authoritative - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the authoritative + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::FETA ->authoritative - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->authoritative( + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->authoritative( MOBY::RDF::Utils::trim($val) =~ m/true/i ? 1 : 0 ); - # set the contact email - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the contact email + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE ->creator - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->contactEmail( MOBY::RDF::Utils::trim($val) ); + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->contactEmail( MOBY::RDF::Utils::trim($val) ); - # set the authority uri - $val = $model->getObjects( - $providedBy, - new RDF::Core::Resource( + # set the authority uri + $val = $model->getObjects( + $providedBy, + new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE ->publisher - ) - ); - $val = "" unless $$val[0]; - $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; - $instance->authority( MOBY::RDF::Utils::trim($val) ); + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $instance->authority( MOBY::RDF::Utils::trim($val) ); + } # no longer need the providedBy node $providedBy = undef; @@ -281,6 +290,9 @@ $hasOperation = $$hasOperation[0] if ref($hasOperation) eq 'ARRAY' and $$hasOperation[0]; + # if this is missing ... what's the point? + next unless $hasOperation; + # process any inputs my $inputs = $model->getObjects( $hasOperation, @@ -454,6 +466,7 @@ } elsif ( $val eq MOBY::RDF::Predicates::FETA->secondaryParameter ) { my $param = MOBY::Client::SecondaryArticle->new; + # get the articlename $val = $model->getObjects( @@ -761,7 +774,72 @@ $performs = undef; # process any unit test information - #TODO + my $unit_test = + $model->getObjects( + $hasOperation, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->hasUnitTest + ) + ); + $unit_test = [] unless @$unit_test; + foreach my $ut (@$unit_test) { + my $unit = new MOBY::Client::MobyUnitTest; + + # get example input + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->exampleInput + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->example_input( MOBY::RDF::Utils::trim($val) ); + + # get example output + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA + ->validOutputXML + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->expected_output( MOBY::RDF::Utils::trim($val) ); + + # get regex + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->validREGEX + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->regex( MOBY::RDF::Utils::trim($val) ); + + # get xpath + $val = + $model->getObjects( + $ut, + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->validXPath + ) + ); + $val = "" unless $$val[0]; + $val = $$val[0]->getValue if ref($val) eq 'ARRAY' and $$val[0]; + $unit->xpath( MOBY::RDF::Utils::trim($val) ); + + # set the unit test in the service + $instance->unitTest($unit); + + # should only be one ... so last; + last; + } # this service is done ... push @{$services}, $instance; From kawas at dev.open-bio.org Thu Nov 20 19:37:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:37:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201937.mAKJbggm013344@dev.open-bio.org> kawas Thu Nov 20 14:37:42 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv13309/Perl/MOBY-Client Modified Files: populate_libs.pl Log Message: added the service rdf parser to the list of libs moby-live/Perl/MOBY-Client populate_libs.pl,1.7,1.8 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/17 15:30:55 1.7 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/populate_libs.pl 2008/11/20 19:37:42 1.8 @@ -13,7 +13,7 @@ my @Client = qw ( Central.pm CollectionArticle.pm OntologyServer.pm Registration.pm SecondaryArticle.pm Service.pm ServiceInstance.pm SimpleArticle.pm SimpleInput.pm MobyUnitTest.pm ); my @Exception = qw ( MobyException.pm MobyExceptionCodes.pm ); my @RDF = qw ( Utils.pm ); -my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm); +my @Parsers = qw ( ServiceTypeParser.pm NamespaceParser.pm DatatypeParser.pm ServiceParser.pm ); my @predicates = qw ( DC_PROTEGE.pm MOBY_PREDICATES.pm OMG_LSID.pm RDF.pm RDFS.pm FETA.pm OWL.pm ); # current working directory ... @@ -112,6 +112,8 @@ # ? +---Parsers # ? ? ServiceTypeParser.pm # ? ? NamespaceParser.pm +# ? ? ServiceParser.pm +# ? ? DatatypeParser.pm # ? ? # ? +---Predicates # ? DC_PROTEGE.pm From kawas at dev.open-bio.org Thu Nov 20 19:39:02 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:39:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201939.mAKJd247013385@dev.open-bio.org> kawas Thu Nov 20 14:39:01 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv13350/Perl/MOBY-Client Modified Files: MANIFEST Log Message: added MobyUnitTest and ServiceParser to the MANIFEST moby-live/Perl/MOBY-Client MANIFEST,1.10,1.11 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST,v retrieving revision 1.10 retrieving revision 1.11 diff -u -r1.10 -r1.11 --- /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST 2008/08/06 14:48:49 1.10 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/MANIFEST 2008/11/20 19:39:01 1.11 @@ -28,12 +28,14 @@ lib/MOBY/Client/ServiceInstance.pm lib/MOBY/Client/SimpleArticle.pm lib/MOBY/Client/SimpleInput.pm +lib/MOBY/Client/MobyUnitTest.pm lib/MOBY/CommonSubs.pm lib/MOBY/CrossReference.pm lib/MOBY/MobyXMLConstants.pm lib/MOBY/RDF/Parsers/DatatypeParser.pm lib/MOBY/RDF/Parsers/NamespaceParser.pm lib/MOBY/RDF/Parsers/ServiceTypeParser.pm +lib/MOBY/RDF/Parsers/ServiceParser.pm lib/MOBY/RDF/Predicates/DC_PROTEGE.pm lib/MOBY/RDF/Predicates/FETA.pm lib/MOBY/RDF/Predicates/MOBY_PREDICATES.pm From kawas at dev.open-bio.org Thu Nov 20 19:39:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:39:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201939.mAKJdgTs013443@dev.open-bio.org> kawas Thu Nov 20 14:39:42 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF In directory dev.open-bio.org:/tmp/cvs-serv13408/Perl/MOBY-Server/lib/MOBY/RDF Modified Files: Utils.pm Log Message: added a trim function moby-live/Perl/MOBY-Server/lib/MOBY/RDF Utils.pm,1.6,1.7 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/09/02 13:13:20 1.6 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/20 19:39:42 1.7 @@ -130,7 +130,7 @@ sub getHttpRequestByURL { my ( $self, $url ) = @_; my $ua = LWP::UserAgent->new; - $ua->agent( "pMOBY/Central/1.0"); + $ua->agent( "pMOBY/Central/$VERSION"); my $req = HTTP::Request->new( GET => @@ -171,5 +171,22 @@ END_OF_RDF } +=head2 trim + +trims whitespace from the begining and end of a string + +=cut + +sub trim { + my ($self, $text) = @_; + $text = $self + unless (ref($self) == 'Moby::RDF::Utils') and defined($text); + $text =~ s/^\s+//; + $text =~ s/\s+$//; + return $text; +} + + + 1; __END__ From kawas at dev.open-bio.org Thu Nov 20 19:40:42 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Thu, 20 Nov 2008 14:40:42 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811201940.mAKJegcJ013483@dev.open-bio.org> kawas Thu Nov 20 14:40:41 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv13448/Perl/MOBY-Server Modified Files: MANIFEST Log Message: added MobyUnitTest and ServiceParser to the MANIFEST moby-live/Perl/MOBY-Server MANIFEST,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST 2008/07/07 18:32:25 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/MANIFEST 2008/11/20 19:40:41 1.9 @@ -43,6 +43,7 @@ lib/MOBY/Client/ServiceInstance.pm lib/MOBY/Client/SimpleArticle.pm lib/MOBY/Client/SimpleInput.pm +lib/MOBY/Client/MobyUnitTest.pm lib/MOBY/collection_input.pm lib/MOBY/collection_output.pm lib/MOBY/CommonSubs.pm @@ -67,6 +68,7 @@ lib/MOBY/RDF/Parsers/DatatypeParser.pm lib/MOBY/RDF/Parsers/NamespaceParser.pm lib/MOBY/RDF/Parsers/ServiceTypeParser.pm +lib/MOBY/RDF/Parsers/ServiceParser.pm lib/MOBY/RDF/Predicates/DC_PROTEGE.pm lib/MOBY/RDF/Predicates/FETA.pm lib/MOBY/RDF/Predicates/MOBY_PREDICATES.pm From kawas at dev.open-bio.org Mon Nov 24 14:38:33 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 24 Nov 2008 09:38:33 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811241438.mAOEcXWE010637@dev.open-bio.org> kawas Mon Nov 24 09:38:32 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies In directory dev.open-bio.org:/tmp/cvs-serv10602/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies Modified Files: Services.pm Log Message: added unit test information to the RDF that is outputted by this module. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies Services.pm,1.8,1.9 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm 2008/10/31 18:40:37 1.8 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Ontologies/Services.pm 2008/11/24 14:38:32 1.9 @@ -125,21 +125,21 @@ $self->{datatype_uri} = $CONF->{mobyobject}->{resourceURL} || ''; $self->{namespace_uri} = $CONF->{mobynamespace}->{resourceURL} || ''; } unless $args{endpoint}; - + # save the endpoint/namespace/uri if passed in $self->{endpoint} = $args{endpoint} if $args{endpoint}; $self->{namespace} = $args{endpoint} if $args{namespace}; unless ( $self->{instance_uri} ) { - my $moby = MOBY::Client::Central->new( + my $moby = + MOBY::Client::Central->new( Registries => { mobycentral => { URL => $self->{endpoint}, URI => 'http://mobycentral.cbr.nrc.ca/MOBY/Central' } } - ) - if $self->{endpoint}; + ) if $self->{endpoint}; # otherwise use default one $moby = MOBY::Client::Central->new() unless $self->{endpoint}; @@ -176,10 +176,13 @@ $self->{namespace_uri} = $self->{namespace_uri} . "/" unless $self->{namespace_uri} =~ m/^.*(\/{1})$/; $self->{datatype_uri} = $self->{datatype_uri} . "/" - unless $self->{datatype_uri} =~ m/^.*(\/{1})$/; + unless $self->{datatype_uri} =~ m/^.*(\/{1})$/; #set the isAlive path - $self->{is_alive_path} = $CONF->{mobycentral}->{service_tester_path} if $ENV{MOBY_SERVER} and $self->{endpoint} and $ENV{MOBY_SERVER} eq $self->{endpoint}; + $self->{is_alive_path} = $CONF->{mobycentral}->{service_tester_path} + if $ENV{MOBY_SERVER} + and $self->{endpoint} + and $ENV{MOBY_SERVER} eq $self->{endpoint}; # done return $self; @@ -208,20 +211,20 @@ my $authURI = $hash->{authURI} || ''; my $name = $hash->{serviceName} || ''; my $prettyPrint = $hash->{prettyPrint} ? $hash->{prettyPrint} : 'yes'; - my $addIsAlive = $hash->{isAlive} ? $hash->{isAlive} : 'yes'; - my $services = []; + my $addIsAlive = $hash->{isAlive} ? $hash->{isAlive} : 'yes'; + my $services = []; my $RegObject; # use the passed in endpoint if applicable - my $moby = MOBY::Client::Central->new( + my $moby = + MOBY::Client::Central->new( Registries => { mobycentral => { URL => $self->{endpoint}, URI => 'http://mobycentral.cbr.nrc.ca/MOBY/Central' } } - ) - if $self->{endpoint}; + ) if $self->{endpoint}; # otherwise use default one $moby = MOBY::Client::Central->new() unless $self->{endpoint}; @@ -230,7 +233,8 @@ ( $services, $RegObject ) = $moby->findService( authURI => $authURI, serviceName => $name ); - } else { + } + else { my (@URIS) = $moby->retrieveServiceProviders(); foreach my $provider (@URIS) { my ( $instances, $RegObject ) = @@ -265,13 +269,13 @@ my $node_factory = new RDF::Core::NodeFactory(); foreach my $SI (@$services) { + # used for computing checksums - my $service_name = $SI->name; + my $service_name = $SI->name; my $service_authority = $SI->authority; - my $resource = - new RDF::Core::Resource( $self->{instance_uri}, - $SI->authority . "," . $SI->name ); + my $resource = new RDF::Core::Resource( $self->{instance_uri}, + $SI->authority . "," . $SI->name ); $model->addStmt( new RDF::Core::Statement( $resource, @@ -329,14 +333,18 @@ new RDF::Core::Literal( $SI->name ) ) ); - eval{ + eval { do { + # add is alive information if necessary - if ( $self->{is_alive_path} and -e $self->{is_alive_path} and -r $self->{is_alive_path} ."/isAliveStats.xml") { + if ( $self->{is_alive_path} + and -e $self->{is_alive_path} + and -r $self->{is_alive_path} . "/isAliveStats.xml" ) + { my $parser = XML::LibXML->new(); - my $doc = + my $doc = $parser->parse_file( - $self->{is_alive_path} . '/isAliveStats.xml' ); + $self->{is_alive_path} . '/isAliveStats.xml' ); my $value = "true"; my $id = $SI->authority . "," . $SI->name; my @nodelist = $doc->getElementsByTagName("service"); @@ -346,30 +354,41 @@ last; } $model->addStmt( - new RDF::Core::Statement( - $resource, - $resource->new( MOBY::RDF::Predicates::FETA->isAlive ), - new RDF::Core::Literal($value) - ) + new RDF::Core::Statement( + $resource, + $resource->new( + MOBY::RDF::Predicates::FETA->isAlive + ), + new RDF::Core::Literal($value) + ) ); - } else { - + } + else { + # by default, state the service is alive ... $model->addStmt( - new RDF::Core::Statement( - $resource, - $resource->new( MOBY::RDF::Predicates::FETA->isAlive ), - new RDF::Core::Literal('true') - ) + new RDF::Core::Statement( + $resource, + $resource->new( + MOBY::RDF::Predicates::FETA->isAlive + ), + new RDF::Core::Literal('true') + ) ); } - } unless $addIsAlive =~ /no/i; + } unless $addIsAlive =~ /no/i; }; + # add the authoring statements - my $bnode = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->providedBy ) - ); #$node_factory->newResource; + my $bnode = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->providedBy + ) + ); #$node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $resource, @@ -401,20 +420,25 @@ ) ); $model->addStmt( - new RDF::Core::Statement( - $bnode, - $resource->new( MOBY::RDF::Predicates::RDF->type ), - new RDF::Core::Resource( - MOBY::RDF::Predicates::FETA->organisation - ) - ) + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->organisation + ) + ) ); # add parameter statements - my $operation = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->hasOperation) - ); # $node_factory->newResource; + my $operation = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->hasOperation + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $resource, @@ -440,9 +464,12 @@ ) ); $bnode = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex("$service_authority/$service_name/" . MOBY::RDF::Predicates::FETA->performsTask) - ); # $node_factory->newResource; + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA->performsTask + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -460,26 +487,107 @@ ) ); $model->addStmt( - new RDF::Core::Statement( - $bnode, - $resource->new( MOBY::RDF::Predicates::RDF->type ), - new RDF::Core::Resource( - $self->{service_uri} . $SI->type + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( $self->{service_uri} . $SI->type ) ) - ) ); + # add unit test data here ... + if ( $SI->unitTest ) { + my $unit_test = $SI->unitTest; + $bnode = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . MOBY::RDF::Predicates::FETA + ->unitTest + ) + ); + + # add the type + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::RDF->type ), + new RDF::Core::Resource( + MOBY::RDF::Predicates::FETA->unitTest + ) + ) + ); + + # add the example input if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->exampleInput ), + new RDF::Core::Literal( $unit_test->example_input ) + ) + ) + if $unit_test->example_input + and $unit_test->example_input ne ''; + + # add the valid output xml if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( + MOBY::RDF::Predicates::FETA->validOutputXML + ), + new RDF::Core::Literal( $unit_test->expected_output ) + ) + ) + if $unit_test->expected_output + and $unit_test->expected_output ne ''; + + # add the valid regex if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->validREGEX ), + new RDF::Core::Literal( $unit_test->regex ) + ) + ) + if $unit_test->regex + and $unit_test->regex ne ''; + + # add the valid xpath expression if defined + $model->addStmt( + new RDF::Core::Statement( + $bnode, + $resource->new( MOBY::RDF::Predicates::FETA->validXPath ), + new RDF::Core::Literal( $unit_test->xpath ) + ) + ) + if $unit_test->xpath + and $unit_test->xpath ne ''; + + $model->addStmt( + new RDF::Core::Statement( + $operation, + $resource->new( MOBY::RDF::Predicates::FETA->hasUnitTest ), + $bnode + ) + ); + } + my $inputs = $SI->input; foreach (@$inputs) { - my $inputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName) - ); # $node_factory->newResource; + my $inputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -509,18 +617,17 @@ ) ); - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $_->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter . "/" + . $_->articleName . "/" + . $_->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -535,22 +642,21 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $_->objectType + $self->{datatype_uri} . $_->objectType ) #TODO check for lsid ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -571,17 +677,18 @@ ); my $namespaces = $_->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -605,13 +712,13 @@ $inNamespaces, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); } - } elsif ( $_->isCollection ) { + } + elsif ( $_->isCollection ) { $model->addStmt( new RDF::Core::Statement( @@ -632,16 +739,16 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -663,18 +770,18 @@ my $simples = $_->Simples; foreach my $simp (@$simples) { - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $simp->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $simp->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -689,24 +796,26 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $simp->objectType + $self->{datatype_uri} . $simp->objectType ) #TODO check for lsid ) ); my $namespaces = $simp->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -735,8 +844,7 @@ MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); @@ -749,15 +857,17 @@ foreach (@$secondaries) { next unless $_->isSecondary; - my $inputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . "isSecondaryInputParameter/" - . MOBY::RDF::Predicates::FETA->inputParameter - . "/" - . $_->articleName) - ); #$node_factory->newResource; + my $inputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . "isSecondaryInputParameter/" + . MOBY::RDF::Predicates::FETA->inputParameter + . "/" + . $_->articleName + ) + ); #$node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -777,16 +887,17 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . "isSecondary/" - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . "isSecondary/" + . MOBY::RDF::Predicates::FETA->hasParameterType + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $inputParameter, @@ -822,8 +933,7 @@ $resource->new( MOBY::RDF::Predicates::FETA->min ), new RDF::Core::Literal( $_->min ) ) - ) - if defined( $_->min ); + ) if defined( $_->min ); $model->addStmt( new RDF::Core::Statement( @@ -831,8 +941,7 @@ $resource->new( MOBY::RDF::Predicates::FETA->max ), new RDF::Core::Literal( $_->max ) ) - ) - if defined( $_->max ); + ) if defined( $_->max ); $model->addStmt( new RDF::Core::Statement( @@ -852,8 +961,7 @@ ), new RDF::Core::Literal( $_->default ) ) - ) - if defined( $_->default ); + ) if defined( $_->default ); $model->addStmt( new RDF::Core::Statement( @@ -875,15 +983,18 @@ my $outputs = $SI->output; foreach (@$outputs) { - my $outputParameter = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName) - ); # $node_factory->newResource; + my $outputParameter = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $operation, @@ -913,18 +1024,17 @@ ) ); - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $_->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter . "/" + . $_->articleName . "/" + . $_->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -939,22 +1049,21 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $_->objectType + $self->{datatype_uri} . $_->objectType ) #TODO check for lsid ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -975,17 +1084,18 @@ ); my $namespaces = $_->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1009,13 +1119,13 @@ $inNamespaces, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); } - } elsif ( $_->isCollection ) { + } + elsif ( $_->isCollection ) { $model->addStmt( new RDF::Core::Statement( @@ -1036,16 +1146,16 @@ ) ); - my $pType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->hasParameterType - . "/" - . $_->articleName - ) - ); # $node_factory->newResource; + my $pType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->hasParameterType . "/" + . $_->articleName + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1067,18 +1177,18 @@ my $simples = $_->Simples; foreach my $simp (@$simples) { - my $oType = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/" ) - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $simp->objectType - ) - ); # $node_factory->newResource; + my $oType = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( $_->isSimple ? "isSimple/" : "isCollection/" ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $simp->objectType + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1093,24 +1203,26 @@ $oType, $resource->new( MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{datatype_uri} - . $simp->objectType + $self->{datatype_uri} . $simp->objectType ) #TODO check for lsid ) ); my $namespaces = $simp->namespaces; foreach my $n (@$namespaces) { - my $inNamespaces = new RDF::Core::Resource( - $self->{instance_uri}, - md5_hex( - "$service_authority/$service_name/" - . ($_->isSimple ? "isSimple/" : "isCollection/") - . MOBY::RDF::Predicates::FETA->outputParameter - . "/" - . $_->articleName - . "/" - . $n) - ); # $node_factory->newResource; + my $inNamespaces = + new RDF::Core::Resource( + $self->{instance_uri}, + md5_hex( + "$service_authority/$service_name/" + . ( + $_->isSimple ? "isSimple/" : "isCollection/" + ) + . MOBY::RDF::Predicates::FETA->outputParameter + . "/" + . $_->articleName . "/" + . $n + ) + ); # $node_factory->newResource; $model->addStmt( new RDF::Core::Statement( $outputParameter, @@ -1139,8 +1251,7 @@ MOBY::RDF::Predicates::RDF->type ), new RDF::Core::Resource( - $self->{namespace_uri} - . $n + $self->{namespace_uri} . $n ) #TODO check for lsids ) ); @@ -1150,11 +1261,12 @@ } } my $xml = ''; - my $serializer = new RDF::Core::Model::Serializer( - Model => $model, - Output => \$xml, - BaseURI => 'URI://BASE/', - ); + my $serializer = + new RDF::Core::Model::Serializer( + Model => $model, + Output => \$xml, + BaseURI => 'URI://BASE/', + ); $serializer->serialize; return $xml; } From kawas at dev.open-bio.org Mon Nov 24 14:40:04 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Mon, 24 Nov 2008 09:40:04 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811241440.mAOEe4DW010678@dev.open-bio.org> kawas Mon Nov 24 09:40:03 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv10643/Perl/MOBY-Server Modified Files: Changes Log Message: updated to reflect changes to Services.pm (added unit test information to rdf) moby-live/Perl/MOBY-Server Changes,1.16,1.17 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.16 retrieving revision 1.17 diff -u -r1.16 -r1.17 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/17 15:28:46 1.16 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/24 14:40:03 1.17 @@ -25,6 +25,8 @@ - Fixed the uri in the RDF returned in MobyMetadataResolver.pm when the resolver is attempting to let you know what the latest lsid is for the given entity. + - RDF for service instances now includes unit test information if unit + test information is available for the service instance. 1.05 From kawas at dev.open-bio.org Tue Nov 25 17:29:55 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 12:29:55 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251729.mAPHTti8015447@dev.open-bio.org> kawas Tue Nov 25 12:29:54 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client In directory dev.open-bio.org:/tmp/cvs-serv15412/Perl/MOBY-Server/lib/MOBY/Client Modified Files: MobyUnitTest.pm Log Message: fixed the way that i was using the hash references. moby-live/Perl/MOBY-Server/lib/MOBY/Client MobyUnitTest.pm,1.2,1.3 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/19 21:31:21 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/Client/MobyUnitTest.pm 2008/11/25 17:29:54 1.3 @@ -195,15 +195,15 @@ # for each doc and remove from current level of hash for my $key ( keys %$control ) { next unless $key =~ m/^xmlns[:]?/; - $control_ns->{''} = %$control->{$key} if $key eq 'xmlns'; - $control_ns->{$1} = %$control->{$key} if $key =~ m/xmlns\:(.*)$/g; - delete %$control->{$key}; + $control_ns->{''} = ${$control}->{$key} if $key eq 'xmlns'; + $control_ns->{$1} = ${$control}->{$key} if $key =~ m/xmlns\:(.*)$/g; + delete $$control->{$key}; } for my $key ( keys %$test ) { next unless $key =~ m/^xmlns[:]?/; - $test_ns->{''} = %$test->{$key} if $key eq 'xmlns'; - $test_ns->{$1} = %$test->{$key} if $key =~ m/xmlns\:(.*)$/g; - delete %$test->{$key}; + $test_ns->{''} = ${$test}->{$key} if $key eq 'xmlns'; + $test_ns->{$1} = ${$test}->{$key} if $key =~ m/xmlns\:(.*)$/g; + delete ${$test}->{$key}; } # compare current level number of keys @@ -223,27 +223,27 @@ { # are we dealing with scalar values now or more nesting? - if ( ref( %$control->{$key} ) eq 'ARRAY' ) { + if ( ref( ${$control}->{$key} ) eq 'ARRAY' ) { # both items should be an array - next unless ref(%$test->{$test_key}) eq 'ARRAY'; + next unless ref(${$test}->{$test_key}) eq 'ARRAY'; # array sizes should match here ... - next unless @{%$control->{$key}} == @{%$test->{$test_key}}; + next unless @{${$control}->{$key}} == @{${$test}->{$test_key}}; # more nesting try matching child nodes my $child_matches = 0; - foreach my $child ( @{ %$control->{$key} } ) { + foreach my $child ( @{ ${$control}->{$key} } ) { my $matched = undef; - foreach my $test_child ( @{ %$test->{$test_key} } ) { + foreach my $test_child ( @{ ${$test}->{$test_key} } ) { $matched = $self->_compare_current_level( $child, $test_child, $control_ns, $test_ns ); $child_matches++ if $matched; last if $matched; } # end inner foreach - $matching_nodes++ if @{ %$control->{$key} } == $child_matches; + $matching_nodes++ if @{ ${$control}->{$key} } == $child_matches; } } else { # compare scalar values now # we dont care about whitespace, so we need to trim the text - my $c_text = $self->_clear_whitespace(%$control->{$key}); - my $t_text = $self->_clear_whitespace(%$test->{$test_key}); + my $c_text = $self->_clear_whitespace(${$control}->{$key}); + my $t_text = $self->_clear_whitespace(${$test}->{$test_key}); $matching_nodes++ if $c_text eq $t_text; last if $c_text eq $t_text; } @@ -332,6 +332,8 @@ croak "not yet implemented ...\n"; } +sub DESTROY { } + 1; __END__ From kawas at dev.open-bio.org Tue Nov 25 18:05:44 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 13:05:44 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251805.mAPI5iUF015600@dev.open-bio.org> kawas Tue Nov 25 13:05:44 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers In directory dev.open-bio.org:/tmp/cvs-serv15553/Perl/MOBY-Server/lib/MOBY/RDF/Parsers Modified Files: NamespaceParser.pm ServiceParser.pm DatatypeParser.pm ServiceTypeParser.pm Log Message: array and hash refs werent generated/returned properly. moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers NamespaceParser.pm,1.3,1.4 ServiceParser.pm,1.2,1.3 DatatypeParser.pm,1.2,1.3 ServiceTypeParser.pm,1.3,1.4 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm 2008/09/02 13:12:58 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/NamespaceParser.pm 2008/11/25 18:05:44 1.4 @@ -110,8 +110,8 @@ sub getNamespaces { my ($self, $url) = @_; - -return \{} unless $url; +my %hash; +return \%hash unless $url; # download string from url my $rdf = undef; @@ -120,7 +120,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -135,7 +135,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $namespace = $statement->getSubject->getLocalValue; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/20 19:35:46 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceParser.pm 2008/11/25 18:05:44 1.3 @@ -118,15 +118,15 @@ sub getServices { my ( $self, $url ) = @_; - - return \[] unless $url; + my @services; + return \@services unless $url; # download string from url my $rdf = undef; # 'try/catch' eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; - return \[] unless $rdf; + return \@services unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -149,7 +149,6 @@ ) ) ); - my $services = []; my $statement = $enumerator->getFirst; while ( defined $statement ) { my $instance = MOBY::Client::ServiceInstance->new; @@ -842,15 +841,15 @@ } # this service is done ... - push @{$services}, $instance; + push @services, $instance; # next if any $statement = $enumerator->getNext; } $enumerator->close; - # return hash - return \$services; + # return array ref + return \@services; } =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm 2008/09/02 13:12:58 1.2 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/DatatypeParser.pm 2008/11/25 18:05:44 1.3 @@ -135,8 +135,8 @@ sub getDatatypes { my ($self, $url) = @_; - -return \{} unless $url; +my %hash = (); +return \%hash unless $url; # download string from url my $rdf = undef; @@ -145,7 +145,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate my $storage = new RDF::Core::Storage::Memory; @@ -160,7 +160,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $datatype = $statement->getSubject->getLocalValue; =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm 2008/09/02 13:12:58 1.3 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Parsers/ServiceTypeParser.pm 2008/11/25 18:05:44 1.4 @@ -110,8 +110,8 @@ sub getServiceTypes { my ($self, $url) = @_; - -return \{} unless $url; +my %hash; +return \%hash unless $url; # download string from url my $rdf = undef; @@ -120,7 +120,7 @@ eval { $rdf = MOBY::RDF::Utils->new()->getHttpRequestByURL($url); }; -return \{} unless $rdf; +return \%hash unless $rdf; # create RDF model and populate @@ -136,7 +136,6 @@ # get information from the model my $enumerator = $model->getStmts(undef, new RDF::Core::Resource( MOBY::RDF::Predicates::DC_PROTEGE->publisher ), undef); -my %hash = (); my $statement = $enumerator->getFirst; while (defined $statement) { my $servicetype = $statement->getSubject->getLocalValue; From kawas at dev.open-bio.org Tue Nov 25 18:05:59 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 13:05:59 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251805.mAPI5x1w015640@dev.open-bio.org> kawas Tue Nov 25 13:05:59 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF In directory dev.open-bio.org:/tmp/cvs-serv15605/Perl/MOBY-Server/lib/MOBY/RDF Modified Files: Utils.pm Log Message: moby-live/Perl/MOBY-Server/lib/MOBY/RDF Utils.pm,1.7,1.8 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/20 19:39:42 1.7 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/lib/MOBY/RDF/Utils.pm 2008/11/25 18:05:59 1.8 @@ -180,7 +180,7 @@ sub trim { my ($self, $text) = @_; $text = $self - unless (ref($self) == 'Moby::RDF::Utils') and defined($text); + unless (ref($self) eq 'Moby::RDF::Utils') and defined($text); $text =~ s/^\s+//; $text =~ s/\s+$//; return $text; From kawas at dev.open-bio.org Tue Nov 25 19:37:10 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:37:10 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251937.mAPJbA0r015753@dev.open-bio.org> kawas Tue Nov 25 14:37:10 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi In directory dev.open-bio.org:/tmp/cvs-serv15718/Perl/MOBY-Server/share/cgi Modified Files: service_tester.pl Log Message: added $TIMEOUT to the cgi call for web services moby-live/Perl/MOBY-Server/share/cgi service_tester.pl,1.5,1.6 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl,v retrieving revision 1.5 retrieving revision 1.6 diff -u -r1.5 -r1.6 --- /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl 2008/06/17 16:19:39 1.5 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi/service_tester.pl 2008/11/25 19:37:10 1.6 @@ -154,6 +154,7 @@ # test cgi services do { my $ua = LWP::UserAgent->new; + $ua->timeout($TIMEOUT); my $req = POST $url, [ data => $input]; $req = $ua->request($req); $out = $req->content if $req->is_success; From kawas at dev.open-bio.org Tue Nov 25 19:39:36 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:39:36 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251939.mAPJdaMR015808@dev.open-bio.org> kawas Tue Nov 25 14:39:36 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/share/cgi In directory dev.open-bio.org:/tmp/cvs-serv15777/Perl/MOBY-Server/share/cgi Added Files: service_unit_tester.pl Log Message: first crack at an 'agent' that can do unit testing of moby services. basically: script gets all sig urls services extracted from urls any service that defines a unit test is tested and results stored. moby-live/Perl/MOBY-Server/share/cgi service_unit_tester.pl,NONE,1.1 From kawas at dev.open-bio.org Tue Nov 25 19:47:24 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:47:24 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251947.mAPJlNY0015848@dev.open-bio.org> kawas Tue Nov 25 14:47:23 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts In directory dev.open-bio.org:/tmp/cvs-serv15813/Perl/MOBY-Server/bin/scripts Modified Files: moby-s-install.pl Log Message: added a check for XML::Simple and added a copy statement for service_unit_tester.pl moby-live/Perl/MOBY-Server/bin/scripts moby-s-install.pl,1.13,1.14 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl,v retrieving revision 1.13 retrieving revision 1.14 diff -u -r1.13 -r1.14 --- /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl 2008/09/02 13:19:13 1.13 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/bin/scripts/moby-s-install.pl 2008/11/25 19:47:23 1.14 @@ -76,6 +76,7 @@ DBI DBD::mysql LS + XML::Simple ) ) { @@ -1393,7 +1394,7 @@ } $answer = pprompt( -"Would you like to auxillary scripts? These include the service pinger, a test page for the rdf agent, an RDF generator page, etc? [y] ", +"Would you like to auxillary scripts? These include the service pinger, unit tester, a test page for the rdf agent, an RDF generator page, etc? [y] ", -ynd => 'y' ); if ($answer eq 'y') { @@ -1442,7 +1443,19 @@ { '#!/usr/bin/perl -w' => "#!$perl_exec", } ); say -'Please don\'t forget to place the service pinger on a cron! TODO - explain how to do that!'; +'Please don\'t forget to place the service pinger on a cron!'; + + # copy the service unit tester script + file_from_template( + "$service_tester_path/service_unit_tester.pl", + File::ShareDir::dist_file( + 'MOBY', 'cgi/service_unit_tester.pl' + ), + 'MOBY-Central service unit tester script', + { '#!/usr/bin/perl -w' => "#!$perl_exec", } + ); + say +'Please don\'t forget to place the service unit tester on a cron!'; #copy the other scripts now file_from_template( From kawas at dev.open-bio.org Tue Nov 25 19:49:38 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:49:38 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251949.mAPJncdW015888@dev.open-bio.org> kawas Tue Nov 25 14:49:38 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Server In directory dev.open-bio.org:/tmp/cvs-serv15853/Perl/MOBY-Server Modified Files: Changes Log Message: updated the changes to reflect addition of the service_unit_tester script and some bug fixes moby-live/Perl/MOBY-Server Changes,1.17,1.18 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Server/Changes,v retrieving revision 1.17 retrieving revision 1.18 diff -u -r1.17 -r1.18 --- /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/24 14:40:03 1.17 +++ /home/repository/moby/moby-live/Perl/MOBY-Server/Changes 2008/11/25 19:49:38 1.18 @@ -27,6 +27,8 @@ for the given entity. - RDF for service instances now includes unit test information if unit test information is available for the service instance. + - fixed how references were created in MOBY::RDF::Ontologies::* + - added a unit testing script for services to the shared/cgi dir. 1.05 From kawas at dev.open-bio.org Tue Nov 25 19:51:19 2008 From: kawas at dev.open-bio.org (Eddie Kawas) Date: Tue, 25 Nov 2008 14:51:19 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811251951.mAPJpJmF015928@dev.open-bio.org> kawas Tue Nov 25 14:51:19 EST 2008 Update of /home/repository/moby/moby-live/Perl/MOBY-Client In directory dev.open-bio.org:/tmp/cvs-serv15893/Perl/MOBY-Client Modified Files: Changes Log Message: moby-live/Perl/MOBY-Client Changes,1.4,1.5 =================================================================== RCS file: /home/repository/moby/moby-live/Perl/MOBY-Client/Changes,v retrieving revision 1.4 retrieving revision 1.5 diff -u -r1.4 -r1.5 --- /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/17 15:30:55 1.4 +++ /home/repository/moby/moby-live/Perl/MOBY-Client/Changes 2008/11/25 19:51:18 1.5 @@ -4,6 +4,9 @@ * changes to makefile reflecting the cpan addition of wsrf * added MOBY/Async.pm to the module * added MOBY/Client/MobyUnitTest for unit testing our services. + * RDF for service instances now includes unit test information if unit + test information is available for the service instance. + * fixed how references were created in MOBY::RDF::Ontologies::* 1.02 16 May 2008 * fixed bug in MOBY::Client::Central::DUMP that resulted From groscurt at dev.open-bio.org Wed Nov 26 08:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRmW017272@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg added to the repository moby-live/Java/src/main/de/mpg - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRfs017255@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de added to the repository moby-live/Java/src/main/de - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:51:37 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:37 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pb0G017378@dev.open-bio.org> groscurt Wed Nov 26 03:51:37 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv17347/src/main/de/mpg/mpiz_koeln/featureClient Added Files: FeatureClientResult.java FeatureClientException.java FeatureClient.java ServiceCallFactory.java Log Message: package for the featureClient moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient FeatureClientResult.java,NONE,1.1 FeatureClientException.java,NONE,1.1 FeatureClient.java,NONE,1.1 ServiceCallFactory.java,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 08:51:27 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:27 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRsA017291@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg/mpiz_koeln Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:51:28 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:51:28 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260851.mAQ8pRBG017310@dev.open-bio.org> groscurt Wed Nov 26 03:51:27 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv17221/src/main/de/mpg/mpiz_koeln/featureClient Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:52:05 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:52:05 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260852.mAQ8q5mp017420@dev.open-bio.org> groscurt Wed Nov 26 03:52:05 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test In directory dev.open-bio.org:/tmp/cvs-serv17386/src/main/de/mpg/mpiz_koeln/featureClient/test Log Message: Directory /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test added to the repository moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:52:20 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:52:20 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260852.mAQ8qKRs017480@dev.open-bio.org> groscurt Wed Nov 26 03:52:20 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test In directory dev.open-bio.org:/tmp/cvs-serv17449/src/main/de/mpg/mpiz_koeln/featureClient/test Added Files: FeatureClientFactory.java SimpleSingleCall.java SingleCallWithParameters.java MultiCallWithParameters.java MultiCallByDefinition.java ComplexSingleCall.java SingleCallDefinition.java SimpleMultiCall.java SingleMultiServiceCall.java Log Message: test classes for feature client moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/test FeatureClientFactory.java,NONE,1.1 SimpleSingleCall.java,NONE,1.1 SingleCallWithParameters.java,NONE,1.1 MultiCallWithParameters.java,NONE,1.1 MultiCallByDefinition.java,NONE,1.1 ComplexSingleCall.java,NONE,1.1 SingleCallDefinition.java,NONE,1.1 SimpleMultiCall.java,NONE,1.1 SingleMultiServiceCall.java,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 08:56:44 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:56:44 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260856.mAQ8uiLj017675@dev.open-bio.org> groscurt Wed Nov 26 03:56:44 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv17640/docs Modified Files: index.html Added Files: FeatureClient.html Log Message: docs for the featureClient moby-live/Java/docs FeatureClient.html,NONE,1.1 index.html,1.36,1.37 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.36 retrieving revision 1.37 diff -u -r1.36 -r1.37 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/11/19 15:29:04 1.36 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/26 08:56:43 1.37 @@ -138,7 +138,9 @@ href="CmdLineClients.html">Command-line clients
    • How to use the BioMoby plugin in -Taverna

      +Taverna +

    • The Feature Client (an extended MOBY client)

    • Using generated object (MoSeS)
        From groscurt at dev.open-bio.org Wed Nov 26 11:06:51 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:06:51 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261106.mAQB6pOY018427@dev.open-bio.org> groscurt Wed Nov 26 06:06:50 EST 2008 Update of /home/repository/moby/moby-live/Java/src/support/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18393/src/support/featureClient Log Message: Directory /home/repository/moby/moby-live/Java/src/support/featureClient added to the repository moby-live/Java/src/support/featureClient - New directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/-,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/New,v: No such file or directory rcsdiff: /home/repository/moby/moby-live/Java/src/support/featureClient/RCS/directory,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 11:07:02 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:02 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB72Ep018487@dev.open-bio.org> groscurt Wed Nov 26 06:07:02 EST 2008 Update of /home/repository/moby/moby-live/Java/src/support/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18456/src/support/featureClient Added Files: README Log Message: README for the featureClient moby-live/Java/src/support/featureClient README,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 11:07:57 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:57 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB7vXv018551@dev.open-bio.org> groscurt Wed Nov 26 06:07:57 EST 2008 Update of /home/repository/moby/moby-live/Java In directory dev.open-bio.org:/tmp/cvs-serv18516 Modified Files: build.xml Log Message: ant files changed or added for the featureclient moby-live/Java build.xml,1.75,1.76 =================================================================== RCS file: /home/repository/moby/moby-live/Java/build.xml,v retrieving revision 1.75 retrieving revision 1.76 diff -u -r1.75 -r1.76 --- /home/repository/moby/moby-live/Java/build.xml 2008/10/25 14:28:18 1.75 +++ /home/repository/moby/moby-live/Java/build.xml 2008/11/26 11:07:57 1.76 @@ -14,6 +14,7 @@ + ]> @@ -123,7 +124,8 @@ - + + @@ -145,6 +147,7 @@ &dashboardBuild; &seahawkBuild; &mobysyncBuild; + &featureClientBuild; @@ -362,7 +365,7 @@ + From groscurt at dev.open-bio.org Wed Nov 26 11:07:57 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 06:07:57 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261107.mAQB7vFa018567@dev.open-bio.org> groscurt Wed Nov 26 06:07:57 EST 2008 Update of /home/repository/moby/moby-live/Java/xmls In directory dev.open-bio.org:/tmp/cvs-serv18516/xmls Added Files: featureClientBuild.xml Log Message: ant files changed or added for the featureclient moby-live/Java/xmls featureClientBuild.xml,NONE,1.1 From groscurt at dev.open-bio.org Wed Nov 26 14:56:19 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 09:56:19 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811261456.mAQEuJBe018903@dev.open-bio.org> groscurt Wed Nov 26 09:56:19 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient In directory dev.open-bio.org:/tmp/cvs-serv18868/src/main/de/mpg/mpiz_koeln/featureClient Modified Files: FeatureClient.java Log Message: typo moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient FeatureClient.java,1.1,1.2 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java 2008/11/26 08:51:37 1.1 +++ /home/repository/moby/moby-live/Java/src/main/de/mpg/mpiz_koeln/featureClient/FeatureClient.java 2008/11/26 14:56:19 1.2 @@ -598,7 +598,7 @@ * @param user the user * @param password his/her password */ - public void setAuthentification(String user, String password) { + public void setAuthentication(String user, String password) { this.user = user; this.password = password; } From groscurt at dev.open-bio.org Fri Nov 28 12:05:03 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Fri, 28 Nov 2008 07:05:03 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811281205.mASC533i030271@dev.open-bio.org> groscurt Fri Nov 28 07:05:02 EST 2008 Update of /home/repository/moby/moby-live/Java/docs In directory dev.open-bio.org:/tmp/cvs-serv30216/docs Modified Files: index.html Log Message: updated to point to secure web service documentation moby-live/Java/docs index.html,1.37,1.38 =================================================================== RCS file: /home/repository/moby/moby-live/Java/docs/index.html,v retrieving revision 1.37 retrieving revision 1.38 diff -u -r1.37 -r1.38 --- /home/repository/moby/moby-live/Java/docs/index.html 2008/11/26 08:56:43 1.37 +++ /home/repository/moby/moby-live/Java/docs/index.html 2008/11/28 12:05:02 1.38 @@ -102,7 +102,8 @@
      • How to change Ant's build.xml
      • RDF Agent -
      • The Dashboard as Webstart +
      • The Dashboard as Webstart
    @@ -139,7 +140,8 @@
  • How to use the BioMoby plugin in Taverna -
  • The Feature Client (an extended MOBY client)

  • Using generated object (MoSeS) @@ -173,7 +175,8 @@
  • MoSeS - Moby Services Support
  • Biomoby Dashboard -
  • An Alternative jMoby Step-by-Step Guide +
  • An Alternative jMoby Step-by-Step Guide
  • Code Examples

    @@ -189,6 +192,9 @@

  • The org.biomoby.shared.data package "In Anger": creating data instances
  • +
  • How to setup and create secure BioMoby web services
  • + From senger at dev.open-bio.org Sun Nov 30 10:33:17 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Sun, 30 Nov 2008 05:33:17 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811301033.mAUAXHEa020365@dev.open-bio.org> senger Sun Nov 30 05:33:17 EST 2008 Update of /home/repository/moby/jars-archive In directory dev.open-bio.org:/tmp/cvs-serv20346 Modified Files: README Log Message: remove not-anymore-needed jar files jars-archive README,1.3,1.4 =================================================================== RCS file: /home/repository/moby/jars-archive/README,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- /home/repository/moby/jars-archive/README 2005/06/10 14:07:45 1.3 +++ /home/repository/moby/jars-archive/README 2008/11/30 10:33:17 1.4 @@ -1,45 +1,6 @@ -Purpose -------- - -This module serves just one purpose: to store commonly (or less -commonly) used third-party Java libraries (jar files) in order to -share them by several other CVS modules without the need to include -them separately in all those CVS modules. - -I guess that the purpose is similar to the CVS-native notion of the -module dependencies. Or similar what one can get from sites like -www.ibiblio.org. - -The idea is that various projects (mainly those dealing with and using -Java) can have in their build.xml a target "gather" (or whatever name) -that will use HTTP protocol to fetch the third-party libraries the -first time it builds everything. An example can be found in the -moby-live module (subdirectory Java). - -It started as a BioMoby initiative so it is located as a module within -the 'moby' CVS repository. But it can used by others, as well - one -does not use it as a CVS module, but like a normal HTTP resource. Only -when you want to add a new library, or to update an existing one, you -need to check-out it as usual. - - -Directory structure -------------------- - -current - It contains (usually) the latest version of the third-party -libraries. This is the most convenient place to fetch all the jars -files from because your build.xml can use just one property pointing -here. - However, if you need special (older or newer) version of a -third-party libraries for a particular project, create a new directory -(e.g. a directory jMoby for libraries that are specific for the -BioMoby in Java). - -licenses - Put here licenses for various third-party libraries that are -included in this module. Also, when adding new libraries make sure -that you are not breaking any licenses. +This directory of jar files was replaced by using Maven. Please update +to the latest jMoby and you will not need to use this module. Except +for other puposes, like getting jMoby's web applications (war files). ---------------------------------------------------------------------- Started by: Martin Senger (martin.senger at gmail.com), June 2005 From senger at dev.open-bio.org Sun Nov 30 10:33:07 2008 From: senger at dev.open-bio.org (Martin Senger) Date: Sun, 30 Nov 2008 05:33:07 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811301033.mAUAX7cT020333@dev.open-bio.org> senger Sun Nov 30 05:33:06 EST 2008 Update of /home/repository/moby/jars-archive/current In directory dev.open-bio.org:/tmp/cvs-serv20246 Removed Files: FastInfoset.jar activation.jar adenine.jar alltools.jar alltools2.jar axis-ant.jar axis.jar castor-0.9.5.jar commons-codec-1.3.jar commons-collections-2.1.jar commons-dbcp-1.1.jar commons-discovery-0.2.jar commons-httpclient-3.0-rc2.jar commons-io-1.3.1.jar commons-lang-2.1.jar commons-logging-1.0.4.jar commons-pool-1.1.jar concurrent.jar dnsjava-1.3.2.jar fetaEngine.jar http.jar icis-pedigree.jar icu4j.jar jakarta-oro-2.0.5.jar jaxb-api.jar jaxb-impl.jar jaxb-xjc.jar jaxen-core.jar jaxen-jdom.jar jaxrpc.jar jaxws-api.jar jaxws-rt.jar jaxws-tools.jar jcalendar.jar jdom.jar jena.jar jfcunit.jar jodconverter-2.2.1.jar jsr173_api.jar jsr181-api.jar jsr250-api.jar juh-2.3.0.jar junit.jar jurt-2.3.0.jar log4j-1.2.12.jar lsid-client-1.1.2.jar lsid-server-1.1.2.jar mail.jar mailapi_1_3_1.jar mysql-connector-java-3.1.7-bin.jar rdf-api-2001-01-19.jar resolver.jar ridl-2.3.0.jar saaj-api.jar saaj-impl.jar saaj.jar saxpath.jar seahawk.jar servlet.jar sjsxp.jar slf4j-api-1.4.3.jar slf4j-jdk14-1.4.3.jar stax-ex.jar streambuffer.jar taverna.jar unoil-2.3.0.jar wsdl4j-1.5.1.jar xalan.jar xercesImpl.jar xercesSamples.jar xml-apis.jar xmlParserAPIs.jar Log Message: remove not-anymore-needed jar files jars-archive/current FastInfoset.jar,1.1,NONE activation.jar,1.3,NONE adenine.jar,1.1,NONE alltools.jar,1.1,NONE alltools2.jar,1.10,NONE axis-ant.jar,1.2,NONE axis.jar,1.2,NONE castor-0.9.5.jar,1.1,NONE commons-codec-1.3.jar,1.1,NONE commons-collections-2.1.jar,1.1,NONE commons-dbcp-1.1.jar,1.1,NONE commons-discovery-0.2.jar,1.1,NONE commons-httpclient-3.0-rc2.jar,1.1,NONE commons-io-1.3.1.jar,1.1,NONE commons-lang-2.1.jar,1.1,NONE commons-logging-1.0.4.jar,1.1,NONE commons-pool-1.1.jar,1.1,NONE concurrent.jar,1.1,NONE dnsjava-1.3.2.jar,1.1,NONE fetaEngine.jar,1.1,NONE http.jar,1.1,NONE icis-pedigree.jar,1.1,NONE icu4j.jar,1.1,NONE jakarta-oro-2.0.5.jar,1.1,NONE jaxb-api.jar,1.1,NONE jaxb-impl.jar,1.1,NONE jaxb-xjc.jar,1.1,NONE jaxen-core.jar,1.1,NONE jaxen-jdom.jar,1.1,NONE jaxrpc.jar,1.2,NONE jaxws-api.jar,1.1,NONE jaxws-rt.jar,1.1,NONE jaxws-tools.jar,1.1,NONE jcalendar.jar,1.1,NONE jdom.jar,1.2,NONE jena.jar,1.1,NONE jfcunit.jar,1.1,NONE jodconverter-2.2.1.jar,1.1,NONE j! sr173_api.jar,1.1,NONE jsr181-api.jar,1.1,NONE jsr250-api.jar,1.1,NONE juh-2.3.0.jar,1.1,NONE junit.jar,1.1,NONE jurt-2.3.0.jar,1.1,NONE log4j-1.2.12.jar,1.1,NONE lsid-client-1.1.2.jar,1.1,NONE lsid-server-1.1.2.jar,1.1,NONE mail.jar,1.1,NONE mailapi_1_3_1.jar,1.1,NONE mysql-connector-java-3.1.7-bin.jar,1.1,NONE rdf-api-2001-01-19.jar,1.1,NONE resolver.jar,1.1,NONE ridl-2.3.0.jar,1.1,NONE saaj-api.jar,1.1,NONE saaj-impl.jar,1.1,NONE saaj.jar,1.2,NONE saxpath.jar,1.1,NONE seahawk.jar,1.2,NONE servlet.jar,1.2,NONE sjsxp.jar,1.1,NONE slf4j-api-1.4.3.jar,1.1,NONE slf4j-jdk14-1.4.3.jar,1.1,NONE stax-ex.jar,1.1,NONE streambuffer.jar,1.1,NONE taverna.jar,1.1,NONE unoil-2.3.0.jar,1.1,NONE wsdl4j-1.5.1.jar,1.1,NONE xalan.jar,1.1,NONE xercesImpl.jar,1.2,NONE xercesSamples.jar,1.1,NONE xml-apis.jar,1.1,NONE xmlParserAPIs.jar,1.2,NONE rcsdiff: /home/repository/moby/jars-archive/current/RCS/FastInfoset.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/activation.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/adenine.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/alltools.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/alltools2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/axis-ant.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/axis.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/castor-0.9.5.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-codec-1.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-collections-2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-dbcp-1.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-discovery-0.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-httpclient-3.0-rc2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-io-1.3.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-lang-2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-logging-1.0.4.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/commons-pool-1.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/concurrent.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/dnsjava-1.3.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/fetaEngine.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/http.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/icis-pedigree.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/icu4j.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jakarta-oro-2.0.5.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-impl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxb-xjc.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxen-core.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxen-jdom.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxrpc.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-rt.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jaxws-tools.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jcalendar.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jdom.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jena.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jfcunit.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jodconverter-2.2.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr173_api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr181-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jsr250-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/juh-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/junit.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/jurt-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/log4j-1.2.12.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/lsid-client-1.1.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/lsid-server-1.1.2.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mail.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mailapi_1_3_1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/mysql-connector-java-3.1.7-bin.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/rdf-api-2001-01-19.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/resolver.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/ridl-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj-api.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj-impl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saaj.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/saxpath.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/seahawk.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/servlet.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/sjsxp.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/slf4j-api-1.4.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/slf4j-jdk14-1.4.3.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/stax-ex.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/streambuffer.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/taverna.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/unoil-2.3.0.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/wsdl4j-1.5.1.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xalan.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xercesImpl.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xercesSamples.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xml-apis.jar,v: No such file or directory rcsdiff: /home/repository/moby/jars-archive/current/RCS/xmlParserAPIs.jar,v: No such file or directory From groscurt at dev.open-bio.org Wed Nov 26 08:53:43 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:53:43 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260853.mAQ8rhFs017531@dev.open-bio.org> groscurt Wed Nov 26 03:53:43 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/client In directory dev.open-bio.org:/tmp/cvs-serv17488/src/main/org/biomoby/client Modified Files: MobyRequest.java CentralImpl.java BaseClient.java Log Message: changes done enabling the authentication for services moby-live/Java/src/main/org/biomoby/client MobyRequest.java,1.40,1.41 CentralImpl.java,1.57,1.58 BaseClient.java,1.12,1.13 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java,v retrieving revision 1.40 retrieving revision 1.41 diff -u -r1.40 -r1.41 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/14 20:32:02 1.40 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/MobyRequest.java 2008/11/26 08:53:43 1.41 @@ -1,1019 +1,1028 @@ -package org.biomoby.client; - -import java.io.*; -import java.util.*; - -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.rpc.Service; -import javax.xml.transform.TransformerException; - -import org.apache.axis.client.Call; -import org.apache.axis.message.MessageElement; -import org.apache.xml.utils.PrefixResolver; -import org.apache.xml.utils.PrefixResolverDefault; -import org.apache.xpath.XPath; -import org.apache.xpath.XPathContext; -import org.apache.xpath.objects.XNodeSet; -import org.apache.xpath.objects.XObject; - -import org.biomoby.shared.*; -import org.biomoby.shared.data.*; -import org.biomoby.shared.parser.MobyTags; // defined the Moby XML element names -import org.biomoby.w3c.addressing.EndpointReference; -import org.omg.lsae.notifications.AnalysisEvent; - -import org.w3c.dom.*; - -/** - * This class handles the WSDL transaction to request a response - * from a remote SOAP Web service that handles the - * MOBY format. It depends on - * having already retrieved the definition of the Web service via - * the MOBY central registry using the - * jMOBY API, - * and for now it uses the - * Apache - * Axis Web services framework, as well as Apache Xalan. There are code comments for the - * few lines that rely on Axis classes rather than the JAX-RPC interfaces. - * - * @author Paul Gordon gordonp at ucalgary.ca - */ -public class MobyRequest{ - - protected MobyService mobyService = null; - protected MobyContentInstance inputData = null; - protected MobyContentInstance outputData = null; - protected Central mobyCentral = null; - protected PrefixResolver mobyPrefixResolver = null; - - protected Hashtable wsdlCache = null; - protected String lastWsdlCacheKey = null; - protected DocumentBuilder docBuilder = null; - protected Service service = null; - - protected Class stringType; - protected static boolean debug = false; - protected PrintStream debugPS = System.err; - protected XPathContext xpath_context; - protected String responseString = null; - - private XPath stringEncodedXPath; - private XPath base64EncodedXPath; - private XPath simpleChildXPath; - private XPath collectionChildXPath; - - private int autoID = 0; - - // Used as invocation callback if MobyRequest is acting as a server, - // or is executing services as a client asynchronously - private Vector eventHandlers; - - /** - * Default constructor. You should have a Central instance around since you're going to - * be retrieving MobyServices to pass into here. Lets reuse it. - * - * @param central An instance of a Moby central object so we can make requests about object types, etc. - * @throws ParserConfigurationException if JAXP doesn't have any valid DOM-building XML parsers set up for use - */ - public MobyRequest(Central central) throws ParserConfigurationException{ - mobyCentral = central; - wsdlCache = new Hashtable(); - - eventHandlers = new Vector(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - docBuilder = dbf.newDocumentBuilder(); - - try{ - stringType = Class.forName("java.lang.String"); - }catch(ClassNotFoundException classe){ - debugPS.println("WARNING: Something is very wrong, could not find Class definition of String: " + classe); - } - - xpath_context = new XPathContext(); - mobyPrefixResolver = new MobyPrefixResolver(); - - // Now compile the XPath statements that will be used fetch data from the server response - try{ - base64EncodedXPath = new XPath("//*[starts-with(substring-after(@"+ - MobyPrefixResolver.XSI1999_PREFIX+ - ":type, ':'), \"base64\") or starts-with(substring-after(@"+ - MobyPrefixResolver.XSI2001_PREFIX+ - ":type, ':'), \"base64\")]", null, - mobyPrefixResolver, XPath.SELECT); - stringEncodedXPath = new XPath("//*[substring-after(@"+ - MobyPrefixResolver.XSI1999_PREFIX+ - ":type, ':')=\"string\" or substring-after(@"+ - MobyPrefixResolver.XSI2001_PREFIX+ - ":type, ':')=\"string\"] | //"+ - MobyPrefixResolver.SOAP_ENC_PREFIX+":string", null, - mobyPrefixResolver, XPath.SELECT); - simpleChildXPath = new XPath("moby:Simple | Simple", null, - mobyPrefixResolver, XPath.SELECT); - collectionChildXPath = new XPath("moby:Collection | Collection", null, - mobyPrefixResolver, XPath.SELECT); - } - catch(TransformerException te){ - debugPS.println("Syntax error encountered while compiling XPath " + - "statements for internal use (code bug?): " + te); - } - setDebugMode(System.getProperty("moby.debug") != null); - } - - /** - * @param mode if true, debugging information is printed to the stream returned by getDebugOutputStream - */ - public void setDebugMode(boolean mode){ - debug = mode; - } - - /** - * Standard error is used unless this method is called. - * - * @param ps the OutputStream to which debugging information is sent. - * @throws IllegalArgumentException if the stream is null - */ - public void setDebugPrintStream(PrintStream ps) throws IllegalArgumentException{ - if(ps == null){ - throw new IllegalArgumentException("The OutputStream specified to MobyRequest was null"); - } - debugPS = ps; - } - - /** - * @return the instance of the class implementing Central that we are using - */ - public Central getCentralImpl(){ - return mobyCentral; - } - - /** - * @param mobyservice the MobyService that should be executed when invokeService is called - */ - public void setService(MobyService mobyservice){ - if(mobyservice == null){ - mobyService = null; - } - else if(mobyService == null || !mobyservice.equals(mobyService)){ - mobyService = mobyservice; - } - } - - /** - * @return the MobyService that will be executed when invokeService is called - */ - public MobyService getService(){ - return mobyService; - } - - /** - * @return the Raw MOBY XML response as a string - */ - public String getResponseXML(){ - return responseString; - } - - /** - * Sets the input data for the MOBY service request. The length of the input array, and the - * number of input parameters required by the service must be equal when invokeService() is called. - * This method strictly enforces that the input be of the appropriate type for the service. - * - * Note that there is no requirement to use MobyDataInstance.setXmlMode() before passing in - * data, this class will temporarily set the XML mode of the data when it is required. - * - * @throws IllegalArgumentException if the input does not fit the criteria of the service (e.g. wrong data type) - */ - public void setInput(MobyContentInstance data) throws MobyException{ - inputData = data; - } - - /** - * Takes the data in the array, with their current articleNames, as input for the service - */ - public void setInput(MobyDataInstance[] data) throws MobyException{ - MobyDataJob job = new MobyDataJob(); - for(MobyDataInstance param: data){ - job.put(param.getName(), param); - } - inputData = new MobyContentInstance(); - inputData.put(job); - } - - /** - * Convenience method to run services that take one argument. If the service - * requires the input to have a name, it will be automatically assigned. - */ - public void setInput(MobyDataInstance datum) throws MobyException{ - setInput(datum, ""); - } - - /** - * Convenience method to run services that take one named argument. - */ - public void setInput(MobyDataInstance datum, String paramName) throws MobyException{ - inputData = new MobyContentInstance(datum, paramName); - } - - /** - * @return the MobyService that will be executed when invokeService is called - */ - public MobyContentInstance getInput(){ - return inputData; - } - - /** - * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) - */ - public void setSecondaryInput(Collection secondaryData) throws MobyException{ - setSecondaryInput(secondaryData.toArray(new MobyDataSecondaryInstance[secondaryData.size()])); - } - - /** - * This method will assign the provided secondary parameters to all primary input data currently - * in this object. This is covenient if you are running 100 seqs through BLAST and only want to set - * the parameters once. If you instead want to set secondary input differently for all primary inputs, you'll - * need to create a custom MobyContentInstance as input to setInput(). - * - * @throws MobyException if a parameter name is blank, or overrides a primary parameter - */ - public void setSecondaryInput(MobyDataSecondaryInstance[] secondaryData) throws MobyException{ - - Iterator queryNames = inputData.keySet().iterator(); - // For each query - while(queryNames.hasNext()){ - MobyDataJob queryParams = inputData.get(queryNames.next()); - // Set all the secondary params (overwrites any old ones) - for(int i = 0; i < secondaryData.length; i++){ - String secName = secondaryData[i].getName(); - if(secName == null || secName.length() == 0){ - throw new MobyException("A secondary parameter cannot have a blank name (array index " + i + ")"); - } - if(queryParams.containsKey(secName) && queryParams.get(secName) instanceof MobyPrimaryData){ - throw new MobyException("A secondary parameter cannot override an existing primary parameter " + - "with the same name (" + secName + ")"); - } - queryParams.put(secName, secondaryData[i]); - } - } - } - - /** - * @return a vector of MobyDataInstance[], each element of the vector is the collection of response objects for the correspondingly indexed input request. - * - * @throws MobyException if you try to get the results before calling InvokeService - */ - public MobyContentInstance getOutput() throws MobyException{ - if(outputData == null){ - throw new MobyException("Trying to access MOBY service results " + - "before the service is invoked"); - } - else{ - return outputData; - } - } - - /** - * The main method of the class. If all of the MOBY input objects - * are properly defined according to the Web service definition, - * a SOAP request will be sent to the remote server, and the method - * will return one or more MOBY objects (synchronous). - * Call this method after calling setService, and setInput. If you do not call - * setSecondaryInput, the default secondary parameter values will be used. - * - * @return the results of the remote Web service in response to the give input - * - * @throws MobyException i.e. there was something wrong with the input, output or remote service's logic - * @throws SOAPException i.e. there was a problem with the underlying transaction/transport layer - */ - public MobyContentInstance invokeService() throws Exception, MobyException, SOAPException, NoSuccessException{ - return mobyService.isAsynchronous() ? invokeService(inputData, new StringBuffer()) : invokeService(inputData, (StringBuffer) null); - } - - // Used internally for asynchronous thread calls that all need the XML data - // and can't rely on the answer from thread-insensitive getResponseXML() - private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML) - throws Exception, MobyException, SOAPException, NoSuccessException{ - return invokeService(inData, contentsXML, null, 0); - } - - private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML, MobyRequestEventHandler handler, int requestId) - throws Exception, MobyException, SOAPException, NoSuccessException{ - - if(mobyService == null){ - throw new MobyException("Tried to invoke null service from MobyRequest (call setService first)"); - } - - Element mobyDOM = null; - if(mobyService.isAsynchronous()){ - // Async is "simpler", because it had to merge DOMs together into a single MobyContentInstance anyway - MobyContentInstance mci = performAsyncSOAPRequest(mobyService, inData, handler, requestId); - StringWriter writer = new StringWriter(); - MobyDataUtils.toXMLDocument(writer, mci); - contentsXML.append(writer.toString()); - return mci; - } - else{ - String mobyXML = convertMOBYDataToMOBYRequest(inData); - Call call = getServiceFromWSDL(); - mobyDOM = performSOAPRequest(call, mobyXML, contentsXML); - // The following parses the DOM and extracts all the appropriate jMOBY objects to represent the XML in Java - return MobyDataUtils.fromXMLDocument(mobyDOM, mobyService.getServiceType().getRegistry()); - } - } - - protected MobyContentInstance performAsyncSOAPRequest(MobyService mservice, MobyContentInstance inData, - MobyRequestEventHandler handler, int requestId) - throws Exception{ - String mobyXML = convertMOBYDataToMOBYRequest(inData); - EndpointReference epr = AsyncClient.sendRequest(mservice, mobyXML); - - // Essentially cloning, so removing ids doesn't change the - // MobyContentInstance "data" (which we will use again later on) - MobyContentInstance finalContents = new MobyContentInstance(); - Set queryIDs = new HashSet(inData.keySet()); - try { - // Should add some timeout here... - while(!queryIDs.isEmpty()){ - // todo: make this setable - Thread.sleep(5000); - - AnalysisEvent[] events = - AsyncClient.poll(epr, queryIDs); - - Vector newDataAvailable = new Vector(); - for(AnalysisEvent event: events){ - if(event != null && event.isCompleted()){ - queryIDs.remove(event.getQueryId()); - newDataAvailable.add(event.getQueryId()); - } - } - - if(newDataAvailable.size() > 0){ - // Parse and merge the new data into the existing contents - InputStream resultStream = AsyncClient.getResultStream(epr, newDataAvailable); - Element mobyDOM = asyncSoapTextToMobyDOM(resultStream); - MobyContentInstance newResults = MobyDataUtils.fromXMLDocument(mobyDOM, mservice.getServiceType().getRegistry()); - // The merge - for(String jobid: newResults.keySet()){ - finalContents.put(jobid, newResults.get(jobid)); - } - - // Inform the handler that some data has been added to the response (for incremental display?) - if(handler != null){ - MobyRequestEvent mre = new MobyRequestEvent(finalContents, this, mservice, null, requestId); - StringWriter xmlWriter = new StringWriter(); - MobyDataUtils.toXMLDocument(xmlWriter, finalContents); - - mre.setContentsXML(xmlWriter.toString()); - if(!queryIDs.isEmpty()){ - // Send an update event only if we aren't finished yet. - // If we are finished, the client is going to get this event as the - // invocation thread finishes up (no need to double up). - handler.processEvent(mre); - } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - AsyncClient.destroy(epr); - throw new Exception("Exception occured while polling the service invocation: " + e); - } - - return finalContents; - } - - private Element asyncSoapTextToMobyDOM(InputStream inStream) throws Exception{ - Element soapDOM = null; - synchronized(docBuilder){ - soapDOM = docBuilder.parse(inStream).getDocumentElement(); - } - final boolean IS_ASYNC_SERVICE_CALL = true; - return decodeSOAPMessage(soapDOM, null, null, IS_ASYNC_SERVICE_CALL); - } - - /** - * Asynchronous call to invokeService. A callback to the passed-in handler will be made when - * the response is ready, or there is an exception. - * - * @return the id that the callback event will return from getID(), allowing a client to distinguish between multiple concurrent invocation callbacks - */ - public synchronized int invokeService(MobyRequestEventHandler handler){ - int id = autoID++; - - Thread t = new InvocationThread(this, inputData, handler, id); // see internal class definition below - t.start(); - - return id; - } - - // This is the class that asynchronously calls the service and does a callback to - // the handler specified in the invocation. - class InvocationThread extends Thread { - MobyContentInstance data; - MobyService mservice; - MobyRequest mobyRequest; - MobyRequestEventHandler handler; - int requestId; - - InvocationThread(MobyRequest mr, MobyContentInstance inData, MobyRequestEventHandler h, int id){ - data = inData; - mobyRequest = mr; - mservice = mobyRequest.getService(); - handler = h; - requestId = id; - - // Name the thread after the service being run, mostly for ease of debugging - setName(mservice.getName()+requestId); - } - - public void run() { - MobyRequestEvent requestEvent = new MobyRequestEvent(data, mobyRequest, mservice, null, requestId); - // Tell the handler we're starting the request, with the given data - handler.start(requestEvent); - - MobyRequestEvent responseEvent = null; - MobyContentInstance content = null; - StringBuffer contentsXML = new StringBuffer(); //to be filled in by the RPC call below - try{ - content = mobyRequest.invokeService(data, contentsXML, handler, requestId); //RPC call... - } - catch(Exception e){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, e, requestId); - } - catch(Error err){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, err, requestId); - } - if(responseEvent == null){ - responseEvent = new MobyRequestEvent(content, mobyRequest, mservice, null, requestId); - } - // We've got the raw XML laying around, so why not provide it unmolested to the callback? - responseEvent.setContentsXML(contentsXML.toString()); - handler.processEvent(responseEvent); - handler.stop(mobyRequest, requestId); - } - } - - public void addEventHandler(MobyRequestEventHandler h){ - eventHandlers.add(h); - } - - public void removeEventHandler(MobyRequestEventHandler h){ - eventHandlers.remove(h); - } - - public void sendResponse(MobyRequestEvent mre){ - // Not yet implemented, need to conform to some web.xml specification here... - } - - /** - * This method retrieves from Moby Central a copy of the WSDL document for the service - * (or uses an internally cached copy from a previous invocation), and sets the variables for the - * SOAP call appropriately so you can consequently call performSOAPRequest. - */ - protected Call getServiceFromWSDL() throws MobyException, NoSuccessException{ -// String wsdl = null; - -// // Since this is how we retrieve a service from Central, use the same values as the key to the hash -// String wsdlCacheKey = mobyService.getName() + "@" + mobyService.getAuthority(); - -// // This is the same call as last time, so we don't need to change the setup -// if(wsdlCacheKey.equals(lastWsdlCacheKey)){ -// return setCallFromWSDL((String) wsdlCache.get(wsdlCacheKey)); -// } -// // We haven't encountered this service yet -// else if(!wsdlCache.containsKey(wsdlCacheKey)){ -// wsdl = mobyCentral.getServiceWSDL(mobyService.getName(), mobyService.getAuthority()); -// wsdlCache.put(wsdlCacheKey, wsdl); -// } -// // We've dealt with this one before -// else{ -// wsdl = (String) wsdlCache.get(wsdlCacheKey); -// } - -// lastWsdlCacheKey = wsdlCacheKey; // Keep track of the last invocation - - // Get ready to do SOAP - return setCallFromWSDL(null); - } - - /** - * Creates the SOAP Call that will be invoked later. This should be based on the WSDL document - * and parameter information from the MobyService, but these are currently not up to snuff. - */ - protected Call setCallFromWSDL(String wsdl) throws MobyException, SOAPException{ - if(service == null){ - service = new org.apache.axis.client.Service(); // AXIS SPECIFIC This acts as a factory for Calls - } - - Call soapCall; - try{ - soapCall = (Call) service.createCall();//create a fresh Call each time - }catch(javax.xml.rpc.ServiceException se){ - throw new SOAPException("Could not instatiate call to SOAP Service: " + se); - } - - // Should initialize endpoint, etc. This call is AXIS SPECIFIC, otherwise you'll - // have to do the call's info setting manually. - //((org.apache.axis.client.Call) soapCall).setSOAPService(soapService); - soapCall.removeAllParameters(); - soapCall.setTargetEndpointAddress(mobyService.getURL()); - soapCall.setPortName(new QName("http://biomoby.org/", - mobyService.getName() + "PortType")); - //soapCall.setOperationName(new QName("http://biomoby.org/", - // mobyService.getName())); - soapCall.setSOAPActionURI("http://biomoby.org/#" + mobyService.getName()); - return soapCall; - } - - /** - * Calls the invoke() method of the JAX-RPC Call interface. - */ - protected Element performSOAPRequest(Call soapCall, String mobyInputXML, StringBuffer contentsXMLOutput) throws SOAPException{ - // First, turn the input objects into a MOBY XML request - String[] mobyXMLInputData = new String[1]; - - //Setup - mobyXMLInputData[0] = mobyInputXML; - - if(debug) - debugPS.println("returnType just before invoke call is " + soapCall.getReturnType()); - Object returnedObject = null; - try{ - returnedObject = soapCall.invoke(new QName("http://biomoby.org/", - mobyService.getName()), mobyXMLInputData); - } - catch(Exception e){ - e.printStackTrace(); - //System.err.println("Input: "+mobyInputXML); - throw new SOAPException("While invoking SOAP Call: " + e); - } - - try{ - if(debug){ - debugPS.println("SOAP Response was:\n"); - debugPS.println(soapCall.getResponseMessage().getSOAPPart().getEnvelope()); - } - Element resultDom = ((MessageElement) soapCall.getResponseMessage().getSOAPPart().getEnvelope()).getAsDOM(); - return decodeSOAPMessage(resultDom, contentsXMLOutput, mobyInputXML); - } catch(Exception e){ - e.printStackTrace(); - throw new SOAPException("Could not get SOAP response as DOM Element: "+ e); - } - - } - - public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML) - throws SOAPException, MobyException{ - return decodeSOAPMessage(n, contentsXMLOutput, inputXML, false); - } - - /** - * Isolates the MOBY Data from the SOAP message returned by the remote service host. - * - * @throws SOAPException if the MOBY payload cannot be found in the SOAP message - * @throws MobyException if the MOBY message is not well-formed XML - * - * @return The root element of the MOBY response DOM - */ - public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML, boolean async) - throws SOAPException, MobyException{ - if(n == null){ - throw new SOAPException("SOAP Message given to decode is null"); - } - - NodeList node_list = null; - XPath responseElementXPath = null; - try{ - if(async){ - responseElementXPath = new XPath("//"+MobyPrefixResolver.WSRP_PREFIX + - ":"+AsyncClient.WSRP_MULTI_PROPERTY_TAG_NAME+"Response", - null, mobyPrefixResolver, XPath.SELECT); - } - else{ - responseElementXPath = new XPath("//"+ MobyPrefixResolver.MOBY_TRANSPORT_PREFIX+ - ":"+mobyService.getName()+"Response | //" + - mobyService.getName()+"Response | " + - "//"+ MobyPrefixResolver.MOBY_TRANSPORT_PREFIX+ - ":"+mobyService.getName() + " | //" + - mobyService.getName(), - null, mobyPrefixResolver, XPath.SELECT); - } - }catch(TransformerException te){ - throw new SOAPException("Cannot select SOAP nodes due to exception "+ - "while compiling XPath statement (code bug?):" +te); - } - try{ - node_list = runXPath(responseElementXPath, n); - }catch(TransformerException te){ - throw new SOAPException("Cannot select SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - - if(node_list == null || node_list.getLength() == 0){ - throw new SOAPException("Could not find a response element in SOAP payload (service " + - mobyService.getName() + ")"); - } - - if(node_list.getLength() > 1){ - throw new SOAPException("Found more than one response element in SOAP payload, " + - "unable to resolve ambiguity of the payload (service provider error?)"); - } - - Node[] responseNodes = null; - if(async){ - Vector nodes = new Vector(); - NodeList resultNodeList = node_list.item(0).getChildNodes(); - for(int i = 0; resultNodeList != null && i < resultNodeList.getLength(); i++){ - if(!(resultNodeList.item(i) instanceof Element)){ - continue; - } - Element resultElement = (Element) resultNodeList.item(i); - if(resultElement.getLocalName().startsWith(AsyncClient.MOBY_RESULT_PROPERTY_PREFIX)){ - nodes.add(resultElement); - } - } - responseNodes = nodes.toArray(new Node[nodes.size()]); - } - else{ - responseNodes = new Node[]{node_list.item(0)}; - } - - Element domRoot = null; // Where the result will be put - - for(Node responseNode: responseNodes){ - // Find base64 encoded elements in the SOAP message using XPath and - // replace them with the real decoded contents - node_list = null; - try{ - node_list = runXPath(base64EncodedXPath, responseNode); - } - catch(TransformerException te){ - throw new SOAPException("Cannot select base64 encoded SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - if(debug && node_list != null){ - debugPS.println("There were " + node_list.getLength() + - " base64 encoded elements in the data"); - } - - // Do decoding for each base64 part found - for(int i = 0; node_list != null && i < node_list.getLength(); i++){ - org.w3c.dom.Node change = node_list.item(i); - /* Make sure the text data is all put into one contiguous piece for decoding*/ - change.normalize(); - - byte[] decodedBytes = org.apache.axis.encoding.Base64.decode(change.getFirstChild().getNodeValue()); - String newText = new String(decodedBytes); - if(debug){ - debugPS.println("New decoded text is" + newText); - } - - // Swap out this node for the decoded data - change.getParentNode().replaceChild(n.getOwnerDocument().createTextNode(new String(decodedBytes)), - change); - } - - // Now see if there are any strings that need decoding - node_list = null; - try{ - node_list = runXPath(stringEncodedXPath, responseNode); - } - catch(TransformerException te){ - throw new SOAPException("Cannot select string encoded SOAP nodes due to exception "+ - "while executing XPath statement:" +te); - } - - // Do concatenation for each plain string part found - for(int i = 0; node_list != null && i < node_list.getLength(); i++){ - org.w3c.dom.Node change = node_list.item(i); - /* Make sure the text data is all put into one contiguous piece for decoding*/ - change.normalize(); - String plainString = ""; - int j = 0; - for(NodeList children = change.getChildNodes(); - children != null && j < children.getLength(); - j++){ - Node child = children.item(j); - if(child instanceof CDATASection || child instanceof Text){ - plainString += child.getNodeValue(); - if(debug){ - debugPS.println("Plain string is now " + plainString); - } - } - } - - // Swap out this node for the decoded data - change.getParentNode().replaceChild(n.getOwnerDocument().createCDATASection(plainString), change); - } - if(debug && node_list != null){ - debugPS.println("There were " + node_list.getLength() + - " XML Schema string encoded elements in the data"); - } - - // Parse the MOBY XML document payload - responseNode.normalize(); - NodeList children = responseNode.getChildNodes(); - if(children == null){ - throw new MobyException("The MOBY payload has no contents at all"); - } - if(children.getLength() != 1){ - if(debug){ - debugPS.println("Warning: MOBY Payload appears to have more than " + - "just text in it, skipping the non-text sections"); - } - } - - Element predefinedDOM = null; // Choice of ripping DOM Element for moby payload out of SOAP DOM - String localResponseString = ""; // or storing raw XML strings, to be converted to a DOM later - for(int j = 0; j < children.getLength(); j++){ - Node child = children.item(j); - if(child instanceof CDATASection || child instanceof Text){ - // Unescape XML special characters in the string, so we can later on - // parse the payload as regular XML. - // Ignore whitespace-only node - if(child.getNodeValue().matches("^\\s+$")){ - continue; - } - if(debug){ - debugPS.println("Concatenating text in response " + child.getNodeValue()); - } - localResponseString += child.getNodeValue();//.replaceAll("<", "<").replaceAll(">", ">").replaceAll("(&|F)", "&"); - } - if(child instanceof Element && child.getLocalName().equals(MobyTags.MOBY)){ - debugPS.println("Warning: The MOBY contents was found as raw XML inside the SOAP response!\n" + - "This is illegal according to the MOBY-API, please inform the service\n " + - " provider, as parsing such text may not be supported in the future"); - localResponseString = null; - // Store the moby payload root element's DOM represntation, so we don't - // have to serialize it to the localResponseString and then parse it out - // again (that would be wasteful). - predefinedDOM = (Element) child; - break; - } - } - - if(localResponseString != null){ - if(localResponseString.length() == 0){ - throw new MobyException("The MOBY payload has no text contents at all"); - } - if(Character.isWhitespace(localResponseString.charAt(0))){ - localResponseString = localResponseString.trim(); - } - } - - // Check if the payload is an XML document. If not, try a last ditch effort - // by base64 decoding the contents. This is technically not allowable in the - // MOBY spec, but we are being lenient. - if(localResponseString != null && !localResponseString.startsWith("\n"+localResponseString; - debugPS.println("Warning: The MOBY contents was missing an XML declaration, but it is " + - "required by the MOBY API, and may stop working in the future without it. Please " + - "contact the client's provider to correct this."); - } - else{ - String oldResponse = localResponseString; - localResponseString = new String(org.apache.axis.encoding.Base64.decode(localResponseString)); - if(!localResponseString.startsWith(" entry: data.entrySet()){ - String queryName = entry.getKey(); - MobyDataJob query = entry.getValue(); - - // Additionally, we check if they are MobyDataInstances below - Map primaryParams = new HashMap(); - Map secondaryParams = new HashMap(); - - // To store the primary input parameter name as given by the user, - // in case we need it later on for parameter renaming... - String primaryParamName = null; - - for(Map.Entry subentry: query.entrySet()){ - String name = subentry.getKey(); - MobyDataInstance param = subentry.getValue(); - if(param == null){ - throw new MobyException("Query " + queryName + - " contained a null input parameter (" + name + ")"); - } - else if(param instanceof MobyPrimaryData){ - primaryParams.put(name, (MobyPrimaryData) param); - primaryParamName = name; - } - else if(param instanceof MobySecondaryData){ - secondaryParams.put(name, (MobySecondaryData) param); - } - else{ - System.err.println("Input parameter " + name + " (query " + queryName + - ") was not a MobyPrimaryData or MobySecondaryData " + - "as expected, but rather was of class " + param.getClass().getName()); - } - } - - if(inputs != null && inputs.length != primaryParams.size()){ - throw new MobyException("Service " + mobyService.getName() + " was provided " + - primaryParams.size() + - " primary input parameter(s), but takes " + inputs.length + - " (query " + queryName + ")"); - } - if(secondaries != null){ - // If no secondaries provided, fill them in by default - if(secondaries.length != 0){ - for(MobySecondaryData secondary: secondaries){ - if(!secondaryParams.containsKey(secondary.getName())){ - if(debug){ - System.err.println("Setting default secondary param value for missing param " + secondary); - } - query.put(secondary.getName(), new MobyDataSecondaryInstance(secondary)); - } - } - } - if(secondaries.length != secondaryParams.size()){ - throw new MobyException("Service " + mobyService.getName() + " was provided " + - secondaryParams.size() + - " secondary input parameter(s), but takes " + secondaries.length + - " (query " + queryName + "). Extra secondary" + - " parameters must have been specified"); - } - } - - // If there was one anonymous input, assign the name automatically in - // the case the service requires it to be named. This is the only - // unambiguous case in which we can do this. - if(inputs.length == 1){ - String serviceParamName = inputs[0].getName(); // name as req'd by the service - - // name isn't the same as required currently - if(serviceParamName != null && serviceParamName.length() > 0 && - !serviceParamName.equals(primaryParamName)){ - // take out the old parameter - MobyPrimaryData theInputToRename = (MobyPrimaryData) query.remove(primaryParamName); - - // Add in the same parameter, but with the appropriate name - query.put(serviceParamName, (MobyDataInstance) theInputToRename); - } - } - } - - ByteArrayOutputStream mobyRequest = new ByteArrayOutputStream(); - try{ - MobyDataUtils.toXMLDocument(mobyRequest, data); - } - catch(MobyException me){ - throw me; - } - catch(Exception e){ - e.printStackTrace(); - throw new MobyException("Could not create MOBY payload XML from input data: " +e); - } - - if(debug){ - debugPS.println("Input to MOBY Service is:"); - debugPS.print(mobyRequest.toString()); - } - - return mobyRequest.toString(); - } - - /** - * A method that sets up the execution environment for and runs a compiled XPath statement against a DOM node - * You should call releaseXPath when you're done with the results - * @return the list of Nodes that satisfy the XPath in this Node's context - */ - protected NodeList runXPath(XPath xpath, Node n) throws TransformerException{ - NodeList result = null; - int dtm_node_handle = xpath_context.getDTMHandleFromNode(n); - PrefixResolver node_prefix_resolver = new PrefixResolverDefault(n); - XObject xobject = xpath.execute(xpath_context, n, node_prefix_resolver); - if(xobject instanceof XNodeSet){ - result = ((XNodeSet) xobject).nodelist(); - } - else if(debug && xobject != null){ - debugPS.println("Output of XPath was not a XNodeSet as expected, found " + xobject.getClass().getName()); - debugPS.flush(); - } - return result; - } - - protected void releaseXPath(Node n){ - xpath_context.release(xpath_context.getDTM(xpath_context.getDTMHandleFromNode(n)), false); - } -} + +package org.biomoby.client; + +import java.io.*; +import java.util.*; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.rpc.Service; +import javax.xml.transform.TransformerException; + +import org.apache.axis.client.Call; +import org.apache.axis.message.MessageElement; +import org.apache.xml.utils.PrefixResolver; +import org.apache.xml.utils.PrefixResolverDefault; +import org.apache.xpath.XPath; +import org.apache.xpath.XPathContext; +import org.apache.xpath.objects.XNodeSet; +import org.apache.xpath.objects.XObject; + +import org.biomoby.shared.*; +import org.biomoby.shared.data.*; +import org.biomoby.shared.parser.MobyTags; // defined the Moby XML element names +import org.biomoby.w3c.addressing.EndpointReference; +import org.omg.lsae.notifications.AnalysisEvent; + +import org.w3c.dom.*; + +/** + * This class handles the WSDL transaction to request a response from a remote SOAP Web service that handles the MOBY format. It depends on having already retrieved the definition of the Web + * service via the MOBY central registry using the jMOBY + * API, and for now it uses the Apache Axis Web services framework, + * as well as Apache Xalan. There are code comments for the few lines that rely on Axis classes rather than the JAX-RPC + * interfaces. + * + * @author Paul Gordon gordonp at ucalgary.ca + */ +public class MobyRequest { + + protected MobyService mobyService = null; + protected MobyContentInstance inputData = null; + protected MobyContentInstance outputData = null; + protected Central mobyCentral = null; + protected PrefixResolver mobyPrefixResolver = null; + + protected Hashtable wsdlCache = null; + protected String lastWsdlCacheKey = null; + protected DocumentBuilder docBuilder = null; + protected Service service = null; + + protected Class stringType; + protected static boolean debug = false; + protected PrintStream debugPS = System.err; + protected XPathContext xpath_context; + protected String responseString = null; + + private XPath stringEncodedXPath; + private XPath base64EncodedXPath; + private XPath simpleChildXPath; + private XPath collectionChildXPath; + + private int autoID = 0; + + // Used as invocation callback if MobyRequest is acting as a server, + // or is executing services as a client asynchronously + private Vector< MobyRequestEventHandler > eventHandlers; + + private String user; + private String password; + + /** + * Default constructor. You should have a Central instance around since you're going to be retrieving MobyServices + * to pass into here. Lets reuse it. + * + * @param central An instance of a Moby central object so we can make requests about object types, etc. + * @throws ParserConfigurationException if JAXP doesn't have any valid DOM-building XML parsers set up for use + */ + public MobyRequest( Central central ) throws ParserConfigurationException { + mobyCentral = central; + wsdlCache = new Hashtable(); + + eventHandlers = new Vector< MobyRequestEventHandler >(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware( true ); + docBuilder = dbf.newDocumentBuilder(); + + try { + stringType = Class.forName( "java.lang.String" ); + } + catch ( ClassNotFoundException classe ) { + debugPS.println( "WARNING: Something is very wrong, could not find Class definition of String: " + classe ); + } + + xpath_context = new XPathContext(); + mobyPrefixResolver = new MobyPrefixResolver(); + + // Now compile the XPath statements that will be used fetch data from the server response + try { + base64EncodedXPath = new XPath( "//*[starts-with(substring-after(@" + MobyPrefixResolver.XSI1999_PREFIX + + ":type, ':'), \"base64\") or starts-with(substring-after(@" + MobyPrefixResolver.XSI2001_PREFIX + + ":type, ':'), \"base64\")]", null, mobyPrefixResolver, XPath.SELECT ); + stringEncodedXPath = new XPath( "//*[substring-after(@" + MobyPrefixResolver.XSI1999_PREFIX + + ":type, ':')=\"string\" or substring-after(@" + MobyPrefixResolver.XSI2001_PREFIX + + ":type, ':')=\"string\"] | //" + MobyPrefixResolver.SOAP_ENC_PREFIX + ":string", null, + mobyPrefixResolver, XPath.SELECT ); + simpleChildXPath = new XPath( "moby:Simple | Simple", null, mobyPrefixResolver, XPath.SELECT ); + collectionChildXPath = new XPath( "moby:Collection | Collection", null, mobyPrefixResolver, XPath.SELECT ); + } + catch ( TransformerException te ) { + debugPS.println( "Syntax error encountered while compiling XPath " + + "statements for internal use (code bug?): " + te ); + } + setDebugMode( System.getProperty( "moby.debug" ) != null ); + } + + /** + * @param mode if true, debugging information is printed to the stream returned by getDebugOutputStream + */ + public void setDebugMode(boolean mode) { + debug = mode; + } + + /** + * Standard error is used unless this method is called. + * + * @param ps the OutputStream to which debugging information is sent. + * @throws IllegalArgumentException if the stream is null + */ + public void setDebugPrintStream(PrintStream ps) throws IllegalArgumentException { + if ( ps == null ) { + throw new IllegalArgumentException( "The OutputStream specified to MobyRequest was null" ); + } + debugPS = ps; + } + + /** + * @param user the user for a possible service authentication + * @param password the passoword for a possible service authentication + */ + public void setAuthentication(String user, String password) { + this.user = user; + this.password = password; + } + + /** + * @return the instance of the class implementing Central that we are using + */ + public Central getCentralImpl() { + return mobyCentral; + } + + /** + * @param mobyservice the MobyService that should be executed when invokeService is called + */ + public void setService(MobyService mobyservice) { + if ( mobyservice == null ) { + mobyService = null; + } + else if ( mobyService == null || !mobyservice.equals( mobyService ) ) { + mobyService = mobyservice; + } + } + + /** + * @return the MobyService that will be executed when invokeService is called + */ + public MobyService getService() { + return mobyService; + } + + /** + * @return the Raw MOBY XML response as a string + */ + public String getResponseXML() { + return responseString; + } + + /** + * Sets the input data for the MOBY service request. The length of the input array, and the number of input + * parameters required by the service must be equal when invokeService() is called. This method strictly enforces + * that the input be of the appropriate type for the service. + * + * Note that there is no requirement to use MobyDataInstance.setXmlMode() before passing in data, this class will + * temporarily set the XML mode of the data when it is required. + * + * @throws IllegalArgumentException if the input does not fit the criteria of the service (e.g. wrong data type) + */ + public void setInput(MobyContentInstance data) throws MobyException { + inputData = data; + } + + /** + * Takes the data in the array, with their current articleNames, as input for the service + */ + public void setInput(MobyDataInstance[] data) throws MobyException { + MobyDataJob job = new MobyDataJob(); + for ( MobyDataInstance param : data ) { + job.put( param.getName(), param ); + } + inputData = new MobyContentInstance(); + inputData.put( job ); + } + + /** + * Convenience method to run services that take one argument. If the service requires the input to have a name, it + * will be automatically assigned. + */ + public void setInput(MobyDataInstance datum) throws MobyException { + setInput( datum, "" ); + } + + /** + * Convenience method to run services that take one named argument. + */ + public void setInput(MobyDataInstance datum, String paramName) throws MobyException { + inputData = new MobyContentInstance( datum, paramName ); + } + + /** + * @return the MobyService that will be executed when invokeService is called + */ + public MobyContentInstance getInput() { + return inputData; + } + + /** + * Same functionality as setSecondaryInput(MobyDataSecondaryInstance[]) + */ + public void setSecondaryInput(Collection< MobyDataSecondaryInstance > secondaryData) throws MobyException { + setSecondaryInput( secondaryData.toArray( new MobyDataSecondaryInstance[ secondaryData.size() ] ) ); + } + + /** + * This method will assign the provided secondary parameters to all primary input data currently in this object. + * This is covenient if you are running 100 seqs through BLAST and only want to set the parameters once. If you + * instead want to set secondary input differently for all primary inputs, you'll need to create a custom + * MobyContentInstance as input to setInput(). + * + * @throws MobyException if a parameter name is blank, or overrides a primary parameter + */ + public void setSecondaryInput(MobyDataSecondaryInstance[] secondaryData) throws MobyException { + + Iterator queryNames = inputData.keySet().iterator(); + // For each query + while (queryNames.hasNext()) { + MobyDataJob queryParams = inputData.get( queryNames.next() ); + // Set all the secondary params (overwrites any old ones) + for ( int i = 0; i < secondaryData.length; i++ ) { + String secName = secondaryData[ i ].getName(); + if ( secName == null || secName.length() == 0 ) { + throw new MobyException( "A secondary parameter cannot have a blank name (array index " + i + ")" ); + } + if ( queryParams.containsKey( secName ) && queryParams.get( secName ) instanceof MobyPrimaryData ) { + throw new MobyException( "A secondary parameter cannot override an existing primary parameter " + + "with the same name (" + secName + ")" ); + } + queryParams.put( secName, secondaryData[ i ] ); + } + } + } + + /** + * @return a vector of MobyDataInstance[], each element of the vector is the collection of response objects for the + * correspondingly indexed input request. + * + * @throws MobyException if you try to get the results before calling InvokeService + */ + public MobyContentInstance getOutput() throws MobyException { + if ( outputData == null ) { + throw new MobyException( "Trying to access MOBY service results " + "before the service is invoked" ); + } + else { + return outputData; + } + } + + /** + * The main method of the class. If all of the MOBY input objects are properly defined according to the Web service + * definition, a SOAP request will be sent to the remote server, and the method will return one or more MOBY objects + * (synchronous). Call this method after calling setService, and setInput. If you do not call setSecondaryInput, the + * default secondary parameter values will be used. + * + * @return the results of the remote Web service in response to the give input + * + * @throws MobyException i.e. there was something wrong with the input, output or remote service's logic + * @throws SOAPException i.e. there was a problem with the underlying transaction/transport layer + */ + public MobyContentInstance invokeService() throws Exception, MobyException, SOAPException, NoSuccessException { + return mobyService.isAsynchronous() + ? invokeService( inputData, new StringBuffer() ) + : invokeService( inputData, ( StringBuffer ) null ); + } + + // Used internally for asynchronous thread calls that all need the XML data + // and can't rely on the answer from thread-insensitive getResponseXML() + private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML) throws Exception, + MobyException, SOAPException, NoSuccessException { + return invokeService( inData, contentsXML, null, 0 ); + } + + private MobyContentInstance invokeService(MobyContentInstance inData, StringBuffer contentsXML, + MobyRequestEventHandler handler, int requestId) throws Exception, MobyException, SOAPException, + NoSuccessException { + + if ( mobyService == null ) { + throw new MobyException( "Tried to invoke null service from MobyRequest (call setService first)" ); + } + + Element mobyDOM = null; + if ( mobyService.isAsynchronous() ) { + // Async is "simpler", because it had to merge DOMs together into a single MobyContentInstance anyway + MobyContentInstance mci = performAsyncSOAPRequest( mobyService, inData, handler, requestId ); + StringWriter writer = new StringWriter(); + MobyDataUtils.toXMLDocument( writer, mci ); + contentsXML.append( writer.toString() ); + return mci; + } + else { + String mobyXML = convertMOBYDataToMOBYRequest( inData ); + Call call = getServiceFromWSDL(); + if ( user != null && password != null ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, password ); + } + mobyDOM = performSOAPRequest( call, mobyXML, contentsXML ); + // The following parses the DOM and extracts all the appropriate jMOBY objects to represent the XML in Java + return MobyDataUtils.fromXMLDocument( mobyDOM, mobyService.getServiceType().getRegistry() ); + } + } + + protected MobyContentInstance performAsyncSOAPRequest(MobyService mservice, MobyContentInstance inData, + MobyRequestEventHandler handler, int requestId) throws Exception { + String mobyXML = convertMOBYDataToMOBYRequest( inData ); + EndpointReference epr = AsyncClient.sendRequest( mservice, mobyXML ); + + // Essentially cloning, so removing ids doesn't change the + // MobyContentInstance "data" (which we will use again later on) + MobyContentInstance finalContents = new MobyContentInstance(); + Set< String > queryIDs = new HashSet< String >( inData.keySet() ); + try { + // Should add some timeout here... + while (!queryIDs.isEmpty()) { + // todo: make this setable + Thread.sleep( 5000 ); + + AnalysisEvent[] events = AsyncClient.poll( epr, queryIDs ); + + Vector< String > newDataAvailable = new Vector< String >(); + for ( AnalysisEvent event : events ) { + if ( event != null && event.isCompleted() ) { + queryIDs.remove( event.getQueryId() ); + newDataAvailable.add( event.getQueryId() ); + } + } + + if ( newDataAvailable.size() > 0 ) { + // Parse and merge the new data into the existing contents + InputStream resultStream = AsyncClient.getResultStream( epr, newDataAvailable ); + Element mobyDOM = asyncSoapTextToMobyDOM( resultStream ); + MobyContentInstance newResults = MobyDataUtils.fromXMLDocument( mobyDOM, + mservice.getServiceType() + .getRegistry() ); + // The merge + for ( String jobid : newResults.keySet() ) { + finalContents.put( jobid, newResults.get( jobid ) ); + } + + // Inform the handler that some data has been added to the response (for incremental display?) + if ( handler != null ) { + MobyRequestEvent mre = new MobyRequestEvent( finalContents, this, mservice, null, requestId ); + StringWriter xmlWriter = new StringWriter(); + MobyDataUtils.toXMLDocument( xmlWriter, finalContents ); + + mre.setContentsXML( xmlWriter.toString() ); + if ( !queryIDs.isEmpty() ) { + // Send an update event only if we aren't finished yet. + // If we are finished, the client is going to get this event as the + // invocation thread finishes up (no need to double up). + handler.processEvent( mre ); + } + } + } + } + } + catch ( Exception e ) { + e.printStackTrace(); + AsyncClient.destroy( epr ); + throw new Exception( "Exception occured while polling the service invocation: " + e ); + } + + return finalContents; + } + + private Element asyncSoapTextToMobyDOM(InputStream inStream) throws Exception { + Element soapDOM = null; + synchronized ( docBuilder ) { + soapDOM = docBuilder.parse( inStream ).getDocumentElement(); + } + final boolean IS_ASYNC_SERVICE_CALL = true; + return decodeSOAPMessage( soapDOM, null, null, IS_ASYNC_SERVICE_CALL ); + } + + /** + * Asynchronous call to invokeService. A callback to the passed-in handler will be made when the response is ready, + * or there is an exception. + * + * @return the id that the callback event will return from getID(), allowing a client to distinguish between + * multiple concurrent invocation callbacks + */ + public synchronized int invokeService(MobyRequestEventHandler handler) { + int id = autoID++; + + Thread t = new InvocationThread( this, inputData, handler, id ); // see internal class definition below + t.start(); + + return id; + } + + // This is the class that asynchronously calls the service and does a callback to + // the handler specified in the invocation. + class InvocationThread extends Thread { + MobyContentInstance data; + MobyService mservice; + MobyRequest mobyRequest; + MobyRequestEventHandler handler; + int requestId; + + InvocationThread( MobyRequest mr, MobyContentInstance inData, MobyRequestEventHandler h, int id ) { + data = inData; + mobyRequest = mr; + mservice = mobyRequest.getService(); + handler = h; + requestId = id; + + // Name the thread after the service being run, mostly for ease of debugging + setName( mservice.getName() + requestId ); + } + + public void run() { + MobyRequestEvent requestEvent = new MobyRequestEvent( data, mobyRequest, mservice, null, requestId ); + // Tell the handler we're starting the request, with the given data + handler.start( requestEvent ); + + MobyRequestEvent responseEvent = null; + MobyContentInstance content = null; + StringBuffer contentsXML = new StringBuffer(); // to be filled in by the RPC call below + try { + content = mobyRequest.invokeService( data, contentsXML, handler, requestId ); // RPC call... + } + catch ( Exception e ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, e, requestId ); + } + catch ( Error err ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, err, requestId ); + } + if ( responseEvent == null ) { + responseEvent = new MobyRequestEvent( content, mobyRequest, mservice, null, requestId ); + } + // We've got the raw XML laying around, so why not provide it unmolested to the callback? + responseEvent.setContentsXML( contentsXML.toString() ); + handler.processEvent( responseEvent ); + handler.stop( mobyRequest, requestId ); + } + } + + public void addEventHandler(MobyRequestEventHandler h) { + eventHandlers.add( h ); + } + + public void removeEventHandler(MobyRequestEventHandler h) { + eventHandlers.remove( h ); + } + + public void sendResponse(MobyRequestEvent mre) { + // Not yet implemented, need to conform to some web.xml specification here... + } + + /** + * This method retrieves from Moby Central a copy of the WSDL document for the service (or uses an internally cached + * copy from a previous invocation), and sets the variables for the SOAP call appropriately so you can consequently + * call performSOAPRequest. + */ + protected Call getServiceFromWSDL() throws MobyException, NoSuccessException { + // String wsdl = null; + + // // Since this is how we retrieve a service from Central, use the same values as the key to the hash + // String wsdlCacheKey = mobyService.getName() + "@" + mobyService.getAuthority(); + + // // This is the same call as last time, so we don't need to change the setup + // if(wsdlCacheKey.equals(lastWsdlCacheKey)){ + // return setCallFromWSDL((String) wsdlCache.get(wsdlCacheKey)); + // } + // // We haven't encountered this service yet + // else if(!wsdlCache.containsKey(wsdlCacheKey)){ + // wsdl = mobyCentral.getServiceWSDL(mobyService.getName(), mobyService.getAuthority()); + // wsdlCache.put(wsdlCacheKey, wsdl); + // } + // // We've dealt with this one before + // else{ + // wsdl = (String) wsdlCache.get(wsdlCacheKey); + // } + + // lastWsdlCacheKey = wsdlCacheKey; // Keep track of the last invocation + + // Get ready to do SOAP + return setCallFromWSDL( null ); + } + + /** + * Creates the SOAP Call that will be invoked later. This should be based on the WSDL document and parameter + * information from the MobyService, but these are currently not up to snuff. + */ + protected Call setCallFromWSDL(String wsdl) throws MobyException, SOAPException { + if ( service == null ) { + service = new org.apache.axis.client.Service(); // AXIS SPECIFIC This acts as a factory for Calls + } + + Call soapCall; + try { + soapCall = ( Call ) service.createCall();// create a fresh Call each time + } + catch ( javax.xml.rpc.ServiceException se ) { + throw new SOAPException( "Could not instatiate call to SOAP Service: " + se ); + } + + // Should initialize endpoint, etc. This call is AXIS SPECIFIC, otherwise you'll + // have to do the call's info setting manually. + // ((org.apache.axis.client.Call) soapCall).setSOAPService(soapService); + soapCall.removeAllParameters(); + soapCall.setTargetEndpointAddress( mobyService.getURL() ); + soapCall.setPortName( new QName( "http://biomoby.org/", mobyService.getName() + "PortType" ) ); + // soapCall.setOperationName(new QName("http://biomoby.org/", + // mobyService.getName())); + soapCall.setSOAPActionURI( "http://biomoby.org/#" + mobyService.getName() ); + return soapCall; + } + + /** + * Calls the invoke() method of the JAX-RPC Call interface. + */ + protected Element performSOAPRequest(Call soapCall, String mobyInputXML, StringBuffer contentsXMLOutput) + throws SOAPException { + // First, turn the input objects into a MOBY XML request + String[] mobyXMLInputData = new String[ 1 ]; + + // Setup + mobyXMLInputData[ 0 ] = mobyInputXML; + + if ( debug ) + debugPS.println( "returnType just before invoke call is " + soapCall.getReturnType() ); + Object returnedObject = null; + try { + returnedObject = soapCall.invoke( new QName( "http://biomoby.org/", mobyService.getName() ), + mobyXMLInputData ); + } + catch ( Exception e ) { + e.printStackTrace(); + // System.err.println("Input: "+mobyInputXML); + throw new SOAPException( "While invoking SOAP Call: " + e ); + } + + try { + if ( debug ) { + debugPS.println( "SOAP Response was:\n" ); + debugPS.println( soapCall.getResponseMessage().getSOAPPart().getEnvelope() ); + } + Element resultDom = ( ( MessageElement ) soapCall.getResponseMessage().getSOAPPart().getEnvelope() ).getAsDOM(); + return decodeSOAPMessage( resultDom, contentsXMLOutput, mobyInputXML ); + } + catch ( Exception e ) { + e.printStackTrace(); + throw new SOAPException( "Could not get SOAP response as DOM Element: " + e ); + } + + } + + public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML) throws SOAPException, + MobyException { + return decodeSOAPMessage( n, contentsXMLOutput, inputXML, false ); + } + + /** + * Isolates the MOBY Data from the SOAP message returned by the remote service host. + * + * @throws SOAPException if the MOBY payload cannot be found in the SOAP message + * @throws MobyException if the MOBY message is not well-formed XML + * + * @return The root element of the MOBY response DOM + */ + public Element decodeSOAPMessage(Element n, StringBuffer contentsXMLOutput, String inputXML, boolean async) + throws SOAPException, MobyException { + if ( n == null ) { + throw new SOAPException( "SOAP Message given to decode is null" ); + } + + NodeList node_list = null; + XPath responseElementXPath = null; + try { + if ( async ) { + responseElementXPath = new XPath( "//" + MobyPrefixResolver.WSRP_PREFIX + ":" + + AsyncClient.WSRP_MULTI_PROPERTY_TAG_NAME + "Response", null, mobyPrefixResolver, XPath.SELECT ); + } + else { + responseElementXPath = new XPath( "//" + MobyPrefixResolver.MOBY_TRANSPORT_PREFIX + ":" + + mobyService.getName() + "Response | //" + mobyService.getName() + "Response | " + "//" + + MobyPrefixResolver.MOBY_TRANSPORT_PREFIX + ":" + mobyService.getName() + " | //" + + mobyService.getName(), null, mobyPrefixResolver, XPath.SELECT ); + } + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select SOAP nodes due to exception " + + "while compiling XPath statement (code bug?):" + te ); + } + try { + node_list = runXPath( responseElementXPath, n ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select SOAP nodes due to exception " + "while executing XPath statement:" + + te ); + } + + if ( node_list == null || node_list.getLength() == 0 ) { + throw new SOAPException( "Could not find a response element in SOAP payload (service " + + mobyService.getName() + ")" ); + } + + if ( node_list.getLength() > 1 ) { + throw new SOAPException( "Found more than one response element in SOAP payload, " + + "unable to resolve ambiguity of the payload (service provider error?)" ); + } + + Node[] responseNodes = null; + if ( async ) { + Vector< Node > nodes = new Vector< Node >(); + NodeList resultNodeList = node_list.item( 0 ).getChildNodes(); + for ( int i = 0; resultNodeList != null && i < resultNodeList.getLength(); i++ ) { + if ( ! ( resultNodeList.item( i ) instanceof Element ) ) { + continue; + } + Element resultElement = ( Element ) resultNodeList.item( i ); + if ( resultElement.getLocalName().startsWith( AsyncClient.MOBY_RESULT_PROPERTY_PREFIX ) ) { + nodes.add( resultElement ); + } + } + responseNodes = nodes.toArray( new Node[ nodes.size() ] ); + } + else { + responseNodes = new Node[]{node_list.item( 0 )}; + } + + Element domRoot = null; // Where the result will be put + + for ( Node responseNode : responseNodes ) { + // Find base64 encoded elements in the SOAP message using XPath and + // replace them with the real decoded contents + node_list = null; + try { + node_list = runXPath( base64EncodedXPath, responseNode ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select base64 encoded SOAP nodes due to exception " + + "while executing XPath statement:" + te ); + } + if ( debug && node_list != null ) { + debugPS.println( "There were " + node_list.getLength() + " base64 encoded elements in the data" ); + } + + // Do decoding for each base64 part found + for ( int i = 0; node_list != null && i < node_list.getLength(); i++ ) { + org.w3c.dom.Node change = node_list.item( i ); + /* Make sure the text data is all put into one contiguous piece for decoding */ + change.normalize(); + + byte[] decodedBytes = org.apache.axis.encoding.Base64.decode( change.getFirstChild().getNodeValue() ); + String newText = new String( decodedBytes ); + if ( debug ) { + debugPS.println( "New decoded text is" + newText ); + } + + // Swap out this node for the decoded data + change.getParentNode().replaceChild( n.getOwnerDocument().createTextNode( new String( decodedBytes ) ), + change ); + } + + // Now see if there are any strings that need decoding + node_list = null; + try { + node_list = runXPath( stringEncodedXPath, responseNode ); + } + catch ( TransformerException te ) { + throw new SOAPException( "Cannot select string encoded SOAP nodes due to exception " + + "while executing XPath statement:" + te ); + } + + // Do concatenation for each plain string part found + for ( int i = 0; node_list != null && i < node_list.getLength(); i++ ) { + org.w3c.dom.Node change = node_list.item( i ); + /* Make sure the text data is all put into one contiguous piece for decoding */ + change.normalize(); + String plainString = ""; + int j = 0; + for ( NodeList children = change.getChildNodes(); children != null && j < children.getLength(); j++ ) { + Node child = children.item( j ); + if ( child instanceof CDATASection || child instanceof Text ) { + plainString += child.getNodeValue(); + if ( debug ) { + debugPS.println( "Plain string is now " + plainString ); + } + } + } + + // Swap out this node for the decoded data + change.getParentNode().replaceChild( n.getOwnerDocument().createCDATASection( plainString ), change ); + } + if ( debug && node_list != null ) { + debugPS.println( "There were " + node_list.getLength() + + " XML Schema string encoded elements in the data" ); + } + + // Parse the MOBY XML document payload + responseNode.normalize(); + NodeList children = responseNode.getChildNodes(); + if ( children == null ) { + throw new MobyException( "The MOBY payload has no contents at all" ); + } + if ( children.getLength() != 1 ) { + if ( debug ) { + debugPS.println( "Warning: MOBY Payload appears to have more than " + + "just text in it, skipping the non-text sections" ); + } + } + + Element predefinedDOM = null; // Choice of ripping DOM Element for moby payload out of SOAP DOM + String localResponseString = ""; // or storing raw XML strings, to be converted to a DOM later + for ( int j = 0; j < children.getLength(); j++ ) { + Node child = children.item( j ); + if ( child instanceof CDATASection || child instanceof Text ) { + // Unescape XML special characters in the string, so we can later on + // parse the payload as regular XML. + // Ignore whitespace-only node + if ( child.getNodeValue().matches( "^\\s+$" ) ) { + continue; + } + if ( debug ) { + debugPS.println( "Concatenating text in response " + child.getNodeValue() ); + } + localResponseString += child.getNodeValue();// .replaceAll("<", "<").replaceAll(">", + // ">").replaceAll("(&|F)", "&"); + } + if ( child instanceof Element && child.getLocalName().equals( MobyTags.MOBY ) ) { + debugPS.println( "Warning: The MOBY contents was found as raw XML inside the SOAP response!\n" + + "This is illegal according to the MOBY-API, please inform the service\n " + + " provider, as parsing such text may not be supported in the future" ); + localResponseString = null; + // Store the moby payload root element's DOM represntation, so we don't + // have to serialize it to the localResponseString and then parse it out + // again (that would be wasteful). + predefinedDOM = ( Element ) child; + break; + } + } + + if ( localResponseString != null ) { + if ( localResponseString.length() == 0 ) { + throw new MobyException( "The MOBY payload has no text contents at all" ); + } + if ( Character.isWhitespace( localResponseString.charAt( 0 ) ) ) { + localResponseString = localResponseString.trim(); + } + } + + // Check if the payload is an XML document. If not, try a last ditch effort + // by base64 decoding the contents. This is technically not allowable in the + // MOBY spec, but we are being lenient. + if ( localResponseString != null && !localResponseString.startsWith( "\n" + localResponseString; + debugPS.println( "Warning: The MOBY contents was missing an XML declaration, but it is " + + "required by the MOBY API, and may stop working in the future without it. Please " + + "contact the client's provider to correct this." ); + } + else { + String oldResponse = localResponseString; + localResponseString = new String( org.apache.axis.encoding.Base64.decode( localResponseString ) ); + if ( !localResponseString.startsWith( " entry : data.entrySet() ) { + String queryName = entry.getKey(); + MobyDataJob query = entry.getValue(); + + // Additionally, we check if they are MobyDataInstances below + Map< String, MobyPrimaryData > primaryParams = new HashMap< String, MobyPrimaryData >(); + Map< String, MobySecondaryData > secondaryParams = new HashMap< String, MobySecondaryData >(); + + // To store the primary input parameter name as given by the user, + // in case we need it later on for parameter renaming... + String primaryParamName = null; + + for ( Map.Entry< String, MobyDataInstance > subentry : query.entrySet() ) { + String name = subentry.getKey(); + MobyDataInstance param = subentry.getValue(); + if ( param == null ) { + throw new MobyException( "Query " + queryName + " contained a null input parameter (" + name + ")" ); + } + else if ( param instanceof MobyPrimaryData ) { + primaryParams.put( name, ( MobyPrimaryData ) param ); + primaryParamName = name; + } + else if ( param instanceof MobySecondaryData ) { + secondaryParams.put( name, ( MobySecondaryData ) param ); + } + else { + System.err.println( "Input parameter " + name + " (query " + queryName + + ") was not a MobyPrimaryData or MobySecondaryData " + + "as expected, but rather was of class " + param.getClass().getName() ); + } + } + + if ( inputs != null && inputs.length != primaryParams.size() ) { + throw new MobyException( "Service " + mobyService.getName() + " was provided " + primaryParams.size() + + " primary input parameter(s), but takes " + inputs.length + " (query " + queryName + ")" ); + } + if ( secondaries != null ) { + // If no secondaries provided, fill them in by default + if ( secondaries.length != 0 ) { + for ( MobySecondaryData secondary : secondaries ) { + if ( !secondaryParams.containsKey( secondary.getName() ) ) { + if ( debug ) { + System.err.println( "Setting default secondary param value for missing param " + + secondary ); + } + query.put( secondary.getName(), new MobyDataSecondaryInstance( secondary ) ); + } + } + } + if ( secondaries.length != secondaryParams.size() ) { + throw new MobyException( "Service " + mobyService.getName() + " was provided " + + secondaryParams.size() + " secondary input parameter(s), but takes " + secondaries.length + + " (query " + queryName + "). Extra secondary" + " parameters must have been specified" ); + } + } + + // If there was one anonymous input, assign the name automatically in + // the case the service requires it to be named. This is the only + // unambiguous case in which we can do this. + if ( inputs.length == 1 ) { + String serviceParamName = inputs[ 0 ].getName(); // name as req'd by the service + + // name isn't the same as required currently + if ( serviceParamName != null && serviceParamName.length() > 0 + && !serviceParamName.equals( primaryParamName ) ) { + // take out the old parameter + MobyPrimaryData theInputToRename = ( MobyPrimaryData ) query.remove( primaryParamName ); + + // Add in the same parameter, but with the appropriate name + query.put( serviceParamName, ( MobyDataInstance ) theInputToRename ); + } + } + } + + ByteArrayOutputStream mobyRequest = new ByteArrayOutputStream(); + try { + MobyDataUtils.toXMLDocument( mobyRequest, data ); + } + catch ( MobyException me ) { + throw me; + } + catch ( Exception e ) { + e.printStackTrace(); + throw new MobyException( "Could not create MOBY payload XML from input data: " + e ); + } + + if ( debug ) { + debugPS.println( "Input to MOBY Service is:" ); + debugPS.print( mobyRequest.toString() ); + } + + return mobyRequest.toString(); + } + + /** + * A method that sets up the execution environment for and runs a compiled XPath statement against a DOM node You + * should call releaseXPath when you're done with the results + * + * @return the list of Nodes that satisfy the XPath in this Node's context + */ + protected NodeList runXPath(XPath xpath, Node n) throws TransformerException { + NodeList result = null; + int dtm_node_handle = xpath_context.getDTMHandleFromNode( n ); + PrefixResolver node_prefix_resolver = new PrefixResolverDefault( n ); + XObject xobject = xpath.execute( xpath_context, n, node_prefix_resolver ); + if ( xobject instanceof XNodeSet ) { + result = ( ( XNodeSet ) xobject ).nodelist(); + } + else if ( debug && xobject != null ) { + debugPS.println( "Output of XPath was not a XNodeSet as expected, found " + xobject.getClass().getName() ); + debugPS.flush(); + } + return result; + } + + protected void releaseXPath(Node n) { + xpath_context.release( xpath_context.getDTM( xpath_context.getDTMHandleFromNode( n ) ), false ); + } +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java,v retrieving revision 1.57 retrieving revision 1.58 diff -u -r1.57 -r1.58 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java 2008/10/30 02:33:25 1.57 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/CentralImpl.java 2008/11/26 08:53:43 1.58 @@ -1,2139 +1,1957 @@ -// CentralImpl.java -// A default client to the Moby Central service. -// -// senger at ebi.ac.uk -// February 2003 -// - -package org.biomoby.client; - -import org.biomoby.registry.meta.Registry; -import org.biomoby.shared.Central; -import org.biomoby.shared.MobyData; -import org.biomoby.shared.MobyDataType; -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyNamespace; -import org.biomoby.shared.MobyPrimaryDataSet; -import org.biomoby.shared.MobyPrimaryDataSimple; -import org.biomoby.shared.MobyRelationship; -import org.biomoby.shared.MobySecondaryData; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.MobyServiceType; -import org.biomoby.shared.NoSuccessException; -import org.biomoby.shared.PendingCurationException; -import org.biomoby.shared.MobyResourceRef; -import org.biomoby.shared.Utils; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.namespace.QName; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.apache.axis.AxisFault; -import org.apache.axis.client.Call; -import org.apache.axis.client.Service; -import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.HeadMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.PrintStream; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Vector; -import java.util.TreeMap; -import java.util.Comparator; -import java.util.zip.GZIPInputStream; -import java.util.logging.*; - -/** - * A default implementation of the - * interface {@link org.biomoby.shared.Central Central} - * allowing access to a Moby registry. - *

    - * This class is supposed to be used by all other clients that wish - * to communicate with the Moby Registry, but do not want to know - * about all XML details that are necessary for talking with the Moby Central - * directly. This is an example of a client program: - *

    - * import org.biomoby.shared.Central;
    - * import org.biomoby.shared.MobyException;
    - * import org.biomoby.client.CentralImpl;
    - * import java.util.Map;
    - * import java.util.Iterator;
    - *
    - * public class Test {
    - *
    - *    public static void main (String[] args)
    - *       throws MobyException {
    - *
    - *       Central worker = new CentralImpl();
    - *       Map authorities = worker.getServiceNamesByAuthority();
    - *
    - *       for (Iterator it = authorities.entrySet().iterator(); it.hasNext(); ) {
    - *          Map.Entry entry = (Map.Entry)it.next();
    - *          System.out.println (entry.getKey());
    - *          String[] names = (String[])entry.getValue();
    - *          for (int i = 0; i < names.length; i++)
    - *             System.out.println ("\t" + names[i]);
    - *       }
    - *    }
    - * }
    - *
    - * - * @author Martin Senger - * @version $Id$ - */ - -public class CentralImpl - implements Central, SimpleCache { - - private URL endpoint; - private String uri; - protected boolean debug = false; - - /** Common central used to if getDefaultCentral() is called */ - protected static Map defaultCentrals = new HashMap(); - - /** Default location (endpoint) of a Moby registry. */ - public static final String DEFAULT_ENDPOINT = "http://moby.ucalgary.ca/moby/MOBY-Central.pl"; - - /** Default namespace used by the contacted Moby registry. */ - public static final String DEFAULT_NAMESPACE = "http://moby.ucalgary.ca/MOBY/Central"; - - /** - * The META-INF resource file that will be checked to determine what - * default class should be instantiated in order to create a Central Implementation - * when getDefaultCentral() is called. - */ - public static final String CENTRAL_IMPL_RESOURCE_NAME = "org.biomoby.shared.CentralDefaultImpl"; - /** The class to use for getDefaultCentral if all else fails */ - public static final String DEFAULT_CENTRAL_IMPL_CLASSNAME = "org.biomoby.client.CentralDigestCachedImpl"; - private static Logger logger = Logger.getLogger("org.biomoby.client.CentralImpl"); - - /** - * Thread local that gives each thread its own - * DocumentBuilderFactory (since it is not thread-safe). Code taken - * from Apache's JaxpUtils. - */ - public static ThreadLocal DOCUMENT_BUILDER_FACTORIES = new ThreadLocal() { - protected synchronized Object initialValue() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware (true); - return dbf; - } - }; - - - /************************************************************************* - * Default constructor. It connects to a default Moby registry - * (as defined in {@link #DEFAULT_ENDPOINT}) using a default namespace - * (as defined int {@link #DEFAULT_NAMESPACE}). - *************************************************************************/ - public CentralImpl() - throws MobyException { - this (DEFAULT_ENDPOINT, DEFAULT_NAMESPACE); - } - - /************************************************************************* - * Constructor allowing to specify which Moby Registry to use. - * - * @throws MobyException if 'endpoint' is not a valid URL, or if no - * DOM parser is available - *************************************************************************/ - public CentralImpl (String endpoint) - throws MobyException { - this (endpoint, DEFAULT_NAMESPACE); - } - - /************************************************************************* - * Constructor allowing to specify which Moby Registry and what - * namespace to use. If any of the parameters is null, its default - * value is used instead. - *

    - * @throws MobyException if 'endpoint' is not a valid URL, or if no - * DOM parser was found - *************************************************************************/ - public CentralImpl (String endpoint, String namespace) - throws MobyException { - - if (endpoint == null || "".equals (endpoint.trim())) - endpoint = DEFAULT_ENDPOINT; - if (namespace == null || "".equals (namespace.trim())) - namespace = DEFAULT_NAMESPACE; - - try { - this.endpoint = new URL (endpoint); - } catch (MalformedURLException e) { - throw new MobyException ("Bad URL: " + endpoint); - } - this.uri = namespace; - - cache = new Hashtable(); - useCache = true; - } - - /************************************************************************* - * Loads a DOM Document from an InputStream. Uses thread-safe - * mechanism. - *************************************************************************/ - public static Document loadDocument (InputStream input) - throws MobyException { - try { - DocumentBuilderFactory dbf - = (DocumentBuilderFactory)DOCUMENT_BUILDER_FACTORIES.get(); - DocumentBuilder db = dbf.newDocumentBuilder(); - return (db.parse (input)); - } catch (Exception e) { - throw new MobyException ("Problem with reading XML input: " + e.toString(), e); - } - } - - /************************************************************************* - * Call 'method' with 'parameters' and return its result. - *************************************************************************/ - protected Object doCall (String method, Object[] parameters) - throws MobyException { - - Call call = null; - try { - Service service = new Service(); - call = (Call) service.createCall(); - call.setTargetEndpointAddress (endpoint); - call.setTimeout (new Integer (0)); - - call.setSOAPActionURI (uri + "#" + method); - - if (debug) { - System.err.println ("METHOD CALL: " + method); - System.err.println ("------------"); - if (parameters.length > 0) - System.err.println (parameters[0] + "\n"); - System.err.println ("------------\n"); - - Object result = call.invoke (uri, method, parameters); - - System.err.println ("METHOD RETURN:"); - System.err.println ("------------"); - if (result != null) - System.err.println (result + "\n"); - System.err.println ("------------\n"); - - return resultToString (result); - - } else { - return resultToString (call.invoke (uri, method, parameters)); - } - - } catch (AxisFault e) { - throw new MobyException - (formatFault (e, - endpoint.toString(), - (call == null ? null : call.getOperationName())), - e); -// (endpoint.toString()+(call == null ? "" : call.getOperationName()), e); - - } catch (Exception e) { - throw new MobyException (e.toString(), e); -// e.printStackTrace(); - } - } - - - /************************************************************************** - * Parse the given XML sniplet to find tag 'success'. If it has value '1' - * look further for tag 'id' and return it back (or return an empty string - * if ID is not there). Otherwise raise an exception with the 'culprit' - * and with the message from the tag 'message'.

    - * - * The return value is a two-element long array. The first element - * is the ID (given by BioMobe registry), and the second element - * is RDF corresponding with the registered object (BioMoby - * returns this only for service instances, so for other objects - * this will be null).

    - * - * This is how the XML is supposed to look: - * - * - * - * - * - * - * - * Success takes the value "1" to indicate success, "0" to - * indicate failure, and "-1" to indicate "Pending Curation". - *************************************************************************/ - protected String[] checkRegistration (String xml, Object culprit) - throws MobyException, NoSuccessException, PendingCurationException { - - String id = "", success = "0", message = "", rdf = ""; - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (xml.getBytes())); - Element root = document.getDocumentElement(); - - NodeList children = root.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - if (children.item (i).getNodeType() != Node.ELEMENT_NODE) - continue; - Element elem = (Element)children.item (i); - if (elem.getNodeName().equals ("id")) { - if (elem.getFirstChild() != null) - id = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals("success")) { - if (elem.getFirstChild() != null) - success = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals ("message")) { - if (elem.getFirstChild() != null) - message = elem.getFirstChild().getNodeValue(); - } else if (elem.getNodeName().equals ("RDF")) { - if (elem.getFirstChild() != null) - rdf = elem.getFirstChild().getNodeValue(); - } - } - - if (success.equals ("0")) - throw new NoSuccessException (message, culprit); - else if (success.equals ("-1")) - throw new PendingCurationException(); - return new String[] { id, rdf }; - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing input - * data types and their usage in the given service. Only data considered - * primary are included. Note that the main job of converting to XML is - * done by instances of MobyPrimaryData. - * - * The returned XML looks like this: - * - * - * - *************************************************************************/ - protected String buildPrimaryInputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] primaryInputs = service.getPrimaryInputs(); - buf.append ("\n"); - for (int i = 0; i < primaryInputs.length; i++) - buf.append (primaryInputs[i].toXML()); - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing input - * data types and their usage in the given service. Only data considered - * secondary are included. Note that the main job of converting to XML is - * done by instances of MobySecondaryData. - * - * The returned XML looks like this: - * - * - * - *************************************************************************/ - protected String buildSecondaryInputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] secInputs = service.getSecondaryInputs(); - buf.append ("\n"); - for (int i = 0; i < secInputs.length; i++) { - buf.append (secInputs[i].toXML()); - } - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML created from the definitions representing output - * data types and their usage in the given service. Only data considered - * primary are included. Note that the main job of converting to XML is - * done by instances of MobyPrimaryData. - * - * The returned XML looks like this: - * - * - * - * - *************************************************************************/ - protected String buildOutputTag (MobyService service) { - StringBuffer buf = new StringBuffer(); - MobyData[] primaryOutputs = service.getPrimaryOutputs(); - buf.append ("\n"); - for (int i = 0; i < primaryOutputs.length; i++) - buf.append (primaryOutputs[i].toXML()); - buf.append ("\n"); - return new String (buf); - } - - /************************************************************************** - * Return a piece of XML represented a query object (an object used - * to find a service). - * - * The returned XML looks like this: - * - * - * - * - * - * - * - * - * - * - * - * ServiceTypeTerm - * ServiceName - * moby - * http://desired.service.provider; - * 1|0 - * 1|0 - * 1|0 - * - * something - * .... - * .... - * - *************************************************************************/ - protected String buildQueryObject (MobyService service, - String[] keywords, - boolean expandObjects, - boolean expandServices, - boolean authoritative) { - if (service == null) { - service = new MobyService ("dummy"); - service.setCategory (""); - } - StringBuffer buf = new StringBuffer(); - - buf.append ("\n\n"); - MobyData[] pi = service.getPrimaryInputs(); - if (pi.length > 0) { - for (int i = 0; i < pi.length; i++) - buf.append (pi[i].toXML()); - } - buf.append ("\n\n"); - - buf.append ("\n\n"); - MobyData[] po = service.getPrimaryOutputs(); - if (po.length > 0) { - for (int i = 0; i < po.length; i++) - buf.append (po[i].toXML()); - } - buf.append ("\n\n"); - - buf.append ("" + service.getType() + "\n"); - - String name = service.getName(); - if (!name.equals ("") && !name.equals ("dummy") && !name.equals (MobyService.DUMMY_NAME)) - buf.append ("" + service.getName() + "\n"); - - String sigURL = service.getSignatureURL(); - if (!sigURL.equals ("")) - buf.append ("" + sigURL + "\n"); - - buf.append ("" + service.getCategory() + "\n"); - buf.append ("" + service.getAuthority() + "\n"); - - buf.append (""); - buf.append (expandObjects ? "1" : "0"); - buf.append ("\n"); - - buf.append (""); - buf.append (expandServices ? "1" : "0"); - buf.append ("\n"); - - buf.append (""); - buf.append (authoritative ? "1" : "0"); - buf.append ("\n"); - - buf.append ("\n"); - if (keywords != null && keywords.length > 0) { - for (int i = 0; i < keywords.length; i++) { - buf.append (""); - buf.append (keywords[i]); - buf.append ("\n"); - } - } - buf.append ("\n"); - - return new String (buf); - } - - /************************************************************************** - * Extract one or more MobyService objects from the given XML piece. - * The XML should look like this: - *

    -     *  <Services>
    -     *    <Service authURI="authority.URI.here" lsid="..." serviceName="MyService">
    -     *      <serviceType>Service_Ontology_Term</serviceType>
    -     *      <Category>moby</Category> <!-- or 'cgi' or 'soap' -->
    -     *      <contactEmail>your at email.addy.here</contactEmail>
    -     *      <signatureURL>http://service.RDF.here</signatureURL>
    -     *      <URL>http://service.endpoint.here/scriptname</URL>
    -     *      <authoritative>1</authoritative>
    -     *      <Input>
    -     *           <!-- one or more Simple and/or Complex Primary articles -->
    -     *      </Input>
    -     *      <Output>
    -     *           <!-- one or more Simple and/or Complex Primary articles --> 
    -     *      </Output>
    -     *      <secondaryArticles>
    -     *           <!-- one or more Secondary articles -->
    -     *      </secondaryArticles>
    -     *      <Description><![CDATA[free text description here]]></Description>
    -     *    </Service>
    -     *    ...  <!--  one or more Service blocks may be returned -->
    -     *    ...
    -     *    ...
    -     *  </Services>
    -     * 
    - * @throws MobyException if the XML document is invalid - *************************************************************************/ - public MobyService[] extractServices (String xml) - throws MobyException { - - Document document = loadDocument (new ByteArrayInputStream (xml.getBytes())); - NodeList list = document.getElementsByTagName ("Service"); - MobyService[] results = new MobyService [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyService service = new MobyService (elem.getAttribute ("serviceName")); - service.setAuthority (elem.getAttribute ("authURI")); - service.setLSID (elem.getAttribute ("lsid")); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("Description")) { - service.setDescription (getFirstValue (children.item (j))); - } else if (nodeName.equals ("Category")) { - service.setCategory (getFirstValue (children.item (j))); - } else if (nodeName.equals ("URL")) { - service.setURL (getFirstValue (children.item (j))); - } else if (nodeName.equals ("signatureURL")) { - service.setSignatureURL (getFirstValue (children.item (j))); - } else if (nodeName.equals ("contactEmail")) { - service.setEmailContact (getFirstValue (children.item (j))); - } else if (nodeName.equals ("serviceType")) { - service.setType (getFirstValue (children.item (j))); - MobyServiceType mst = new MobyServiceType(service.getType()); - NamedNodeMap map = (children.item (j).getAttributes()); - if (map != null) { - Node node = map.getNamedItemNS(children.item(j).getNamespaceURI(),"lsid"); - if (node != null) - mst.setLSID(node.getNodeValue()); - } - service.setServiceType(mst); - } else if (nodeName.equals ("authoritative")) { - String authoritative = getFirstValue (children.item (j)); - service.setAuthoritative (authoritative.equals ("1") ? true : false); - } else if (nodeName.equals ("Input")) { - // - // - // - // ... - // - // - // ...... - // ...... - // - // - NodeList inputs = children.item (j).getChildNodes(); - for (int k = 0; k < inputs.getLength(); k++) { - if (inputs.item (k).getNodeName().equals ("Simple")) { - MobyPrimaryDataSimple data = new MobyPrimaryDataSimple ((Element)inputs.item (k)); - service.addInput (data); - } else if (inputs.item (k).getNodeName().equals ("Collection")) { - MobyPrimaryDataSet data = new MobyPrimaryDataSet ((Element)inputs.item (k)); - service.addInput (data); - } - } - } else if (nodeName.equals ("Output")) { - // - // - // - NodeList inputs = children.item (j).getChildNodes(); - for (int k = 0; k < inputs.getLength(); k++) { - if (inputs.item (k).getNodeName().equals ("Simple")) { - MobyPrimaryDataSimple data = new MobyPrimaryDataSimple ((Element)inputs.item (k)); - service.addOutput (data); - } else if (inputs.item (k).getNodeName().equals ("Collection")) { - MobyPrimaryDataSet data = new MobyPrimaryDataSet ((Element)inputs.item (k)); - service.addOutput (data); - } - } - - } else if (nodeName.equals ("secondaryArticles")) { - // - // ... - // - NodeList parameters = children.item (j).getChildNodes(); - for (int k = 0; k < parameters.getLength(); k++) { - if (parameters.item (k).getNodeName().equals ("Parameter")) { - MobySecondaryData data = new MobySecondaryData ((Element)parameters.item (k)); - service.addInput (data); - } - } - } - } - results [i] = service; - } - return results; - } - - // protect against null values - protected String getFirstValue (Node child) { - Node node = child.getFirstChild(); - if (node == null) return ""; - String value = node.getNodeValue(); - if (value == null) return ""; - return value; - } - - protected String getFirstValue (NodeList children) { - if (children.item(0) != null && children.item(0).hasChildNodes()) { - children.item(0).normalize(); - return getFirstValue (children.item(0)); - } - return ""; - } - - /************************************************************************** - * - * Implementing SimpleCache interface. - * - * Why to have an interface for such trivial thing? Well, because - * I needed to overwrite the caching mechanism in the subclasses - * so I needed to have all caching functions as separate methods - - * that's why I have collect them in an interface. - * - *************************************************************************/ - private Hashtable cache; // this is the cache itself - private boolean useCache; // this signal that we are actually caching things - - // not used here - public String createId (String rootName, - String semanticType, String syntaxType, - long lastModified, - Properties props) { - return ""; // not used here - } - - // check existence of a cached object - public boolean existsInCache (String id) { - synchronized (cache) { - if (useCache) return cache.containsKey (id); - else return false; - } - } - - // retrieve from cache - public Object getContents (String id) { - synchronized (cache) { - if (useCache) return cache.get (id); - else return null; - } - } - - // cache an object - public void setContents (String id, java.lang.Object data) { - synchronized (cache) { - if (useCache) cache.put (id, data); - } - } - - // in this implementation, it clears the whole cache, regardless - // what 'id' is passed - public void removeFromCache (String id) { - cache.clear(); - } - - /************************************************************************** - * - * And the other methods related to caching (but not part of the - * SimpleCache interface). - * - **************************************************************************/ - - /************************************************************************** - * By default, caching is enabled to reduce network traffic. - * Setting this to false will clear the cache, and not cache any - * further calls unless it is set to true again.

    - * - * @param shouldCache whether retrieveXXX call results should be - * cached in case they are called again (i.e. don't request - * MobyCentral every time) - **************************************************************************/ - public void setCacheMode (boolean shouldCache) { - useCache = shouldCache; - if (! useCache) - removeFromCache (null); - } - - /************************************************************************** - * Find if caching is currently enabled. - * - * @return true if caching is enabled - **************************************************************************/ - public boolean getCacheMode(){ - return useCache; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     * <serviceNames>
    -     *   <serviceName name="serviceName" authURI='authority.info.here'/>
    -     *   ...
    -     *   ...
    -     * </serviceNames>
    -     * 
    - * - * @deprecated Replaced by {@link - * #getServiceNamesByAuthority}. The reason is that this method - * returns a random result if there are more services with the - * same name but belonging to different authorities.

    - * - *************************************************************************/ - public Map getServiceNames() - throws MobyException { - - String result = (String)doCall ("retrieveServiceNames", - new Object[] {}); - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceName"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - results.put (elem.getAttribute ("name"), - elem.getAttribute ("authURI")); - } - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     * <serviceNames>
    -     *   <serviceName name="serviceName" lsid="..." authURI='authority.info.here'/>
    -     *   ...
    -     *   ...
    -     * </serviceNames>
    -     * 
    - * - * @return a Map which has authorities as keys, and String arrays - * with service names as a values. - *************************************************************************/ - public Map getServiceNamesByAuthority() - throws MobyException { - String result = getServiceNamesByAuthorityAsXML(); - return createServicesByAuthorityFromXML (result, true); - } - - /************************************************************************** - * Similar to {@link #getServiceNamesByAuthority} but the - * resulting Map contains slightly more.

    - * - * @return a Map which has authorities as keys, and arrays of - * MobyServices as a values. Each MobyService is filled with its - * name, authority and LSID. - *************************************************************************/ - public Map getServicesByAuthority() - throws MobyException { - String result = getServiceNamesByAuthorityAsXML(); - return createServicesByAuthorityFromXML (result, false); - } - - // - protected String getServiceNamesByAuthorityAsXML() - throws MobyException { - return (String)doCall ("retrieveServiceNames", - new Object[] {}); - } - - // if onlyNames == true - // Map: authority name -> String[] - // (filled with service namea) - // else - // Map: authority name -> MobyService[] - // (filled with service name, authority and lsid) - protected Map createServicesByAuthorityFromXML (String result, - boolean onlyNames) - throws MobyException { - - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceName"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String name = elem.getAttribute ("name"); - String auth = elem.getAttribute ("authURI"); - Vector v = - (results.containsKey (auth) ? (Vector)results.get (auth) : new Vector()); - if (onlyNames) { - v.addElement (name); - } else { - MobyService ms = new MobyService (name); - ms.setAuthority (auth); - ms.setLSID (elem.getAttribute ("lsid")); - v.addElement (ms); - } - results.put (auth, v); - } - - // change values of type Vector to MobyService[] or String[] - for (Iterator it = results.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = (Map.Entry)it.next(); - Vector v = (Vector)entry.getValue(); - if (onlyNames) { - String[] sNames = new String [v.size()]; - v.copyInto (sNames); - entry.setValue (sNames); - } else { - MobyService[] mss = new MobyService [v.size()]; - v.copyInto (mss); - entry.setValue (mss); - } - } - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <serviceProviders>
    -     *     <serviceProvider name="authority.URI.here"/>
    -     *          ...
    -     *          ...
    -     *  </serviceProviders>
    -     * 
    - *************************************************************************/ - public String[] getProviders() - throws MobyException { - - String cacheId = "retrieveServiceProviders"; - String[] cachedResults = (String[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = (String)doCall ("retrieveServiceProviders", - new Object[] {}); - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceProvider"); - String[] results = new String [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) - results[i] = ((Element)list.item (i)).getAttribute ("name"); - - // Add this data to the cache in case we get called again - setContents (cacheId, results); - - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <serviceTypes>
    -     *     <serviceType name="serviceName" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *            <contactEmail>...</contactEmail>
    -     *            <authURI>...</authURI>
    -     *     </serviceType>
    -     *          ...
    -     *          ...
    -     *  </serviceTypes>
    -     * 
    - *************************************************************************/ - public Map getServiceTypes() - throws MobyException { - String result = getServiceTypesAsXML(); - Map results = new TreeMap (getStringComparator()); - MobyServiceType[] types = createServiceTypesFromXML (result); - for (int i = 0; i < types.length; i++) { - results.put (types[i].getName(), - types[i].getDescription()); - } - return results; - } - - // - protected String getServiceTypesAsXML() - throws MobyException { - return (String)doCall ("retrieveServiceTypes", - new Object[] {}); - } - - // but be aware that the created MobyServiceTypes are not complete - // - they do not have the relationship information; that's why - // this method is not public; the full service types are available - // from CentralDigest implementations - protected MobyServiceType[] createServiceTypesFromXML (String result) - throws MobyException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("serviceType"); - if (list == null || list.getLength() == 0) - return new MobyServiceType[] {}; - MobyServiceType[] results = new MobyServiceType [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyServiceType st = new MobyServiceType (elem.getAttribute ("name")); - st.setLSID (elem.getAttribute ("lsid")); - st.setDescription (getFirstValue (elem.getElementsByTagName ("Description"))); - st.setEmailContact (getFirstValue (elem.getElementsByTagName ("contactEmail"))); - st.setAuthority (getFirstValue (elem.getElementsByTagName ("authURI"))); - results[i] = st; - } - java.util.Arrays.sort (results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *  <Namespaces>
    -     *     <Namespace name="namespace" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *            <contactEmail>...</contactEmail>
    -     *            <authURI>...</authURI>
    -     *     </Namespace>
    -     *          ...
    -     *          ...
    -     *  </Namespaces>
    -     * 
    - *************************************************************************/ - public MobyNamespace[] getFullNamespaces() - throws MobyException { - - String result = getNamespacesAsXML(); - return createNamespacesFromXML (result); - } - - // - protected String getNamespacesAsXML() - throws MobyException { - return (String)doCall ("retrieveNamespaces", - new Object[] {}); - } - - // - protected MobyNamespace[] createNamespacesFromXML (String result) - throws MobyException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getDocumentElement().getElementsByTagName ("Namespace"); - if (list == null || list.getLength() == 0) { - return new MobyNamespace[] {}; - } - MobyNamespace[] results = new MobyNamespace [list.getLength()]; - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - MobyNamespace nm = new MobyNamespace (elem.getAttribute ("name")); - nm.setLSID (elem.getAttribute ("lsid")); - nm.setDescription (getFirstValue (elem.getElementsByTagName ("Description"))); - nm.setEmailContact (getFirstValue (elem.getElementsByTagName ("contactEmail"))); - nm.setAuthority (getFirstValue (elem.getElementsByTagName ("authURI"))); - results[i] = nm; - } - - java.util.Arrays.sort (results); - return results; - } - - /************************************************************************** - * - * @deprecated Replaced by {@link #getFullNamespaces} that gives - * more information for the same price.

    - *************************************************************************/ - public Map getNamespaces() - throws MobyException { - - Map results = new TreeMap (getStringComparator()); - MobyNamespace[] namespaces = getFullNamespaces(); - for (int i = 0; i < namespaces.length; i++) { - results.put (namespaces[i].getName(), - namespaces[i].getDescription()); - } - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *

    -     *  <objectNames>
    -     *     <Object name="objectName" lsid="...">
    -     *            <Description><![CDATA[free text description here]]></Description>
    -     *     </Object>
    -     *          ...
    -     *          ...
    -     *  </objectNames>
    -     * 
    - *************************************************************************/ - public Map getDataTypeNames() - throws MobyException { - String result = getDataTypeNamesAsXML(); - return createDataTypeNamesFromXML (result, true); - } - - // - protected String getDataTypeNamesAsXML() - throws MobyException { - return (String)doCall ("retrieveObjectNames", - new Object[] {}); - } - - // if onlyNames == true - // Map: data type name -> description (String) - // else - // Map: data type name -> MobyDataType[] - // (filled with name, description, and lsid) - protected Map createDataTypeNamesFromXML (String result, - boolean onlyNames) - throws MobyException { - - // parse returned XML - Map results = new TreeMap (getStringComparator()); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Object"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String name = elem.getAttribute ("name"); - if (name == null) - continue; // ignore no-named data types - String desc = ""; - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("Description")) { - desc = getFirstValue (children.item (j)); - break; - } - } - if (onlyNames) { - results.put (name, desc); - } else { - MobyDataType dt = new MobyDataType (name); - dt.setDescription (desc); - dt.setLSID (elem.getAttribute ("lsid")); - results.put (name, dt); - } - } - return results; - } - - - /************************************************************************** - * Parses and imports the following XML. An example: - * - *
    -     * <retrieveObjectDefinition>
    -     *   <objectType lsid="...">go_term</objectType>
    -     *   <Description><![CDATA[A very lightweight object holding a GO term name and its definition]]></Description>
    -     *   <authURI>http://www.illuminae.com</authURI>
    -     *   <contactEmail>markw at illuminae.com</contactEmail>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *      <objectType articleName=''>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *   </Relationship>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    -     *      <objectType articleName='Term'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *      <objectType articleName='Definition'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *   </Relationship>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:has'>
    -     *      <objectType articleName='Problems'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *      <objectType articleName='Issues'>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *   </Relationship>
    -     * </retrieveObjectDefinition>
    -     * 
    - *************************************************************************/ - public MobyDataType getDataType (String dataTypeName) - throws MobyException, NoSuccessException { - - String result = getDataTypeAsXML (dataTypeName); - return createDataTypeFromXML (result, dataTypeName); - } - - public MobyDataType[] getDataTypes() - throws MobyException, NoSuccessException { - Map datatypeMap = getDataTypeNames(); - MobyDataType[] datatypes = new MobyDataType[datatypeMap.size()]; - int i = 0; - for(String dataTypeName: datatypeMap.keySet()){ - datatypes[i++] = getDataType(dataTypeName); - } - return datatypes; - } - - protected String getDataTypeAsXML (String dataTypeName) - throws MobyException, NoSuccessException { - - return (String)doCall ("retrieveObjectDefinition", - new Object[] { - "" + - "" + dataTypeName + "" + - "" - }); - } - - protected MobyDataType createDataTypeFromXML (String xmlSource, String dataTypeName) - throws MobyException, NoSuccessException { - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (xmlSource.getBytes())); - NodeList list = document.getElementsByTagName ("retrieveObjectDefinition"); - if (list == null || list.getLength() == 0) - throw new NoSuccessException ("Data Type name was not found.", - dataTypeName); - MobyDataType data = null; - Element elem = (Element)list.item (0); - NodeList children = elem.getChildNodes(); - - // first find the "real" (LSID-ized) data type name - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("objectType")) { - data = new MobyDataType (getFirstValue (children.item (j))); - data.setLSID ( ((Element)children.item (j) ).getAttribute ("lsid")); - break; - } - } - - // if not found (unprobable) use the name given by the caller - if (data == null) - data = new MobyDataType (dataTypeName); - - // now fill the data type object with the rest of attributes - for (int j = 0; j < children.getLength(); j++) { - String nodeName = children.item (j).getNodeName(); - if (nodeName.equals ("Description")) { - data.setDescription (getFirstValue (children.item (j))); - } else if (nodeName.equals ("authURI")) { - data.setAuthority (getFirstValue (children.item (j))); - } else if (nodeName.equals ("contactEmail")) { - data.setEmailContact (getFirstValue (children.item (j))); - } else if (nodeName.equals ("Relationship")) { - String relationshipType = ((Element)children.item (j)).getAttribute ("relationshipType"); - if (relationshipType.endsWith ("isa")) { - - NodeList parents = children.item (j).getChildNodes(); - for (int k = 0; k < parents.getLength(); k++) { - if (parents.item (k).getNodeName().equals ("objectType")) { - data.addParentName (getFirstValue (parents.item (k))); - } - } - } else if (relationshipType.endsWith ("hasa")) { - - NodeList belows = children.item (j).getChildNodes(); - for (int k = 0; k < belows.getLength(); k++) { - if (belows.item (k).getNodeName().equals ("objectType")) { - data.addChild ( ((Element)belows.item (k)).getAttribute ("articleName"), - getFirstValue (belows.item (k)), - Central.iHASA ); - } - } - } else if (relationshipType.endsWith ("has")) { - - NodeList belows = children.item (j).getChildNodes(); - for (int k = 0; k < belows.getLength(); k++) { - if (belows.item (k).getNodeName().equals ("objectType")) { - data.addChild ( ((Element)belows.item (k)).getAttribute ("articleName"), - belows.item (k).getFirstChild().getNodeValue(), - Central.iHAS ); - } - } - } - } - } - return data; - } - - /************************************************************************** - * - *************************************************************************/ - public String getServiceWSDL (String serviceName) - throws MobyException, NoSuccessException { - - Map names = getServiceNames(); - - for (Iterator it = names.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = (Map.Entry)it.next(); - if ( ((String)entry.getKey()).equals (serviceName) ) - return getServiceWSDL (serviceName, (String)entry.getValue()); - } - - throw new NoSuccessException ("Service not found.", serviceName); - } - - /************************************************************************** - * - *************************************************************************/ - public String getServiceWSDL (String serviceName, String authority) - throws MobyException, NoSuccessException { - - String cacheId = "getServiceWSDL" + serviceName + ":" + authority; - String cachedResults = (String)getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("retrieveService", - new Object[] { - "" + - "" + - "" - }); - - // parse returned XML - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - Element service = document.getDocumentElement(); - Node wsdl = service.getFirstChild(); - if (wsdl == null) - throw new NoSuccessException ("Service not found OR WSDL is not available.", - serviceName + " (" + authority + ")"); - - String results = wsdl.getNodeValue(); - setContents (cacheId, results); - return results; - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterDataTypeXML (MobyDataType dataType) { - - // build the ISA tag (expressing hierarchy of data types) - String[] names = dataType.getParentNames(); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < names.length; i++) { - buf.append (""); - buf.append (names[i]); - buf.append (""); - buf.append ("\n"); - } - - // build the HASA/HAS tags (expressing containments of data types) - MobyRelationship[] children = dataType.getChildren(); - StringBuffer buf2 = new StringBuffer(); // for HASA - StringBuffer buf3 = new StringBuffer(); // for HAS - for (int i = 0; i < children.length; i++) { - if (children[i].getRelationshipType() == Central.iHASA) { - buf2.append (""); - buf2.append (children[i].getDataTypeName()); - buf2.append (""); - } else if (children[i].getRelationshipType() == Central.iHAS) { - buf3.append (""); - buf3.append (children[i].getDataTypeName()); - buf3.append (""); - } - } - - return - "" + - "" + dataType.getName() + "" + - "" + - "" + - "" + new String (buf) + - "" + - "" + new String (buf2) + - "" + - "" + new String (buf3) + - "" + - "" + dataType.getAuthority() + "" + - "" + dataType.getEmailContact() + "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerDataType (MobyDataType dataType) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerObjectClass", - new Object[] { getRegisterDataTypeXML (dataType) }); - dataType.setId (checkRegistration (result, dataType)[0]); - } - - /************************************************************************* - * B - *************************************************************************/ - public void unregisterDataType (MobyDataType dataType) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterObjectClass", - new Object[] { - "" + - "" + dataType.getName() + "" + - "" - }); - checkRegistration (result, dataType); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterServiceTypeXML (MobyServiceType serviceType) { - - // build the ISA tag (expressing hierarchy of service types) - String[] names = serviceType.getParentNames(); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < names.length; i++) { - buf.append (""); - buf.append (names[i]); - buf.append (""); - buf.append ("\n"); - } - - return - "" + - "" + serviceType.getName() + "" + - "" + serviceType.getEmailContact() + "" + - "" + serviceType.getAuthority() + "" + - "" + - "" + - "" + new String (buf) + - "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerServiceType (MobyServiceType serviceType) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerServiceType", - new Object[] { getRegisterServiceTypeXML (serviceType) }); - serviceType.setId (checkRegistration (result, serviceType)[0]); - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterServiceType (MobyServiceType serviceType) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterServiceType", - new Object[] { - "" + - "" + serviceType.getName() + "" + - "" - }); - checkRegistration (result, serviceType); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterNamespaceXML (MobyNamespace namespace) { - return - "" + - "" + namespace.getName() + "" + - "" + namespace.getEmailContact() + "" + - "" + namespace.getAuthority() + "" + - "" + - "" + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerNamespace (MobyNamespace namespace) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("registerNamespace", - new Object[] { getRegisterNamespaceXML (namespace) }); - namespace.setId (checkRegistration (result, namespace)[0]); - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterNamespace (MobyNamespace namespace) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterNamespace", - new Object[] { - "" + - "" + namespace.getName() + "" + - "" - }); - checkRegistration (result, namespace); - } - - /************************************************************************* - * - *************************************************************************/ - public String getRegisterServiceXML (MobyService service) { - return - "" + - "" + service.getCategory() + "" + - "" + service.getName() + "" + - "" + service.getType() + "" + - "" + (service.getLSID() == null ? "" : service.getLSID().trim() )+ "" + - "" + service.getAuthority() + "" + - "" + escapeXML (service.getSignatureURL()) + "" + - "" + escapeXML (service.getURL()) + "" + - "" + service.getEmailContact() + "" + - "" + (service.isAuthoritative() ? "1" : "0") + "" + - "" + - "" + - buildPrimaryInputTag (service) + - buildSecondaryInputTag (service) + - buildOutputTag (service) + - ""; - } - - /************************************************************************* - * - *************************************************************************/ - public void registerService (MobyService service) - throws MobyException, NoSuccessException, PendingCurationException { - - String result = - (String)doCall ("registerService", - new Object[] { getRegisterServiceXML (service) }); - String[] registered = checkRegistration (result, service); - service.setId (registered [0]); - service.setRDF (registered [1]); - String pathToRDF = service.getPathToRDF(); - if ( ! pathToRDF.equals ("") ) { - File fileRDF = new File (pathToRDF); - try { - PrintStream fileout = new PrintStream (new FileOutputStream (fileRDF)); - fileout.println (registered [1]); - fileout.close(); - } catch (IOException e) { - StringBuffer buf = new StringBuffer (100); - buf.append ("Failed to save RDF in '"); - buf.append (fileRDF.getAbsolutePath() + "'. "); - buf.append (e.toString()); - try { - File tmpFile = File.createTempFile (service.getName() + "-", ".rdf"); - PrintStream fileout = new PrintStream (new FileOutputStream (tmpFile)); - fileout.println (registered [1]); - fileout.close(); - buf.append ("\nReturned RDF file was therefore stored in: "); - buf.append (tmpFile.getAbsolutePath()); - } catch (IOException e2) { - buf.append ("\nEven saving in a temporary file failed: "); - buf.append (e2.toString()); - } - throw new MobyException (buf.toString()); - } - } - } - - /************************************************************************* - * - *************************************************************************/ - public void unregisterService (MobyService service) - throws MobyException, NoSuccessException, PendingCurationException { - String result = - (String)doCall ("deregisterService", - new Object[] { - "" + - "" + service.getAuthority() + "" + - "" + service.getName() + "" + - "" - }); - checkRegistration (result, service); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (String serviceType) - throws MobyException { - if (serviceType == null) - return new MobyService[] {}; - MobyService pattern = new MobyService ("dummy"); - pattern.setCategory (""); - pattern.setType (serviceType); - return findService (pattern, null); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (String[] keywords) - throws MobyException { - if (keywords == null) - return new MobyService[] {}; - return findService (null, keywords); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (MobyService pattern) - throws MobyException { - if (pattern == null) - return new MobyService[] {}; - return findService (pattern, null); - } - - /************************************************************************** - * - *************************************************************************/ - public MobyService[] findService (MobyService pattern, String[] keywords) - throws MobyException { - return findService (pattern, keywords, true, true); - } - - /************************************************************************** - * All 'findService' methods end up here. - *************************************************************************/ - public MobyService[] findService (MobyService pattern, String[] keywords, - boolean includeChildrenServiceTypes, - boolean includeParentDataTypes) - throws MobyException { - if (pattern == null) { - pattern = new MobyService ("dummy"); - pattern.setCategory (""); - } - - String result = - getServicesAsXML (pattern, keywords, includeChildrenServiceTypes, includeParentDataTypes); - MobyService[] services = extractServices (result); - return services; - } - - // ...actually all 'findService' methods end up here - protected String getServicesAsXML (MobyService pattern, String[] keywords, - boolean includeChildrenServiceTypes, - boolean includeParentDataTypes) - throws MobyException { - String[] query = new String[] { - "" + - buildQueryObject (pattern, keywords, - includeParentDataTypes, - includeChildrenServiceTypes, - false) + - "" - }; - return (String)doCall ("findService", query); - } - - /************************************************************************** - * - *************************************************************************/ - public String call (String methodName, String inputXML) - throws MobyException { - Object result; - if (inputXML == null || inputXML.equals ("")) - result = doCall (methodName, new Object[] { }); - else - result = doCall (methodName, new Object[] { inputXML }); - return (String)result; - } - - /************************************************************************** - * - *************************************************************************/ - protected static String resultToString (Object result) - throws MobyException { - if (result == null) - throw new MobyException ("Returned result is null."); - if (result instanceof String) - return (String)result; - if (result instanceof String[]) { - String[] tmp = (String[])result; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < tmp.length; i++) - buf.append (tmp[i]); - return new String (buf); - } - if (result instanceof byte[]) - return new String ((byte[])result); - - throw new MobyException ("Unknown type of result: " + result.getClass().getName()); - } - - /************************************************************************** - * - *************************************************************************/ - public boolean setDebug (boolean enabled) { - boolean oldMode = debug; - debug = enabled; - return oldMode; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     * <Relationships>
    -     *   <Relationship relationshipType='urn:lsid:biomoby.org:servicerelation:isa'>
    -     *     <serviceType>urn:lsid:biomoby.org:servicetype:analysis</serviceType>
    -     *     <serviceType>urn:lsid:biomoby.org:servicetype:service</serviceType>
    -     *   </Relationship>
    -     * </Relationships>
    -     * 
    - *************************************************************************/ - public String[] getServiceTypeRelationships (String serviceTypeName, - boolean expand) - throws MobyException { - String result = getServiceTypeRelationshipsAsXML (serviceTypeName, expand); - return createServiceTypeRelationshipsFromXML (result); - } - - // - protected String getServiceTypeRelationshipsAsXML (String serviceTypeName, - boolean expand) - throws MobyException { - return - (String)doCall ("Relationships", - new Object[] { - "" + - "" + serviceTypeName + "" + - "" + Central.ISA + "" + - "" + (expand ? "1" : "0") + "" + - "" - }); - } - - // - protected String[] createServiceTypeRelationshipsFromXML (String result) - throws MobyException { - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("serviceType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - } - String[] results = new String [v.size()]; - v.copyInto (results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *<Relationships>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *  </Relationship>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:string</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:integer</objectType>
    -     *  </Relationship>
    -     *</Relationships>
    -     * 
    - * - * Added at Sun Feb 19 19:32:31 PHT 2006: it recognizes also an - * attributes 'lsid' and 'articleName' in <objectType> element. - *************************************************************************/ - public Map getDataTypeRelationships (String dataTypeName) - throws MobyException { - - String cacheId = "getDataTypeRelationships_" + dataTypeName; - Map cachedResults = (Map)getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("Relationships", - new Object[] { - "" + - "" + dataTypeName + "" + - "" + Central.ISA + "" + - "" + Central.HASA + "" + - "" + Central.HAS + "" + - "1" + - "" - }); - - // parse returned XML - Map results = new HashMap(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - String relType = elem.getAttribute ("relationshipType"); - NodeList children = elem.getChildNodes(); - Vector v = new Vector(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("objectType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - String[] names = new String [v.size()]; - v.copyInto (names); - results.put (relType, names); - } - - setContents (cacheId, results); - return results; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     *<Relationships>
    -     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    -     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    -     *  </Relationship>
    -     *</Relationships>
    -     * 
    - *************************************************************************/ - public String[] getDataTypeRelationships (String dataTypeName, - String relationshipType) - throws MobyException { - - String cacheId = "getDataTypeRelationships_" + dataTypeName + ":" + relationshipType; - String[] cachedResults = (String[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = - (String)doCall ("Relationships", - new Object[] { - "" + - "" + dataTypeName + "" + - "" + relationshipType + "" + - "1" + - "" - }); - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Relationship"); - - // it should always be just one element in this list - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - NodeList children = elem.getChildNodes(); - for (int j = 0; j < children.getLength(); j++) { - if (children.item (j).getNodeName().equals ("objectType")) { - v.addElement (getFirstValue (children.item (j))); - } - } - } - String[] results = new String [v.size()]; - v.copyInto (results); - - setContents (cacheId, results); - return results; - } - -// /************************************************************************** -// * -// *************************************************************************/ -// public MobyRelationship[] getRelationships (String dataTypeName) -// throws MobyException { -// return null; -// } - - - /************************************************************************** - * - *************************************************************************/ - public String getRegistryEndpoint() { - return endpoint.toString(); - } - - /************************************************************************** - * - *************************************************************************/ - public String getRegistryNamespace() { - return uri; - } - - /************************************************************************** - * Parses and imports the following XML. - *
    -     * <resourceURLs>
    -     *   <Resource name="Service"         url="..." />
    -     *   <Resource name="Object"          url="..." />
    -     *   <Resource name="Namespace"       url="..." />
    -     *   <Resource name="ServiceInstance" url="..." />
    -     *   <Resource name="Full"            url="..." />
    -     * </resourceURLs>
    -     * 
    - *************************************************************************/ - public MobyResourceRef[] getResourceRefs() - throws MobyException { - - String cacheId = "retrieveResourceURLs"; - MobyResourceRef[] cachedResults = (MobyResourceRef[])getContents (cacheId); - if (cachedResults != null) - return cachedResults; - - String result = (String)doCall ("retrieveResourceURLs", - new Object[] {}); - - // parse returned XML - Vector v = new Vector(); - Document document = loadDocument (new ByteArrayInputStream (result.getBytes())); - NodeList list = document.getElementsByTagName ("Resource"); - for (int i = 0; i < list.getLength(); i++) { - Element elem = (Element)list.item (i); - try { - v.addElement - (new MobyResourceRef (elem.getAttribute ("name"), - new URL ((String)elem.getAttribute ("url")), - elem.getAttribute ("type"))); - } catch (MalformedURLException e2) { - if (debug) - System.err.println ("Bad URL: " + elem.getAttribute ("url")); - } - } - - MobyResourceRef[] results = new MobyResourceRef [v.size()]; - v.copyInto (results); - - // Add this data to the cache in case we get called again - setContents (cacheId, results); - - return results; - } - - /************************************************************************** - * - *************************************************************************/ - public InputStream getResource (String resourceName) - throws MobyException { - - MobyResourceRef[] resourceRefs = getResourceRefs(); - for (int i = 0; i < resourceRefs.length; i++) { - if (resourceName.equalsIgnoreCase (resourceRefs[i].getResourceName())) { - return Utils.getInputStream (resourceRefs[i].getResourceLocation()); - } - } - throw new MobyException ("No resource found for '" + resourceName + "'."); - } - - /************************************************************************** - * Return a case-insensitive comparator of Strings. It is used to - * create various TreeMaps where keys are strings. - *************************************************************************/ - protected static Comparator getStringComparator() { - return new Comparator() { - public int compare (Object o1, Object o2) { - return ((String)o1).compareToIgnoreCase ((String)o2); - } - }; - } - - // cache URL/URI so we only check once - private static String CHECKED_URL = null; - private static String CHECKED_URI = null; - - /** - * Using this method to get a Central object will ensure that other parts of the org.biomoby.shared - * class hierarchy that implicitly check the registry will use the same cache. Otherwise, methods - * such as MobyNamespace.getNamespace() must be passed a Central object parameter as well. - * - * @return a CentralImpl using the default Central URI, and currently a class implementing a caching mechanism - */ - public static CentralImpl getDefaultCentral() throws MobyException{ - return getDefaultCentral(null); - } - - public static CentralImpl getDefaultCentral(Registry reg) throws MobyException{ - if(reg == null && defaultCentrals.containsKey("")){ - return defaultCentrals.get(""); - } - else if(reg != null && defaultCentrals.containsKey(reg.getEndpoint())){ - return defaultCentrals.get(reg.getEndpoint()); - } - - String className = DEFAULT_CENTRAL_IMPL_CLASSNAME; - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - URL resURL = classLoader.getResource("META-INF/"+CENTRAL_IMPL_RESOURCE_NAME); - if(resURL != null){ - System.err.println("Loading "+resURL); - try{ - LineNumberReader reader = new LineNumberReader(new InputStreamReader(resURL.openStream())); - for(String line = reader.readLine(); line != null; line = reader.readLine()){ - if(!line.trim().startsWith("#")){ - className = line.trim(); - break; - } - } - } catch(Exception e){ - logger.log(Level.WARNING, - "Error reading " + resURL, - e); - } - } - try{ - System.err.println("Central class is "+className); - Class clazz = Class.forName(className); - if(reg == null){ // should use default nullary c-tor - defaultCentrals.put("", (CentralImpl) clazz.newInstance()); - } - else{ // should have (String endpoint, String namespace) c-tor - for(Constructor ctor: clazz.getDeclaredConstructors()){ - Class[] params = ctor.getParameterTypes(); - if(params.length == 2 && params[0].getName().equals("java.lang.String") && - params[1].getName().equals("java.lang.String") ){ - defaultCentrals.put(reg.getEndpoint(), - (CentralImpl) ctor.newInstance(reg.getEndpoint(), reg.getNamespace())); - break; - } - } - if(!defaultCentrals.containsKey(reg.getEndpoint())){ - logger.log(Level.WARNING, - "Could not find required (String endpoint, String namespace)" + - "constructor for class " + className); - } - } - } catch(Exception e){ - logger.log(Level.WARNING, - "Could not load class " + className, - e); - if(reg == null){ - defaultCentrals.put("", new CentralImpl()); //fallback to this class, no caching, etc. - } - else{ - defaultCentrals.put(reg.getEndpoint(), - new CentralImpl(reg.getEndpoint(), reg.getNamespace())); - } - } - - return defaultCentrals.get(reg == null ? "" : reg.getEndpoint()); - } - - /** - * - * @return a String representing the Default mobycentral endpoint. If the - * system property 'moby.check.default' exists and is set to true, - * then the URL http://biomoby.org/mobycentral is queried and the - * default central endpoint is returned, otherwise DEFAULT_ENDPOINT - * is returned. - */ - public static String getDefaultURL() { - boolean check = false; - try { - check = Boolean.getBoolean("moby.check.default"); - } catch (Exception e) { - - } - - if (check) { - // return the last checked url if we have done this before - if (CHECKED_URL != null && CHECKED_URL.trim() != "") { - return CHECKED_URL; - } - - // create a HttpClient object - HttpClient client = new HttpClient(); - // set up the Head method - HeadMethod method = new HeadMethod("http://biomoby.org/mobycentral"); - // do not follow redirects or we will get a 411 error - method.setFollowRedirects(false); - // retry 3 times - method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false)); - // set the user agent ... should probably make this something more reasonable - method.getParams().setParameter(HttpMethodParams.USER_AGENT,"jMoby/1.0"); - try { - // Execute the method. - int statusCode = client.executeMethod(method); - - if (statusCode != HttpStatus.SC_MOVED_PERMANENTLY) { - System.err.println("Method failed: " - + method.getStatusLine()); - } else { - try { - String location = method.getResponseHeader("location").getValue(); - CHECKED_URL = location; - try { - CHECKED_URI = "http://" + (new URL(CHECKED_URL).getAuthority()) + "/MOBY/Central"; - } catch (MalformedURLException murle ) { - CHECKED_URI = DEFAULT_NAMESPACE; - } - return CHECKED_URL; - } catch (NullPointerException npe) { - return DEFAULT_ENDPOINT; - } - } - } catch (HttpException e) { - System.err.println("Fatal protocol violation: " - + e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - System.err.println("Fatal transport error: " + e.getMessage()); - e.printStackTrace(); - } finally { - // Release the connection. - method.releaseConnection(); - } - - } else { - return DEFAULT_ENDPOINT; - } - return DEFAULT_ENDPOINT; - } - - /** - * - * @return a String representing the default mobycentral uri. If the - * system property 'moby.check.default' exists and is set to true, - * then the URL http://biomoby.org/mobycentral is queried and the - * default central namespace is returned, otherwise DEFAULT_NAMESPACE - * is returned. - */ - public static String getDefaultURI() { - boolean check = false; - try { - check = Boolean.getBoolean("moby.check.default"); - } catch (Exception e) { - - } - if (check) { - if (CHECKED_URI != null && CHECKED_URI.trim() != "") { - return CHECKED_URI; - } - // need to check ... - getDefaultURL(); - return CHECKED_URI; - } else { - return DEFAULT_NAMESPACE; - } - } - /************************************************************************** - * Convert non-suitable characters in a XML string into their - * entity references.

    - * - * Adapted from jDom. - * - * @param str input to be converted - * @return If there were any non-suitable characters, return a new - * string with those characters escaped, otherwise return the - * unmodified input string - * - *************************************************************************/ - public String escapeXML (String str) { - StringBuffer buffer = null; - char ch; - String entity; - for (int i = 0; i < str.length(); i++) { - ch = str.charAt (i); - switch (ch) { - case '<' : - entity = "<"; - break; - case '>' : - entity = ">"; - break; - case '&' : - entity = "&"; - break; - default : - entity = null; - break; - } - if (buffer == null) { - if (entity != null) { - // An entity occurred, so we'll have to use StringBuffer - // (allocate room for it plus a few more entities). - buffer = new StringBuffer (str.length() + 20); - // Copy previous skipped characters and fall through - // to pickup current character - buffer.append (str.substring (0, i)); - buffer.append (entity); - } - } else { - if (entity == null) { - buffer.append (ch); - } else { - buffer.append (entity); - } - } - } - - // If there were any entities, return the escaped characters - // that we put in the StringBuffer. Otherwise, just return - // the unmodified input string. - return (buffer == null) ? str : buffer.toString(); - } - - /************************************************************************* - * Format an exception. - *************************************************************************/ - public static String formatFault (AxisFault e, String endpoint, QName method) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - formatFault (e, new PrintStream (baos), endpoint, method); - return baos.toString(); - } - - /************************************************************************* - * Format an exception. - *************************************************************************/ - public static void formatFault (AxisFault e, PrintStream out, - String endpoint, QName method) { - - out.println ("===ERROR==="); - out.println ("Fault details:"); - // for some obvious errors I do not print all details (with a lenghty trace stack) - String faultString = e.getFaultString(); - if ( (! faultString.startsWith ("java.net.ConnectException")) && - (faultString.indexOf ("Could not find class for the service named:") == -1) - ) { - org.w3c.dom.Element[] details = e.getFaultDetails(); - for (int i = 0; i < details.length; i++) { - String s = details[i].toString().replaceAll ("<", "<"); - s = s.replaceAll (">", ">"); - out.println (s); - } - } - out.println ("Fault string: " + faultString); - out.println ("Fault code: " + e.getFaultCode()); - out.println ("Fault actor: " + e.getFaultActor()); - if (endpoint != null || method != null) - out.println ("When calling:"); - if (endpoint != null) - out.println ("\t" + endpoint); - if (method != null) - out.println ("\t" + method); - out.println ("==========="); - } - - -} +// CentralImpl.java +// A default client to the Moby Central service. +// +// senger at ebi.ac.uk +// February 2003 +// + +package org.biomoby.client; + +import org.biomoby.registry.meta.Registry; +import org.biomoby.shared.Central; +import org.biomoby.shared.MobyData; +import org.biomoby.shared.MobyDataType; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyNamespace; +import org.biomoby.shared.MobyPrimaryDataSet; +import org.biomoby.shared.MobyPrimaryDataSimple; +import org.biomoby.shared.MobyRelationship; +import org.biomoby.shared.MobySecondaryData; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.MobyServiceType; +import org.biomoby.shared.NoSuccessException; +import org.biomoby.shared.PendingCurationException; +import org.biomoby.shared.MobyResourceRef; +import org.biomoby.shared.Utils; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.namespace.QName; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.apache.axis.AxisFault; +import org.apache.axis.client.Call; +import org.apache.axis.client.Service; +import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.HeadMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.PrintStream; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.Vector; +import java.util.TreeMap; +import java.util.Comparator; +import java.util.zip.GZIPInputStream; +import java.util.logging.*; + +/** + * A default implementation of the interface {@link org.biomoby.shared.Central Central} allowing access to a Moby + * registry. + *

    + * This class is supposed to be used by all other clients that wish to communicate with the Moby Registry, but do not + * want to know about all XML details that are necessary for talking with the Moby Central directly. This is an example + * of a client program: + * + *

    + * import org.biomoby.shared.Central;
    + * import org.biomoby.shared.MobyException;
    + * import org.biomoby.client.CentralImpl;
    + * import java.util.Map;
    + * import java.util.Iterator;
    + * 
    + * public class Test {
    + * 
    + *     public static void main( String[] args ) throws MobyException {
    + * 
    + *         Central worker = new CentralImpl();
    + *         Map authorities = worker.getServiceNamesByAuthority();
    + * 
    + *         for ( Iterator it = authorities.entrySet().iterator(); it.hasNext(); ) {
    + *             Map.Entry entry = ( Map.Entry ) it.next();
    + *             System.out.println( entry.getKey() );
    + *             String[] names = ( String[] ) entry.getValue();
    + *             for ( int i = 0; i < names.length; i++ )
    + *                 System.out.println( "\t" + names[ i ] );
    + *         }
    + *     }
    + * }
    + * 
    + * + * @author Martin Senger + * @version $Id$ + */ + +public class CentralImpl implements Central, SimpleCache { + + private URL endpoint; + private String uri; + protected boolean debug = false; + + /** Common central used to if getDefaultCentral() is called */ + protected static Map< String, CentralImpl > defaultCentrals = new HashMap< String, CentralImpl >(); + + /** Default location (endpoint) of a Moby registry. */ + public static final String DEFAULT_ENDPOINT = "http://moby.ucalgary.ca/moby/MOBY-Central.pl"; + + /** Default namespace used by the contacted Moby registry. */ + public static final String DEFAULT_NAMESPACE = "http://moby.ucalgary.ca/MOBY/Central"; + + /** + * The META-INF resource file that will be checked to determine what default class should be instantiated in order + * to create a Central Implementation when getDefaultCentral() is called. + */ + public static final String CENTRAL_IMPL_RESOURCE_NAME = "org.biomoby.shared.CentralDefaultImpl"; + /** The class to use for getDefaultCentral if all else fails */ + public static final String DEFAULT_CENTRAL_IMPL_CLASSNAME = "org.biomoby.client.CentralDigestCachedImpl"; + private static Logger logger = Logger.getLogger( "org.biomoby.client.CentralImpl" ); + + /** + * Thread local that gives each thread its own DocumentBuilderFactory (since it is not thread-safe). Code taken from + * Apache's JaxpUtils. + */ + public static ThreadLocal DOCUMENT_BUILDER_FACTORIES = new ThreadLocal() { + protected synchronized Object initialValue() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware( true ); + return dbf; + } + }; + + /******************************************************************************************************************* + * Default constructor. It connects to a default Moby registry (as defined in {@link #DEFAULT_ENDPOINT}) using a + * default namespace (as defined int {@link #DEFAULT_NAMESPACE}). + ******************************************************************************************************************/ + public CentralImpl() throws MobyException { + this( DEFAULT_ENDPOINT, DEFAULT_NAMESPACE ); + } + + /******************************************************************************************************************* + * Constructor allowing to specify which Moby Registry to use. + * + * @throws MobyException + * if 'endpoint' is not a valid URL, or if no DOM parser is available + ******************************************************************************************************************/ + public CentralImpl( String endpoint ) throws MobyException { + this( endpoint, DEFAULT_NAMESPACE ); + } + + /******************************************************************************************************************* + * Constructor allowing to specify which Moby Registry and what namespace to use. If any of the parameters is null, + * its default value is used instead. + *

    + * + * @throws MobyException + * if 'endpoint' is not a valid URL, or if no DOM parser was found + ******************************************************************************************************************/ + public CentralImpl( String endpoint, String namespace ) throws MobyException { + + if ( endpoint == null || "".equals( endpoint.trim() ) ) endpoint = DEFAULT_ENDPOINT; + if ( namespace == null || "".equals( namespace.trim() ) ) namespace = DEFAULT_NAMESPACE; + + try { + this.endpoint = new URL( endpoint ); + } + catch ( MalformedURLException e ) { + throw new MobyException( "Bad URL: " + endpoint ); + } + this.uri = namespace; + + cache = new Hashtable< String, Object >(); + useCache = true; + } + + /******************************************************************************************************************* + * Loads a DOM Document from an InputStream. Uses thread-safe mechanism. + ******************************************************************************************************************/ + public static Document loadDocument( InputStream input ) throws MobyException { + try { + DocumentBuilderFactory dbf = ( DocumentBuilderFactory ) DOCUMENT_BUILDER_FACTORIES.get(); + DocumentBuilder db = dbf.newDocumentBuilder(); + return ( db.parse( input ) ); + } + catch ( Exception e ) { + throw new MobyException( "Problem with reading XML input: " + e.toString(), e ); + } + } + + /******************************************************************************************************************* + * Call 'method' with 'parameters' and return its result. + ******************************************************************************************************************/ + protected Object doCall( String method, Object[] parameters ) throws MobyException { + + Call call = null; + try { + Service service = new Service(); + call = ( Call ) service.createCall(); + call.setTargetEndpointAddress( endpoint ); + call.setTimeout( new Integer( 0 ) ); + + String user = System.getProperty( "user" ); + String password = System.getProperty( "password" ); + + if ( user != null && password != null ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, password ); + } + + call.setSOAPActionURI( uri + "#" + method ); + + if ( debug ) { + System.err.println( "METHOD CALL: " + method ); + System.err.println( "------------" ); + if ( parameters.length > 0 ) System.err.println( parameters[ 0 ] + "\n" ); + System.err.println( "------------\n" ); + + Object result = call.invoke( uri, method, parameters ); + + System.err.println( "METHOD RETURN:" ); + System.err.println( "------------" ); + if ( result != null ) System.err.println( result + "\n" ); + System.err.println( "------------\n" ); + + return resultToString( result ); + + } + else { + return resultToString( call.invoke( uri, method, parameters ) ); + } + + } + catch ( AxisFault e ) { + throw new MobyException( formatFault( e, endpoint.toString(), ( call == null ? null : call + .getOperationName() ) ), e ); + // (endpoint.toString()+(call == null ? "" : call.getOperationName()), e); + + } + catch ( Exception e ) { + throw new MobyException( e.toString(), e ); + // e.printStackTrace(); + } + } + + /******************************************************************************************************************* + * Parse the given XML sniplet to find tag 'success'. If it has value '1' look further for tag 'id' and return it + * back (or return an empty string if ID is not there). Otherwise raise an exception with the 'culprit' and with the + * message from the tag 'message'. + *

    + * + * The return value is a two-element long array. The first element is the ID (given by BioMobe registry), and the + * second element is RDF corresponding with the registered object (BioMoby returns this only for service instances, + * so for other objects this will be null). + *

    + * + * This is how the XML is supposed to look: + * + * Success takes the value "1" to indicate success, "0" to indicate failure, and "-1" to indicate "Pending + * Curation". + ******************************************************************************************************************/ + protected String[] checkRegistration( String xml, Object culprit ) throws MobyException, NoSuccessException, + PendingCurationException { + + String id = "", success = "0", message = "", rdf = ""; + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( xml.getBytes() ) ); + Element root = document.getDocumentElement(); + + NodeList children = root.getChildNodes(); + for ( int i = 0; i < children.getLength(); i++ ) { + if ( children.item( i ).getNodeType() != Node.ELEMENT_NODE ) continue; + Element elem = ( Element ) children.item( i ); + if ( elem.getNodeName().equals( "id" ) ) { + if ( elem.getFirstChild() != null ) id = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "success" ) ) { + if ( elem.getFirstChild() != null ) success = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "message" ) ) { + if ( elem.getFirstChild() != null ) message = elem.getFirstChild().getNodeValue(); + } + else if ( elem.getNodeName().equals( "RDF" ) ) { + if ( elem.getFirstChild() != null ) rdf = elem.getFirstChild().getNodeValue(); + } + } + + if ( success.equals( "0" ) ) + throw new NoSuccessException( message, culprit ); + else if ( success.equals( "-1" ) ) throw new PendingCurationException(); + return new String[] { id, rdf }; + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing input data types and their usage in the given + * service. Only data considered primary are included. Note that the main job of converting to XML is done by + * instances of MobyPrimaryData. + * + * The returned XML looks like this: + ******************************************************************************************************************/ + protected String buildPrimaryInputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] primaryInputs = service.getPrimaryInputs(); + buf.append( "\n" ); + for ( int i = 0; i < primaryInputs.length; i++ ) + buf.append( primaryInputs[ i ].toXML() ); + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing input data types and their usage in the given + * service. Only data considered secondary are included. Note that the main job of converting to XML is done by + * instances of MobySecondaryData. + * + * The returned XML looks like this: + * + ******************************************************************************************************************/ + protected String buildSecondaryInputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] secInputs = service.getSecondaryInputs(); + buf.append( "\n" ); + for ( int i = 0; i < secInputs.length; i++ ) { + buf.append( secInputs[ i ].toXML() ); + } + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML created from the definitions representing output data types and their usage in the given + * service. Only data considered primary are included. Note that the main job of converting to XML is done by + * instances of MobyPrimaryData. + * + * The returned XML looks like this: + * + * + ******************************************************************************************************************/ + protected String buildOutputTag( MobyService service ) { + StringBuffer buf = new StringBuffer(); + MobyData[] primaryOutputs = service.getPrimaryOutputs(); + buf.append( "\n" ); + for ( int i = 0; i < primaryOutputs.length; i++ ) + buf.append( primaryOutputs[ i ].toXML() ); + buf.append( "\n" ); + return new String( buf ); + } + + /******************************************************************************************************************* + * Return a piece of XML represented a query object (an object used to find a service). + * + * The returned XML looks like this: + * + * + * + * ServiceTypeTerm ServiceName moby + * http://desired.service.provider; 1|0 1|0 + * 1|0 something .... .... + ******************************************************************************************************************/ + protected String buildQueryObject( MobyService service, String[] keywords, boolean expandObjects, + boolean expandServices, boolean authoritative ) { + if ( service == null ) { + service = new MobyService( "dummy" ); + service.setCategory( "" ); + } + StringBuffer buf = new StringBuffer(); + + buf.append( "\n\n" ); + MobyData[] pi = service.getPrimaryInputs(); + if ( pi.length > 0 ) { + for ( int i = 0; i < pi.length; i++ ) + buf.append( pi[ i ].toXML() ); + } + buf.append( "\n\n" ); + + buf.append( "\n\n" ); + MobyData[] po = service.getPrimaryOutputs(); + if ( po.length > 0 ) { + for ( int i = 0; i < po.length; i++ ) + buf.append( po[ i ].toXML() ); + } + buf.append( "\n\n" ); + + buf.append( "" + service.getType() + "\n" ); + + String name = service.getName(); + if ( !name.equals( "" ) && !name.equals( "dummy" ) && !name.equals( MobyService.DUMMY_NAME ) ) + buf.append( "" + service.getName() + "\n" ); + + String sigURL = service.getSignatureURL(); + if ( !sigURL.equals( "" ) ) buf.append( "" + sigURL + "\n" ); + + buf.append( "" + service.getCategory() + "\n" ); + buf.append( "" + service.getAuthority() + "\n" ); + + buf.append( "" ); + buf.append( expandObjects ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "" ); + buf.append( expandServices ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "" ); + buf.append( authoritative ? "1" : "0" ); + buf.append( "\n" ); + + buf.append( "\n" ); + if ( keywords != null && keywords.length > 0 ) { + for ( int i = 0; i < keywords.length; i++ ) { + buf.append( "" ); + buf.append( keywords[ i ] ); + buf.append( "\n" ); + } + } + buf.append( "\n" ); + + return new String( buf ); + } + + /******************************************************************************************************************* + * Extract one or more MobyService objects from the given XML piece. The XML should look like this: + * + *

    +     *  <Services>
    +     *    <Service authURI="authority.URI.here" lsid="..." serviceName="MyService">
    +     *      <serviceType>Service_Ontology_Term</serviceType>
    +     *      <Category>moby</Category> <!-- or 'cgi' or 'soap' -->
    +     *      <contactEmail>your at email.addy.here</contactEmail>
    +     *      <signatureURL>http://service.RDF.here</signatureURL>
    +     *      <URL>http://service.endpoint.here/scriptname</URL>
    +     *      <authoritative>1</authoritative>
    +     *      <Input>
    +     *           <!-- one or more Simple and/or Complex Primary articles -->
    +     *      </Input>
    +     *      <Output>
    +     *           <!-- one or more Simple and/or Complex Primary articles --> 
    +     *      </Output>
    +     *      <secondaryArticles>
    +     *           <!-- one or more Secondary articles -->
    +     *      </secondaryArticles>
    +     *      <Description><![CDATA[free text description here]]></Description>
    +     *    </Service>
    +     *    ...  <!--  one or more Service blocks may be returned -->
    +     *    ...
    +     *    ...
    +     *  </Services>
    +     * 
    + * + * @throws MobyException + * if the XML document is invalid + ******************************************************************************************************************/ + public MobyService[] extractServices( String xml ) throws MobyException { + + Document document = loadDocument( new ByteArrayInputStream( xml.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Service" ); + MobyService[] results = new MobyService[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyService service = new MobyService( elem.getAttribute( "serviceName" ) ); + service.setAuthority( elem.getAttribute( "authURI" ) ); + service.setLSID( elem.getAttribute( "lsid" ) ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "Description" ) ) { + service.setDescription( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "Category" ) ) { + service.setCategory( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "URL" ) ) { + service.setURL( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "signatureURL" ) ) { + service.setSignatureURL( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "contactEmail" ) ) { + service.setEmailContact( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "serviceType" ) ) { + service.setType( getFirstValue( children.item( j ) ) ); + MobyServiceType mst = new MobyServiceType( service.getType() ); + NamedNodeMap map = ( children.item( j ).getAttributes() ); + if ( map != null ) { + Node node = map.getNamedItemNS( children.item( j ).getNamespaceURI(), "lsid" ); + if ( node != null ) mst.setLSID( node.getNodeValue() ); + } + service.setServiceType( mst ); + } + else if ( nodeName.equals( "authoritative" ) ) { + String authoritative = getFirstValue( children.item( j ) ); + service.setAuthoritative( authoritative.equals( "1" ) ? true : false ); + } + else if ( nodeName.equals( "Input" ) ) { + // + // + // + // ... + // + // + // ...... + // ...... + // + // + NodeList inputs = children.item( j ).getChildNodes(); + for ( int k = 0; k < inputs.getLength(); k++ ) { + if ( inputs.item( k ).getNodeName().equals( "Simple" ) ) { + MobyPrimaryDataSimple data = new MobyPrimaryDataSimple( ( Element ) inputs.item( k ) ); + service.addInput( data ); + } + else if ( inputs.item( k ).getNodeName().equals( "Collection" ) ) { + MobyPrimaryDataSet data = new MobyPrimaryDataSet( ( Element ) inputs.item( k ) ); + service.addInput( data ); + } + } + } + else if ( nodeName.equals( "Output" ) ) { + // + // + // + NodeList inputs = children.item( j ).getChildNodes(); + for ( int k = 0; k < inputs.getLength(); k++ ) { + if ( inputs.item( k ).getNodeName().equals( "Simple" ) ) { + MobyPrimaryDataSimple data = new MobyPrimaryDataSimple( ( Element ) inputs.item( k ) ); + service.addOutput( data ); + } + else if ( inputs.item( k ).getNodeName().equals( "Collection" ) ) { + MobyPrimaryDataSet data = new MobyPrimaryDataSet( ( Element ) inputs.item( k ) ); + service.addOutput( data ); + } + } + + } + else if ( nodeName.equals( "secondaryArticles" ) ) { + // + // ... + // + NodeList parameters = children.item( j ).getChildNodes(); + for ( int k = 0; k < parameters.getLength(); k++ ) { + if ( parameters.item( k ).getNodeName().equals( "Parameter" ) ) { + MobySecondaryData data = new MobySecondaryData( ( Element ) parameters.item( k ) ); + service.addInput( data ); + } + } + } + } + results[ i ] = service; + } + return results; + } + + // protect against null values + protected String getFirstValue( Node child ) { + Node node = child.getFirstChild(); + if ( node == null ) return ""; + String value = node.getNodeValue(); + if ( value == null ) return ""; + return value; + } + + protected String getFirstValue( NodeList children ) { + if ( children.item( 0 ) != null && children.item( 0 ).hasChildNodes() ) { + children.item( 0 ).normalize(); + return getFirstValue( children.item( 0 ) ); + } + return ""; + } + + /******************************************************************************************************************* + * + * Implementing SimpleCache interface. + * + * Why to have an interface for such trivial thing? Well, because I needed to overwrite the caching mechanism in the + * subclasses so I needed to have all caching functions as separate methods - that's why I have collect them in an + * interface. + * + ******************************************************************************************************************/ + private Hashtable< String, Object > cache; // this is the cache itself + private boolean useCache; // this signal that we are actually caching things + + // not used here + public String createId( String rootName, String semanticType, String syntaxType, long lastModified, Properties props ) { + return ""; // not used here + } + + // check existence of a cached object + public boolean existsInCache( String id ) { + synchronized ( cache ) { + if ( useCache ) + return cache.containsKey( id ); + else + return false; + } + } + + // retrieve from cache + public Object getContents( String id ) { + synchronized ( cache ) { + if ( useCache ) + return cache.get( id ); + else + return null; + } + } + + // cache an object + public void setContents( String id, java.lang.Object data ) { + synchronized ( cache ) { + if ( useCache ) cache.put( id, data ); + } + } + + // in this implementation, it clears the whole cache, regardless + // what 'id' is passed + public void removeFromCache( String id ) { + cache.clear(); + } + + /******************************************************************************************************************* + * + * And the other methods related to caching (but not part of the SimpleCache interface). + * + ******************************************************************************************************************/ + + /******************************************************************************************************************* + * By default, caching is enabled to reduce network traffic. Setting this to false will clear the cache, and not + * cache any further calls unless it is set to true again. + *

    + * + * @param shouldCache + * whether retrieveXXX call results should be cached in case they are called again (i.e. don't request + * MobyCentral every time) + ******************************************************************************************************************/ + public void setCacheMode( boolean shouldCache ) { + useCache = shouldCache; + if ( !useCache ) removeFromCache( null ); + } + + /******************************************************************************************************************* + * Find if caching is currently enabled. + * + * @return true if caching is enabled + ******************************************************************************************************************/ + public boolean getCacheMode() { + return useCache; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     * <serviceNames>
    +     *   <serviceName name="serviceName" authURI='authority.info.here'/>
    +     *   ...
    +     *   ...
    +     * </serviceNames>
    +     * 
    + * + * @deprecated Replaced by {@link #getServiceNamesByAuthority}. The reason is that this method returns a random + * result if there are more services with the same name but belonging to different authorities. + *

    + * + ******************************************************************************************************************/ + public Map< String, String > getServiceNames() throws MobyException { + + String result = ( String ) doCall( "retrieveServiceNames", new Object[] {} ); + // parse returned XML + Map< String, String > results = new TreeMap< String, String >( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceName" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + results.put( elem.getAttribute( "name" ), elem.getAttribute( "authURI" ) ); + } + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     * <serviceNames>
    +     *   <serviceName name="serviceName" lsid="..." authURI='authority.info.here'/>
    +     *   ...
    +     *   ...
    +     * </serviceNames>
    +     * 
    + * + * @return a Map which has authorities as keys, and String arrays with service names as a values. + ******************************************************************************************************************/ + public Map getServiceNamesByAuthority() throws MobyException { + String result = getServiceNamesByAuthorityAsXML(); + return createServicesByAuthorityFromXML( result, true ); + } + + /******************************************************************************************************************* + * Similar to {@link #getServiceNamesByAuthority} but the resulting Map contains slightly more. + *

    + * + * @return a Map which has authorities as keys, and arrays of MobyServices as a values. Each MobyService is filled + * with its name, authority and LSID. + ******************************************************************************************************************/ + public Map getServicesByAuthority() throws MobyException { + String result = getServiceNamesByAuthorityAsXML(); + return createServicesByAuthorityFromXML( result, false ); + } + + // + protected String getServiceNamesByAuthorityAsXML() throws MobyException { + return ( String ) doCall( "retrieveServiceNames", new Object[] {} ); + } + + // if onlyNames == true + // Map: authority name -> String[] + // (filled with service namea) + // else + // Map: authority name -> MobyService[] + // (filled with service name, authority and lsid) + protected Map createServicesByAuthorityFromXML( String result, boolean onlyNames ) throws MobyException { + + // parse returned XML + Map results = new TreeMap( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceName" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String name = elem.getAttribute( "name" ); + String auth = elem.getAttribute( "authURI" ); + Vector< Object > v = ( results.containsKey( auth ) ? ( Vector ) results.get( auth ) + : new Vector< Object >() ); + if ( onlyNames ) { + v.addElement( name ); + } + else { + MobyService ms = new MobyService( name ); + ms.setAuthority( auth ); + ms.setLSID( elem.getAttribute( "lsid" ) ); + v.addElement( ms ); + } + results.put( auth, v ); + } + + // change values of type Vector to MobyService[] or String[] + for ( Iterator it = results.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = ( Map.Entry ) it.next(); + Vector v = ( Vector ) entry.getValue(); + if ( onlyNames ) { + String[] sNames = new String[ v.size() ]; + v.copyInto( sNames ); + entry.setValue( sNames ); + } + else { + MobyService[] mss = new MobyService[ v.size() ]; + v.copyInto( mss ); + entry.setValue( mss ); + } + } + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     *  <serviceProviders>
    +     *     <serviceProvider name="authority.URI.here"/>
    +     *          ...
    +     *          ...
    +     *  </serviceProviders>
    +     * 
    + ******************************************************************************************************************/ + public String[] getProviders() throws MobyException { + + String cacheId = "retrieveServiceProviders"; + String[] cachedResults = ( String[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveServiceProviders", new Object[] {} ); + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceProvider" ); + String[] results = new String[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) + results[ i ] = ( ( Element ) list.item( i ) ).getAttribute( "name" ); + + // Add this data to the cache in case we get called again + setContents( cacheId, results ); + + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     *  <serviceTypes>
    +     *     <serviceType name="serviceName" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *            <contactEmail>...</contactEmail>
    +     *            <authURI>...</authURI>
    +     *     </serviceType>
    +     *          ...
    +     *          ...
    +     *  </serviceTypes>
    +     * 
    + ******************************************************************************************************************/ + public Map getServiceTypes() throws MobyException { + String result = getServiceTypesAsXML(); + Map results = new TreeMap( getStringComparator() ); + MobyServiceType[] types = createServiceTypesFromXML( result ); + for ( int i = 0; i < types.length; i++ ) { + results.put( types[ i ].getName(), types[ i ].getDescription() ); + } + return results; + } + + // + protected String getServiceTypesAsXML() throws MobyException { + return ( String ) doCall( "retrieveServiceTypes", new Object[] {} ); + } + + // but be aware that the created MobyServiceTypes are not complete + // - they do not have the relationship information; that's why + // this method is not public; the full service types are available + // from CentralDigest implementations + protected MobyServiceType[] createServiceTypesFromXML( String result ) throws MobyException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "serviceType" ); + if ( list == null || list.getLength() == 0 ) return new MobyServiceType[] {}; + MobyServiceType[] results = new MobyServiceType[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyServiceType st = new MobyServiceType( elem.getAttribute( "name" ) ); + st.setLSID( elem.getAttribute( "lsid" ) ); + st.setDescription( getFirstValue( elem.getElementsByTagName( "Description" ) ) ); + st.setEmailContact( getFirstValue( elem.getElementsByTagName( "contactEmail" ) ) ); + st.setAuthority( getFirstValue( elem.getElementsByTagName( "authURI" ) ) ); + results[ i ] = st; + } + java.util.Arrays.sort( results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     *  <Namespaces>
    +     *     <Namespace name="namespace" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *            <contactEmail>...</contactEmail>
    +     *            <authURI>...</authURI>
    +     *     </Namespace>
    +     *          ...
    +     *          ...
    +     *  </Namespaces>
    +     * 
    + ******************************************************************************************************************/ + public MobyNamespace[] getFullNamespaces() throws MobyException { + + String result = getNamespacesAsXML(); + return createNamespacesFromXML( result ); + } + + // + protected String getNamespacesAsXML() throws MobyException { + return ( String ) doCall( "retrieveNamespaces", new Object[] {} ); + } + + // + protected MobyNamespace[] createNamespacesFromXML( String result ) throws MobyException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getDocumentElement().getElementsByTagName( "Namespace" ); + if ( list == null || list.getLength() == 0 ) { + return new MobyNamespace[] {}; + } + MobyNamespace[] results = new MobyNamespace[ list.getLength() ]; + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + MobyNamespace nm = new MobyNamespace( elem.getAttribute( "name" ) ); + nm.setLSID( elem.getAttribute( "lsid" ) ); + nm.setDescription( getFirstValue( elem.getElementsByTagName( "Description" ) ) ); + nm.setEmailContact( getFirstValue( elem.getElementsByTagName( "contactEmail" ) ) ); + nm.setAuthority( getFirstValue( elem.getElementsByTagName( "authURI" ) ) ); + results[ i ] = nm; + } + + java.util.Arrays.sort( results ); + return results; + } + + /******************************************************************************************************************* + * + * @deprecated Replaced by {@link #getFullNamespaces} that gives more information for the same price. + *

    + ******************************************************************************************************************/ + public Map getNamespaces() throws MobyException { + + Map results = new TreeMap( getStringComparator() ); + MobyNamespace[] namespaces = getFullNamespaces(); + for ( int i = 0; i < namespaces.length; i++ ) { + results.put( namespaces[ i ].getName(), namespaces[ i ].getDescription() ); + } + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *

    +     *  <objectNames>
    +     *     <Object name="objectName" lsid="...">
    +     *            <Description><![CDATA[free text description here]]></Description>
    +     *     </Object>
    +     *          ...
    +     *          ...
    +     *  </objectNames>
    +     * 
    + ******************************************************************************************************************/ + public Map getDataTypeNames() throws MobyException { + String result = getDataTypeNamesAsXML(); + return createDataTypeNamesFromXML( result, true ); + } + + // + protected String getDataTypeNamesAsXML() throws MobyException { + return ( String ) doCall( "retrieveObjectNames", new Object[] {} ); + } + + // if onlyNames == true + // Map: data type name -> description (String) + // else + // Map: data type name -> MobyDataType[] + // (filled with name, description, and lsid) + protected Map createDataTypeNamesFromXML( String result, boolean onlyNames ) throws MobyException { + + // parse returned XML + Map results = new TreeMap( getStringComparator() ); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Object" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String name = elem.getAttribute( "name" ); + if ( name == null ) continue; // ignore no-named data types + String desc = ""; + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "Description" ) ) { + desc = getFirstValue( children.item( j ) ); + break; + } + } + if ( onlyNames ) { + results.put( name, desc ); + } + else { + MobyDataType dt = new MobyDataType( name ); + dt.setDescription( desc ); + dt.setLSID( elem.getAttribute( "lsid" ) ); + results.put( name, dt ); + } + } + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. An example: + * + *
    +     * <retrieveObjectDefinition>
    +     *   <objectType lsid="...">go_term</objectType>
    +     *   <Description><![CDATA[A very lightweight object holding a GO term name and its definition]]></Description>
    +     *   <authURI>http://www.illuminae.com</authURI>
    +     *   <contactEmail>markw at illuminae.com</contactEmail>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *      <objectType articleName=''>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *   </Relationship>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    +     *      <objectType articleName='Term'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *      <objectType articleName='Definition'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *   </Relationship>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:has'>
    +     *      <objectType articleName='Problems'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *      <objectType articleName='Issues'>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *   </Relationship>
    +     * </retrieveObjectDefinition>
    +     * 
    + ******************************************************************************************************************/ + public MobyDataType getDataType( String dataTypeName ) throws MobyException, NoSuccessException { + + String result = getDataTypeAsXML( dataTypeName ); + return createDataTypeFromXML( result, dataTypeName ); + } + + public MobyDataType[] getDataTypes() throws MobyException, NoSuccessException { + Map< String, String > datatypeMap = getDataTypeNames(); + MobyDataType[] datatypes = new MobyDataType[ datatypeMap.size() ]; + int i = 0; + for ( String dataTypeName : datatypeMap.keySet() ) { + datatypes[ i++ ] = getDataType( dataTypeName ); + } + return datatypes; + } + + protected String getDataTypeAsXML( String dataTypeName ) throws MobyException, NoSuccessException { + + return ( String ) doCall( "retrieveObjectDefinition", new Object[] { "" + + "" + dataTypeName + "" + "" } ); + } + + protected MobyDataType createDataTypeFromXML( String xmlSource, String dataTypeName ) throws MobyException, + NoSuccessException { + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( xmlSource.getBytes() ) ); + NodeList list = document.getElementsByTagName( "retrieveObjectDefinition" ); + if ( list == null || list.getLength() == 0 ) + throw new NoSuccessException( "Data Type name was not found.", dataTypeName ); + MobyDataType data = null; + Element elem = ( Element ) list.item( 0 ); + NodeList children = elem.getChildNodes(); + + // first find the "real" (LSID-ized) data type name + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "objectType" ) ) { + data = new MobyDataType( getFirstValue( children.item( j ) ) ); + data.setLSID( ( ( Element ) children.item( j ) ).getAttribute( "lsid" ) ); + break; + } + } + + // if not found (unprobable) use the name given by the caller + if ( data == null ) data = new MobyDataType( dataTypeName ); + + // now fill the data type object with the rest of attributes + for ( int j = 0; j < children.getLength(); j++ ) { + String nodeName = children.item( j ).getNodeName(); + if ( nodeName.equals( "Description" ) ) { + data.setDescription( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "authURI" ) ) { + data.setAuthority( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "contactEmail" ) ) { + data.setEmailContact( getFirstValue( children.item( j ) ) ); + } + else if ( nodeName.equals( "Relationship" ) ) { + String relationshipType = ( ( Element ) children.item( j ) ).getAttribute( "relationshipType" ); + if ( relationshipType.endsWith( "isa" ) ) { + + NodeList parents = children.item( j ).getChildNodes(); + for ( int k = 0; k < parents.getLength(); k++ ) { + if ( parents.item( k ).getNodeName().equals( "objectType" ) ) { + data.addParentName( getFirstValue( parents.item( k ) ) ); + } + } + } + else if ( relationshipType.endsWith( "hasa" ) ) { + + NodeList belows = children.item( j ).getChildNodes(); + for ( int k = 0; k < belows.getLength(); k++ ) { + if ( belows.item( k ).getNodeName().equals( "objectType" ) ) { + data.addChild( ( ( Element ) belows.item( k ) ).getAttribute( "articleName" ), + getFirstValue( belows.item( k ) ), Central.iHASA ); + } + } + } + else if ( relationshipType.endsWith( "has" ) ) { + + NodeList belows = children.item( j ).getChildNodes(); + for ( int k = 0; k < belows.getLength(); k++ ) { + if ( belows.item( k ).getNodeName().equals( "objectType" ) ) { + data.addChild( ( ( Element ) belows.item( k ) ).getAttribute( "articleName" ), belows.item( + k ).getFirstChild().getNodeValue(), Central.iHAS ); + } + } + } + } + } + return data; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getServiceWSDL( String serviceName ) throws MobyException, NoSuccessException { + + Map names = getServiceNames(); + + for ( Iterator it = names.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = ( Map.Entry ) it.next(); + if ( ( ( String ) entry.getKey() ).equals( serviceName ) ) + return getServiceWSDL( serviceName, ( String ) entry.getValue() ); + } + + throw new NoSuccessException( "Service not found.", serviceName ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getServiceWSDL( String serviceName, String authority ) throws MobyException, NoSuccessException { + + String cacheId = "getServiceWSDL" + serviceName + ":" + authority; + String cachedResults = ( String ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveService", + new Object[] { "" + "" + "" } ); + + // parse returned XML + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + Element service = document.getDocumentElement(); + Node wsdl = service.getFirstChild(); + if ( wsdl == null ) + throw new NoSuccessException( "Service not found OR WSDL is not available.", serviceName + " (" + authority + + ")" ); + + String results = wsdl.getNodeValue(); + setContents( cacheId, results ); + return results; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterDataTypeXML( MobyDataType dataType ) { + + // build the ISA tag (expressing hierarchy of data types) + String[] names = dataType.getParentNames(); + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < names.length; i++ ) { + buf.append( "" ); + buf.append( names[ i ] ); + buf.append( "" ); + buf.append( "\n" ); + } + + // build the HASA/HAS tags (expressing containments of data types) + MobyRelationship[] children = dataType.getChildren(); + StringBuffer buf2 = new StringBuffer(); // for HASA + StringBuffer buf3 = new StringBuffer(); // for HAS + for ( int i = 0; i < children.length; i++ ) { + if ( children[ i ].getRelationshipType() == Central.iHASA ) { + buf2.append( "" ); + buf2.append( children[ i ].getDataTypeName() ); + buf2.append( "" ); + } + else if ( children[ i ].getRelationshipType() == Central.iHAS ) { + buf3.append( "" ); + buf3.append( children[ i ].getDataTypeName() ); + buf3.append( "" ); + } + } + + return "" + "" + dataType.getName() + "" + + "" + "" + + "" + new String( buf ) + "" + + "" + new String( buf2 ) + "" + + "" + new String( buf3 ) + "" + "" + + dataType.getAuthority() + "" + "" + dataType.getEmailContact() + + "" + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerDataType( MobyDataType dataType ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerObjectClass", new Object[] { getRegisterDataTypeXML( dataType ) } ); + dataType.setId( checkRegistration( result, dataType )[ 0 ] ); + } + + /******************************************************************************************************************* + * B + ******************************************************************************************************************/ + public void unregisterDataType( MobyDataType dataType ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterObjectClass", new Object[] { "" + + "" + dataType.getName() + "" + "" } ); + checkRegistration( result, dataType ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterServiceTypeXML( MobyServiceType serviceType ) { + + // build the ISA tag (expressing hierarchy of service types) + String[] names = serviceType.getParentNames(); + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < names.length; i++ ) { + buf.append( "" ); + buf.append( names[ i ] ); + buf.append( "" ); + buf.append( "\n" ); + } + + return "" + "" + serviceType.getName() + "" + "" + + serviceType.getEmailContact() + "" + "" + serviceType.getAuthority() + + "" + "" + "" + + "" + new String( buf ) + "" + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerServiceType( MobyServiceType serviceType ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerServiceType", + new Object[] { getRegisterServiceTypeXML( serviceType ) } ); + serviceType.setId( checkRegistration( result, serviceType )[ 0 ] ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterServiceType( MobyServiceType serviceType ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterServiceType", new Object[] { "" + + "" + serviceType.getName() + "" + "" } ); + checkRegistration( result, serviceType ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterNamespaceXML( MobyNamespace namespace ) { + return "" + "" + namespace.getName() + "" + "" + + namespace.getEmailContact() + "" + "" + namespace.getAuthority() + + "" + "" + "" + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerNamespace( MobyNamespace namespace ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "registerNamespace", new Object[] { getRegisterNamespaceXML( namespace ) } ); + namespace.setId( checkRegistration( result, namespace )[ 0 ] ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterNamespace( MobyNamespace namespace ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterNamespace", new Object[] { "" + + "" + namespace.getName() + "" + "" } ); + checkRegistration( result, namespace ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegisterServiceXML( MobyService service ) { + return "" + "" + service.getCategory() + "" + "" + + service.getName() + "" + "" + service.getType() + "" + + "" + ( service.getLSID() == null ? "" : service.getLSID().trim() ) + "" + + "" + service.getAuthority() + "" + "" + + escapeXML( service.getSignatureURL() ) + "" + "" + escapeXML( service.getURL() ) + + "" + "" + service.getEmailContact() + "" + + "" + ( service.isAuthoritative() ? "1" : "0" ) + "" + + "" + "" + + buildPrimaryInputTag( service ) + buildSecondaryInputTag( service ) + buildOutputTag( service ) + + ""; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void registerService( MobyService service ) throws MobyException, NoSuccessException, + PendingCurationException { + + String result = ( String ) doCall( "registerService", new Object[] { getRegisterServiceXML( service ) } ); + String[] registered = checkRegistration( result, service ); + service.setId( registered[ 0 ] ); + service.setRDF( registered[ 1 ] ); + String pathToRDF = service.getPathToRDF(); + if ( !pathToRDF.equals( "" ) ) { + File fileRDF = new File( pathToRDF ); + try { + PrintStream fileout = new PrintStream( new FileOutputStream( fileRDF ) ); + fileout.println( registered[ 1 ] ); + fileout.close(); + } + catch ( IOException e ) { + StringBuffer buf = new StringBuffer( 100 ); + buf.append( "Failed to save RDF in '" ); + buf.append( fileRDF.getAbsolutePath() + "'. " ); + buf.append( e.toString() ); + try { + File tmpFile = File.createTempFile( service.getName() + "-", ".rdf" ); + PrintStream fileout = new PrintStream( new FileOutputStream( tmpFile ) ); + fileout.println( registered[ 1 ] ); + fileout.close(); + buf.append( "\nReturned RDF file was therefore stored in: " ); + buf.append( tmpFile.getAbsolutePath() ); + } + catch ( IOException e2 ) { + buf.append( "\nEven saving in a temporary file failed: " ); + buf.append( e2.toString() ); + } + throw new MobyException( buf.toString() ); + } + } + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public void unregisterService( MobyService service ) throws MobyException, NoSuccessException, + PendingCurationException { + String result = ( String ) doCall( "deregisterService", new Object[] { "" + "" + + service.getAuthority() + "" + "" + service.getName() + "" + + "" } ); + checkRegistration( result, service ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( String serviceType ) throws MobyException { + if ( serviceType == null ) return new MobyService[] {}; + MobyService pattern = new MobyService( "dummy" ); + pattern.setCategory( "" ); + pattern.setType( serviceType ); + return findService( pattern, null ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( String[] keywords ) throws MobyException { + if ( keywords == null ) return new MobyService[] {}; + return findService( null, keywords ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern ) throws MobyException { + if ( pattern == null ) return new MobyService[] {}; + return findService( pattern, null ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern, String[] keywords ) throws MobyException { + return findService( pattern, keywords, true, true ); + } + + /******************************************************************************************************************* + * All 'findService' methods end up here. + ******************************************************************************************************************/ + public MobyService[] findService( MobyService pattern, String[] keywords, boolean includeChildrenServiceTypes, + boolean includeParentDataTypes ) throws MobyException { + if ( pattern == null ) { + pattern = new MobyService( "dummy" ); + pattern.setCategory( "" ); + } + + String result = getServicesAsXML( pattern, keywords, includeChildrenServiceTypes, includeParentDataTypes ); + MobyService[] services = extractServices( result ); + return services; + } + + // ...actually all 'findService' methods end up here + protected String getServicesAsXML( MobyService pattern, String[] keywords, boolean includeChildrenServiceTypes, + boolean includeParentDataTypes ) throws MobyException { + String[] query = new String[] { "" + + buildQueryObject( pattern, keywords, includeParentDataTypes, includeChildrenServiceTypes, false ) + + "" }; + return ( String ) doCall( "findService", query ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String call( String methodName, String inputXML ) throws MobyException { + Object result; + if ( inputXML == null || inputXML.equals( "" ) ) + result = doCall( methodName, new Object[] {} ); + else + result = doCall( methodName, new Object[] { inputXML } ); + return ( String ) result; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected static String resultToString( Object result ) throws MobyException { + if ( result == null ) throw new MobyException( "Returned result is null." ); + if ( result instanceof String ) return ( String ) result; + if ( result instanceof String[] ) { + String[] tmp = ( String[] ) result; + StringBuffer buf = new StringBuffer(); + for ( int i = 0; i < tmp.length; i++ ) + buf.append( tmp[ i ] ); + return new String( buf ); + } + if ( result instanceof byte[] ) return new String( ( byte[] ) result ); + + throw new MobyException( "Unknown type of result: " + result.getClass().getName() ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public boolean setDebug( boolean enabled ) { + boolean oldMode = debug; + debug = enabled; + return oldMode; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * <Relationships>
    +     *   <Relationship relationshipType='urn:lsid:biomoby.org:servicerelation:isa'>
    +     *     <serviceType>urn:lsid:biomoby.org:servicetype:analysis</serviceType>
    +     *     <serviceType>urn:lsid:biomoby.org:servicetype:service</serviceType>
    +     *   </Relationship>
    +     * </Relationships>
    +     * 
    + ******************************************************************************************************************/ + public String[] getServiceTypeRelationships( String serviceTypeName, boolean expand ) throws MobyException { + String result = getServiceTypeRelationshipsAsXML( serviceTypeName, expand ); + return createServiceTypeRelationshipsFromXML( result ); + } + + // + protected String getServiceTypeRelationshipsAsXML( String serviceTypeName, boolean expand ) throws MobyException { + return ( String ) doCall( "Relationships", new Object[] { "" + "" + serviceTypeName + + "" + "" + Central.ISA + "" + + "" + ( expand ? "1" : "0" ) + "" + "" } ); + } + + // + protected String[] createServiceTypeRelationshipsFromXML( String result ) throws MobyException { + + // parse returned XML + Vector< String > v = new Vector< String >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "serviceType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + } + String[] results = new String[ v.size() ]; + v.copyInto( results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * lt;Relationships>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *  </Relationship>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:hasa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:string</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:integer</objectType>
    +     *  </Relationship>
    +     * lt;/Relationships>
    +     * 
    + * + * Added at Sun Feb 19 19:32:31 PHT 2006: it recognizes also an attributes 'lsid' and 'articleName' in + * <objectType> element. + ******************************************************************************************************************/ + public Map getDataTypeRelationships( String dataTypeName ) throws MobyException { + + String cacheId = "getDataTypeRelationships_" + dataTypeName; + Map cachedResults = ( Map ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "Relationships", new Object[] { "" + "" + + dataTypeName + "" + "" + Central.ISA + "" + + "" + Central.HASA + "" + "" + Central.HAS + + "" + "1" + "" } ); + + // parse returned XML + Map results = new HashMap(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + String relType = elem.getAttribute( "relationshipType" ); + NodeList children = elem.getChildNodes(); + Vector< String > v = new Vector< String >(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "objectType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + String[] names = new String[ v.size() ]; + v.copyInto( names ); + results.put( relType, names ); + } + + setContents( cacheId, results ); + return results; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * lt;Relationships>
    +     *  <Relationship relationshipType='urn:lsid:biomoby.org:objectrelation:isa'>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:virtualsequence</objectType>
    +     *    <objectType>urn:lsid:biomoby.org:objectclass:object</objectType>
    +     *  </Relationship>
    +     * lt;/Relationships>
    +     * 
    + ******************************************************************************************************************/ + public String[] getDataTypeRelationships( String dataTypeName, String relationshipType ) throws MobyException { + + String cacheId = "getDataTypeRelationships_" + dataTypeName + ":" + relationshipType; + String[] cachedResults = ( String[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "Relationships", new Object[] { "" + "" + + dataTypeName + "" + "" + relationshipType + "" + + "1" + "" } ); + + // parse returned XML + Vector< String > v = new Vector< String >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Relationship" ); + + // it should always be just one element in this list + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + NodeList children = elem.getChildNodes(); + for ( int j = 0; j < children.getLength(); j++ ) { + if ( children.item( j ).getNodeName().equals( "objectType" ) ) { + v.addElement( getFirstValue( children.item( j ) ) ); + } + } + } + String[] results = new String[ v.size() ]; + v.copyInto( results ); + + setContents( cacheId, results ); + return results; + } + + // /************************************************************************** + // * + // *************************************************************************/ + // public MobyRelationship[] getRelationships (String dataTypeName) + // throws MobyException { + // return null; + // } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegistryEndpoint() { + return endpoint.toString(); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getRegistryNamespace() { + return uri; + } + + /******************************************************************************************************************* + * Parses and imports the following XML. + * + *
    +     * <resourceURLs>
    +     *   <Resource name="Service"         url="..." />
    +     *   <Resource name="Object"          url="..." />
    +     *   <Resource name="Namespace"       url="..." />
    +     *   <Resource name="ServiceInstance" url="..." />
    +     *   <Resource name="Full"            url="..." />
    +     * </resourceURLs>
    +     * 
    + ******************************************************************************************************************/ + public MobyResourceRef[] getResourceRefs() throws MobyException { + + String cacheId = "retrieveResourceURLs"; + MobyResourceRef[] cachedResults = ( MobyResourceRef[] ) getContents( cacheId ); + if ( cachedResults != null ) return cachedResults; + + String result = ( String ) doCall( "retrieveResourceURLs", new Object[] {} ); + + // parse returned XML + Vector< MobyResourceRef > v = new Vector< MobyResourceRef >(); + Document document = loadDocument( new ByteArrayInputStream( result.getBytes() ) ); + NodeList list = document.getElementsByTagName( "Resource" ); + for ( int i = 0; i < list.getLength(); i++ ) { + Element elem = ( Element ) list.item( i ); + try { + v.addElement( new MobyResourceRef( elem.getAttribute( "name" ), new URL( ( String ) elem + .getAttribute( "url" ) ), elem.getAttribute( "type" ) ) ); + } + catch ( MalformedURLException e2 ) { + if ( debug ) System.err.println( "Bad URL: " + elem.getAttribute( "url" ) ); + } + } + + MobyResourceRef[] results = new MobyResourceRef[ v.size() ]; + v.copyInto( results ); + + // Add this data to the cache in case we get called again + setContents( cacheId, results ); + + return results; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public InputStream getResource( String resourceName ) throws MobyException { + + MobyResourceRef[] resourceRefs = getResourceRefs(); + for ( int i = 0; i < resourceRefs.length; i++ ) { + if ( resourceName.equalsIgnoreCase( resourceRefs[ i ].getResourceName() ) ) { + return Utils.getInputStream( resourceRefs[ i ].getResourceLocation() ); + } + } + throw new MobyException( "No resource found for '" + resourceName + "'." ); + } + + /******************************************************************************************************************* + * Return a case-insensitive comparator of Strings. It is used to create various TreeMaps where keys are strings. + ******************************************************************************************************************/ + protected static Comparator getStringComparator() { + return new Comparator() { + public int compare( Object o1, Object o2 ) { + return ( ( String ) o1 ).compareToIgnoreCase( ( String ) o2 ); + } + }; + } + + // cache URL/URI so we only check once + private static String CHECKED_URL = null; + private static String CHECKED_URI = null; + + /** + * Using this method to get a Central object will ensure that other parts of the org.biomoby.shared class hierarchy + * that implicitly check the registry will use the same cache. Otherwise, methods such as + * MobyNamespace.getNamespace() must be passed a Central object parameter as well. + * + * @return a CentralImpl using the default Central URI, and currently a class implementing a caching mechanism + */ + public static CentralImpl getDefaultCentral() throws MobyException { + return getDefaultCentral( null ); + } + + public static CentralImpl getDefaultCentral( Registry reg ) throws MobyException { + if ( reg == null && defaultCentrals.containsKey( "" ) ) { + return defaultCentrals.get( "" ); + } + else if ( reg != null && defaultCentrals.containsKey( reg.getEndpoint() ) ) { + return defaultCentrals.get( reg.getEndpoint() ); + } + + String className = DEFAULT_CENTRAL_IMPL_CLASSNAME; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + URL resURL = classLoader.getResource( "META-INF/" + CENTRAL_IMPL_RESOURCE_NAME ); + if ( resURL != null ) { + System.err.println( "Loading " + resURL ); + try { + LineNumberReader reader = new LineNumberReader( new InputStreamReader( resURL.openStream() ) ); + for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { + if ( !line.trim().startsWith( "#" ) ) { + className = line.trim(); + break; + } + } + } + catch ( Exception e ) { + logger.log( Level.WARNING, "Error reading " + resURL, e ); + } + } + try { + System.err.println( "Central class is " + className ); + Class clazz = Class.forName( className ); + if ( reg == null ) { // should use default nullary c-tor + defaultCentrals.put( "", ( CentralImpl ) clazz.newInstance() ); + } + else { // should have (String endpoint, String namespace) c-tor + for ( Constructor ctor : clazz.getDeclaredConstructors() ) { + Class[] params = ctor.getParameterTypes(); + if ( params.length == 2 && params[ 0 ].getName().equals( "java.lang.String" ) + && params[ 1 ].getName().equals( "java.lang.String" ) ) { + defaultCentrals.put( reg.getEndpoint(), ( CentralImpl ) ctor.newInstance( reg.getEndpoint(), + reg.getNamespace() ) ); + break; + } + } + if ( !defaultCentrals.containsKey( reg.getEndpoint() ) ) { + logger.log( Level.WARNING, "Could not find required (String endpoint, String namespace)" + + "constructor for class " + className ); + } + } + } + catch ( Exception e ) { + logger.log( Level.WARNING, "Could not load class " + className, e ); + if ( reg == null ) { + defaultCentrals.put( "", new CentralImpl() ); // fallback to this class, no caching, etc. + } + else { + defaultCentrals.put( reg.getEndpoint(), new CentralImpl( reg.getEndpoint(), reg.getNamespace() ) ); + } + } + + return defaultCentrals.get( reg == null ? "" : reg.getEndpoint() ); + } + + /** + * + * @return a String representing the Default mobycentral endpoint. If the system property 'moby.check.default' + * exists and is set to true, then the URL http://biomoby.org/mobycentral is queried and the default central + * endpoint is returned, otherwise DEFAULT_ENDPOINT is returned. + */ + public static String getDefaultURL() { + boolean check = false; + try { + check = Boolean.getBoolean( "moby.check.default" ); + } + catch ( Exception e ) { + + } + + if ( check ) { + // return the last checked url if we have done this before + if ( CHECKED_URL != null && CHECKED_URL.trim() != "" ) { + return CHECKED_URL; + } + + // create a HttpClient object + HttpClient client = new HttpClient(); + // set up the Head method + HeadMethod method = new HeadMethod( "http://biomoby.org/mobycentral" ); + // do not follow redirects or we will get a 411 error + method.setFollowRedirects( false ); + // retry 3 times + method.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, + new DefaultHttpMethodRetryHandler( 3, false ) ); + // set the user agent ... should probably make this something more reasonable + method.getParams().setParameter( HttpMethodParams.USER_AGENT, "jMoby/1.0" ); + try { + // Execute the method. + int statusCode = client.executeMethod( method ); + + if ( statusCode != HttpStatus.SC_MOVED_PERMANENTLY ) { + System.err.println( "Method failed: " + method.getStatusLine() ); + } + else { + try { + String location = method.getResponseHeader( "location" ).getValue(); + CHECKED_URL = location; + try { + CHECKED_URI = "http://" + ( new URL( CHECKED_URL ).getAuthority() ) + "/MOBY/Central"; + } + catch ( MalformedURLException murle ) { + CHECKED_URI = DEFAULT_NAMESPACE; + } + return CHECKED_URL; + } + catch ( NullPointerException npe ) { + return DEFAULT_ENDPOINT; + } + } + } + catch ( HttpException e ) { + System.err.println( "Fatal protocol violation: " + e.getMessage() ); + e.printStackTrace(); + } + catch ( IOException e ) { + System.err.println( "Fatal transport error: " + e.getMessage() ); + e.printStackTrace(); + } + finally { + // Release the connection. + method.releaseConnection(); + } + + } + else { + return DEFAULT_ENDPOINT; + } + return DEFAULT_ENDPOINT; + } + + /** + * + * @return a String representing the default mobycentral uri. If the system property 'moby.check.default' exists and + * is set to true, then the URL http://biomoby.org/mobycentral is queried and the default central namespace + * is returned, otherwise DEFAULT_NAMESPACE is returned. + */ + public static String getDefaultURI() { + boolean check = false; + try { + check = Boolean.getBoolean( "moby.check.default" ); + } + catch ( Exception e ) { + + } + if ( check ) { + if ( CHECKED_URI != null && CHECKED_URI.trim() != "" ) { + return CHECKED_URI; + } + // need to check ... + getDefaultURL(); + return CHECKED_URI; + } + else { + return DEFAULT_NAMESPACE; + } + } + + /******************************************************************************************************************* + * Convert non-suitable characters in a XML string into their entity references. + *

    + * + * Adapted from jDom. + * + * @param str + * input to be converted + * @return If there were any non-suitable characters, return a new string with those characters escaped, otherwise + * return the unmodified input string + * + ******************************************************************************************************************/ + public String escapeXML( String str ) { + StringBuffer buffer = null; + char ch; + String entity; + for ( int i = 0; i < str.length(); i++ ) { + ch = str.charAt( i ); + switch ( ch ) { + case '<': + entity = "<"; + break; + case '>': + entity = ">"; + break; + case '&': + entity = "&"; + break; + default: + entity = null; + break; + } + if ( buffer == null ) { + if ( entity != null ) { + // An entity occurred, so we'll have to use StringBuffer + // (allocate room for it plus a few more entities). + buffer = new StringBuffer( str.length() + 20 ); + // Copy previous skipped characters and fall through + // to pickup current character + buffer.append( str.substring( 0, i ) ); + buffer.append( entity ); + } + } + else { + if ( entity == null ) { + buffer.append( ch ); + } + else { + buffer.append( entity ); + } + } + } + + // If there were any entities, return the escaped characters + // that we put in the StringBuffer. Otherwise, just return + // the unmodified input string. + return ( buffer == null ) ? str : buffer.toString(); + } + + /******************************************************************************************************************* + * Format an exception. + ******************************************************************************************************************/ + public static String formatFault( AxisFault e, String endpoint, QName method ) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + formatFault( e, new PrintStream( baos ), endpoint, method ); + return baos.toString(); + } + + /******************************************************************************************************************* + * Format an exception. + ******************************************************************************************************************/ + public static void formatFault( AxisFault e, PrintStream out, String endpoint, QName method ) { + + out.println( "===ERROR===" ); + out.println( "Fault details:" ); + // for some obvious errors I do not print all details (with a lenghty trace stack) + String faultString = e.getFaultString(); + if ( ( !faultString.startsWith( "java.net.ConnectException" ) ) + && ( faultString.indexOf( "Could not find class for the service named:" ) == -1 ) ) { + org.w3c.dom.Element[] details = e.getFaultDetails(); + for ( int i = 0; i < details.length; i++ ) { + String s = details[ i ].toString().replaceAll( "<", "<" ); + s = s.replaceAll( ">", ">" ); + out.println( s ); + } + } + out.println( "Fault string: " + faultString ); + out.println( "Fault code: " + e.getFaultCode() ); + out.println( "Fault actor: " + e.getFaultActor() ); + if ( endpoint != null || method != null ) out.println( "When calling:" ); + if ( endpoint != null ) out.println( "\t" + endpoint ); + if ( method != null ) out.println( "\t" + method ); + out.println( "===========" ); + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java 2007/05/29 03:51:46 1.12 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/client/BaseClient.java 2008/11/26 08:53:43 1.13 @@ -1,481 +1,429 @@ -// BaseClient.java -// -// Created: August 2005 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.client; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.parser.JDOMUtils; -import org.biomoby.shared.Central; -import org.biomoby.client.CentralImpl; -import org.biomoby.shared.parser.MobyPackage; -import org.biomoby.shared.parser.MobyJob; -import org.biomoby.shared.parser.ServiceException; -import org.biomoby.shared.parser.MobyTags; - -import org.tulsoft.tools.soap.axis.AxisCall; -import org.tulsoft.shared.GException; - -import org.apache.commons.lang.StringUtils; - -import org.jdom.input.SAXBuilder; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.Namespace; - -import java.net.URL; -import java.net.MalformedURLException; -import java.io.StringReader; - -/** - * This is a base class for Biomoby clients. It takes care about - * converting user input into Biomoby XML, sending it in a SOAP - * message to a Biomoby service, waiting for the response and parsing - * it from Biomoby XML. It also divides requests and responses into - * so-called jobs - each of them corresponds to a Biomoby - * query (a Biomoby single network request may contain more - * queries/jobs).

    - * - * Any client can override various methods - but the ones she/he - * must override in a subclass are those telling what service - * to call ({@link #getServiceLocator}), what data to put in a request - * ({@link #fillRequest(MobyJob,MobyPackage) fillRequest}), and what - * to do with a response ({@link #useResponse(MobyJob,MobyPackage) - * useResponse}.

    - * - * @author Martin Senger - * @version $Id$ - */ - -abstract public class BaseClient { - - private static org.apache.commons.logging.Log log = - org.apache.commons.logging.LogFactory.getLog (BaseClient.class); - - /************************************************************************** - * - *************************************************************************/ - static protected boolean notEmpty (String value) { - return StringUtils.isNotBlank (value); - } - static protected boolean isEmpty (String value) { - return StringUtils.isBlank (value); - } - - /************************************************************************** - * The main method that packs input data, invokes a BioMoby - * service and uses its response. Use this method if the input - * data should have just one job (which is a usual case) - - * otherwise use method {@link #process(int)}.

    - * - * @throws MobyException if (a) a sub-class throws it during the - * filling data or using response, or (b) a Biomoby service - * invocation fails - *************************************************************************/ - public void process() - throws MobyException { - process (1); - } - - /************************************************************************** - * The main method that packs input data, invokes a BioMoby - * service and uses its response. The input data may consist from - * more than one job (query) - the 'jobCount' is a suggestion how - * many jobs will be included, but this can be changed by the - * implementing sub-class.

    - * - * Usually a client developer does not need to overwrite this - * method. She or he makes the real input data filling in the - * {@link #fillRequest} method, and uses the response in the - * {@link #useResponse} method.

    - * - * @throws MobyException if (a) a sub-class throws it during the - * filling data or using response, or (b) a Biomoby service - * invocation fails - *************************************************************************/ - public void process (int jobCount) - throws MobyException { - - String xmlResponse = null; - - // input: raw-level processing - String xmlInput = fillRequest(); - if (xmlInput != null) { - if ( (xmlInput = interceptRequest (xmlInput)) == null ) - return; - } - - // input: usual processing (i.e. collect XML in iterations) - else { - MobyPackage mobyInput = new MobyPackage(); - if (! fillRequest (mobyInput, jobCount)) return; - xmlInput = mobyInput.toXML(); - if ( (xmlInput = interceptRequest (xmlInput)) == null ) - return; - } - - // calling service - xmlResponse = callRemoteService (xmlInput); - - // output: raw-level processing - if (! useResponse (xmlResponse)) return; - - // output: usual processing (again by iterations) - MobyPackage mobyResponse = MobyPackage.createFromXML (xmlResponse); - useResponse (mobyResponse); - } - - public String interceptRequest (String xmlInput) - throws MobyException { - return xmlInput; - } - - /************************************************************************** - * Create raw XML input. Override this method if you have already - * an input XML, or you want to create it yourself.

    - * - * @return a full XML input for a Biomoby service (in this case no - * other fillRequest methods will called); return null if - * no XML was created and a usual process to gather it will be used - * - * @throws MobyException if an XML cannot be created - *************************************************************************/ - public String fillRequest() - throws MobyException { - return null; - } - - /************************************************************************** - * - *************************************************************************/ - protected String filterMobyResponseType (Object result) - throws MobyException { - if (result instanceof String) - return (String)result; - else if (result instanceof byte[]) - return new String ((byte[])result); - else - throw new MobyException - ("The Biomoby data should be sent/received either as type String or base64/byte[]. " + - "But they are of type '" + result.getClass().getName() + "'."); - } - - /************************************************************************** - * - *************************************************************************/ - protected String callBiomobyService (MobyServiceLocator locator, - String xmlInput) - throws MobyException { - - - MobyService service = locator.getService(); - String serviceName = service.getName(); - boolean asBytes = locator.isAsBytes(); - String serviceEndpoint = service.getURL(); - int timeout = locator.getSuggestedTimeout(); - - try { - URL target = new URL (serviceEndpoint); - AxisCall call = new AxisCall (target, timeout); - call.getCall().setSOAPActionURI (MobyService.BIOMOBY_SERVICE_URI + "#" + serviceName); - return filterMobyResponseType - (call.doCall (MobyService.BIOMOBY_SERVICE_URI, - serviceName, - new Object[] { sendingFilter (xmlInput, asBytes) })); - } catch (MalformedURLException e) { - throw new MobyException ("Service endpoint '" + serviceEndpoint + - "' is not a valid URL."); - } catch (GException e) { - throw new MobyException (e.getMessage(), e); - } - } - - // - protected Object sendingFilter (String input, boolean asBytes) { - if (asBytes) { - log.debug ("Data sent as a byte array"); - return input.getBytes(); - } else { - return input; - } - } - - /************************************************************************** - * Call a SOAP-based BioMoby service. In order to find what - * service to call and what are its characteristics (such as its - * endpoint) it will call method {@link #getServiceLocator} that - * should be implemented by a sub-class.

    - * - * Once it has the service locator, this class does one of the - * following, in this order:

      - * - *
    • The locator must contain at least a service name. If it - * does not, an exception is raised. - * - *
    • If the locator contains a service endpoint, a call is - * made to this endpoint, using also the service name as a - * method name. - * - *
    • If the locator has a registry endpoint, an enquiry to - * the registry is made to find an endpoint of a service - * corresponding with the given service name. Once found, the - * service is called. - * - *
    • The same as the previous one but using a default - * registry. - * - * @param xmlInput data will be sent to the called Biomoby service - * - * @return service response (still in XML) - * - * @throws MobyException (a) if service call (or a call to - * registry; for example because the registry does not know given - * service) fails, or (b) if the used {@link MobyServiceLocator} - * does not contain a service name. - * - *************************************************************************/ - public String callRemoteService (String xmlInput) - throws MobyException { - - // 1) service name is a must - MobyServiceLocator locator = getServiceLocator(); - MobyService service = locator.getService(); - if (service == null) - throw new MobyException ("MobyService locator returned an empty service object.\n" + - "I do not know what service to call..."); - String serviceName = service.getName(); - if (isEmpty (serviceName) || - MobyService.DUMMY_NAME.equals (serviceName)) - throw new MobyException ("MobyService locator returned an empty service name.\n" + - "I do not know what service to call..."); - - // 2) try service endpoint - String serviceEndpoint = service.getURL(); - if (notEmpty (serviceEndpoint)) - return callBiomobyService (locator, xmlInput); - - // 3) find service endpoint in a Biomoby registry - Central worker = new CentralImpl (locator.getRegistryEndpoint(), - locator.getRegistryNamespace()); - MobyService[] services = worker.findService (service); - if (services == null || services.length == 0) - throw new MobyException ("Service " + service.toShortString() + - " is not known in Biomoby registry: \n" + - "\t" + worker.getRegistryEndpoint() + "\n" + - "\t" + worker.getRegistryNamespace()); - // ...and call the service - serviceEndpoint = services[0].getURL(); - if (notEmpty (serviceEndpoint)) { - service.setURL (serviceEndpoint); - return callBiomobyService (locator, xmlInput); - } - - // what else can I do? - throw new MobyException ("Registry has not returned any URL for service " + - service.toShortString()); - } - - /************************************************************************** - * Fill the whole 'mobyInput' - put there any number of jobs - * (queries) as you wish (you do not need to follow the 'jobCount' - * hint suggesting how many jobs should be put there).

      - * - * Usually there is not need to overwrite this method. It serves - * as an inter-mediator between the main {@link #process} method - * and the individual request fillings (done by a sub-class in - * method {@link #fillRequest(MobyJob,MobyPackage)}).

      - * - * @return false if you wish to cancel whole request (nothing will - * be sent to a Biomoby service); otherwise return true. - * - * @param mobyInput is an empty shell that you are supposed to - * fill with the input data for a Biomoby service execution - * - * @param jobCount is only a suggestion how many requests/job - * should be created (it comes from the {@link #process} method) - - * but it does not need to be obeyed - * - *************************************************************************/ - public boolean fillRequest (MobyPackage mobyInput, int jobCount) - throws MobyException { - - if (jobCount < 0) jobCount = 0; - for (int i = 0; i < jobCount; i++) { - MobyJob request = new MobyJob ("job_" + i); - if (! fillRequest (request, mobyInput)) - break; - mobyInput.addJob (request); - } - return (mobyInput.size() > 0); - } - - /************************************************************************** - * A raw-level processing. Use it if you need access to raw XML - * coming from a service.

      - * - * @param xmlResponse is a raw XML response returned from a - * BioMoby service - * - * @return false if the response should be considered fully - * processed (in this case no other 'useResponse' will be called); - * true indicates that normal processing of the response will - * follow; by default, this class (BaseClient) returns true - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'mobyResponse' is broken - *************************************************************************/ - public boolean useResponse (String xmlResponse) - throws MobyException { - return true; - } - - /************************************************************************** - * A high-level processing. Use it if you need access to all jobs - * (queries) - that returned from a service - in the same time. - * Otherwise use the processing on the job level (method {@link - * #useResponse(MobyJob,MobyPackage)}.

      - * - * @param mobyResponse is a full response returned from a BioMoby - * service - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'mobyResponse' is broken - *************************************************************************/ - public void useResponse (MobyPackage mobyResponse) - throws MobyException { - - // iterate over all input jobs - for (int i = 0; i < mobyResponse.size(); i++) { - if (! useResponse (mobyResponse.getJob (i), - mobyResponse)) - return; - } - } - - /************************************************************************** - * Extracts errors from a raw service response. It is iseful when - * one does not want to create a whole MobyPackage from a - * response, but just find whether a response is good or bad.

      - * - * @param xmlResponse is a full response returned from a BioMoby - * service - * - * @return a slightly formatted list of exceptions (of severity - * error) extracted from the response; or null if there - * are no errors there - *************************************************************************/ - public String errorsInResponse (String xmlResponse) { - try { - StringBuffer buf = new StringBuffer(); - SAXBuilder builder = new SAXBuilder(); - Document doc = - builder.build (new StringReader (xmlResponse)); - Element root = doc.getRootElement(); - Element mobyContent = JDOMUtils.getChild (root, MobyTags.MOBYCONTENT); - Element serviceNotes = JDOMUtils.getChild (mobyContent, MobyTags.SERVICENOTES); - ServiceException[] exceptions = - ServiceException.extractExceptions (serviceNotes); - for (int i = 0; i < exceptions.length; i++) { - if (exceptions[i].getSeverity() != ServiceException.ERROR) - continue; - if (buf.length() > 0) - buf.append ("\n"); - buf.append (exceptions[i].getErrorCodeAsString()); - buf.append (": "); - buf.append (exceptions[i].getMessage()); - } - return (buf.length() == 0 ? null : new String (buf)); - - } catch (Exception e) { - return e.toString(); - } - } - - - // - // Abstract methods - // - - /************************************************************************** - * Return characteristics of a BioMoby service that will be - * called, and that reveal where to find such service.

      - * - * @see #callRemoteService - * - * @return an object defining a location of a BioMoby service - * @throws MobyException if service locator cannot be - * returned/created (e.g. because there is not enough information - * about what service to call) - *************************************************************************/ - abstract public MobyServiceLocator getServiceLocator() - throws MobyException; - - /************************************************************************** - * Crate data (fill them into 'request') for one Moby job - * (query). The request will be sent within given 'inputContext' - - * but it is not yet there (because you may wish not to put it - * there - see the return value), and it is not the task of this - * method to put it there (just fill the 'request').

      - * - * This is a method that should be implemented by a client - * developer, and it is the place where the client's business - * logic sits.

      - * - * @return true if this request should be included into the input - * data (package) that will be sent to a biomoby service; or - * return false if you do not wish to create any more requests for - * this particular package (also this 'request' will not be used) - * - * @param request is an object that you are supposed to fill with - * input data for one service invocation; it already has a name - * (so called 'query id' in the BioMoby speak) but you are free to change it - * - * @param inputContext is an envelope where all requests will be - * stored and sent to a Biomoby service; you do not need to do - * anything with it here unless you wish; note that all already - * created requests are there, but not the one you are just - * creating in this method - * - * @throws MobyException if you need so (from whatever reason in - * your business logic); if thrown then nothing will be sent to a - * Biomoby service - * - *************************************************************************/ - abstract public boolean fillRequest (MobyJob request, MobyPackage inputContext) - throws MobyException; - - /************************************************************************** - * Process a single job returned from a BioMoby service.

      - * - * This is a method that should be implemented by a client - * developer, and it is the place where the client's business - * logic using the response sits.

      - * - * @param response is an object that you are supposed to use - * - * @param responseContext is an envelope where the full response - * (all its jobs) is located; you do not need to do anything with - * it here unless you wish (e.g. it gives you knowledge about how - * many jobs are in the full response, or it gives you access to - * the so-called 'service notes') - * - * @return false if you do not wish to get any more - * responses/jobs; otherwise return true - * - * @throws MobyException if you are not satisfied with a response - * data, or from whatever reasons; it also throws this exception - * if the 'response' is broken - * - *************************************************************************/ - abstract public boolean useResponse (MobyJob response, - MobyPackage responseContext) - throws MobyException; - -} +// BaseClient.java +// +// Created: August 2005 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.client; + +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.axis.client.Call; +import org.apache.commons.lang.StringUtils; +import org.biomoby.shared.Central; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.parser.JDOMUtils; +import org.biomoby.shared.parser.MobyJob; +import org.biomoby.shared.parser.MobyPackage; +import org.biomoby.shared.parser.MobyTags; +import org.biomoby.shared.parser.ServiceException; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; +import org.tulsoft.shared.GException; +import org.tulsoft.tools.soap.axis.AxisCall; + +/** + * This is a base class for Biomoby clients. It takes care about converting user input into Biomoby XML, sending it in a + * SOAP message to a Biomoby service, waiting for the response and parsing it from Biomoby XML. It also divides requests + * and responses into so-called jobs - each of them corresponds to a Biomoby query (a Biomoby single network + * request may contain more queries/jobs). + *

      + * + * Any client can override various methods - but the ones she/he must override in a subclass are those + * telling what service to call ({@link #getServiceLocator}), what data to put in a request ({@link #fillRequest(MobyJob,MobyPackage) fillRequest}), + * and what to do with a response ({@link #useResponse(MobyJob,MobyPackage) useResponse}. + *

      + * + * @author Martin Senger + * @version $Id$ + */ + +abstract public class BaseClient { + private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( BaseClient.class ); + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + static protected boolean notEmpty(String value) { + return StringUtils.isNotBlank( value ); + } + static protected boolean isEmpty(String value) { + return StringUtils.isBlank( value ); + } + + /******************************************************************************************************************* + * The main method that packs input data, invokes a BioMoby service and uses its response. Use this method if the + * input data should have just one job (which is a usual case) - otherwise use method {@link #process(int)}. + *

      + * + * @throws MobyException if (a) a sub-class throws it during the filling data or using response, or (b) a Biomoby + * service invocation fails + ******************************************************************************************************************/ + public void process() throws MobyException { + process( 1 ); + } + + /******************************************************************************************************************* + * The main method that packs input data, invokes a BioMoby service and uses its response. The input data may + * consist from more than one job (query) - the 'jobCount' is a suggestion how many jobs will be included, but this + * can be changed by the implementing sub-class. + *

      + * + * Usually a client developer does not need to overwrite this method. She or he makes the real input data filling in + * the {@link #fillRequest} method, and uses the response in the {@link #useResponse} method. + *

      + * + * @throws MobyException if (a) a sub-class throws it during the filling data or using response, or (b) a Biomoby + * service invocation fails + ******************************************************************************************************************/ + public void process(int jobCount) throws MobyException { + + String xmlResponse = null; + + // input: raw-level processing + String xmlInput = fillRequest(); + if ( xmlInput != null ) { + if ( ( xmlInput = interceptRequest( xmlInput ) ) == null ) + return; + } + + // input: usual processing (i.e. collect XML in iterations) + else { + MobyPackage mobyInput = new MobyPackage(); + if ( !fillRequest( mobyInput, jobCount ) ) + return; + xmlInput = mobyInput.toXML(); + if ( ( xmlInput = interceptRequest( xmlInput ) ) == null ) + return; + } + + // calling service + xmlResponse = callRemoteService( xmlInput ); + + // output: raw-level processing + if ( !useResponse( xmlResponse ) ) + return; + + // output: usual processing (again by iterations) + MobyPackage mobyResponse = MobyPackage.createFromXML( xmlResponse ); + useResponse( mobyResponse ); + } + + public String interceptRequest(String xmlInput) throws MobyException { + return xmlInput; + } + + /******************************************************************************************************************* + * Create raw XML input. Override this method if you have already an input XML, or you want to create it yourself. + *

      + * + * @return a full XML input for a Biomoby service (in this case no other fillRequest methods will + * called); return null if no XML was created and a usual process to gather it will be used + * + * @throws MobyException if an XML cannot be created + ******************************************************************************************************************/ + public String fillRequest() throws MobyException { + return null; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected String filterMobyResponseType(Object result) throws MobyException { + if ( result instanceof String ) + return ( String ) result; + else if ( result instanceof byte[] ) + return new String( ( byte[] ) result ); + else + throw new MobyException( + "The Biomoby data should be sent/received either as type String or base64/byte[]. " + + "But they are of type '" + result.getClass().getName() + "'." ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + protected String callBiomobyService(MobyServiceLocator locator, String xmlInput) throws MobyException { + + MobyService service = locator.getService(); + String serviceName = service.getName(); + boolean asBytes = locator.isAsBytes(); + String serviceEndpoint = service.getURL(); + int timeout = locator.getSuggestedTimeout(); + + try { + URL target = new URL( serviceEndpoint ); + AxisCall call = new AxisCall( target, timeout ); + // to allow service calls which need authentication + setAuthentication( call.getCall() ); + call.getCall().setSOAPActionURI( MobyService.BIOMOBY_SERVICE_URI + "#" + serviceName ); + + return filterMobyResponseType( call.doCall( MobyService.BIOMOBY_SERVICE_URI, serviceName, + new Object[]{sendingFilter( xmlInput, asBytes )} ) ); + } + catch ( MalformedURLException e ) { + throw new MobyException( "Service endpoint '" + serviceEndpoint + "' is not a valid URL." ); + } + catch ( GException e ) { + throw new MobyException( e.getMessage(), e ); + } + } + + /** + * Sets the authentication for the call. The default implementation does not do anything ! + * + * @param call + */ + protected void setAuthentication(Call call) { + return; + } + + // + protected Object sendingFilter(String input, boolean asBytes) { + if ( asBytes ) { + log.debug( "Data sent as a byte array" ); + return input.getBytes(); + } + else { + return input; + } + } + + /******************************************************************************************************************* + * Call a SOAP-based BioMoby service. In order to find what service to call and what are its characteristics (such + * as its endpoint) it will call method {@link #getServiceLocator} that should be implemented by a sub-class. + *

      + * + * Once it has the service locator, this class does one of the following, in this order: + *

        + * + *
      • The locator must contain at least a service name. If it does not, an exception is raised. + * + *
      • If the locator contains a service endpoint, a call is made to this endpoint, using also the service name as + * a method name. + * + *
      • If the locator has a registry endpoint, an enquiry to the registry is made to find an endpoint of a service + * corresponding with the given service name. Once found, the service is called. + * + *
      • The same as the previous one but using a default registry. + * + * @param xmlInput data will be sent to the called Biomoby service + * + * @return service response (still in XML) + * + * @throws MobyException (a) if service call (or a call to registry; for example because the registry does not know + * given service) fails, or (b) if the used {@link MobyServiceLocator} does not contain a service name. + * + ******************************************************************************************************************/ + public String callRemoteService(String xmlInput) throws MobyException { + + // 1) service name is a must + MobyServiceLocator locator = getServiceLocator(); + MobyService service = locator.getService(); + if ( service == null ) + throw new MobyException( "MobyService locator returned an empty service object.\n" + + "I do not know what service to call..." ); + String serviceName = service.getName(); + if ( isEmpty( serviceName ) || MobyService.DUMMY_NAME.equals( serviceName ) ) + throw new MobyException( "MobyService locator returned an empty service name.\n" + + "I do not know what service to call..." ); + + // 2) try service endpoint + String serviceEndpoint = service.getURL(); + if ( notEmpty( serviceEndpoint ) ) + return callBiomobyService( locator, xmlInput ); + + // 3) find service endpoint in a Biomoby registry + Central worker = new CentralImpl( locator.getRegistryEndpoint(), locator.getRegistryNamespace() ); + MobyService[] services = worker.findService( service ); + if ( services == null || services.length == 0 ) + throw new MobyException( "Service " + service.toShortString() + " is not known in Biomoby registry: \n" + + "\t" + worker.getRegistryEndpoint() + "\n" + "\t" + worker.getRegistryNamespace() ); + // ...and call the service + serviceEndpoint = services[ 0 ].getURL(); + if ( notEmpty( serviceEndpoint ) ) { + service.setURL( serviceEndpoint ); + return callBiomobyService( locator, xmlInput ); + } + + // what else can I do? + throw new MobyException( "Registry has not returned any URL for service " + service.toShortString() ); + } + + /******************************************************************************************************************* + * Fill the whole 'mobyInput' - put there any number of jobs (queries) as you wish (you do not need to follow the + * 'jobCount' hint suggesting how many jobs should be put there). + *

        + * + * Usually there is not need to overwrite this method. It serves as an inter-mediator between the main + * {@link #process} method and the individual request fillings (done by a sub-class in method + * {@link #fillRequest(MobyJob,MobyPackage)}). + *

        + * + * @return false if you wish to cancel whole request (nothing will be sent to a Biomoby service); otherwise return + * true. + * + * @param mobyInput is an empty shell that you are supposed to fill with the input data for a Biomoby service + * execution + * + * @param jobCount is only a suggestion how many requests/job should be created (it comes from the {@link #process} + * method) - but it does not need to be obeyed + * + ******************************************************************************************************************/ + public boolean fillRequest(MobyPackage mobyInput, int jobCount) throws MobyException { + + if ( jobCount < 0 ) + jobCount = 0; + for ( int i = 0; i < jobCount; i++ ) { + MobyJob request = new MobyJob( "job_" + i ); + if ( !fillRequest( request, mobyInput ) ) + break; + mobyInput.addJob( request ); + } + return ( mobyInput.size() > 0 ); + } + + /******************************************************************************************************************* + * A raw-level processing. Use it if you need access to raw XML coming from a service. + *

        + * + * @param xmlResponse is a raw XML response returned from a BioMoby service + * + * @return false if the response should be considered fully processed (in this case no other 'useResponse' will be + * called); true indicates that normal processing of the response will follow; by default, this class (BaseClient) + * returns true + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'mobyResponse' is broken + ******************************************************************************************************************/ + public boolean useResponse(String xmlResponse) throws MobyException { + return true; + } + + /******************************************************************************************************************* + * A high-level processing. Use it if you need access to all jobs (queries) - that returned from a service - in the + * same time. Otherwise use the processing on the job level (method {@link #useResponse(MobyJob,MobyPackage)}. + *

        + * + * @param mobyResponse is a full response returned from a BioMoby service + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'mobyResponse' is broken + ******************************************************************************************************************/ + public void useResponse(MobyPackage mobyResponse) throws MobyException { + + // iterate over all input jobs + for ( int i = 0; i < mobyResponse.size(); i++ ) { + if ( !useResponse( mobyResponse.getJob( i ), mobyResponse ) ) + return; + } + } + + /******************************************************************************************************************* + * Extracts errors from a raw service response. It is iseful when one does not want to create a whole + * MobyPackage from a response, but just find whether a response is good or bad. + *

        + * + * @param xmlResponse is a full response returned from a BioMoby service + * + * @return a slightly formatted list of exceptions (of severity error) extracted from the response; or + * null if there are no errors there + ******************************************************************************************************************/ + public String errorsInResponse(String xmlResponse) { + try { + StringBuffer buf = new StringBuffer(); + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build( new StringReader( xmlResponse ) ); + Element root = doc.getRootElement(); + Element mobyContent = JDOMUtils.getChild( root, MobyTags.MOBYCONTENT ); + Element serviceNotes = JDOMUtils.getChild( mobyContent, MobyTags.SERVICENOTES ); + ServiceException[] exceptions = ServiceException.extractExceptions( serviceNotes ); + for ( int i = 0; i < exceptions.length; i++ ) { + if ( exceptions[ i ].getSeverity() != ServiceException.ERROR ) + continue; + if ( buf.length() > 0 ) + buf.append( "\n" ); + buf.append( exceptions[ i ].getErrorCodeAsString() ); + buf.append( ": " ); + buf.append( exceptions[ i ].getMessage() ); + } + return ( buf.length() == 0 ? null : new String( buf ) ); + + } + catch ( Exception e ) { + return e.toString(); + } + } + + // + // Abstract methods + // + + /******************************************************************************************************************* + * Return characteristics of a BioMoby service that will be called, and that reveal where to find such service. + *

        + * + * @see #callRemoteService + * + * @return an object defining a location of a BioMoby service + * @throws MobyException if service locator cannot be returned/created (e.g. because there is not enough information + * about what service to call) + ******************************************************************************************************************/ + abstract public MobyServiceLocator getServiceLocator() throws MobyException; + + /******************************************************************************************************************* + * Crate data (fill them into 'request') for one Moby job (query). The request will be sent within given + * 'inputContext' - but it is not yet there (because you may wish not to put it there - see the return value), and + * it is not the task of this method to put it there (just fill the 'request'). + *

        + * + * This is a method that should be implemented by a client developer, and it is the place where the client's + * business logic sits. + *

        + * + * @return true if this request should be included into the input data (package) that will be sent to a biomoby + * service; or return false if you do not wish to create any more requests for this particular package (also + * this 'request' will not be used) + * + * @param request is an object that you are supposed to fill with input data for one service invocation; it already + * has a name (so called 'query id' in the BioMoby speak) but you are free to change it + * + * @param inputContext is an envelope where all requests will be stored and sent to a Biomoby service; you do not + * need to do anything with it here unless you wish; note that all already created requests are there, + * but not the one you are just creating in this method + * + * @throws MobyException if you need so (from whatever reason in your business logic); if thrown then nothing will + * be sent to a Biomoby service + * + ******************************************************************************************************************/ + abstract public boolean fillRequest(MobyJob request, MobyPackage inputContext) throws MobyException; + + /******************************************************************************************************************* + * Process a single job returned from a BioMoby service. + *

        + * + * This is a method that should be implemented by a client developer, and it is the place where the client's + * business logic using the response sits. + *

        + * + * @param response is an object that you are supposed to use + * + * @param responseContext is an envelope where the full response (all its jobs) is located; you do not need to do + * anything with it here unless you wish (e.g. it gives you knowledge about how many jobs are in the full + * response, or it gives you access to the so-called 'service notes') + * + * @return false if you do not wish to get any more responses/jobs; otherwise return true + * + * @throws MobyException if you are not satisfied with a response data, or from whatever reasons; it also throws + * this exception if the 'response' is broken + * + ******************************************************************************************************************/ + abstract public boolean useResponse(MobyJob response, MobyPackage responseContext) throws MobyException; + +} From groscurt at dev.open-bio.org Wed Nov 26 08:54:21 2008 From: groscurt at dev.open-bio.org (Andreas Groscurth) Date: Wed, 26 Nov 2008 03:54:21 -0500 Subject: [MOBY-guts] biomoby commit Message-ID: <200811260854.mAQ8sLbO017586@dev.open-bio.org> groscurt Wed Nov 26 03:54:21 EST 2008 Update of /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard In directory dev.open-bio.org:/tmp/cvs-serv17543/src/main/org/biomoby/service/dashboard Modified Files: SimpleClientPanel.java ServiceCallerModel.java DashboardProperties.java Log Message: changes done to enable authentication handling moby-live/Java/src/main/org/biomoby/service/dashboard SimpleClientPanel.java,1.12,1.13 ServiceCallerModel.java,1.6,1.7 DashboardProperties.java,1.29,1.30 =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java,v retrieving revision 1.12 retrieving revision 1.13 diff -u -r1.12 -r1.13 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java 2008/05/27 16:06:14 1.12 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/SimpleClientPanel.java 2008/11/26 08:54:21 1.13 @@ -1,774 +1,791 @@ -// SimpleClientPanel.java -// -// Created: December 2005 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.service.dashboard; - -import org.tulsoft.shared.UUtils; -import org.tulsoft.tools.gui.SwingUtils; -import org.tulsoft.tools.gui.AwtUtils; -import org.tulsoft.tools.gui.JFileChooserWithHistory; -import org.tulsoft.tools.gui.JTextFieldWithHistory; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.MobyDataType; -import org.biomoby.service.dashboard.data.ServiceInputPanel; -import org.biomoby.service.dashboard.data.DataContainer; - -import javax.swing.JPanel; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JRadioButton; -import javax.swing.ButtonGroup; -import javax.swing.JCheckBox; -import javax.swing.JSplitPane; -import javax.swing.JComponent; -import javax.swing.Box; -import javax.swing.tree.DefaultMutableTreeNode; - -import java.awt.GridBagLayout; -import java.awt.Component; -import java.awt.Color; -import java.awt.Font; -import java.awt.Insets; -import java.awt.Dimension; -import java.awt.event.KeyEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; - -import java.io.File; -import java.util.Date; - -/** - * A panel allowing to formulate input data and to call an arbitrary - * Biomoby service. Its interface is however not that user-friendly, - * and it is supposed to be used more or less for testing purposes in - * time when a new service is being created and developed.

        - * - * @author Martin Senger - * @version $Id$ - */ - -public class SimpleClientPanel - extends AbstractPanel { - - private static org.apache.commons.logging.Log log = - org.apache.commons.logging.LogFactory.getLog (SimpleClientPanel.class); - - /** A property name. Its value contains a name of color that will - * be used to display service name. - */ - protected static final String P_S_TITLE_COLOR = "simpleclient.service.title.color"; - - /** A property name. Its value contains a name of color that will - * be used as background for editable console with XML input. - */ - protected static final String P_S_EDIT_BGCOLOR = "simpleclient.service.edit.bgcolor"; - - // some texts - protected static final String INIT_SELECT = - "

        Start by selecting a service
        " + - "that you wish to call.
        "; - - protected static final String CALLER_ERROR = - "Sorry, an error happened when calling a service.\n\n"; - - protected static final Insets BREATH_UP = new Insets (6,6,0,6); - protected static final Insets BREATH_DOWN = new Insets (0,6,6,6); - - // associated models working behind the scene - RegistryModel registryModel; - ServiceCallerModel callerModel; - - // components that are used from more methods - JLabel selService; - CommonConsole input; - JFileChooserWithHistory outFile, inFile; - JButton runButton, stopButton; - JCheckBox iShowXML, iFromFile; - JTextFieldWithHistory className, endpoint; - JPanel dataTablesPanel; - ServiceInputPanel inputDataTables; - MySwingWorker runWorker; - ResultsPanel results; - JComponent resultsComp; - JSplitPane resSplit; -// JTextFieldWithHistory recentServices; - - boolean selectionAllowed = false; - - // shared icons - protected static Icon runIcon, runIconDis; - protected static Icon stopIcon, stopIconDis; - protected static Icon addDataIcon, addDataIconDis; - - /********************************************************************* - * Default constructor. - ********************************************************************/ - public SimpleClientPanel() { - super(); - panelIconFileName = "images/debug.gif"; - } - - /********************************************************************* - * Load shared icons. - ********************************************************************/ - protected void loadIcons() { - super.loadIcons(); - - if (runIcon == null) runIcon = loadIcon ("images/smallRun.gif"); - if (runIconDis == null) runIconDis = loadIcon ("images/smallRun_dis.gif"); - - if (stopIcon == null) stopIcon = loadIcon ("images/smallCancel.gif"); - if (stopIconDis == null) stopIconDis = loadIcon ("images/smallCancel_dis.gif"); - - if (addDataIcon == null) addDataIcon = loadIcon ("images/smallAnnotate.gif"); - if (addDataIconDis == null) addDataIconDis = loadIcon ("images/smallAnnonate_dis.gif"); - - } - - /************************************************************************** - * - **************************************************************************/ - public JComponent getComponent (PropertyChannel aPropertyChannel) { - setPropertyChannel (aPropertyChannel); - registryModel = createRegistryModel(); - callerModel = new ServiceCallerModel(); - callerModel.setPropertyChannel (aPropertyChannel); - - if (pComponent != null) return pComponent; - pComponent = new JPanel (new GridBagLayout(), true); - - // result panel - results = new ResultsPanel(); - resultsComp = results.getComponent (aPropertyChannel); - propertyChannel.addPropertyChangeListener (new PropertyChangeListener() { - public void propertyChange (PropertyChangeEvent e) { - if (DP_DETACH_VIEW.equals (e.getPropertyName())) { - - MobyService srv = - (MobyService)propertyChannel.get (DP_SC_SERVICE); - String title = (srv == null ? "Service results" : - srv.getName() + " at " + new Date()); - JComponent current = results.getComponent (propertyChannel); - results.adjustForDetachement(); - JFrame newFrame = - SwingUtils.createSoftMainFrame (current, - title); - Dimension dim = current.getPreferredSize(); - SwingUtils.showMainFrameRelativeTo - (pComponent, newFrame, (int)dim.getWidth(), (int)dim.getHeight()); - results = new ResultsPanel(); - resultsComp = results.getComponent (propertyChannel); - resSplit.setBottomComponent (resultsComp); - } - }}); - - - // panel with all the fields (except for building inputs) - JPanel controls = getControlPanel(); - - // panel with input data - JPanel inputData = getInputPanel(); - updateInputDataPanel (INIT_SELECT); - - // service ontology tree - JPanel sBoard = new JPanel (new GridBagLayout()); -// JLabel lRecent = new JLabel ("Recently called services"); -// recentServices = createText (null, -// DP_SC_SERVICES, -// DP_SC_SERVICES); -// recentServices.addActionListener (new ActionListener() { -// public void actionPerformed (ActionEvent e) { -// String contents = ((JTextFieldWithHistory)e.getSource()).getText(); -// if (! "".equals (contents) && selectionAllowed) { -// System.out.println ("SEL: " + contents); -// selectService (contents); -// } -// } -// }); - - ServicesBoard servicesBoard = - new ServicesBoard (registryModel, - null, - propertyChannel, - new CustomServicesTree (registryModel, - null)); - log.debug ("Services tree update started"); - servicesBoard.updateTree (CommonTree.SORTED_BY_AUTHORITY); -// SwingUtils.addComponent (sBoard, lRecent, 0, 0, 1, 1, NONE, NWEST, 0.0, 0.0, BREATH_UP); -// SwingUtils.addComponent (sBoard, recentServices, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0, BREATH_DOWN); - SwingUtils.addComponent (sBoard, servicesBoard, 0, 2, 1, 1, BOTH, NWEST, 1.0, 1.0); - - // split it into moving panels - JSplitPane split = hSplit (resSplit = vSplit (hSplit (controls, - sBoard, 0.5), - resultsComp, 0.1), - inputData, - 0.5); - - SwingUtils.addComponent (pComponent, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - - // initialize by a last used service name from preferences - String lastServiceName = getPrefValue (DP_SC_SERVICE_NAME, ""); - if (! "".equals (lastServiceName)) - selectService (lastServiceName); - - return pComponent; - } - - /************************************************************************** - * Create a sub-panel for all the controls... - **************************************************************************/ - protected JPanel getControlPanel() { - JPanel p = new JPanel (new GridBagLayout()); - - // (selected) service name - selService = new JLabel(); - selService.setFont (FAT_BORDER_FONT); - selService.setForeground - (GraphColours.getColour (DashboardConfig.getString (P_S_TITLE_COLOR, null), - Color.blue)); - - // how to invoke the service - JPanel howTo = createTitledPanel ("Service invocation"); - endpoint = createText (null, DP_ENDPOINT, DP_ENDPOINT); - className = createText (null, DP_IMPL_CLASS, DP_IMPL_CLASS); - - ButtonGroup group = new ButtonGroup(); - JRadioButton htNone, htRegistry, htEndpoint, htLocal, htNewURL; - group.add (htEndpoint = createHowToButton ("Use service's usual endpoint", DP_CS_URL)); - htNone = createHowToButton ("No real call, just show/echo input", DP_CS_NONE); - htNone.addItemListener( - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - if (enabled) runButton.setText(" Show Input "); - else { - if (propertyChannel.getBoolean(DP_INP_PING, false)){ - runButton.setText(" Ping Service "); - } - else { - runButton.setText(" Call Service "); - } - } - } - }); - group.add (htNone); - group.add (htRegistry = createHowToButton ("Ask registry where service is, and call it", DP_CS_REGISTRY)); - group.add (htNewURL = createHowToButton ("Use this endpoint", DP_CS_NEWURL)); - group.add (htLocal = createHowToButton ("Use this local class", DP_CS_CLASS)); - - // run the service - // determine button text from preferences - boolean usingPing = getPrefValue (DP_INP_PING, false); - boolean usingAsBytes = getPrefValue (DP_INP_ASBYTES, false); - String runLabel = " Call Service "; - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runLabel = " Show Input "; - else if (usingPing) runLabel = " Ping Service "; - - runButton = - createButton (runLabel, - "Invoke selected service", - KeyEvent.VK_C, - new ActionListener() { - public void actionPerformed (ActionEvent e) { - MobyService srv = (MobyService)propertyChannel.get (DP_SC_SERVICE); - if (srv != null) { - runWorker = new MySwingWorker (srv); - runWorker.start(); - } - } - }); - runButton.setIcon (runIcon); - runButton.setDisabledIcon (runIconDis); - runButton.setEnabled (false); // will enable when a service is selected - - stopButton = - createButton (" Stop service ", - "Cancel connection to a running service", - KeyEvent.VK_S, - new ActionListener() { - public void actionPerformed (ActionEvent e) { - if (runWorker != null) { -// runWorker.interrupt(); // no sense with the current Biomoby API - runWorker.cancel(); - } - serviceFinished(); - } - }); - stopButton.setIcon (stopIcon); - stopButton.setDisabledIcon (stopIconDis); - stopButton.setEnabled (false); // will enable when a service is called - - JPanel buttonPanel = createButtonPanel (new JButton[] { runButton, - stopButton }); - - JCheckBox asPing = createCheckBox - ("'Ping' this service", - usingPing, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPropertySelect (enabled, DP_INP_PING); - setPrefValue (DP_INP_PING, enabled); - propertyChannel.put (DP_INP_PING, - new Boolean (enabled).toString()); - if (enabled) { - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runButton.setText(" Show Input "); - else - runButton.setText(" Ping Service "); - } - else { - if (propertyChannel.getString(DP_CALL_SERVICE).equals(DP_CS_NONE)) - runButton.setText(" Show Input "); - else - runButton.setText(" Call Service "); - } - } - }); - setPropertySelect (usingPing, DP_INP_PING); - asPing.setToolTipText ("A Moby 'Ping' is used to determine if the service is responsive " + - "and if it responds in an API-compliant manner."); - Font font = asPing.getFont(); - asPing.setFont (font.deriveFont (Math.max (1, font.getSize2D() - 1))); - - JCheckBox asBytes = createCheckBox - ("Send data to service as a byte array", - usingAsBytes, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPropertySelect (enabled, DP_INP_ASBYTES); - setPrefValue (DP_INP_ASBYTES, enabled); - propertyChannel.put (DP_INP_ASBYTES, - new Boolean (enabled).toString()); - } - }); - setPropertySelect (usingAsBytes, DP_INP_ASBYTES); - asBytes.setToolTipText ("It should not have any effect on result; it is for debugging"); - font = asBytes.getFont(); - asBytes.setFont (font.deriveFont (Math.max (1, font.getSize2D() - 1))); - - - SwingUtils.addComponent (howTo, htEndpoint, 0, 0, 2, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htNewURL, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, endpoint, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htRegistry, 0, 2, 2, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, htLocal, 0, 3, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, className, 1, 3, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (howTo, htNone, 0, 4, 2, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (howTo, asPing, 0, 5, 2, 1, NONE, NWEST, 0.0, 0.0, BREATH_TOP); - SwingUtils.addComponent (howTo, asBytes, 0, 6, 2, 1, NONE, NWEST, 0.0, 0.0); - - - Component glue = Box.createVerticalGlue(); - SwingUtils.addComponent (p, selService, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0); - SwingUtils.addComponent (p, howTo, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (p, buttonPanel, 0, 2, 1, 1, NONE, CENTER, 0.0, 0.0, BREATH_TOP); - SwingUtils.addComponent (p, glue, 0, 3, 1, 1, VERT, NWEST, 0.0, 1.0); - return p; - } - - /************************************************************************** - * Select/unselect using 'send as bytes' or 'ping'... - **************************************************************************/ - protected void setPropertySelect (boolean enabled, String property) { - setPrefValue (property, enabled); - propertyChannel.put (property, new Boolean (enabled).toString()); - } - - /************************************************************************** - * Create a specialized radio button - for various ways how to - * call a service. - **************************************************************************/ - private JRadioButton createHowToButton (String title, String howTo) { - JRadioButton radio = new JRadioButton (title); - radio.setActionCommand (howTo); - radio.addActionListener (howToListener); - String initHowTo = getPrefValue (DP_CALL_SERVICE, DP_CS_NONE); - if (howTo.equals (initHowTo)) { - radio.setSelected (true); - radio.setEnabled (true); - propertyChannel.put (DP_CALL_SERVICE, howTo); - } - endpoint.setEnabled (initHowTo.equals (DP_CS_NEWURL)); - className.setEnabled (initHowTo.equals (DP_CS_CLASS)); - return radio; - } - - // - private ActionListener howToListener = new ActionListener() { - public void actionPerformed (ActionEvent e) { - String howTo = e.getActionCommand(); - setPrefValue (DP_CALL_SERVICE, howTo); - propertyChannel.put (DP_CALL_SERVICE, howTo); - endpoint.setEnabled (howTo.equals (DP_CS_NEWURL)); - className.setEnabled (howTo.equals (DP_CS_CLASS)); - } - }; - - /************************************************************************** - * Create a specialized check box for "what to do with input/output"... - **************************************************************************/ - private JCheckBox createDataBox (String title, - final String preferenceKey, - boolean defaultValue) { - boolean initValue = getPrefValue (preferenceKey, defaultValue); - propertyChannel.put (preferenceKey, - new Boolean (initValue).toString()); - return createCheckBox - (title, initValue, -1, - new ItemListener() { - public void itemStateChanged (ItemEvent e) { - boolean enabled = (e.getStateChange() == ItemEvent.SELECTED); - setPrefValue (preferenceKey, enabled); - propertyChannel.put (preferenceKey, - new Boolean (enabled).toString()); - inFile.setEnabled (iFromFile.isSelected()); - } - }); - } - - /************************************************************************** - * Create a sub-panel for service inputs... - **************************************************************************/ - protected JPanel getInputPanel() { - JPanel inputData = new JPanel (new GridBagLayout()); - inputData.setBorder (createFatBorder - ("Service Input Data", - GraphColours.getColour ("cadetblue", Color.blue))); - - // upper part (tables, input file, show-xml check-box) - JPanel upper = new JPanel (new GridBagLayout()); - - dataTablesPanel = new JPanel (new GridBagLayout()); - - iFromFile = createDataBox ("Take an input from this XML file", DP_SC_IN_FILE, false); - inFile = createFileSelector ("Select input XML for calling a service", - "Select", - null, - DP_SC_INPUT_FILE, - DP_SC_INPUT_FILE); - inFile.setEnabled (iFromFile.isSelected()); - - iShowXML = createDataBox ("Show input as XML", DP_INP_SHOWXML, true); - - SwingUtils.addComponent (upper, dataTablesPanel, 0, 0, 2, 1, BOTH, NWEST, 1.0, 1.0); - SwingUtils.addComponent (upper, iFromFile, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0); - SwingUtils.addComponent (upper, inFile, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0); - SwingUtils.addComponent (upper, iShowXML, 0, 2, 1, 1, NONE, NWEST, 0.0, 0.0); - - // lower part (console showing/editing input XML) - input = new EditableConsole(); - input.setAppendMode (false); - input.setVerboseMode (false); - - // split upper and lower parts into moving panels - JSplitPane split = vSplit (upper, input, 0.5); - SwingUtils.addComponent (inputData, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - return inputData; - } - - class EditableConsole - extends CommonConsole { - - public EditableConsole() { - super(); - textArea.setEditable (true); - textArea.setBackground - (GraphColours.getColour (DashboardConfig.getString (P_S_EDIT_BGCOLOR, null), - textArea.getBackground())); - } - } - - /************************************************************************** - * Replace the global 'dataTablesPanel' with an information text. - **************************************************************************/ - protected void updateInputDataPanel (String info) { - dataTablesPanel.removeAll(); - AwtUtils.redisplay (dataTablesPanel); - - JLabel text = new JLabel (info); - SwingUtils.addComponent (dataTablesPanel, text, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0); - dataTablesPanel.validate(); - return; - } - - /************************************************************************** - * Replace the global 'dataTablesPanel' with fields defining the - * input data for the given service. - **************************************************************************/ - protected void updateInputDataPanel (MobyService service, - MobyDataType[] dataTypes) { - dataTablesPanel.removeAll(); - - inputDataTables = new ServiceInputPanel (service, dataTypes); - SwingUtils.addComponent (dataTablesPanel, inputDataTables, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0); - dataTablesPanel.validate(); - } - - /************************************************************************** - * Find 'dataTypeToBeFound in 'dataTypes' and return it. The same - * could be achieved by calling registryModel.getDataType() but - * here I do not want to create yet another swing worker for it. - **************************************************************************/ - protected MobyDataType findDataType (String dataTypeToBeFound, - MobyDataType[] dataTypes) { - for (int i = 0; i < dataTypes.length; i++) { - if (dataTypeToBeFound.equals (dataTypes[i].getName())) - return dataTypes[i]; - } - log.error ("Strange, data type '" + dataTypeToBeFound + - "' was not found in " + dataTypes.length + " data types."); - return null; - } - - /************************************************************************** - * - * A worker that calls the service... - * - **************************************************************************/ - class MySwingWorker - extends SwingWorker { - - MobyException exception = null; - DataContainer data = new DataContainer(); - boolean wasCancelled = false; - MobyService service; - - public MySwingWorker (MobyService service) { - super(); - this.service = service; - data.setMetadata (propertyChannel); - } - - public void cancel() { - wasCancelled = true; - propertyChannel.fire (DP_STATUS_MSG, "Service invocation cancelled."); - } - - public Object construct() { - try { - runButton.setEnabled (false); - propertyChannel.fire (DP_STATUS_MSG, - "Calling service " + service.getName() + "..."); - - // create a data container with input data... - if (propertyChannel.getBoolean (DP_SC_IN_FILE, false)) { - - // ...either from a file - String inputFile = propertyChannel.getString (DP_SC_INPUT_FILE); - if (UUtils.isEmpty (inputFile)) - throw new MobyException ("No input XML file given."); - data.setDataFromFile (new File (inputFile)); - - } else { - data.setData (inputDataTables.toXML()); - } - - // optionally, show XML data: we want to show this XML - // input only (a) if it was explicitly asked for (property - // DP_INP_SHOWXML is true), or (b) if "no real service - // call" was selected (property DP_CALL_SERVICE has value - // DP_CS_NONE) - if ( DP_CS_NONE.equals (propertyChannel.getString (DP_CALL_SERVICE)) || - (propertyChannel.getBoolean (DP_INP_SHOWXML, false)) ) { - input.setText ((String)data.getData()); - } - - // If we are only pinging the service, set the data object to an empty message - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - String emptyMsg = "\n" + - "\n" + - " \n" + - ""; - data.setData(emptyMsg); - input.setText(emptyMsg); - } - - // finally, call the service - stopButton.setEnabled (true); - callerModel.runIt (data); - - } catch (MobyException e) { - exception = e; - - } catch (Error e) { - exception = new MobyException (e.toString()); - } - return null; // not used here - } - - // runs on the event-dispatching thread - public void finished() { - if (wasCancelled) { - // service was interrupted by the Stop button - do - // nothing (the whole GUI should be already in a good - // state - the button 'Stop' took care about it) - return; - } - - if (exception == null) { - - // handle results here (using renderers...) - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - propertyChannel.fire (DP_STATUS_MSG, service.getName()+" isAlive."); - } else { - propertyChannel.fire (DP_STATUS_MSG, "Service invocation finished."); - } - - if (! DP_CS_NONE.equals (propertyChannel.getString (DP_CALL_SERVICE))) { - results.updateComponent (data); - } - - } else { - if (propertyChannel.getString(DP_INP_PING).toLowerCase().equals("true")) { - propertyChannel.fire (DP_STATUS_MSG, service.getName()+" is dead."); - results.removeResults(); - } else { - propertyChannel.fire (DP_STATUS_MSG, "Service invocation failed."); - error (CALLER_ERROR, exception); - } - exception.printStackTrace(); - } - serviceFinished(); - } - } - - /************************************************************************** - * Called when a call to a service finished. - **************************************************************************/ - protected void serviceFinished() { - runButton.setEnabled (true); - stopButton.setEnabled (false); - } - - /************************************************************************** - * Called when a service is selected in a service tree (or in a - * 'recently used services' combo box), and also at the beginning - * when a service name is retrieved from user preferences. - * - * Get selected service from a registry model and generate a new - * 'input data panel' to reflect input data of the selected - * service. - **************************************************************************/ - protected void selectService (final String serviceName) { - final Object source = this; - final SwingWorker worker = new SwingWorker() { - MobyService service; - MobyDataType[] dataTypes; - public Object construct() { - try { - service = registryModel.getService (serviceName); - dataTypes = registryModel.getDataTypes (source); - } catch (MobyException e) { - error (ServicesTree.SERVICES_ACCESS_ERROR, e); - } - return service; // not used here - } - - // runs on the event-dispatching thread. - public void finished() { - if (service == null) { - deselectService(); - } else { - updateInputDataPanel (service, dataTypes); - selService.setText (service.getName()); -// selectionAllowed = false; -// recentServices.setText (service.getName()); -// selectionAllowed = true; - propertyChannel.put (DP_SC_SERVICE, service); - runButton.setEnabled (true); - - } - } - }; - worker.start(); - } - - /************************************************************************** - * Called when no service is selected in order to display this - * fact on various places in the panel. - **************************************************************************/ - protected void deselectService() { - selService.setText (""); - updateInputDataPanel (INIT_SELECT); - propertyChannel.remove (DP_SC_SERVICE); - runButton.setEnabled (false); - } - - /************************************************************************** - * - **************************************************************************/ - public String getName() { - return "Simple Client"; - } - - /************************************************************************** - * - **************************************************************************/ - public String getDescription() { - return - "A panel allowing to create input data and to call an arbitrary Biomoby service. " + - "Its purpose is mostly for the service developers to test their new services."; - } - - /************************************************************************** - * - * Customized tree of services... - * - **************************************************************************/ - protected class CustomServicesTree - extends ServicesTree { - - /********************************************************************* - * Construtor - ********************************************************************/ - public CustomServicesTree (RegistryModel model, - CommonConsole console) { - super (model, console); - } - - /********************************************************************* - * - ********************************************************************/ - protected void createPopups (String title) { - super.createPopups (title); - removeFromPopups (AC_RELOAD); - removeSeparatorAfter (AC_COLLAPSE); - } - - /********************************************************************* - * Service selected in a service tree... - ********************************************************************/ - protected void selected (DefaultMutableTreeNode node) { - if (node == null) { - // nothing selected - deselectService(); - return; - } - updateInputDataPanel ("Loading..."); - selService.setText (""); - final CommonNode nodeObject = (CommonNode)node.getUserObject(); - String currentServiceName = nodeObject.getValue(); - selectService (currentServiceName); - setPrefValue (DP_SC_SERVICE_NAME, currentServiceName); - } - } - -} +// SimpleClientPanel.java +// +// Created: December 2005 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.service.dashboard; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.Date; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JRadioButton; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.tree.DefaultMutableTreeNode; + +import org.biomoby.service.dashboard.data.DataContainer; +import org.biomoby.service.dashboard.data.ServiceInputPanel; +import org.biomoby.shared.MobyDataType; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.tulsoft.shared.UUtils; +import org.tulsoft.tools.gui.AwtUtils; +import org.tulsoft.tools.gui.JFileChooserWithHistory; +import org.tulsoft.tools.gui.JTextFieldWithHistory; +import org.tulsoft.tools.gui.SwingUtils; + +/** + * A panel allowing to formulate input data and to call an arbitrary Biomoby service. Its interface is however not that + * user-friendly, and it is supposed to be used more or less for testing purposes in time when a new service is being + * created and developed. + *

        + * + * @author Martin Senger + * @version $Id$ + */ + +public class SimpleClientPanel extends AbstractPanel { + + private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory + .getLog( SimpleClientPanel.class ); + + /** + * A property name. Its value contains a name of color that will be used to display service name. + */ + protected static final String P_S_TITLE_COLOR = "simpleclient.service.title.color"; + + /** + * A property name. Its value contains a name of color that will be used as background for editable console with XML + * input. + */ + protected static final String P_S_EDIT_BGCOLOR = "simpleclient.service.edit.bgcolor"; + + // some texts + protected static final String INIT_SELECT = "

        Start by selecting a service
        " + + "that you wish to call.
        "; + + protected static final String CALLER_ERROR = "Sorry, an error happened when calling a service.\n\n"; + + protected static final Insets BREATH_UP = new Insets( 6, 6, 0, 6 ); + protected static final Insets BREATH_DOWN = new Insets( 0, 6, 6, 6 ); + + // associated models working behind the scene + RegistryModel registryModel; + ServiceCallerModel callerModel; + + // components that are used from more methods + JLabel selService; + CommonConsole input; + JFileChooserWithHistory outFile, inFile; + JButton runButton, stopButton; + JCheckBox iShowXML, iFromFile; + JTextFieldWithHistory className, endpoint; + JPanel dataTablesPanel; + ServiceInputPanel inputDataTables; + MySwingWorker runWorker; + ResultsPanel results; + JComponent resultsComp; + JSplitPane resSplit; + // JTextFieldWithHistory recentServices; + + boolean selectionAllowed = false; + + // shared icons + protected static Icon runIcon, runIconDis; + protected static Icon stopIcon, stopIconDis; + protected static Icon addDataIcon, addDataIconDis; + + /******************************************************************************************************************* + * Default constructor. + ******************************************************************************************************************/ + public SimpleClientPanel() { + super(); + panelIconFileName = "images/debug.gif"; + } + + /******************************************************************************************************************* + * Load shared icons. + ******************************************************************************************************************/ + protected void loadIcons() { + super.loadIcons(); + + if ( runIcon == null ) runIcon = loadIcon( "images/smallRun.gif" ); + if ( runIconDis == null ) runIconDis = loadIcon( "images/smallRun_dis.gif" ); + + if ( stopIcon == null ) stopIcon = loadIcon( "images/smallCancel.gif" ); + if ( stopIconDis == null ) stopIconDis = loadIcon( "images/smallCancel_dis.gif" ); + + if ( addDataIcon == null ) addDataIcon = loadIcon( "images/smallAnnotate.gif" ); + if ( addDataIconDis == null ) addDataIconDis = loadIcon( "images/smallAnnonate_dis.gif" ); + + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public JComponent getComponent( PropertyChannel aPropertyChannel ) { + setPropertyChannel( aPropertyChannel ); + registryModel = createRegistryModel(); + callerModel = new ServiceCallerModel(); + callerModel.setPropertyChannel( aPropertyChannel ); + + if ( pComponent != null ) return pComponent; + pComponent = new JPanel( new GridBagLayout(), true ); + + // result panel + results = new ResultsPanel(); + resultsComp = results.getComponent( aPropertyChannel ); + propertyChannel.addPropertyChangeListener( new PropertyChangeListener() { + public void propertyChange( PropertyChangeEvent e ) { + if ( DP_DETACH_VIEW.equals( e.getPropertyName() ) ) { + + MobyService srv = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + String title = ( srv == null ? "Service results" : srv.getName() + " at " + new Date() ); + JComponent current = results.getComponent( propertyChannel ); + results.adjustForDetachement(); + JFrame newFrame = SwingUtils.createSoftMainFrame( current, title ); + Dimension dim = current.getPreferredSize(); + SwingUtils.showMainFrameRelativeTo( pComponent, newFrame, ( int ) dim.getWidth(), ( int ) dim + .getHeight() ); + results = new ResultsPanel(); + resultsComp = results.getComponent( propertyChannel ); + resSplit.setBottomComponent( resultsComp ); + } + } + } ); + + // panel with all the fields (except for building inputs) + JPanel controls = getControlPanel(); + + // panel with input data + JPanel inputData = getInputPanel(); + updateInputDataPanel( INIT_SELECT ); + + // service ontology tree + JPanel sBoard = new JPanel( new GridBagLayout() ); + // JLabel lRecent = new JLabel ("Recently called services"); + // recentServices = createText (null, + // DP_SC_SERVICES, + // DP_SC_SERVICES); + // recentServices.addActionListener (new ActionListener() { + // public void actionPerformed (ActionEvent e) { + // String contents = ((JTextFieldWithHistory)e.getSource()).getText(); + // if (! "".equals (contents) && selectionAllowed) { + // System.out.println ("SEL: " + contents); + // selectService (contents); + // } + // } + // }); + + ServicesBoard servicesBoard = new ServicesBoard( registryModel, null, propertyChannel, new CustomServicesTree( + registryModel, null ) ); + log.debug( "Services tree update started" ); + servicesBoard.updateTree( CommonTree.SORTED_BY_AUTHORITY ); + // SwingUtils.addComponent (sBoard, lRecent, 0, 0, 1, 1, NONE, NWEST, 0.0, 0.0, BREATH_UP); + // SwingUtils.addComponent (sBoard, recentServices, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0, BREATH_DOWN); + SwingUtils.addComponent( sBoard, servicesBoard, 0, 2, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + + // split it into moving panels + JSplitPane split = hSplit( resSplit = vSplit( hSplit( controls, sBoard, 0.5 ), resultsComp, 0.1 ), inputData, + 0.5 ); + + SwingUtils.addComponent( pComponent, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + + // initialize by a last used service name from preferences + String lastServiceName = getPrefValue( DP_SC_SERVICE_NAME, "" ); + if ( !"".equals( lastServiceName ) ) selectService( lastServiceName ); + + return pComponent; + } + + /******************************************************************************************************************* + * Create a sub-panel for all the controls... + ******************************************************************************************************************/ + protected JPanel getControlPanel() { + JPanel p = new JPanel( new GridBagLayout() ); + + // (selected) service name + selService = new JLabel(); + selService.setFont( FAT_BORDER_FONT ); + selService.setForeground( GraphColours.getColour( DashboardConfig.getString( P_S_TITLE_COLOR, null ), + Color.blue ) ); + + // how to invoke the service + JPanel howTo = createTitledPanel( "Service invocation" ); + endpoint = createText( null, DP_ENDPOINT, DP_ENDPOINT ); + className = createText( null, DP_IMPL_CLASS, DP_IMPL_CLASS ); + + ButtonGroup group = new ButtonGroup(); + JRadioButton htNone, htRegistry, htEndpoint, htLocal, htNewURL; + group.add( htEndpoint = createHowToButton( "Use service's usual endpoint", DP_CS_URL ) ); + htNone = createHowToButton( "No real call, just show/echo input", DP_CS_NONE ); + htNone.addItemListener( new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + if ( enabled ) + runButton.setText( " Show Input " ); + else { + if ( propertyChannel.getBoolean( DP_INP_PING, false ) ) { + runButton.setText( " Ping Service " ); + } + else { + runButton.setText( " Call Service " ); + } + } + } + } ); + group.add( htNone ); + group.add( htRegistry = createHowToButton( "Ask registry where service is, and call it", DP_CS_REGISTRY ) ); + group.add( htNewURL = createHowToButton( "Use this endpoint", DP_CS_NEWURL ) ); + group.add( htLocal = createHowToButton( "Use this local class", DP_CS_CLASS ) ); + + // run the service + // determine button text from preferences + boolean usingPing = getPrefValue( DP_INP_PING, false ); + boolean usingAsBytes = getPrefValue( DP_INP_ASBYTES, false ); + String runLabel = " Call Service "; + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runLabel = " Show Input "; + else if ( usingPing ) runLabel = " Ping Service "; + + runButton = createButton( runLabel, "Invoke selected service", KeyEvent.VK_C, new ActionListener() { + public void actionPerformed( ActionEvent e ) { + MobyService srv = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + if ( srv != null ) { + // if the authentication was selected a dialog opens to ask for the user/password + if ( propertyChannel.getBoolean( DP_AUTHENTICATION, false ) ) { + askForAuthentication(); + } + // if not make sure to remove any previous authentication + else { + propertyChannel.remove( DP_USER_AUTHENTICATION ); + propertyChannel.remove( DP_PASSWORD_AUTHENTICATION ); + } + runWorker = new MySwingWorker( srv ); + runWorker.start(); + } + } + } ); + runButton.setIcon( runIcon ); + runButton.setDisabledIcon( runIconDis ); + runButton.setEnabled( false ); // will enable when a service is selected + + stopButton = createButton( " Stop service ", "Cancel connection to a running service", KeyEvent.VK_S, + new ActionListener() { + public void actionPerformed( ActionEvent e ) { + if ( runWorker != null ) { + // runWorker.interrupt(); // no sense with the current Biomoby API + runWorker.cancel(); + } + serviceFinished(); + } + } ); + stopButton.setIcon( stopIcon ); + stopButton.setDisabledIcon( stopIconDis ); + stopButton.setEnabled( false ); // will enable when a service is called + + JPanel buttonPanel = createButtonPanel( new JButton[] { runButton, stopButton } ); + + JCheckBox asPing = createCheckBox( "'Ping' this service", usingPing, -1, new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPropertySelect( enabled, DP_INP_PING ); + setPrefValue( DP_INP_PING, enabled ); + propertyChannel.put( DP_INP_PING, new Boolean( enabled ).toString() ); + if ( enabled ) { + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runButton.setText( " Show Input " ); + else + runButton.setText( " Ping Service " ); + } + else { + if ( propertyChannel.getString( DP_CALL_SERVICE ).equals( DP_CS_NONE ) ) + runButton.setText( " Show Input " ); + else + runButton.setText( " Call Service " ); + } + } + } ); + setPropertySelect( usingPing, DP_INP_PING ); + asPing.setToolTipText( "A Moby 'Ping' is used to determine if the service is responsive " + + "and if it responds in an API-compliant manner." ); + Font font = asPing.getFont(); + asPing.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + JCheckBox asBytes = createCheckBox( "Send data to service as a byte array", usingAsBytes, -1, + new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPropertySelect( enabled, DP_INP_ASBYTES ); + setPrefValue( DP_INP_ASBYTES, enabled ); + propertyChannel.put( DP_INP_ASBYTES, new Boolean( enabled ).toString() ); + } + } ); + setPropertySelect( usingAsBytes, DP_INP_ASBYTES ); + asBytes.setToolTipText( "It should not have any effect on result; it is for debugging" ); + font = asBytes.getFont(); + asBytes.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + JCheckBox authenticationBox = createCheckBox( "Use a user/password for authentication", false, -1, + new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + propertyChannel.put( DP_AUTHENTICATION, e.getStateChange() == ItemEvent.SELECTED ); + } + } ); + authenticationBox.setToolTipText( "If the service requires authentication. " + + "A dialog will open if you call the service to enter the authentication." ); + font = authenticationBox.getFont(); + authenticationBox.setFont( font.deriveFont( Math.max( 1, font.getSize2D() - 1 ) ) ); + + SwingUtils.addComponent( howTo, htEndpoint, 0, 0, 2, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htNewURL, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, endpoint, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htRegistry, 0, 2, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, htLocal, 0, 3, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, className, 1, 3, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( howTo, htNone, 0, 4, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, asPing, 0, 5, 2, 1, NONE, NWEST, 0.0, 0.0, BREATH_TOP ); + SwingUtils.addComponent( howTo, asBytes, 0, 6, 2, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( howTo, authenticationBox, 0, 7, 2, 1, NONE, NWEST, 0.0, 0.0 ); + + Component glue = Box.createVerticalGlue(); + SwingUtils.addComponent( p, selService, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0 ); + SwingUtils.addComponent( p, howTo, 0, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( p, buttonPanel, 0, 2, 1, 1, NONE, CENTER, 0.0, 0.0, BREATH_TOP ); + SwingUtils.addComponent( p, glue, 0, 3, 1, 1, VERT, NWEST, 0.0, 1.0 ); + return p; + } + + /******************************************************************************************************************* + * Select/unselect using 'send as bytes' or 'ping'... + ******************************************************************************************************************/ + protected void setPropertySelect( boolean enabled, String property ) { + setPrefValue( property, enabled ); + propertyChannel.put( property, new Boolean( enabled ).toString() ); + } + + /******************************************************************************************************************* + * Opens a dialog and asks for webservice authentication + ******************************************************************************************************************/ + private void askForAuthentication() { + final JDialog dialog = new JDialog( new JFrame(), "Authentication", true ); + JPanel panel = new JPanel( new GridBagLayout() ); + panel.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ) ); + + Insets insets = new Insets( 4, 4, 4, 4 ); + + JLabel label = new JLabel( "Please enter your username and password !" ); + SwingUtils.addComponent( panel, label, 0, 0, 2, 1, HORI, CENTER, 1, 0, insets ); + + label = new JLabel( "User: " ); + SwingUtils.addComponent( panel, label, 0, 1, 1, 1, HORI, NWEST, 0, 0, insets ); + + final JTextField userField = new JTextField( propertyChannel.getString( DP_USER_AUTHENTICATION ), 20 ); + SwingUtils.addComponent( panel, userField, 1, 1, 1, 1, HORI, NWEST, 0, 0, insets ); + + label = new JLabel( "Password: " ); + SwingUtils.addComponent( panel, label, 0, 2, 1, 1, HORI, NWEST, 0, 0, insets ); + + final JPasswordField passwordField = new JPasswordField( + propertyChannel.getString( DP_PASSWORD_AUTHENTICATION ), 20 ); + SwingUtils.addComponent( panel, passwordField, 1, 2, 1, 1, HORI, NWEST, 0, 0, insets ); + + JButton button = new JButton( "Enter..." ); + button.addActionListener( new ActionListener() { + public void actionPerformed( ActionEvent e ) { + propertyChannel.put( DP_USER_AUTHENTICATION, userField.getText() ); + propertyChannel.put( DP_PASSWORD_AUTHENTICATION, passwordField.getPassword() ); + + dialog.setVisible( false ); + } + } ); + SwingUtils.addComponent( panel, button, 0, 3, 2, 1, HORI, CENTER, 0, 0, insets ); + + dialog.setContentPane( panel ); + dialog.pack(); + dialog.setLocationRelativeTo( this ); + dialog.setVisible( true ); + } + + /******************************************************************************************************************* + * Create a specialized radio button - for various ways how to call a service. + ******************************************************************************************************************/ + private JRadioButton createHowToButton( String title, String howTo ) { + JRadioButton radio = new JRadioButton( title ); + radio.setActionCommand( howTo ); + radio.addActionListener( howToListener ); + String initHowTo = getPrefValue( DP_CALL_SERVICE, DP_CS_NONE ); + if ( howTo.equals( initHowTo ) ) { + radio.setSelected( true ); + radio.setEnabled( true ); + propertyChannel.put( DP_CALL_SERVICE, howTo ); + } + endpoint.setEnabled( initHowTo.equals( DP_CS_NEWURL ) ); + className.setEnabled( initHowTo.equals( DP_CS_CLASS ) ); + return radio; + } + + // + private ActionListener howToListener = new ActionListener() { + public void actionPerformed( ActionEvent e ) { + String howTo = e.getActionCommand(); + setPrefValue( DP_CALL_SERVICE, howTo ); + propertyChannel.put( DP_CALL_SERVICE, howTo ); + endpoint.setEnabled( howTo.equals( DP_CS_NEWURL ) ); + className.setEnabled( howTo.equals( DP_CS_CLASS ) ); + } + }; + + /******************************************************************************************************************* + * Create a specialized check box for "what to do with input/output"... + ******************************************************************************************************************/ + private JCheckBox createDataBox( String title, final String preferenceKey, boolean defaultValue ) { + boolean initValue = getPrefValue( preferenceKey, defaultValue ); + propertyChannel.put( preferenceKey, new Boolean( initValue ).toString() ); + return createCheckBox( title, initValue, -1, new ItemListener() { + public void itemStateChanged( ItemEvent e ) { + boolean enabled = ( e.getStateChange() == ItemEvent.SELECTED ); + setPrefValue( preferenceKey, enabled ); + propertyChannel.put( preferenceKey, new Boolean( enabled ).toString() ); + inFile.setEnabled( iFromFile.isSelected() ); + } + } ); + } + + /******************************************************************************************************************* + * Create a sub-panel for service inputs... + ******************************************************************************************************************/ + protected JPanel getInputPanel() { + JPanel inputData = new JPanel( new GridBagLayout() ); + inputData + .setBorder( createFatBorder( "Service Input Data", GraphColours.getColour( "cadetblue", Color.blue ) ) ); + + // upper part (tables, input file, show-xml check-box) + JPanel upper = new JPanel( new GridBagLayout() ); + + dataTablesPanel = new JPanel( new GridBagLayout() ); + + iFromFile = createDataBox( "Take an input from this XML file", DP_SC_IN_FILE, false ); + inFile = createFileSelector( "Select input XML for calling a service", "Select", null, DP_SC_INPUT_FILE, + DP_SC_INPUT_FILE ); + inFile.setEnabled( iFromFile.isSelected() ); + + iShowXML = createDataBox( "Show input as XML", DP_INP_SHOWXML, true ); + + SwingUtils.addComponent( upper, dataTablesPanel, 0, 0, 2, 1, BOTH, NWEST, 1.0, 1.0 ); + SwingUtils.addComponent( upper, iFromFile, 0, 1, 1, 1, NONE, NWEST, 0.0, 0.0 ); + SwingUtils.addComponent( upper, inFile, 1, 1, 1, 1, HORI, NWEST, 1.0, 0.0 ); + SwingUtils.addComponent( upper, iShowXML, 0, 2, 1, 1, NONE, NWEST, 0.0, 0.0 ); + + // lower part (console showing/editing input XML) + input = new EditableConsole(); + input.setAppendMode( false ); + input.setVerboseMode( false ); + + // split upper and lower parts into moving panels + JSplitPane split = vSplit( upper, input, 0.5 ); + SwingUtils.addComponent( inputData, split, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + return inputData; + } + + class EditableConsole extends CommonConsole { + + public EditableConsole() { + super(); + textArea.setEditable( true ); + textArea.setBackground( GraphColours.getColour( DashboardConfig.getString( P_S_EDIT_BGCOLOR, null ), + textArea.getBackground() ) ); + } + } + + /******************************************************************************************************************* + * Replace the global 'dataTablesPanel' with an information text. + ******************************************************************************************************************/ + protected void updateInputDataPanel( String info ) { + dataTablesPanel.removeAll(); + AwtUtils.redisplay( dataTablesPanel ); + + JLabel text = new JLabel( info ); + SwingUtils.addComponent( dataTablesPanel, text, 0, 0, 1, 1, NONE, CENTER, 0.0, 0.0 ); + dataTablesPanel.validate(); + return; + } + + /******************************************************************************************************************* + * Replace the global 'dataTablesPanel' with fields defining the input data for the given service. + ******************************************************************************************************************/ + protected void updateInputDataPanel( MobyService service, MobyDataType[] dataTypes ) { + dataTablesPanel.removeAll(); + + inputDataTables = new ServiceInputPanel( service, dataTypes ); + SwingUtils.addComponent( dataTablesPanel, inputDataTables, 0, 0, 1, 1, BOTH, NWEST, 1.0, 1.0 ); + dataTablesPanel.validate(); + } + + /******************************************************************************************************************* + * Find 'dataTypeToBeFound in 'dataTypes' and return it. The same could be achieved by calling + * registryModel.getDataType() but here I do not want to create yet another swing worker for it. + ******************************************************************************************************************/ + protected MobyDataType findDataType( String dataTypeToBeFound, MobyDataType[] dataTypes ) { + for ( int i = 0; i < dataTypes.length; i++ ) { + if ( dataTypeToBeFound.equals( dataTypes[ i ].getName() ) ) return dataTypes[ i ]; + } + log.error( "Strange, data type '" + dataTypeToBeFound + "' was not found in " + dataTypes.length + + " data types." ); + return null; + } + + /******************************************************************************************************************* + * + * A worker that calls the service... + * + ******************************************************************************************************************/ + class MySwingWorker extends SwingWorker { + + MobyException exception = null; + DataContainer data = new DataContainer(); + boolean wasCancelled = false; + MobyService service; + + public MySwingWorker( MobyService service ) { + super(); + this.service = service; + data.setMetadata( propertyChannel ); + } + + public void cancel() { + wasCancelled = true; + propertyChannel.fire( DP_STATUS_MSG, "Service invocation cancelled." ); + } + + public Object construct() { + try { + runButton.setEnabled( false ); + propertyChannel.fire( DP_STATUS_MSG, "Calling service " + service.getName() + "..." ); + + // create a data container with input data... + if ( propertyChannel.getBoolean( DP_SC_IN_FILE, false ) ) { + + // ...either from a file + String inputFile = propertyChannel.getString( DP_SC_INPUT_FILE ); + if ( UUtils.isEmpty( inputFile ) ) throw new MobyException( "No input XML file given." ); + data.setDataFromFile( new File( inputFile ) ); + + } + else { + data.setData( inputDataTables.toXML() ); + } + + // optionally, show XML data: we want to show this XML + // input only (a) if it was explicitly asked for (property + // DP_INP_SHOWXML is true), or (b) if "no real service + // call" was selected (property DP_CALL_SERVICE has value + // DP_CS_NONE) + if ( DP_CS_NONE.equals( propertyChannel.getString( DP_CALL_SERVICE ) ) + || ( propertyChannel.getBoolean( DP_INP_SHOWXML, false ) ) ) { + input.setText( ( String ) data.getData() ); + } + + // If we are only pinging the service, set the data object to an empty message + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + String emptyMsg = "\n" + + "\n" + " \n" + + ""; + data.setData( emptyMsg ); + input.setText( emptyMsg ); + } + + // finally, call the service + stopButton.setEnabled( true ); + callerModel.runIt( data ); + + } + catch ( MobyException e ) { + exception = e; + + } + catch ( Error e ) { + exception = new MobyException( e.toString() ); + } + return null; // not used here + } + + // runs on the event-dispatching thread + public void finished() { + if ( wasCancelled ) { + // service was interrupted by the Stop button - do + // nothing (the whole GUI should be already in a good + // state - the button 'Stop' took care about it) + return; + } + + if ( exception == null ) { + + // handle results here (using renderers...) + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + propertyChannel.fire( DP_STATUS_MSG, service.getName() + " isAlive." ); + } + else { + propertyChannel.fire( DP_STATUS_MSG, "Service invocation finished." ); + } + + if ( !DP_CS_NONE.equals( propertyChannel.getString( DP_CALL_SERVICE ) ) ) { + results.updateComponent( data ); + } + + } + else { + if ( propertyChannel.getString( DP_INP_PING ).toLowerCase().equals( "true" ) ) { + propertyChannel.fire( DP_STATUS_MSG, service.getName() + " is dead." ); + results.removeResults(); + } + else { + propertyChannel.fire( DP_STATUS_MSG, "Service invocation failed." ); + error( CALLER_ERROR, exception ); + } + exception.printStackTrace(); + } + serviceFinished(); + } + } + + /******************************************************************************************************************* + * Called when a call to a service finished. + ******************************************************************************************************************/ + protected void serviceFinished() { + runButton.setEnabled( true ); + stopButton.setEnabled( false ); + } + + /******************************************************************************************************************* + * Called when a service is selected in a service tree (or in a 'recently used services' combo box), and also at the + * beginning when a service name is retrieved from user preferences. + * + * Get selected service from a registry model and generate a new 'input data panel' to reflect input data of the + * selected service. + ******************************************************************************************************************/ + protected void selectService( final String serviceName ) { + final Object source = this; + final SwingWorker worker = new SwingWorker() { + MobyService service; + MobyDataType[] dataTypes; + + public Object construct() { + try { + service = registryModel.getService( serviceName ); + dataTypes = registryModel.getDataTypes( source ); + } + catch ( MobyException e ) { + error( ServicesTree.SERVICES_ACCESS_ERROR, e ); + } + return service; // not used here + } + + // runs on the event-dispatching thread. + public void finished() { + if ( service == null ) { + deselectService(); + } + else { + updateInputDataPanel( service, dataTypes ); + selService.setText( service.getName() ); + // selectionAllowed = false; + // recentServices.setText (service.getName()); + // selectionAllowed = true; + propertyChannel.put( DP_SC_SERVICE, service ); + runButton.setEnabled( true ); + + } + } + }; + worker.start(); + } + + /******************************************************************************************************************* + * Called when no service is selected in order to display this fact on various places in the panel. + ******************************************************************************************************************/ + protected void deselectService() { + selService.setText( "" ); + updateInputDataPanel( INIT_SELECT ); + propertyChannel.remove( DP_SC_SERVICE ); + runButton.setEnabled( false ); + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getName() { + return "Simple Client"; + } + + /******************************************************************************************************************* + * + ******************************************************************************************************************/ + public String getDescription() { + return "A panel allowing to create input data and to call an arbitrary Biomoby service. " + + "Its purpose is mostly for the service developers to test their new services."; + } + + /******************************************************************************************************************* + * + * Customized tree of services... + * + ******************************************************************************************************************/ + protected class CustomServicesTree extends ServicesTree { + + /*************************************************************************************************************** + * Construtor + **************************************************************************************************************/ + public CustomServicesTree( RegistryModel model, CommonConsole console ) { + super( model, console ); + } + + /*************************************************************************************************************** + * + **************************************************************************************************************/ + protected void createPopups( String title ) { + super.createPopups( title ); + removeFromPopups( AC_RELOAD ); + removeSeparatorAfter( AC_COLLAPSE ); + } + + /*************************************************************************************************************** + * Service selected in a service tree... + **************************************************************************************************************/ + protected void selected( DefaultMutableTreeNode node ) { + if ( node == null ) { + // nothing selected + deselectService(); + return; + } + updateInputDataPanel( "Loading..." ); + selService.setText( "" ); + final CommonNode nodeObject = ( CommonNode ) node.getUserObject(); + String currentServiceName = nodeObject.getValue(); + selectService( currentServiceName ); + setPrefValue( DP_SC_SERVICE_NAME, currentServiceName ); + } + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java,v retrieving revision 1.6 retrieving revision 1.7 diff -u -r1.6 -r1.7 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java 2008/05/14 20:37:10 1.6 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/ServiceCallerModel.java 2008/11/26 08:54:21 1.7 @@ -1,168 +1,168 @@ -// ServiceCallerModel.java -// -// Created: February 2006 -// -// This file is a component of the BioMoby project. -// Copyright Martin Senger (martin.senger at gmail.com). -// - -package org.biomoby.service.dashboard; - -import org.biomoby.shared.MobyException; -import org.biomoby.shared.MobyService; -import org.biomoby.shared.parser.MobyPackage; -import org.biomoby.shared.parser.MobyJob; -import org.biomoby.client.ExtendedProtocolClient; -import org.biomoby.client.MobyServiceLocator; -import org.biomoby.client.ExtendedServiceLocator; -import org.biomoby.service.dashboard.data.DataContainer; - -import org.tulsoft.shared.UUtils; - -/** - * A model that achieves its task by calling (local, remote, or none) - * Biomoby service. It delegates the task of calling a service to a - * true Biomoby client (that extends BaseClient).

        - * - * @author Martin Senger - * @version $Id$ - */ - -public class ServiceCallerModel - extends AbstractModel { - -// private static org.apache.commons.logging.Log log = -// org.apache.commons.logging.LogFactory.getLog (ServiceCallerModel.class); - - /************************************************************************** - * Call a service. This is the main purpose of this model.

        - * - * @param data contains input data and this method replaces them - * by result data - *************************************************************************/ - public void runIt (DataContainer data) - throws MobyException { - SimpleClient worker = new SimpleClient (data); - worker.process(); - } - - /************************************************************************** - * - * A real client - the main worker for this model.. - * - *************************************************************************/ - protected class SimpleClient - extends ExtendedProtocolClient { - - DataContainer data; - - /************************************************************************** - * Constructor. - *************************************************************************/ - public SimpleClient (DataContainer data) { - super(); - this.data = data; - } - - /************************************************************************** - * What service to call and where to find it. - *************************************************************************/ - public MobyServiceLocator getServiceLocator() - throws MobyException { - return new MyServiceLocator(); - } - - /************************************************************************** - * Not used here... - *************************************************************************/ - public boolean fillRequest (MobyJob request, MobyPackage inputContext) - throws MobyException { - return true; - } - - /************************************************************************** - * Not used here... - *************************************************************************/ - public boolean useResponse (MobyJob response, - MobyPackage responseContext) - throws MobyException { - return true; - } - - /************************************************************************** - * Return input XML (from a data container obtained in the - * constructor). - *************************************************************************/ - public String fillRequest() - throws MobyException { - - if (data == null) - throw new MobyException ("No input data given."); - - return (String)data.getData(); - } - - /************************************************************************** - * - *************************************************************************/ - public boolean useResponse (String xmlResponse) - throws MobyException { - - data.setData (xmlResponse); - - // do nothing more if it is just an input echo - if ( ((ExtendedServiceLocator)getServiceLocator()).isLoop()) - return false; - - return false; - } - } - - /************************************************************************** - * - * A service locator filled from the property channel. - * - *************************************************************************/ - protected class MyServiceLocator - extends ExtendedServiceLocator { - - public MyServiceLocator() - throws MobyException { - super(); - - // fill this locator by a service - MobyService selService = (MobyService)propertyChannel.get (DP_SC_SERVICE); - if (selService == null) - throw new MobyException ("No service given."); - MobyService clonedService = new MobyService (selService.getName(), selService.getAuthority()); - clonedService.setURL (selService.getURL()); - setService (clonedService); - - // fill how to call this service - String howToCall = propertyChannel.getString (DP_CALL_SERVICE); - if (DP_CS_NEWURL.equals (howToCall)) { - String sEndpoint = propertyChannel.getString (DP_ENDPOINT); - if (! UUtils.isEmpty (sEndpoint)) - clonedService.setURL (sEndpoint); - - } else if (DP_CS_REGISTRY.equals (howToCall)) { - clonedService.setURL (null); - setRegistryEndpoint (propertyChannel.getString (DP_REGISTRY_ENDPOINT)); - setRegistryNamespace (propertyChannel.getString (DP_REGISTRY_NAMESPACE)); - - } else if (DP_CS_CLASS.equals (howToCall)) { - String localClass = propertyChannel.getString (DP_IMPL_CLASS); - if (UUtils.isEmpty (localClass)) - throw new MobyException ("No local class given."); - setLocalClass (localClass); - - } else if (DP_CS_NONE.equals (howToCall)) { - setLoop (true); - } - - setAsBytes (propertyChannel.getBoolean (DP_INP_ASBYTES, false)); - - } - } - -} +// ServiceCallerModel.java +// +// Created: February 2006 +// +// This file is a component of the BioMoby project. +// Copyright Martin Senger (martin.senger at gmail.com). +// + +package org.biomoby.service.dashboard; + +import org.apache.axis.client.Call; +import org.biomoby.client.ExtendedProtocolClient; +import org.biomoby.client.ExtendedServiceLocator; +import org.biomoby.client.MobyServiceLocator; +import org.biomoby.service.dashboard.data.DataContainer; +import org.biomoby.shared.MobyException; +import org.biomoby.shared.MobyService; +import org.biomoby.shared.parser.MobyJob; +import org.biomoby.shared.parser.MobyPackage; +import org.tulsoft.shared.UUtils; + +/** + * A model that achieves its task by calling (local, remote, or none) Biomoby service. It delegates the task of calling + * a service to a true Biomoby client (that extends BaseClient). + *

        + * + * @author Martin Senger + * @version $Id$ + */ + +public class ServiceCallerModel extends AbstractModel { + + // private static org.apache.commons.logging.Log log = + // org.apache.commons.logging.LogFactory.getLog (ServiceCallerModel.class); + + /******************************************************************************************************************* + * Call a service. This is the main purpose of this model. + *

        + * + * @param data + * contains input data and this method replaces them by result data + ******************************************************************************************************************/ + public void runIt( DataContainer data ) throws MobyException { + SimpleClient worker = new SimpleClient( data ); + worker.process(); + } + + /******************************************************************************************************************* + * + * A real client - the main worker for this model.. + * + ******************************************************************************************************************/ + protected class SimpleClient extends ExtendedProtocolClient { + + DataContainer data; + + /*************************************************************************************************************** + * Constructor. + **************************************************************************************************************/ + public SimpleClient( DataContainer data ) { + super(); + this.data = data; + } + + /*************************************************************************************************************** + * What service to call and where to find it. + **************************************************************************************************************/ + public MobyServiceLocator getServiceLocator() throws MobyException { + return new MyServiceLocator(); + } + + /*************************************************************************************************************** + * Not used here... + **************************************************************************************************************/ + public boolean fillRequest( MobyJob request, MobyPackage inputContext ) throws MobyException { + return true; + } + + /*************************************************************************************************************** + * Not used here... + **************************************************************************************************************/ + public boolean useResponse( MobyJob response, MobyPackage responseContext ) throws MobyException { + return true; + } + + /*************************************************************************************************************** + * Return input XML (from a data container obtained in the constructor). + **************************************************************************************************************/ + public String fillRequest() throws MobyException { + + if ( data == null ) throw new MobyException( "No input data given." ); + + return ( String ) data.getData(); + } + + /** + * Sets the authentication for the service call. If the user has checked the corresponding box in the Dashboard + * the values are stored in the propertychannel. + */ + protected void setAuthentication( Call call ) { + String user = propertyChannel.getString( DashboardProperties.DP_USER_AUTHENTICATION ); + if ( !isEmpty( user ) ) { + call.setProperty( Call.USERNAME_PROPERTY, user ); + call.setProperty( Call.PASSWORD_PROPERTY, new String( ( char[] ) propertyChannel + .get( DashboardProperties.DP_PASSWORD_AUTHENTICATION ) ) ); + } + } + + /*************************************************************************************************************** + * + **************************************************************************************************************/ + public boolean useResponse( String xmlResponse ) throws MobyException { + + data.setData( xmlResponse ); + + // do nothing more if it is just an input echo + if ( ( ( ExtendedServiceLocator ) getServiceLocator() ).isLoop() ) return false; + + return false; + } + } + + /******************************************************************************************************************* + * + * A service locator filled from the property channel. + * + ******************************************************************************************************************/ + protected class MyServiceLocator extends ExtendedServiceLocator { + + public MyServiceLocator() throws MobyException { + super(); + + // fill this locator by a service + MobyService selService = ( MobyService ) propertyChannel.get( DP_SC_SERVICE ); + if ( selService == null ) throw new MobyException( "No service given." ); + MobyService clonedService = new MobyService( selService.getName(), selService.getAuthority() ); + clonedService.setURL( selService.getURL() ); + setService( clonedService ); + + // fill how to call this service + String howToCall = propertyChannel.getString( DP_CALL_SERVICE ); + if ( DP_CS_NEWURL.equals( howToCall ) ) { + String sEndpoint = propertyChannel.getString( DP_ENDPOINT ); + if ( !UUtils.isEmpty( sEndpoint ) ) clonedService.setURL( sEndpoint ); + + } + else if ( DP_CS_REGISTRY.equals( howToCall ) ) { + clonedService.setURL( null ); + setRegistryEndpoint( propertyChannel.getString( DP_REGISTRY_ENDPOINT ) ); + setRegistryNamespace( propertyChannel.getString( DP_REGISTRY_NAMESPACE ) ); + + } + else if ( DP_CS_CLASS.equals( howToCall ) ) { + String localClass = propertyChannel.getString( DP_IMPL_CLASS ); + if ( UUtils.isEmpty( localClass ) ) throw new MobyException( "No local class given." ); + setLocalClass( localClass ); + + } + else if ( DP_CS_NONE.equals( howToCall ) ) { + setLoop( true ); + } + + setAsBytes( propertyChannel.getBoolean( DP_INP_ASBYTES, false ) ); + + } + } + +} =================================================================== RCS file: /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java,v retrieving revision 1.29 retrieving revision 1.30 diff -u -r1.29 -r1.30 --- /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/18 06:40:11 1.29 +++ /home/repository/moby/moby-live/Java/src/main/org/biomoby/service/dashboard/DashboardProperties.java 2008/11/26 08:54:21 1.30 @@ -9,10 +9,10 @@ package org.biomoby.service.dashboard; /** - * A list of names of most/all recognized properties that can be fired - * by dashboard panels, and a list of names of Java properties that - * can be used to configure the dashboard.

        - * + * A list of names of most/all recognized properties that can be fired by dashboard panels, and a list of names of Java + * properties that can be used to configure the dashboard. + *

        + * * @author Martin Senger * @version $Id$ */ @@ -44,9 +44,9 @@ static final String DP_FL_BIOCASE = "biocase"; static final String DP_FL_HIBERNATE = "hibernate"; - static final String DP_SEL_SERVICES = "selectedServices"; // type: Vector with service/authority name - static final String DP_SEL_AUTHORITIES = "selectedAuthorities"; // type: Vector with authority name - static final String DP_DEPL_SERVICES = "servicesToDeploy"; // type: Map with serviceName => className + static final String DP_SEL_SERVICES = "selectedServices"; // type: Vector with service/authority name + static final String DP_SEL_AUTHORITIES = "selectedAuthorities"; // type: Vector with authority name + static final String DP_DEPL_SERVICES = "servicesToDeploy"; // type: Map with serviceName => className static final String DP_LOCAL_DEPLOY = "use-local-deploy"; static final String DP_TOMCAT_HOME = "tomcatHome"; @@ -82,10 +82,10 @@ static final String DP_DETACH_VIEW = "detachViewers"; -// static final String DP_SC_IN_DATA = "sc-inputData"; + // static final String DP_SC_IN_DATA = "sc-inputData"; static final String DP_SC_IN_FILE = "sc-inputFromFile"; static final String DP_SC_INPUT_FILE = "sc-inputFile"; - static final String DP_SC_SERVICE = "dp-sc-service"; // type: MobyService + static final String DP_SC_SERVICE = "dp-sc-service"; // type: MobyService static final String DP_SC_SERVICE_NAME = "dp-sc-service-name"; static final String DP_SC_SERVICES = "dp-sc-recent-services"; @@ -97,21 +97,21 @@ static final String DP_DATATYPE_NAME = "dp-datatype-name"; // names of properties used in property channel storage - static final String DP_REGISTRY_MODEL = "dp-registry-model"; // type: RegistryModel - static final String DP_ANT_MODEL = "dp-ant-model"; // type: AntModel + static final String DP_REGISTRY_MODEL = "dp-registry-model"; // type: RegistryModel + static final String DP_ANT_MODEL = "dp-ant-model"; // type: AntModel static final String DP_REGISTRY_SYNONYM = "dp-registry-synonym"; - static final String DP_REG_INFO = "dp-reg-info"; // type: Boolean + static final String DP_REG_INFO = "dp-reg-info"; // type: Boolean static final String DP_REGISTRY_ENDPOINT = "dp-registry-endpoint"; static final String DP_REGISTRY_NAMESPACE = "dp-registry-namespace"; static final String DP_CACHE_DIR = "dp-cache-dir"; - static final String DP_USE_CACHE = "dp-use-cache"; // type: Boolean + static final String DP_USE_CACHE = "dp-use-cache"; // type: Boolean static final String DP_REG_DT_NAME = "dp-reg-dt-name"; static final String DP_REG_DT_AUTH = "dp-reg-dt-auth"; static final String DP_REG_DT_EMAIL = "dp-reg-dt-email"; static final String DP_REG_DT_DESC = "dp-reg-dt-desc"; - static final String DP_REG_DT_TREE = "dp-reg-dt-tree"; // type: MobyDataType + static final String DP_REG_DT_TREE = "dp-reg-dt-tree"; // type: MobyDataType static final String DP_REG_NS_NAME = "dp-reg-ns-name"; static final String DP_REG_NS_AUTH = "dp-reg-ns-auth"; @@ -132,94 +132,103 @@ static final String DP_REG_S_RDF_URL = "dp-reg-s-rdf-url"; static final String DP_REG_S_RDF_PATH = "dp-reg-s-rdf-path"; static final String DP_REG_S_XML_PATH = "dp-reg-s-xml-path"; - static final String DP_USE_SIGNATURE = "dp-use-signature"; // type: Boolean - static final String DP_USE_AUTHORITATIVE = "dp-use-auth"; // type: Boolean + static final String DP_USE_SIGNATURE = "dp-use-signature"; // type: Boolean + static final String DP_USE_AUTHORITATIVE = "dp-use-auth"; // type: Boolean static final String DP_REG_S_TYPE = "dp-reg-s-type"; static final String DP_REG_VERBOSE = "dp-reg-verbose"; - static final String DP_S_SELECTED = "dp-s-selected"; // type: MobyService + static final String DP_S_SELECTED = "dp-s-selected"; // type: MobyService - /** A property name. Its value contains a title that will appear - * in big fonts on top of the dashboard. It may be empty if - * property {@link #DP_TITLE_ICON} is defined; otherwise a default - * value will be used. + /** + * A property name. Its value contains a title that will appear in big fonts on top of the dashboard. It may be + * empty if property {@link #DP_TITLE_ICON} is defined; otherwise a default value will be used. */ static final String DP_TITLE = "dashboard.title"; - /** A property name. Its value contains a filename with an icon - * accompanying a dashboard title (defined by property {@link - * #DP_TITLE}. No default value used. Specify here either an - * absolute path (not recommended) or a relative path whose - * beginning can be found somewhere on the CLASSPATH. + /** + * A property name. Its value contains a filename with an icon accompanying a dashboard title (defined by property + * {@link #DP_TITLE}. No default value used. Specify here either an absolute path (not recommended) or a relative + * path whose beginning can be found somewhere on the CLASSPATH. */ static final String DP_TITLE_ICON = "dashboard.title.icon"; - /** A property name. Its value contains a filename with the main - * dashboard icon. Specify here either an absolute path (not - * recommended) or a relative path whose beginning can be found - * somewhere on the CLASSPATH. + /** + * A property name. Its value contains a filename with the main dashboard icon. Specify here either an absolute path + * (not recommended) or a relative path whose beginning can be found somewhere on the CLASSPATH. */ static final String DP_ICON = "dashboard.icon"; - /** A property name. Its value contains a color name used to paint - * main dashboard background. The name can be a color name, or a - * number in various format (see GraphColours for - * details). + /** + * A property name. Its value contains a color name used to paint main dashboard background. The name can be a color + * name, or a number in various format (see GraphColours for details). */ static final String DP_BGCOLOR = "dashboard.bgcolor"; - /** A property name. Its value contains a short description what a - dashboard can do generally. Often, however, it is more - convenient to put the description in a file and to use - property {@link #DP_DESCRIPTION_FILE}. + /** + * A property name. Its value contains a short description what a dashboard can do generally. Often, however, it is + * more convenient to put the description in a file and to use property {@link #DP_DESCRIPTION_FILE}. */ static final String DP_DESCRIPTION = "dashboard.description"; - /** A property name. Its value contains a file name with a short - description what a dashboard can do generally. + /** + * A property name. Its value contains a file name with a short description what a dashboard can do generally. */ static final String DP_DESCRIPTION_FILE = "dashboard.description.file"; - /** A property name. Its value contains a short description of a - project that uses this dashboard. Often, however, it is more - convenient to put the description in a file and to use - property {@link #DP_P_DESCRIPTION_FILE}. + /** + * A property name. Its value contains a short description of a project that uses this dashboard. Often, however, it + * is more convenient to put the description in a file and to use property {@link #DP_P_DESCRIPTION_FILE}. */ static final String DP_P_DESCRIPTION = "project.description"; - /** A property name. Its value contains a file name with a short - description of a project that uses this dashboard. + /** + * A property name. Its value contains a file name with a short description of a project that uses this dashboard. */ static final String DP_P_DESCRIPTION_FILE = "project.description.file"; - /** A property name. Its value contains a name of a contact - person, possibly with an email address. + /** + * A property name. Its value contains a name of a contact person, possibly with an email address. */ static final String DP_CONTACT = "dashboard.contact"; - /** A property name. Its value contains a directory name with the - * local cache of a BiMoby Central registry. + /** + * A property name. Its value contains a directory name with the local cache of a BiMoby Central registry. */ static final String DP_REGISTRY_CACHE_DIR = "registry.cache.dir"; - /** A property name. Its value contains a name or a - * comma-separated list of names of BioMoby registries that will - * be displayed in the RegistryPanel. If this property is missing, - * the list is taken from the hard-coded known registries in the - * Java source file.

        - * - * The names (values of this property) are equivalent to the - * 'synonym' attribute of the Registry class. + /** + * A property name. Its value contains a name or a comma-separated list of names of BioMoby registries that will be + * displayed in the RegistryPanel. If this property is missing, the list is taken from the hard-coded known + * registries in the Java source file. + *

        + * + * The names (values of this property) are equivalent to the 'synonym' attribute of the Registry class. */ static final String DP_WANTED_REGISTRIES = "dashboard.wanted.registries"; - /** A property name. Its value contains a name (synonym) of a - * default BioMoby registry. By default, the default registry is - * taken either from the first element in {@link - * #DP_WANTED_REGISTRIES} or from + /** + * A property name. Its value contains a name (synonym) of a default BioMoby registry. By default, the default + * registry is taken either from the first element in {@link #DP_WANTED_REGISTRIES} or from * Registries.DEFAULT_REGISTRY_SYNONYM. */ static final String DP_DEFAULT_REGISTRY = "dashboard.default.registry"; + /** + * A property name. Its value contains the user name used for the authentication required for the servlet container + * the service is hosted at. + */ + static final String DP_USER_AUTHENTICATION = "service-authentication-user"; + + /** + * A property name. Its value contains the password used for the authentication required for the servlet container + * the service is hosted at. + */ + static final String DP_PASSWORD_AUTHENTICATION = "service-authentication-passwd"; + + /** + * A property name. Its value contains whether authentication is required for the servlet container the service is + * hosted at. + */ + static final String DP_AUTHENTICATION = "service-authentication"; }