001/*
002 * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Luís Duarte
018 */
019package org.nuxeo.ecm.directory.providers;
020
021import java.util.Arrays;
022import java.util.Collections;
023import java.util.List;
024import java.util.stream.Collectors;
025
026import org.nuxeo.ecm.directory.Directory;
027import org.nuxeo.ecm.directory.Session;
028import org.nuxeo.ecm.directory.api.DirectoryEntry;
029import org.nuxeo.ecm.platform.query.api.AbstractPageProvider;
030
031/**
032 * Simple page provider giving the possibility to paginate a {@link Directory}.
033 *
034 * @since 10.2
035 */
036public class DirectoryEntryPageProvider extends AbstractPageProvider<DirectoryEntry> {
037
038    private static final long serialVersionUID = 1L;
039
040    @Override
041    public List<DirectoryEntry> getCurrentPage() {
042        Object[] parameters = getParameters();
043        if (parameters == null || parameters.length > 1) {
044            throw new IllegalStateException("Invalid parameters: " + Arrays.toString(parameters));
045        }
046
047        if (!(parameters[0] instanceof Directory)) {
048            throw new IllegalStateException("Provided parameter is not a Directory: " + parameters[0]);
049        }
050
051        Directory directory = (Directory) parameters[0];
052
053        try (Session session = directory.getSession()) {
054            return session.query(Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap(), false,
055                    (int) getPageSize(), (int) getCurrentPageOffset())
056                          .stream()
057                          .map(dir -> new DirectoryEntry(directory.getName(), dir))
058                          .collect(Collectors.toList());
059        }
060    }
061}