Added proper header for reader record utilities for yaz-ztest.
[yaz-moved-to-github.git] / ztest / ztest.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2008 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /*
7  * Demonstration of simple server
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13 #if HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16
17 #include <yaz/log.h>
18 #include <yaz/backend.h>
19 #include <yaz/ill.h>
20 #include <yaz/diagbib1.h>
21
22 #include "ztest.h"
23
24 static int log_level=0;
25 static int log_level_set=0;
26
27 int ztest_search(void *handle, bend_search_rr *rr);
28 int ztest_sort(void *handle, bend_sort_rr *rr);
29 int ztest_present(void *handle, bend_present_rr *rr);
30 int ztest_esrequest(void *handle, bend_esrequest_rr *rr);
31 int ztest_delete(void *handle, bend_delete_rr *rr);
32
33 /** \fn get_term_hit
34     \brief use term value as hit count 
35    
36     Traverse RPN tree 'in order' and use term value as hit count.
37     Only terms  that looks a numeric is used.. Returns -1 if
38     no sub tree has a hit count term
39 */
40 static int get_term_hit(Z_RPNStructure *s)
41 {
42     int h = -1;
43     switch(s->which)
44     {
45     case Z_RPNStructure_simple:
46         if (s->u.simple->which == Z_Operand_APT)
47         {
48             Z_AttributesPlusTerm *apt = s->u.simple->u.attributesPlusTerm;
49             if (apt->term->which == Z_Term_general)
50             {
51                 Odr_oct *oct = apt->term->u.general;
52                 if (oct->len > 0 && oct->buf[0] >= '0' && oct->buf[0] <= '9')
53                     h = atoi_n((const char *) oct->buf, oct->len);
54             }
55         }
56         break;
57     case Z_RPNStructure_complex:
58         h = get_term_hit(s->u.complex->s1);
59         if (h == -1)
60             h = get_term_hit(s->u.complex->s2);
61         break;
62     }
63     return h;
64 }
65
66 /** \fn get_hit_count
67     \brief gets hit count for numeric terms in RPN queries
68     
69     This is just for testing.. A real database of course uses
70     the content of a database to establish a value.. In our case, we
71     have a way to trigger a certain hit count. Good for testing of
72     client applications etc
73 */
74 static int get_hit_count(Z_Query *q)
75 {
76     int h = -1;
77     if (q->which == Z_Query_type_1 || q->which == Z_Query_type_101)
78         h = get_term_hit(q->u.type_1->RPNStructure);
79     if (h == -1)
80         h = rand() % 24;
81     return h;
82 }
83
84 int ztest_search(void *handle, bend_search_rr *rr)
85 {
86     if (rr->num_bases != 1)
87     {
88         rr->errcode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
89         return 0;
90     }
91     /* Throw Database unavailable if other than Default or Slow */
92     if (!yaz_matchstr (rr->basenames[0], "Default"))
93         ;  /* Default is OK in our test */
94     else if(!yaz_matchstr (rr->basenames[0], "Slow"))
95     {
96 #if HAVE_UNISTD_H
97         /* wait up to 3 seconds and check if connection is still alive */
98         int i;
99         for (i = 0; i<3; i++)
100         {
101             if (!bend_assoc_is_alive(rr->association))
102             {
103                 yaz_log(YLOG_LOG, "search aborted");
104                 break;
105             }
106             sleep(1);
107         }
108 #endif
109         rr->estimated_hit_count = 1;
110     }
111     else
112     {
113         rr->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
114         rr->errstring = rr->basenames[0];
115         return 0;
116     }
117
118     rr->hits = get_hit_count(rr->query);
119     return 0;
120 }
121
122
123 /* this huge function handles extended services */
124 int ztest_esrequest (void *handle, bend_esrequest_rr *rr)
125 {
126     /* user-defined handle - created in bend_init */
127     int *counter = (int*) handle;  
128
129     yaz_log(log_level, "ESRequest no %d", *counter);
130
131     (*counter)++;
132
133     if (rr->esr->packageName)
134         yaz_log(log_level, "packagename: %s", rr->esr->packageName);
135     yaz_log(log_level, "Waitaction: %d", *rr->esr->waitAction);
136
137
138     yaz_log(log_level, "function: %d", *rr->esr->function);
139
140     if (!rr->esr->taskSpecificParameters)
141     {
142         yaz_log (log_level, "No task specific parameters");
143     }
144     else if (rr->esr->taskSpecificParameters->which == Z_External_itemOrder)
145     {
146         Z_ItemOrder *it = rr->esr->taskSpecificParameters->u.itemOrder;
147         yaz_log (log_level, "Received ItemOrder");
148         if (it->which == Z_IOItemOrder_esRequest)
149         {
150             Z_IORequest *ir = it->u.esRequest;
151             Z_IOOriginPartToKeep *k = ir->toKeep;
152             Z_IOOriginPartNotToKeep *n = ir->notToKeep;
153             const char *xml_in_response = 0;
154             
155             if (k && k->contact)
156             {
157                 if (k->contact->name)
158                     yaz_log(log_level, "contact name %s", k->contact->name);
159                 if (k->contact->phone)
160                     yaz_log(log_level, "contact phone %s", k->contact->phone);
161                 if (k->contact->email)
162                     yaz_log(log_level, "contact email %s", k->contact->email);
163             }
164             if (k->addlBilling)
165             {
166                 yaz_log(log_level, "Billing info (not shown)");
167             }
168             
169             if (n->resultSetItem)
170             {
171                 yaz_log(log_level, "resultsetItem");
172                 yaz_log(log_level, "setId: %s", n->resultSetItem->resultSetId);
173                 yaz_log(log_level, "item: %d", *n->resultSetItem->item);
174             }
175             if (n->itemRequest)
176             {
177                 Z_External *r = (Z_External*) n->itemRequest;
178                 ILL_ItemRequest *item_req = 0;
179                 ILL_APDU *ill_apdu = 0;
180                 if (r->direct_reference)
181                 {
182                     char oid_name_str[OID_STR_MAX];
183                     oid_class oclass;
184                     const char *oid_name = 
185                         yaz_oid_to_string_buf(r->direct_reference,
186                                           &oclass, oid_name_str);
187                     if (oid_name)
188                         yaz_log(log_level, "OID %s", oid_name);
189                     if (!oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
190                     {
191                         yaz_log (log_level, "ILL XML request");
192                         if (r->which == Z_External_octet)
193                             yaz_log (log_level, "%.*s",
194                                      r->u.octet_aligned->len,
195                                      r->u.octet_aligned->buf); 
196                         xml_in_response = "<dummy>x</dummy>";
197                     }
198                     if (!oid_oidcmp(r->direct_reference, 
199                                     yaz_oid_general_isoill_1))
200                     {
201                         yaz_log (log_level, "Decode ItemRequest begin");
202                         if (r->which == ODR_EXTERNAL_single)
203                         {
204                             odr_setbuf(rr->decode,
205                                        (char *) r->u.single_ASN1_type->buf,
206                                        r->u.single_ASN1_type->len, 0);
207                             
208                             if (!ill_ItemRequest (rr->decode, &item_req, 0, 0))
209                             {
210                                 yaz_log (log_level,
211                                     "Couldn't decode ItemRequest %s near %ld",
212                                        odr_errmsg(odr_geterror(rr->decode)),
213                                        (long) odr_offset(rr->decode));
214                             }
215                             else
216                                 yaz_log(log_level, "Decode ItemRequest OK");
217                             if (rr->print)
218                             {
219                                 ill_ItemRequest (rr->print, &item_req, 0,
220                                     "ItemRequest");
221                                 odr_reset (rr->print);
222                             }
223                         }
224                         if (!item_req && r->which == ODR_EXTERNAL_single)
225                         {
226                             yaz_log (log_level, "Decode ILL APDU begin");
227                             odr_setbuf(rr->decode,
228                                        (char*) r->u.single_ASN1_type->buf,
229                                        r->u.single_ASN1_type->len, 0);
230                             
231                             if (!ill_APDU (rr->decode, &ill_apdu, 0, 0))
232                             {
233                                 yaz_log (log_level,
234                                     "Couldn't decode ILL APDU %s near %ld",
235                                        odr_errmsg(odr_geterror(rr->decode)),
236                                        (long) odr_offset(rr->decode));
237                                 yaz_log(log_level, "PDU dump:");
238                                 odr_dumpBER(yaz_log_file(),
239                                      (char *) r->u.single_ASN1_type->buf,
240                                      r->u.single_ASN1_type->len);
241                             }
242                             else
243                                 yaz_log(log_level, "Decode ILL APDU OK");
244                             if (rr->print)
245                             {
246                                 ill_APDU (rr->print, &ill_apdu, 0,
247                                     "ILL APDU");
248                                 odr_reset (rr->print);
249                             }
250                         }
251                     }
252                 }
253                 if (item_req)
254                 {
255                     yaz_log (log_level, "ILL protocol version = %d",
256                              *item_req->protocol_version_num);
257                 }
258             }
259             if (k)
260             {
261
262                 Z_External *ext = (Z_External *)
263                     odr_malloc (rr->stream, sizeof(*ext));
264                 Z_IUOriginPartToKeep *keep = (Z_IUOriginPartToKeep *)
265                     odr_malloc (rr->stream, sizeof(*keep));
266                 Z_IOTargetPart *targetPart = (Z_IOTargetPart *)
267                     odr_malloc (rr->stream, sizeof(*targetPart));
268
269                 rr->taskPackage = (Z_TaskPackage *)
270                     odr_malloc (rr->stream, sizeof(*rr->taskPackage));
271                 rr->taskPackage->packageType =
272                     odr_oiddup (rr->stream, rr->esr->packageType);
273                 rr->taskPackage->packageName = 0;
274                 rr->taskPackage->userId = 0;
275                 rr->taskPackage->retentionTime = 0;
276                 rr->taskPackage->permissions = 0;
277                 rr->taskPackage->description = 0;
278                 rr->taskPackage->targetReference = (Odr_oct *)
279                     odr_malloc (rr->stream, sizeof(Odr_oct));
280                 rr->taskPackage->targetReference->buf =
281                     (unsigned char *) odr_strdup (rr->stream, "911");
282                 rr->taskPackage->targetReference->len =
283                     rr->taskPackage->targetReference->size =
284                     strlen((char *) (rr->taskPackage->targetReference->buf));
285                 rr->taskPackage->creationDateTime = 0;
286                 rr->taskPackage->taskStatus = odr_intdup(rr->stream, 0);
287                 rr->taskPackage->packageDiagnostics = 0;
288                 rr->taskPackage->taskSpecificParameters = ext;
289
290                 ext->direct_reference =
291                     odr_oiddup (rr->stream, rr->esr->packageType);
292                 ext->indirect_reference = 0;
293                 ext->descriptor = 0;
294                 ext->which = Z_External_itemOrder;
295                 ext->u.itemOrder = (Z_ItemOrder *)
296                     odr_malloc (rr->stream, sizeof(*ext->u.update));
297                 ext->u.itemOrder->which = Z_IOItemOrder_taskPackage;
298                 ext->u.itemOrder->u.taskPackage =  (Z_IOTaskPackage *)
299                     odr_malloc (rr->stream, sizeof(Z_IOTaskPackage));
300                 ext->u.itemOrder->u.taskPackage->originPart = k;
301                 ext->u.itemOrder->u.taskPackage->targetPart = targetPart;
302
303                 if (xml_in_response)
304                     targetPart->itemRequest =
305                         z_ext_record_xml(rr->stream, xml_in_response,
306                                          strlen(xml_in_response));
307                 else
308                     targetPart->itemRequest = 0;
309                     
310                 targetPart->statusOrErrorReport = 0;
311                 targetPart->auxiliaryStatus = 0;
312             }
313         }
314     }
315     else if (rr->esr->taskSpecificParameters->which == Z_External_update)
316     {
317         Z_IUUpdate *up = rr->esr->taskSpecificParameters->u.update;
318         yaz_log (log_level, "Received DB Update");
319         if (up->which == Z_IUUpdate_esRequest)
320         {
321             Z_IUUpdateEsRequest *esRequest = up->u.esRequest;
322             Z_IUOriginPartToKeep *toKeep = esRequest->toKeep;
323             Z_IUSuppliedRecords *notToKeep = esRequest->notToKeep;
324             
325             yaz_log (log_level, "action");
326             if (toKeep->action)
327             {
328                 switch (*toKeep->action)
329                 {
330                 case Z_IUOriginPartToKeep_recordInsert:
331                     yaz_log (log_level, " recordInsert");
332                     break;
333                 case Z_IUOriginPartToKeep_recordReplace:
334                     yaz_log (log_level, " recordReplace");
335                     break;
336                 case Z_IUOriginPartToKeep_recordDelete:
337                     yaz_log (log_level, " recordDelete");
338                     break;
339                 case Z_IUOriginPartToKeep_elementUpdate:
340                     yaz_log (log_level, " elementUpdate");
341                     break;
342                 case Z_IUOriginPartToKeep_specialUpdate:
343                     yaz_log (log_level, " specialUpdate");
344                     break;
345                 default:
346                     yaz_log (log_level, " unknown (%d)", *toKeep->action);
347                 }
348             }
349             if (toKeep->databaseName)
350             {
351                 yaz_log (log_level, "database: %s", toKeep->databaseName);
352                 if (!strcmp(toKeep->databaseName, "fault"))
353                 {
354                     rr->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
355                     rr->errstring = toKeep->databaseName;
356                 }
357                 if (!strcmp(toKeep->databaseName, "accept"))
358                     rr->errcode = -1;
359             }
360             if (toKeep)
361             {
362                 Z_External *ext = (Z_External *)
363                     odr_malloc (rr->stream, sizeof(*ext));
364                 Z_IUOriginPartToKeep *keep = (Z_IUOriginPartToKeep *)
365                     odr_malloc (rr->stream, sizeof(*keep));
366                 Z_IUTargetPart *targetPart = (Z_IUTargetPart *)
367                     odr_malloc (rr->stream, sizeof(*targetPart));
368
369                 rr->taskPackage = (Z_TaskPackage *)
370                     odr_malloc (rr->stream, sizeof(*rr->taskPackage));
371                 rr->taskPackage->packageType =
372                     odr_oiddup (rr->stream, rr->esr->packageType);
373                 rr->taskPackage->packageName = 0;
374                 rr->taskPackage->userId = 0;
375                 rr->taskPackage->retentionTime = 0;
376                 rr->taskPackage->permissions = 0;
377                 rr->taskPackage->description = 0;
378                 rr->taskPackage->targetReference = (Odr_oct *)
379                     odr_malloc (rr->stream, sizeof(Odr_oct));
380                 rr->taskPackage->targetReference->buf =
381                     (unsigned char *) odr_strdup (rr->stream, "123");
382                 rr->taskPackage->targetReference->len =
383                     rr->taskPackage->targetReference->size =
384                     strlen((char *) (rr->taskPackage->targetReference->buf));
385                 rr->taskPackage->creationDateTime = 0;
386                 rr->taskPackage->taskStatus = odr_intdup(rr->stream, 0);
387                 rr->taskPackage->packageDiagnostics = 0;
388                 rr->taskPackage->taskSpecificParameters = ext;
389
390                 ext->direct_reference =
391                     odr_oiddup (rr->stream, rr->esr->packageType);
392                 ext->indirect_reference = 0;
393                 ext->descriptor = 0;
394                 ext->which = Z_External_update;
395                 ext->u.update = (Z_IUUpdate *)
396                     odr_malloc (rr->stream, sizeof(*ext->u.update));
397                 ext->u.update->which = Z_IUUpdate_taskPackage;
398                 ext->u.update->u.taskPackage =  (Z_IUUpdateTaskPackage *)
399                     odr_malloc (rr->stream, sizeof(Z_IUUpdateTaskPackage));
400                 ext->u.update->u.taskPackage->originPart = keep;
401                 ext->u.update->u.taskPackage->targetPart = targetPart;
402
403                 keep->action = (int *) odr_malloc (rr->stream, sizeof(int));
404                 *keep->action = *toKeep->action;
405                 keep->databaseName =
406                     odr_strdup (rr->stream, toKeep->databaseName);
407                 keep->schema = 0;
408                 keep->elementSetName = 0;
409                 keep->actionQualifier = 0;
410
411                 targetPart->updateStatus = odr_intdup (rr->stream, 1);
412                 targetPart->num_globalDiagnostics = 0;
413                 targetPart->globalDiagnostics = (Z_DiagRec **) odr_nullval();
414                 targetPart->num_taskPackageRecords = 1;
415                 targetPart->taskPackageRecords = 
416                     (Z_IUTaskPackageRecordStructure **)
417                     odr_malloc (rr->stream,
418                                 sizeof(Z_IUTaskPackageRecordStructure *));
419                 targetPart->taskPackageRecords[0] =
420                     (Z_IUTaskPackageRecordStructure *)
421                     odr_malloc (rr->stream,
422                                 sizeof(Z_IUTaskPackageRecordStructure));
423                 
424                 targetPart->taskPackageRecords[0]->which =
425                     Z_IUTaskPackageRecordStructure_record;
426                 targetPart->taskPackageRecords[0]->u.record = 
427                     z_ext_record_sutrs(rr->stream, "test", 4);
428                 targetPart->taskPackageRecords[0]->correlationInfo = 0; 
429                 targetPart->taskPackageRecords[0]->recordStatus =
430                     odr_intdup (rr->stream,
431                                 Z_IUTaskPackageRecordStructure_success);  
432                 targetPart->taskPackageRecords[0]->num_supplementalDiagnostics
433                     = 0;
434
435                 targetPart->taskPackageRecords[0]->supplementalDiagnostics = 0;
436             }
437             if (notToKeep)
438             {
439                 int i;
440                 for (i = 0; i < notToKeep->num; i++)
441                 {
442                     Z_External *rec = notToKeep->elements[i]->record;
443
444                     if (rec->direct_reference)
445                     {
446                         char oid_name_str[OID_STR_MAX];
447                         const char *oid_name 
448                             = oid_name = yaz_oid_to_string_buf(
449                                 rec->direct_reference, 0,
450                                 oid_name_str);
451                         if (oid_name)
452                             yaz_log (log_level, "record %d type %s", i,
453                                      oid_name);
454                     }
455                     switch (rec->which)
456                     {
457                     case Z_External_sutrs:
458                         if (rec->u.octet_aligned->len > 170)
459                             yaz_log (log_level, "%d bytes:\n%.168s ...",
460                                      rec->u.sutrs->len,
461                                      rec->u.sutrs->buf);
462                         else
463                             yaz_log (log_level, "%d bytes:\n%s",
464                                      rec->u.sutrs->len,
465                                      rec->u.sutrs->buf);
466                         break;
467                     case Z_External_octet        :
468                         if (rec->u.octet_aligned->len > 170)
469                             yaz_log (log_level, "%d bytes:\n%.168s ...",
470                                      rec->u.octet_aligned->len,
471                                      rec->u.octet_aligned->buf);
472                         else
473                             yaz_log (log_level, "%d bytes\n%s",
474                                      rec->u.octet_aligned->len,
475                                      rec->u.octet_aligned->buf);
476                     }
477                 }
478             }
479         }
480     }
481     return 0;
482 }
483
484 /* result set delete */
485 int ztest_delete (void *handle, bend_delete_rr *rr)
486 {
487     if (rr->num_setnames == 1 && !strcmp (rr->setnames[0], "1"))
488         rr->delete_status = Z_DeleteStatus_success;
489     else
490         rr->delete_status = Z_DeleteStatus_resultSetDidNotExist;
491     return 0;
492 }
493
494 /* Our sort handler really doesn't sort... */
495 int ztest_sort (void *handle, bend_sort_rr *rr)
496 {
497     rr->errcode = 0;
498     rr->sort_status = Z_SortResponse_success;
499     return 0;
500 }
501
502
503 /* present request handler */
504 int ztest_present (void *handle, bend_present_rr *rr)
505 {
506     return 0;
507 }
508
509 /* retrieval of a single record (present, and piggy back search) */
510 int ztest_fetch(void *handle, bend_fetch_rr *r)
511 {
512     char *cp;
513     const Odr_oid *oid = r->request_format;
514
515     r->last_in_set = 0;
516     r->basename = "Default";
517     r->output_format = r->request_format;
518
519     if (!oid || yaz_oid_is_iso2709(oid))
520     {
521         cp = dummy_marc_record(r->number, r->stream);
522         if (!cp)
523         {
524             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
525         }
526         else
527         {
528             r->len = strlen(cp);
529             r->record = cp;
530             r->output_format = odr_oiddup(r->stream, yaz_oid_recsyn_usmarc);
531         }
532     }
533     else if (!oid_oidcmp(oid, yaz_oid_recsyn_opac))
534     {
535         Z_OPACRecord *rec;
536         int i;
537         cp = dummy_marc_record(r->number, r->stream);
538         if (!cp)
539         {
540             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
541             return 0;
542         }
543         rec = odr_malloc(r->stream, sizeof(*rec));
544         rec->bibliographicRecord =
545             z_ext_record_usmarc(r->stream, cp, strlen(cp));
546         rec->num_holdingsData = 1;
547         rec->holdingsData = odr_malloc(r->stream, sizeof(*rec->holdingsData));
548         for (i = 0; i < rec->num_holdingsData; i++)
549         {
550             Z_HoldingsRecord *hr = odr_malloc(r->stream, sizeof(*hr));
551             Z_HoldingsAndCircData *hc = odr_malloc(r->stream, sizeof(*hc));
552
553             rec->holdingsData[i] = hr;
554             hr->which = Z_HoldingsRecord_holdingsAndCirc;
555             hr->u.holdingsAndCirc = hc;
556             
557             hc->typeOfRecord = odr_strdup(r->stream, "x");
558             hc->typeOfRecord[0] = cp[5]; /* LDR 6 */
559
560             hc->encodingLevel = odr_strdup(r->stream, "x");
561             hc->encodingLevel[0] = cp[16]; /* LDR 17 */
562
563             hc->format = 0; /* OPT */
564             hc->receiptAcqStatus = 0; /* OPT */
565             hc->generalRetention = 0; /* OPT */
566             hc->completeness = 0; /* OPT */
567             hc->dateOfReport = 0; /* OPT */
568             hc->nucCode = 0; /* OPT */
569             hc->localLocation = 0; /* OPT */
570             hc->shelvingLocation = 0; /* OPT */
571             hc->callNumber = 0; /* OPT */
572             hc->shelvingData = 0; /* OPT */
573             hc->copyNumber = 0; /* OPT */
574             hc->publicNote = 0; /* OPT */
575             hc->reproductionNote = 0; /* OPT */
576             hc->termsUseRepro = 0; /* OPT */
577             hc->enumAndChron = 0; /* OPT */
578
579             hc->num_volumes = 0;
580             hc->volumes = 0;
581
582             hc->num_circulationData = 0;
583             hc->circulationData = 0;
584         }
585
586         r->len = -1;
587         r->record = (char*) rec;
588     }
589     else if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
590     {
591         /* this section returns a small record */
592         char buf[100];
593         
594         sprintf(buf, "This is dummy SUTRS record number %d\n", r->number);
595
596         r->len = strlen(buf);
597         r->record = (char *) odr_malloc (r->stream, r->len+1);
598         strcpy(r->record, buf);
599     }
600     else if (!oid_oidcmp(oid, yaz_oid_recsyn_grs_1))
601     {
602         r->len = -1;
603         r->record = (char*) dummy_grs_record(r->number, r->stream);
604         if (!r->record)
605         {
606             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
607             return 0;
608         }
609     }
610     else if (!oid_oidcmp(oid, yaz_oid_recsyn_postscript))
611     {
612         char fname[20];
613         FILE *f;
614         long size;
615
616         sprintf (fname, "part.%d.ps", r->number);
617         f = fopen(fname, "rb");
618         if (!f)
619         {
620             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
621             return 0;
622         }
623         fseek (f, 0L, SEEK_END);
624         size = ftell (f);
625         if (size <= 0 || size >= 5000000)
626         {
627             r->errcode = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
628             return 0;
629         }
630         fseek (f, 0L, SEEK_SET);
631         r->record = (char*) odr_malloc (r->stream, size);
632         r->len = size;
633         fread (r->record, size, 1, f);
634         fclose (f);
635     }
636     else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
637     {
638         if ((cp = dummy_xml_record (r->number, r->stream)))
639         {
640             r->len = strlen(cp);
641             r->record = cp;
642         }
643         else 
644         {
645             r->errcode = YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE;
646             r->surrogate_flag = 1;
647             return 0;
648         }
649     }
650     else
651     {
652         char buf[OID_STR_MAX];
653         r->errcode = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
654         r->errstring = odr_strdup(r->stream, oid_oid_to_dotstring(oid, buf));
655         return 0;
656     }
657     r->errcode = 0;
658     return 0;
659 }
660
661 /*
662  * silly dummy-scan what reads words from a file.
663  */
664 int ztest_scan(void *handle, bend_scan_rr *q)
665 {
666     static FILE *f = 0;
667     static struct scan_entry list[200];
668     static char entries[200][80];
669     int hits[200];
670     char term[80], *p;
671     int i, pos;
672     int term_position_req = q->term_position;
673     int num_entries_req = q->num_entries;
674
675     /* Throw Database unavailable if other than Default or Slow */
676     if (!yaz_matchstr (q->basenames[0], "Default"))
677         ;  /* Default is OK in our test */
678     else if(!yaz_matchstr (q->basenames[0], "Slow"))
679     {
680 #if HAVE_UNISTD_H
681         sleep(3);
682 #endif
683         ;
684     }
685     else
686     {
687         q->errcode = YAZ_BIB1_DATABASE_UNAVAILABLE;
688         q->errstring = q->basenames[0];
689         return 0;
690     }
691
692     q->errcode = 0;
693     q->errstring = 0;
694     q->entries = list;
695     q->status = BEND_SCAN_SUCCESS;
696     if (!f && !(f = fopen("dummy-words", "r")))
697     {
698         perror("dummy-words");
699         exit(1);
700     }
701     if (q->num_entries > 200)
702     {
703         q->errcode = YAZ_BIB1_RESOURCES_EXHAUSTED_NO_RESULTS_AVAILABLE;
704         return 0;
705     }
706     if (q->term)
707     {
708         int len;
709         if (q->term->term->which != Z_Term_general)
710         {
711             q->errcode = YAZ_BIB1_TERM_TYPE_UNSUPP;
712             return 0;
713         }
714         if (*q->step_size != 0)
715         {
716             q->errcode = YAZ_BIB1_ONLY_ZERO_STEP_SIZE_SUPPORTED_FOR_SCAN;
717             return 0;
718         }
719         len = q->term->term->u.general->len;
720         if (len >= sizeof(term))
721             len = sizeof(term)-1;
722         memcpy(term, q->term->term->u.general->buf, len);
723         term[len] = '\0';
724     }
725     else if (q->scanClause)
726     {
727         strncpy(term, q->scanClause, sizeof(term)-1);
728         term[sizeof(term)-1] = '\0';
729     }
730     else
731         strcpy(term, "0");
732
733     for (p = term; *p; p++)
734         if (islower(*(unsigned char *) p))
735             *p = toupper(*p);
736
737     fseek(f, 0, SEEK_SET);
738     q->num_entries = 0;
739
740     for (i = 0, pos = 0; fscanf(f, " %79[^:]:%d", entries[pos], &hits[pos]) == 2;
741         i++, pos < 199 ? pos++ : (pos = 0))
742     {
743         if (!q->num_entries && strcmp(entries[pos], term) >= 0) /* s-point fnd */
744         {
745             if ((q->term_position = term_position_req) > i + 1)
746             {
747                 q->term_position = i + 1;
748                 q->status = BEND_SCAN_PARTIAL;
749             }
750             for (; q->num_entries < q->term_position; q->num_entries++)
751             {
752                 int po;
753
754                 po = pos - q->term_position + q->num_entries+1; /* find pos */
755                 if (po < 0)
756                     po += 200;
757
758                 if (!strcmp (term, "SD") && q->num_entries == 2)
759                 {
760                     list[q->num_entries].term = entries[pos];
761                     list[q->num_entries].occurrences = -1;
762                     list[q->num_entries].errcode =
763                         YAZ_BIB1_SCAN_UNSUPP_VALUE_OF_POSITION_IN_RESPONSE;
764                     list[q->num_entries].errstring = "SD for Scan Term";
765                 }
766                 else
767                 {
768                     list[q->num_entries].term = entries[po];
769                     list[q->num_entries].occurrences = hits[po];
770                 }
771             }
772         }
773         else if (q->num_entries)
774         {
775             list[q->num_entries].term = entries[pos];
776             list[q->num_entries].occurrences = hits[pos];
777             q->num_entries++;
778         }
779         if (q->num_entries >= num_entries_req)
780             break;
781     }
782     if (feof(f))
783         q->status = BEND_SCAN_PARTIAL;
784     return 0;
785 }
786
787 int ztest_explain(void *handle, bend_explain_rr *rr)
788 {
789     if (rr->database && !strcmp(rr->database, "Default"))
790     {
791         rr->explain_buf = "<explain>\n"
792             "\t<serverInfo>\n"
793             "\t\t<host>localhost</host>\n"
794             "\t\t<port>210</port>\n"
795             "\t</serverInfo>\n"
796             "</explain>\n";
797     }
798     return 0;
799 }
800
801 int ztest_update(void *handle, bend_update_rr *rr)
802 {
803     rr->operation_status = "success";
804     return 0;
805 }
806
807 bend_initresult *bend_init(bend_initrequest *q)
808 {
809     bend_initresult *r = (bend_initresult *)
810         odr_malloc (q->stream, sizeof(*r));
811     int *counter = (int *) xmalloc (sizeof(int));
812
813     if (!log_level_set)
814     {
815         log_level=yaz_log_module_level("ztest");
816         log_level_set=1;
817     }
818
819     *counter = 0;
820     r->errcode = 0;
821     r->errstring = 0;
822     r->handle = counter;         /* user handle, in this case a simple int */
823     q->bend_sort = ztest_sort;              /* register sort handler */
824     q->bend_search = ztest_search;          /* register search handler */
825     q->bend_present = ztest_present;        /* register present handle */
826     q->bend_esrequest = ztest_esrequest;
827     q->bend_delete = ztest_delete;
828     q->bend_fetch = ztest_fetch;
829     q->bend_scan = ztest_scan;
830 #if 0
831     q->bend_explain = ztest_explain;
832 #endif
833     q->bend_srw_scan = ztest_scan;
834     q->bend_srw_update = ztest_update;
835
836     q->query_charset = "ISO-8859-1";
837     q->records_in_same_charset = 0;
838
839     return r;
840 }
841
842 void bend_close(void *handle)
843 {
844     xfree (handle);              /* release our user-defined handle */
845     return;
846 }
847
848 int main(int argc, char **argv)
849 {
850     return statserv_main(argc, argv, bend_init, bend_close);
851 }
852 /*
853  * Local variables:
854  * c-basic-offset: 4
855  * indent-tabs-mode: nil
856  * End:
857  * vim: shiftwidth=4 tabstop=8 expandtab
858  */
859