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

org.jtrim2.taskgraph.ResultTransformerFactory Maven / Gradle / Ivy

There is a newer version: 2.0.7
Show newest version
package org.jtrim2.taskgraph;

import java.util.Objects;
import java.util.function.Function;
import org.jtrim2.cancel.CancellationToken;
import org.jtrim2.executor.CancelableFunction;

final class ResultTransformerFactory implements TaskFactory {
    private final ResultTransformer resultTransformer;

    public  ResultTransformerFactory(
            Class dependencyResultType,
            Function resultTransformer) {
        this.resultTransformer = new ResultTransformer<>(dependencyResultType, resultTransformer);
    }

    @Override
    public CancelableFunction createTaskNode(
            CancellationToken cancelToken,
            TaskNodeCreateArgs nodeDef) throws Exception {

        TaskInputRef resultRef = resultTransformer.bindInput(nodeDef.nodeKey(), nodeDef.inputs());
        return taskCancelToken -> resultRef.consumeInput();
    }

    private static final class ResultTransformer {
        private final Class dependencyResultType;
        private final Function resultTransformer;

        public ResultTransformer(
                Class dependencyResultType,
                Function resultTransformer) {
            this.dependencyResultType = Objects.requireNonNull(dependencyResultType, "dependencyResultType");
            this.resultTransformer = Objects.requireNonNull(resultTransformer, "resultTransformer");
        }

        public TaskInputRef bindInput(TaskNodeKey srcKey, TaskInputBinder inputs) {
            TaskNodeKey dependencyKey = srcKey.withResultType(dependencyResultType);
            TaskInputRef resultRef = inputs.bindInput(dependencyKey);
            return convertResult(resultRef, resultTransformer);
        }

        private static  TaskInputRef convertResult(
                TaskInputRef srcRef,
                Function resultTransformer) {
            return () -> {
                R2 result = srcRef.consumeInput();
                return resultTransformer.apply(result);
            };
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy