List of usage examples for org.xml.sax XMLReader setContentHandler
public void setContentHandler(ContentHandler handler);
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);// www . j ava 2 s.co m 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/*www . 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.axis.utils.XMLUtils.java
/** Return a SAX parser for reuse. * @param parser A SAX parser that is available for reuse *//* w ww. j a va2 s . c o m*/ public static void releaseSAXParser(SAXParser parser) { if (!tryReset || !enableParserReuse) return; //Free up possible ref. held by past contenthandler. try { XMLReader xmlReader = parser.getXMLReader(); if (null != xmlReader) { xmlReader.setContentHandler(doNothingContentHandler); xmlReader.setDTDHandler(doNothingContentHandler); try { xmlReader.setEntityResolver(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } try { xmlReader.setErrorHandler(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set ErrorHandler on DocumentBuilder", t); } synchronized (XMLUtils.class) { saxParsers.push(parser); } } else { tryReset = false; } } catch (org.xml.sax.SAXException e) { tryReset = false; } }
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 a2 s . com*/ 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 v a2 s. c om * * @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.camel.dataformat.tagsoup.TidyMarkupDataFormat.java
/** * Return the HTML Markup as an {@link org.w3c.dom.Node} * // w ww .ja v a 2 s . c o m * @param inputStream * The input Stream to convert * @return org.w3c.dom.Node The HTML Markup as a DOM Node * @throws CamelException */ public Node asNodeTidyMarkup(InputStream inputStream) throws CamelException { XMLReader parser = createTagSoupParser(); StringWriter w = new StringWriter(); parser.setContentHandler(createContentHandler(w)); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(parser, new InputSource(inputStream)), result); return result.getNode(); } catch (Exception e) { throw new CamelException("Failed to convert the HTML to tidy Markup", e); } }
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"); }// www . j a v a 2s .c om 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 www . j av a 2 s . c o 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. j a v a 2 s .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"); }// w w w . j ava 2 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; }