was_777
was_777

Reputation: 711

Sonar java:S3516: Methods returns should not be invariant

Got the sonar error for the isValid method. I don't understand what is wrong with this implementation. The 2 return value are not always the same. validLength can be conditionally true/false.

@Slf4j
public class JsonNodeValidator implements ConstraintValidator<ValidJsonNode, JsonNode> {
  private String message;
  private int maxLength;

  @Override
  public void initialize(ValidJsonNode requiredIfChecked) {
    this.message = requiredIfChecked.message();
    this.maxLength = requiredIfChecked.maxLength();
  }

  @Override
  public boolean isValid(JsonNode value, ConstraintValidatorContext context) {
    if (value.isEmpty()) {
      setContext(context, "Data cannot be empty.");
      return false;
    }
    var validLength = getLength(value) <= maxLength;
    if (!validLength) {
      setContext(context, "Max Length exceeded");
    }
    return validLength;
  }

  private void setContext(ConstraintValidatorContext context, String msg) {
    context.disableDefaultConstraintViolation();
    context
        .buildConstraintViolationWithTemplate(message.concat(" ").concat(msg))
        .addConstraintViolation();
  }

  private int getLength(JsonNode responseData) {
    try {
      var objectMapper = new ObjectMapper();
      var bytes = objectMapper.writeValueAsBytes(responseData);
      return bytes.length / (1024 * 1024);
    } catch (JsonProcessingException e) {
      var msg = "Error in processing data";
      log.error(msg, e);
    }
  }
}

Upvotes: 0

Views: 178

Answers (0)

Related Questions