Add licence.
[simpleserver-moved-to-github.git] / SimpleServer.pm
1 ##
2 ##  Copyright (c) 2000-2006, Index Data.
3 ##
4 ##  Permission to use, copy, modify, distribute, and sell this software and
5 ##  its documentation, in whole or in part, for any purpose, is hereby granted,
6 ##  provided that:
7 ##
8 ##  1. This copyright and permission notice appear in all copies of the
9 ##  software and its documentation. Notices of copyright or attribution
10 ##  which appear at the beginning of any file must remain unchanged.
11 ##
12 ##  2. The name of Index Data or the individual authors may not be used to
13 ##  endorse or promote products derived from this software without specific
14 ##  prior written permission.
15 ##
16 ##  THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,
17 ##  EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
18 ##  WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 ##  IN NO EVENT SHALL INDEX DATA BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
20 ##  INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES
21 ##  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR
22 ##  NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 ##  LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 ##  OF THIS SOFTWARE.
25 ##
26 ##
27
28 ## $Id: SimpleServer.pm,v 1.48 2009-03-04 15:02:20 mike Exp $
29
30 package Net::Z3950::SimpleServer;
31
32 use strict;
33 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
34 use Carp;
35
36 require Exporter;
37 require DynaLoader;
38 require AutoLoader;
39
40 @ISA = qw(Exporter AutoLoader DynaLoader);
41 @EXPORT = qw( );
42 $VERSION = '1.10';
43
44 bootstrap Net::Z3950::SimpleServer $VERSION;
45
46 # Preloaded methods go here.
47
48 my $count = 0;
49
50 sub new {
51         my $class = shift;
52         my %args = @_;
53         my $self = \%args;
54
55         if ($count) {
56                 carp "SimpleServer.pm: WARNING: Multithreaded server unsupported";
57         }
58         $count = 1;
59
60         croak "SimpleServer.pm: ERROR: Unspecified search handler" unless defined($self->{SEARCH});
61         croak "SimpleServer.pm: ERROR: Unspecified fetch handler" unless defined($self->{FETCH});
62
63         bless $self, $class;
64         return $self;
65 }
66
67
68 sub launch_server {
69         my $self = shift;
70         my @args = @_;
71
72         ### This modal internal interface, in which we set a bunch of
73         #   globals and then call start_server(), is asking for
74         #   trouble.  Instead, we should just pass the $self object
75         #   as a parameter into start_server().
76         if (defined($self->{GHANDLE})) {
77                 set_ghandle($self->{GHANDLE});
78         }
79         if (defined($self->{INIT})) {
80                 set_init_handler($self->{INIT});
81         }
82         set_search_handler($self->{SEARCH});
83         set_fetch_handler($self->{FETCH});
84         if (defined($self->{CLOSE})) {
85                 set_close_handler($self->{CLOSE});
86         }
87         if (defined($self->{PRESENT})) {
88                 set_present_handler($self->{PRESENT});
89         }
90         if (defined($self->{SCAN})) {
91                 set_scan_handler($self->{SCAN});
92         }
93         if (defined($self->{SORT})) {
94                 set_sort_handler($self->{SORT});
95         }
96         if (defined($self->{EXPLAIN})) {
97                 set_explain_handler($self->{EXPLAIN});
98         }
99         if (defined($self->{DELETE})) {
100                 set_delete_handler($self->{DELETE});
101         }
102
103         start_server(@args);
104 }
105
106
107 # Register packages that we will use in translated RPNs
108 package Net::Z3950::RPN::Node;
109 package Net::Z3950::APDU::Query;
110 our @ISA = qw(Net::Z3950::RPN::Node);
111 package Net::Z3950::APDU::OID;
112 package Net::Z3950::RPN::And;
113 our @ISA = qw(Net::Z3950::RPN::Node);
114 package Net::Z3950::RPN::Or;
115 our @ISA = qw(Net::Z3950::RPN::Node);
116 package Net::Z3950::RPN::AndNot;
117 our @ISA = qw(Net::Z3950::RPN::Node);
118 package Net::Z3950::RPN::Term;
119 our @ISA = qw(Net::Z3950::RPN::Node);
120 package Net::Z3950::RPN::RSID;
121 our @ISA = qw(Net::Z3950::RPN::Node);
122 package Net::Z3950::RPN::Attributes;
123 package Net::Z3950::RPN::Attribute;
124
125
126 # Utility method for re-rendering Type-1 query back down to PQF
127 package Net::Z3950::RPN::Node;
128
129 sub toPQF {
130     my $this = shift();
131     my $class = ref $this;
132
133     if ($class eq "Net::Z3950::APDU::Query") {
134         my $res = "";
135         my $set = $this->{attributeSet};
136         $res .= "\@attrset $set " if defined $set;
137         return $res . $this->{query}->toPQF();
138     } elsif ($class eq "Net::Z3950::RPN::Or") {
139         return '@or ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
140     } elsif ($class eq "Net::Z3950::RPN::And") {
141         return '@and ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
142     } elsif ($class eq "Net::Z3950::RPN::AndNot") {
143         return '@not ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
144     } elsif ($class eq "Net::Z3950::RPN::RSID") {
145         return '@set ' . $this->{id};
146     } elsif ($class ne "Net::Z3950::RPN::Term") {
147         die "unknown PQF node-type '$class'";
148     }
149
150     my $res = "";
151     foreach my $attr (@{ $this->{attributes} }) {
152         $res .= "\@attr ";
153         my $set = $attr->{attributeSet};
154         $res .= "$set " if defined $set;
155         $res .= $attr->{attributeType} . "=" . $attr->{attributeValue} . " ";
156     }
157
158     return $res . $this->{term};
159 }
160
161
162 # Must revert to original package for Autoloader's benefit
163 package Net::Z3950::SimpleServer;
164
165
166 # Autoload methods go after =cut, and are processed by the autosplit program.
167
168 1;
169 __END__
170 # Below is the stub of documentation for your module. You better edit it!
171
172 =head1 NAME
173
174 Net::Z3950::SimpleServer - Simple Perl API for building Z39.50 servers. 
175
176 =head1 SYNOPSIS
177
178   use Net::Z3950::SimpleServer;
179
180   sub my_search_handler {
181         my $args = shift;
182
183         my $set_id = $args->{SETNAME};
184         my @database_list = @{ $args->{DATABASES} };
185         my $query = $args->{QUERY};
186
187         ## Perform the query on the specified set of databases
188         ## and return the number of hits:
189
190         $args->{HITS} = $hits;
191   }
192
193   sub my_fetch_handler {        # Get a record for the user
194         my $args = shift;
195
196         my $set_id = $args->{SETNAME};
197
198         my $record = fetch_a_record($args->{OFFSET});
199
200         $args->{RECORD} = $record;
201         if (number_of_hits() == $args->{OFFSET}) {      ## Last record in set?
202                 $args->{LAST} = 1;
203         } else {
204                 $args->{LAST} = 0;
205         }
206   }
207
208   ## Register custom event handlers:
209   my $z = new Net::Z3950::SimpleServer(GHANDLE = $someObject,
210                                        INIT   =>  \&my_init_handler,
211                                        CLOSE  =>  \&my_close_handler,
212                                        SEARCH =>  \&my_search_handler,
213                                        FETCH  =>  \&my_fetch_handler);
214
215   ## Launch server:
216   $z->launch_server("ztest.pl", @ARGV);
217
218 =head1 DESCRIPTION
219
220 The SimpleServer module is a tool for constructing Z39.50 "Information
221 Retrieval" servers in Perl. The module is easy to use, but it
222 does help to have an understanding of the Z39.50 query
223 structure and the construction of structured retrieval records.
224
225 Z39.50 is a network protocol for searching remote databases and
226 retrieving the results in the form of structured "records". It is widely
227 used in libraries around the world, as well as in the US Federal Government.
228 In addition, it is generally useful whenever you wish to integrate a number
229 of different database systems around a shared, asbtract data model.
230
231 The model of the module is simple: It implements a "generic" Z39.50
232 server, which invokes callback functions supplied by you to search
233 for content in your database. You can use any tools available in
234 Perl to supply the content, including modules like DBI and
235 WWW::Search.
236
237 The server will take care of managing the network connections for
238 you, and it will spawn a new process (or thread, in some
239 environments) whenever a new connection is received.
240
241 The programmer can specify subroutines to take care of the following type
242 of events:
243
244   - Initialize request
245   - Search request
246   - Present request
247   - Fetching of records
248   - Scan request (browsing) 
249   - Closing down connection
250
251 Note that only the Search and Fetch handler functions are required.
252 The module can supply default responses to the other on its own.
253
254 After the launching of the server, all control is given away from
255 the Perl script to the server. The server calls the registered
256 subroutines to field incoming requests from Z39.50 clients.
257
258 A reference to an anonymous hash is passed to each handler. Some of
259 the entries of these hashes are to be considered input and others
260 output parameters.
261
262 The Perl programmer specifies the event handlers for the server by
263 means of the SimpleServer object constructor
264
265   my $z = new Net::Z3950::SimpleServer(
266                         INIT    =>      \&my_init_handler,
267                         CLOSE   =>      \&my_close_handler,
268                         SEARCH  =>      \&my_search_handler,
269                         PRESENT =>      \&my_present_handler,
270                         SCAN    =>      \&my_scan_handler,
271                         FETCH   =>      \&my_fetch_handler,
272                         EXPLAIN =>      \&my_explain_handler,
273                         DELETE  =>      \&my_delete_handler,
274                         SORT    =>      \&my_sort_handler);
275
276 In addition, the arguments to the constructor may include GHANDLE, a
277 global handle which is made available to each invocation of every
278 callback function.  This is typically a reference to either a hash or
279 an object.
280
281 If you want your SimpleServer to start a thread (threaded mode) to
282 handle each incoming Z39.50 request instead of forking a process
283 (forking mode), you need to register the handlers by symbol rather
284 than by code reference. Thus, in threaded mode, you will need to
285 register your handlers this way:
286
287   my $z = new Net::Z3950::SimpleServer(
288                         INIT    =>      "my_package::my_init_handler",
289                         CLOSE   =>      "my_package::my_close_handler",
290                         ....
291                         ....          );
292
293 where my_package is the Perl package in which your handler is
294 located.
295
296 After the custom event handlers are declared, the server is launched
297 by means of the method
298
299   $z->launch_server("MyServer.pl", @ARGV);
300
301 Notice, the first argument should be the name of your server
302 script (for logging purposes), while the rest of the arguments
303 are documented in the YAZ toolkit manual: The section on
304 application invocation: <http://indexdata.com/yaz/doc/server.invocation.tkl>
305
306 In particular, you need to use the -T switch to start your SimpleServer
307 in threaded mode.
308
309 =head2 Init handler
310
311 The init handler is called whenever a Z39.50 client is attempting
312 to logon to the server. The exchange of parameters between the
313 server and the handler is carried out via an anonymous hash reached
314 by a reference, i.e.
315
316   $args = shift;
317
318 The argument hash passed to the init handler has the form
319
320   $args = {
321                                     ## Response parameters:
322
323              PEER_NAME =>  "",      ## Name or IP address of connecting client
324              IMP_ID    =>  "",      ## Z39.50 Implementation ID
325              IMP_NAME  =>  "",      ## Z39.50 Implementation name
326              IMP_VER   =>  "",      ## Z39.50 Implementation version
327              ERR_CODE  =>  0,       ## Error code, cnf. Z39.50 manual
328              ERR_STR   =>  "",      ## Error string (additional info.)
329              USER      =>  "xxx"    ## If Z39.50 authentication is used,
330                                     ## this member contains user name
331              PASS      =>  "yyy"    ## Under same conditions, this member
332                                     ## contains the password in clear text
333              GHANDLE   =>  $obj     ## Global handler specified at creation
334              HANDLE    =>  undef    ## Handler of Perl data structure
335           };
336
337 The HANDLE member can be used to store any scalar value which will then
338 be provided as input to all subsequent calls (ie. for searching, record
339 retrieval, etc.). A common use of the handle is to store a reference to
340 a hash which may then be used to store session-specific parameters.
341 If you have any session-specific information (such as a list of
342 result sets or a handle to a back-end search engine of some sort),
343 it is always best to store them in a private session structure -
344 rather than leaving them in global variables in your script.
345
346 The Implementation ID, name and version are only really used by Z39.50
347 client developers to see what kind of server they're dealing with.
348 Filling these in is optional.
349
350 The ERR_CODE should be left at 0 (the default value) if you wish to
351 accept the connection. Any other value is interpreted as a failure
352 and the client will be shown the door, with the code and the
353 associated additional information, ERR_STR returned.
354
355 =head2 Search handler
356
357 Similarly, the search handler is called with a reference to an anony-
358 mous hash. The structure is the following:
359
360   $args = {
361                                     ## Request parameters:
362
363              GHANDLE   =>  $obj     ## Global handler specified at creation
364              HANDLE    =>  ref,     ## Your session reference.
365              SETNAME   =>  "id",    ## ID of the result set
366              REPL_SET  =>  0,       ## Replace set if already existing?
367              DATABASES =>  ["xxx"], ## Reference to a list of data-
368                                     ## bases to search
369              QUERY     =>  "query", ## The query expression
370              RPN       =>  $obj,    ## Reference to a Net::Z3950::APDU::Query
371
372                                     ## Response parameters:
373
374              ERR_CODE  =>  0,       ## Error code (0=Succesful search)
375              ERR_STR   =>  "",      ## Error string
376              HITS      =>  0        ## Number of matches
377           };
378
379 Note that a search which finds 0 hits is considered successful in
380 Z39.50 terms - you should only set the ERR_CODE to a non-zero value
381 if there was a problem processing the request. The Z39.50 standard
382 provides a comprehensive list of standard diagnostic codes, and you
383 should use these whenever possible.
384
385 The QUERY is a tree-structure of terms combined by operators, the
386 terms being qualified by lists of attributes. The query is presented
387 to the search function in the Prefix Query Format (PQF) which is
388 used in many applications based on the YAZ toolkit. The full grammar
389 is described in the YAZ manual.
390
391 The following are all examples of valid queries in the PQF. 
392
393         dylan
394
395         "bob dylan"
396
397         @or "dylan" "zimmerman"
398
399         @set Result-1
400
401         @or @and bob dylan @set Result-1
402
403         @and @attr 1=1 "bob dylan" @attr 1=4 "slow train coming"
404
405         @attrset @attr 4=1 @attr 1=4 "self portrait"
406
407 You will need to write a recursive function or something similar to
408 parse incoming query expressions, and this is usually where a lot of
409 the work in writing a database-backend happens. Fortunately, you don't
410 need to support anymore functionality than you want to. For instance,
411 it is perfectly legal to not accept boolean operators, but you SHOULD
412 try to return good error codes if you run into something you can't or
413 won't support.
414
415 A more convenient alternative to the QUERY member may be the RPN
416 member, which is a reference to a Net::Z3950::APDU::Query object
417 representing the RPN query tree.  The structure of that object is
418 supposed to be self-documenting, but here's a brief summary of what
419 you get:
420
421 =over 4
422
423 =item *
424
425 C<Net::Z3950::APDU::Query> is a hash with two fields:
426
427 Z<>
428
429 =over 4
430
431 =item C<attributeSet>
432
433 Optional.  If present, it is a reference to a
434 C<Net::Z3950::APDU::OID>.  This is a string of dot-separated integers
435 representing the OID of the query's top-level attribute set.
436
437 =item C<query>
438
439 Mandatory: a refererence to the RPN tree itself.
440
441 =back
442
443 =item *
444
445 Each node of the tree is an object of one of the following types:
446
447 Z<>
448
449 =over 4
450
451 =item C<Net::Z3950::RPN::And>
452
453 =item C<Net::Z3950::RPN::Or>
454
455 =item C<Net::Z3950::RPN::AndNot>
456
457 These three classes are all arrays of two elements, each of which is a
458 node of one of the above types.
459
460 =item C<Net::Z3950::RPN::Term>
461
462 See below for details.
463
464 =item C<Net::Z3950::RPN::RSID>
465
466 A reference to a result-set ID indicating a previous search.  The ID
467 of the result-set is in the C<id> element.
468
469 =back
470
471 =back
472
473 =over 4
474
475 =item *
476
477 C<Net::Z3950::RPN::Term> is a hash with two fields:
478
479 Z<>
480
481 =over 4
482
483 =item C<term>
484
485 A string containing the search term itself.
486
487 =item C<attributes>
488
489 A reference to a C<Net::Z3950::RPN::Attributes> object.
490
491 =back
492
493 =item *
494
495 C<Net::Z3950::RPN::Attributes> is an array of references to
496 C<Net::Z3950::RPN::Attribute> objects.  (Note the plural/singular
497 distinction.)
498
499 =item *
500
501 C<Net::Z3950::RPN::Attribute> is a hash with three elements:
502
503 Z<>
504
505 =over 4
506
507 =item C<attributeSet>
508
509 Optional.  If present, it is dot-separated OID string, as above.
510
511 =item C<attributeType>
512
513 An integer indicating the type of the attribute - for example, under
514 the BIB-1 attribute set, type 1 indicates a ``use'' attribute, type 2
515 a ``relation'' attribute, etc.
516
517 =item C<attributeValue>
518
519 An integer or string indicating the value of the attribute - for example, under
520 BIB-1, if the attribute type is 1, then value 4 indictates a title
521 search and 7 indictates an ISBN search; but if the attribute type is
522 2, then value 4 indicates a ``greater than or equal'' search, and 102
523 indicates a relevance match.
524
525 =back
526
527 =back
528
529 All of these classes except C<Attributes> and C<Attribute> are
530 subclasses of the abstract class C<Net::Z3950::RPN::Node>.  That class
531 has a single method, C<toPQF()>, which may be used to turn an RPN
532 tree, or part of one, back into a textual prefix query.
533
534 Note that, apart to C<toPQF()>, none of these classes have any methods at
535 all: the blessing into classes is largely just a documentation thing
536 so that, for example, if you do
537
538         { use Data::Dumper; print Dumper($args->{RPN}) }
539
540 you get something fairly human-readable.  But of course, the type
541 distinction between the three different kinds of boolean node is
542 important.
543
544 By adding your own methods to these classes (building what I call
545 ``augmented classes''), you can easily build code that walks the tree
546 of the incoming RPN.  Take a look at C<samples/render-search.pl> for a
547 sample implementation of such an augmented classes technique.
548
549
550 =head2 Present handler
551
552 The presence of a present handler in a SimpleServer front-end is optional.
553 Each time a client wishes to retrieve records, the present service is
554 called. The present service allows the origin to request a certain number
555 of records retrieved from a given result set.
556 When the present handler is called, the front-end server should prepare a
557 result set for fetching. In practice, this means to get access to the
558 data from the backend database and store the data in a temporary fashion
559 for fast and efficient fetching. The present handler does *not* fetch
560 anything. This task is taken care of by the fetch handler, which will be
561 called the correct number of times by the YAZ library. More about this
562 below.
563 If no present handler is implemented in the front-end, the YAZ toolkit
564 will take care of a minimum of preparations itself. This default present
565 handler is sufficient in many situations, where only a small amount of
566 records are expected to be retrieved. If on the other hand, large result
567 sets are likely to occur, the implementation of a reasonable present
568 handler can gain performance significantly.
569
570 The informations exchanged between client and present handle are:
571
572   $args = {
573                                     ## Client/server request:
574
575              GHANDLE   =>  $obj     ## Global handler specified at creation
576              HANDLE    =>  ref,     ## Reference to datastructure
577              SETNAME   =>  "id",    ## Result set ID
578              START     =>  xxx,     ## Start position
579              COMP      =>  "",      ## Desired record composition
580              NUMBER    =>  yyy,     ## Number of requested records
581
582
583                                     ## Respons parameters:
584
585              HITS      =>  zzz,     ## Number of returned records
586              ERR_CODE  =>  0,       ## Error code
587              ERR_STR   =>  ""       ## Error message
588           };
589
590
591 =head2 Fetch handler
592
593 The fetch handler is asked to retrieve a SINGLE record from a given
594 result set (the front-end server will automatically call the fetch
595 handler as many times as required).
596
597 The parameters exchanged between the server and the fetch handler are
598
599   $args = {
600                                     ## Client/server request:
601
602              GHANDLE   =>  $obj     ## Global handler specified at creation
603              HANDLE    =>  ref      ## Reference to data structure
604              SETNAME   =>  "id"     ## ID of the requested result set
605              OFFSET    =>  nnn      ## Record offset number
606              REQ_FORM  =>  "n.m.k.l"## Client requested format OID
607              COMP      =>  "xyz"    ## Formatting instructions
608              SCHEMA    =>  "abc"    ## Requested schema, if any
609
610                                     ## Handler response:
611
612              RECORD    =>  ""       ## Record string
613              BASENAME  =>  ""       ## Origin of returned record
614              LAST      =>  0        ## Last record in set?
615              ERR_CODE  =>  0        ## Error code
616              ERR_STR   =>  ""       ## Error string
617              SUR_FLAG  =>  0        ## Surrogate diagnostic flag
618              REP_FORM  =>  "n.m.k.l"## Provided format OID
619              SCHEMA    =>  "abc"    ## Provided schema, if any
620           };
621
622 The REP_FORM value has by default the REQ_FORM value but can be set to
623 something different if the handler desires. The BASENAME value should
624 contain the name of the database from where the returned record originates.
625 The ERR_CODE and ERR_STR works the same way they do in the search
626 handler. If there is an error condition, the SUR_FLAG is used to
627 indicate whether the error condition pertains to the record currently
628 being retrieved, or whether it pertains to the operation as a whole
629 (eg. the client has specified a result set which does not exist.)
630
631 If you need to return USMARC records, you might want to have a look at
632 the MARC module on CPAN, if you don't already have a way of generating
633 these.
634
635 NOTE: The record offset is 1-indexed - 1 is the offset of the first
636 record in the set.
637
638 =head2 Scan handler
639
640 A full featured Z39.50 server should support scan (or in some literature
641 browse). The client specifies a starting term of the scan, and the server
642 should return an ordered list of specified length consisting of terms
643 actually occurring in the data base. Each of these terms should be close
644 to or equal to the term originally specified. The quality of scan compared
645 to simple search is a guarantee of hits. It is simply like browsing through
646 an index of a book, you always find something! The parameters exchanged are
647
648   $args = {
649                                                 ## Client request
650
651                 GHANDLE         => $obj,        ## Global handler specified at creation
652                 HANDLE          => $ref,        ## Reference to data structure
653                 DATABASES       => ["xxx"],     ## Reference to a list of data-
654                                                 ## bases to search
655                 TERM            => 'start',     ## The start term
656                 RPN             =>  $obj,       ## Reference to a Net::Z3950::RPN::Term
657
658                 NUMBER          => xx,          ## Number of requested terms
659                 POS             => yy,          ## Position of starting point
660                                                 ## within returned list
661                 STEP            => 0,           ## Step size
662
663                                                 ## Server response
664
665                 ERR_CODE        => 0,           ## Error code
666                 ERR_STR         => '',          ## Diagnostic message
667                 NUMBER          => zz,          ## Number of returned terms
668                 STATUS          => $status,     ## ScanSuccess/ScanFailure
669                 ENTRIES         => $entries     ## Referenced list of terms
670         };
671
672 where the term list is returned by reference in the scalar $entries, which
673 should point at a data structure of this kind,
674
675   my $entries = [
676                         {       TERM            => 'energy',
677                                 OCCURRENCE      => 5            },
678
679                         {       TERM            => 'energy density',
680                                 OCCURRENCE      => 6,           },
681
682                         {       TERM            => 'energy flow',
683                                 OCCURRENCE      => 3            },
684
685                                 ...
686
687                                 ...
688         ];
689
690 The $status flag is only meaningful after a successful scan, and
691 should be assigned one of two values:
692
693   Net::Z3950::SimpleServer::ScanSuccess  Full success (default)
694   Net::Z3950::SimpleServer::ScanPartial  Fewer terms returned than requested
695
696 The STEP member contains the requested number of entries in the term-list
697 between two adjacent entries in the response.
698
699 A better alternative to the TERM member is the the RPN
700 member, which is a reference to a Net::Z3950::RPN::Term object
701 representing the scan cloause.  The structure of that object is the
702 same as for Term objects included as part of the RPN tree passed to
703 search handlers.  This is more useful than the simple TERM because it
704 includes attributes (e.g. access points associated with the term),
705 which are discarded by the TERM element.
706
707 =head2 Close handler
708
709 The argument hash recieved by the close handler has two elements only:
710
711   $args = {
712                                     ## Server provides:
713
714              GHANDLE   =>  $obj     ## Global handler specified at creation
715              HANDLE    =>  ref      ## Reference to data structure
716           };
717
718 What ever data structure the HANDLE value points at goes out of scope
719 after this call. If you need to close down a connection to your server
720 or something similar, this is the place to do it.
721
722 =head2 Delete handler
723
724 The argument hash recieved by the delete handler has the following elements:
725
726   $args = {
727                                     ## Client request:
728              GHANDLE   =>  $obj,    ## Global handler specified at creation
729              HANDLE    =>  ref,     ## Reference to data structure
730              SETNAME   =>  "id",    ## Result set ID
731
732                                     ## Server response:
733              STATUS    => 0         ## Deletion status
734           };
735
736 The SETNAME element of the argument hash may or may not be defined.
737 If it is, then SETNAME is the name of a result set to be deleted; if
738 not, then all result-sets associated with the current session should
739 be deleted.  In either case, the callback function should report on
740 success or failure by setting the STATUS element either to zero, on
741 success, or to an integer from 1 to 10, to indicate one of the ten
742 possible failure codes described in section 3.2.4.1.4 of the Z39.50
743 standard -- see 
744 http://www.loc.gov/z3950/agency/markup/05.html#Delete-list-statuses1
745
746 =head2 Sort handler
747
748 The argument hash recieved by the sort handler has the following elements:
749
750         $args = {
751                                         ## Client request:
752                 GHANDLE => $obj,        ## Global handler specified at creation
753                 HANDLE => ref,          ## Reference to data structure
754                 INPUT => [ a, b ... ],  ## Names of result-sets to sort
755                 OUTPUT => "name",       ## Name of result-set to sort into
756                 SEQUENCE                ## Sort specification: see below
757
758                                         ## Server response:
759                 STATUS => 0,            ## Success, Partial or Failure
760                 ERR_CODE => 0,          ## Error code
761                 ERR_STR => '',          ## Diagnostic message
762
763         };
764
765 The SEQUENCE element is a reference to an array, each element of which
766 is a hash representing a sort key.  Each hash contains the following
767 elements:
768
769 =over 4
770
771 =item RELATION
772
773 0 for an ascending sort, 1 for descending, 3 for ascending by
774 frequency, or 4 for descending by frequency.
775
776 =item CASE
777
778 0 for a case-sensitive sort, 1 for case-insensitive
779
780 =item MISSING
781
782 How to respond if one or more records in the set to be sorted are
783 missing the fields indicated in the sort specification.  1 to abort
784 the sort, 2 to use a "null value", 3 if a value is provided to use in
785 place of the missing data (although in the latter case, the actual
786 value to use is currently not made available, so this is useless).
787
788 =back
789
790 And one or other of the following:
791
792 =over 4
793
794 =item SORTFIELD
795
796 A string indicating the field to be sorted, which the server may
797 interpret as it sees fit (presumably by an out-of-band agreement with
798 the client).
799
800 =item ELEMENTSPEC_TYPE and ELEMENTSPEC_VALUE
801
802 I have no idea what this is.
803
804 =item ATTRSET and SORT_ATTR
805
806 ATTRSET is the attribute set from which the attributes are taken, and
807 SORT_ATTR is a reference to an array containing the attributes
808 themselves.  Each attribute is represented by (are you following this
809 carefully?) yet another hash, this one containing the elements
810 ATTR_TYPE and ATTR_VALUE: for example, type=1 and value=4 in the BIB-1
811 attribute set would indicate access-point 4 which is title, so that a
812 sort of title is requested.
813
814 =back
815
816 Precisely why all of the above is so is not clear, but goes some way
817 to explain why, in the Z39.50 world, the developers of the standard
818 are not so much worshipped as blamed.
819
820 The backend function should set STATUS to 0 on success, 1 for "partial
821 success" (don't ask) or 2 on failure, in which case ERR_CODE and
822 ERR_STR should be set.
823
824 =head2 Support for SRU and SRW
825
826 Since release 1.0, SimpleServer includes support for serving the SRU
827 and SRW protocols as well as Z39.50.  These ``web-friendly'' protocols
828 enable similar functionality to that of Z39.50, but by means of rich
829 URLs in the case of SRU, and a SOAP-based web-service in the case of
830 SRW.  These protocols are described at
831 http://www.loc.gov/sru
832
833 In order to serve these protocols from a SimpleServer-based
834 application, it is necessary to launch the application with a YAZ
835 Generic Frontend Server (GFS) configuration file, which can be
836 specified using the command-line argument C<-f> I<filename>.  A
837 minimal configuration file looks like this:
838
839   <yazgfs>
840     <server>
841       <cql2rpn>pqf.properties</cql2rpn>
842     </server>
843   </yazgfs>
844
845 This file specifies only that C<pqf.properties> should be used to
846 translate the CQL queries of SRU and SRW into corresponding Z39.50
847 Type-1 queries.  For more information about YAZ GFS configuration,
848 including how to specify an Explain record, see the I<Virtual Hosts>
849 section of the YAZ manual at
850 http://indexdata.com/yaz/doc/server.vhosts.tkl
851
852 The mapping of CQL queries into Z39.50 Type-1 queries is specified by
853 a file that indicates which BIB-1 attributes should be generated for
854 each CQL index, relation, modifiers, etc.  A typical section of this
855 file looks like this:
856
857   index.dc.title                        = 1=4
858   index.dc.subject                      = 1=21
859   index.dc.creator                      = 1=1003
860   relation.<                            = 2=1
861   relation.le                           = 2=2
862
863 This file specifies the BIB-1 access points (type=1) for the Dublin
864 Core indexes C<title>, C<subject> and C<creator>, and the BIB-1
865 relations (type=2) corresponding to the CQL relations C<E<lt>> and
866 C<E<lt>=>.  For more information about the format of this file, see
867 the I<CQL> section of the YAZ manual at
868 http://indexdata.com/yaz/doc/tools.tkl#tools.cql
869
870 The YAZ distribution include a sample CQL-to-PQF mapping configuration
871 file called C<pqf.properties>; this is sufficient for many
872 applications, and a good base to work from for most others.
873
874 If a SimpleServer-based application is run without this SRU-specific
875 configuration, it can still serve SRU; however, CQL queries will not
876 be translated, but passed straight through to the search-handler
877 function, as the C<CQL> member of the parameters hash.  It is then the
878 responsibility of the back-end application to parse and handle the CQL
879 query, which is most easily done using Ed Summers' fine C<CQL::Parser>
880 module, available from CPAN at
881 http://search.cpan.org/~esummers/CQL-Parser/
882
883 =head1 AUTHORS
884
885 Anders Sønderberg (sondberg@indexdata.dk),
886 Sebastian Hammer (quinn@indexdata.dk),
887 Mike Taylor (indexdata.com).
888
889 =head1 COPYRIGHT AND LICENCE
890
891 Copyright (C) 2000-2009 by Index Data.
892
893 This library is free software; you can redistribute it and/or modify
894 it under the same terms as Perl itself, either Perl version 5.8.4 or,
895 at your option, any later version of Perl 5 you may have available.
896
897 =head1 SEE ALSO
898
899 Any Perl module which is useful for accessing the database of your
900 choice.
901
902 =cut