Created
December 26, 2016 21:51
-
-
Save eribeiro/8e72ca595ed9c33572e5c153f7fa56ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
joinZPath
with a negativeend
will print the whole path. OTOH,end >= 0
will print the portion of the path up toend
value.