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

org.boothub.Result.groovy Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2017 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 org.boothub

import groovy.transform.Canonical
import groovy.util.logging.Slf4j

import java.util.function.Predicate

@Slf4j
@Canonical
class Result {
    static enum Type {SUCCESS, WARNING, ERROR}

    Type type = Type.SUCCESS
    String message
    V value

    public static  Result onFailure(String errMessage, Closure valueProvider) {
        try {
            return new Result(type: Type.SUCCESS, value: valueProvider.call())
        } catch (Exception e) {
            log.error(errMessage, e)
            return new Result(type: Type.ERROR, message: errMessage)
        }
    }

    boolean isSuccessful() {
        type == Type.SUCCESS
    }

    V valueOrThrow() {
        if(!successful) throw new RuntimeException(message)
        value
    }

    public  Result mapValueIf(Predicate> checker, Closure mapper) {
        if(!checker.test(this)) {
            new Result(type: type, message: message, value: null)
        } else {
            try {
                new Result(type: type, message: message, value: mapper.call(value))
            } catch (Exception e) {
                log.error("Cannot map result: $this", e)
                new Result(type: Type.ERROR, message: "An error occurred.", value: null)
            }
        }
    }

    public  Result mapValue(Closure mapper) {
        mapValue({true}, mapper)
    }

    public  Result mapValueIfSuccess(Closure mapper) {
        mapValueIf({res -> res.successful}, mapper)
    }

    public  Result mapValueIfNotNull(Closure mapper) {
        mapValueIf({res -> res.value != null}, mapper)
    }

    public  Result mapValueIfNotNullAndSuccess(Closure mapper) {
        mapValueIf({res -> res.successful && (res.value != null)}, mapper)
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy