Java Code Examples for javax.xml.parsers.SAXParserFactory#setNamespaceAware()

The following examples show how to use javax.xml.parsers.SAXParserFactory#setNamespaceAware() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XmlUtil.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: StartupListener.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example 3
Source File: Catalog.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: Resolver.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: Catalog.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Source File: XmlUtils.java    From juddi with Apache License 2.0 6 votes vote down vote up
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;

        }
 
Example 7
Source File: ResolvingParser.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/** 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();
  }
}
 
Example 8
Source File: JAXBDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@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();
    }
  }
}
 
Example 9
Source File: SanitizedXmlSourceSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: SAXFilterFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: Bug6359330.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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.
    }
}
 
Example 12
Source File: JaxbJavaee.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 13
Source File: CatalogSupportBase.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: LogbackLoggerOverrides.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: JAXPParser.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public JAXPParser( SAXParserFactory factory ) {
    factory.setNamespaceAware(true);    // just in case
    this.factory = factory;
}
 
Example 16
Source File: Bug4970402.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private XMLReader createXMLReader() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    return parserFactory.newSAXParser().getXMLReader();
}
 
Example 17
Source File: JAXPParser.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public JAXPParser( SAXParserFactory factory ) {
    factory.setNamespaceAware(true);    // just in case
    this.factory = factory;
}
 
Example 18
Source File: XMLUtility.java    From database with GNU General Public License v2.0 4 votes vote down vote up
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 */);

}
 
Example 19
Source File: CatalogResolverImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: LoginHelper.java    From EMP-Connector with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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();
    }
}