2 * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.restconf.server.spi;
10 import static java.util.Objects.requireNonNull;
12 import com.google.gson.stream.JsonWriter;
13 import java.io.IOException;
14 import java.io.StringWriter;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodec;
20 * A hack to intercept {@link JSONCodec#writeValue(JsonWriter, Object)} output. This class is closely tailored to
21 * respond implementation behaviour of JSONCodecs.
23 // FIXME: remove this class once we have YANGTOOLS-1569
24 final class HackJsonWriter extends JsonWriter {
26 record Value(String rawString, Kind kind) {
35 requireNonNull(rawString);
40 private static final Value FALSE = new Value("false", Value.Kind.BOOLEAN);
41 private static final Value TRUE = new Value("true", Value.Kind.BOOLEAN);
42 private static final Value NULL = new Value("[null]", Value.Kind.NULL);
44 private Value captured = null;
47 super(new StringWriter());
51 public JsonWriter nullValue() throws IOException {
53 return super.nullValue();
57 public JsonWriter value(final boolean value) throws IOException {
58 capture(value ? TRUE : FALSE);
59 return super.value(value);
63 public JsonWriter value(final Boolean value) throws IOException {
64 // We assume non-null values
65 return value(value.booleanValue());
69 public JsonWriter value(final Number value) throws IOException {
70 capture(new Value(value.toString(), Value.Kind.NUMBER));
71 return super.value(value);
75 public JsonWriter value(final String value) throws IOException {
79 capture(new Value(value, Value.Kind.STRING));
80 return super.value(value);
83 @NonNull Value acquireCaptured() throws IOException {
84 final var local = captured;
86 throw new IOException("No value set");
91 private void capture(final Value newValue) throws IOException {
92 if (captured != null) {
93 throw new IOException("Value already set to " + captured);