Example usage for org.xml.sax XMLReader setProperty

List of usage examples for org.xml.sax XMLReader setProperty

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setProperty.

Prototype

public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Set the value of a property.

Usage

From source file:eionet.gdem.validation.ValidationService.java

/**
 * Set the schemaLocation property. The value is "namespace schemaLocation".
 *
 * @param reader XMLReader./*from w  w  w .  j  a va2  s .  c o m*/
 * @param namespace XML Schema default namespace.
 * @param schema XML Schema URL.
 * @throws SAXNotRecognizedException
 * @throws SAXNotSupportedException
 */
private void setNamespaceSchemaProperty(XMLReader reader, String namespace, String schema)
        throws SAXNotRecognizedException, SAXNotSupportedException {
    setLocalSchemaUrl(schema);
    reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            namespace + " " + getValidatedSchema());
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and DOM nodes out.
 *//*from   ww  w  .j  av a2 s . com*/
public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Make sure the transformer factory we obtained supports both
    // DOM and SAX.
    if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) {
        // We can now safely cast to a SAXTransformerFactory.
        SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

        // Create an Document node as the root for the output.
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();

        // Create a ContentHandler that can liston to SAX events 
        // and transform the output to DOM nodes.
        TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID));
        handler.setResult(new DOMResult(outNode));

        // Create a reader and set it's ContentHandler to be the 
        // transformer.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Send the SAX events from the parser to the transformer,
        // and thus to the DOM tree.
        reader.parse(sourceID);

        // Serialize the node for diagnosis.
        exampleSerializeNode(outNode);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and SAX events out.
 *//*from  ww w  .  ja  v a  2s  .c  o m*/
public static void exampleContentHandlerToContentHandler(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // If so, we can safely cast.
        SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // A TransformerHandler is a ContentHandler that will listen for 
        // SAX events, and transform them to the result.
        TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID));

        // Set the result handling to be a serialization to System.out.
        Result result = new SAXResult(new ExampleContentHandler());
        handler.setResult(result);

        // Create a reader, and set it's content handler to be the TransformerHandler.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);

        // It's a good idea for the parser to send lexical events.
        // The TransformerHandler is also a LexicalHandler.
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Parse the source XML, and send the parse events to the TransformerHandler.
        reader.parse(sourceID);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:com.mirth.connect.model.converters.NCPDPSerializer.java

@Override
public String fromXML(String source) throws SerializerException {
    /*/*w ww .  j a v a2  s . co m*/
     * Need to determine the version by looking at the raw message.
     * The transaction header will contain the version ("51" for 5.1 and
     * "D0" for D.0)
     */
    String version = "D0";

    if (source.indexOf("D0") == -1) {
        version = "51";
    } else if (source.indexOf("51") == -1) {
        version = "D0";
    } else if (source.indexOf("51") < source.indexOf("D0")) {
        version = "51";
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        NCPDPXMLHandler handler = new NCPDPXMLHandler(segmentDelimeter, groupDelimeter, fieldDelimeter,
                version);
        reader.setContentHandler(handler);

        if (useStrictValidation) {
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    "ncpdp" + version + ".xsd");
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "/ncpdp" + version + ".xsd");
        }

        /*
         * Parse, but first replace all spaces between brackets. This fixes
         * pretty-printed XML we might receive
         */
        reader.parse(new InputSource(new StringReader(source.replaceAll(">\\s+<", "><"))));
        return handler.getOutput().toString();
    } catch (Exception e) {
        throw new SerializerException("Error converting XML to NCPDP message.", e);
    }
}

From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisher.java

/**
 * Publishes all the menus in the XML specified by the URL.
 * /*from   w ww.ja  v a2 s .  c  om*/
 * @param xmlSourceUrl URL to the menu XML.
 */
public void publishMenus(URL xmlSourceUrl) {
    LOG.info("Publishing menus from: " + xmlSourceUrl);

    try {
        //The XMLReader will read in the XML document
        final XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");

        try {
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);

            final URL menuSchema = this.getClass().getResource("/menu.xsd");
            if (menuSchema == null) {
                throw new MissingResourceException("Could not load menu schema. '/menu.xsd'",
                        this.getClass().getName(), "/menu.xsd");
            }

            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    menuSchema.toString());
        } catch (SAXNotRecognizedException snre) {
            LOG.warn("Could not enable XSD validation", snre);
        } catch (SAXNotSupportedException xnse) {
            LOG.warn("Could not enable XSD validation", xnse);
        }

        final MenuItemGeneratingHandler handler = new MenuItemGeneratingHandler();

        reader.setContentHandler(handler);
        reader.parse(new InputSource(xmlSourceUrl.openStream()));

        final Map menus = handler.getMenus();

        final BeanFactory factory = this.getFactory();
        final MenuDao dao = (MenuDao) factory.getBean("menuDao", MenuDao.class);

        for (final Iterator nameItr = menus.entrySet().iterator(); nameItr.hasNext();) {
            final Map.Entry entry = (Map.Entry) nameItr.next();
            final String menuName = (String) entry.getKey();
            final MenuItem rootItem = (MenuItem) entry.getValue();

            LOG.info("Publishing menu='" + menuName + "' item='" + rootItem + "'");
            dao.storeMenu(menuName, rootItem);
        }

        LOG.info("Published menus from: " + xmlSourceUrl);
    } catch (IOException ioe) {
        LOG.error("Error publishing menus", ioe);
    } catch (SAXException saxe) {
        LOG.error("Error publishing menus", saxe);
    }
}

From source file:com.mirth.connect.plugins.datatypes.ncpdp.NCPDPSerializer.java

@Override
public String fromXML(String source) throws MessageSerializerException {
    /*/*  www .  j a v a  2s.co m*/
     * Need to determine the version by looking at the raw message.
     * The transaction header will contain the version ("51" for 5.1 and
     * "D0" for D.0)
     */
    String version = "D0";

    if (source.indexOf("D0") == -1) {
        version = "51";
    } else if (source.indexOf("51") == -1) {
        version = "D0";
    } else if (source.indexOf("51") < source.indexOf("D0")) {
        version = "51";
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        NCPDPXMLHandler handler = new NCPDPXMLHandler(deserializationSegmentDelimiter,
                deserializationGroupDelimiter, deserializationFieldDelimiter, version);
        reader.setContentHandler(handler);

        if (deserializationProperties.isUseStrictValidation()) {
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    "ncpdp" + version + ".xsd");
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "/ncpdp" + version + ".xsd");
        }

        /*
         * Parse, but first replace all spaces between brackets. This fixes
         * pretty-printed XML we might receive
         */
        reader.parse(new InputSource(new StringReader(prettyPattern.matcher(source).replaceAll("><"))));
        return handler.getOutput().toString();
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting XML to NCPDP message.", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to NCPDP", e));
    }
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

public void parse() throws ReportedException {
    firstPassReadFile();//from  w w w  .  java  2 s  . com
    offsetMap = new OffsetMap(rawXMLText.length());

    // Setup special tag handling to cover behavior for
    // add, del, note and pb tags
    setupCustomTagHandling();

    try {
        if (file.getName().endsWith("xml")) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            parser = factory.newSAXParser();

            XMLReader xmlReader = parser.getXMLReader();
            xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", this);

            // ignore external DTDs
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

            parser.parse(new InputSource(new StringReader(rawXMLText)), this);
            if (getDocumentType() == DocumentType.UNKNOWN) {
                // If we made it here and we don't know what the document type is,
                // it's just an XML document
                setDocumentType(DocumentType.XML);
            }
            // Uncomment these lines for some verbose debugging of the XML parsing
            // and the resulting processed output.
            //                getRootNode().debugPrint();
            //                try {
            //                    printDebuggingInfo();
            //                } catch (ReportedException ex) {
            //Logger.getLogger(JuxtaXMLParser.class.getName()).log(Level.SEVERE, null, ex);
            //                }
        } else {
            processAsPlaintext();
        }
    } catch (ParserConfigurationException ex) {
        throw new ReportedException(ex, "Problem with our parser configuration.");
    } catch (SAXParseException ex) {
        throw new ReportedException(ex, "XML Parsing Error at column " + ex.getColumnNumber() + ", line "
                + ex.getLineNumber() + " :\n" + ex.getLocalizedMessage());
    } catch (SAXException ex) {
        throw new ReportedException(ex, "SAX Exception: " + ex.getLocalizedMessage());
    } catch (IOException ex) {
        throw new ReportedException(ex, ex.getLocalizedMessage());
    }
}

