Java Code Examples for javax.xml.XMLConstants

The following examples show how to use javax.xml.XMLConstants. These examples are extracted from open source projects. 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 Project: tomee   Author: apache   File: HandlerChainsStringQNameAdapter.java    License: 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 Project: astor   Author: SpoonLabs   File: XtbMessageBundle.java    License: 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 #3
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: SAXBufferProcessor.java    License: 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 Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: UnmarshallingContext.java    License: 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 Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: XMLSchemaValidatorComponentManager.java    License: 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 #6
Source Project: jdk8u60   Author: chenghanpeng   File: DomPostInitAction.java    License: 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 #7
Source Project: ph-commons   Author: phax   File: MapBasedNamespaceContext.java    License: 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 #8
Source Project: openjdk-8   Author: bpupadhyaya   File: XMLSchemaFactory.java    License: 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 #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: StaxStreamHandler.java    License: 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 #10
Source Project: hottub   Author: dsrg-uoft   File: XMLDOMWriterImpl.java    License: 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 #11
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: XMLSchemaFactory.java    License: 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 #12
Source Project: lams   Author: lamsfoundation   File: SimpleNamespaceContext.java    License: 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 #13
Source Project: Bytecoder   Author: mirkosertic   File: XMLSchemaValidatorComponentManager.java    License: 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 #14
Source Project: jdk8u60   Author: chenghanpeng   File: XmlFactory.java    License: 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 #15
Source Project: XACML   Author: att   File: NodeNamespaceContext.java    License: 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 #16
Source Project: mrgeo   Author: ngageoint   File: XmlUtils.java    License: 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 #17
Source Project: metron   Author: apache   File: TaxiiHandler.java    License: 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 #18
Source Project: TencentKona-8   Author: Tencent   File: AbstractSchemaValidationTube.java    License: 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 #19
Source Project: hottub   Author: dsrg-uoft   File: SAXBufferProcessor.java    License: 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 #20
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: CanonicalizerSpi.java    License: 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 #21
Source Project: wildfly-core   Author: wildfly   File: SchemaValidator.java    License: 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 #22
Source Project: cxf   Author: apache   File: JmsSubscription.java    License: 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 #23
Source Project: hbase-indexer   Author: NGDATA   File: MavenUtil.java    License: 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 #24
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: CanonicalizerSpi.java    License: 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 #25
Source Project: TencentKona-8   Author: Tencent   File: UnmarshallingContext.java    License: 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 #26
Source Project: jdk8u60   Author: chenghanpeng   File: XMLSchemaValidatorComponentManager.java    License: 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 #27
Source Project: hottub   Author: dsrg-uoft   File: ContentHandlerNamespacePrefixAdapter.java    License: 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 #28
Source Project: dragonwell8_jdk   Author: alibaba   File: AnyURITest.java    License: 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 #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Bug6967214Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        File dir = new File(Bug6967214Test.class.getResource("Bug6967214").getPath());
        File files[] = dir.listFiles();
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        for (int i = 0; i < files.length; i++) {
            try {
                System.out.println(files[i].getName());
                Schema schema = schemaFactory.newSchema(new StreamSource(files[i]));
                Assert.fail("should report error");
            } catch (org.xml.sax.SAXParseException spe) {
                continue;
            }
        }
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
 
Example #30
Source Project: juddi   Author: apache   File: RequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
public static synchronized String getText(Element element) throws TransformerException {
        if (transFactory == null) {
                transFactory = TransformerFactory.newInstance();
                transFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
                transFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        }
        Transformer trans = transFactory.newTransformer();
        StringWriter sw = new StringWriter();
        trans.transform(new DOMSource(element), new StreamResult(sw));
        return sw.toString();
}