This repository has been archived on 2022-12-21. You can view files and clone it, but cannot push or open issues or pull requests.
sdm03/src/main/java/com/github/dtschust/zork/parser/ZorkXMLParser.java

47 lines
2.0 KiB
Java

package com.github.dtschust.zork.parser;
import com.github.dtschust.zork.objects.ZorkContainer;
import com.github.dtschust.zork.objects.ZorkCreature;
import com.github.dtschust.zork.objects.ZorkItem;
import com.github.dtschust.zork.objects.ZorkRoom;
import com.github.dtschust.zork.parser.dom.DOMElement;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.nio.channels.NonReadableChannelException;
public class ZorkXMLParser extends ZorkParser {
public ZorkXMLParser(final PropertyParseStrategy<ZorkCreature> creatureStrategy,
final PropertyParseStrategy<ZorkContainer> containerStrategy,
final PropertyParseStrategy<ZorkItem> itemStrategy,
final PropertyParseStrategy<ZorkRoom> roomStrategy) {
super(creatureStrategy, containerStrategy, itemStrategy, roomStrategy);
}
@Override
protected Property getRootProperty(String filename) {
File file = new File(filename);
if (!file.canRead()) {
System.out.println("Error opening file. Exiting...");
throw new NonReadableChannelException();
}
try {
// Open the xml file
final DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
// Limit XML features to mitigate vulnerabilities
builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
final Element rootElement = builder.newDocumentBuilder().parse(file).getDocumentElement();
return DOMElement.of(rootElement);
} catch (final Exception ignored) {
System.out.println("Invalid XML file, exiting");
System.exit(-1);
return null; // never reached
}
}
}