javax.xml.XMLConstants Java Examples

The following examples show how to use javax.xml.XMLConstants. 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: HandlerChainsStringQNameAdapter.java    From tomee with Apache License 2.0 7 votes vote down vote up
@Override
public QName unmarshal(final String value) throws Exception {
    if (value == null || value.isEmpty()) {
        return new QName(XMLConstants.NULL_NS_URI, "");
    }
    final int colonIndex = value.indexOf(':');
    if (colonIndex == -1) {
        return new QName(XMLConstants.NULL_NS_URI, value);
    }
    final String prefix = value.substring(0, colonIndex);
    final String localPart = (colonIndex == (value.length() - 1)) ? "" : value.substring(colonIndex + 1);

    String nameSpaceURI = "";
    if (xmlFilter != null) {
        nameSpaceURI = xmlFilter.lookupNamespaceURI(prefix);
    } else if (namespaceContext != null) {
        nameSpaceURI = namespaceContext.getNamespaceURI(prefix);
    }

    if (nameSpaceURI == null) {
        nameSpaceURI = XMLConstants.NULL_NS_URI;
    }
    return new QName(nameSpaceURI, localPart, prefix);
}
 
Example #2
Source File: XmlFactory.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns properly configured (e.g. security features) factory
 * - namespaceAware == true
 * - securityProcessing == is set based on security processing property, default is true
 */
public static DocumentBuilderFactory createDocumentBuilderFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "DocumentBuilderFactory instance: {0}", factory);
        }
        factory.setNamespaceAware(true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (ParserConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
 
Example #3
Source File: SAXBufferProcessor.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void processNamespaceAttribute(String prefix, String uri) throws SAXException {
    _contentHandler.startPrefixMapping(prefix, uri);

    if (_namespacePrefixesFeature) {
        // Add the namespace delcaration as an attribute
        if (prefix != "") {
            _attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix,
                    getQName(XMLConstants.XMLNS_ATTRIBUTE, prefix),
                    "CDATA", uri);
        } else {
            _attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE,
                    XMLConstants.XMLNS_ATTRIBUTE,
                    "CDATA", uri);
        }
    }

    cacheNamespacePrefix(prefix);
}
 
Example #4
Source File: UnmarshallingContext.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getPrefix(String uri) {
    if( uri==null )
        throw new IllegalArgumentException();
    if( uri.equals(XMLConstants.XML_NS_URI) )
        return XMLConstants.XML_NS_PREFIX;
    if( uri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) )
        return XMLConstants.XMLNS_ATTRIBUTE;

    for( int i=nsLen-2; i>=0; i-=2 )
        if(uri.equals(nsBind[i+1]))
            if( getNamespaceURI(nsBind[i]).equals(nsBind[i+1]) )
                // make sure that this prefix is still effective.
                return nsBind[i];

    if(environmentNamespaceContext!=null)
        return environmentNamespaceContext.getPrefix(uri);

    return null;
}
 
Example #5
Source File: DomPostInitAction.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    Set<String> declaredPrefixes = new HashSet<String>();
    for( Node n=node; n!=null && n.getNodeType()==Node.ELEMENT_NODE; n=n.getParentNode() ) {
        NamedNodeMap atts = n.getAttributes();
        if(atts==null)      continue; // broken DOM. but be graceful.
        for( int i=0; i<atts.getLength(); i++ ) {
            Attr a = (Attr)atts.item(i);
            String nsUri = a.getNamespaceURI();
            if(nsUri==null || !nsUri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))
                continue;   // not a namespace declaration
            String prefix = a.getLocalName();
            if(prefix==null)
                continue;   // broken DOM. skip to be safe
            if(prefix.equals("xmlns")) {
                prefix = "";
            }
            String value = a.getValue();
            if(value==null)
                continue;   // broken DOM. skip to be safe
            if(declaredPrefixes.add(prefix)) {
                serializer.addInscopeBinding(value,prefix);
            }
        }
    }
}
 
Example #6
Source File: XtbMessageBundle.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private SAXParser createSAXParser()
    throws ParserConfigurationException, SAXException {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setValidating(false);
  factory.setXIncludeAware(false);
  factory.setFeature(
      "http://xml.org/sax/features/external-general-entities", false);
  factory.setFeature(
      "http://xml.org/sax/features/external-parameter-entities",false);
  factory.setFeature(
      "http://apache.org/xml/features/nonvalidating/load-external-dtd",
      false);
  factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

  SAXParser parser = factory.newSAXParser();
  XMLReader xmlReader = parser.getXMLReader();
  xmlReader.setEntityResolver(NOOP_RESOLVER);
  return parser;
}
 
Example #7
Source File: JmsSubscription.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected boolean doFilter(Element content) {
    if (contentFilter != null) {
        if (!contentFilter.getDialect().equals(XPATH1_URI)) {
            throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect());
        }
        try {
            XPathFactory xpfactory = XPathFactory.newInstance();
            try {
                xpfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
            } catch (Throwable t) {
                //possibly old version, though doesn't really matter as content is already parsed as an Element
            }
            XPath xpath = xpfactory.newXPath();
            XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString());
            Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN);
            return ret.booleanValue();
        } catch (XPathExpressionException e) {
            LOGGER.log(Level.WARNING, "Could not filter notification", e);
        }
        return false;
    }
    return true;
}
 
Example #8
Source File: MavenUtil.java    From hbase-indexer with Apache License 2.0 6 votes vote down vote up
@Override
public String getNamespaceURI(String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("Null argument: prefix");
    }

    if (prefix.equals(XMLConstants.XML_NS_PREFIX)) {
        return XMLConstants.XML_NS_URI;
    } else if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) {
        return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
    }

    String uri = prefixToUri.get(prefix);
    if (uri != null) {
        return uri;
    } else {
        return XMLConstants.NULL_NS_URI;
    }
}
 
Example #9
Source File: CanonicalizerSpi.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method canonicalize
 *
 * @param inputBytes
 * @return the c14n bytes.
 *
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] engineCanonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
    org.xml.sax.SAXException, CanonicalizationException {

    java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    // needs to validate for ID attribute normalization
    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    Document document = db.parse(in);
    return this.engineCanonicalizeSubTree(document);
}
 
Example #10
Source File: UnmarshallingContext.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private String resolveNamespacePrefix( String prefix ) {
    if(prefix.equals("xml"))
        return XMLConstants.XML_NS_URI;

    for( int i=nsLen-2; i>=0; i-=2 ) {
        if(prefix.equals(nsBind[i]))
            return nsBind[i+1];
    }

    if(environmentNamespaceContext!=null)
        // temporary workaround until Zephyr fixes 6337180
        return environmentNamespaceContext.getNamespaceURI(prefix.intern());

    // by default, the default ns is bound to "".
    // but allow environmentNamespaceContext to take precedence
    if(prefix.equals(""))
        return "";

    // unresolved. error.
    return null;
}
 
Example #11
Source File: XMLSchemaValidatorComponentManager.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the state of a feature.
 *
 * @param featureId The feature identifier.
 * @return true if the feature is supported
 *
 * @throws XMLConfigurationException Thrown for configuration error.
 *                                   In general, components should
 *                                   only throw this exception if
 *                                   it is <strong>really</strong>
 *                                   a critical error.
 */
public FeatureState getFeatureState(String featureId)
        throws XMLConfigurationException {
    if (PARSER_SETTINGS.equals(featureId)) {
        return FeatureState.is(fConfigUpdated);
    }
    else if (VALIDATION.equals(featureId) || SCHEMA_VALIDATION.equals(featureId)) {
        return FeatureState.is(true);
    }
    else if (USE_GRAMMAR_POOL_ONLY.equals(featureId)) {
        return FeatureState.is(fUseGrammarPoolOnly);
    }
    else if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(featureId)) {
        return FeatureState.is(fInitSecurityManager.isSecureProcessing());
    }
    else if (SCHEMA_ELEMENT_DEFAULT.equals(featureId)) {
        return FeatureState.is(true); //pre-condition: VALIDATION and SCHEMA_VALIDATION are always true
    }
    return super.getFeatureState(featureId);
}
 
Example #12
Source File: ContentHandlerNamespacePrefixAdapter.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
    if(namespacePrefixes) {
        this.atts.setAttributes(atts);
        // add namespace bindings back as attributes
        for( int i=0; i<len; i+=2 ) {
            String prefix = nsBinding[i];
            if(prefix.length()==0)
                this.atts.addAttribute(XMLConstants.XML_NS_URI,"xmlns","xmlns","CDATA",nsBinding[i+1]);
            else
                this.atts.addAttribute(XMLConstants.XML_NS_URI,prefix,"xmlns:"+prefix,"CDATA",nsBinding[i+1]);
        }
        atts = this.atts;
    }
    len=0;
    super.startElement(uri, localName, qName, atts);
}
 
Example #13
Source File: XMLSchemaValidatorComponentManager.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the state of a feature.
 *
 * @param featureId The feature identifier.
 * @return true if the feature is supported
 *
 * @throws XMLConfigurationException Thrown for configuration error.
 *                                   In general, components should
 *                                   only throw this exception if
 *                                   it is <strong>really</strong>
 *                                   a critical error.
 */
public FeatureState getFeatureState(String featureId)
        throws XMLConfigurationException {
    if (PARSER_SETTINGS.equals(featureId)) {
        return FeatureState.is(fConfigUpdated);
    }
    else if (VALIDATION.equals(featureId) || SCHEMA_VALIDATION.equals(featureId)) {
        return FeatureState.is(true);
    }
    else if (USE_GRAMMAR_POOL_ONLY.equals(featureId)) {
        return FeatureState.is(fUseGrammarPoolOnly);
    }
    else if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(featureId)) {
        return FeatureState.is(fInitSecurityManager.isSecureProcessing());
    }
    else if (SCHEMA_ELEMENT_DEFAULT.equals(featureId)) {
        return FeatureState.is(true); //pre-condition: VALIDATION and SCHEMA_VALIDATION are always true
    }
    return super.getFeatureState(featureId);
}
 
Example #14
Source File: SchemaValidator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Validate the XML content against the XSD.
 *
 * The whole XML content must be valid.
 */
static void validateXML(String xmlContent, String xsdPath, Properties resolvedProperties) throws Exception {
    String resolvedXml = resolveAllExpressions(xmlContent, resolvedProperties);

    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdPath);
    final Source source = new StreamSource(stream);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(ERROR_HANDLER);
    schemaFactory.setResourceResolver(new JBossEntityResolver());
    Schema schema = schemaFactory.newSchema(source);
    javax.xml.validation.Validator validator = schema.newValidator();
    validator.setErrorHandler(ERROR_HANDLER);
    validator.setFeature("http://apache.org/xml/features/validation/schema", true);
    validator.validate(new StreamSource(new StringReader(resolvedXml)));
}
 
Example #15
Source File: CanonicalizerSpi.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Method canonicalize
 *
 * @param inputBytes
 * @return the c14n bytes.
 *
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] engineCanonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
    org.xml.sax.SAXException, CanonicalizationException {

    java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    // needs to validate for ID attribute normalization
    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    Document document = db.parse(in);
    return this.engineCanonicalizeSubTree(document);
}
 
Example #16
Source File: SAXBufferProcessor.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void processNamespaceAttribute(String prefix, String uri) throws SAXException {
    _contentHandler.startPrefixMapping(prefix, uri);

    if (_namespacePrefixesFeature) {
        // Add the namespace delcaration as an attribute
        if (prefix != "") {
            _attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix,
                    getQName(XMLConstants.XMLNS_ATTRIBUTE, prefix),
                    "CDATA", uri);
        } else {
            _attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE,
                    XMLConstants.XMLNS_ATTRIBUTE,
                    "CDATA", uri);
        }
    }

    cacheNamespacePrefix(prefix);
}
 
Example #17
Source File: XMLSchemaFactory.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public boolean getFeature(String name)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                "FeatureNameNull", null));
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return (fSecurityManager != null && fSecurityManager.isSecureProcessing());
    }
    try {
        return fXMLSchemaLoader.getFeature(name);
    }
    catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == Status.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object [] {identifier}));
        }
        else {
            throw new SAXNotSupportedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object [] {identifier}));
        }
    }
}
 
