aboutsummaryrefslogtreecommitdiffstats
path: root/predicate-search/src/main/java/com/yahoo/search/predicate/utils/VespaFeedParser.java
blob: a20800758ce76c7eeaf27f221520a15684727f6f (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.utils;

import com.yahoo.document.predicate.Predicate;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.function.Consumer;

/**
 * Parses a feed file containing documents in XML format. Its implementation is based on the following assumptions:
 *  1. Each document has single predicate field.
 *  2. The predicate is stored in a field named "boolean".
 *
 *  @author bjorncs
 */
public class VespaFeedParser {

    public static int parseDocuments(String feedFile, int maxDocuments, Consumer<Predicate> consumer) throws IOException {
        int documentCount = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(feedFile), 8 * 1024)) {
            reader.readLine();
            reader.readLine(); // Skip to start of first document
            String line = reader.readLine();
            while (!line.startsWith("</vespafeed>") && documentCount < maxDocuments) {
                while (!line.startsWith("<boolean>")) {
                    line = reader.readLine();
                }
                Predicate predicate = Predicate.fromString(extractBooleanExpression(line));
                consumer.accept(predicate);
                ++documentCount;
                while (!line.startsWith("<document") && !line.startsWith("</vespafeed>")) {
                    line = reader.readLine();
                }
            }
        }
        return documentCount;
    }

    private static String extractBooleanExpression(String line) {
        return line.substring(9, line.length() - 10);
    }

}