001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (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 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.webengine.model.impl;
023
024import java.io.File;
025import java.io.FileFilter;
026import java.io.IOException;
027import java.util.ArrayList;
028import java.util.Arrays;
029import java.util.List;
030
031/**
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034public class DirectoryStack {
035
036    protected final List<File> dirs;
037
038    public DirectoryStack() {
039        dirs = new ArrayList<>();
040    }
041
042    public DirectoryStack(List<File> entries) {
043        this();
044        dirs.addAll(entries);
045    }
046
047    public List<File> getDirectories() {
048        return dirs;
049    }
050
051    public boolean isEmpty() {
052        return dirs.isEmpty();
053    }
054
055    public void addDirectory(File dir) throws IOException {
056        dirs.add(dir.getCanonicalFile());
057    }
058
059    /**
060     * Gets the file given its name in this virtual directory.
061     * <p>
062     * The canonical file is returned if any file is found
063     *
064     * @param name the file name to lookup
065     * @return the file in the canonical form
066     */
067    public File getFile(String name) throws IOException {
068        for (File entry : dirs) {
069            File file = new File(entry, name);
070            if (file.exists()) {
071                return file.getCanonicalFile();
072            }
073        }
074        return null;
075    }
076
077    public File[] listFiles() {
078        List<File> result = new ArrayList<>();
079        for (File entry : dirs) {
080            File[] files = entry.listFiles();
081            result.addAll(Arrays.asList(files));
082        }
083        return result.toArray(new File[0]);
084    }
085
086    public File[] listFiles(FileFilter filter) {
087        List<File> result = new ArrayList<>();
088        for (File entry : dirs) {
089            File[] files = entry.listFiles(filter);
090            result.addAll(Arrays.asList(files));
091        }
092        return result.toArray(new File[0]);
093    }
094
095}