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.sakaiproject.kernel.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 * @param xml a stream containing the xml
 * @param schema a stream containing the schema
 * @return a list of errors or warnings, a 0 lenght string if none.
 *//*w w  w. ja va 2  s  .  c om*/
public static String validate(InputStream xml, InputStream schema) {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final StringBuilder errors = new StringBuilder();
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        Schema s = schemaFactory.newSchema(new StreamSource(schema));
        Validator validator = s.newValidator();
        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
        errors.append(e.getMessage()).append("\n");
    } catch (SAXException e) {
        errors.append(e.getMessage()).append("\n");
    }
    return errors.toString();
}

From source file:org.tonguetied.datatransfer.importing.ResourceImporter.java

@Override
protected void doImport(final byte[] input, final TranslationState state) throws ImportException {
    if (logger.isDebugEnabled())
        logger.debug("attempting import");
    ByteArrayInputStream bais = null;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);/*from w w  w .jav a2 s.  c  o m*/
    factory.setNamespaceAware(true);
    try {
        //            validate(bais);
        //            XMLReader reader = XMLReaderFactory.createXMLReader();
        //            reader.setContentHandler(new ResourceHandler(
        //                    getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
        //            // Request validation
        //            reader.setFeature("http://xml.org/sax/features/validation", true);
        //            InputSource is = new InputSource(bais);
        //            reader.parse(is);

        SAXParser parser = factory.newSAXParser();

        bais = new ByteArrayInputStream(input);
        parser.parse(bais,
                new ResourceHandler(getBundle(), getCountry(), getLanguage(), state, getKeywordService()));
    } catch (SAXException saxe) {
        throw new ImportException(saxe);
    } catch (ParserConfigurationException pce) {
        throw new ImportException(pce);
    } catch (IOException ioe) {
        throw new ImportException(ioe);
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.unitils.dbunit.datasetfactory.DataSetFactoryFactory.java

/**
 * Creates a namespace aware sax parser factory.
 * All validation is disabled so data sets can still be loaded when a DTD or XSD is missing
 *
 * @return the factory, not null/*ww w  . jav  a 2 s  .co  m*/
 */
protected SAXParserFactory createSAXParserFactory() {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    disableValidation(saxParserFactory);
    return saxParserFactory;
}

From source file:org.unitils.dbunit.util.MultiSchemaXmlDataSetReader.java

/**
 * Factory method for creating the SAX xml reader.
 *
 * @return the XML reader, not null//from   w  ww .  j av a  2s.  c o m
 */
protected XMLReader createXMLReader() {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);

        // disable validation, so dataset can still be used when a DTD or XSD is missing
        disableValidation(saxParserFactory);
        return saxParserFactory.newSAXParser().getXMLReader();

    } catch (Exception e) {
        throw new UnitilsException("Unable to create SAX parser to read data set xml.", e);
    }
}

From source file:org.walkmod.util.DomHelper.java

/**
 * Creates a W3C Document that remembers the location of each element in the
 * source file. The location of element nodes can then be retrieved using
 * the {@link #getLocationObject(Element)} method.
 *
 * @param inputSource/*from w  w w  .j a va  2 s .  com*/
 *            the inputSource to read the document from
 * @param dtdMappings
 *            a map of DTD names and public ids
 * @return Document
 */
public static Document parse(InputSource inputSource, Map<String, String> dtdMappings) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating((dtdMappings != null));
    factory.setNamespaceAware(true);
    SAXParser parser = null;
    try {
        parser = factory.newSAXParser();
    } catch (Exception ex) {
        throw new WalkModException("Unable to create SAX parser", ex);
    }
    DOMBuilder builder = new DOMBuilder();
    ContentHandler locationHandler = new LocationAttributes.Pipe(builder);
    try {
        parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings));
    } catch (Exception ex) {
        throw new WalkModException(ex);
    }
    return builder.getDocument();
}

From source file:org.wso2.carbon.sample.tfl.traffic.TrafficPollingTask.java

