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

io.sphere.sdk.categories.CategoryTreeImpl Maven / Gradle / Ivy

There is a newer version: 1.0.0-M26
Show newest version
package io.sphere.sdk.categories;

import io.sphere.sdk.models.Base;
import io.sphere.sdk.models.Identifiable;
import io.sphere.sdk.models.LocalizedStringEntry;

import java.util.*;

import static io.sphere.sdk.utils.MapUtils.*;
import static io.sphere.sdk.utils.ListUtils.*;

class CategoryTreeImpl extends Base implements CategoryTree {
    private final List roots;
    private final List allAsFlatList;
    final Map categoriesByLocaleAndSlug;
    final Map categoriesById;
    private final Map> childrenByParentId;

    CategoryTreeImpl(final List roots,
                     final List allAsFlatList,
                     final Map categoriesByLocaleAndSlug,
                     final Map categoriesById,
                     final Map> childrenByParentId) {
        this.childrenByParentId = childrenByParentId;
        this.roots = immutableCopyOf(roots);
        this.allAsFlatList = immutableCopyOf(allAsFlatList);
        this.categoriesByLocaleAndSlug = immutableCopyOf(categoriesByLocaleAndSlug);
        this.categoriesById = immutableCopyOf(categoriesById);
    }

    @Override
    public List getRoots() {
        return roots;
    }

    @Override
    public Optional findById(final String id) {
        return Optional.ofNullable(categoriesById.get(id));
    }

    @Override
    public Optional findByExternalId(final String externalId) {
        return getAllAsFlatList().parallelStream()
                .filter(cat -> Optional.ofNullable(cat.getExternalId()).map(extIdElement -> extIdElement.equals(externalId)).orElse(false))
                .findAny();//should be okay, since the externalId should be unique
    }

    @Override
    public Optional findBySlug(final Locale locale, final String slug) {
        return Optional.ofNullable(categoriesByLocaleAndSlug.get(LocalizedStringEntry.of(locale, slug)));
    }

    @Override
    public List getAllAsFlatList() {
        return allAsFlatList;
    }

    @Override
    public List findChildren(final Identifiable category) {
        final String categoryId = category.getId();
        return childrenByParentId.getOrDefault(categoryId, Collections.emptyList());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy