aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/federation/vespa/ResultBuilder.java
blob: a6aec30b4966de64202c206c96c1032403d8a0e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.federation.vespa;

import com.yahoo.log.LogLevel;
import com.yahoo.prelude.hitfield.XMLString;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.text.XML;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import static com.yahoo.text.Lowercase.toLowerCase;

/**
 * Parse Vespa XML results and create Result instances.
 *
 * @author Steinar Knutsen
 * @deprecated
 */
// TODO: Remove on Vespa 7
@Deprecated // OK
@SuppressWarnings("deprecation")
public class ResultBuilder extends DefaultHandler {
    private static final String ERROR = "error";

    private static final String FIELD = "field";

    private static Logger log = Logger.getLogger(ResultBuilder.class.getName());

    /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
    protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";

    /**
     * Namespace prefixes feature id
     * (http://xml.org/sax/features/namespace-prefixes).
     */
    protected static final String NAMESPACE_PREFIXES_FEATURE_ID = "http://xml.org/sax/features/namespace-prefixes";

    /** Validation feature id (http://xml.org/sax/features/validation). */
    protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";

    /**
     * Schema validation feature id
     * (http://apache.org/xml/features/validation/schema).
     */
    protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";

    /**
     * Dynamic validation feature id
     * (http://apache.org/xml/features/validation/dynamic).
     */
    protected static final String DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic";

    // default settings

    /** Default parser name. */
    protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";

    /** Default namespaces support (false). */
    protected static final boolean DEFAULT_NAMESPACES = false;

    /** Default namespace prefixes (false). */
    protected static final boolean DEFAULT_NAMESPACE_PREFIXES = false;

    /** Default validation support (false). */
    protected static final boolean DEFAULT_VALIDATION = false;

    /** Default Schema validation support (false). */
    protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;

    /** Default dynamic validation support (false). */
    protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false;

    private StringBuilder fieldContent;

    private String fieldName;

    private int fieldLevel = 0;

    private boolean hasLiteralTags = false;

    private Map<String, Object> hitFields = new HashMap<>();
    private String hitType;
    private String hitRelevance;
    private String hitSource;

    private int offset = 0;

    private List<Tag> tagStack = new ArrayList<>();

    private final XMLReader parser;

    private Query query;

    private Result result;

    private static enum ResultPart {
        ROOT, ERRORDETAILS, HIT, HITGROUP;
    }

    Deque<ResultPart> location = new ArrayDeque<>(10);

    private String currentErrorCode;

    private String currentError;

    private Deque<HitGroup> hitGroups = new ArrayDeque<>(5);

    private static class Tag {
        public final String name;

        /**
         * Offset is a number which is generated for all data and tags inside
         * fields, used to determine whether a tag was closed without enclosing
         * any characters or other tags.
         */
        public final int offset;

        public Tag(final String name, final int offset) {
            this.name = name;
            this.offset = offset;
        }

        @Override
        public String toString() {
            return name + '(' + Integer.valueOf(offset) + ')';
        }
    }

    /** Default constructor. */
    public ResultBuilder() throws RuntimeException {
        this(createParser());
    }

    public ResultBuilder(XMLReader parser) {
        this.parser = parser;
        this.parser.setContentHandler(this);
        this.parser.setErrorHandler(this);
    }

    public static XMLReader createParser() {
        ClassLoader savedContextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(org.apache.xerces.parsers.SAXParser.class.getClassLoader());

        try {
            XMLReader reader = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            setParserFeatures(reader);
            return reader;
        } catch (Exception e) {
            throw new RuntimeException("error: Unable to instantiate parser ("
                    + DEFAULT_PARSER_NAME + ")", e);
        } finally {
            Thread.currentThread().setContextClassLoader(savedContextClassLoader);
        }
    }

    private static void setParserFeatures(XMLReader reader) {
        try {
            reader.setFeature(NAMESPACES_FEATURE_ID, DEFAULT_NAMESPACES);
        } catch (SAXException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not support feature ("
                    + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            reader.setFeature(NAMESPACE_PREFIXES_FEATURE_ID,
                    DEFAULT_NAMESPACE_PREFIXES);
        } catch (SAXException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not support feature ("
                    + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            reader.setFeature(VALIDATION_FEATURE_ID, DEFAULT_VALIDATION);
        } catch (SAXException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not support feature ("
                    + VALIDATION_FEATURE_ID + ")");
        }
        try {
            reader.setFeature(SCHEMA_VALIDATION_FEATURE_ID,
                    DEFAULT_SCHEMA_VALIDATION);
        } catch (SAXNotRecognizedException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not recognize feature ("
                    + SCHEMA_VALIDATION_FEATURE_ID + ")");

        } catch (SAXNotSupportedException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not support feature ("
                    + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }

        try {
            reader.setFeature(DYNAMIC_VALIDATION_FEATURE_ID,
                    DEFAULT_DYNAMIC_VALIDATION);
        } catch (SAXNotRecognizedException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not recognize feature ("
                    + DYNAMIC_VALIDATION_FEATURE_ID + ")");

        } catch (SAXNotSupportedException e) {
            log.log(LogLevel.WARNING, "warning: Parser does not support feature ("
                    + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
    }

    @Override
    public void startDocument() throws SAXException {
        reset();
        result = new Result(query);
        hitGroups.addFirst(result.hits());
        location.addFirst(ResultPart.ROOT);
        return;
    }

    private void reset() {
        result = null;
        fieldLevel = 0;
        hasLiteralTags = false;
        tagStack = null;
        fieldContent = null;
        offset = 0;
        currentError = null;
        currentErrorCode = null;
        hitGroups.clear();
        location.clear();
    }

    @Override
    public void startElement(String uri, String local, String raw,
            Attributes attrs) throws SAXException {
        // "Everybody" wants this switch to be moved into the
        // enum class instead, but in this case, I find the classic
        // approach more readable.
        switch (location.peekFirst()) {
        case HIT:
            if (fieldLevel > 0) {
                tagInField(raw, attrs, FIELD);
                ++offset;
                return;
            }
            if (FIELD.equals(raw)) {
                ++fieldLevel;
                fieldName = attrs.getValue("name");
                fieldContent = new StringBuilder();
                hasLiteralTags = false;
            }
            break;
        case ERRORDETAILS:
            if (fieldLevel > 0) {
                tagInField(raw, attrs, ERROR);
                ++offset;
                return;
            }
            if (ERROR.equals(raw)) {
                if (attrs != null) {
                    currentErrorCode = attrs.getValue("code");
                    currentError = attrs.getValue("error");
                }
                ++fieldLevel;
                fieldContent = new StringBuilder();
                hasLiteralTags = false;
            }
            break;
        case HITGROUP:
            if ("hit".equals(raw)) {
                startHit(attrs);
            } else if ("group".equals(raw)) {
                startHitGroup(attrs);
            }
            break;
        case ROOT:
            if ("hit".equals(raw)) {
                startHit(attrs);
            } else if ("errordetails".equals(raw)) {
                location.addFirst(ResultPart.ERRORDETAILS);
            } else if ("result".equals(raw)) {
                if (attrs != null) {
                    String total = attrs.getValue("total-hit-count");
                    if (total != null) {
                        result.setTotalHitCount(Long.valueOf(total));
                    }
                }
            } else if ("group".equals(raw)) {
                startHitGroup(attrs);
            } else if (ERROR.equals(raw)) {
                if (attrs != null) {
                    currentErrorCode = attrs.getValue("code");
                    fieldContent = new StringBuilder();
                }
            }
            break;
        }
        ++offset;
    }

    private void startHitGroup(Attributes attrs) {
        HitGroup g = new HitGroup();
        Set<String> types = g.types();

        final String source;
        if (attrs != null) {
            String groupType = attrs.getValue("type");
            if (groupType != null) {
                for (String s : groupType.split(" ")) {
                    if (s.length() > 0) {
                        types.add(s);
                    }
                }
            }

            source = attrs.getValue("source");
        } else {
            source = null;
        }

        g.setId((source != null) ? source : "dummy");

        hitGroups.peekFirst().add(g);
        hitGroups.addFirst(g);
        location.addFirst(ResultPart.HITGROUP);
    }

    private void startHit(Attributes attrs) {
        hitFields.clear();
        location.addFirst(ResultPart.HIT);
        if (attrs != null) {
            hitRelevance = attrs.getValue("relevancy");
            hitSource = attrs.getValue("source");
            hitType = attrs.getValue("type");
        } else {
            hitRelevance = null;
            hitSource = null;
            hitType = null;
        }
    }

    private void tagInField(String tag, Attributes attrs, String enclosingTag) {
        if (!hasLiteralTags) {
            hasLiteralTags = true;
            String fieldTillNow = XML.xmlEscape(fieldContent.toString(), false);
            fieldContent = new StringBuilder(fieldTillNow);
            tagStack = new ArrayList<>();
        }
        if (enclosingTag.equals(tag)) {
            ++fieldLevel;
        }
        if (tagStack.size() > 0) {
            Tag prevTag = tagStack.get(tagStack.size() - 1);
            if (prevTag != null && (prevTag.offset + 1) == offset) {
                fieldContent.append(">");
            }
        }
        fieldContent.append("<").append(tag);
        if (attrs != null) {
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                fieldContent.append(" ").append(attrs.getQName(i))
                        .append("=\"").append(
                                XML.xmlEscape(attrs.getValue(i), true)).append(
                                "\"");
            }
        }
        tagStack.add(new Tag(tag, offset));
    }

    private void endElementInField(String qName, String enclosingTag) {
        Tag prevTag = tagStack.get(tagStack.size() - 1);
        if (qName.equals(prevTag.name) && offset == (prevTag.offset + 1)) {
            fieldContent.append(" />");
        } else {
            fieldContent.append("</").append(qName).append('>');
        }
        if (prevTag.name.equals(qName)) {
            tagStack.remove(tagStack.size() - 1);
        }
    }

    private void endElementInHitField(String qName) {
        if (FIELD.equals(qName) && --fieldLevel == 0) {
            Object content;
            if (hasLiteralTags) {
                content = new XMLString(fieldContent.toString());
            } else {
                content = fieldContent.toString();
            }
            hitFields.put(fieldName, content);
            if ("collapseId".equals(fieldName)) {
                hitFields.put(fieldName, Integer.valueOf(content.toString()));
            }
            fieldName = null;
            fieldContent = null;
            tagStack = null;
        } else {
            Tag prevTag = tagStack.get(tagStack.size() - 1);
            if (qName.equals(prevTag.name) && offset == (prevTag.offset + 1)) {
                fieldContent.append(" />");
            } else {
                fieldContent.append("</").append(qName).append('>');
            }
            if (prevTag.name.equals(qName)) {
                tagStack.remove(tagStack.size() - 1);
            }
        }
    }
    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {

        switch (location.peekFirst()) {
        case ERRORDETAILS:
        case HIT:
            if (fieldLevel > 0) {
                if (hasLiteralTags) {
                    if (tagStack.size() > 0) {
                        Tag tag = tagStack.get(tagStack.size() - 1);
                        if (tag != null && (tag.offset + 1) == offset) {
                            fieldContent.append(">");
                        }
                    }
                    fieldContent.append(
                            XML.xmlEscape(new String(ch, start, length), false));
                } else {
                    fieldContent.append(ch, start, length);
                }
            }
            break;
        default:
            if (fieldContent != null) {
                fieldContent.append(ch, start, length);
            }
            break;
        }
        ++offset;
    }

    @Override
    public void ignorableWhitespace(char ch[], int start, int length)
            throws SAXException {
        return;
    }

    @Override
    public void processingInstruction(String target, String data)
            throws SAXException {
        return;
    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName)
            throws SAXException {
        switch (location.peekFirst()) {
        case HITGROUP:
            if ("group".equals(qName)) {
                hitGroups.removeFirst();
                location.removeFirst();
            }
            break;
        case HIT:
            if (fieldLevel > 0) {
                endElementInHitField(qName);
            }  else if ("hit".equals(qName)) {
                 //assert(hitKeys.size() == hitValues.size());
                 //We try to get either uri or documentID and use that as id
                 Object docId = extractDocumentID();
                 Hit newHit = new Hit(docId.toString());
                 if (hitRelevance != null) newHit.setRelevance(new Relevance(Double.parseDouble(hitRelevance)));
                 if(hitSource != null) newHit.setSource(hitSource);
                 if(hitType != null) {
                     for(String type: hitType.split(" ")) {
                         newHit.types().add(type);
                     }
                 }
                 for(Map.Entry<String, Object> field : hitFields.entrySet()) {
                     newHit.setField(field.getKey(), field.getValue());
                 }

                 hitGroups.peekFirst().add(newHit);
                 location.removeFirst();
            }
            break;
        case ERRORDETAILS:
            if (fieldLevel == 1 && ERROR.equals(qName)) {
                ErrorMessage error = new ErrorMessage(Integer.valueOf(currentErrorCode),
                        currentError,
                        fieldContent.toString());
                hitGroups.peekFirst().addError(error);
                currentError = null;
                currentErrorCode = null;
                fieldContent = null;
                tagStack = null;
                fieldLevel = 0;
            } else if (fieldLevel > 0) {
                endElementInField(qName, ERROR);
            } else if ("errordetails".equals(qName)) {
                location.removeFirst();
            }
            break;
        case ROOT:
            if (ERROR.equals(qName)) {
                ErrorMessage error = new ErrorMessage(Integer.valueOf(currentErrorCode),
                        fieldContent.toString());
                hitGroups.peekFirst().addError(error);
                currentErrorCode = null;
                fieldContent = null;
            }
            break;
        default:
            break;
        }
        ++offset;
    }

    private Object extractDocumentID() {
        Object docId = null;
        if (hitFields.containsKey("uri")) {
            docId = hitFields.get("uri");
        } else {
            final String documentId = "documentId";
            if (hitFields.containsKey(documentId)) {
                docId = hitFields.get(documentId);
            } else {
                final String lcDocumentId = toLowerCase(documentId);
                for (Map.Entry<String, Object> e : hitFields.entrySet()) {
                    String key = e.getKey();
                    // case insensitive matching, checking length first hoping to avoid some lowercasing
                    if (documentId.length() == key.length() && lcDocumentId.equals(toLowerCase(key))) {
                        docId = e.getValue();
                        break;
                    }
                }
            }
        }
        if (docId == null) {
            docId = "dummy";
            log.info("Results from vespa backend did not contain either uri or documentId");
        }
        return docId;
    }

    @Override
    public void warning(SAXParseException ex) throws SAXException {
        printError("Warning", ex);
    }

    @Override
    public void error(SAXParseException ex) throws SAXException {
        printError("Error", ex);
    }

    @Override
    public void fatalError(SAXParseException ex) throws SAXException {
        printError("Fatal Error", ex);
        // throw ex;
    }

    /** Prints the error message. */
    protected void printError(String type, SAXParseException ex) {
        StringBuilder errorMessage = new StringBuilder();

        errorMessage.append(type);
        if (ex != null) {
            String systemId = ex.getSystemId();
            if (systemId != null) {
                int index = systemId.lastIndexOf('/');
                if (index != -1)
                    systemId = systemId.substring(index + 1);
                errorMessage.append(' ').append(systemId);
            }
        }
        errorMessage.append(':')
            .append(ex.getLineNumber())
            .append(':')
            .append(ex.getColumnNumber())
            .append(": ")
            .append(ex.getMessage());
        log.log(LogLevel.WARNING, errorMessage.toString());

    }

    public Result parse(String identifier, Query query) {
        Result toReturn;

        setQuery(query);
        try {
            parser.parse(identifier);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            log.log(LogLevel.WARNING, "Error parsing result from Vespa",e);
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);
        }
        toReturn = result;
        reset();
        return toReturn;
    }

    public Result parse(InputSource input, Query query) {
        Result toReturn;

        setQuery(query);
        try {
            parser.parse(input);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            log.log(LogLevel.WARNING, "Error parsing result from Vespa",e);
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);
        }
        toReturn = result;
        reset();
        return toReturn;
    }


    private void setQuery(Query query) {
        this.query = query;
    }
}