Tokenizer.java

 1package eu.siacs.conversations.crypto.sasl;
 2
 3import java.util.ArrayList;
 4import java.util.Arrays;
 5import java.util.Iterator;
 6import java.util.List;
 7import java.util.NoSuchElementException;
 8
 9/**
10 * A tokenizer for GS2 header strings
11 */
12public final class Tokenizer implements Iterator<String>, Iterable<String> {
13    private final List<String> parts;
14    private int index;
15
16    public Tokenizer(final byte[] challenge) {
17        final String challengeString = new String(challenge);
18        parts = new ArrayList<>(Arrays.asList(challengeString.split(",")));
19        // Trim parts.
20        for (int i = 0; i < parts.size(); i++) {
21            parts.set(i, parts.get(i).trim());
22        }
23        index = 0;
24    }
25
26    /**
27     * Returns true if there is at least one more element, false otherwise.
28     *
29     * @see #next
30     */
31    @Override
32    public boolean hasNext() {
33        return parts.size() != index + 1;
34    }
35
36    /**
37     * Returns the next object and advances the iterator.
38     *
39     * @return the next object.
40     * @throws java.util.NoSuchElementException if there are no more elements.
41     * @see #hasNext
42     */
43    @Override
44    public String next() {
45        if (hasNext()) {
46            return parts.get(index++);
47        } else {
48            throw new NoSuchElementException("No such element. Size is: " + parts.size());
49        }
50    }
51
52    /**
53     * Removes the last object returned by {@code next} from the collection.
54     * This method can only be called once between each call to {@code next}.
55     *
56     * @throws UnsupportedOperationException if removing is not supported by the collection being
57     *                                       iterated.
58     * @throws IllegalStateException         if {@code next} has not been called, or {@code remove} has
59     *                                       already been called after the last call to {@code next}.
60     */
61    @Override
62    public void remove() {
63        if (index <= 0) {
64            throw new IllegalStateException("You can't delete an element before first next() method call");
65        }
66        parts.remove(--index);
67    }
68
69    /**
70     * Returns an {@link java.util.Iterator} for the elements in this object.
71     *
72     * @return An {@code Iterator} instance.
73     */
74    @Override
75    public Iterator<String> iterator() {
76        return parts.iterator();
77    }
78}