下面列出了javax.xml.parsers.SAXParserFactory#setNamespaceAware ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/** Initialize the parser. */
private void initParser() {
catalogResolver = new CatalogResolver(catalogManager);
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(namespaceAware);
spf.setValidating(validating);
try {
saxParser = spf.newSAXParser();
parser = saxParser.getParser();
documentHandler = null;
dtdHandler = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Object unmarshal(Reader reader, Class...clazz) {
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(clazz);
Unmarshaller um = jc.createUnmarshaller();
return um.unmarshal(xmlSource);
} catch (Exception ex) {
log.warn("Failed to unmarshall object. Increase logging to debug for additional information. 1" + ex.getMessage());
log.debug(ex.getMessage(), ex);
}
return null;
}
/**
* Setup readers.
*/
public void setupReaders() {
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
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);
}
/**
* Setup readers.
*/
public void setupReaders() {
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
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.ExtendedXMLCatalogReader");
addReader("application/xml", saxReader);
TR9401CatalogReader textReader = new TR9401CatalogReader();
addReader("text/plain", textReader);
}
/**
* Setup readers.
*/
public void setupReaders() {
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
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();
}
}
@Override
public void prepare() throws Exception {
super.prepare();
checkState(content == null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
try (OutputStream output = new BufferedOutputStream(stream)) {
StreamSource styleSource = new StreamSource(new StringReader(stylesheet));
TransformerFactory transformerFactory = SafeXml.newTransformerFactory();
Transformer transformer = transformerFactory.newTransformer(styleSource);
SAXParserFactory parserFactory = SafeXml.newSaxParserFactory();
parserFactory.setNamespaceAware(true);
SAXParser parser = parserFactory.newSAXParser();
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
XMLReader reader = parser.getXMLReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
transformer.transform(new SAXSource(reader, new InputSource(input)), new StreamResult(output));
}
}
content = stream.toByteArray();
}
@Override
public Object decode(Response response, Type type) throws IOException {
if (response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
while (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
type = ptype.getRawType();
}
if (!(type instanceof Class)) {
throw new UnsupportedOperationException(
"JAXB only supports decoding raw types. Found " + type);
}
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
/* Explicitly control sax configuration to prevent XXE attacks */
saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
saxParserFactory.setNamespaceAware(namespaceAware);
return jaxbContextFactory.createUnmarshaller((Class<?>) type).unmarshal(new SAXSource(
saxParserFactory.newSAXParser().getXMLReader(),
new InputSource(response.body().asInputStream())));
} catch (JAXBException | ParserConfigurationException | SAXException e) {
throw new DecodeException(response.status(), e.toString(), response.request(), e);
} finally {
if (response.body() != null) {
response.body().close();
}
}
}
private XMLReader getXMLReader() throws SAXException, ParserConfigurationException {
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true);
// pfactory.setValidating(true);
XMLReader xmlreader = pfactory.newSAXParser().getXMLReader();
// entity resolver is used in stylesheets ra-ent.xsl,
// dec-ent.xsl. Other stylehsheets will not use it
// since they do not contain ext entities.
xmlreader.setEntityResolver(entityResolver);
return xmlreader;
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
/**
* Read in a T from the input stream.
*
* @param type Class of object to be read in
* @param in input stream to read
* @param validate whether to validate the input.
* @param <T> class of object to be returned
* @return a T read from the input stream
* @throws ParserConfigurationException is the SAX parser can not be configured
* @throws SAXException if there is an xml problem
* @throws JAXBException if the xml cannot be marshalled into a T.
*/
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean validate) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(validate);
final SAXParser parser = factory.newSAXParser();
final JAXBContext ctx = JaxbJavaee.getContext(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
System.out.println(validationEvent);
return false;
}
});
final JaxbJavaee.NoSourceFilter xmlFilter = new JaxbJavaee.NoSourceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
final SAXSource source = new SAXSource(xmlFilter, inputSource);
currentPublicId.set(new TreeSet<String>());
try {
return unmarshaller.unmarshal(source);
} finally {
currentPublicId.set(null);
}
}
/**
* Returns an instance of SAXParser with a catalog if one is provided.
*
* @param setUseCatalog a flag indicates whether USE_CATALOG shall be set
* through the factory
* @param useCatalog the value of USE_CATALOG
* @param catalog a catalog
* @return an instance of SAXParser
* @throws ParserConfigurationException
* @throws SAXException
*/
SAXParser getSAXParser(boolean setUseCatalog, boolean useCatalog, String catalog)
throws ParserConfigurationException, SAXException {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setXIncludeAware(true);
if (setUseCatalog) {
spf.setFeature(XMLConstants.USE_CATALOG, useCatalog);
}
SAXParser parser = spf.newSAXParser();
parser.setProperty(CatalogFeatures.Feature.FILES.getPropertyName(), catalog);
return parser;
}
/**
* Read logger levels from logback.xml formatted include file.
*/
private Map<String, LoggerLevel> read(final File inputFile) throws Exception {
final Map<String, LoggerLevel> result = Maps.newHashMap();
SAXParserFactory parserFactory = SafeXml.newSaxParserFactory();
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(true);
SAXParser parser = parserFactory.newSAXParser();
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
parser.parse(inputFile, new DefaultHandler()
{
@Override
public void startElement(final String uri,
final String localName,
final String qName,
final Attributes attributes) throws SAXException
{
// NOTE: ATM we are ignoring 'property' elements, this is needed for root, but is only needed
// NOTE: to persist as a property for use in top-level logback.xml file
if ("logger".equals(localName)) {
String name = attributes.getValue("name");
String level = attributes.getValue("level");
result.put(name, LoggerLevel.valueOf(level));
}
}
});
return result;
}
public static BayeuxParameters login(URL loginEndpoint, String username, String password,
BayeuxParameters parameters) throws Exception {
HttpClient client = new HttpClient(parameters.sslContextFactory());
try {
client.getProxyConfiguration().getProxies().addAll(parameters.proxies());
client.start();
URL endpoint = new URL(loginEndpoint, getSoapUri());
Request post = client.POST(endpoint.toURI());
post.content(new ByteBufferContentProvider("text/xml", ByteBuffer.wrap(soapXmlForLogin(username, password))));
post.header("SOAPAction", "''");
post.header("PrettyPrint", "Yes");
ContentResponse response = post.send();
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.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
LoginResponseParser parser = new LoginResponseParser();
saxParser.parse(new ByteArrayInputStream(response.getContent()), parser);
String sessionId = parser.sessionId;
if (sessionId == null || parser.serverUrl == null) { throw new ConnectException(
String.format("Unable to login: %s", parser.faultstring)); }
URL soapEndpoint = new URL(parser.serverUrl);
String cometdEndpoint = Float.parseFloat(parameters.version()) < 37 ? COMETD_REPLAY_OLD : COMETD_REPLAY;
URL replayEndpoint = new URL(soapEndpoint.getProtocol(), soapEndpoint.getHost(), soapEndpoint.getPort(),
new StringBuilder().append(cometdEndpoint).append(parameters.version()).toString());
return new DelegatingBayeuxParameters(parameters) {
@Override
public String bearerToken() {
return sessionId;
}
@Override
public URL endpoint() {
return replayEndpoint;
}
};
} finally {
client.stop();
client.destroy();
}
}
/**
* Establish an entityResolver for newly resolved URIs.
* <p>
* This is called from the URIResolver to set an EntityResolver on the SAX
* parser to be used for new XML documents that are encountered as a result
* of the document() function, xsl:import, or xsl:include. This is done
* because the XSLT processor calls out to the SAXParserFactory itself to
* create a new SAXParser to parse the new document. The new parser does not
* automatically inherit the EntityResolver of the original (although
* arguably it should). Quote from JAXP specification on Class
* SAXTransformerFactory:
* <p>
* {@code If an application wants to set the ErrorHandler or EntityResolver
* for an XMLReader used during a transformation, it should use a URIResolver
* to return the SAXSource which provides (with getXMLReader) a reference to
* the XMLReader}
*
*/
private void setEntityResolver(SAXSource source) {
XMLReader reader = source.getXMLReader();
if (reader == null) {
SAXParserFactory spFactory = new SAXParserFactoryImpl();
spFactory.setNamespaceAware(true);
try {
reader = spFactory.newSAXParser().getXMLReader();
} catch (ParserConfigurationException | SAXException ex) {
CatalogMessages.reportRunTimeError(CatalogMessages.ERR_PARSER_CONF, ex);
}
}
if (entityResolver != null) {
entityResolver = new CatalogResolverImpl(catalog);
}
reader.setEntityResolver(entityResolver);
source.setXMLReader(reader);
}
public void readXML(final CounterSet root, final InputStream is,
final IInstrumentFactory instrumentFactory, final Pattern filter)
throws IOException, ParserConfigurationException, SAXException {
if (is == null)
throw new IllegalArgumentException();
if (instrumentFactory == null)
throw new IllegalArgumentException();
final SAXParser p;
{
final SAXParserFactory f = SAXParserFactory.newInstance();
f.setNamespaceAware(true);
p = f.newSAXParser();
}
final MyHandler handler = new MyHandler(root, instrumentFactory, filter);
p.parse(is, handler /* @todo set validating and pass in systemId */);
}
private XMLReader createXMLReader() throws ParserConfigurationException, SAXException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
return parserFactory.newSAXParser().getXMLReader();
}
public JAXPParser( SAXParserFactory factory ) {
factory.setNamespaceAware(true); // just in case
this.factory = factory;
}
public JAXPParser( SAXParserFactory factory ) {
factory.setNamespaceAware(true); // just in case
this.factory = factory;
}