aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/main/java/com/yahoo/document/json/JsonFeedReader.java
blob: 740fc6125245eab0e6d08228ae49809117481461 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonFactoryBuilder;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.yahoo.document.DocumentOperation;
import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentRemove;
import com.yahoo.document.DocumentTypeManager;
import com.yahoo.document.DocumentUpdate;
import com.yahoo.vespaxmlparser.DocumentFeedOperation;
import com.yahoo.vespaxmlparser.DocumentUpdateFeedOperation;
import com.yahoo.vespaxmlparser.FeedOperation;
import com.yahoo.vespaxmlparser.FeedReader;
import com.yahoo.vespaxmlparser.RemoveFeedOperation;

import java.io.InputStream;

/**
 * Facade between JsonReader and the FeedReader API.
 *
 * The feed reader will take ownership of the input stream and close it when the
 * last parseable document has been read.
 *
 * @author Steinar Knutsen
 */
public class JsonFeedReader implements FeedReader {

    private final JsonReader reader;
    private final InputStream stream;
    private static final JsonFactory jsonFactory = new JsonFactoryBuilder()
            .disable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES)
            .streamReadConstraints(StreamReadConstraints.builder().maxStringLength(Integer.MAX_VALUE).build())
            .build();

    public JsonFeedReader(InputStream stream, DocumentTypeManager docMan) {
        reader = new JsonReader(docMan, stream, jsonFactory);
        this.stream = stream;
    }

    @Override
    public FeedOperation read() throws Exception {
        DocumentOperation documentOperation = reader.next();

        if (documentOperation == null) {
            stream.close();
            return FeedOperation.INVALID;
        }

        if (documentOperation instanceof DocumentUpdate) {
            return new DocumentUpdateFeedOperation((DocumentUpdate) documentOperation);
        } else if (documentOperation instanceof DocumentRemove) {
            return new RemoveFeedOperation((DocumentRemove)documentOperation);
        } else if (documentOperation instanceof DocumentPut) {
            return new DocumentFeedOperation((DocumentPut) documentOperation);
        } else {
            throw new IllegalArgumentException("Got unknown class from JSON reader: " + documentOperation.getClass().getName());
        }
    }

}