Example usage for javax.xml.transform.sax SAXSource SAXSource

List of usage examples for javax.xml.transform.sax SAXSource SAXSource

Introduction

In this page you can find the example usage for javax.xml.transform.sax SAXSource SAXSource.

Prototype

public SAXSource(XMLReader reader, InputSource inputSource) 

Source Link

Document

Create a SAXSource, using an org.xml.sax.XMLReader and a SAX InputSource.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    XMLReader xmlReader = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
        String namespace = "http://www.java2s.com/schemas.xsd";
        String pref = "ns0:";

        @Override//from w w w .java2  s  . com
        public void startElement(String uri, String localName, String qName, Attributes atts)
                throws SAXException {
            super.startElement(namespace, localName, pref + qName, atts);
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(namespace, localName, pref + qName);
        }
    };
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    StringWriter s = new StringWriter();
    t.transform(new SAXSource(xmlReader, new InputSource("test.xml")), new StreamResult(s));
    System.out.println(s);
}

From source file:com.semsaas.jsonxml.tools.JsonXpath.java

public static void main(String[] args) {
    /*/*from   ww  w. ja  va 2s .  c  o  m*/
     * Process options
     */
    LinkedList<String> files = new LinkedList<String>();
    LinkedList<String> expr = new LinkedList<String>();
    boolean help = false;
    String activeOption = null;
    String error = null;

    for (int i = 0; i < args.length && error == null && !help; i++) {
        if (activeOption != null) {
            if (activeOption.equals("-e")) {
                expr.push(args[i]);
            } else if (activeOption.equals("-h")) {
                help = true;
            } else {
                error = "Unknown option " + activeOption;
            }
            activeOption = null;
        } else {
            if (args[i].startsWith("-")) {
                activeOption = args[i];
            } else {
                files.push(args[i]);
            }
        }
    }

    if (error != null) {
        System.err.println(error);
        showHelp();
    } else if (help) {
        showHelp();
    } else {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            for (String f : files) {
                System.out.println("*** " + f + " ***");
                try {
                    // Create a JSON XML reader
                    XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader");

                    // Prepare a reader with the JSON file as input
                    InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f));
                    SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader));

                    // Prepare a DOMResult which will hold the DOM of the xjson
                    DOMResult domResult = new DOMResult();

                    // Run SAX processing through a transformer
                    // (This could be done more simply, but we have here the opportunity to pass our xjson through
                    // an XSLT and get a legacy XML output ;) )
                    transformer.transform(saxSource, domResult);
                    Node dom = domResult.getNode();

                    XPathFactory xpathFactory = XPathFactory.newInstance();
                    for (String x : expr) {
                        try {
                            XPath xpath = xpathFactory.newXPath();
                            xpath.setNamespaceContext(new NamespaceContext() {
                                public Iterator getPrefixes(String namespaceURI) {
                                    return null;
                                }

                                public String getPrefix(String namespaceURI) {
                                    return null;
                                }

                                public String getNamespaceURI(String prefix) {
                                    if (prefix == null) {
                                        return XJSON.XMLNS;
                                    } else if ("j".equals(prefix)) {
                                        return XJSON.XMLNS;
                                    } else {
                                        return null;
                                    }
                                }
                            });
                            NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET);
                            System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x
                                    + "' in file '" + f + "'");
                            for (int i = 0; i < nl.getLength(); i++) {
                                System.out.println(" +(" + i + ")+ ");
                                XMLJsonGenerator handler = new XMLJsonGenerator();
                                StringWriter buffer = new StringWriter();
                                handler.setOutputWriter(buffer);

                                SAXResult result = new SAXResult(handler);
                                transformer.transform(new DOMSource(nl.item(i)), result);

                                System.out.println(buffer.toString());
                            }
                        } catch (XPathExpressionException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        } catch (TransformerException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.err.println("File '" + f + "' was not found");
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T readXMLFromString(Class<?> class1, String content)
        throws JAXBException, FileNotFoundException, SAXException, ParserConfigurationException {
    JAXBContext context = JAXBContext.newInstance(class1);
    Unmarshaller um = context.createUnmarshaller();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    spf.setFeature("http://xml.org/sax/features/validation", false);

    XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader();
    try (StringReader reader = new StringReader(content)) {
        SAXSource source = new SAXSource(xr, new InputSource(reader));

        T obj = (T) um.unmarshal(source);
        return obj;
    }//from  w  w  w  .  java  2  s  .c o  m
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T readXML(Class<?> class1, File file)
        throws JAXBException, IOException, SAXException, ParserConfigurationException {
    JAXBContext context = JAXBContext.newInstance(class1);
    Unmarshaller um = context.createUnmarshaller();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    spf.setFeature("http://xml.org/sax/features/validation", false);

    XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader();
    try (FileReader reader = new FileReader(file)) {
        SAXSource source = new SAXSource(xr, new InputSource(reader));

        T obj = (T) um.unmarshal(source);
        return obj;
    }//from  w w  w .  j a v a2 s  .  com
}

From source file:Main.java

/**
 * Helper method to unmarshall a xml doc
 * @see http://docs.oracle.com/javase/tutorial/jaxb/intro/basic.html
 * http://jaxb.java.net/nonav/2.2.6/docs/ch03.html#unmarshalling
 * this uses <T> JAXBElement<T> unmarshal(Source source,
                    Class<T> declaredType)
                  throws JAXBException//from w w w  . j  a va2s  . com
 * 
 */
/*   public static <T> T unmarshall(Class<T> docClass, InputStream inputStream) throws JAXBException{
 String packageName = docClass.getPackage().getName();
 JAXBContext jc = JAXBContext.newInstance( packageName );
 Unmarshaller u = jc.createUnmarshaller();
 JAXBElement<T> root = u.unmarshal(new StreamSource(inputStream),docClass);
 return root.getValue();
 }*/

public static <T> T unmarshall(Class<T> docClass, InputStream inputStream)
        throws JAXBException, ParserConfigurationException, SAXException {
    String packageName = docClass.getPackage().getName();
    JAXBContext jc = JAXBContext.newInstance(packageName);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://apache.org/xml/features/validation/schema", false);
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    InputSource inputSource = new InputSource(inputStream);
    SAXSource source = new SAXSource(xmlReader, inputSource);

    Unmarshaller u = jc.createUnmarshaller();
    JAXBElement<T> root = u.unmarshal(source, docClass);
    return root.getValue();
}

From source file:Main.java

/**
 * Returns a {@link SAXSource} for the provided {@link InputStream} that explicitly forfeit external DTD validation
 *
 * @param in the {@link InputStream} for the {@link SAXSource}
 * @return a {@link SAXSource} for the provided {@link InputStream} that explicitly forfeit external DTD validation
 * @throws SAXException                 if a SAX error occurs
 * @throws ParserConfigurationException if a configuration error occurs
 *///from  w  w  w  .  j  a  va 2  s  .c o  m
public static Source toNonValidatingSAXSource(InputStream in)
        throws SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    InputSource inputSource = new InputSource(in);
    return new SAXSource(xmlReader, inputSource);
}

From source file:Main.java

/**
 * Filters an XML document./*from w  w w .j a  v a2s.  c  om*/
 * 
 * @param source the input source for the XML document
 * @param filter the filter
 * 
 * @return an input source for the resulting document
 * 
 * @throws Exception
 */
public static InputSource filterXml(InputSource source, XMLFilter filter) throws Exception {
    // Create filter, which uses a "real" XMLReader but also removes the
    // attributes
    XMLReader reader = XMLReaderFactory.createXMLReader();
    filter.setParent(reader);

    // Create a Transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();

    // Transform the source tree, applying the filter, and store the result
    // tree in a character array
    CharArrayWriter writer = new CharArrayWriter();
    t.transform(new SAXSource(filter, source), new StreamResult(writer));

    // Return a new InputSource using the result tree
    return new InputSource(new CharArrayReader(writer.toCharArray()));
}

From source file:edu.wisc.my.portlets.dmp.web.MenuXsltView.java

/**
 * @see org.springframework.web.servlet.view.xslt.AbstractXsltView#createXsltSource(java.util.Map, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from   ww w.jav  a 2  s.  c  o m*/
@SuppressWarnings("unchecked")
@Override
protected Source createXsltSource(Map model, String root, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //TODO deal with 'root' argument (can I use it as the menu name?)

    final String menuName = (String) model.get(ViewMenuController.MODEL_MENU_NAME);
    if (menuName == null) {
        throw new IllegalArgumentException("model Map must contain a menu name String with a key='"
                + ViewMenuController.MODEL_MENU_NAME + "'");
    }

    final MenuItem rootItem = (MenuItem) model.get(ViewMenuController.MODEL_ROOT_ITEM);
    if (rootItem == null) {
        throw new IllegalArgumentException("model Map must contain a root MenuItem with a key='"
                + ViewMenuController.MODEL_ROOT_ITEM + "'");
    }

    if (this.logger.isInfoEnabled()) {
        this.logger.info("Creating Xslt Source for menuName='" + menuName + "', menu='" + rootItem + "'");
    }

    final XMLReader reader = new MenuItemXmlReader();
    final MenuItemInputSource inputSource = new MenuItemInputSource(menuName, rootItem);
    final Source source = new SAXSource(reader, inputSource);
    return source;
}

From source file:com.wudaosoft.net.httpclient.SAXSourceResponseHandler.java

private SAXSource readSAXSource(InputStream body) throws IOException {
    try {//w w w  . j a v a 2  s .com
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        reader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
        return new SAXSource(reader, new InputSource(body));
    } catch (SAXException ex) {
        throw new ClientProtocolException("Could not parse document: " + ex.getMessage(), ex);
    }
}

From source file:net.sourceforge.vulcan.spring.SpringProjectDomBuilder.java

@Override
protected Transformer createTransformer(String format) throws NoSuchTransformFormatException {
    if (!transformResources.containsKey(format)) {
        throw new NoSuchTransformFormatException();
    }/*from   w w  w.  ja  va  2  s. c  o m*/

    final Resource resource = applicationContext.getResource(transformResources.get(format));

    try {
        final SAXSource source = new SAXSource(XMLReaderFactory.createXMLReader(),
                new InputSource(resource.getInputStream()));

        try {
            // Try to tell the xsl where it is for the sake of xsl:include
            source.setSystemId(resource.getFile().getAbsolutePath());
        } catch (FileNotFoundException ignore) {
            // Not all resources are backed by files.
        }

        return transformerFactory.newTransformer(source);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

}