Reformat
[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     sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
64
65     for (node = ptr->children; node; node = node->next)
66     {
67         if (node->type == XML_ELEMENT_NODE)
68         {
69             Z_SRW_record *record = sr->records + i;
70             xmlBufferPtr buf = xmlBufferCreate();
71             xmlNode *tmp = xmlCopyNode(node, 1);
72
73             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
74
75             xmlFreeNode(tmp);
76
77             record->recordSchema = 0;
78             record->recordPacking = Z_SRW_recordPacking_XML;
79             record->recordData_len = buf->use;
80             record->recordData_buf = odr_malloc(o, buf->use + 1);
81             memcpy(record->recordData_buf, buf->content, buf->use);
82             record->recordData_buf[buf->use] = '\0';
83             // TODO Solve the real problem in zoom-sru, that doesnt work with 0-based indexes.
84             // Work-around: Making the recordPosition 1-based.
85             record->recordPosition = odr_intdup(o, start + offset + 1);
86
87             xmlBufferFree(buf);
88
89             offset++;
90             i++;
91         }
92     }
93 }
94
95 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
96                                   Z_SRW_searchRetrieveResponse *sr)
97 {
98     Odr_int start = 0;
99     struct _xmlAttr *attr;
100     for (attr = ptr->properties; attr; attr = attr->next)
101         if (attr->children && attr->children->type == XML_TEXT_NODE)
102         {
103             if (!strcmp((const char *) attr->name, "numFound"))
104             {
105                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
106                         (const char *) attr->children->content));
107             } 
108             else if (!strcmp((const char *) attr->name, "start"))
109             {
110                 start = odr_atoi((const char *) attr->children->content);
111             }
112         }
113     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
114         yaz_solr_decode_result_docs(o, ptr, start, sr);
115     if (sr->numberOfRecords)
116         return 0;
117     return -1;
118 }
119
120 static const char *get_facet_term_count(xmlNodePtr node, int *freq)
121 {
122     const char *term = yaz_element_attribute_value_get(node, "int", "name");
123     xmlNodePtr child;
124     WRBUF wrbuf = wrbuf_alloc();
125     if (!term)
126         return term;
127
128     for (child = node->children; child ; child = child->next)
129     {
130         if (child->type == XML_TEXT_NODE)
131             wrbuf_puts(wrbuf, (const char *) child->content);
132     }
133     *freq = atoi(wrbuf_cstr(wrbuf));
134     wrbuf_destroy(wrbuf);
135     return term;
136 }
137
138 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
139                                           Z_SRW_searchRetrieveResponse *sr)
140
141 {
142     Z_AttributeList *list;
143     Z_FacetField *facet_field;
144     int num_terms = 0;
145     int index = 0;
146     xmlNodePtr node;
147     // USE attribute
148     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
149     char *pos = strstr(name, "_exact");
150     /* HACK */
151     if (pos) {
152         pos[0] = 0;
153     }
154     list = yaz_use_attribute_create(o, name);
155     for (node = ptr->children; node; node = node->next)
156         num_terms++;
157     facet_field = facet_field_create(o, list, num_terms);
158     index = 0;
159     for (node = ptr->children; node; node = node->next)
160     {
161         int count = 0;
162         const char *term = get_facet_term_count(node, &count);
163         facet_field_term_set(o, facet_field,
164                              facet_term_create(o, term_create(o, term), count),
165                              index);
166         index++;
167     }
168     return facet_field;
169 }
170
171 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
172                                         Z_SRW_searchRetrieveResponse *sr)
173 {
174     xmlNodePtr ptr;
175     for (ptr = root->children; ptr; ptr = ptr->next)
176     {
177         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
178         {
179             xmlNodePtr node;
180             Z_FacetList *facet_list;
181             int num_facets = 0;
182             for (node = ptr->children; node; node= node->next)
183             {
184                 num_facets++;
185             }
186             facet_list = facet_list_create(o, num_facets);
187             num_facets = 0;
188             for (node = ptr->children; node; node= node->next)
189             {
190                 facet_list_field_set(o, facet_list,
191                                      yaz_solr_decode_facet_field(o, node, sr),
192                                      num_facets);
193                 num_facets++;
194             }
195             sr->facetList = facet_list;
196             break;
197         }
198     }
199     return 0;
200 }
201
202 #endif
203
204 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
205 {
206 #if YAZ_HAVE_XML2
207     const char *content_buf = hres->content_buf;
208     int content_len = hres->content_len;
209     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
210     int ret = 0;
211     xmlNodePtr ptr = 0;
212     Z_SRW_PDU *pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
213     Z_SRW_searchRetrieveResponse *sr = pdu->u.response;
214
215     if (!doc)
216     {
217         ret = -1;
218     }
219     if (doc)
220     {
221         xmlNodePtr root = xmlDocGetRootElement(doc);
222         if (!root)
223         {
224             ret = -1;
225         }
226         else if (strcmp((const char *) root->name, "response"))
227         {
228             ret = -1;
229         }
230         else
231         {
232             /** look for result (required) and facets node (optional) */
233             int rc_result = -1;
234             int rc_facets = 0;
235             for (ptr = root->children; ptr; ptr = ptr->next)
236             {
237                 if (ptr->type == XML_ELEMENT_NODE &&
238                     !strcmp((const char *) ptr->name, "result"))
239                         rc_result = yaz_solr_decode_result(o, ptr, sr);
240                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
241                  * The work-around works because the results is before the facets in the xml. */
242                 if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
243                     match_xml_node_attribute(ptr, "lst", "name",
244                                              "facet_counts"))
245                     rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
246             }
247             ret = rc_result + rc_facets;
248         }
249     }
250     if (doc)
251         xmlFreeDoc(doc);
252     if (ret == 0)
253         *pdup = pdu;
254     return ret;
255 #else
256     return -1;
257 #endif
258 }
259
260 static void yaz_solr_encode_facet_field(
261     ODR encode, char **name, char **value, int *i,
262     Z_FacetField *facet_field)
263 {
264     Z_AttributeList *attribute_list = facet_field->attributes;
265     struct yaz_facet_attr attr_values;
266     yaz_facet_attr_init(&attr_values);
267     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
268     // TODO do we want to support server decided
269     if (!attr_values.errcode && attr_values.useattr)
270     {
271         WRBUF wrbuf = wrbuf_alloc();
272         wrbuf_puts(wrbuf, (char *) attr_values.useattr);
273         /* Skip date field */
274         if (strcmp("date", attr_values.useattr) != 0)
275             wrbuf_puts(wrbuf, "_exact");
276         yaz_add_name_value_str(encode, name, value, i,
277                                "facet.field",
278                                odr_strdup(encode, wrbuf_cstr(wrbuf)));
279         if (attr_values.limit > 0)
280         {
281             WRBUF wrbuf2 = wrbuf_alloc();
282             Odr_int olimit;
283             wrbuf_puts(wrbuf2, "f.");
284             wrbuf_puts(wrbuf2, wrbuf_cstr(wrbuf));
285             wrbuf_puts(wrbuf2, ".facet.limit");
286             olimit = attr_values.limit;
287             yaz_add_name_value_int(encode, name, value, i,
288                                    odr_strdup(encode, wrbuf_cstr(wrbuf2)),
289                                    &olimit);
290             wrbuf_destroy(wrbuf2);
291         }
292         wrbuf_destroy(wrbuf);
293     }
294 }
295
296 static void yaz_solr_encode_facet_list(
297     ODR encode, char **name, char **value,
298     int *i, Z_FacetList *facet_list)
299 {
300     int index;
301     for (index = 0; index < facet_list->num; index++)
302     {
303         yaz_solr_encode_facet_field(encode, name, value, i,
304                                     facet_list->elements[index]);
305         
306     }
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             yaz_solr_encode_facet_list(encode, name, value, &i, facet_list);
355             /*
356             olimit = limit;
357             yaz_add_name_value_int(encode, name, value, &i, "facet.limit", &olimit);
358              */
359
360         }
361     }
362     else
363         return -1;
364     name[i] = 0;
365     yaz_array_to_uri(&uri_args, encode, name, value);
366     
367     hreq->method = "GET";
368     
369     path = (char *)
370         odr_malloc(encode, strlen(hreq->path) +
371                    strlen(uri_args) + strlen(solr_op) + 4);
372
373     sprintf(path, "%s/%s?%s", hreq->path, solr_op, uri_args);
374     hreq->path = path;
375
376     z_HTTP_header_add_content_type(encode, &hreq->headers,
377                                    "text/xml", charset);
378     return 0;
379 }
380
381
382 /*
383  * Local variables:
384  * c-basic-offset: 4
385  * c-file-style: "Stroustrup"
386  * indent-tabs-mode: nil
387  * End:
388  * vim: shiftwidth=4 tabstop=8 expandtab
389  */
390