Commit d0ab625c authored by Administrator's avatar Administrator

Initial commit

parents
#Eclipse
.settings
.project
.classpath
#Maven
target
#General
bak
This diff is collapsed.
# Kata 6. Recetas de Cocina (APIs)
En esta kata trataremos el manejo de las APIs DOM y SAX de Java. Para ello, partiendo del presente proyecto, queremos hacer un programa que, dado el nombre de un autor, nos devuelva la lista de recetas en las que participa.
Una vez completado el trabajo con DOM y SAX, habrá que repetir el trabajo pero utilizando el API de Java de XPath para recuperar la información.
Por último, se debe hacer la transformación del documento XML utilizando el documento XSLT a través del API de XSLT de Java.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.uvigo.esei.dai</groupId>
<artifactId>kata6</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>DAI Dojo - Kata 6</name>
<inceptionYear>2014</inceptionYear>
<url>https://sing-group.org/dt/gitlab/dai/kata6</url>
<developers>
<developer>
<name>Miguel Reboiro-Jato</name>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<email>mrjato@uvigo.gal</email>
</developer>
</developers>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Plugin versions -->
<license-maven-plugin.version>2.2.0</license-maven-plugin.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<!-- license-maven-plugin configuration -->
<license.licenseName>gpl_v3</license.licenseName>
<license.copyrightOwners>Miguel Reboiro Jato</license.copyrightOwners>
<license.organizationName>Universidade de Vigo</license.organizationName>
<license.addJavaLicenseAfterPackage>false</license.addJavaLicenseAfterPackage>
</properties>
<contributors>
<contributor>
<name>Miguel Reboiro Jato</name>
<email>mrjato@uvigo.gal</email>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<roles>
<role>author</role>
<role>professor</role>
</roles>
</contributor>
</contributors>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<version>${license-maven-plugin.version}</version>
<executions>
<execution>
<id>first</id>
<goals>
<goal>update-file-header</goal>
</goals>
<phase>process-sources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
/*-
* #%L
* DAI Dojo - Kata 6
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.xml;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class SimpleErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
}
/*-
* #%L
* DAI Dojo - Kata 6
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.xml.dom;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import es.uvigo.esei.dai.xml.SimpleErrorHandler;
public class DOMParsing {
public static Document loadDocument(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setNamespaceAware(true);
final DocumentBuilder builder = factory.newDocumentBuilder();
// Parsing del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithInternalDTD(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento activando validación
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// Al construir el parser hay que añadir un manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
// Parsing y validación del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithInternalXSD(String documentPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento activando validación
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Al construir el parser hay que añadir un manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
// Parsing y validación del documento
return builder.parse(new File(documentPath));
}
public static Document loadAndValidateWithExternalXSD(String documentPath, String schemaPath)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(new File(schemaPath));
// Construcción del parser del documento. Se establece el esquema y se activa
// la validación y comprobación de namespaces
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setSchema(schema);
// Se añade el manejador de errores
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new SimpleErrorHandler());
return builder.parse(new File(documentPath));
}
public static String toXML(Document document) throws TransformerException, IOException {
// Creación y configuración del transformador. En este caso, se activa
// la indentación del XML
final TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute("indent-number", 3);
final Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// El resultado se almacenará en una cadena de texto
try (final StringWriter writer = new StringWriter()) {
transformer.transform(new DOMSource(document), new StreamResult(writer));
return writer.toString();
}
}
}
/*-
* #%L
* DAI Dojo - Kata 6
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.xml.sax;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import es.uvigo.esei.dai.xml.SimpleErrorHandler;
public class SAXParsing {
public static void parseFile(String xmlPath, ContentHandler handler)
throws SAXException, IOException, ParserConfigurationException {
// Construcción del parser SAX
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
// Se añade el handler al parser SAX
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
reader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidatedWithInternalDTD(String xmlPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser SAX activando la validación
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
// Al construir el parser hay que añadir un manejador de errores
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidateWithInternalXSD(String xmlPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del parser del documento. Se activa
// la validación y comprobación de namespaces
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(true);
parserFactory.setNamespaceAware(true);
// Se añade el manejador de errores y se activa la validación por schema
final SAXParser parser = parserFactory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
public static void parseAndValidateWithExternalXSD(String xmlPath, String schemaPath, ContentHandler handler)
throws ParserConfigurationException, SAXException, IOException {
// Construcción del schema
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = schemaFactory.newSchema(new File(schemaPath));
// Construcción del parser del documento. Se establece el esquema y se activa
// la validación y comprobación de namespaces
final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(true);
parserFactory.setSchema(schema);
// Se añade el manejador de errores
final SAXParser parser = parserFactory.newSAXParser();
final XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(new SimpleErrorHandler());
// Parsing
try (FileReader fileReader = new FileReader(new File(xmlPath))) {
xmlReader.parse(new InputSource(fileReader));
}
}
}
/*-
* #%L
* DAI Dojo - Kata 6
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.xml.xpath;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
public class NamespaceContextMap implements NamespaceContext {
private final Map<String, String> namespaceToPrefix;
private final Map<String, String> prefixToNamespace;
public NamespaceContextMap() {
this.namespaceToPrefix = new HashMap<>();
this.prefixToNamespace = new HashMap<>();
}
public void putNamespaceURI(String prefix, String namespaceURI) {
this.namespaceToPrefix.put(namespaceURI, prefix);
this.prefixToNamespace.put(prefix, namespaceURI);
}
@Override
public String getNamespaceURI(String prefix) {
return this.prefixToNamespace.get(prefix);
}
@Override
public String getPrefix(String namespaceURI) {
return this.namespaceToPrefix.get(namespaceURI);
}
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
return this.namespaceToPrefix.keySet().iterator();
}
}
/*-
* #%L
* DAI Dojo - Kata 6
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.xml.xpath;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class XSLUtils {
public static Object xpathQueryDOM(Object object, String expression, QName qname) throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
return xpath.evaluate(expression, object, qname);
/*
* También sería válido XPathExpression xpExp = xpath.compile(expression); return xpExp.evaluate(object, qname);
*/
}
public static Object xpathQuerySAX(InputSource xmlSource, String expression, QName qname)
throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
return xpath.evaluate(expression, xmlSource, qname);
/*
* También sería válido XPathExpression xpExp = xpath.compile(expression); return xpExp.evaluate(xmlSource, qname);
*/
}
public static Object xpathQueryDOM(Object object, String expression, QName returnType, NamespaceContext nsContext)
throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
if (nsContext != null) {
xpath.setNamespaceContext(nsContext);
}
return xpath.evaluate(expression, object, returnType);
}
public static Object xpathQuerySAX(
InputSource xmlSource, String expression, QName returnType, NamespaceContext nsContext
) throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
if (nsContext != null) {
xpath.setNamespaceContext(nsContext);
}
return xpath.evaluate(expression, xmlSource, returnType);
}
public static void transformWithXSLT(Source xmlSource, Source xsltSource, Result result) throws TransformerException {
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer(xsltSource);
transformer.transform(xmlSource, result);
}
public static String transformWithXSLT(File xml, File xslt) throws TransformerException, IOException {
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer(new StreamSource(xslt));
try (final StringWriter writer = new StringWriter()) {
transformer.transform(new StreamSource(xml), new StreamResult(writer));
return writer.toString();
}
}
public static String transformToString(File xml) throws TransformerException, IOException {
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer();
try (final StringWriter writer = new StringWriter()) {
transformer.transform(new StreamSource(xml), new StreamResult(writer));
return writer.toString();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment