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:org.orbeon.oxf.xforms.XFormsUtils.java

private static void htmlStringToResult(String value, LocationData locationData, Result result) {
    try {/*  ww  w  .  ja v  a2 s . c  o m*/
        final XMLReader xmlReader = new org.ccil.cowan.tagsoup.Parser();
        xmlReader.setProperty(org.ccil.cowan.tagsoup.Parser.schemaProperty, TAGSOUP_HTML_SCHEMA);
        xmlReader.setFeature(org.ccil.cowan.tagsoup.Parser.ignoreBogonsFeature, true);
        final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
        identity.setResult(result);
        xmlReader.setContentHandler(identity);
        final InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(value));
        xmlReader.parse(inputSource);
    } catch (Exception e) {
        throw new ValidationException("Cannot parse value as text/html for value: '" + value + "'",
                locationData);
    }
    //         r.setFeature(Parser.CDATAElementsFeature, false);
    //         r.setFeature(Parser.namespacesFeature, false);
    //         r.setFeature(Parser.ignoreBogonsFeature, true);
    //         r.setFeature(Parser.bogonsEmptyFeature, false);
    //         r.setFeature(Parser.defaultAttributesFeature, false);
    //         r.setFeature(Parser.translateColonsFeature, true);
    //         r.setFeature(Parser.restartElementsFeature, false);
    //         r.setFeature(Parser.ignorableWhitespaceFeature, true);
    //         r.setProperty(Parser.scannerProperty, new PYXScanner());
    //          r.setProperty(Parser.lexicalHandlerProperty, h);
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java

/**
 * Configures the xml reader. Use this to set features or properties before the documents get parsed.
 *
 * @param handler the parser implementation that will handle the SAX-Callbacks.
 * @param reader  the xml reader that should be configured.
 *///w w w  . jav a 2 s  .  co m
protected void configureReader(final XMLReader reader, final RootXmlReadHandler handler) {
    try {
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler.getCommentHandler());
    } catch (final SAXException se) {
        // ignore ..
        logger.debug("Comments are not supported by this SAX implementation.");
    }

    try {
        reader.setFeature("http://xml.org/sax/features/xmlns-uris", true);
    } catch (final SAXException e) {
        // ignore
        handler.setXmlnsUrisNotAvailable(true);
    }
    try {
        // disable validation, as our parsers should handle that already. And we do not want to read
        // external DTDs that may not exist at all.
        reader.setFeature("http://xml.org/sax/features/validation", false);
        reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
    } catch (final SAXException e) {
        // ignore
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Disabling external validation failed. Parsing may or may not fail with a parse error later.");
        }
    }

    try {
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    } catch (final SAXException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("No Namespace features will be available. (Yes, this is serious)", e);
        } else if (logger.isWarnEnabled()) {
            logger.warn("No Namespace features will be available. (Yes, this is serious)");
        }
    }
}

From source file:org.portletbridge.portlet.PortletBridgePortlet.java

/**
 * @return//from  w  w  w. j av  a  2  s. c  o  m
 * @throws PortletException
 * @throws IllegalAccessException 
 * @throws  
 */
protected BridgeViewPortlet createViewPortlet(ResourceBundle resourceBundle, TemplateFactory templateFactory)
        throws PortletException {
    PortletConfig config = this.getPortletConfig();

    // get the memento session key
    String mementoSessionKey = config.getInitParameter("mementoSessionKey");
    if (mementoSessionKey == null) {
        throw new PortletException(resourceBundle.getString("error.mementoSessionKey"));
    }
    // get the servlet name
    String servletName = config.getInitParameter("servletName");
    if (servletName == null) {
        throw new PortletException(resourceBundle.getString("error.servletName"));
    }
    // get parserClassName
    String parserClassName = config.getInitParameter("parserClassName");
    if (parserClassName == null) {
        throw new PortletException(resourceBundle.getString("error.parserClassName"));
    }
    // get authenticatorClassName
    String authenticatorClassName = config.getInitParameter("authenticatorClassName");
    if (authenticatorClassName == null) {
        throw new PortletException(resourceBundle.getString("error.authenticatorClassName"));
    }
    BridgeAuthenticator bridgeAuthenticator = null;
    try {
        bridgeAuthenticator = PortletBridgeObjects.createBridgeAuthenticator(authenticatorClassName);
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn(
                    "Problem constructing BridgeAuthenticator instance, returning instance of DefaultBridgeAuthenticator",
                    e);
        }
        bridgeAuthenticator = new DefaultBridgeAuthenticator();
    }
    //        try {
    //            Class authenticatorClass = Class.forName(authenticatorClassName);
    //            bridgeAuthenticator = (BridgeAuthenticator) authenticatorClass.newInstance();
    //        } catch (ClassNotFoundException e) {
    //            log.warn(e, e);
    //            throw new PortletException(resourceBundle
    //                    .getString("error.authenticator"));
    //        } catch (InstantiationException e) {
    //            log.warn(e, e);
    //            throw new PortletException(resourceBundle
    //                    .getString("error.authenticator"));
    //        } catch (IllegalAccessException e) {
    //            log.warn(e, e);
    //            throw new PortletException(resourceBundle
    //                    .getString("error.authenticator"));
    //        }
    String initUrlFactoryClassName = config.getInitParameter("initUrlFactoryClassName");
    InitUrlFactory initUrlFactory = null;
    if (initUrlFactoryClassName != null && initUrlFactoryClassName.trim().length() > 0) {
        try {
            initUrlFactory = PortletBridgeObjects.createInitUrlFactory(initUrlFactoryClassName);
        } catch (Exception e) {
            if (log.isWarnEnabled()) {
                log.warn(
                        "Problem constructing InitUrlFactory instance, returning instance of DefaultInitUrlFactory",
                        e);
            }
            initUrlFactory = new DefaultInitUrlFactory();
        }
    }
    String idParamKey = config.getInitParameter("idParamKey");
    // setup parser
    BridgeTransformer transformer = null;
    try {
        String cssRegex = config.getInitParameter("cssRegex");
        String javascriptRegex = config.getInitParameter("jsRegex");
        XMLReader parser = XMLReaderFactory.createXMLReader(parserClassName);
        for (Enumeration names = config.getInitParameterNames(); names.hasMoreElements();) {
            String name = (String) names.nextElement();
            if (name.startsWith("parserFeature-")) {
                parser.setFeature(name.substring("parserFeature-".length()),
                        "true".equalsIgnoreCase(config.getInitParameter(name)));
            } else if (name.startsWith("parserProperty-")) {
                parser.setProperty(name.substring("parserProperty-".length()), config.getInitParameter(name));
            }
        }
        IdGenerator idGenerator = new DefaultIdGenerator();
        ContentRewriter javascriptRewriter = new RegexContentRewriter(javascriptRegex);
        ContentRewriter cssRewriter = new RegexContentRewriter(cssRegex);
        BridgeFunctionsFactory bridgeFunctionsFactory = new BridgeFunctionsFactory(idGenerator,
                javascriptRewriter, cssRewriter);
        transformer = new AltBridgeTransformer(bridgeFunctionsFactory, templateFactory, parser, servletName);
    } catch (SAXNotRecognizedException e) {
        throw new PortletException(e);
    } catch (SAXNotSupportedException e) {
        throw new PortletException(e);
    } catch (SAXException e) {
        throw new PortletException(e);
    }

    BridgeViewPortlet bridgeViewPortlet = new BridgeViewPortlet();

    bridgeViewPortlet.setInitUrlFactory(initUrlFactory);
    bridgeViewPortlet.setHttpClientTemplate(new DefaultHttpClientTemplate());
    bridgeViewPortlet.setTransformer(transformer);
    bridgeViewPortlet.setMementoSessionKey(mementoSessionKey);
    bridgeViewPortlet.setBridgeAuthenticator(bridgeAuthenticator);
    if (idParamKey != null) {
        bridgeViewPortlet.setIdParamKey(idParamKey);
    }
    return bridgeViewPortlet;
}

From source file:org.smartfrog.projects.alpine.xmlutils.CatalogHandler.java

/**
 * parser.setProperty( "http://apache.org/xml/properties/schema/external-schemaLocation",
 * "http: //domain.com/mynamespace mySchema.xsd");
 *
 * @param parser//from  w  w w.  j a va2s .  c  om
 */
public void setImportPaths(XMLReader parser) throws SAXNotSupportedException, SAXNotRecognizedException {
    StringBuffer buffer = new StringBuffer();
    for (String schema : mappings.keySet()) {
        String filename = mappings.get(schema);
        buffer.append(schema);
        buffer.append(' ');
        buffer.append(filename);
        buffer.append(' ');
    }
    String s = new String(buffer);
    parser.setProperty(XmlConstants.PROPERTY_XERCES_SCHEMA_LOCATION, s);
}

From source file:org.smartfrog.services.cddlm.cdl.CdlCatalog.java

/**
 * parser.setProperty( "http://apache.org/xml/properties/schema/external-schemaLocation",
 * "http: //domain.com/mynamespace mySchema.xsd");
 *
 * @param parser//from  ww w .  j a  v a  2 s  . com
 */
public void setImportPaths(XMLReader parser) throws SAXNotSupportedException, SAXNotRecognizedException {
    String[] map = CDDLM_MAPPINGS;
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < map.length; i += 2) {
        String schema = map[i];
        String filename = map[i + 1];
        buffer.append(schema);
        buffer.append(' ');
        buffer.append(filename);
        buffer.append(' ');
    }
    String s = new String(buffer);
    parser.setProperty(SCHEMA_LOCATION, s);
}

From source file:org.sonar.plugins.xml.parsers.DetectSchemaParser.java

/**
 * Find the Doctype (DTD or schema).//w  w  w.j a v a  2  s . c om
 */
public Doctype findDoctype(InputStream input) {
    Handler handler = new Handler();

    try {
        SAXParser parser = newSaxParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        parser.parse(input, handler);
        return handler.doctype;
    } catch (IOException e) {
        throw new SonarException(e);
    } catch (StopParserException e) {
        return handler.doctype;
    } catch (SAXException e) {
        throw new SonarException(e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.sonar.plugins.xml.parsers.LineCountParser.java

private void processCommentLines(File file) throws SAXException, IOException {
    SAXParser parser = newSaxParser(false);
    XMLReader xmlReader = parser.getXMLReader();
    commentHandler = new CommentHandler();
    xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler);
    parser.parse(FileUtils.openInputStream(file), commentHandler);
}

From source file:org.springframework.oxm.xmlbeans.XmlBeansMarshaller.java

@Override
protected final Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
        throws XmlMappingException, IOException {
    XmlSaxHandler saxHandler = XmlObject.Factory.newXmlSaxHandler(getXmlOptions());
    xmlReader.setContentHandler(saxHandler.getContentHandler());
    try {/*  w w w.j  a  v  a  2s .com*/
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", saxHandler.getLexicalHandler());
    } catch (SAXNotRecognizedException e) {
        // ignore
    } catch (SAXNotSupportedException e) {
        // ignore
    }
    try {
        xmlReader.parse(inputSource);
        XmlObject object = saxHandler.getObject();
        validate(object);
        return object;
    } catch (SAXException ex) {
        throw convertXmlBeansException(ex, false);
    } catch (XmlException ex) {
        throw convertXmlBeansException(ex, false);
    }
}

From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransformer.java

private String transform(List inputXSLs, String inputXML, Map inputParams,
        IXMLTransformerHelper transformerHelper) throws XMLTransformerException {

    String outputXML = null;/*from ww  w .  j a v  a2  s  . c om*/
    ByteArrayInputStream xmlInputStream = null;
    ByteArrayOutputStream xmlOutputStream = null;
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        setFactoryResolver(tFactory);

        if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) {
            // Cast the TransformerFactory to SAXTransformerFactory.
            SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);

            // Create a TransformerHandler for each stylesheet.
            ArrayList tHandlers = new ArrayList();
            TransformerHandler tHandler = null;

            // Create an XMLReader.
            XMLReader reader = new SAXParser();

            // transformer3 outputs SAX events to the serializer.
            if (outputProperties == null) {
                outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html");
            }
            Serializer serializer = SerializerFactory.getSerializer(outputProperties);
            String xslFile = null;
            for (int it = 0; it < inputXSLs.size(); it++) {
                Object source = inputXSLs.get(it);
                if (source instanceof StreamSource) {
                    tHandler = saxTFactory.newTransformerHandler((StreamSource) source);
                    if (xslFile == null)
                        xslFile = ((StreamSource) source).getSystemId();
                } else {
                    //tHandler = saxTFactory.newTransformerHandler(new StreamSource(getXSLFile((String) source)));
                    tHandler = saxTFactory
                            .newTransformerHandler(uriResolver.resolve((String) source + ".xsl", ""));
                    if (xslFile == null)
                        xslFile = (String) source;
                }
                Transformer transformer = tHandler.getTransformer();
                transformer.setOutputProperty("encoding", "UTF-8");
                transformer.setErrorListener(tFactory.getErrorListener());
                if (inputParams != null) {
                    Iterator paramIt = inputParams.entrySet().iterator();
                    while (paramIt.hasNext()) {
                        Map.Entry thisParam = (Map.Entry) paramIt.next();
                        transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue());
                    }
                }
                if (transformerHelper != null) {
                    transformer.setParameter(TRANSFORMER_HELPER, transformerHelper);
                }
                tHandlers.add(tHandler);
            }
            tHandler = null;
            for (int th = 0; th < tHandlers.size(); th++) {
                tHandler = (TransformerHandler) tHandlers.get(th);
                if (th == 0) {
                    reader.setContentHandler(tHandler);
                    reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler);
                } else {
                    ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler));
                }
            }
            // Parse the XML input document. The input ContentHandler and output ContentHandler
            // work in separate threads to optimize performance.
            InputSource xmlSource = null;
            xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8"));
            if (log.isTraceEnabled()) {
                log.trace("Input XML:\n" + inputXML);
            }
            xmlSource = new InputSource(xmlInputStream);
            xmlOutputStream = new ByteArrayOutputStream();
            serializer.setOutputStream(xmlOutputStream);
            ((TransformerHandler) tHandlers.get(tHandlers.size() - 1))
                    .setResult(new SAXResult(serializer.asContentHandler()));

            Date timer = new Date();
            reader.parse(xmlSource);
            Date timer2 = new Date();
            outputXML = xmlOutputStream.toString("UTF-8");
            if (log.isDebugEnabled()) {
                long diff = timer2.getTime() - timer.getTime();
                log.debug("Time to transform: " + diff + " mS XSL: " + xslFile);
                if (log.isTraceEnabled()) {
                    log.trace("Output XML:\n" + outputXML);
                }
            }
        }
    } catch (IOException ex) {
        throw new XMLTransformerException(ex);
    } catch (IllegalArgumentException ex) {
        throw new XMLTransformerException(ex);
    } catch (SAXException ex) {
        throw new XMLTransformerException(ex);
    } catch (TransformerConfigurationException ex) {
        throw new XMLTransformerException(ex);
    } catch (TransformerFactoryConfigurationError ex) {
        throw new XMLTransformerException(ex);
    } catch (TransformerException ex) {
        throw new XMLTransformerException(ex);
    } finally {
        try {
            if (xmlInputStream != null) {
                xmlInputStream.close();
                xmlInputStream = null;
            }
            if (xmlOutputStream != null) {
                xmlOutputStream.close();
                xmlOutputStream = null;
            }
        } catch (IOException ex) {
        }
    }
    return outputXML;
}