From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java

private XRoadSoapHandler handleSoap(Writer writer, InputStream inputStream) throws Exception {
    try (BufferedWriter out = new BufferedWriter(writer)) {
        XRoadSoapHandler handler = new XRoadSoapHandler(out);
        SAXParser saxParser = PARSER_FACTORY.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);
        // ensure both builtin entities and character entities are reported to the parser
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
        xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);

        saxParser.parse(inputStream, handler);
        return handler;
    } catch (SAXException ex) {
        throw new SOAPException(ex);
    }/*from   w  w  w.ja  v  a 2  s  . c o  m*/
}

From source file:net.sf.joost.trax.TrAXFilter.java

/**
 * Parses the <code>InputSource</code>
 * @param input A <code>InputSource</code> object.
 * @throws SAXException/*from  www.ja  v a 2 s . c  o  m*/
 * @throws IOException
 */
public void parse(InputSource input) throws SAXException, IOException {

    Transformer transformer = null;
    if (DEBUG) {
        if (log.isDebugEnabled())
            log.debug("parsing InputSource " + input.getSystemId());
    }

    try {
        // get a new Transformer
        transformer = this.templates.newTransformer();
        if (transformer instanceof TransformerImpl) {
            this.processor = ((TransformerImpl) transformer).getStxProcessor();
        } else {
            String msg = "An error is occured, because the given transformer is "
                    + "not an instance of TransformerImpl";
            if (log != null)
                log.fatal(msg);
            else
                System.err.println("Fatal error - " + msg);

        }
        XMLReader parent = this.getParent();

        if (parent == null) {
            parent = XMLReaderFactory.createXMLReader();
            setParent(parent);
        }
        ContentHandler handler = this.getContentHandler();

        if (handler == null) {
            handler = parent.getContentHandler();
        }
        if (handler == null) {
            throw new SAXException("no ContentHandler registered");
        }
        //init StxEmitter
        StxEmitter out = null;

        //SAX specific Implementation
        out = new SAXEmitter(handler);

        if (this.processor != null) {
            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);
        } else {
            throw new SAXException("Joost-Processor is not correct configured.");
        }
        if (parent == null) {
            throw new SAXException("No parent for filter");
        }
        parent.setContentHandler(this.processor);
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this.processor);
        parent.setEntityResolver(this);
        parent.setDTDHandler(this);
        parent.setErrorHandler(this);
        parent.parse(input);

    } catch (TransformerConfigurationException tE) {
        try {
            configErrListener.fatalError(tE);
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (SAXException sE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(sE.getMessage(), sE));
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (IOException iE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(iE.getMessage(), iE));
        } catch (TransformerConfigurationException innerE) {
            throw new IOException(innerE.getMessage());
        }
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

protected XMLReader createTagSoupParser() throws Exception {
    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, false);
    reader.setFeature(Parser.namespacePrefixesFeature, false);
    reader.setProperty(Parser.schemaProperty, new org.ccil.cowan.tagsoup.HTMLSchema() {
        {/*from w  ww  .  j a  va2  s  .c  o  m*/
            //problem with nested lists that the confluence {toc} macro creates
            elementType("ul", M_LI, M_BLOCK | M_LI, 0);
        }
    });

    return reader;
}