Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:nl.nn.adapterframework.util.XmlUtils.java

static public boolean isWellFormed(String input, String root) {
    Set<List<String>> rootValidations = null;
    if (StringUtils.isNotEmpty(root)) {
        List<String> path = new ArrayList<String>();
        path.add(root);//  w  ww . ja  v a2s.c om
        rootValidations = new HashSet<List<String>>();
        rootValidations.add(path);
    }
    XmlValidatorContentHandler xmlHandler = new XmlValidatorContentHandler(null, rootValidations, null, true);
    XmlValidatorErrorHandler xmlValidatorErrorHandler = new XmlValidatorErrorHandler(xmlHandler,
            "Is not well formed");
    xmlHandler.setXmlValidatorErrorHandler(xmlValidatorErrorHandler);
    try {
        SAXSource saxSource = stringToSAXSource(input, true, false);
        XMLReader xmlReader = saxSource.getXMLReader();
        xmlReader.setContentHandler(xmlHandler);
        // Prevent message in System.err: [Fatal Error] :-1:-1: Premature end of file.
        xmlReader.setErrorHandler(xmlValidatorErrorHandler);
        xmlReader.parse(saxSource.getInputSource());
    } catch (Exception e) {
        return false;
    }
    return true;
}

From source file:nl.nn.adapterframework.validation.XercesXmlValidator.java

/**
 * Validate the XML string/* w  w w. ja v a 2 s  . co  m*/
 * @param input a String
 * @param session a {@link nl.nn.adapterframework.core.IPipeLineSession pipeLineSession}
 * @return MonitorEvent declared in{@link AbstractXmlValidator}
 * @throws XmlValidatorException when <code>isThrowException</code> is true and a validationerror occurred.
 * @throws PipeRunException
 * @throws ConfigurationException
 */
@Override
public String validate(Object input, IPipeLineSession session, String logPrefix)
        throws XmlValidatorException, PipeRunException, ConfigurationException {
    if (StringUtils.isNotEmpty(getReasonSessionKey())) {
        log.debug(logPrefix + "removing contents of sessionKey [" + getReasonSessionKey() + "]");
        session.remove(getReasonSessionKey());
    }

    if (StringUtils.isNotEmpty(getXmlReasonSessionKey())) {
        log.debug(logPrefix + "removing contents of sessionKey [" + getXmlReasonSessionKey() + "]");
        session.remove(getXmlReasonSessionKey());
    }

    PreparseResult preparseResult;
    String schemasId = schemasProvider.getSchemasId();
    if (schemasId == null) {
        schemasId = schemasProvider.getSchemasId(session);
        preparseResult = preparse(schemasId, schemasProvider.getSchemas(session));
    } else {
        if (cache == null) {
            preparseResult = this.preparseResult;
            if (preparseResult == null) {
                init();
                preparseResult = this.preparseResult;
            }
        } else {
            preparseResult = (PreparseResult) cache.getObject(preparseResultId);
            if (preparseResult == null) {
                preparseResult = preparse(schemasId, schemasProvider.getSchemas());
                cache.putObject(preparseResultId, preparseResult);
            }
        }
    }
    SymbolTable symbolTable = preparseResult.getSymbolTable();
    XMLGrammarPool grammarPool = preparseResult.getGrammarPool();
    Set<String> namespacesSet = preparseResult.getNamespaceSet();

    String mainFailureMessage = "Validation using " + schemasProvider.getClass().getSimpleName() + " with '"
            + schemasId + "' failed";

    XmlValidatorContentHandler xmlValidatorContentHandler = new XmlValidatorContentHandler(namespacesSet,
            rootValidations, invalidRootNamespaces, getIgnoreUnknownNamespaces());
    XmlValidatorErrorHandler xmlValidatorErrorHandler = new XmlValidatorErrorHandler(xmlValidatorContentHandler,
            mainFailureMessage);
    xmlValidatorContentHandler.setXmlValidatorErrorHandler(xmlValidatorErrorHandler);
    XMLReader parser = new SAXParser(new ShadowedSymbolTable(symbolTable), grammarPool);
    parser.setErrorHandler(xmlValidatorErrorHandler);
    parser.setContentHandler(xmlValidatorContentHandler);
    try {
        parser.setFeature(NAMESPACES_FEATURE_ID, true);
        parser.setFeature(VALIDATION_FEATURE_ID, true);
        parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true);
        parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, isFullSchemaChecking());
    } catch (SAXNotRecognizedException e) {
        throw new XmlValidatorException(logPrefix + "parser does not recognize necessary feature", e);
    } catch (SAXNotSupportedException e) {
        throw new XmlValidatorException(logPrefix + "parser does not support necessary feature", e);
    }

    InputSource is = getInputSource(input);

    try {
        parser.parse(is);
    } catch (Exception e) {
        return handleFailures(xmlValidatorErrorHandler, session, XML_VALIDATOR_PARSER_ERROR_MONITOR_EVENT, e);
    }

    if (xmlValidatorErrorHandler.hasErrorOccured()) {
        return handleFailures(xmlValidatorErrorHandler, session, XML_VALIDATOR_NOT_VALID_MONITOR_EVENT, null);
    }
    return XML_VALIDATOR_VALID_MONITOR_EVENT;
}

From source file:org.apache.camel.component.validator.jing.JingValidator.java

public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();//from   ww w  . j  a v a  2 s.  c  o  m
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
        Source source = ExchangeHelper.getMandatoryInBody(exchange, Source.class);
        saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
}

From source file:org.apache.camel.dataformat.tagsoup.TidyMarkupDataFormat.java

/**
 * Return the tidy markup as a string//from w w  w.j  a  va  2s .com
 * 
 * @param inputStream
 * @return String of XML
 * @throws CamelException
 */
public String asStringTidyMarkup(InputStream inputStream) throws CamelException {

    XMLReader parser = createTagSoupParser();
    StringWriter w = new StringWriter();
    parser.setContentHandler(createContentHandler(w));

    try {
        parser.parse(new InputSource(inputStream));
        return w.toString();

    } catch (Exception e) {
        throw new CamelException("Failed to convert the HTML to tidy Markup", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            LOG.warn("Failed to close the inputStream");
        }
    }
}

From source file:org.apache.cayenne.configuration.XMLDataChannelDescriptorLoader.java

@Override
public ConfigurationTree<DataChannelDescriptor> load(Resource configurationResource)
        throws ConfigurationException {

    if (configurationResource == null) {
        throw new NullPointerException("Null configurationResource");
    }/*ww w .jav a 2  s  . co  m*/

    URL configurationURL = configurationResource.getURL();

    logger.info("Loading XML configuration resource from " + configurationURL);

    DataChannelDescriptor descriptor = new DataChannelDescriptor();
    descriptor.setConfigurationSource(configurationResource);
    descriptor.setName(nameMapper.configurationNodeName(DataChannelDescriptor.class, configurationResource));

    DataChannelHandler rootHandler;

    InputStream in = null;

    try {
        in = configurationURL.openStream();
        XMLReader parser = Util.createXmlReader();

        rootHandler = new DataChannelHandler(descriptor, parser);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ioex) {
            logger.info("failure closing input stream for " + configurationURL + ", ignoring", ioex);
        }
    }

    // TODO: andrus 03/10/2010 - actually provide load failures here...
    return new ConfigurationTree<DataChannelDescriptor>(descriptor, null);
}

From source file:org.apache.cayenne.map.MapLoader.java

/**
 * Loads a DataMap from XML input source.
 *///from   w w  w  .j  av a2s.co m
public synchronized DataMap loadDataMap(InputSource src) throws CayenneRuntimeException {
    if (src == null) {
        throw new NullPointerException("Null InputSource.");
    }

    try {
        String mapName = mapNameFromLocation(src.getSystemId());
        dataMap = new DataMap(mapName);
        XMLReader parser = Util.createXmlReader();

        parser.setContentHandler(this);
        parser.setErrorHandler(this);
        parser.parse(src);
    } catch (SAXException e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Wrong DataMap format, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    } catch (Exception e) {
        dataMap = null;
        throw new CayenneRuntimeException(
                "Error loading DataMap, last processed tag: " + constructCurrentStateString(),
                Util.unwindException(e));
    }
    return dataMap;
}

From source file:org.apache.cayenne.project.upgrade.v6.XMLDataChannelDescriptorLoader_V3_0_0_1.java

List<DataChannelDescriptor> load(Resource configurationSource) throws ConfigurationException {

    if (configurationSource == null) {
        throw new NullPointerException("Null configurationSource");
    }//from w w w .  ja  v  a 2s. co m

    URL configurationURL = configurationSource.getURL();

    List<DataChannelDescriptor> domains = new ArrayList<>();

    try (InputStream in = configurationURL.openStream();) {

        XMLReader parser = Util.createXmlReader();

        DomainsHandler rootHandler = new DomainsHandler(configurationSource, domains, parser);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    }

    return domains;
}

From source file:org.apache.cayenne.project.upgrade.v6.XMLDataSourceInfoLoader_V3_0_0_1.java

DataSourceInfo load(Resource configurationSource) {
    if (configurationSource == null) {
        throw new NullPointerException("Null configurationSource");
    }//from  w w w  .j a  v  a2  s. com

    URL configurationURL = configurationSource.getURL();

    DataSourceInfo dataSourceInfo = new DataSourceInfo();

    InputStream in = null;

    try {
        in = configurationURL.openStream();
        XMLReader parser = Util.createXmlReader();

        DriverHandler rootHandler = new DriverHandler(parser, dataSourceInfo);
        parser.setContentHandler(rootHandler);
        parser.setErrorHandler(rootHandler);
        parser.parse(new InputSource(in));
    } catch (Exception e) {
        throw new ConfigurationException("Error loading configuration from %s", e, configurationURL);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ioex) {
            logger.info("failure closing input stream for " + configurationURL + ", ignoring", ioex);
        }
    }

    return dataSourceInfo;
}

From source file:org.apache.cocoon.xml.dom.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 #getLocation(Element)} method.
 *
 * @param inputSource the inputSource to read the document from
 *///from w  w w  .j ava2  s  . c o m
public static Document parse(InputSource inputSource)
        throws SAXException, SAXNotSupportedException, IOException {
    try {
        final XMLReader parser = saxFactory.newSAXParser().getXMLReader();
        final DOMBuilder builder = new DOMBuilder();

        // Enhance the sax stream with location information
        final ContentHandler locationHandler = new LocationAttributes.Pipe(builder);
        parser.setContentHandler(locationHandler);

        parser.parse(inputSource);

        return builder.getDocument();
    } catch (ParserConfigurationException pce) {
        throw new SAXException(pce);
    }
}

From source file:org.apache.fop.fotreetest.FOTreeTestCase.java

/**
 * Runs a test./*from   w  w  w  .  ja  v a 2 s .  c o m*/
 * @throws Exception if a test or FOP itself fails
 */
@Test
public void runTest() throws Exception {
    try {
        ResultCollector collector = ResultCollector.getInstance();
        collector.reset();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Resetting values modified by processing instructions
        fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
                FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
        fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);

        FOUserAgent ua = fopFactory.newFOUserAgent();
        ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
        ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
        ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName()));

        // Used to set values in the user agent through processing instructions
        reader = new PIListener(reader, ua);

        Fop fop = fopFactory.newFop(ua);

        reader.setContentHandler(fop.getDefaultHandler());
        reader.setDTDHandler(fop.getDefaultHandler());
        reader.setErrorHandler(fop.getDefaultHandler());
        reader.setEntityResolver(fop.getDefaultHandler());
        try {
            reader.parse(testFile.toURI().toURL().toExternalForm());
        } catch (Exception e) {
            collector.notifyError(e.getLocalizedMessage());
            throw e;
        }

        List<String> results = collector.getResults();
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                System.out.println((String) results.get(i));
            }
            throw new IllegalStateException((String) results.get(0));
        }
    } catch (Exception e) {
        org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName());
        throw e;
    }
}