2 ## Copyright (c) 2000, 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 ## $Log: SimpleServer.pm,v $
29 ## Revision 1.12 2002-03-05 20:52:22 sondberg
30 ## Version 0.05 so that we can release the thing at CPAN.
32 ## Revision 1.11 2002/03/05 20:49:56 sondberg
33 ## Added a couple of lines of documentation.
35 ## Revision 1.10 2002/02/28 11:21:57 mike
36 ## Add RPN structure to search-handler argument hash.
38 ## Revision 1.9 2001/08/29 11:48:36 sondberg
41 ## Net::Z3950::SimpleServer::ScanSuccess
42 ## Net::Z3950::SimpleServer::ScanPartial
44 ## and a bit of documentation.
46 ## Revision 1.8 2001/08/29 10:29:51 sondberg
47 ## Added some documentation of scan.
49 ## Revision 1.7 2001/08/24 14:00:20 sondberg
50 ## Added support for scan.
52 ## Revision 1.6 2001/03/13 14:17:15 sondberg
53 ## Added support for GRS-1.
56 package Net::Z3950::SimpleServer;
59 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
66 @ISA = qw(Exporter AutoLoader DynaLoader);
67 # Items to export into callers namespace by default. Note: do not export
68 # names by default without a very good reason. Use EXPORT_OK instead.
69 # Do not simply export all your public functions/methods/constants.
75 bootstrap Net::Z3950::SimpleServer $VERSION;
77 # Preloaded methods go here.
87 carp "SimpleServer.pm: WARNING: Multithreaded server unsupported";
91 croak "SimpleServer.pm: ERROR: Unspecified search handler" unless defined($self->{SEARCH});
92 croak "SimpleServer.pm: ERROR: Unspecified fetch handler" unless defined($self->{FETCH});
103 if (defined($self->{INIT})) {
104 set_init_handler($self->{INIT});
106 set_search_handler($self->{SEARCH});
107 set_fetch_handler($self->{FETCH});
108 if (defined($self->{CLOSE})) {
109 set_close_handler($self->{CLOSE});
111 if (defined($self->{PRESENT})) {
112 set_present_handler($self->{PRESENT});
114 if (defined($self->{SCAN})) {
115 set_scan_handler($self->{SCAN});
122 # Register packages that we will use in translated RPNs
123 package Net::Z3950::APDU::Query;
124 package Net::Z3950::APDU::OID;
125 package Net::Z3950::RPN::And;
126 package Net::Z3950::RPN::Or;
127 package Net::Z3950::RPN::AndNot;
128 package Net::Z3950::RPN::Term;
129 package Net::Z3950::RPN::Attributes;
130 package Net::Z3950::RPN::Attribute;
132 # Must revert to original package for Autoloader's benefit
133 package Net::Z3950::SimpleServer;
136 # Autoload methods go after =cut, and are processed by the autosplit program.
140 # Below is the stub of documentation for your module. You better edit it!
144 Net::Z3950::SimpleServer - Simple Perl API for building Z39.50 servers.
148 use Net::Z3950::SimpleServer;
150 sub my_search_handler {
153 my $set_id = $args->{SETNAME};
154 my @database_list = @{ $args->{DATABASES} };
155 my $query = $args->{QUERY};
157 ## Perform the query on the specified set of databases
158 ## and return the number of hits:
160 $args->{HITS} = $hits;
163 sub my_fetch_handler { # Get a record for the user
166 my $set_id = $args->{SETNAME};
168 my $record = fetch_a_record($args->{OFFSET});
170 $args->{RECORD} = $record;
171 if (number_of_hits() == $args->{OFFSET}) { ## Last record in set?
179 ## Register custom event handlers:
181 my $z = new Net::Z3950::SimpleServer( INIT => \&my_init_handler,
182 CLOSE => \&my_close_handler,
183 SEARCH => \&my_search_handler,
184 FETCH => \&my_fetch_handler);
187 $z->launch_server("ztest.pl", @ARGV);
191 The SimpleServer module is a tool for constructing Z39.50 "Information
192 Retrieval" servers in Perl. The module is easy to use, but it
193 does help to have an understanding of the Z39.50 query
194 structure and the construction of structured retrieval records.
196 Z39.50 is a network protocol for searching remote databases and
197 retrieving the results in the form of structured "records". It is widely
198 used in libraries around the world, as well as in the US Federal Government.
199 In addition, it is generally useful whenever you wish to integrate a number
200 of different database systems around a shared, asbtract data model.
202 The model of the module is simple: It implements a "generic" Z39.50
203 server, which invokes callback functions supplied by you to search
204 for content in your database. You can use any tools available in
205 Perl to supply the content, including modules like DBI and
208 The server will take care of managing the network connections for
209 you, and it will spawn a new process (or thread, in some
210 environments) whenever a new connection is received.
212 The programmer can specify subroutines to take care of the following type
218 - Fetching of records
219 - Scan request (browsing)
220 - Closing down connection
222 Note that only the Search and Fetch handler functions are required.
223 The module can supply default responses to the other on its own.
225 After the launching of the server, all control is given away from
226 the Perl script to the server. The server calls the registered
227 subroutines to field incoming requests from Z39.50 clients.
229 A reference to an anonymous hash is passed to each handle. Some of
230 the entries of these hashes are to be considered input and others
233 The Perl programmer specifies the event handles for the server by
234 means of the the SimpleServer object constructor
236 my $z = new Net::Z3950::SimpleServer(
237 INIT => \&my_init_handler,
238 CLOSE => \&my_close_handler,
239 SEARCH => \&my_search_handler,
240 PRESENT => \&my_present_handler,
241 SCAN => \&my_scan_handler,
242 FETCH => \&my_fetch_handler);
244 After the custom event handles are declared, the server is launched
245 by means of the method
247 $z->launch_server("MyServer.pl", @ARGV);
249 Notice, the first argument should be the name of your server
250 script (for logging purposes), while the rest of the arguments
251 are documented in the YAZ toolkit manual: The section on
252 application invocation: <http://www.indexdata.dk/yaz/yaz-7.php>
256 The init handler is called whenever a Z39.50 client is attempting
257 to logon to the server. The exchange of parameters between the
258 server and the handler is carried out via an anonymous hash reached
263 The argument hash passed to the init handler has the form
266 ## Response parameters:
268 IMP_NAME => "", ## Z39.50 Implementation name
269 IMP_VER => "", ## Z39.50 Implementation version
270 ERR_CODE => 0, ## Error code, cnf. Z39.50 manual
271 HANDLE => undef ## Handler of Perl data structure
274 The HANDLE member can be used to store any scalar value which will then
275 be provided as input to all subsequent calls (ie. for searching, record
276 retrieval, etc.). A common use of the handle is to store a reference to
277 a hash which may then be used to store session-specific parameters.
278 If you have any session-specific information (such as a list of
279 result sets or a handle to a back-end search engine of some sort),
280 it is always best to store them in a private session structure -
281 rather than leaving them in global variables in your script.
283 The Implementation name and version are only really used by Z39.50
284 client developers to see what kind of server they're dealing with.
285 Filling these in is optional.
287 The ERR_CODE should be left at 0 (the default value) if you wish to
288 accept the connection. Any other value is interpreted as a failure
289 and the client will be shown the door.
291 =head2 Search handler
293 Similarly, the search handler is called with a reference to an anony-
294 mous hash. The structure is the following:
297 ## Request parameters:
299 HANDLE => ref, ## Your session reference.
300 SETNAME => "id", ## ID of the result set
301 REPL_SET => 0, ## Replace set if already existing?
302 DATABASES => ["xxx"], ## Reference to a list of data-
304 QUERY => "query", ## The query expression
305 RPN => $obj, ## Blessed reference int the package
306 ## Net::Z3950::APDU::Query
308 ## Response parameters:
310 ERR_CODE => 0, ## Error code (0=Succesful search)
311 ERR_STR => "", ## Error string
312 HITS => 0 ## Number of matches
315 Note that a search which finds 0 hits is considered successful in
316 Z39.50 terms - you should only set the ERR_CODE to a non-zero value
317 if there was a problem processing the request. The Z39.50 standard
318 provides a comprehensive list of standard diagnostic codes, and you
319 should use these whenever possible.
321 The QUERY is a tree-structure of terms combined by operators, the
322 terms being qualified by lists of attributes. The query is presented
323 to the search function in the Prefix Query Format (PQF) which is
324 used in many applications based on the YAZ toolkit. The full grammar
325 is described in the YAZ manual.
327 The following are all examples of valid queries in the PQF.
333 @or "dylan" "zimmerman"
337 @or @and bob dylan @set Result-1
339 @and @attr 1=1 "bob dylan" @attr 1=4 "slow train coming"
341 @attrset @attr 4=1 @attr 1=4 "self portrait"
343 You will need to write a recursive function or something similar to
344 parse incoming query expressions, and this is usually where a lot of
345 the work in writing a database-backend happens. Fortunately, you don't
346 need to support anymore functionality than you want to. For instance,
347 it is perfectly legal to not accept boolean operators, but you SHOULD
348 try to return good error codes if you run into something you can't or
351 The RPN member is a blessed reference into the package Net::Z3950::APDU::Query.
352 By means of an augmented type of coding, you can easily construct a
353 parser of the incoming RPN. Take a look at samples/render-search.pl for
354 a sample implementation of such an augmented parser technique.
356 =head2 Present handler
358 The presence of a present handler in a SimpleServer front-end is optional.
359 Each time a client wishes to retrieve records, the present service is
360 called. The present service allows the origin to request a certain number
361 of records retrieved from a given result set.
362 When the present handler is called, the front-end server should prepare a
363 result set for fetching. In practice, this means to get access to the
364 data from the backend database and store the data in a temporary fashion
365 for fast and efficient fetching. The present handler does *not* fetch
366 anything. This task is taken care of by the fetch handler, which will be
367 called the correct number of times by the YAZ library. More about this
369 If no present handler is implemented in the front-end, the YAZ toolkit
370 will take care of a minimum of preparations itself. This default present
371 handler is sufficient in many situations, where only a small amount of
372 records are expected to be retrieved. If on the other hand, large result
373 sets are likely to occur, the implementation of a reasonable present
374 handler can gain performance significantly.
376 The informations exchanged between client and present handle are:
379 ## Client/server request:
381 HANDLE => ref, ## Reference to datastructure
382 SETNAME => "id", ## Result set ID
383 START => xxx, ## Start position
384 COMP => "", ## Desired record composition
385 NUMBER => yyy, ## Number of requested records
388 ## Respons parameters:
390 HITS => zzz, ## Number of returned records
391 ERR_CODE => 0, ## Error code
392 ERR_STR => "" ## Error message
398 The fetch handler is asked to retrieve a SINGLE record from a given
399 result set (the front-end server will automatically call the fetch
400 handler as many times as required).
402 The parameters exchanged between the server and the fetch handler are
405 ## Client/server request:
407 HANDLE => ref ## Reference to data structure
408 SETNAME => "id" ## ID of the requested result set
409 OFFSET => nnn ## Record offset number
410 REQ_FORM => "n.m.k.l"## Client requested format OID
411 COMP => "xyz" ## Formatting instructions
415 RECORD => "" ## Record string
416 BASENAME => "" ## Origin of returned record
417 LAST => 0 ## Last record in set?
418 ERR_CODE => 0 ## Error code
419 ERR_STR => "" ## Error string
420 SUR_FLAG => 0 ## Surrogate diagnostic flag
421 REP_FORM => "n.m.k.l"## Provided format OID
424 The REP_FORM value has by default the REQ_FORM value but can be set to
425 something different if the handler desires. The BASENAME value should
426 contain the name of the database from where the returned record originates.
427 The ERR_CODE and ERR_STR works the same way they do in the search
428 handler. If there is an error condition, the SUR_FLAG is used to
429 indicate whether the error condition pertains to the record currently
430 being retrieved, or whether it pertains to the operation as a whole
431 (eg. the client has specified a result set which does not exist.)
433 If you need to return USMARC records, you might want to have a look at
434 the MARC module on CPAN, if you don't already have a way of generating
437 NOTE: The record offset is 1-indexed - 1 is the offset of the first
442 A full featured Z39.50 server should support scan (or in some literature
443 browse). The client specifies a starting term of the scan, and the server
444 should return an ordered list of specified length consisting of terms
445 actually occurring in the data base. Each of these terms should be close
446 to or equal to the term originally specified. The quality of scan compared
447 to simple search is a guarantee of hits. It is simply like browsing through
448 an index of a book, you always find something! The parameters exchanged are
453 HANDLE => $ref ## Reference to data structure
454 TERM => 'start', ## The start term
455 NUMBER => xx, ## Number of requested terms
456 POS => yy, ## Position of starting point
457 ## within returned list
458 STEP => 0, ## Step size
462 ERR_CODE => 0, ## Error code
463 ERR_STR => '', ## Diagnostic message
464 NUMBER => zz, ## Number of returned terms
465 STATUS => $status, ## ScanSuccess/ScanFailure
466 ENTRIES => $entries ## Referenced list of terms
469 where the term list is returned by reference in the scalar $entries, which
470 should point at a data structure of this kind,
476 { TERM => 'energy density',
479 { TERM => 'energy flow',
487 The $status flag should be assigned one of two values:
489 Net::Z3950::SimpleServer::ScanSuccess On success (default)
490 Net::Z3950::SimpleServer::ScanPartial Less terms returned than requested
492 The STEP member contains the requested number of entries in the term-list
493 between two adjacent entries in the response.
497 The argument hash recieved by the close handler has one element only:
501 HANDLE => ref ## Reference to data structure
504 What ever data structure the HANDLE value points at goes out of scope
505 after this call. If you need to close down a connection to your server
506 or something similar, this is the place to do it.
510 Anders Sønderberg (sondberg@indexdata.dk) and Sebastian Hammer
511 (quinn@indexdata.dk). Substantial contributions made by Mike Taylor (mike@tecc.co.uk).
517 Any Perl module which is useful for accessing the database of your