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.apache.oozie.util.GraphGenerator.java

/**
 * Stream the PNG file to client/*  ww  w .  j a v a 2 s.c  o m*/
 * @param out
 * @throws Exception
 */
public void write(OutputStream out) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new XMLParser(out));
    xmlReader.parse(new InputSource(new StringReader(xml)));
}

From source file:org.apache.openmeetings.db.dao.label.LabelDao.java

private static List<StringLabel> getLabels(InputStream is) throws Exception {
    final List<StringLabel> labels = new ArrayList<StringLabel>();
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*from   w  w  w. j av a  2  s  .  c  o  m*/
    try {
        SAXParser parser = spf.newSAXParser();
        XMLReader xr = parser.getXMLReader();
        xr.setContentHandler(new ContentHandler() {
            StringLabel label = null;

            @Override
            public void startPrefixMapping(String prefix, String uri) throws SAXException {
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                if (ENTRY_ELEMENT.equals(localName)) {
                    label = new StringLabel(atts.getValue(KEY_ATTR), "");
                }
            }

            @Override
            public void startDocument() throws SAXException {
            }

            @Override
            public void skippedEntity(String name) throws SAXException {
            }

            @Override
            public void setDocumentLocator(Locator locator) {
            }

            @Override
            public void processingInstruction(String target, String data) throws SAXException {
            }

            @Override
            public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            }

            @Override
            public void endPrefixMapping(String prefix) throws SAXException {
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (ENTRY_ELEMENT.equals(localName)) {
                    labels.add(label);
                }
            }

            @Override
            public void endDocument() throws SAXException {
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                StringBuilder sb = new StringBuilder(label.getValue());
                sb.append(ch, start, length);
                label.setValue(sb.toString());
            }
        });
        xr.parse(new InputSource(is));
    } catch (Exception e) {
        throw e;
    }
    return labels;
}

From source file:org.apache.poi.xssf.eventusermodel.XLSX2CSV.java

/**
 * Parses and shows the content of one sheet
 * using the specified styles and shared-strings tables.
 *
 * @param styles// w  w  w  . j a va2 s . c  o m
 * @param strings
 * @param sheetInputStream
 */
public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream)
        throws IOException, ParserConfigurationException, SAXException {

    InputSource sheetSource = new InputSource(sheetInputStream);
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader sheetParser = saxParser.getXMLReader();
    ContentHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output);
    sheetParser.setContentHandler(handler);
    sheetParser.parse(sheetSource);
}

From source file:org.apache.sling.tooling.support.source.impl.FelixJettySourceReferenceFinder.java

@Override
public List<SourceReference> findSourceReferences(Bundle bundle) throws SourceReferenceException {
    // the org.apache.felix.http.jetty bundle does not retain references to the source bundles
    // so infer them from the X-Jetty-Version header
    if (!bundle.getSymbolicName().equals("org.apache.felix.http.jetty")) {
        return Collections.emptyList();
    }//w ww .jav a  2  s  . com

    final Object jettyVersion = bundle.getHeaders().get("X-Jetty-Version");
    if (!(jettyVersion instanceof String)) {
        return Collections.emptyList();
    }

    URL entry = bundle.getEntry("/META-INF/maven/org.apache.felix/org.apache.felix.http.jetty/pom.xml");

    InputStream pom = null;
    try {
        pom = entry.openStream();

        try {
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser parser = parserFactory.newSAXParser();
            PomHandler handler = new PomHandler((String) jettyVersion);
            parser.parse(new InputSource(pom), handler);

            return handler.getReferences();
        } catch (SAXException e) {
            throw new SourceReferenceException(e);
        } catch (ParserConfigurationException e) {
            throw new SourceReferenceException(e);
        } finally {
            IOUtils.closeQuietly(pom);
        }
    } catch (IOException e) {
        throw new SourceReferenceException(e);
    } finally {
        IOUtils.closeQuietly(pom);
    }

}

From source file:org.apache.synapse.mediators.builtin.ValidateMediator.java

public boolean mediate(SynapseContext synCtx) {

    ByteArrayInputStream baisFromSource = null;
    StringBuffer nsLocations = new StringBuffer();

    try {//from  www  .j ava 2s  . c  om
        // create a byte array output stream and serialize the source node into it
        ByteArrayOutputStream baosForSource = new ByteArrayOutputStream();
        XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource);

        // save the list of defined namespaces for validation against the schema
        OMNode sourceNode = getValidateSource(synCtx.getSynapseMessage());
        if (sourceNode instanceof OMElement) {
            Iterator iter = ((OMElement) sourceNode).getAllDeclaredNamespaces();
            while (iter.hasNext()) {
                OMNamespace omNS = (OMNamespace) iter.next();
                nsLocations.append(omNS.getName() + " " + getSchemaUrl());
            }
        }
        sourceNode.serialize(xsWriterForSource);
        baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray());

    } catch (Exception e) {
        String msg = "Error accessing source element for validation : " + source;
        log.error(msg);
        throw new SynapseException(msg, e);
    }

    try {
        SAXParserFactory spFactory = SAXParserFactory.newInstance();
        spFactory.setNamespaceAware(true);
        spFactory.setValidating(true);
        SAXParser parser = spFactory.newSAXParser();

        parser.setProperty(VALIDATION, Boolean.TRUE);
        parser.setProperty(SCHEMA_VALIDATION, Boolean.TRUE);
        parser.setProperty(FULL_CHECKING, Boolean.TRUE);
        parser.setProperty(SCHEMA_LOCATION_NS, nsLocations.toString());
        parser.setProperty(SCHEMA_LOCATION_NO_NS, getSchemaUrl());

        Validator handler = new Validator();
        parser.parse(baisFromSource, handler);

        if (handler.isValidationError()) {
            log.debug("Validation failed :" + handler.getSaxParseException().getMessage());
            // super.mediate() invokes the "on-fail" sequence of mediators
            return super.mediate(synCtx);
        }

    } catch (Exception e) {
        String msg = "Error validating " + source + " against schema : " + schemaUrl + " : " + e.getMessage();
        log.error(msg);
        throw new SynapseException(msg, e);
    }

    return true;
}

From source file:org.apache.syncope.client.cli.commands.MigrateTest.java

@Test
public void conf() throws Exception {
    // 1. migrate
    String[] args = new String[4];
    args[0] = "migrate";
    args[1] = "--conf";
    args[2] = BASE_PATH + File.separator + "content12.xml";
    args[3] = BASE_PATH + File.separator + "MasterContent.xml";

    new MigrateCommand().execute(new Input(args));

    // 2. initialize db as persistence-jpa does
    DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:syncopedb;DB_CLOSE_DELAY=-1", "sa", null);

    new ResourceDatabasePopulator(new ClassPathResource("/schema20.sql")).execute(dataSource);

    // 3. attempt to set initial content from the migrated MasterContent.xml
    SAXParserFactory factory = SAXParserFactory.newInstance();
    InputStream in = null;/*from  ww w  .ja v  a 2 s .  c o m*/
    try {
        in = new FileInputStream(args[3]);

        SAXParser parser = factory.newSAXParser();
        parser.parse(in, new ContentLoaderHandler(dataSource, ROOT_ELEMENT, false));
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.syncope.core.persistence.dao.impl.ContentLoader.java

private void loadDefaultContent() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    InputStream in = null;/*w ww .j av a2 s.  c o  m*/
    try {
        in = getClass().getResourceAsStream("/" + CONTENT_XML);

        SAXParser parser = factory.newSAXParser();
        parser.parse(in, new ContentLoaderHandler(dataSource, ROOT_ELEMENT));
        LOG.debug("Default content successfully loaded");
    } catch (Exception e) {
        LOG.error("While loading default content", e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentLoader.java

private void loadDefaultContent(final String domain, final ResourceWithFallbackLoader contentXML,
        final DataSource dataSource) throws Exception {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    InputStream in = null;// w ww . j  av  a2  s  .c o  m
    try {
        in = contentXML.getResource().getInputStream();

        SAXParser parser = factory.newSAXParser();
        parser.parse(in, new ContentLoaderHandler(dataSource, ROOT_ELEMENT, true));
        LOG.debug("[{}] Default content successfully loaded", domain);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.tomcat.util.digester.GenericParser.java

/**
 * Create a <code>SAXParser</code> configured to support XML Scheman and DTD
 * @param properties parser specific properties/features
 * @return an XML Schema/DTD enabled <code>SAXParser</code>
 */// w  w w .jav  a  2 s  .c  om
public static SAXParser newSAXParser(Properties properties)
        throws ParserConfigurationException, SAXException, SAXNotRecognizedException {

    SAXParserFactory factory = (SAXParserFactory) properties.get("SAXParserFactory");
    SAXParser parser = factory.newSAXParser();
    String schemaLocation = (String) properties.get("schemaLocation");
    String schemaLanguage = (String) properties.get("schemaLanguage");

    try {
        if (schemaLocation != null) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
            parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
        }
    } catch (SAXNotRecognizedException e) {
        log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported.");
    }
    return parser;
}

From source file:org.apache.tomcat.util.digester.XercesParser.java

/**
 * Create a <code>SAXParser</code> based on the underlying
 * <code>Xerces</code> version.
 * @param properties parser specific properties/features
 * @return an XML Schema/DTD enabled <code>SAXParser</code>
 *//*  w ww  . j  a  v  a2s  .  c o  m*/
public static SAXParser newSAXParser(Properties properties)
        throws ParserConfigurationException, SAXException, SAXNotSupportedException {

    SAXParserFactory factory = (SAXParserFactory) properties.get("SAXParserFactory");

    if (versionNumber == null) {
        versionNumber = getXercesVersion();
        version = new Float(versionNumber).floatValue();
    }

    // Note: 2.2 is completely broken (with XML Schema). 
    if (version > 2.1) {

        configureXerces(factory);
        return factory.newSAXParser();
    } else {
        SAXParser parser = factory.newSAXParser();
        configureOldXerces(parser, properties);
        return parser;
    }
}