BAEL 2338 - Updated code for the article Convert XML to HTML in Java (#7813)

* FEAT Added close handling to resources & extra security configurations

* UPDATE Added extra security configuration

* UPDATE Closed input stream & rename local variables to avoid shadowing
This commit is contained in:
Juan Moreno 2019-09-17 22:35:11 -03:00 committed by KevinGilmore
parent 76b69c3b00
commit 2140022058
4 changed files with 80 additions and 67 deletions

View File

@ -24,7 +24,7 @@ public class FreemarkerTransformer {
this.templateFile = templateFile; this.templateFile = templateFile;
} }
public String html() throws IOException, XMLStreamException, TemplateException { public String html() throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29); Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
cfg.setDirectoryForTemplateLoading(new File(templateDirectory)); cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString()); cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
@ -33,8 +33,9 @@ public class FreemarkerTransformer {
cfg.setWrapUncheckedExceptions(true); cfg.setWrapUncheckedExceptions(true);
cfg.setFallbackOnNullLoopVariable(false); cfg.setFallbackOnNullLoopVariable(false);
Template temp = cfg.getTemplate(templateFile); Template temp = cfg.getTemplate(templateFile);
Writer output = new StringWriter(); try (Writer output = new StringWriter()) {
temp.process(staxTransformer.buildMap(), output); temp.process(staxTransformer.getMap(), output);
return output.toString(); return output.toString();
}
} }
} }

View File

@ -27,12 +27,13 @@ public class JaxpTransformer {
// 1- Build the doc from the XML file // 1- Build the doc from the XML file
factory = DocumentBuilderFactory.newInstance(); factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
input = factory input = factory
.newDocumentBuilder() .newDocumentBuilder()
.parse(resourcePath); .parse(resourcePath);
} }
public String html() throws ParserConfigurationException, TransformerException { public String html() throws ParserConfigurationException, TransformerException, IOException {
Element xml = input.getDocumentElement(); Element xml = input.getDocumentElement();
Document doc = factory Document doc = factory
.newDocumentBuilder() .newDocumentBuilder()
@ -48,19 +49,19 @@ public class JaxpTransformer {
Element body = buildBody(map, doc); Element body = buildBody(map, doc);
html.appendChild(body); html.appendChild(body);
doc.appendChild(html); doc.appendChild(html);
Writer output = applyTransformation(doc); return String.format("<!DOCTYPE html>%n%s", applyTransformation(doc));
return String.format("<!DOCTYPE html>%n%s", output.toString());
} }
private Writer applyTransformation(Document doc) throws TransformerException { private String applyTransformation(Document doc) throws TransformerException, IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance(); TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
Writer output = new StringWriter(); try (Writer output = new StringWriter()) {
Transformer transformer = transformerFactory.newTransformer(); Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(output)); transformer.transform(new DOMSource(doc), new StreamResult(output));
return output; return output.toString();
}
} }
private Map<String, String> buildMap(Element xml) { private Map<String, String> buildMap(Element xml) {

View File

@ -19,12 +19,13 @@ public class MustacheTransformer {
this.templateFile = templateFile; this.templateFile = templateFile;
} }
public String html() throws IOException, XMLStreamException { public String html() throws IOException {
MustacheFactory mf = new DefaultMustacheFactory(); MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(templateFile); Mustache mustache = mf.compile(templateFile);
Writer output = new StringWriter(); try (Writer output = new StringWriter()) {
mustache.execute(output, staxTransformer.buildMap()); mustache.execute(output, staxTransformer.getMap());
output.flush(); output.flush();
return output.toString(); return output.toString();
}
} }
} }

View File

@ -2,7 +2,7 @@ package com.baeldung.xmlhtml.stax;
import javax.xml.stream.*; import javax.xml.stream.*;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.util.HashMap; import java.util.HashMap;
@ -10,80 +10,90 @@ import java.util.Map;
public class StaxTransformer { public class StaxTransformer {
private XMLStreamReader input; private Map<String, String> map;
public StaxTransformer(String resourcePath) throws FileNotFoundException, XMLStreamException { public StaxTransformer(String resourcePath) throws IOException, XMLStreamException {
XMLInputFactory factory = XMLInputFactory.newInstance(); XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
input = factory.createXMLStreamReader(new FileInputStream(resourcePath)); XMLStreamReader input = null;
try (FileInputStream file = new FileInputStream(resourcePath)) {
input = factory.createXMLStreamReader(file);
map = buildMap(input);
} finally {
if (input != null) {
input.close();
}
}
} }
public String html() throws XMLStreamException { public String html() throws XMLStreamException, IOException {
Map<String, String> map = buildMap(); try (Writer output = new StringWriter()) {
Writer output = new StringWriter(); XMLStreamWriter writer = XMLOutputFactory
XMLStreamWriter writer = XMLOutputFactory .newInstance()
.newInstance() .createXMLStreamWriter(output);
.createXMLStreamWriter(output); //Head
//Head writer.writeDTD("<!DOCTYPE html>");
writer.writeDTD("<!DOCTYPE html>"); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeStartElement("html");
writer.writeStartElement("html"); writer.writeAttribute("lang", "en");
writer.writeAttribute("lang", "en"); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeStartElement("head");
writer.writeStartElement("head"); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeDTD("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
writer.writeDTD("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeStartElement("title");
writer.writeStartElement("title"); writer.writeCharacters(map.get("heading"));
writer.writeCharacters(map.get("heading")); writer.writeEndElement();
writer.writeEndElement(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeEndElement();
writer.writeEndElement(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); //Body
//Body writer.writeStartElement("body");
writer.writeStartElement("body"); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeStartElement("p");
writer.writeStartElement("p"); writer.writeCharacters(map.get("from"));
writer.writeCharacters(map.get("from")); writer.writeEndElement();
writer.writeEndElement(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeStartElement("p");
writer.writeStartElement("p"); writer.writeCharacters(map.get("content"));
writer.writeCharacters(map.get("content")); writer.writeEndElement();
writer.writeEndElement(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeEndElement();
writer.writeEndElement(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.writeEndDocument();
writer.writeEndDocument(); writer.writeCharacters(String.format("%n"));
writer.writeCharacters(String.format("%n")); writer.flush();
writer.flush(); return output.toString();
writer.close(); }
return output.toString();
} }
public Map<String, String> buildMap() throws XMLStreamException { private Map<String, String> buildMap(XMLStreamReader input) throws XMLStreamException {
Map<String, String> map = new HashMap<>(); Map<String, String> tempMap = new HashMap<>();
while (input.hasNext()) { while (input.hasNext()) {
input.next(); input.next();
if (input.isStartElement()) { if (input.isStartElement()) {
if (input if (input
.getLocalName() .getLocalName()
.equals("heading")) { .equals("heading")) {
map.put("heading", input.getElementText()); tempMap.put("heading", input.getElementText());
} }
if (input if (input
.getLocalName() .getLocalName()
.equals("from")) { .equals("from")) {
map.put("from", String.format("from: %s", input.getElementText())); tempMap.put("from", String.format("from: %s", input.getElementText()));
} }
if (input if (input
.getLocalName() .getLocalName()
.equals("content")) { .equals("content")) {
map.put("content", input.getElementText()); tempMap.put("content", input.getElementText());
} }
} }
} }
input.close(); return tempMap;
}
public Map<String, String> getMap() {
return map; return map;
} }
} }