Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.StringReader;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.transform.Source;
- import javax.xml.transform.stream.StreamSource;
- import javax.xml.validation.Schema;
- import javax.xml.validation.SchemaFactory;
- import javax.xml.validation.Validator;
- import javax.xml.xpath.XPath;
- import javax.xml.xpath.XPathFactory;
- import org.w3c.dom.Document;
- import org.xml.sax.SAXException;
- /*
- * A blank servlet to make it easy to quickly test code snippets. For developers use.
- */
- public class TestingServlet extends HttpServlet {
- String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><computer><keyboard>105 keys</keyboard><mouse>3 button</mouse><monitor>vga</monitor></computer>";
- static URL xsdPath;
- @Override public void init(ServletConfig config) throws ServletException {
- super.init(config);
- try {
- xsdPath = config.getServletContext().getResource("/WEB-INF/test.xsd");
- } catch (MalformedURLException e) {
- throw new ServletException("Exception during servlet initilization!", e);
- }
- }
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- try {
- SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
- Schema schema = factory.newSchema(xsdPath);
- Validator validator = schema.newValidator();
- Source source = new StreamSource(new StringReader(xml));
- validator.validate(source);
- InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- DocumentBuilder builder = dbf.newDocumentBuilder();
- Document doc = builder.parse(stream);
- XPathFactory xpf = XPathFactory.newInstance();
- XPath xpath = xpf.newXPath();
- } catch (SAXException | ParserConfigurationException e) {
- throw new ServletException("Exception during testing!", e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment