2 ## Copyright (c) 2000-2006, Index Data.
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,
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.
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.
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
28 ## $Id: SimpleServer.pm,v 1.31 2006-12-27 12:24:50 sondberg Exp $
30 package Net::Z3950::SimpleServer;
33 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
40 @ISA = qw(Exporter AutoLoader DynaLoader);
44 bootstrap Net::Z3950::SimpleServer $VERSION;
46 # Preloaded methods go here.
56 carp "SimpleServer.pm: WARNING: Multithreaded server unsupported";
60 croak "SimpleServer.pm: ERROR: Unspecified search handler" unless defined($self->{SEARCH});
61 croak "SimpleServer.pm: ERROR: Unspecified fetch handler" unless defined($self->{FETCH});
72 if (defined($self->{INIT})) {
73 set_init_handler($self->{INIT});
75 set_search_handler($self->{SEARCH});
76 set_fetch_handler($self->{FETCH});
77 if (defined($self->{CLOSE})) {
78 set_close_handler($self->{CLOSE});
80 if (defined($self->{PRESENT})) {
81 set_present_handler($self->{PRESENT});
83 if (defined($self->{SCAN})) {
84 set_scan_handler($self->{SCAN});
86 if (defined($self->{SORT})) {
87 set_sort_handler($self->{SORT});
89 if (defined($self->{EXPLAIN})) {
90 set_explain_handler($self->{EXPLAIN});
97 # Register packages that we will use in translated RPNs
98 package Net::Z3950::APDU::Query;
99 package Net::Z3950::APDU::OID;
100 package Net::Z3950::RPN::And;
101 package Net::Z3950::RPN::Or;
102 package Net::Z3950::RPN::AndNot;
103 package Net::Z3950::RPN::Term;
104 package Net::Z3950::RPN::RSID;
105 package Net::Z3950::RPN::Attributes;
106 package Net::Z3950::RPN::Attribute;
108 # Must revert to original package for Autoloader's benefit
109 package Net::Z3950::SimpleServer;
112 # Autoload methods go after =cut, and are processed by the autosplit program.
116 # Below is the stub of documentation for your module. You better edit it!
120 Net::Z3950::SimpleServer - Simple Perl API for building Z39.50 servers.
124 use Net::Z3950::SimpleServer;
126 sub my_search_handler {
129 my $set_id = $args->{SETNAME};
130 my @database_list = @{ $args->{DATABASES} };
131 my $query = $args->{QUERY};
133 ## Perform the query on the specified set of databases
134 ## and return the number of hits:
136 $args->{HITS} = $hits;
139 sub my_fetch_handler { # Get a record for the user
142 my $set_id = $args->{SETNAME};
144 my $record = fetch_a_record($args->{OFFSET});
146 $args->{RECORD} = $record;
147 if (number_of_hits() == $args->{OFFSET}) { ## Last record in set?
155 ## Register custom event handlers:
157 my $z = new Net::Z3950::SimpleServer( INIT => \&my_init_handler,
158 CLOSE => \&my_close_handler,
159 SEARCH => \&my_search_handler,
160 FETCH => \&my_fetch_handler);
163 $z->launch_server("ztest.pl", @ARGV);
167 The SimpleServer module is a tool for constructing Z39.50 "Information
168 Retrieval" servers in Perl. The module is easy to use, but it
169 does help to have an understanding of the Z39.50 query
170 structure and the construction of structured retrieval records.
172 Z39.50 is a network protocol for searching remote databases and
173 retrieving the results in the form of structured "records". It is widely
174 used in libraries around the world, as well as in the US Federal Government.
175 In addition, it is generally useful whenever you wish to integrate a number
176 of different database systems around a shared, asbtract data model.
178 The model of the module is simple: It implements a "generic" Z39.50
179 server, which invokes callback functions supplied by you to search
180 for content in your database. You can use any tools available in
181 Perl to supply the content, including modules like DBI and
184 The server will take care of managing the network connections for
185 you, and it will spawn a new process (or thread, in some
186 environments) whenever a new connection is received.
188 The programmer can specify subroutines to take care of the following type
194 - Fetching of records
195 - Scan request (browsing)
196 - Closing down connection
198 Note that only the Search and Fetch handler functions are required.
199 The module can supply default responses to the other on its own.
201 After the launching of the server, all control is given away from
202 the Perl script to the server. The server calls the registered
203 subroutines to field incoming requests from Z39.50 clients.
205 A reference to an anonymous hash is passed to each handler. Some of
206 the entries of these hashes are to be considered input and others
209 The Perl programmer specifies the event handlers for the server by
210 means of the SimpleServer object constructor
212 my $z = new Net::Z3950::SimpleServer(
213 INIT => \&my_init_handler,
214 CLOSE => \&my_close_handler,
215 SEARCH => \&my_search_handler,
216 PRESENT => \&my_present_handler,
217 SCAN => \&my_scan_handler,
218 FETCH => \&my_fetch_handler,
219 EXPLAIN => \&my_explain_handler);
221 If you want your SimpleServer to start a thread (threaded mode) to
222 handle each incoming Z39.50 request instead of forking a process
223 (forking mode), you need to register the handlers by symbol rather
224 than by code reference. Thus, in threaded mode, you will need to
225 register your handlers this way:
227 my $z = new Net::Z3950::SimpleServer(
228 INIT => "my_package::my_init_handler",
229 CLOSE => "my_package::my_close_handler",
233 where my_package is the Perl package in which your handler is
236 After the custom event handlers are declared, the server is launched
237 by means of the method
239 $z->launch_server("MyServer.pl", @ARGV);
241 Notice, the first argument should be the name of your server
242 script (for logging purposes), while the rest of the arguments
243 are documented in the YAZ toolkit manual: The section on
244 application invocation: <http://www.indexdata.dk/yaz/yaz-7.php>
246 In particular, you need to use the -T switch to start your SimpleServer
251 The init handler is called whenever a Z39.50 client is attempting
252 to logon to the server. The exchange of parameters between the
253 server and the handler is carried out via an anonymous hash reached
258 The argument hash passed to the init handler has the form
261 ## Response parameters:
263 IMP_ID => "", ## Z39.50 Implementation ID
264 IMP_NAME => "", ## Z39.50 Implementation name
265 IMP_VER => "", ## Z39.50 Implementation version
266 ERR_CODE => 0, ## Error code, cnf. Z39.50 manual
267 ERR_STR => "", ## Error string (additional info.)
268 USER => "xxx" ## If Z39.50 authentication is used,
269 ## this member contains user name
270 PASS => "yyy" ## Under same conditions, this member
271 ## contains the password in clear text
272 HANDLE => undef ## Handler of Perl data structure
275 The HANDLE member can be used to store any scalar value which will then
276 be provided as input to all subsequent calls (ie. for searching, record
277 retrieval, etc.). A common use of the handle is to store a reference to
278 a hash which may then be used to store session-specific parameters.
279 If you have any session-specific information (such as a list of
280 result sets or a handle to a back-end search engine of some sort),
281 it is always best to store them in a private session structure -
282 rather than leaving them in global variables in your script.
284 The Implementation ID, name and version are only really used by Z39.50
285 client developers to see what kind of server they're dealing with.
286 Filling these in is optional.
288 The ERR_CODE should be left at 0 (the default value) if you wish to
289 accept the connection. Any other value is interpreted as a failure
290 and the client will be shown the door, with the code and the
291 associated additional information, ERR_STR returned.
293 =head2 Search handler
295 Similarly, the search handler is called with a reference to an anony-
296 mous hash. The structure is the following:
299 ## Request parameters:
301 HANDLE => ref, ## Your session reference.
302 SETNAME => "id", ## ID of the result set
303 REPL_SET => 0, ## Replace set if already existing?
304 DATABASES => ["xxx"], ## Reference to a list of data-
306 QUERY => "query", ## The query expression
307 RPN => $obj, ## Reference to a Net::Z3950::APDU::Query
309 ## Response parameters:
311 ERR_CODE => 0, ## Error code (0=Succesful search)
312 ERR_STR => "", ## Error string
313 HITS => 0 ## Number of matches
316 Note that a search which finds 0 hits is considered successful in
317 Z39.50 terms - you should only set the ERR_CODE to a non-zero value
318 if there was a problem processing the request. The Z39.50 standard
319 provides a comprehensive list of standard diagnostic codes, and you
320 should use these whenever possible.
322 The QUERY is a tree-structure of terms combined by operators, the
323 terms being qualified by lists of attributes. The query is presented
324 to the search function in the Prefix Query Format (PQF) which is
325 used in many applications based on the YAZ toolkit. The full grammar
326 is described in the YAZ manual.
328 The following are all examples of valid queries in the PQF.
334 @or "dylan" "zimmerman"
338 @or @and bob dylan @set Result-1
340 @and @attr 1=1 "bob dylan" @attr 1=4 "slow train coming"
342 @attrset @attr 4=1 @attr 1=4 "self portrait"
344 You will need to write a recursive function or something similar to
345 parse incoming query expressions, and this is usually where a lot of
346 the work in writing a database-backend happens. Fortunately, you don't
347 need to support anymore functionality than you want to. For instance,
348 it is perfectly legal to not accept boolean operators, but you SHOULD
349 try to return good error codes if you run into something you can't or
352 A more convenient alternative to the QUERY member may be the RPN
353 member, which is a reference to a Net::Z3950::APDU::Query object
354 representing the RPN query tree. The structure of that object is
355 supposed to be self-documenting, but here's a brief summary of what
362 C<Net::Z3950::APDU::Query> is a hash with two fields:
368 =item C<attributeSet>
370 Optional. If present, it is a reference to a
371 C<Net::Z3950::APDU::OID>. This is a string of dot-separated integers
372 representing the OID of the query's top-level attribute set.
376 Mandatory: a refererence to the RPN tree itself.
382 Each node of the tree is an object of one of the following types:
388 =item C<Net::Z3950::RPN::And>
390 =item C<Net::Z3950::RPN::Or>
392 =item C<Net::Z3950::RPN::AndNot>
394 These three classes are all arrays of two elements, each of which is a
395 node of one of the above types.
397 =item C<Net::Z3950::RPN::Term>
399 See below for details.
401 =item C<Net::Z3950::RPN::RSID>
403 A reference to a result-set ID indicating a previous search. The ID
404 of the result-set is in the C<id> element.
408 (I guess I should make a superclass C<Net::Z3950::RPN::Node> and make
409 all of these subclasses of it. Not done that yet, but will do one day.)
417 C<Net::Z3950::RPN::Term> is a hash with two fields:
425 A string containing the search term itself.
429 A reference to a C<Net::Z3950::RPN::Attributes> object.
435 C<Net::Z3950::RPN::Attributes> is an array of references to
436 C<Net::Z3950::RPN::Attribute> objects. (Note the plural/singular
441 C<Net::Z3950::RPN::Attribute> is a hash with three elements:
447 =item C<attributeSet>
449 Optional. If present, it is dot-separated OID string, as above.
451 =item C<attributeType>
453 An integer indicating the type of the attribute - for example, under
454 the BIB-1 attribute set, type 1 indicates a ``use'' attribute, type 2
455 a ``relation'' attribute, etc.
457 =item C<attributeValue>
459 An integer indicating the value of the attribute - for example, under
460 BIB-1, if the attribute type is 1, then value 4 indictates a title
461 search and 7 indictates an ISBN search; but if the attribute type is
462 2, then value 4 indicates a ``greater than or equal'' search, and 102
463 indicates a relevance match.
469 Note that, at the moment, none of these classes have any methods at
470 all: the blessing into classes is largely just a documentation thing
471 so that, for example, if you do
473 { use Data::Dumper; print Dumper($args->{RPN}) }
475 you get something fairly human-readable. But of course, the type
476 distinction between the three different kinds of boolean node is
479 By adding your own methods to these classes (building what I call
480 ``augmented classes''), you can easily build code that walks the tree
481 of the incoming RPN. Take a look at C<samples/render-search.pl> for a
482 sample implementation of such an augmented classes technique.
485 =head2 Present handler
487 The presence of a present handler in a SimpleServer front-end is optional.
488 Each time a client wishes to retrieve records, the present service is
489 called. The present service allows the origin to request a certain number
490 of records retrieved from a given result set.
491 When the present handler is called, the front-end server should prepare a
492 result set for fetching. In practice, this means to get access to the
493 data from the backend database and store the data in a temporary fashion
494 for fast and efficient fetching. The present handler does *not* fetch
495 anything. This task is taken care of by the fetch handler, which will be
496 called the correct number of times by the YAZ library. More about this
498 If no present handler is implemented in the front-end, the YAZ toolkit
499 will take care of a minimum of preparations itself. This default present
500 handler is sufficient in many situations, where only a small amount of
501 records are expected to be retrieved. If on the other hand, large result
502 sets are likely to occur, the implementation of a reasonable present
503 handler can gain performance significantly.
505 The informations exchanged between client and present handle are:
508 ## Client/server request:
510 HANDLE => ref, ## Reference to datastructure
511 SETNAME => "id", ## Result set ID
512 START => xxx, ## Start position
513 COMP => "", ## Desired record composition
514 NUMBER => yyy, ## Number of requested records
517 ## Respons parameters:
519 HITS => zzz, ## Number of returned records
520 ERR_CODE => 0, ## Error code
521 ERR_STR => "" ## Error message
527 The fetch handler is asked to retrieve a SINGLE record from a given
528 result set (the front-end server will automatically call the fetch
529 handler as many times as required).
531 The parameters exchanged between the server and the fetch handler are
534 ## Client/server request:
536 HANDLE => ref ## Reference to data structure
537 SETNAME => "id" ## ID of the requested result set
538 OFFSET => nnn ## Record offset number
539 REQ_FORM => "n.m.k.l"## Client requested format OID
540 COMP => "xyz" ## Formatting instructions
541 SCHEMA => "abc" ## Requested schema, if any
545 RECORD => "" ## Record string
546 BASENAME => "" ## Origin of returned record
547 LAST => 0 ## Last record in set?
548 ERR_CODE => 0 ## Error code
549 ERR_STR => "" ## Error string
550 SUR_FLAG => 0 ## Surrogate diagnostic flag
551 REP_FORM => "n.m.k.l"## Provided format OID
552 SCHEMA => "abc" ## Provided schema, if any
555 The REP_FORM value has by default the REQ_FORM value but can be set to
556 something different if the handler desires. The BASENAME value should
557 contain the name of the database from where the returned record originates.
558 The ERR_CODE and ERR_STR works the same way they do in the search
559 handler. If there is an error condition, the SUR_FLAG is used to
560 indicate whether the error condition pertains to the record currently
561 being retrieved, or whether it pertains to the operation as a whole
562 (eg. the client has specified a result set which does not exist.)
564 If you need to return USMARC records, you might want to have a look at
565 the MARC module on CPAN, if you don't already have a way of generating
568 NOTE: The record offset is 1-indexed - 1 is the offset of the first
573 A full featured Z39.50 server should support scan (or in some literature
574 browse). The client specifies a starting term of the scan, and the server
575 should return an ordered list of specified length consisting of terms
576 actually occurring in the data base. Each of these terms should be close
577 to or equal to the term originally specified. The quality of scan compared
578 to simple search is a guarantee of hits. It is simply like browsing through
579 an index of a book, you always find something! The parameters exchanged are
584 HANDLE => $ref ## Reference to data structure
585 TERM => 'start', ## The start term
586 NUMBER => xx, ## Number of requested terms
587 POS => yy, ## Position of starting point
588 ## within returned list
589 STEP => 0, ## Step size
593 ERR_CODE => 0, ## Error code
594 ERR_STR => '', ## Diagnostic message
595 NUMBER => zz, ## Number of returned terms
596 STATUS => $status, ## ScanSuccess/ScanFailure
597 ENTRIES => $entries ## Referenced list of terms
600 where the term list is returned by reference in the scalar $entries, which
601 should point at a data structure of this kind,
607 { TERM => 'energy density',
610 { TERM => 'energy flow',
618 The $status flag should be assigned one of two values:
620 Net::Z3950::SimpleServer::ScanSuccess On success (default)
621 Net::Z3950::SimpleServer::ScanPartial Less terms returned than requested
623 The STEP member contains the requested number of entries in the term-list
624 between two adjacent entries in the response.
628 The argument hash recieved by the close handler has one element only:
632 HANDLE => ref ## Reference to data structure
635 What ever data structure the HANDLE value points at goes out of scope
636 after this call. If you need to close down a connection to your server
637 or something similar, this is the place to do it.
639 =head2 Support for SRU and SRW
641 Since release 1.0, SimpleServer includes support for serving the SRU
642 and SRW protocols as well as Z39.50. These ``web-friendly'' protocols
643 enable similar functionality to that of Z39.50, but by means of rich
644 URLs in the case of SRU, and a SOAP-based web-service in the case of
645 SRW. These protocols are described at
646 http://www.loc.gov/sru
648 In order to serve these protocols from a SimpleServer-based
649 application, it is necessary to launch the application with a YAZ
650 Generic Frontend Server (GFS) configuration file, which can be
651 specified using the command-line argument C<-f> I<filename>. A
652 minimal configuration file looks like this:
656 <cql2rpn>pqf.properties</cql2rpn>
660 This file specifies only that C<pqf.properties> should be used to
661 translate the CQL queries of SRU and SRW into corresponding Z39.50
662 Type-1 queries. For more information about YAZ GFS configuration,
663 including how to specify an Explain record, see the I<Virtual Hosts>
664 section of the YAZ manual at
665 http://indexdata.com/yaz/doc/server.vhosts.tkl
667 The mapping of CQL queries into Z39.50 Type-1 queries is specified by
668 a file that indicates which BIB-1 attributes should be generated for
669 each CQL index, relation, modifiers, etc. A typical section of this
670 file looks like this:
673 index.dc.subject = 1=21
674 index.dc.creator = 1=1003
678 This file specifies the BIB-1 access points (type=1) for the Dublin
679 Core indexes C<title>, C<subject> and C<creator>, and the BIB-1
680 relations (type=2) corresponding to the CQL relations C<E<lt>> and
681 C<E<lt>=>. For more information about the format of this file, see
682 the I<CQL> section of the YAZ manual at
683 http://indexdata.com/yaz/doc/tools.tkl#tools.cql
685 The YAZ distribution include a sample CQL-to-PQF mapping configuration
686 file called C<pqf.properties>; this is sufficient for many
687 applications, and a good base to work from for most others.
689 If a SimpleServer-based application is run without this SRU-specific
690 configuration, it can still serve SRU; however, CQL queries will not
691 be translated, but passed straight through to the search-handler
692 function, as the C<CQL> member of the parameters hash. It is then the
693 responsibility of the back-end application to parse and handle the CQL
694 query, which is most easily done using Ed Summers' fine C<CQL::Parser>
695 module, available from CPAN at
696 http://search.cpan.org/~esummers/CQL-Parser/
700 Anders Sønderberg (sondberg@indexdata.dk),
701 Sebastian Hammer (quinn@indexdata.dk),
702 Mike Taylor (indexdata.com).
706 Any Perl module which is useful for accessing the database of your