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

de.knightsoftnet.validators.shared.impl.LimitCharsetValidator Maven / Gradle / Ivy

Go to download

The MT Bean Validators is a collection of JSR-303/JSR-349/JSR-380 bean validators. It's extracted from GWT Bean Validators and contains no dependencies to GWT.

There is a newer version: 2.3.1
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License. You may obtain a
 * copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package de.knightsoftnet.validators.shared.impl;

import de.knightsoftnet.validators.shared.LimitCharset;

import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * The annotated element must contain only characters which are allowed in the given charset.
 *
 * @author Manfred Tremmel
 *
 */
public class LimitCharsetValidator implements ConstraintValidator {

  /**
   * charset to check against.
   */
  private Charset charset;

  /**
   * {@inheritDoc} initialize the validator.
   *
   * @see jakarta.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
   */
  @Override
  public final void initialize(final LimitCharset constraintAnnotation) {
    charset = Charset.forName(constraintAnnotation.charset());
  }

  /**
   * {@inheritDoc} check if given string is a valid mail.
   *
   * @see jakarta.validation.ConstraintValidator#isValid(java.lang.Object,
   *      jakarta.validation.ConstraintValidatorContext)
   */
  @Override
  public final boolean isValid(final String value, final ConstraintValidatorContext context) {
    if (StringUtils.isEmpty(value)) {
      return true;
    }
    try {
      final String target = new String(value.getBytes(charset), charset);
      return StringUtils.equals(value, target);
    } catch (final Exception e) {
      return false;
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy