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.opendaylight.yangtools.yang.data.codec.gson.JSONCodec;
19 * A hack to intercept {@link JSONCodec#writeValue(JsonWriter, Object)} output. This class is closely tailored to
20 * respond implementation behaviour of JSONCodecs.
22 // FIXME: remove this class once we have YANGTOOLS-1569
23 final class HackJsonWriter extends JsonWriter {
24 record Value(String rawString, Kind kind) {
33 requireNonNull(rawString);
38 private static final Value FALSE = new Value("false", Value.Kind.BOOLEAN);
39 private static final Value TRUE = new Value("true", Value.Kind.BOOLEAN);
40 private static final Value NULL = new Value("[null]", Value.Kind.NULL);
42 private Value captured = null;
45 super(new StringWriter());
49 public JsonWriter nullValue() throws IOException {
51 return super.nullValue();
55 public JsonWriter value(final boolean value) throws IOException {
56 capture(value ? TRUE : FALSE);
57 return super.value(value);
61 public JsonWriter value(final Boolean value) throws IOException {
62 // We assume non-null values
63 return value(value.booleanValue());
67 public JsonWriter value(final Number value) throws IOException {
68 capture(new Value(value.toString(), Value.Kind.NUMBER));
69 return super.value(value);
73 public JsonWriter value(final String value) throws IOException {
77 capture(new Value(value, Value.Kind.STRING));
78 return super.value(value);
81 @NonNull Value acquireCaptured() throws IOException {
82 final var local = captured;
84 throw new IOException("No value set");
89 private void capture(final Value newValue) throws IOException {
90 if (captured != null) {
91 throw new IOException("Value already set to " + captured);