SOLR decode: avoid creating empty records array
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2011 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file solr.c
7  * \brief Implements SOAP Webservice decoding/encoding
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <stdlib.h>
14 #include <assert.h>
15 #include <yaz/srw.h>
16 #include <yaz/matchstr.h>
17 #include <yaz/yaz-iconv.h>
18 #include <yaz/log.h>
19 #include <yaz/facet.h>
20 #include <yaz/wrbuf.h>
21
22 #include "sru-p.h"
23
24 #define SOLR_MAX_PARAMETERS  100
25
26 #if YAZ_HAVE_XML2
27 #include <libxml/parser.h>
28 #include <libxml/tree.h>
29
30 static int match_xml_node_attribute(
31     xmlNodePtr ptr,
32     const char *node_name, const char *attribute_name, const char *value)
33 {
34     const char *attribute_value;
35     // check if the node name matches
36     if (strcmp((const char*) ptr->name, node_name))
37         return 0;
38     if (attribute_name)
39     {
40         attribute_value = yaz_element_attribute_value_get(ptr, node_name,
41                                                           attribute_name);
42         if (attribute_value && !strcmp(attribute_value, value))
43             return 1;
44     }
45     else /* No attribute to check */
46         return 1;
47     return 0;
48 }
49
50 static void yaz_solr_decode_result_docs(ODR o, xmlNodePtr ptr,
51                                         Odr_int start,
52                                         Z_SRW_searchRetrieveResponse *sr)
53 {
54     xmlNodePtr node;
55     int offset = 0;
56     int i = 0;
57
58     sr->num_records = 0;
59     for (node = ptr->children; node; node = node->next)
60         if (node->type == XML_ELEMENT_NODE)
61             sr->num_records++;
62     
63     if (sr->num_records)
64         sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
65
66     for (node = ptr->children; node; node = node->next)
67     {
68         if (node->type == XML_ELEMENT_NODE)
69         {
70             Z_SRW_record *record = sr->records + i;
71             xmlBufferPtr buf = xmlBufferCreate();
72             xmlNode *tmp = xmlCopyNode(node, 1);
73
74             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
75
76             xmlFreeNode(tmp);
77
78             record->recordSchema = 0;
79             record->recordPacking = Z_SRW_recordPacking_XML;
80             record->recordData_len = buf->use;
81             record->recordData_buf = odr_malloc(o, buf->use + 1);
82             memcpy(record->recordData_buf, buf->content, buf->use);
83             record->recordData_buf[buf->use] = '\0';
84             // TODO Solve the real problem in zoom-sru, that doesnt work with 0-based indexes.
85             // Work-around: Making the recordPosition 1-based.
86             record->recordPosition = odr_intdup(o, start + offset + 1);
87
88             xmlBufferFree(buf);
89
90             offset++;
91             i++;
92         }
93     }
94 }
95
96 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
97                                   Z_SRW_searchRetrieveResponse *sr)
98 {
99     Odr_int start = 0;
100     struct _xmlAttr *attr;
101     for (attr = ptr->properties; attr; attr = attr->next)
102         if (attr->children && attr->children->type == XML_TEXT_NODE)
103         {
104             if (!strcmp((const char *) attr->name, "numFound"))
105             {
106                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
107                         (const char *) attr->children->content));
108             } 
109             else if (!strcmp((const char *) attr->name, "start"))
110             {
111                 start = odr_atoi((const char *) attr->children->content);
112             }
113         }
114     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
115         yaz_solr_decode_result_docs(o, ptr, start, sr);
116     if (sr->numberOfRecords)
117         return 0;
118     return -1;
119 }
120
121 static const char *get_facet_term_count(xmlNodePtr node, int *freq)
122 {
123     const char *term = yaz_element_attribute_value_get(node, "int", "name");
124     xmlNodePtr child;
125     WRBUF wrbuf = wrbuf_alloc();
126     if (!term)
127         return term;
128
129     for (child = node->children; child ; child = child->next)
130     {
131         if (child->type == XML_TEXT_NODE)
132             wrbuf_puts(wrbuf, (const char *) child->content);
133     }
134     *freq = atoi(wrbuf_cstr(wrbuf));
135     wrbuf_destroy(wrbuf);
136     return term;
137 }
138
139 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
140                                           Z_SRW_searchRetrieveResponse *sr)
141
142 {
143     Z_AttributeList *list;
144     Z_FacetField *facet_field;
145     int num_terms = 0;
146     int index = 0;
147     xmlNodePtr node;
148     // USE attribute
149     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
150     list = yaz_use_attribute_create(o, name);
151     for (node = ptr->children; node; node = node->next)
152         num_terms++;
153     facet_field = facet_field_create(o, list, num_terms);
154     index = 0;
155     for (node = ptr->children; node; node = node->next)
156     {
157         int count = 0;
158         const char *term = get_facet_term_count(node, &count);
159         facet_field_term_set(o, facet_field,
160                              facet_term_create(o, term_create(o, term), count),
161                              index);
162         index++;
163     }
164     return facet_field;
165 }
166
167 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
168                                         Z_SRW_searchRetrieveResponse *sr)
169 {
170     xmlNodePtr ptr;
171     for (ptr = root->children; ptr; ptr = ptr->next)
172     {
173         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
174         {
175             xmlNodePtr node;
176             Z_FacetList *facet_list;
177             int num_facets = 0;
178             for (node = ptr->children; node; node= node->next)
179             {
180                 num_facets++;
181             }
182             facet_list = facet_list_create(o, num_facets);
183             num_facets = 0;
184             for (node = ptr->children; node; node= node->next)
185             {
186                 facet_list_field_set(o, facet_list,
187                                      yaz_solr_decode_facet_field(o, node, sr),
188                                      num_facets);
189                 num_facets++;
190             }
191             sr->facetList = facet_list;
192             break;
193         }
194     }
195     return 0;
196 }
197
198 #endif
199
200 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
201 {
202 #if YAZ_HAVE_XML2
203     const char *content_buf = hres->content_buf;
204     int content_len = hres->content_len;
205     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
206     int ret = 0;
207     xmlNodePtr ptr = 0;
208     Z_SRW_PDU *pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
209     Z_SRW_searchRetrieveResponse *sr = pdu->u.response;
210
211     if (!doc)
212     {
213         ret = -1;
214     }
215     if (doc)
216     {
217         xmlNodePtr root = xmlDocGetRootElement(doc);
218         if (!root)
219         {
220             ret = -1;
221         }
222         else if (strcmp((const char *) root->name, "response"))
223         {
224             ret = -1;
225         }
226         else
227         {
228             /** look for result (required) and facets node (optional) */
229             int rc_result = -1;
230             int rc_facets = 0;
231             for (ptr = root->children; ptr; ptr = ptr->next)
232             {
233                 if (ptr->type == XML_ELEMENT_NODE &&
234                     !strcmp((const char *) ptr->name, "result"))
235                         rc_result = yaz_solr_decode_result(o, ptr, sr);
236                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
237                  * The work-around works because the results is before the facets in the xml. */
238                 if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
239                     match_xml_node_attribute(ptr, "lst", "name",
240                                              "facet_counts"))
241                     rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
242             }
243             ret = rc_result + rc_facets;
244         }
245     }
246     if (doc)
247         xmlFreeDoc(doc);
248     if (ret == 0)
249         *pdup = pdu;
250     return ret;
251 #else
252     return -1;
253 #endif
254 }
255
256 static int yaz_solr_encode_facet_field(
257     ODR encode, char **name, char **value, int *i,
258     Z_FacetField *facet_field)
259 {
260     Z_AttributeList *attribute_list = facet_field->attributes;
261     struct yaz_facet_attr attr_values;
262     yaz_facet_attr_init(&attr_values);
263     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
264     // TODO do we want to support server decided
265
266     if (attr_values.errcode)
267         return -1;
268     if (attr_values.useattr)
269     {
270         WRBUF wrbuf = wrbuf_alloc();
271         wrbuf_puts(wrbuf, (char *) attr_values.useattr);
272         yaz_add_name_value_str(encode, name, value, i,
273                                "facet.field",
274                                odr_strdup(encode, wrbuf_cstr(wrbuf)));
275         if (attr_values.limit > 0)
276         {
277             WRBUF wrbuf2 = wrbuf_alloc();
278             Odr_int olimit;
279             wrbuf_puts(wrbuf2, "f.");
280             wrbuf_puts(wrbuf2, wrbuf_cstr(wrbuf));
281             wrbuf_puts(wrbuf2, ".facet.limit");
282             olimit = attr_values.limit;
283             yaz_add_name_value_int(encode, name, value, i,
284                                    odr_strdup(encode, wrbuf_cstr(wrbuf2)),
285                                    &olimit);
286             wrbuf_destroy(wrbuf2);
287         }
288         wrbuf_destroy(wrbuf);
289     }
290     return 0;
291 }
292
293 static int yaz_solr_encode_facet_list(
294     ODR encode, char **name, char **value,
295     int *i, Z_FacetList *facet_list)
296 {
297     int index;
298     for (index = 0; index < facet_list->num; index++)
299     {
300         int r = yaz_solr_encode_facet_field(encode, name, value, i,
301                                             facet_list->elements[index]);
302         if (r)
303             return -1;
304         
305     }
306     return 0;
307 }
308
309 int yaz_solr_encode_request(Z_HTTP_Request *hreq, Z_SRW_PDU *srw_pdu,
310                             ODR encode, const char *charset)
311 {
312     const char *solr_op = 0;
313     //TODO Change. not a nice hard coded, unchecked limit.
314     char *name[SOLR_MAX_PARAMETERS], *value[SOLR_MAX_PARAMETERS];
315     char *uri_args;
316     char *path;
317     int i = 0;
318     
319     z_HTTP_header_add_basic_auth(encode, &hreq->headers, 
320                                  srw_pdu->username, srw_pdu->password);
321     if (srw_pdu->which == Z_SRW_searchRetrieve_request)
322     {
323         Z_SRW_searchRetrieveRequest *request = srw_pdu->u.request;
324         solr_op = "select";
325         switch (srw_pdu->u.request->query_type)
326         {
327         case Z_SRW_query_type_pqf:
328             yaz_add_name_value_str(encode, name, value, &i,
329                                    "q", request->query.pqf);
330             break;
331         case Z_SRW_query_type_cql:
332             yaz_add_name_value_str(encode, name, value, &i,
333                                    "q", request->query.cql);
334             break;
335         default:
336             return -1;
337         }
338         if (srw_pdu->u.request->startRecord)
339         {
340             Odr_int start = *request->startRecord - 1;
341             yaz_add_name_value_int(encode, name, value, &i,
342                                    "start", &start);
343         }
344         yaz_add_name_value_int(encode, name, value, &i,
345                                "rows", request->maximumRecords);
346         yaz_add_name_value_str(encode, name, value, &i,
347                                "fl", request->recordSchema);
348
349         if (request->facetList)
350         {
351             Z_FacetList *facet_list = request->facetList;
352             yaz_add_name_value_str(encode, name, value, &i, "facet", "true");
353             yaz_add_name_value_str(encode, name, value, &i, "facet.mincount", "1");
354             if (yaz_solr_encode_facet_list(encode, name, value, &i, facet_list))
355                 return -1;
356         }
357     }
358     else
359         return -1;
360     name[i] = 0;
361     yaz_array_to_uri(&uri_args, encode, name, value);
362     
363     hreq->method = "GET";
364     
365     path = (char *)
366         odr_malloc(encode, strlen(hreq->path) +
367                    strlen(uri_args) + strlen(solr_op) + 4);
368
369     sprintf(path, "%s/%s?%s", hreq->path, solr_op, uri_args);
370     hreq->path = path;
371
372     z_HTTP_header_add_content_type(encode, &hreq->headers,
373                                    "text/xml", charset);
374     return 0;
375 }
376
377
378 /*
379  * Local variables:
380  * c-basic-offset: 4
381  * c-file-style: "Stroustrup"
382  * indent-tabs-mode: nil
383  * End:
384  * vim: shiftwidth=4 tabstop=8 expandtab
385  */
386