Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:org.easyxml.parser.EasySAXParser.java

/**
 * /*from   w  ww.  jav a  2s .c  o m*/
 * Parse XML as an InputSource. If external schema is referred, then it
 * would fail to locate the DTD file.
 * 
 * @param is
 *            - InputSource to be parsed.
 * 
 * @return org.easyxml.xml.Document instance if it is parsed successfully,
 *         otherwise null.
 */
public static Document parse(InputSource is) {

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {
        saxParserFactory.setValidating(true);
        saxParserFactory.setFeature("http://apache.org/xml/features/validation/schema", true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        EasySAXParser handler = new EasySAXParser();
        saxParser.parse(is, handler);
        return handler.getDocument();
    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.easyxml.parser.EasySAXParser.java

/**
 * /*ww w  .  ja v a 2 s  .  c  om*/
 * Parse XML file specified by the url. If external schema is referred, then
 * it must be located at the same directory of the XML.
 * 
 * @param url
 *            - URL of the XML file to be parsed.
 * 
 * @return org.easyxml.xml.Document instance if it is parsed successfully,
 *         otherwise null.
 */
public static Document parse(URL url) {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {
        SAXParser saxParser = saxParserFactory.newSAXParser();
        EasySAXParser handler = new EasySAXParser();
        String path = url.getFile();
        saxParser.parse(path, handler);

        return handler.getDocument();
    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.ebayopensource.turmeric.tools.library.utils.TypeLibraryUtilities.java

public static AdditionalXSDInformation parseTheXSDFile(String xsdSrcPath) {

    final AdditionalXSDInformation additionalXSDInformation = new AdditionalXSDInformation();

    class ParseClass extends DefaultHandler {

        @Override//from ww  w.  ja v  a 2 s  .c  o m
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            String elementName = ("".equals(localName)) ? qName : localName;

            if (elementName.startsWith("schema") || elementName.contains(":schema")) {
                String tns = attributes.getValue("targetNamespace");
                String version = attributes.getValue("version");
                additionalXSDInformation.setTargetNamespace(tns);
                additionalXSDInformation.setVersion(version);
            }

            if (elementName.startsWith("simpleType") || elementName.contains(":simpleType")) {
                additionalXSDInformation.setSimpleType(true);
                String typeName = attributes.getValue("name");
                additionalXSDInformation.setTypeName(typeName);
                additionalXSDInformation.getTypeNamesList().add(typeName);
            }

            if (elementName.startsWith("complexType") || elementName.contains(":complexType")) {
                additionalXSDInformation.setSimpleType(false);
                String typeName = attributes.getValue("name");
                additionalXSDInformation.setTypeName(typeName);
                additionalXSDInformation.getTypeNamesList().add(typeName);
            }

        }

    }

    File xsdFile = new File(xsdSrcPath);
    if (!xsdFile.exists()) {
        //need to do additional check for backward compatibility
        if (!checkIfXsdExistsInOlderPath(xsdSrcPath, additionalXSDInformation)) {
            logger.log(Level.INFO, "Xsd file not found in " + xsdSrcPath);
            additionalXSDInformation.setDoesFileExist(false);
            logger.log(Level.INFO, "Setting AdditionalXsdInformation setDoesFileExist to false");
            return additionalXSDInformation;
        }
    } else {
        additionalXSDInformation.setDoesFileExist(true);
    }

    DefaultHandler defaultHandler = new ParseClass();
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    if (additionalXSDInformation.isXsdPathChanged()) {
        String newXsdLocation = getOlderXsdSrcPath(xsdSrcPath);
        xsdFile = new File(newXsdLocation);
    }

    try {
        SAXParser saxParser = parserFactory.newSAXParser();
        saxParser.parse(xsdFile, defaultHandler);
    } catch (ParserConfigurationException e) {
        getLogger().log(Level.WARNING,
                "ParserConfigurationException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    } catch (SAXException e) {
        getLogger().log(Level.WARNING,
                "SAXException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    } catch (IOException e) {
        getLogger().log(Level.WARNING,
                "IOException while parsing XSD file " + xsdSrcPath + "\n" + e.getMessage());
    }

    return additionalXSDInformation;

}

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file./* w  ww  .  j a  v  a2 s  . c  o m*/
 *
 * @param project The project name.
 * @param filename The file path to the xml file.
 * @param schema True to use schema validation relying on the
 * xsi:schemaLocation attribute of the document.
 * @param handler The content handler to use while parsing the file.
 * @return A possibly empty list of errors.
 */
public static List<Error> validateXml(String project, String filename, boolean schema, DefaultHandler handler)
        throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    if (schema) {
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    }

    SAXParser parser = factory.newSAXParser();

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(handler, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclim.plugin.core.util.XmlUtils.java

/**
 * Validate the supplied xml file against the specified xsd.
 *
 * @param project The project name./*  w ww.  ja  v a  2  s  . c om*/
 * @param filename The file path to the xml file.
 * @param schema The file path to the xsd.
 * @return A possibly empty array of errors.
 */
public static List<Error> validateXml(String project, String filename, String schema) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setFeature("http://apache.org/xml/features/validation/schema", true);
    factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    SAXParser parser = factory.newSAXParser();
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    if (!schema.startsWith("file:")) {
        schema = "file://" + schema;
    }
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);
    parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            schema.replace('\\', '/'));

    filename = ProjectUtils.getFilePath(project, filename);
    filename = filename.replace('\\', '/');

    ErrorAggregator errorHandler = new ErrorAggregator(filename);
    EntityResolver entityResolver = new EntityResolver(FileUtils.getFullPath(filename));
    try {
        parser.parse(new File(filename), getHandler(null, errorHandler, entityResolver));
    } catch (SAXParseException spe) {
        ArrayList<Error> errors = new ArrayList<Error>();
        errors.add(new Error(spe.getMessage(), filename, spe.getLineNumber(), spe.getColumnNumber(), false));
        return errors;
    }

    return errorHandler.getErrors();
}

From source file:org.eclipse.emf.teneo.annotations.xml.XmlPersistenceMapper.java

/**
 * Applies the XML persistence mapping to a PAnnotatedModel.
 * // ww w . j  a va 2  s  . c  o m
 * @throws IllegalStateException
 *             if the XML mapping was not configured.
 * @throws RuntimeException
 *             If there was an error reading or parsing the XML file.
 */
public void applyPersistenceMapping(PAnnotatedModel pAnnotatedModel) {
    if (xmlMapping == null) {
        throw new IllegalStateException("XML mapping not configured.");
    }

    SAXParser saxParser;
    try {
        final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setValidating(true);

        saxParser = saxParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (SAXException e) {
        throw new ParseXMLAnnotationsException(e);
    }

    try {
        try {
            saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    this.getClass().getResourceAsStream("persistence-mapping.xsd"));
        } catch (SAXNotRecognizedException s) {
            log.warn("Properties schemaSource and/or schemaLanguage are not supported, setvalidating=false. "
                    + "Probably running 1.4 with an old crimson sax parser. Ignoring this and continuing with "
                    + "a non-validating and name-space-aware sax parser");
            final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            saxParserFactory.setNamespaceAware(true);
            saxParserFactory.setValidating(false);
            saxParser = saxParserFactory.newSAXParser();
        }

        final XmlPersistenceContentHandler xmlContentHandler = extensionManager
                .getExtension(XmlPersistenceContentHandler.class);
        xmlContentHandler.setPAnnotatedModel(pAnnotatedModel);
        xmlContentHandler.setPrefix(getPrefix());
        xmlContentHandler.setSchema(this.getClass().getResourceAsStream("persistence-mapping.xsd"));
        saxParser.parse(xmlMapping, xmlContentHandler);
    } catch (SAXException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (IOException e) {
        throw new ParseXMLAnnotationsException(e);
    } catch (ParserConfigurationException e) {
        throw new ParseXMLAnnotationsException(e);
    } finally {
        try {
            xmlMapping.close();
        } catch (IOException e) {
            // ignoring io exception
        }
    }
}

From source file:org.eclipse.wst.ws.internal.parser.wsil.WebServicesParser.java

private void parseURL(int parseOption) throws MalformedURLException, IOException, ParserConfigurationException,
        SAXException, WWWAuthenticationException {
    WebServiceEntity wsEntity = new WebServiceEntity();

    // This variable makes this object a little more thread safe than it was
    // before, although this object is not completely thread safe.  The scenario
    // that we are trying to avoid is where one call to this method gets blocked
    // at the getInputStreamAsByteArray call.  Then a second call to the method
    // is made that changes the uri_ global variable.  When the first call
    // completes it would use uri_ value from the second invocation instead
    // of the value from the first.  Storing the uri_ into this variable helps 
    // avoid this bad scenario.
    String theUri = uri_;/* w w  w .  jav a  2  s .c om*/

    wsEntity.setURI(theUri);
    byte[] b = getInputStreamAsByteArray(theUri);
    wsEntity.setBytes(b);
    setHTTPSettings(wsEntity);
    uriToEntityTable_.put(theUri, wsEntity);
    // parse uri_ as a HTML document
    HTMLHeadHandler headHandler = new HTMLHeadHandler(theUri);
    byte[] head = headHandler.harvestHeadTags(b);
    String byteEncoding = headHandler.getByteEncoding();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(head);
        InputStreamReader isr = new InputStreamReader(bais, byteEncoding);
        InputSource is = new InputSource(isr);
        parser.parse(is, headHandler);
    } catch (Exception t) {
    }
    String[] wsilURIs = headHandler.getWsils();
    String[] discoURIs = headHandler.getDiscos();
    // true if uri_ is a HTML document
    if (wsilURIs.length > 0 || discoURIs.length > 0) {
        wsEntity.setType(WebServiceEntity.TYPE_HTML);
        for (int i = 0; i < wsilURIs.length; i++) {
            String absoluteURI = convertToAbsoluteURI(theUri, wsilURIs[i]);
            WebServiceEntity wsilEntity = new WebServiceEntity();
            wsilEntity.setType(WebServiceEntity.TYPE_WSIL);
            wsilEntity.setURI(absoluteURI);
            associate(wsEntity, wsilEntity);
            uriToEntityTable_.put(absoluteURI, wsilEntity);
            if ((parseOption | PARSE_WSIL) == parseOption) {
                try {
                    parseWSIL(absoluteURI, parseOption, byteEncoding);
                } catch (Exception t) {
                }
            }
        }
        for (int i = 0; i < discoURIs.length; i++) {
            WebServiceEntity discoEntity = new WebServiceEntity();
            discoEntity.setType(WebServiceEntity.TYPE_DISCO);
            discoEntity.setURI(discoURIs[i]);
            associate(wsEntity, discoEntity);
            uriToEntityTable_.put(discoURIs[i], discoEntity);
            if ((parseOption | PARSE_DISCO) == parseOption) {
                try {
                    parseDISCO(discoURIs[i], parseOption);
                } catch (Exception t) {
                }
            }
        }
    }
    // false if uri_ is not a HTML document
    // then parse uri_ as a WSIL document
    else {
        try {
            parseWSIL(theUri, parseOption, byteEncoding);
            // no exception thrown if uri_ is a WSIL document
            wsEntity.setType(WebServiceEntity.TYPE_WSIL);
        } catch (Exception t) {
            // exception thrown if uri_ is not a WSIL document
            // then parse uri_ as a DISCO document.
            try {
                parseDISCO(theUri, parseOption);
                // no exception thrown if uri_ is a DISCO document
                wsEntity.setType(WebServiceEntity.TYPE_DISCO);
            } catch (Exception t2) {
                // exception thrown if uri_ is not a DISCO document
                // then parse uri_ as a WSDL document
                try {
                    parseWSDL(theUri);
                    // no exception thrown if uri_ is a WSDL document
                    wsEntity.setType(WebServiceEntity.TYPE_WSDL);
                } catch (Exception t3) {
                    // exception thrown if uri_ is not a WSDL document
                    // then do nothing
                }
            }
        }
    }
}

From source file:org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.java

protected XMLReader createReader() throws SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*  www  .  j  a v  a  2 s.co m*/
    return spf.newSAXParser().getXMLReader();
}

From source file:org.entando.entando.plugins.jpwebform.aps.system.services.form.FormManager.java

protected void valueEntityFromXml(IApsEntity entityPrototype, String xml) throws ApsSystemException {
    try {/*from  w  w w  .  ja  v a 2 s .  com*/
        SAXParserFactory parseFactory = SAXParserFactory.newInstance();
        SAXParser parser = parseFactory.newSAXParser();
        InputSource is = new InputSource(new StringReader(xml));
        EntityHandler handler = this.getEntityHandler();
        handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager());
        parser.parse(is, handler);
    } catch (Throwable t) {
        _logger.error("Error detected while creating the entity. xml:{}", xml, t);
        throw new ApsSystemException("Error detected while creating the entity", t);
    }
}

From source file:org.exist.http.SOAPServer.java

/**
 * Builds an XML Document from a string representation
 * /*from  w ww  .j av a  2s.c  om*/
 * @param buf   The XML Document content
 * 
 * @return   DOM XML Document
 */
private Document BuildXMLDocument(byte[] buf) throws SAXException, ParserConfigurationException, IOException {
    //try and construct xml document from input stream, we use eXist's in-memory DOM implementation
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    //TODO we should be able to cope with context.getBaseURI()            
    final InputSource src = new InputSource(new ByteArrayInputStream(buf));
    final SAXParser parser = factory.newSAXParser();
    final XMLReader reader = parser.getXMLReader();
    final SAXAdapter adapter = new SAXAdapter();
    reader.setContentHandler(adapter);
    reader.setContentHandler(adapter);
    reader.parse(src);

    //return receiver.getDocument();
    return adapter.getDocument();
}