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