下面列出了java.io.StringBufferInputStream#javax.xml.parsers.SAXParserFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) {
SAXParserFactory factory = SAXParserFactory.newInstance();
String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
try {
boolean securityOn = !xmlSecurityDisabled(disableSecurity);
factory.setFeature(featureToSet, securityOn);
factory.setNamespaceAware(true);
if (securityOn) {
featureToSet = DISALLOW_DOCTYPE_DECL;
factory.setFeature(featureToSet, true);
featureToSet = EXTERNAL_GE;
factory.setFeature(featureToSet, false);
featureToSet = EXTERNAL_PE;
factory.setFeature(featureToSet, false);
featureToSet = LOAD_EXTERNAL_DTD;
factory.setFeature(featureToSet, false);
}
} catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[]{factory.getClass().getName()});
}
return factory;
}
private void parseXmlString(String file) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XmlAppHandler handler = new XmlAppHandler();
xr.setContentHandler(handler);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(file));
xr.parse(is);
server = handler.getServers();
app = handler.getApp();
} catch (IOException | SAXException | ParserConfigurationException e) {
Logger.printException(e);
}
}
private static SVG parse(InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode,
int targetWidth, int targetHeight) throws SVGParseException {
// Util.debug("Parsing SVG...");
try {
long start = System.currentTimeMillis();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
final Picture picture = new Picture();
SVGHandler handler = new SVGHandler(picture, targetWidth, targetHeight);
handler.setColorSwap(searchColor, replaceColor);
handler.setWhiteMode(whiteMode);
xr.setContentHandler(handler);
xr.parse(new InputSource(in));
// Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + " millis.");
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) {
throw new SVGParseException(e);
}
}
public void parseFile(String filePath) {
String myerror = "";
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
InputSource inp = new InputSource (new FileReader(filePath));
parser.parse(inp, this);
} catch (SAXParseException err) {
myerror = "\n** Parsing error" + ", line " + err.getLineNumber()
+ ", uri " + err.getSystemId();
myerror += "\n" + err.getMessage();
System.out.println("myerror = " + myerror);
} catch (SAXException e) {
Exception x = e;
if (e.getException() != null)
x = e.getException();
myerror += "\nSAXException --" + x.getMessage();
System.out.println("myerror = " + myerror);
} catch (Exception eee) {
eee.printStackTrace();
myerror += "\nException --" + eee.getMessage();
System.out.println("myerror = " + myerror);
}
}
public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) {
SAXParserFactory factory = SAXParserFactory.newInstance();
String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
try {
boolean securityOn = !isXMLSecurityDisabled(disableSecurity);
factory.setFeature(featureToSet, securityOn);
factory.setNamespaceAware(true);
if (securityOn) {
featureToSet = DISALLOW_DOCTYPE_DECL;
factory.setFeature(featureToSet, true);
featureToSet = EXTERNAL_GE;
factory.setFeature(featureToSet, false);
featureToSet = EXTERNAL_PE;
factory.setFeature(featureToSet, false);
featureToSet = LOAD_EXTERNAL_DTD;
factory.setFeature(featureToSet, false);
}
} catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[]{factory.getClass().getName()});
}
return factory;
}
/**
* Testing set MaxOccursLimit to 10000 in the secure processing enabled for
* SAXParserFactory.
*
* @throws Exception If any errors occur.
*/
@Test
public void testMaxOccurLimitPos() throws Exception {
String schema_file = XML_DIR + "toys.xsd";
String xml_file = XML_DIR + "toys.xml";
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setFeature(FEATURE_SECURE_PROCESSING, true);
setSystemProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000));
SAXParser parser = factory.newSAXParser();
parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file));
try (InputStream is = new FileInputStream(xml_file)) {
MyErrorHandler eh = new MyErrorHandler();
parser.parse(is, eh);
assertFalse(eh.isAnyError());
}
}
/**
* Error Handler to capture all error events to output file. Verifies the
* output file is same as golden file.
*
* @throws Exception If any errors occur.
*/
@Test
public void testEHFatal() throws Exception {
String outputFile = USER_DIR + "EHFatal.out";
String goldFile = GOLDEN_DIR + "EHFatalGF.out";
String xmlFile = XML_DIR + "invalid.xml";
try(MyErrorHandler eHandler = new MyErrorHandler(outputFile);
FileInputStream instream = new FileInputStream(xmlFile)) {
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(eHandler);
InputSource is = new InputSource(instream);
xmlReader.parse(is);
fail("Parse should throw SAXException");
} catch (SAXException expected) {
// This is expected.
}
// Need close the output file before we compare it with golden file.
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Set the xslt resource.
*
* @param xsltresource
* an Input Source to the XSLT
* @throws Exception
*/
public void setXslt(InputSource xsltresource) throws Exception
{
if ( saxParserFactory == null) {
saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
}
TemplatesHandler th = factory.newTemplatesHandler();
String systemId = xsltresource.getSystemId();
th.setSystemId(systemId);
SAXParser parser = saxParserFactory.newSAXParser();
XMLReader xr = parser.getXMLReader();
xr.setContentHandler(th);
xr.parse(xsltresource);
templates = th.getTemplates();
}
public void parseDocument(URL oscarURL) {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
InputStream is = new BufferedInputStream(oscarURL.openStream());
sp.parse(is, this);
System.out.println("done parsing count="+count);
is.close();
} catch (SAXException se) {
se.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
private XMLReader createReader() throws SAXException {
try {
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setValidating(true);
pfactory.setNamespaceAware(true);
// Enable schema validation
SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));
return pfactory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException ex) {
throw new SAXException(ex);
}
}
/**
* Create a <code>SAXParser</code> based on the underlying
* <code>Xerces</code> version.
* @param properties parser specific properties/features
* @return an XML Schema/DTD enabled <code>SAXParser</code>
*/
public static SAXParser newSAXParser(Properties properties)
throws ParserConfigurationException,
SAXException,
SAXNotSupportedException {
SAXParserFactory factory =
(SAXParserFactory)properties.get("SAXParserFactory");
if (versionNumber == null){
versionNumber = getXercesVersion();
version = new Float( versionNumber ).floatValue();
}
// Note: 2.2 is completely broken (with XML Schema).
if (version > 2.1) {
configureXerces(factory);
return factory.newSAXParser();
} else {
SAXParser parser = factory.newSAXParser();
configureOldXerces(parser,properties);
return parser;
}
}
public void init() throws ComponentNotReadyException {
//create mapping DOM
Document mappingDOM;
try {
mappingDOM = createMappingDOM(rawMapping);
createMapping(mappingDOM);
} catch (XMLConfigurationException e) {
throw new ComponentNotReadyException(e);
}
// create new sax factory
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(validate);
initXmlFeatures(factory);
try {
// create new sax parser
parser = factory.newSAXParser();
} catch (Exception ex) {
throw new ComponentNotReadyException(ex);
}
}
void parse() throws SAXException {
String xml = "<data>\n<broken/>\u0000</data>";
try {
InputSource is = new InputSource(new StringReader(xml));
is.setSystemId("file:///path/to/some.xml");
// notice that exception thrown here doesn't include the line number
// information when reported by JVM -- CR6889654
SAXParserFactory.newInstance().newSAXParser().parse(is, new DefaultHandler());
} catch (SAXException e) {
// notice that this message isn't getting displayed -- CR6889649
throw new SAXException(MSG, e);
} catch (ParserConfigurationException pce) {
} catch (IOException ioe) {
}
}
/**
* Checks an xml string is well formed.
*
* @param is
* inputstream
* @return true if the xml is well formed.
*/
public static boolean isXMLWellFormed( InputStream is ) throws KettleException {
boolean retval = false;
try {
SAXParserFactory factory = XMLParserFactoryProducer.createSecureSAXParserFactory();
XMLTreeHandler handler = new XMLTreeHandler();
// Parse the input.
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( is, handler );
retval = true;
} catch ( Exception e ) {
throw new KettleException( e );
}
return retval;
}
public static PomModel parse(String path, InputStream is) {
MinimalPomParser handler = new MinimalPomParser();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating( false );
factory.setNamespaceAware( false );
SAXParser parser = factory.newSAXParser();
parser.parse( is, handler );
} catch (Exception e) {
throw new RuntimeException("Unable to parse File '" + path + "'", e);
}
return handler.getPomModel();
}
public void loadLevelFromStream(final InputStream pInputStream) throws IOException {
try{
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
final XMLReader xr = sp.getXMLReader();
this.onBeforeLoadLevel();
final LevelParser levelParser = new LevelParser(this.mDefaultEntityLoader, this.mEntityLoaders);
xr.setContentHandler(levelParser);
xr.parse(new InputSource(new BufferedInputStream(pInputStream)));
this.onAfterLoadLevel();
} catch (final SAXException se) {
Debug.e(se);
/* Doesn't happen. */
} catch (final ParserConfigurationException pe) {
Debug.e(pe);
/* Doesn't happen. */
} finally {
StreamUtils.close(pInputStream);
}
}
public static Object unmarshal(Reader reader, String packageName) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
spf.setNamespaceAware(true);
Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(reader));
JAXBContext jc = JAXBContext.newInstance(packageName);
Unmarshaller um = jc.createUnmarshaller();
return ((javax.xml.bind.JAXBElement)um.unmarshal(xmlSource)).getValue();
} catch (Exception ex) {
log.warn("Failed to unmarshall object. Increase logging to debug for additional information. 3" + ex.getMessage());
log.debug(ex.getMessage(), ex);
}
return null;
}
/**
* Setup readers.
*/
public void setupReaders() {
SAXParserFactory spf = JdkXmlUtils.getSAXFactory(catalogManager.overrideDefaultParser());
spf.setValidating(false);
SAXCatalogReader saxReader = new SAXCatalogReader(spf);
saxReader.setCatalogParser(null, "XMLCatalog",
"com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");
saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
"catalog",
"com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader");
addReader("application/xml", saxReader);
TR9401CatalogReader textReader = new TR9401CatalogReader();
addReader("text/plain", textReader);
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContext = servletContextEvent.getServletContext();
ResourceReader resourceReader = new ResourceReader(servletContext);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
boolean validating = false;
saxParserFactory.setValidating(validating);
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser;
try {
saxParser = saxParserFactory.newSAXParser();
boolean resolveEntities = false;
boolean scanWebFragments = true;
WebConfigScanner webConfigScanner = new WebConfigScanner(getClass().getClassLoader(), resourceReader,
saxParser, resolveEntities, scanWebFragments);
WebConfig webConfig = webConfigScanner.scan();
configuredContextParams = webConfig.getConfiguredContextParams();
displayName = webConfig.getDisplayName();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(URL file, TrackingHandler handler) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(file.openStream(), handler);
}
catch (Exception ex) {
throw new RuntimeException("Error parsing XML file " + handler.getLineNumberString(), ex);
}
}
@Override
public void apply(XSSFContext context) throws Exception {
InputSource sheetSource = new InputSource(context.getInpuStream());
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
XSSFSheetHandler sheetHandler = getSheetHandler();
sheetHandler.setContext(context);
sheetParser.setContentHandler(sheetHandler);
sheetParser.parse(sheetSource);
}
/**
* The constructor for an <code>XmlAnalyzer</code>.
*
* @param endOfFileName the file suffix used to determine if a file should be analyzed; this can be a mere file
* extension like <tt>.xml</tt> or a partial path like <tt>WEB-INF/web.xml</tt>
* @since 1.4
*/
protected XmlAnalyzer(@Nonnull String endOfFileName) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature("http://xml.org/sax/features/namespaces", true);
this.parser = factory.newSAXParser();
} catch (Exception e) {
throw new RuntimeException("Failed to set up XML parser!", e);
}
checkArgument(isNotBlank(endOfFileName), "[endOfFileName] must be set!");
this.endOfFileName = endOfFileName;
}
public static EndPointInformation parse(String xml) throws TechnicalConnectorException {
ByteArrayInputStream is = new ByteArrayInputStream(ConnectorIOUtils.toBytes(xml, Charset.UTF_8));
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
StatusPageParser.SaxHandler handler = new StatusPageParser.SaxHandler();
saxParser.parse(is, handler);
return handler.getInfo();
} catch (Exception var5) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_TECHNICAL, var5, new Object[0]);
}
}
/**
* Returns a SAXParserFactory instance.
*
* @param overrideDefaultParser a flag indicating whether the system-default
* implementation may be overridden. If the system property of the
* DOM factory ID is set, override is always allowed.
*
* @return a SAXParserFactory instance.
*/
public static SAXParserFactory getSAXFactory(boolean overrideDefaultParser) {
boolean override = overrideDefaultParser;
String spSAXFactory = SecuritySupport.getJAXPSystemProperty(SAX_FACTORY_ID);
if (spSAXFactory != null && System.getSecurityManager() == null) {
override = true;
}
SAXParserFactory factory
= !override
? new SAXParserFactoryImpl()
: SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
public static <T extends IEntity<?>> T parseEntity(Class<T> type, InputSource is) throws SAXException, IOException {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DefaultSaxParser handler = new DefaultSaxParser();
parser.parse(is, handler);
return (T) handler.getEntity();
} catch (ParserConfigurationException var4) {
throw new IllegalStateException("Unable to get SAX parser instance!", var4);
}
}
@Override
public AbstractSAXConfigReader parseConfigFile(File configFile) throws MetExtractorConfigReaderException {
try {
SAXParser p = SAXParserFactory.newInstance().newSAXParser();
p.parse(configFile, this);
} catch (Exception e) {
throw new MetExtractorConfigReaderException(e.getMessage());
}
return this;
}
/**
* Parses an xml config file and returns a Config object.
*
* @param xmlFile
* The xml config file which is passed by the user to annotation processing
* @return
* A non null Config object
*/
private Config parseAndGetConfig (File xmlFile, ErrorHandler errorHandler, boolean disableSecureProcessing) throws SAXException, IOException {
XMLReader reader;
try {
SAXParserFactory factory = XmlFactory.createParserFactory(disableSecureProcessing);
reader = factory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException e) {
// in practice this will never happen
throw new Error(e);
}
NGCCRuntimeEx runtime = new NGCCRuntimeEx(errorHandler);
// set up validator
ValidatorHandler validator = configSchema.newValidator();
validator.setErrorHandler(errorHandler);
// the validator will receive events first, then the parser.
reader.setContentHandler(new ForkContentHandler(validator,runtime));
reader.setErrorHandler(errorHandler);
Config config = new Config(runtime);
runtime.setRootHandler(config);
reader.parse(new InputSource(xmlFile.toURL().toExternalForm()));
runtime.reset();
return config;
}
/**
* Attaches the reader to the catalog.
*/
private void attachReaderToCatalog (Catalog catalog) {
SAXParserFactory spf = new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
spf.setValidating(false);
SAXCatalogReader saxReader = new SAXCatalogReader(spf);
saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName, "catalog",
"com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader");
catalog.addReader("application/xml", saxReader);
}
public static WsdlWrapperHandler parse(File file) throws ParserConfigurationException, SAXException, IOException {
WsdlWrapperHandler handler = new WsdlWrapperHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, handler);
return handler;
}
public XMLTreeParser()
throws ParserConfigurationException, SAXException
{
// get a parser factory
SAXParserFactory spf = SAXParserFactory.newInstance();
// get a XMLReader
parser = spf.newSAXParser();
}