001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.marshall; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.StringUtils.*; 021 022import java.math.*; 023 024/** 025 * Supported wire formats for {@link BigInteger} and {@link BigDecimal} values. 026 * 027 * <p> 028 * Used by {@link MarshallingContext.Builder#bigNumberFormat(BigNumberFormat)}, 029 * {@link Marshalled#bigNumberFormat()}, 030 * {@link MarshalledProp#bigNumberFormat()}, and 031 * {@link MarshalledConfig#bigNumberFormat()} to control how 032 * {@link BigInteger} / {@link BigDecimal} values are written to text-based wire formats. 033 * 034 * <p> 035 * The default is {@link #NUMBER} which preserves the historical wire output (a bare numeric token). 036 * 037 * <h2 class='topic'>JS-interop motivation</h2> 038 * 039 * <p> 040 * JavaScript's {@code Number.MAX_SAFE_INTEGER} is {@code 2^53 − 1} (= {@code 9007199254740991}). 041 * Values outside that range silently lose precision when parsed by a JavaScript client. {@link #STRING} 042 * forces a quoted-string representation that round-trips losslessly. {@link #AUTO} picks {@link #NUMBER} 043 * for values that are JS-safe and {@link #STRING} for everything else — the typical "safe default" for 044 * services that may be consumed by both JVM and browser clients. 045 * 046 * <h2 class='topic'>Precedence (highest to lowest)</h2> 047 * <ol> 048 * <li>{@link MarshalledProp#bigNumberFormat() @MarshalledProp(bigNumberFormat=…)} on the bean property. 049 * <li>{@link Marshalled#bigNumberFormat() @Marshalled(bigNumberFormat=…)} on the bean class. 050 * <li>{@link MarshalledConfig#bigNumberFormat() @MarshalledConfig(bigNumberFormat=…)} on 051 * <code><ja>@Rest</ja></code>-annotated classes / methods. 052 * <li>Programmatic {@link MarshallingContext.Builder#bigNumberFormat(BigNumberFormat)}. 053 * <li>Environment variable <c>MarshallingContext.bigNumberFormat</c>. 054 * <li>The default constant ({@link #NUMBER}). 055 * </ol> 056 * 057 * <h2 class='topic'>Parser leniency</h2> 058 * 059 * <p> 060 * Parsers SHALL accept both bare numeric and quoted-string input regardless of the parser-side 061 * {@code BigNumberFormat} setting. The configured constant is informational only. 062 * 063 * <h2 class='topic'>Binary serializers</h2> 064 * 065 * <p> 066 * Binary serializers (BSON / CBOR / MsgPack / Prototext) emit native numeric types regardless of the 067 * configured {@code BigNumberFormat}; this setting only affects text-based serializers. BSON has 068 * {@code decimal128} for exact decimal values; CBOR / MsgPack handle big-integer values via 069 * tag 2 / tag 3 with string fallback. 070 */ 071public enum BigNumberFormat { 072 073 /** Sentinel meaning "no value configured" — falls through to the next-higher precedence level. */ 074 NOT_SET, 075 076 /** 077 * Bare numeric token (the default). 078 * 079 * <h4 class='figure'>Example:</h4> 080 * <p class='bcode'> 081 * 12345678901234567890 082 * </p> 083 * 084 * <p> 085 * This is the historical wire output and the natural form for server-to-server JVM clients. 086 */ 087 NUMBER, 088 089 /** 090 * Quoted-string form for lossless precision. 091 * 092 * <h4 class='figure'>Example:</h4> 093 * <p class='bcode'> 094 * "12345678901234567890" 095 * </p> 096 * 097 * <p> 098 * Round-trips losslessly through any JSON / YAML / etc. parser, including JavaScript clients which 099 * would otherwise truncate to a 64-bit double. 100 */ 101 STRING, 102 103 /** 104 * Hybrid — emit {@link #NUMBER} when the value is JS-safe (fits in {@code ±(2^53 − 1)}), otherwise 105 * emit {@link #STRING}. 106 * 107 * <p> 108 * For {@link BigDecimal} values, any non-zero scale forces {@link #STRING} (a fractional value cannot 109 * be safely represented in a JS double regardless of magnitude). 110 * 111 * <p> 112 * The "safe default" for services that may be consumed by both JVM and browser clients. 113 */ 114 AUTO; 115 116 /** {@link Number#MAX_SAFE_INTEGER} equivalent — largest integer that round-trips through a JS double. */ 117 private static final long JS_MAX_SAFE_INTEGER = 9007199254740991L; 118 private static final BigInteger BIG_JS_MAX_SAFE = BigInteger.valueOf(JS_MAX_SAFE_INTEGER); 119 private static final BigInteger BIG_JS_MIN_SAFE = BigInteger.valueOf(-JS_MAX_SAFE_INTEGER); 120 121 /** 122 * Formats the specified {@link BigInteger} using this format. 123 * 124 * <p> 125 * Returns either a {@link Number} (when {@link #NUMBER} or {@link #AUTO} produces a JS-safe value) or 126 * a {@link String} (when {@link #STRING} or {@link #AUTO} produces an out-of-range value). Callers 127 * should branch on the runtime type: 128 * <ul> 129 * <li>{@link Number} → emit as a bare numeric wire token. 130 * <li>{@link String} → emit as a quoted string. 131 * </ul> 132 * 133 * @param value The value to format. Can be <jk>null</jk> (returns <jk>null</jk>). 134 * @param format The configured format. Can be <jk>null</jk> (treated as {@link #NUMBER}). 135 * @return The formatted value (a {@link BigInteger} for numeric output, a {@link String} for string output), 136 * or <jk>null</jk> if {@code value} is <jk>null</jk>. 137 */ 138 public static Object format(BigInteger value, BigNumberFormat format) { 139 if (value == null) 140 return null; 141 var fmt = format == null ? NUMBER : format; 142 return switch (fmt) { 143 case NOT_SET, NUMBER -> value; 144 case STRING -> value.toString(); 145 case AUTO -> isJsSafe(value) ? (Object) value : value.toString(); 146 }; 147 } 148 149 /** 150 * Formats the specified {@link BigDecimal} using this format. 151 * 152 * <p> 153 * Returns either a {@link Number} (when {@link #NUMBER} or {@link #AUTO} produces a JS-safe value) or 154 * a {@link String} (when {@link #STRING} or {@link #AUTO} produces an out-of-range value). 155 * 156 * <p> 157 * For {@link #AUTO}: any non-zero-scale {@link BigDecimal} (i.e. has a fractional part) forces 158 * {@link #STRING} since fractional values cannot be safely represented in a JS double regardless of 159 * magnitude. Zero-scale values are tested against the integer {@code ±(2^53 − 1)} bound. 160 * 161 * @param value The value to format. Can be <jk>null</jk> (returns <jk>null</jk>). 162 * @param format The configured format. Can be <jk>null</jk> (treated as {@link #NUMBER}). 163 * @return The formatted value (a {@link BigDecimal} for numeric output, a {@link String} for string output), 164 * or <jk>null</jk> if {@code value} is <jk>null</jk>. 165 */ 166 public static Object format(BigDecimal value, BigNumberFormat format) { 167 if (value == null) 168 return null; 169 var fmt = format == null ? NUMBER : format; 170 return switch (fmt) { 171 case NOT_SET, NUMBER -> value; 172 case STRING -> value.toPlainString(); 173 case AUTO -> { 174 if (value.scale() > 0) 175 yield value.toPlainString(); 176 yield isJsSafe(value.toBigInteger()) ? (Object) value : value.toPlainString(); 177 } 178 }; 179 } 180 181 /** 182 * Parses the specified wire value into a {@link BigInteger} or {@link BigDecimal}. 183 * 184 * <p> 185 * Accepts both bare numeric and quoted-string input regardless of the {@code format} hint. The hint is 186 * informational only. 187 * 188 * @param <T> The target type ({@link BigInteger} or {@link BigDecimal}). 189 * @param value The wire value. Can be <jk>null</jk> or blank (returns <jk>null</jk>). 190 * @param format The configured format (informational only — parsing is format-agnostic). Can be <jk>null</jk> (ignored; parsing is format-agnostic). 191 * @param targetType The desired return type — {@link BigInteger} or {@link BigDecimal}. 192 * @return The parsed value, or <jk>null</jk> if {@code value} is <jk>null</jk> or blank. 193 * @throws IllegalArgumentException If the value cannot be parsed as a number or {@code targetType} is unsupported. 194 */ 195 @SuppressWarnings({ 196 "unchecked" // Cast is safe: parameterized by caller. 197 }) 198 public static <T extends Number> T parse(String value, BigNumberFormat format, Class<T> targetType) { 199 if (value == null) 200 return null; 201 var s = value.trim(); 202 if (s.isEmpty()) 203 return null; 204 // Strip surrounding quotes if present (lenient parsing — quoted-string and bare-numeric both accepted). 205 if (s.length() >= 2 && (s.charAt(0) == '"' || s.charAt(0) == '\'') && s.charAt(s.length() - 1) == s.charAt(0)) 206 s = s.substring(1, s.length() - 1).trim(); 207 try { 208 if (BigInteger.class.equals(targetType)) 209 return (T) new BigInteger(s); 210 if (BigDecimal.class.equals(targetType)) 211 return (T) parseBigDecimal(s); 212 throw iaex("Unsupported BigNumberFormat target type: %s", targetType.getName()); 213 } catch (NumberFormatException e) { 214 throw iaex("Invalid big-number value '%s' for format %s: %s", value, format, e.getMessage()); 215 } 216 } 217 218 /** 219 * Returns <jk>true</jk> if this format always emits a numeric wire value. 220 * 221 * <p> 222 * {@link #NUMBER} returns <jk>true</jk>; {@link #STRING} returns <jk>false</jk>. {@link #AUTO} 223 * returns <jk>false</jk> conservatively — its {@code format(...)} return type varies per value, so 224 * serializers should branch on the actual runtime type returned by 225 * {@link #format(BigInteger, BigNumberFormat)} / {@link #format(BigDecimal, BigNumberFormat)} rather 226 * than this hint. 227 * 228 * @return <jk>true</jk> if this format emits a bare numeric wire value. 229 */ 230 public boolean isNumeric() { 231 return this == NUMBER; 232 } 233 234 private static boolean isJsSafe(BigInteger value) { 235 return value.compareTo(BIG_JS_MIN_SAFE) >= 0 && value.compareTo(BIG_JS_MAX_SAFE) <= 0; 236 } 237}