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

import java.io.InputStream;

import com.fasterxml.jackson.core.JsonFactory;
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.FeedReader;
import com.yahoo.vespaxmlparser.VespaXMLFeedReader.Operation;


/**
 * Facade between JsonReader and the FeedReader API.
 *
 * <p>
 * The feed reader will take ownership of the input stream and close it when the
 * last parseable document has been read.
 *
 * @author steinar
 */
public class JsonFeedReader implements FeedReader {
    private final JsonReader reader;
    private InputStream stream;
    private static final JsonFactory jsonFactory = new JsonFactory().disable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES);

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

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

        if (documentOperation == null) {
            stream.close();
            operation.setInvalid();
            return;
        }

        if (documentOperation instanceof DocumentUpdate) {
            operation.setDocumentUpdate((DocumentUpdate) documentOperation);
        } else if (documentOperation instanceof DocumentRemove) {
            operation.setRemove(documentOperation.getId());
        } else if (documentOperation instanceof DocumentPut) {
            operation.setDocument(((DocumentPut) documentOperation).getDocument());
        } else {
            throw new IllegalStateException("Got unknown class from JSON reader: " + documentOperation.getClass().getName());
        }

        operation.setCondition(documentOperation.getCondition());
    }

}