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

com.vaadin.data.ValidationResultWrap Maven / Gradle / Ivy

There is a newer version: 8.27.3
Show newest version
/*
 * Copyright (C) 2000-2024 Vaadin Ltd
 *
 * This program is available under Vaadin Commercial License and Service Terms.
 *
 * See  for the full
 * license.
 */
package com.vaadin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import com.vaadin.server.SerializableConsumer;
import com.vaadin.server.SerializableFunction;

/**
 * Internal implementation of a {@code Result} that collects all possible
 * ValidationResults into one list. This class intercepts the normal chaining of
 * Converters and Validators, catching and collecting results.
 *
 * @param 
 *            the result data type
 *
 * @since 8.2
 */
class ValidationResultWrap implements Result {

    private final List resultList;
    private final Result wrappedResult;

    ValidationResultWrap(Result result, List resultList) {
        this.resultList = resultList;
        this.wrappedResult = result;
    }

    ValidationResultWrap(R value, ValidationResult result) {
        if (result.isError()) {
            wrappedResult = new SimpleResult<>(null, result.getErrorMessage());
        } else {
            wrappedResult = new SimpleResult<>(value, null);
        }
        this.resultList = new ArrayList<>();
        this.resultList.add(result);
    }

    List getValidationResults() {
        return Collections.unmodifiableList(resultList);
    }

    Result getWrappedResult() {
        return wrappedResult;
    }

    @Override
    public  Result flatMap(SerializableFunction> mapper) {
        Result result = wrappedResult.flatMap(mapper);
        if (!(result instanceof ValidationResultWrap)) {
            return new ValidationResultWrap(result, resultList);
        }

        List currentResults = new ArrayList<>(resultList);
        ValidationResultWrap resultWrap = (ValidationResultWrap) result;
        currentResults.addAll(resultWrap.getValidationResults());

        return new ValidationResultWrap<>(resultWrap.getWrappedResult(),
                currentResults);
    }

    @Override
    public void handle(SerializableConsumer ifOk,
            SerializableConsumer ifError) {
        wrappedResult.handle(ifOk, ifError);
    }

    @Override
    public boolean isError() {
        return wrappedResult.isError();
    }

    @Override
    public Optional getMessage() {
        return wrappedResult.getMessage();
    }

    @Override
    public  R getOrThrow(
            SerializableFunction exceptionProvider)
            throws X {
        return wrappedResult.getOrThrow(exceptionProvider);
    }

}