From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransletTransformer.java

public String transform(List inputXSLs, String inputXML, Map inputParams,
        IXMLTransformerHelper transformerHelper) throws XMLTransformerException {

    String outputXML = null;/*from   w w  w .  j  a  v a2 s .  com*/
    ByteArrayInputStream xmlInputStream = null;
    ByteArrayOutputStream xmlOutputStream = null;
    try {
        TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl();
        try {
            //tFactory.setAttribute("use-classpath", Boolean.TRUE);
            tFactory.setAttribute("auto-translet", Boolean.TRUE);
        } catch (IllegalArgumentException iae) {
            log.error("Error setting XSLTC specific attribute", iae);
            throw new XMLTransformerException(iae);
        }
        setFactoryResolver(tFactory);

        TransformerFactoryImpl traxFactory = (TransformerFactoryImpl) tFactory;

        // Create a TransformerHandler for each stylesheet.
        ArrayList tHandlers = new ArrayList();
        TransformerHandler tHandler = null;

        // Create a SAX XMLReader.
        XMLReader reader = new org.apache.xerces.parsers.SAXParser();

        // transformer3 outputs SAX events to the serializer.
        if (outputProperties == null) {
            outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html");
        }
        Serializer serializer = SerializerFactory.getSerializer(outputProperties);
        for (int it = 0; it < inputXSLs.size(); it++) {
            String xslTranslet = (String) inputXSLs.get(it);
            Source source = uriResolver.resolve(xslTranslet + ".xsl", "");

            String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/"))
                    .replaceAll("/", ".").replaceAll("-", "_");

            // Package name needs to be set for each TransformerHandler instance
            tFactory.setAttribute("package-name", tPkg);
            tHandler = traxFactory.newTransformerHandler(source);

            // Set parameters and output encoding on each handlers transformer
            Transformer transformer = tHandler.getTransformer();
            transformer.setOutputProperty("encoding", "UTF-8");
            transformer.setErrorListener(tFactory.getErrorListener());
            if (inputParams != null) {
                Iterator paramIt = inputParams.entrySet().iterator();
                while (paramIt.hasNext()) {
                    Map.Entry thisParam = (Map.Entry) paramIt.next();
                    transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue());
                }
            }
            if (transformerHelper != null) {
                transformer.setParameter(TRANSFORMER_HELPER, transformerHelper);
            }
            tHandlers.add(tHandler);
        }
        tHandler = null;
        // Link the handlers to each other and to the reader
        for (int th = 0; th < tHandlers.size(); th++) {
            tHandler = (TransformerHandler) tHandlers.get(th);
            if (th == 0) {
                reader.setContentHandler(tHandler);
                reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler);
            } else {
                ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler));
            }
        }
        // Parse the XML input document. The input ContentHandler and output ContentHandler
        // work in separate threads to optimize performance.
        InputSource xmlSource = null;
        xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8"));
        xmlSource = new InputSource(xmlInputStream);
        xmlOutputStream = new ByteArrayOutputStream();
        serializer.setOutputStream(xmlOutputStream);
        // Link the last handler to the serializer
        ((TransformerHandler) tHandlers.get(tHandlers.size() - 1))
                .setResult(new SAXResult(serializer.asContentHandler()));
        reader.parse(xmlSource);
        outputXML = xmlOutputStream.toString("UTF-8");
    } catch (Exception ex) {
        log.error("Error performing chained transformation: " + ex.getMessage(), ex);
        throw new XMLTransformerException(ex);
    } finally {
        try {
            if (xmlInputStream != null) {
                xmlInputStream.close();
                xmlInputStream = null;
            }
            if (xmlOutputStream != null) {
                xmlOutputStream.close();
                xmlOutputStream = null;
            }
        } catch (IOException ex) {
        }
    }
    return outputXML;
}