Example #18
Source File: StaxStreamHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void startElementInternal(QName name, Attributes attributes,
		Map<String, String> namespaceMapping) throws XMLStreamException {

	this.streamWriter.writeStartElement(name.getPrefix(), name.getLocalPart(), name.getNamespaceURI());

	for (Map.Entry<String, String> entry : namespaceMapping.entrySet()) {
		String prefix = entry.getKey();
		String namespaceUri = entry.getValue();
		this.streamWriter.writeNamespace(prefix, namespaceUri);
		if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
			this.streamWriter.setDefaultNamespace(namespaceUri);
		}
		else {
			this.streamWriter.setPrefix(prefix, namespaceUri);
		}
	}
	for (int i = 0; i < attributes.getLength(); i++) {
		QName attrName = toQName(attributes.getURI(i), attributes.getQName(i));
		if (!isNamespaceDeclaration(attrName)) {
			this.streamWriter.writeAttribute(attrName.getPrefix(), attrName.getNamespaceURI(),
					attrName.getLocalPart(), attributes.getValue(i));
		}
	}
}
 
Example #19
Source File: XMLDOMWriterImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * creates a namespace attribute and will associate it with the current element in
 * the DOM tree.
 * @param prefix {@inheritDoc}
 * @param namespaceURI {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {

    if (prefix == null) {
        throw new XMLStreamException("prefix cannot be null");
    }

    if (namespaceURI == null) {
        throw new XMLStreamException("NamespaceURI cannot be null");
    }

    String qname = null;

    if (prefix.equals("")) {
        qname = XMLConstants.XMLNS_ATTRIBUTE;
    } else {
        qname = getQName(XMLConstants.XMLNS_ATTRIBUTE,prefix);
    }

    ((Element)currentNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,qname, namespaceURI);
}
 
Example #20
Source File: AbstractSchemaValidationTube.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds inscope namespaces as attributes to  <xsd:schema> fragment nodes.
 *
 * @param nss namespace context info
 * @param elem that is patched with inscope namespaces
 */
private @Nullable void patchDOMFragment(NamespaceSupport nss, Element elem) {
    NamedNodeMap atts = elem.getAttributes();
    for( Enumeration en = nss.getPrefixes(); en.hasMoreElements(); ) {
        String prefix = (String)en.nextElement();

        for( int i=0; i<atts.getLength(); i++ ) {
            Attr a = (Attr)atts.item(i);
            if (!"xmlns".equals(a.getPrefix()) || !a.getLocalName().equals(prefix)) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE, "Patching with xmlns:{0}={1}", new Object[]{prefix, nss.getURI(prefix)});
                }
                elem.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:"+prefix, nss.getURI(prefix));
            }
        }
    }
}
 
Example #21
Source File: XMLSchemaFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public boolean getFeature(String name)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                "FeatureNameNull", null));
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return (fSecurityManager != null && fSecurityManager.isSecureProcessing());
    }
    try {
        return fXMLSchemaLoader.getFeature(name);
    }
    catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == Status.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object [] {identifier}));
        }
        else {
            throw new SAXNotSupportedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object [] {identifier}));
        }
    }
}
 
Example #22
Source File: SimpleNamespaceContext.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Remove the given prefix from this context.
 * @param prefix the prefix to be removed
 */
public void removeBinding(String prefix) {
	if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
		this.defaultNamespaceUri = "";
	}
	else if (prefix != null) {
		String namespaceUri = this.prefixToNamespaceUri.remove(prefix);
		if (namespaceUri != null) {
			Set<String> prefixes = this.namespaceUriToPrefixes.get(namespaceUri);
			if (prefixes != null) {
				prefixes.remove(prefix);
				if (prefixes.isEmpty()) {
					this.namespaceUriToPrefixes.remove(namespaceUri);
				}
			}
		}
	}
}
 
Example #23
Source File: TaxiiHandler.java    From metron with Apache License 2.0 6 votes vote down vote up
public String getStringFromDocument(Document doc)
{
  try
  {
    DOMSource domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    return writer.toString();
  }
  catch(TransformerException ex)
  {
    ex.printStackTrace();
    return null;
  }
}
 
Example #24
Source File: XmlUtils.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
/**
 * @param is
 * @return
 */
public static Document parseInputStream(InputStream is) throws IOException
{
  try
  {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false);
    domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    // NOTE:  In Java 8, XMLConstants.FEATURE_SECURE_PROCESSING disables XMLConstants.ACCESS_EXTERNAL_DTD
    // domFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    return builder.parse(is);
  }
  catch (ParserConfigurationException | SAXException e)
  {
    throw new IOException("Error parsing XML Stream", e);
  }
}
 
Example #25
Source File: XMLSchemaValidatorComponentManager.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the state of a feature.
 *
 * @param featureId The feature identifier.
 * @return true if the feature is supported
 *
 * @throws XMLConfigurationException Thrown for configuration error.
 *                                   In general, components should
 *                                   only throw this exception if
 *                                   it is <strong>really</strong>
 *                                   a critical error.
 */
public FeatureState getFeatureState(String featureId)
        throws XMLConfigurationException {
    if (PARSER_SETTINGS.equals(featureId)) {
        return FeatureState.is(fConfigUpdated);
    }
    else if (VALIDATION.equals(featureId) || SCHEMA_VALIDATION.equals(featureId)) {
        return FeatureState.is(true);
    }
    else if (USE_GRAMMAR_POOL_ONLY.equals(featureId)) {
        return FeatureState.is(fUseGrammarPoolOnly);
    }
    else if (XMLConstants.FEATURE_SECURE_PROCESSING.equals(featureId)) {
        return FeatureState.is(fInitSecurityManager.isSecureProcessing());
    }
    else if (SCHEMA_ELEMENT_DEFAULT.equals(featureId)) {
        return FeatureState.is(true); //pre-condition: VALIDATION and SCHEMA_VALIDATION are always true
    }
    return super.getFeatureState(featureId);
}
 
Example #26
Source File: NodeNamespaceContext.java    From XACML with MIT License 6 votes vote down vote up
@Override
public Iterator<String> getAllPrefixes() {
	NamedNodeMap attributes = document.getDocumentElement().getAttributes();
	List<String> prefixList = new ArrayList<String>();
	for (int i = 0; i < attributes.getLength(); i++) {
		Node node = attributes.item(i);
		if (node.getNodeName().startsWith("xmlns")) {
			// this is a namespace definition
			int index = node.getNodeName().indexOf(":");
			if (node.getNodeName().length() < index + 1) {
				index = -1;
			}
			if (index < 0) {
				// default namespace
				prefixList.add(XMLConstants.DEFAULT_NS_PREFIX);
			} else {
				String prefix = node.getNodeName().substring(index + 1);
				prefixList.add(prefix);
			}
		}
	}
	return prefixList.iterator();
}
 
Example #27
Source File: MapBasedNamespaceContext.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
private MapBasedNamespaceContext _addMapping (@Nonnull final String sPrefix,
                                              @Nonnull final String sNamespaceURI,
                                              final boolean bAllowOverwrite)
{
  ValueEnforcer.notNull (sPrefix, "Prefix");
  ValueEnforcer.notNull (sNamespaceURI, "NamespaceURI");
  if (!bAllowOverwrite && m_aPrefix2NS.containsKey (sPrefix))
    throw new IllegalArgumentException ("The prefix '" +
                                        sPrefix +
                                        "' is already registered to '" +
                                        m_aPrefix2NS.get (sPrefix) +
                                        "'!");

  if (sPrefix.equals (XMLConstants.DEFAULT_NS_PREFIX))
    m_sDefaultNamespaceURI = sNamespaceURI;
  m_aPrefix2NS.put (sPrefix, sNamespaceURI);
  m_aNS2Prefix.computeIfAbsent (sNamespaceURI, x -> new CommonsHashSet <> ()).add (sPrefix);
  return this;
}
 
Example #28
Source File: StaxParserUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void validate(InputStream doc, InputStream sch) throws ParsingException {
    try {
        XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(doc);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(sch));
        Validator validator = schema.newValidator();
        StAXSource stAXSource = new StAXSource(xmlEventReader);
        validator.validate(stAXSource);
    } catch (Exception e) {
        throw logger.parserException(e);
    }

}
 
Example #29
Source File: AnyURITest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src", "."), XSDFILE));
        throw new RuntimeException("Illegal URI // should be rejected.");
    } catch (SAXException e) {
        //expected:
        //Enumeration value '//' is not in the value space of the base type, anyURI.
    }


}
 
Example #30
Source File: XSLTC.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set allowed protocols for accessing external stylesheet.
 */
public void setProperty(String name, Object value) {
    if (name.equals(XMLConstants.ACCESS_EXTERNAL_STYLESHEET)) {
        _accessExternalStylesheet = (String)value;
    }
    else if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
        _accessExternalDTD = (String)value;
    } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
        _xmlSecurityManager = (XMLSecurityManager)value;
    }
}