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