001/*
002 * Copyright 2012-2018 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 *      http://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.boot.json;
018
019import java.util.List;
020import java.util.Map;
021import java.util.concurrent.Callable;
022import java.util.function.Function;
023
024import org.springframework.util.ReflectionUtils;
025
026/**
027 * Base class for parsers wrapped or implemented in this package.
028 *
029 * @author Anton Telechev
030 * @author Phillip Webb
031 * @since 2.0.1
032 */
033public abstract class AbstractJsonParser implements JsonParser {
034
035        protected final Map<String, Object> parseMap(String json,
036                        Function<String, Map<String, Object>> parser) {
037                return trimParse(json, "{", parser);
038        }
039
040        protected final List<Object> parseList(String json,
041                        Function<String, List<Object>> parser) {
042                return trimParse(json, "[", parser);
043        }
044
045        protected final <T> T trimParse(String json, String prefix,
046                        Function<String, T> parser) {
047                String trimmed = (json != null) ? json.trim() : "";
048                if (trimmed.startsWith(prefix)) {
049                        return parser.apply(trimmed);
050                }
051                throw new JsonParseException();
052        }
053
054        protected final <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
055                try {
056                        return parser.call();
057                }
058                catch (Exception ex) {
059                        if (check.isAssignableFrom(ex.getClass())) {
060                                throw new JsonParseException(ex);
061                        }
062                        ReflectionUtils.rethrowRuntimeException(ex);
063                        throw new IllegalStateException(ex);
064                }
065        }
066
067}