All Downloads are FREE. Search and download functionalities are using the official Maven repository.

play.api.libs.json.BigDecimalParser.scala Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 
 */

package play.api.libs.json

private[json] object BigDecimalParser {

  private val useJacksonParser =
    JsonConfig.playJsonConfig.getBoolean("read.use-jackson-big-decimal-parser")

  private lazy val useJacksonFastParser =
    JsonConfig.playJsonConfig.getBoolean("read.use-jackson-fast-decimal-parser")

  def parse(input: String, jsonConfig: JsonConfig): JsResult[java.math.BigDecimal] = {
    // There is a limit of how large the numbers can be since parsing extremely
    // large numbers (think thousand of digits) and operating on the parsed values
    // can potentially cause a DDoS.
    if (input.length > jsonConfig.bigDecimalParseConfig.digitsLimit) {
      JsError("error.expected.numberdigitlimit")
    } else {

      // Must create the BigDecimal with a MathContext that is consistent with the limits used.
      try {
        val bigDecimal = if (useJacksonParser) {
          com.fasterxml.jackson.core.io.NumberInput.parseBigDecimal(input, useJacksonFastParser)
        } else {
          new java.math.BigDecimal(input, jsonConfig.bigDecimalParseConfig.mathContext)
        }

        // We should also avoid numbers with scale that are out of a safe limit
        val scale = bigDecimal.scale
        if (Math.abs(scale) > jsonConfig.bigDecimalParseConfig.scaleLimit) {
          JsError(JsonValidationError("error.expected.numberscalelimit", scale))
        } else {
          JsSuccess(bigDecimal)
        }
      } catch {
        case _: NumberFormatException => JsError("error.expected.numberformatexception")
      }
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy