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

com.ly.invoker.builder.compiler.Context Maven / Gradle / Ivy

package com.ly.invoker.builder.compiler;

import com.ly.invoker.builder.constant.ChainType;
import com.ly.invoker.core.handler.HandlerFunction;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class Context {
    private final List elements = new ArrayList<>();

    public Context name(String name) {
        return helper(Element.of(ChainType.NAME_ROUTER, name));
    }

    public Context version(String version) {
        return helper(Element.of(ChainType.VERSION_ROUTER, version));
    }

    public Context handle(HandlerFunction handler) {
        return helper(Element.of(ChainType.HANDLER, handler));
    }

    public Context emptyHandle() {
        return helper(Element.empty(ChainType.HANDLER));
    }

    public Context name(String... names) {
        for (String name : names) {
            helper(Element.of(ChainType.NAME_ROUTER, name));
        }
        return this;
    }

    public Context version(String... versions) {
        for (String version : versions) {
            helper(Element.of(ChainType.VERSION_ROUTER, version));
        }
        return this;
    }

    public Context handle(HandlerFunction... handlers) {
        for (HandlerFunction handler : handlers) {
            helper(Element.of(ChainType.HANDLER, handler));
        }
        return this;
    }

    public Context emptyHandle(int n) {
        if (n > 0) {
            for (int i = 0; i < n; i++) {
                helper(Element.empty(ChainType.HANDLER));
            }
        }
        return this;
    }

    public Context resolve(Context context) {
        return helper(context);
    }

    public Context resolve(Consumer consumer) {
        Context context = new Context();
        consumer.accept(context);
        return helper(context);
    }

    public Context next(Context context) {
        helper(Element.empty(ChainType.LP));
        helper(context);
        helper(Element.empty(ChainType.RP));
        return this;
    }

    public Context next(Consumer consumer) {
        helper(Element.empty(ChainType.LP));
        Context context = new Context();
        consumer.accept(context);
        helper(context);
        helper(Element.empty(ChainType.RP));
        return this;
    }

    public Context reset() {
        elements.clear();
        return this;
    }

    public List elements() {
        return elements;
    }

    public Context clone() {
        Context ctx = new Context();
        ctx.elements.addAll(elements);
        return ctx;
    }

    private Context helper(Object element) {
        elements.add(element);
        return this;
    }
}