List of usage examples for org.xml.sax XMLReader setFeature
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;
From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java
private XRoadSoapHandler handleSoap(Writer writer, InputStream inputStream) throws Exception { try (BufferedWriter out = new BufferedWriter(writer)) { XRoadSoapHandler handler = new XRoadSoapHandler(out); SAXParser saxParser = PARSER_FACTORY.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, handler); // ensure both builtin entities and character entities are reported to the parser xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true); xmlReader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true); saxParser.parse(inputStream, handler); return handler; } catch (SAXException ex) { throw new SOAPException(ex); }//from w w w.j a v a 2s. co m }
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/* w ww . j a v a2 s . c o m*/ */ 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:net.sf.joost.stx.Processor.java
/** * Create an <code>XMLReader</code> object (a SAX Parser) * @throws SAXException if a SAX Parser couldn't be created *///from w ww. j a v a2 s . c o m public static XMLReader createXMLReader() throws SAXException { // Using pure SAX2, not JAXP XMLReader reader = null; try { // try default parser implementation reader = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { String prop = System.getProperty("org.xml.sax.driver"); if (prop != null) { // property set, but still failed throw new SAXException("Can't create XMLReader for class " + prop); // leave the method here } // try another SAX implementation String PARSER_IMPLS[] = { "org.apache.xerces.parsers.SAXParser", // Xerces "org.apache.crimson.parser.XMLReaderImpl", // Crimson "gnu.xml.aelfred2.SAXDriver" // Aelfred nonvalidating }; for (int i = 0; i < PARSER_IMPLS.length; i++) { try { reader = XMLReaderFactory.createXMLReader(PARSER_IMPLS[i]); break; // for (...) } catch (SAXException e1) { } // continuing } if (reader == null) { throw new SAXException("Can't find SAX parser implementation.\n" + "Please specify a parser class via the system property " + "'org.xml.sax.driver'"); } } // set features and properties that have been put // into the system properties (e.g. via command line) Properties sysProps = System.getProperties(); for (Enumeration e = sysProps.propertyNames(); e.hasMoreElements();) { String propKey = (String) e.nextElement(); if (propKey.startsWith(EXTERN_SAX_FEATURE_PREFIX)) { reader.setFeature(propKey.substring(EXTERN_SAX_FEATURE_PREFIX.length()), Boolean.parseBoolean(sysProps.getProperty(propKey))); continue; } if (propKey.startsWith(EXTERN_SAX_PROPERTY_PREFIX)) { reader.setProperty(propKey.substring(EXTERN_SAX_PROPERTY_PREFIX.length()), sysProps.getProperty(propKey)); continue; } } if (DEBUG) log.debug("Using " + reader.getClass().getName()); return reader; }
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult, * DOMResult and StreamResult//ww w.j a v a 2 s .co m * * @param xmlSource A <code>Source</code> * @param result A <code>Result</code> * @throws TransformerException */ public void transform(Source xmlSource, Result result) throws TransformerException { StxEmitter out = null; SAXSource saxSource = null; // should be synchronized synchronized (reentryGuard) { if (DEBUG) log.debug("perform transformation from " + "xml-source(SAXSource, DOMSource, StreamSource) " + "to SAXResult, DOMResult or StreamResult"); try { // init StxEmitter out = TrAXHelper.initStxEmitter(result, processor, null); out.setSystemId(result.getSystemId()); this.processor.setContentHandler(out); this.processor.setLexicalHandler(out); // register ErrorListener if (this.errorListener != null) { this.processor.setErrorListener(errorListener); } // construct from source a SAXSource saxSource = TrAXHelper.getSAXSource(xmlSource, errorListener); InputSource isource = saxSource.getInputSource(); if (isource != null) { if (DEBUG) log.debug("perform transformation"); if (saxSource.getXMLReader() != null) { // should not be an DOMSource if (xmlSource instanceof SAXSource) { XMLReader xmlReader = ((SAXSource) xmlSource).getXMLReader(); /** * URIs for Identifying Feature Flags and Properties : * There is no fixed set of features or properties * available for SAX2, except for two features that all XML * parsers must support. Implementors are free to define * new features and properties as needed, using URIs to * identify them. * * All XML readers are required to recognize the * "http://xml.org/sax/features/namespaces" and the * "http://xml.org/sax/features/namespace-prefixes" * features (at least to get the feature values, if not set * them) and to support a true value for the namespaces * property and a false value for the namespace-prefixes * property. These requirements ensure that all SAX2 XML * readers can provide the minimal required Namespace * support for higher-level specs such as RDF, XSL, XML * Schemas, and XLink. XML readers are not required to * recognize or support any other features or any * properties. * * For the complete list of standard SAX2 features and * properties, see the {@link org.xml.sax} Package * Description. */ if (xmlReader != null) { try { // set the required // "http://xml.org/sax/features/namespaces" Feature xmlReader.setFeature(FEAT_NS, true); // set the required // "http://xml.org/sax/features/namespace-prefixes" // Feature xmlReader.setFeature(FEAT_NSPREFIX, false); // maybe there would be other features } catch (SAXException sE) { getErrorListener().warning(new TransformerException(sE.getMessage(), sE)); } } } // set the the SAXSource as the parent of the STX-Processor this.processor.setParent(saxSource.getXMLReader()); } // perform transformation this.processor.parse(isource); } else { TransformerException tE = new TransformerException( "InputSource is null - could not perform transformation"); getErrorListener().fatalError(tE); } // perform result performResults(result, out); } catch (SAXException ex) { TransformerException tE; Exception emb = ex.getException(); if (emb instanceof TransformerException) { tE = (TransformerException) emb; } else { tE = new TransformerException(ex.getMessage(), ex); } getErrorListener().fatalError(tE); } catch (IOException ex) { // will this ever happen? getErrorListener().fatalError(new TransformerException(ex.getMessage(), ex)); } } }
From source file:com.jiahuan.svgmapview.core.helper.map.SVGParser.java
static SVG parse(InputSource data, SVGHandler handler) throws SVGParseException { try {//from ww w . ja v a2s. c om final Picture picture = new Picture(); handler.setPicture(picture); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(handler); xr.setFeature("http://xml.org/sax/features/validation", false); if (DISALLOW_DOCTYPE_DECL) { try { xr.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); } catch (SAXNotRecognizedException e) { DISALLOW_DOCTYPE_DECL = false; } } xr.parse(data); SVG result = new SVG(picture, handler.bounds); // Skip bounds if it was an empty pic if (!Float.isInfinite(handler.limits.top)) { result.setLimits(handler.limits); } return result; } catch (Exception e) { Log.e(TAG, "Failed to parse SVG.", e); throw new SVGParseException(e); } }
From source file:net.unicon.academus.apps.XHTMLFilter.java
public static void filterHTML(InputSource in, OutputStream os, XHTMLFilterConfig config) { try {//from ww w . ja v a2 s .com XMLReader r = new Parser(); Writer w = new OutputStreamWriter(os, "UTF-8"); r.setFeature(Parser.ignoreBogonsFeature, true); r.setContentHandler(new XHTMLFilter(w, config)); r.parse(in); } catch (Exception e) { log.error("Unable to parse the given HTML: " + e.getMessage(), e); throw new RuntimeException("Unable to parse the given HTML: " + e.getMessage(), e); } }
From source file:nl.nn.adapterframework.validation.XercesXmlValidator.java
/** * Validate the XML string/*from w w w. j av a2s .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
/** Get a SAX parser instance from the JAXP factory. * * @return a SAXParser instance.//from w w w . j a va 2 s . c om */ public static synchronized SAXParser getSAXParser() { if (enableParserReuse && !saxParsers.empty()) { return (SAXParser) saxParsers.pop(); } try { SAXParser parser = saxFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // parser.getParser().setEntityResolver(new DefaultEntityResolver()); // The above commented line and the following line are added // for preventing XXE (bug #14105). // We may need to uncomment the deprecated setting // in case that it is considered necessary. try { reader.setEntityResolver(new DefaultEntityResolver()); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); return parser; } catch (ParserConfigurationException e) { log.error(Messages.getMessage("parserConfigurationException00"), e); return null; } catch (SAXException se) { log.error(Messages.getMessage("SAXException00"), se); return null; } }
From source file:org.apache.camel.dataformat.tagsoup.TidyMarkupDataFormat.java
/** * Create the tagSoup Parser//from www. j a v a2 s . c om * * @return * @throws CamelException */ protected XMLReader createTagSoupParser() throws CamelException { XMLReader reader = new Parser(); try { reader.setFeature(Parser.namespacesFeature, false); reader.setFeature(Parser.namespacePrefixesFeature, false); /* * set each parser feature that the user may have supplied. * http://www.saxproject.org/apidoc/org/xml/sax/package-summary.html * http://home.ccil.org/~cowan/XML/tagsoup/#properties */ if (getParserFeatures() != null) { for (Entry<String, Boolean> e : getParserFeatures().entrySet()) { reader.setFeature(e.getKey(), e.getValue()); } } /* * set each parser feature that the user may have supplied. {@link * http://home.ccil.org/~cowan/XML/tagsoup/#properties} */ if (getParserPropeties() != null) { for (Entry<String, Object> e : getParserPropeties().entrySet()) { reader.setProperty(e.getKey(), e.getValue()); } } /* * default the schema to HTML */ if (this.getParsingSchema() != null) { reader.setProperty(Parser.schemaProperty, getParsingSchema()); } } catch (Exception e) { throw new IllegalArgumentException("Problem configuring the parser", e); } return reader; }
From source file:org.apache.ode.bpel.compiler.bom.BpelObjectFactory.java
/** * Parse a BPEL process found at the input source. * @param isrc input source.//from ww w . j a v a 2s. co m * @return * @throws SAXException */ public Process parse(InputSource isrc, URI systemURI) throws IOException, SAXException { XMLReader _xr = XMLParserUtils.getXMLReader(); LocalEntityResolver resolver = new LocalEntityResolver(); resolver.register(Bpel11QNames.NS_BPEL4WS_2003_03, getClass().getResource("/bpel4ws_1_1-fivesight.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0, getClass().getResource("/wsbpel_main-draft-Apr-29-2006.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT, getClass().getResource("/ws-bpel_abstract_common_base.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC, getClass().getResource("/ws-bpel_executable.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_PLINK, getClass().getResource("/ws-bpel_plnktype.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_SERVREF, getClass().getResource("/ws-bpel_serviceref.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_VARPROP, getClass().getResource("/ws-bpel_varprop.xsd")); resolver.register(XML, getClass().getResource("/xml.xsd")); resolver.register(WSDL, getClass().getResource("/wsdl.xsd")); resolver.register(Bpel20QNames.NS_WSBPEL_PARTNERLINK_2004_03, getClass().getResource("/wsbpel_plinkType-draft-Apr-29-2006.xsd")); _xr.setEntityResolver(resolver); Document doc = DOMUtils.newDocument(); _xr.setContentHandler(new DOMBuilderContentHandler(doc)); _xr.setFeature("http://xml.org/sax/features/namespaces", true); _xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true); _xr.setFeature("http://xml.org/sax/features/validation", true); XMLParserUtils.addExternalSchemaURL(_xr, Bpel11QNames.NS_BPEL4WS_2003_03, Bpel11QNames.NS_BPEL4WS_2003_03); XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0, Bpel20QNames.NS_WSBPEL2_0); XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC, Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC); XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT, Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT); boolean strict = Boolean .parseBoolean(System.getProperty("org.apache.ode.compiler.failOnValidationErrors", "false")); BOMSAXErrorHandler errorHandler = new BOMSAXErrorHandler(strict); _xr.setErrorHandler(errorHandler); _xr.parse(isrc); if (strict) { if (!errorHandler.wasOK()) { throw new SAXException("Validation errors during parsing"); } } else { if (!errorHandler.wasOK()) { __log.warn( "Validation errors during parsing, continuing due to -Dorg.apache.ode.compiler.failOnValidationErrors=false switch"); } } return (Process) createBpelObject(doc.getDocumentElement(), systemURI); }