io.sphere.sdk.categories.CategoryTreeImpl Maven / Gradle / Ivy
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());
}
}