com.carlomicieli.jtrains.test.ValidationResult.java Source code

Java tutorial

Introduction

Here is the source code for com.carlomicieli.jtrains.test.ValidationResult.java

Source

/*
 * Copyright 2014 the original author or authors.
 *
 *  Licensed 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 com.carlomicieli.jtrains.test;

import org.springframework.util.Assert;

import javax.validation.ConstraintViolation;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * It represents a class to manipulate validation results.
 * @author Carlo Micieli
 */
public final class ValidationResult<T> {
    private final Set<ConstraintViolation<T>> errors;

    private ValidationResult(Set<ConstraintViolation<T>> errors) {
        Assert.notNull(errors, "ValidationResult: errors is null");
        this.errors = errors;
    }

    public static <U> ValidationResult<U> of(Set<ConstraintViolation<U>> errors) {
        return new ValidationResult<>(errors);
    }

    public boolean hasErrors() {
        return this.size() != 0;
    }

    public int size() {
        return errors.size();
    }

    public List<String> fieldErrors(String fieldName) {
        return errorsStream().filter(fieldNamePredicate(fieldName)).map(ConstraintViolation::getMessageTemplate)
                .sorted().collect(Collectors.toList());
    }

    public boolean containsMessage(String msg) {
        return exists(v -> v.getMessageTemplate().equals(msg));
    }

    public String messages() {
        String[] arr = errorsStream().map(ConstraintViolation::getMessageTemplate).sorted().toArray(String[]::new);
        return Arrays.toString(arr);
    }

    private boolean exists(Predicate<ConstraintViolation<T>> p) {
        Optional<ConstraintViolation<T>> err = errorsStream().filter(p).findAny();
        return err.isPresent();
    }

    @Override
    public String toString() {
        return super.toString();
    }

    private Stream<ConstraintViolation<T>> errorsStream() {
        return errors.stream();
    }

    private Predicate<ConstraintViolation<T>> fieldNamePredicate(String fieldName) {
        return cv -> cv.getPropertyPath().toString().equals(fieldName);
    }
}