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