public void run() {
    try {/* w ww.jav a2s  . c om*/
        URL obj = new URL(streamURL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        ArrayList<Disruption> disruptionsList = new ArrayList<Disruption>();
        try {
            // optional default is GET
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            log.info("Sending 'GET' request to URL : " + streamURL);
            log.info("Response Code : " + responseCode);

            double t = System.currentTimeMillis();
            // Get SAX Parser Factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // Turn on validation, and turn off namespaces
            factory.setValidating(true);
            factory.setNamespaceAware(false);
            SAXParser parser = factory.newSAXParser();
            parser.parse(con.getInputStream(), new TrafficXMLHandler(disruptionsList));
            log.info("Number of Disruptions added to the list: " + disruptionsList.size());
            log.info("Time taken for parsing: " + (System.currentTimeMillis() - t));
        } catch (ParserConfigurationException e) {
            log.info("The underlying parser does not support " + " the requested features.");
        } catch (FactoryConfigurationError e) {
            log.info("Error occurred obtaining SAX Parser Factory.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }

        ArrayList<String> list = new ArrayList<String>();
        int count = 0;
        for (Disruption disruption : disruptionsList) {
            if (disruption.getState().contains("Active")) {
                list.add(disruption.toJson());
            }
            count++;
        }
        TflStream.writeToFile("tfl-traffic-data.out", list, true);
    } catch (IOException e) {
        log.error("Error occurred while getting traffic data: " + e.getMessage(), e);
    }

}

From source file:pt.iflow.api.licensing.FileBasedLicenseService.java

private void parseXMLSnapshot(byte[] xml) throws SAXException, IOException, ParserConfigurationException {
    DefaultHandler handler = new DefaultHandler() {
        LicenseEntry currOrg;// ww  w.j av  a2s .co m

        public void startDocument() throws SAXException {
            licenseEntries.clear();
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("org".equals(qName)) {
                currOrg = new LicenseEntry();
                currOrg.available = Long.parseLong(attributes.getValue("available"));
                currOrg.consumed = Long.parseLong(attributes.getValue("consumed"));
                licenseEntries.put(attributes.getValue("id"), currOrg);
            } else if ("flow".equals(qName)) {
                currOrg.flowBased.put(new Integer(attributes.getValue("id")),
                        new Long(attributes.getValue("consumed")));
            }
        }

    };

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    parser.parse(new ByteArrayInputStream(xml), handler);

}

From source file:tds.student.sbacossmerge.data.TestResponseReaderSax.java

public static TestResponseReader parseSax(InputStream xml, TestOpportunity testOpp) throws Exception {
    TestResponseReaderSax saxReader = new TestResponseReaderSax();
    saxReader._testOpp = testOpp;/*from  ww w .  ja  va  2  s .  c  o  m*/

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();

    saxReader._xmlReader = xmlReader;
    ContentHandler defaultHandler = saxReader._parseHandlers.peek();
    xmlReader.setContentHandler(defaultHandler);

    xmlReader.parse(new InputSource(xml));

    return saxReader;
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.xml.exchange.PsiExchangeImpl.java

/**
 * Gets the release dates from a PSI-MI XML InputStream
 * @param is//from w  ww .j  a va2s .com
 * @return
 */
public List<DateTime> getReleaseDates(InputStream is) throws IOException {
    final List<DateTime> releaseDates = new ArrayList<DateTime>();

    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (localName.equals("source")) {
                final String releaseDateStr = attributes.getValue("releaseDate");
                DateTime releaseDate = toDateTime(releaseDateStr);
                releaseDates.add(releaseDate);
            }
        }
    };

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

    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(new InputSource(is), handler);
    } catch (Exception e) {
        throw new IntactException(e);
    }

    return releaseDates;
}

From source file:us.paulevans.basicxslt.Utils.java

/**
 * Method to determine if inputted xml file is valid and well-formed.
 * @param saXmlFile//  w w  w. jav  a  2  s  .  c  o m
 * @throws Exception If saXmlFile is invalid or not well-formed.
 */
public void isValidXml(FileContent faXmlFile, boolean aCheckWarning, boolean aCheckError,
        boolean aCheckFatalError) throws SAXNotSupportedException, SAXNotRecognizedException,
        ParserConfigurationException, SAXException, IOException {

    SAXParserFactory factory;

    checkWarning = aCheckWarning;
    checkError = aCheckError;
    checkFatalError = aCheckFatalError;
    factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    try {
        factory.setFeature(VALIDATION_FEATURE, true);
        factory.setFeature(SCHEMA_FEATURE, true);
        SAXParser parser = factory.newSAXParser();
        parser.parse(faXmlFile.getInputStream(), this);
    } catch (UnknownHostException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new UnknownHostException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SocketException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new SocketException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SAXNotSupportedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXNotRecognizedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (ParserConfigurationException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (IOException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    }
}