/*
* Copyright (c) 2013, the authors.
*
* This file is part of 'DXFS'.
*
* DXFS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DXFS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DXFS. If not, see <http://www.gnu.org/licenses/>.
*/
package nextflow.fs.dx;
import java.io.IOException;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.util.Iterator;
/**
* Stream the content of teh specified path
*
* @see DirectoryStream
* @author Paolo Di Tommaso <paolo.ditommaso@gmail.com>
*
*/
public class DxDirectoryStream implements DirectoryStream<Path> {
private final Filter<? super Path> filter;
private DxPath path;
private Iterator<DxPath> target;
public DxDirectoryStream( DxPath path, Filter<? super Path> filter ) throws IOException {
this.path = path;
this.filter = filter;
this.target = path.getFileSystem().folderIterator(path);
}
@Override
public Iterator<Path> iterator() {
return new Iterator<Path>() {
Path nextValue = findNext(target);
@Override
public boolean hasNext() {
return nextValue != null;
}
@Override
public Path next() {
Path result = nextValue;
nextValue = findNext(target);
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
private Path findNext(Iterator<DxPath> it) {
while( it.hasNext() ) {
Path item = it.next();
try {
if( filter == null || filter.accept(item) ) {
return item;
}
}
catch( IOException e ) {
throw new DirectoryIteratorException(e);
}
}
return null;
}
@Override
public void close() throws IOException {
// nothing to do
}
}