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

org.zalando.riptide.DefaultRoutingTree Maven / Gradle / Ivy

There is a newer version: 4.0.0
Show newest version
package org.zalando.riptide;

import org.springframework.http.client.ClientHttpResponse;

import javax.annotation.Nullable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Collectors.toMap;

final class DefaultRoutingTree implements RoutingTree {

    private final Navigator navigator;
    private final Map routes;
    private final Route wildcard;

    DefaultRoutingTree(final Navigator navigator, final List> bindings) {
        this(navigator, map(bindings));
    }

    private DefaultRoutingTree(final Navigator navigator, final Map routes) {
        this(navigator, unmodifiableMap(routes), routes.remove(null));
    }

    private DefaultRoutingTree(final Navigator navigator, final Map routes, @Nullable final Route wildcard) {
        this.navigator = navigator;
        this.routes = routes;
        this.wildcard = wildcard;
    }

    private static  Map map(final List> bindings) {
        return bindings.stream()
                .collect(toMap(Binding::getAttribute, Binding::getRoute, (u, v) -> {
                    throw new IllegalArgumentException(String.format("Duplicate key %s", u));
                }, LinkedHashMap::new));
    }

    @Override
    public Navigator getNavigator() {
        return navigator;
    }

    @Override
    public Set keySet() {
        return routes.keySet();
    }

    @Override
    public Optional get(final A attribute) {
        return Optional.ofNullable(routes.get(attribute));
    }

    @Override
    public Optional getWildcard() {
        return Optional.ofNullable(wildcard);
    }

    @Override
    public void execute(final ClientHttpResponse response, final MessageReader reader) throws Exception {
        final Optional route = navigator.navigate(response, this);

        if (route.isPresent()) {
            try {
                route.get().execute(response, reader);
            } catch (final NoWildcardException e) {
                executeWildcard(response, reader);
            }
        } else {
            executeWildcard(response, reader);
        }
    }

    private void executeWildcard(final ClientHttpResponse response, final MessageReader reader) throws Exception {
        if (wildcard == null) {
            throw new NoWildcardException();
        }

        wildcard.execute(response, reader);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy