Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

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

/**
 * //from  w  w  w .java  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 w  ww . ja v  a  2  s. com
        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 w  w.  jav  a  2s  . com*/
 *
 * @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.mwe.internal.core.ast.parser.WorkflowParser.java

public AbstractASTBase parse(final InputStream in, final String resourceName, final Issues issues) {
    resource = resourceName;//from  www . j  a v a 2 s  .co m
    this.issues = issues;

    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(in, this);
    } catch (final Exception e) {
        root = null;
        log.error(e.getMessage(), e);
        issues.addError(e.getMessage(), resourceName);
    }

    return root;
}

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

/**
 * Applies the XML persistence mapping to a PAnnotatedModel.
 * //  w w  w .  j  av a 2 s.com
 * @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.smila.integration.solr.SolrPipelet.java

public SearchMessage process(Blackboard blackboard, SearchMessage message) throws ProcessingException {
    if (message.hasQuery()) {
        ParameterAccessor parameters = new ParameterAccessor(blackboard, message.getQuery());
        String query = parameters.getQuery();
        int resultSize = parameters.getResultSize();
        int resultOffset = parameters.getResultOffset();
        List<String> resultAttributes = parameters.getResultAttributes();
        // Threshold seems not to be implemented in Solr, so we just ignore
        // it for now.
        // double threshold = parameters.getThreshold();
        Id queryId = message.getQuery();

        HttpURLConnection conn = null;
        List<Id> rIds = new ArrayList<Id>();

        String searchURL = HTTP_LOCALHOST + SOLR_WEBAPP + SELECT;
        if (_shards != null) {
            searchURL += "shards=";
            for (String shard : _shards) {
                searchURL += shard + SOLR_WEBAPP + ",";
            }//from  w  w  w .  ja  v a 2  s .  c  o  m
        }
        if (_highlight) {
            searchURL += "&hl=true";
        }
        if (_highlightParams != null) {
            for (String hp : _highlightParams) {
                searchURL += "&" + hp;
            }
        }
        searchURL += "&start=" + resultOffset;
        searchURL += "&rows=" + resultSize;
        // Include requested attributes and scores
        // into the result.
        if (resultAttributes != null) {
            // We need to retrieve id explicitly
            searchURL += "&fl=id,";
            for (String ra : resultAttributes) {
                searchURL += ra + ",";
            }
            searchURL += "score";
        }
        searchURL += "&indent=true&q=";
        try {
            if (query != null) {
                searchURL += URLEncoder.encode(query, UTF8);
            } else {
                // We have to set any value for a query otherwise we get
                // error 500
                searchURL += DEFAULT_SEARCH_TERM;
            }
            URL url = new URL(searchURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(GET);
            conn.setDoOutput(true);
            conn.setReadTimeout(10000);
            conn.connect();

            InputStream is = conn.getInputStream();
            SAXParser p = pf.newSAXParser();
            SolrResponseHandler srh = new SolrResponseHandler(blackboard, rIds);
            p.parse(is, srh);
            String totalHits = Integer.toString(srh.noOfHits);
            Annotation resultAnno = blackboard.getAnnotation(queryId, null, SearchAnnotations.RESULT);
            if (resultAnno == null) {
                resultAnno = blackboard.createAnnotation(queryId);
                blackboard.setAnnotation(queryId, null, SearchAnnotations.RESULT, resultAnno);
            }
            resultAnno.setNamedValue(SearchAnnotations.TOTAL_HITS, totalHits);
        } catch (Exception e) {
            String msg = "Error while while processing search request: '" + e.getMessage() + "'.";
            _log.error(msg, e);
            throw new ProcessingException(msg, e);
        } finally {
            conn.disconnect();
            conn = null;
        }
        message.setRecords(rIds);
    }
    return message;
}

From source file:org.eclipse.smila.integration.solr.SolrSearchPipelet.java

@Override
public String[] process(final Blackboard blackboard, final String[] message) throws ProcessingException {
    if (message.length > 0) {
        final QueryParameterAccessor parameters = new QueryParameterAccessor(blackboard, message[0]);
        final String query = parameters.getQuery();
        final int resultSize = parameters.getMaxCount();
        final int resultOffset = parameters.getOffset();
        final List<String> resultAttributes = parameters.getResultAttributes();
        // Threshold seems not to be implemented in Solr, so we just ignore it for now.
        // double threshold = parameters.getThreshold();

        HttpURLConnection conn = null;
        final List<String> rIds = new ArrayList<String>();

        String searchURL = HTTP_LOCALHOST + SOLR_WEBAPP + SELECT;
        if (_shards != null) {
            searchURL += "shards=";
            for (final Any shard : _shards) {
                if (shard.isValue()) {
                    searchURL += ((Value) shard).asString() + SOLR_WEBAPP + ",";
                }/*w  ww.  ja va2  s. c  om*/
            }
        }
        if (_highlight) {
            searchURL += "&hl=true";
        }
        if (_highlightParams != null) {
            for (final Any hp : _highlightParams) {
                if (hp.isValue()) {
                    searchURL += "&" + ((Value) hp).asString();
                }
            }
        }
        searchURL += "&start=" + resultOffset;
        searchURL += "&rows=" + resultSize;
        // Include requested attributes and scores
        // into the result.
        if (resultAttributes != null) {
            // We need to retrieve id & _source explicitly
            searchURL += "&fl=id,_source,";
            for (final String ra : resultAttributes) {
                searchURL += ra + ",";
            }
            searchURL += "score";
        }
        searchURL += "&indent=true&q=";
        try {
            if (query != null) {
                searchURL += URLEncoder.encode(query, UTF8);
            } else {
                // We have to set any value for a query otherwise we get
                // error 500
                searchURL += DEFAULT_SEARCH_TERM;
            }
            final URL url = new URL(searchURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(GET);
            conn.setDoOutput(true);
            conn.setReadTimeout(10000);
            conn.connect();

            final InputStream is = conn.getInputStream();
            final SAXParser p = pf.newSAXParser();
            final SolrResponseHandler srh = new SolrResponseHandler(blackboard, rIds);
            p.parse(is, srh);

            final String totalHits = Integer.toString(srh.noOfHits);
            final AnySeq records = blackboard.getDataFactory().createAnySeq();
            for (final String recordId : rIds) {
                records.add(blackboard.getMetadata(recordId));
            }
            blackboard.getMetadata(message[0]).put(SearchResultConstants.COUNT, totalHits);
            blackboard.getMetadata(message[0]).put(SearchResultConstants.RECORDS, records);
        } catch (final Exception e) {
            final String msg = "Error while while processing search request: '" + e.getMessage() + "'.";
            _log.error(msg, e);
            throw new ProcessingException(msg, e);
        } finally {
            conn.disconnect();
            conn = null;
        }
    }
    return message;
}

From source file:org.eclipse.wb.internal.core.databinding.wizards.autobindings.DescriptorContainer.java

/**
 * Parse descriptors XML file./*w  ww  .  j  a  v a  2s  .  com*/
 * 
 * @return {@link Map} with all descriptors.
 */
public static Map<String, DescriptorContainer> parseDescriptors(InputStream stream,
        final ClassLoader classLoader, final IImageLoader imageLoader) throws Exception {
    final Map<String, DescriptorContainer> containers = Maps.newHashMap();
    //
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(stream, new DefaultHandler() {
        private DescriptorContainer m_container;
        private AbstractDescriptor m_descriptor;
        private Class<?> m_descriptorClass;

        //
        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes)
                throws SAXException {
            try {
                if ("descriptors".equals(name)) {
                    // create container
                    m_container = new DescriptorContainer();
                    containers.put(attributes.getValue("name"), m_container);
                    m_descriptorClass = classLoader.loadClass(attributes.getValue("class"));
                } else if ("descriptor".equals(name)) {
                    // create descriptor
                    m_descriptor = (AbstractDescriptor) m_descriptorClass.newInstance();
                } else if (m_descriptor != null) {
                    // fill attributes
                    if (attributes.getLength() == 0) {
                        // method without parameters
                        ReflectionUtils.invokeMethod(m_descriptor, name + "()", ArrayUtils.EMPTY_OBJECT_ARRAY);
                    } else {
                        if (name.endsWith("Image")) {
                            // special support for images
                            try {
                                ReflectionUtils.invokeMethod(m_descriptor,
                                        name + "(org.eclipse.swt.graphics.Image)",
                                        new Object[] { imageLoader.getImage(attributes.getValue("value")) });
                            } catch (Throwable e) {
                                DesignerPlugin.log(
                                        "DescriptorContainer: error load image " + attributes.getValue("value"),
                                        e);
                            }
                        } else {
                            // method with single String parameter
                            ReflectionUtils.invokeMethod(m_descriptor, name + "(java.lang.String)",
                                    new Object[] { attributes.getValue("value") });
                        }
                    }
                }
            } catch (Exception e) {
                throw new SAXException("startElement", e);
            }
        }

        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            // clear state
            if ("descriptors".equals(name)) {
                m_container = null;
            } else if ("descriptor".equals(name)) {
                m_container.addDescriptor(m_descriptor);
                m_descriptor = null;
            }
        }
    });
    //
    return containers;
}

From source file:org.eclipse.wb.internal.core.editor.palette.PaletteManager.java

private void commandsRead_fromStream0(InputStream inputStream) throws Exception {
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(inputStream, new DefaultHandler() {
        @Override/*ww w  .j  ava2s  .com*/
        public void startElement(String uri, String localName, final String name, final Attributes attributes) {
            ExecutionUtils.runIgnore(new RunnableEx() {
                public void run() throws Exception {
                    commandsRead_singleCommand(name, attributes);
                }
            });
        }
    });
}