Spring Batch Stax XML reading job is not ending when out of input

…衆ロ難τιáo~ 提交于 2019-12-04 16:42:38

I've resolved this problem for myself, though I'm surprised by what I had to do. Debugging through StaxEventItemReader, I noticed that the inner loop in the moveCursorToNextFragment() method would go infinite when the end of my document was reached. Here's the relevant code:

while (true) {
    while (reader.peek() != null && !reader.peek().isStartElement()) {
        reader.nextEvent();
    }
    if (reader.peek() == null) {
        return false;
    }
    QName startElementName = ((StartElement) reader.peek()).getName();
    if (startElementName.getLocalPart().equals(fragmentRootElementName)) {
        if (fragmentRootElementNameSpace == null
    || startElementName.getNamespaceURI().equals(fragmentRootElementNameSpace)) {
           return true;
        }
     }
    reader.nextEvent();
 }

reader.peek() was never returning null. It seemed to me like this code should be checking to see if the XMLEvent encountered during peek() is at the end of the document, but this wasn't so simple due to the StaxEventItemReader's reliance on a DefaultFragmentEventReader wrapping the standard XMLEventReader.

What I wound up doing was rolling my own ItemReader based on StaxEventItemReader but without using a FragmentEventReader at all, and then adjusting the inner loop code to read like so:

        if (reader.peek().getEventType() == XMLStreamConstants.END_DOCUMENT) {
            return false;
        }
        reader.nextEvent();

That works perfectly and allows my batch job to go to COMPLETED at the end of input.

I'm really surprised that I had to do this, though. I wondered if the underlying implementation of the streaming XML libraries I was using was at fault, but I'm using stax2-api-3.0.1.jar as referenced in the Spring Batch dependency list.

I also found that I'm not alone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!