Example usage for javax.xml.parsers SAXParserFactory setNamespaceAware

List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory setNamespaceAware.

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:org.opennms.core.test.xml.XmlTest.java

protected void validateXmlString(final String xml) throws Exception {
    if (getSchemaFile() == null) {
        LOG.warn("skipping validation, schema file not set");
        return;/*  w  w  w  .j  av  a  2s .co m*/
    }

    final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaFile = new File(getSchemaFile());
    LOG.debug("Validating using schema file: {}", schemaFile);
    final Schema schema = schemaFactory.newSchema(schemaFile);

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);

    assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());

    final Validator validator = schema.newValidator();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    final Source source = new StreamSource(inputStream);

    validator.validate(source);
}

From source file:org.openo.sdnhub.common.restconf.SerializeUtil.java

/**
 * Change the XML object to the class type.<br>
 *
 * @param xml is the object to be changed
 * @param clazz the class type that the XML is changed to
 * @return the object that the XML is changed to
 * @service ServiceException// w  w w.  j  av  a2s. co  m
 * @since SDNHUB 0.5
 */
public static <T> T fromXml(String xml, Class<T> clazz) throws ServiceException {
    String sError = "formXml failed.";
    if (StringUtils.isEmpty(xml)) {
        return null;
    }
    try {
        String trimXml = trimBodyStr(xml);
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StringReader reader = new StringReader(trimXml);
        SAXParserFactory sax = SAXParserFactory.newInstance();
        sax.setNamespaceAware(false);
        String feature = "http://apache.org/xml/features/disallow-doctype-decl";
        sax.setFeature(feature, true);
        feature = "http://xml.org/sax/features/external-general-entities";
        sax.setFeature(feature, false);
        feature = "http://xml.org/sax/features/external-parameter-entities";
        sax.setFeature(feature, false);
        XMLReader xmlReader = sax.newSAXParser().getXMLReader();
        Source source = new SAXSource(xmlReader, new InputSource(reader));
        return (T) unmarshaller.unmarshal(source);
    } catch (JAXBException | SAXException | ParserConfigurationException e) {
        LOGGER.error(sError, e);
        throw new ServiceException(sError, e);
    }
}

From source file:org.openstreetmap.josm.tools.Utils.java

/**
 * Returns a new secure SAX parser, supporting XML namespaces.
 * @return a new secure SAX parser, supporting XML namespaces
 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
 * @throws SAXException for SAX errors.//  w ww .ja  v  a  2 s .com
 * @since 8287
 */
public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    parserFactory.setNamespaceAware(true);
    return parserFactory.newSAXParser();
}

From source file:org.ops4j.gaderian.parse.XmlResourceProcessor.java

private SAXParser getSAXParser() throws ParserConfigurationException, SAXException, FactoryConfigurationError {
    if (_saxParser == null) {
        // Enable namespaces to ensure we parse usages of schemas correctly
        final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setNamespaceAware(true);
        _saxParser = parserFactory.newSAXParser();
    }// ww w.ja  v  a2s  .  c  o m
    return _saxParser;
}

From source file:org.ozsoft.xantippe.Indexer.java

Indexer() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    try {//from   w w  w .j  a va 2  s.c o  m
        parser = factory.newSAXParser();
    } catch (Exception e) {
        throw new RuntimeException("Error instantiating SAX parser: " + e.getMessage());
    }
}

From source file:org.plasma.sdo.helper.PlasmaXMLHelper.java

private void validateSAX(InputStream inputStream, String locationURI, XMLOptions options) throws IOException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);/*from   w  w  w.  j  a v  a 2  s .c  o m*/
    factory.setNamespaceAware(true);
    SAXParser parser;

    try {
        factory.setFeature("http://xml.org/sax/features/validation", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        parser = factory.newSAXParser();
        try {
            parser.setProperty(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI);
        } catch (SAXNotRecognizedException e) {
            log.warn("parses does not support JAXP 1.2");
        }
        if (locationURI != null) {
            parser.setProperty(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI);
        }
        XMLReader xmlReader = parser.getXMLReader();
        //xmlReader.setEntityResolver(new SchemaLoader());
        if (options.getErrorHandler() == null)
            xmlReader.setErrorHandler(new DefaultErrorHandler(options));
        else
            xmlReader.setErrorHandler(options.getErrorHandler());
        if (log.isDebugEnabled())
            log.debug("validating...");
        xmlReader.parse(new InputSource(inputStream));

    } catch (SAXNotRecognizedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXNotSupportedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (ParserConfigurationException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXException e) {
        throw new PlasmaDataObjectException(e);
    }
}

From source file:org.richfaces.cdk.rd.mojo.ResourceDependencyMojo.java

public ComponentsHandler findComponents(File webSourceDir, Map<String, Components> components,
        String[] includes, String[] excludes) throws Exception {

    if (includes == null) {
        includes = PluginUtils.DEFAULT_PROCESS_INCLUDES;
    }/* w w  w. j a  v  a  2 s.c o  m*/

    if (excludes == null) {
        excludes = new String[0];
    }

    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(webSourceDir);
    scanner.setIncludes(includes);
    scanner.setExcludes(excludes);
    scanner.addDefaultExcludes();
    getLog().info("search *.xhtml files");
    scanner.scan();

    String[] collectedFiles = scanner.getIncludedFiles();

    for (String collectedFile : collectedFiles) {
        getLog().info(collectedFile + " found");
    }

    ComponentsHandler handler = new ComponentsHandler(getLog());
    handler.setComponents(components);
    handler.setScriptIncludes(scriptIncludes);
    handler.setScriptExcludes(scriptExcludes);
    handler.setStyleIncludes(styleIncludes);
    handler.setStyleExcludes(styleExcludes);
    handler.setComponentIncludes(componentIncludes);
    handler.setComponentExcludes(componentExcludes);
    handler.setNamespaceIncludes(namespaceIncludes);
    handler.setNamespaceExcludes(namespaceExcludes);

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);

    Log log = getLog();
    for (String processFile : collectedFiles) {
        SAXParser saxParser = saxParserFactory.newSAXParser();
        File file = new File(webSourceDir, processFile);
        if (file.exists()) {

            if (log.isDebugEnabled()) {
                log.debug("start process file: " + file.getPath());
            }

            try {
                saxParser.parse(file, handler);
            } catch (Exception e) {
                if (log.isDebugEnabled()) {
                    log.error("Error process file: " + file.getPath() + "\n" + e.getMessage(), e);
                } else {
                    log.error("Error process file: " + file.getPath() + "\n" + e.getMessage());
                }
            }
        }
    }

    return handler;
}

From source file:org.roda.core.common.validation.ValidationUtils.java

public static ValidationReport isXMLValid(ContentPayload xmlPayload) {
    ValidationReport ret = new ValidationReport();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);/*from   w  w  w  .j ava 2  s.c o  m*/
    factory.setNamespaceAware(true);

    RodaErrorHandler errorHandler = new RodaErrorHandler();

    try (Reader reader = new InputStreamReader(new BOMInputStream(xmlPayload.createInputStream()))) {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource inputSource = new InputSource(reader);

        xmlReader.setErrorHandler(errorHandler);
        xmlReader.parse(inputSource);
        ret.setValid(errorHandler.getErrors().isEmpty());
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (SAXException e) {
        ret.setValid(false);
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (IOException e) {
        ret.setValid(false);
        ret.setMessage(e.getMessage());
    }
    return ret;
}

From source file:org.sakaibrary.osid.repository.xserver.AssetIterator.java

/**
 * This method parses the xml StringBuilder and creates Assets, Records
 * and Parts in the Repository with the given repositoryId.
 *
 * @param xml input xml in "sakaibrary" format
 * @param log the log being used by the Repository
 * @param repositoryId the Id of the Repository in which to create Assets,
 * Records and Parts./*from  w w  w . j av a  2  s.c  om*/
 *
 * @throws org.osid.repository.RepositoryException
 */
private void createAssets(java.io.ByteArrayInputStream xml, org.osid.shared.Id repositoryId)
        throws org.osid.repository.RepositoryException {
    this.repositoryId = repositoryId;
    recordStructureId = RecordStructure.getInstance().getId();
    textBuffer = new StringBuilder();

    // use a SAX parser
    javax.xml.parsers.SAXParserFactory factory;
    javax.xml.parsers.SAXParser saxParser;

    // set up the parser
    factory = javax.xml.parsers.SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    // start parsing
    try {
        saxParser = factory.newSAXParser();
        saxParser.parse(xml, this);
        xml.close();
    } catch (SAXParseException spe) {
        // Use the contained exception, if any
        Exception x = spe;

        if (spe.getException() != null) {
            x = spe.getException();
        }

        // Error generated by the parser
        LOG.warn("createAssets() parsing exception: " + spe.getMessage() + " - xml line " + spe.getLineNumber()
                + ", uri " + spe.getSystemId(), x);
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("createAssets() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("createAssets() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
        // I/O error
        LOG.warn("createAssets() IO exception", ioe);
    }
}

From source file:org.sakaibrary.xserver.XServer.java

/**
 * Creates a new XServer object ready to communicate with the
 * MetaLib X-server.  Reads searchProperties, sets up SAX Parser, and
 * sets up session management for this object.
 *///from ww  w  . java 2  s .co  m
public XServer(String guid) throws XServerException {
    this.guid = guid;

    // setup the SAX parser
    SAXParserFactory factory;
    factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    try {
        saxParser = factory.newSAXParser();
    } catch (SAXException sxe) {
        // Error generated by this application
        // (or a parser-initialization error)
        Exception x = sxe;

        if (sxe.getException() != null) {
            x = sxe.getException();
        }

        LOG.warn("XServer() SAX exception in trying to get a new SAXParser " + "from SAXParserFactory: "
                + sxe.getMessage(), x);
        throw new RuntimeException("XServer() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        LOG.warn("XServer() SAX parser cannot be built with specified options");
        throw new RuntimeException(
                "XServer() SAX parser cannot be built with " + "specified options: " + pce.getMessage(), pce);
    }

    // load session state
    msm = MetasearchSessionManager.getInstance();
    MetasearchSession metasearchSession = msm.getMetasearchSession(guid);

    if (metasearchSession == null) {
        // bad state management
        throw new RuntimeException("XServer() - cache MetasearchSession is " + "NULL :: guid is " + guid);
    }

    // get X-Server base URL
    xserverBaseUrl = metasearchSession.getBaseUrl();

    if (!metasearchSession.isLoggedIn()) {
        // need to login
        username = metasearchSession.getUsername();
        password = metasearchSession.getPassword();

        if (!loginURL(username, password)) {
            // authorization failed
            throw new XServerException("XServer.loginURL()", "authorization failed.");
        }

        // login success
        metasearchSession.setLoggedIn(true);
        metasearchSession.setSessionId(sessionId);
    }

    // get search properties
    org.osid.shared.Properties searchProperties = metasearchSession.getSearchProperties();

    try {
        searchSourceIds = (ArrayList) searchProperties.getProperty("searchSourceIds"); // empty TODO
        sortBy = (String) searchProperties.getProperty("sortBy");
        pageSize = (Integer) searchProperties.getProperty("pageSize");
        startRecord = (Integer) searchProperties.getProperty("startRecord");
    } catch (org.osid.shared.SharedException se) {
        LOG.warn("XServer() failed to get search properties - will assign " + "defaults", se);
    }

    // assign defaults if necessary
    // TODO assign the updated values to the session... searchProperties is read-only, need to add additional fields to MetasearchSession.
    if (sortBy == null) {
        sortBy = "rank";
    }

    if (pageSize == null) {
        pageSize = new Integer(10);
    }

    if (startRecord == null) {
        startRecord = new Integer(1);
    }

    // check args
    if (startRecord.intValue() <= 0) {
        LOG.warn("XServer() - startRecord must be set to 1 or higher.");
        startRecord = null;
        startRecord = new Integer(1);
    }

    // add/update this MetasearchSession in the cache
    msm.putMetasearchSession(guid, metasearchSession);
}