Skip to content

Commit

Permalink
Introduce new stateful helper method
Browse files Browse the repository at this point in the history
  • Loading branch information
gwenn committed May 13, 2024
1 parent d011b20 commit cffaee4
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
9 changes: 7 additions & 2 deletions src/main/java/org/stax/StaxHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import javax.xml.stream.XMLStreamException;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
* Like SAX event {@link org.xml.sax.ContentHandler handler} but for StAX.
Expand Down Expand Up @@ -32,10 +33,10 @@ static StaxHandler pushOrSkip(String expected, StaxHandler child) {
};
}
static StaxHandler require(String expected, StaxHandler child) {
return ((sr, name) -> {
return (sr, name) -> {
sr.require(expected);
sr.push(child);
});
};
}

/**
Expand All @@ -51,6 +52,10 @@ interface StatefulHandler<S> {
void start(S state, StaxReader sr, String name) throws XMLStreamException;
}

static <S> StaxHandler stateful(String expected, Supplier<S> init, StatefulHandler<S> handler, Consumer<S> end) {
return stateful((sr, name) -> {sr.require(expected); return init.get();}, handler, end);
}

/**
* <pre>{@code
* <parent> <!-- sr.push(stateful(init, handler, end)); -->
Expand Down
8 changes: 2 additions & 6 deletions src/test/java/org/stax/StaxReaderImplTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.stax.StaxHandler.require;
import static org.stax.StaxHandler.stateful;
import static org.stax.StaxHandler.*;

/**
* Adapted from <a href="http://blog.palominolabs.com/2013/03/06/parsing-xml-with-java-and-staxmate/">Practical XML Parsing With Java and StaxMate</a>
Expand Down Expand Up @@ -38,10 +37,7 @@ static void handleRootChildElement(Food food, StaxReader sr, String name) {
return new Animal(sr.getAttributeValue("name"));
}, StaxReaderImplTest::extractAnimal, food.animals::add));
} else if ("vegetables".equals(name)) {
sr.push(stateful((r, n) -> {
sr.require("vegetable");
return new Vegetable();
}, StaxReaderImplTest::extractVegetable, food.vegetables::add));
sr.push(stateful("vegetable", Vegetable::new, StaxReaderImplTest::extractVegetable, food.vegetables::add));
}
}
private static void extractVegetable(Vegetable vegetable, StaxReader sr, String name) throws XMLStreamException {
Expand Down

0 comments on commit cffaee4

Please sign in to comment.