Skip to content

Instantly share code, notes, and snippets.

@eribeiro
Created December 26, 2016 21:51
Show Gist options
  • Save eribeiro/8e72ca595ed9c33572e5c153f7fa56ff to your computer and use it in GitHub Desktop.
Save eribeiro/8e72ca595ed9c33572e5c153f7fa56ff to your computer and use it in GitHub Desktop.
//import org.apache.zookeeper.common.PathUtils;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public final class PathIterator implements Iterator<String>, Iterable<String> {
public static final String SEP = "/";
private String[] znodes;
private int end = -1;
public PathIterator(String path) {
// PathUtils.validatePath(path);
znodes = path.split("/");
// skip first array element, that is empty
if (znodes.length > 1) {
znodes = Arrays.copyOfRange(znodes, 1, znodes.length);
}
end = znodes.length;
}
@Override
public boolean hasNext() {
return end >= 0;
}
public boolean atParentPath() {
return end != znodes.length;
}
@Override
public String next() {
String localPath = joinZPath(znodes, end);
if (hasNext()) {
end--;
}
else {
throw new NoSuchElementException();
}
return localPath;
}
@Override
public Iterator<String> iterator() {
return this;
}
private static String joinZPath(String[] znodes, int end) {
int counter = 0;
if (end == 0 && counter == 0) {
return SEP;
}
else {
StringBuilder sb = new StringBuilder();
for (String znode : znodes) {
if (end < 0 || counter < end) {
sb.append(SEP).append(znode);
} else {
break;
}
counter++;
}
return sb.toString();
}
}
}
@eribeiro
Copy link
Author

eribeiro commented Dec 26, 2016

joinZPath with a negative end will print the whole path. OTOH, end >= 0 will print the portion of the path up to end value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment