Jackson2Tokenizer.java 4.7 KB
Newer Older
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
/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.http.codec.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.async.ByteArrayFeeder;
import com.fasterxml.jackson.databind.util.TokenBuffer;
import reactor.core.publisher.Flux;

import org.springframework.core.codec.DecodingException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.util.Assert;

/**
R
Polish  
Rossen Stoyanchev 已提交
37 38 39
 * {@link Function} to transform a JSON stream of arbitrary size, byte array
 * chunks into a {@code Flux<TokenBuffer>} where each token buffer is a
 * well-formed JSON object.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 *
 * @author Arjen Poutsma
 * @since 5.0
 */
class Jackson2Tokenizer implements Function<DataBuffer, Flux<TokenBuffer>> {

	private final JsonParser parser;

	private final boolean tokenizeArrayElements;

	private TokenBuffer tokenBuffer;

	private int objectDepth;

	private int arrayDepth;

	// TODO: change to ByteBufferFeeder when supported by Jackson
R
Polish  
Rossen Stoyanchev 已提交
57 58
	private final ByteArrayFeeder inputFeeder;

59 60 61 62 63

	/**
	 * Create a new instance of the {@code Jackson2Tokenizer}.
	 * @param parser the non-blocking parser, obtained via
	 * {@link com.fasterxml.jackson.core.JsonFactory#createNonBlockingByteArrayParser}
R
Polish  
Rossen Stoyanchev 已提交
64 65 66
	 * @param tokenizeArrayElements if {@code true} and the "top level" JSON
	 * object is an array, each element is returned individually, immediately
	 * after it is received.
67 68 69 70 71 72 73 74 75 76
	 */
	public Jackson2Tokenizer(JsonParser parser, boolean tokenizeArrayElements) {
		Assert.notNull(parser, "'parser' must not be null");

		this.parser = parser;
		this.tokenizeArrayElements = tokenizeArrayElements;
		this.tokenBuffer = new TokenBuffer(parser);
		this.inputFeeder = (ByteArrayFeeder) this.parser.getNonBlockingInputFeeder();
	}

R
Polish  
Rossen Stoyanchev 已提交
77

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	@Override
	public Flux<TokenBuffer> apply(DataBuffer dataBuffer) {
		byte[] bytes = new byte[dataBuffer.readableByteCount()];
		dataBuffer.read(bytes);
		DataBufferUtils.release(dataBuffer);

		try {
			this.inputFeeder.feedInput(bytes, 0, bytes.length);
			List<TokenBuffer> result = new ArrayList<>();

			while (true) {
				JsonToken token = this.parser.nextToken();
				if (token == JsonToken.NOT_AVAILABLE) {
					break;
				}
R
Polish  
Rossen Stoyanchev 已提交
93
				updateDepth(token);
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

				if (!this.tokenizeArrayElements) {
					processTokenNormal(token, result);
				}
				else {
					processTokenArray(token, result);
				}
			}
			return Flux.fromIterable(result);
		}
		catch (JsonProcessingException ex) {
			return Flux.error(new DecodingException(
					"JSON decoding error: " + ex.getOriginalMessage(), ex));
		}
		catch (Exception ex) {
			return Flux.error(ex);
		}
	}

R
Polish  
Rossen Stoyanchev 已提交
113
	private void updateDepth(JsonToken token) {
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
		switch (token) {
			case START_OBJECT:
				this.objectDepth++;
				break;
			case END_OBJECT:
				this.objectDepth--;
				break;
			case START_ARRAY:
				this.arrayDepth++;
				break;
			case END_ARRAY:
				this.arrayDepth--;
				break;
		}
	}

	private void processTokenNormal(JsonToken token, List<TokenBuffer> result) throws IOException {
		this.tokenBuffer.copyCurrentEvent(this.parser);

		if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) {
			if (this.objectDepth == 0 && this.arrayDepth == 0) {
				result.add(this.tokenBuffer);
				this.tokenBuffer = new TokenBuffer(this.parser);
			}
		}

	}

	private void processTokenArray(JsonToken token, List<TokenBuffer> result) throws IOException {
143
		if (!isTopLevelArrayToken(token)) {
144 145 146 147 148 149 150 151
			this.tokenBuffer.copyCurrentEvent(this.parser);
		}

		if (token == JsonToken.END_OBJECT && this.objectDepth == 0 &&
				(this.arrayDepth == 1 || this.arrayDepth == 0)) {
			result.add(this.tokenBuffer);
			this.tokenBuffer = new TokenBuffer(this.parser);
		}
R
Polish  
Rossen Stoyanchev 已提交
152
	}
153

154 155 156 157 158
	private boolean isTopLevelArrayToken(JsonToken token) {
		return (token == JsonToken.START_ARRAY && this.arrayDepth == 1) ||
				(token == JsonToken.END_ARRAY && this.arrayDepth == 0);
	}

R
Polish  
Rossen Stoyanchev 已提交
159 160
	public void endOfInput() {
		this.inputFeeder.endOfInput();
161 162 163
	}

}