List of usage examples for org.xml.sax XMLReader setErrorHandler
public void setErrorHandler(ErrorHandler handler);
From source file:com.silverpeas.importExport.control.ImportExport.java
/** * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre. * * @param xmlFileName le fichier xml interprt par Castor * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML Castor * @throws ImportExportException/*from w ww . j a v a 2 s . com*/ */ SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_ENTER_METHOD", "xmlFileName = " + xmlFileName); try { InputSource xmlInputSource = new InputSource(xmlFileName); String xsdPublicId = settings.getString("xsdPublicId"); String xsdSystemId = settings.getString("xsdDefaultSystemId"); // Load and parse default XML schema for import/export SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema", "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", null); Schema schema = schemaFactory.newSchema(new StreamSource(xsdSystemId)); // Create an XML parser for loading XML import file SAXParserFactory factory = SAXParserFactory .newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null); factory.setValidating(false); factory.setNamespaceAware(true); factory.setSchema(schema); SAXParser parser = factory.newSAXParser(); // First try to determine to load the XML file using the default // XML-Schema ImportExportErrorHandler errorHandler = new ImportExportErrorHandler(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); try { xmlReader.parse(xmlInputSource); } catch (SAXException ex) { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("XML File ")).append(xmlFileName) .append(" is not valid according to default schema").toString()); // If case the default schema is not the one specified by the // XML import file, try to get the right XML-schema and // namespace (this is done by parsing without validation) ImportExportNamespaceHandler nsHandler = new ImportExportNamespaceHandler(); factory.setSchema(null); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setContentHandler(nsHandler); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlReader.parse(xmlInputSource); // If OK, extract the name and location of the schema String nsSpec = nsHandler.getNsSpec(); if (nsSpec == null || xsdPublicId.equals(nsSpec)) { throw ex; } String nsVersion = extractUriNameIndex(nsSpec); if (nsVersion.length() == 0) { throw ex; } String altXsdSystemId = settings.getStringWithParam("xsdSystemId", nsVersion); if ((altXsdSystemId == null) || (altXsdSystemId.equals(xsdSystemId))) { throw ex; } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("Trying again using schema specification located at ")) .append(altXsdSystemId).toString()); // Try again to load, parse and validate the XML import file, // using the new schema specification schema = schemaFactory.newSchema(new StreamSource(altXsdSystemId)); factory.setSchema(schema); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); xmlReader.parse(xmlInputSource); } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "XML Validation complete"); // Mapping file for Castor String mappingDir = settings.getString("mappingDir"); String mappingFileName = settings.getString("importExportMapping"); String mappingFile = mappingDir + mappingFileName; Mapping mapping = new Mapping(); // Load mapping and instantiate a Unmarshaller mapping.loadMapping(mappingFile); Unmarshaller unmar = new Unmarshaller(SilverPeasExchangeType.class); unmar.setMapping(mapping); unmar.setValidation(false); // Unmarshall the process model SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmar.unmarshal(xmlInputSource); SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "Unmarshalling complete"); return silverpeasExchange; } catch (MappingException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (MarshalException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_UNMARSHALLING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (ValidationException ve) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve); } catch (IOException ioe) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + ioe.getLocalizedMessage(), ioe); } catch (ParserConfigurationException ex) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ex.getLocalizedMessage(), ex); } catch (SAXNotRecognizedException snre) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snre.getLocalizedMessage(), snre); } catch (SAXNotSupportedException snse) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snse.getLocalizedMessage(), snse); } catch (SAXException se) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + se.getLocalizedMessage(), se); } }
From source file:se.lu.nateko.edca.svc.GeoHelper.java
/** * Parses an XML response from a WFS Transaction (Insert) request and * reports if the response contains a Service Exception. * @param xmlResponse String containing the XML response from a DescribeFeatureType request. *///from ww w . j a v a 2 s . co m protected boolean parseXMLResponse(InputStream xmlResponse) { Log.d(TAG, "parseXMLResponse(InputStream) called."); mInsertedIDs = new ArrayList<Long>(); try { SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory. spfactory.setValidating(false); // Tell the factory not to make validating parsers. SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser. XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler. XMLEventHandler xmlEventHandler = new XMLEventHandler(); xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use. xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls. InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader. xmlReader.parse(source); // Start parsing the XML. } catch (Exception e) { Log.e(TAG, e.toString()); return false; } return true; }
From source file:com.farmafene.commons.cas.ValidateTGT.java
/** * Retrieve the text for a specific element (when we know there is only * one).//from w ww.j av a2s . c o m * * @param xmlAsString * the xml response * @param element * the element to look for * @return the text value of the element. */ private String getTextForElement(final String xmlAsString, final String element) { final XMLReader reader = getXmlReader(); final StringBuffer buffer = new StringBuffer(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { logger.error("", e); return null; } return buffer.toString(); }
From source file:net.sf.joost.trax.TrAXFilter.java
/** * Parses the <code>InputSource</code> * @param input A <code>InputSource</code> object. * @throws SAXException//from w w w. j a va 2s .c om * @throws IOException */ public void parse(InputSource input) throws SAXException, IOException { Transformer transformer = null; if (DEBUG) { if (log.isDebugEnabled()) log.debug("parsing InputSource " + input.getSystemId()); } try { // get a new Transformer transformer = this.templates.newTransformer(); if (transformer instanceof TransformerImpl) { this.processor = ((TransformerImpl) transformer).getStxProcessor(); } else { String msg = "An error is occured, because the given transformer is " + "not an instance of TransformerImpl"; if (log != null) log.fatal(msg); else System.err.println("Fatal error - " + msg); } XMLReader parent = this.getParent(); if (parent == null) { parent = XMLReaderFactory.createXMLReader(); setParent(parent); } ContentHandler handler = this.getContentHandler(); if (handler == null) { handler = parent.getContentHandler(); } if (handler == null) { throw new SAXException("no ContentHandler registered"); } //init StxEmitter StxEmitter out = null; //SAX specific Implementation out = new SAXEmitter(handler); if (this.processor != null) { this.processor.setContentHandler(out); this.processor.setLexicalHandler(out); } else { throw new SAXException("Joost-Processor is not correct configured."); } if (parent == null) { throw new SAXException("No parent for filter"); } parent.setContentHandler(this.processor); parent.setProperty("http://xml.org/sax/properties/lexical-handler", this.processor); parent.setEntityResolver(this); parent.setDTDHandler(this); parent.setErrorHandler(this); parent.parse(input); } catch (TransformerConfigurationException tE) { try { configErrListener.fatalError(tE); } catch (TransformerConfigurationException innerE) { throw new SAXException(innerE.getMessage(), innerE); } } catch (SAXException sE) { try { configErrListener.fatalError(new TransformerConfigurationException(sE.getMessage(), sE)); } catch (TransformerConfigurationException innerE) { throw new SAXException(innerE.getMessage(), innerE); } } catch (IOException iE) { try { configErrListener.fatalError(new TransformerConfigurationException(iE.getMessage(), iE)); } catch (TransformerConfigurationException innerE) { throw new IOException(innerE.getMessage()); } } }
From source file:edwardawebb.queueman.classes.NetFlix.java
public boolean getNewETag(int queueType, int discPosition) { URL QueueUrl = null;//from w w w. j a v a 2 s . c o m DefaultHandler myQueueHandler = null; boolean result = false; //start index is 0 based, so step the true position down one String expanders = "?max_results=" + 1 + "&start_index=" + (discPosition - 1); InputStream xml = null; try { switch (queueType) { case NetFlixQueue.QUEUE_TYPE_INSTANT: QueueUrl = new URL( "http://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders); myQueueHandler = new InstantETagHandler(); break; case NetFlixQueue.QUEUE_TYPE_DISC: QueueUrl = new URL( "http://api.netflix.com/users/" + user.getUserId() + "/queues/disc/available" + expanders); myQueueHandler = new DiscETagHandler(); break; } setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); NetFlix.oaconsumer.sign(request); request.connect(); lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage(); if (request.getResponseCode() == 200) { xml = request.getInputStream(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(myQueueHandler); //our custom handler will throw an exception when he gets what he want, interupting the full parse ErrorProcessor errors = new ErrorProcessor(); xr.setErrorHandler(errors); xr.parse(new InputSource(xml)); result = true; } } catch (ParserConfigurationException e) { reportError(e, lastResponseMessage); } catch (SAXException e) { reportError(e, lastResponseMessage); } catch (IOException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "IO Error connecting to NetFlix queue") } catch (OAuthMessageSignerException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Unable to Sign request - token invalid") } catch (OAuthExpectationFailedException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Expectation failed") } return result; }
From source file:Writer.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();/*w ww. ja v a2 s. c om*/ System.exit(1); } // variables Writer writer = null; XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; boolean canonical = DEFAULT_CANONICAL; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); e.printStackTrace(System.err); } } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("xd")) { externalDTD = option.equals("xd"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equalsIgnoreCase("c")) { canonical = option.equals("c"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); e.printStackTrace(System.err); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // setup writer if (writer == null) { writer = new Writer(); try { writer.setOutput(System.out, "UTF8"); } catch (UnsupportedEncodingException e) { System.err.println("error: Unable to set output. Exiting."); System.exit(1); } } // set parser parser.setContentHandler(writer); parser.setErrorHandler(writer); try { parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer); } catch (SAXException e) { // ignore } // parse file writer.setCanonical(canonical); try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:net.sf.joost.stx.Processor.java
/** * Constructs a new <code>Processor</code> instance by parsing an * STX transformation sheet./*from w ww . j a v a 2s .c o m*/ * @param reader the parser that is used for reading the transformation * sheet * @param src the source for the STX transformation sheet * @param pContext a parse context * @throws IOException if <code>src</code> couldn't be retrieved * @throws SAXException if a SAX parser couldn't be created */ public Processor(XMLReader reader, InputSource src, ParseContext pContext) throws IOException, SAXException { if (reader == null) reader = createXMLReader(); // create a Parser for parsing the STX transformation sheet Parser stxParser = new Parser(pContext); reader.setContentHandler(stxParser); reader.setErrorHandler(pContext.getErrorHandler()); // parse the transformation sheet reader.parse(src); init(stxParser.getTransformNode()); // re-use this XMLReader for processing setParent(reader); }
From source file:nl.b3p.ogc.utils.OgcWfsClient.java
public static AnyNode xmlStringToAnyNode(String xml) throws Exception { AnyNode anyNode = null;/*w ww.j a v a2 s. c om*/ try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); org.exolab.castor.xml.util.SAX2ANY handler = new org.exolab.castor.xml.util.SAX2ANY(); IgnoreEntityResolver r = new IgnoreEntityResolver(); reader.setEntityResolver(r); reader.setContentHandler(handler); reader.setErrorHandler(handler); InputSource source = new InputSource(new StringReader(xml)); reader.parse(source); anyNode = handler.getStartingNode(); } catch (Exception e) { log.error("error", e); } return anyNode; }
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);//from www . ja va2 s . c o 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//from w ww. j a 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; }