|
| 1 | +/* |
| 2 | + * Copyright 2024 dengliming. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.github.dengliming.redismodule.redisjson.codec; |
| 18 | + |
| 19 | +/** |
| 20 | + * Resolves the {@link JsonCodec} used when none is supplied explicitly. |
| 21 | + * <p> |
| 22 | + * Gson is an optional dependency of this module. The default codec is only looked up when a |
| 23 | + * {@code RedisJSON} / {@code RedisJSONClient} is created without a codec, and the Gson-backed class is |
| 24 | + * loaded only if Gson is on the classpath, so applications that bring their own {@link JsonCodec} |
| 25 | + * never need Gson. |
| 26 | + */ |
| 27 | +public final class JsonCodecs { |
| 28 | + |
| 29 | + private static final String GSON_CLASS = "com.google.gson.Gson"; |
| 30 | + |
| 31 | + private JsonCodecs() { |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @return the Gson-backed codec |
| 36 | + * @throws IllegalStateException if Gson is not on the classpath |
| 37 | + */ |
| 38 | + public static JsonCodec defaultCodec() { |
| 39 | + if (!isGsonPresent()) { |
| 40 | + throw new IllegalStateException("No JsonCodec configured and Gson is not on the classpath. " |
| 41 | + + "Add com.google.code.gson:gson or pass a JsonCodec to RedisJSONClient / RedisJSON."); |
| 42 | + } |
| 43 | + return GsonHolder.CODEC; |
| 44 | + } |
| 45 | + |
| 46 | + public static boolean isGsonPresent() { |
| 47 | + try { |
| 48 | + Class.forName(GSON_CLASS, false, JsonCodecs.class.getClassLoader()); |
| 49 | + return true; |
| 50 | + } catch (ClassNotFoundException e) { |
| 51 | + return false; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Holder so that {@link GsonJsonCodec} (and with it Gson) is loaded only on first access. |
| 57 | + */ |
| 58 | + private static final class GsonHolder { |
| 59 | + static final JsonCodec CODEC = GsonJsonCodec.INSTANCE; |
| 60 | + } |
| 61 | +} |
0 commit comments