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.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  .j  a v  a2  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 ww w . j a  v a  2  s .c  o  m
        // 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;/* w  w  w. jav  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;/*  www  .  j  ava  2s . 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 w  w. j  a v a  2 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.tika.parser.epub.EpubContentParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    SAXParser parser = context.getSAXParser();
    parser.parse(new CloseShieldInputStream(stream), new OfflineContentHandler(handler));
}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

private void extractHOCROutput(InputStream is, ParseContext parseContext, XHTMLContentHandler xhtml)
        throws TikaException, IOException, SAXException {
    if (parseContext == null) {
        parseContext = new ParseContext();
    }//  w  w  w .j  a va  2  s .  co  m
    SAXParser parser = parseContext.getSAXParser();
    xhtml.startElement("div", "class", "ocr");
    parser.parse(is, new OfflineContentHandler(new HOCRPassThroughHandler(xhtml)));
    xhtml.endElement("div");
}

From source file:org.apache.tika.parser.odf.OpenDocumentContentParser.java

void parseInternal(InputStream stream, final ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    DefaultHandler dh = new OpenDocumentElementMappingContentHandler(handler, MAPPINGS);

    SAXParser parser = context.getSAXParser();
    parser.parse(new CloseShieldInputStream(stream),
            new OfflineContentHandler(new NSNormalizerContentHandler(dh)));
}

From source file:org.apache.torque.engine.database.transform.XmlToAppData.java

/**
 * Parses a XML input file and returns a newly created and
 * populated Database structure.//  w  w w .  j  av  a 2 s  .c  o m
 *
 * @param xmlFile The input file to parse.
 * @return Database populated by <code>xmlFile</code>.
 */
public Database parseFile(String xmlFile) throws EngineException {
    try {
        // in case I am missing something, make it obvious
        if (!firstPass) {
            throw new Error("No more double pass");
        }
        // check to see if we alread have parsed the file
        if ((alreadyReadFiles != null) && alreadyReadFiles.contains(xmlFile)) {
            return database;
        } else if (alreadyReadFiles == null) {
            alreadyReadFiles = new Vector(3, 1);
        }

        // remember the file to avoid looping
        alreadyReadFiles.add(xmlFile);

        currentXmlFile = xmlFile;

        SAXParser parser = saxFactory.newSAXParser();

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(xmlFile);
        } catch (FileNotFoundException fnfe) {
            throw new FileNotFoundException(new File(xmlFile).getAbsolutePath());
        }
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        try {
            log.info("Parsing file: '" + (new File(xmlFile)).getName() + "'");
            InputSource is = new InputSource(bufferedInputStream);
            is.setSystemId(new File(xmlFile).getAbsolutePath());
            parser.parse(is, this);
        } finally {
            bufferedInputStream.close();
        }
    } catch (SAXParseException e) {
        throw new EngineException("Sax error on line " + e.getLineNumber() + " column " + e.getColumnNumber()
                + " : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new EngineException(e);
    }
    if (!isExternalSchema) {
        firstPass = false;
    }
    database.doFinalInitialization();
    return database;
}

From source file:org.apache.torque.engine.database.transform.XmlToData.java

/**
 *
 *//*  www  . j  av  a 2 s  . c o  m*/
public List parseFile(String xmlFile) throws Exception {
    data = new ArrayList();

    SAXParser parser = saxFactory.newSAXParser();

    FileReader fr = new FileReader(xmlFile);
    BufferedReader br = new BufferedReader(fr);
    try {
        InputSource is = new InputSource(br);
        is.setSystemId(xmlFile);
        parser.parse(is, this);
    } finally {
        br.close();
    }
    return data;
}