001/*
002 * Copyright 2006-2007 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.file.separator;
018
019import org.springframework.util.StringUtils;
020
021/**
022 * JSON-based record separator. Waits for a valid JSON object before returning a
023 * complete line. A valid object has balanced braces ({}), possibly nested, and
024 * ends with a closing brace. This separator can be used to split a stream into
025 * JSON objects, even if those objects are spread over multiple lines, e.g.
026 * 
027 * <pre>
028 * {"foo": "bar",
029 *  "value": { "spam": 2 }}
030 *  {"foo": "rab",
031 *  "value": { "spam": 3, "foo": "bar" }}
032 * </pre>
033 * 
034 * @author Dave Syer
035 * 
036 */
037public class JsonRecordSeparatorPolicy extends SimpleRecordSeparatorPolicy {
038
039        /**
040         * True if the line can be parsed to a JSON object.
041         * 
042         * @see RecordSeparatorPolicy#isEndOfRecord(String)
043         */
044    @Override
045        public boolean isEndOfRecord(String line) {
046                return StringUtils.countOccurrencesOf(line, "{") == StringUtils.countOccurrencesOf(line, "}")
047                                && line.trim().endsWith("}");
048        }
049
050}