Java 类javax.xml.XMLConstants 实例源码

项目:OpenJSharp    文件:XmlFactory.java   
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static TransformerFactory createTransformerFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "TransformerFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (TransformerConfigurationException 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);
    }
}
项目:Hydrograph    文件:ELTSchemaGridWidget.java   
private boolean validateXML(InputStream xml, InputStream xsd){
 try
 {
     SchemaFactory factory = 
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
     javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
     Validator validator = schema.newValidator();

     validator.validate(new StreamSource(xml));
     return true;
 }
 catch( SAXException| IOException ex)
 {
     //MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
     MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR | SWT.OK);
     dialog.setText(Messages.ERROR);
     dialog.setMessage(Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
     logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
     return false;
 }
}
项目:alfresco-xml-factory    文件:AppTest.java   
/**
 * Test we have set features the way we expect as defaults.
 */
public void testSAXParserFactoryInWhiteList() throws Throwable
{
    // Using constructor rather than the service locator and then using the helper to configure it.
    SAXParserFactory spf = new SAXParserFactoryImpl();
    FactoryHelper factoryHelper = new FactoryHelper();
    List<String> whiteListClasses = Collections.singletonList(getClass().getName());
    factoryHelper.configureFactory(spf, FactoryHelper.DEFAULT_FEATURES_TO_ENABLE,
            FactoryHelper.DEFAULT_FEATURES_TO_DISABLE,
            whiteListClasses);

    assertFalse(spf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
    assertFalse(spf.getFeature(FactoryHelper.FEATURE_DISALLOW_DOCTYPE));

    assertTrue(spf.getFeature(FactoryHelper.FEATURE_EXTERNAL_GENERAL_ENTITIES));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_EXTERNAL_PARAMETER_ENTITIES));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_USE_ENTITY_RESOLVER2));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_LOAD_EXTERNAL_DTD));

    assertFalse(spf.isXIncludeAware()); // false is the default so is same as the non whitelist test
}
项目:openjdk-jdk10    文件:XmlUtil.java   
public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
    try {
        boolean securityOn = !xmlSecurityDisabled(disableSecurity);
        factory.setFeature(featureToSet, securityOn);
        factory.setNamespaceAware(true);
        if (securityOn) {
            featureToSet = DISALLOW_DOCTYPE_DECL;
            factory.setFeature(featureToSet, true);
            featureToSet = EXTERNAL_GE;
            factory.setFeature(featureToSet, false);
            featureToSet = EXTERNAL_PE;
            factory.setFeature(featureToSet, false);
            featureToSet = LOAD_EXTERNAL_DTD;
            factory.setFeature(featureToSet, false);
        }
    } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[]{factory.getClass().getName()});
    }
    return factory;
}
项目:jdk8u-jdk    文件:XPathWhiteSpaceTest.java   
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));
    } catch (SAXException e) {
        throw new RuntimeException(e.getMessage());
    }


}
项目:openjdk-jdk10    文件:SAXBufferProcessor.java   
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);
}
项目:incubator-netbeans    文件:SchemaModelImpl.java   
@Override
public <T extends NamedReferenceable>
        T resolve(String namespace, String localName, Class<T> type) 
{
    if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespace) &&
        XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(getSchema().getTargetNamespace())) {
        return resolveImpl(namespace, localName, type);
    }

    if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespace)) {
        SchemaModel sm = SchemaModelFactory.getDefault().getPrimitiveTypesModel();
        return sm.findByNameAndType(localName, type);
    }

    return resolveImpl(namespace, localName, type);
}
项目:jdk8u-jdk    文件:FeaturePropagationTest.java   
public static void main(String[] args) throws Exception {
    InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
    StreamSource xsdSource = new StreamSource(reader);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    Schema schema = null;
    schema = schemaFactory.newSchema(xsdSource);

    Validator validator = schema.newValidator();

    if (validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        throw new RuntimeException("Feature set on the factory is not inherited!");
    }

}
项目:jdk8u-jdk    文件:CanonicalizerSpi.java   
/**
 * 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);
}
项目:OpenJSharp    文件:DomPostInitAction.java   
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);
            }
        }
    }
}
项目:OpenJSharp    文件:XMLStreamWriterImpl.java   
private void writeAttributeWithPrefix(String prefix, String localName,
    String value) throws IOException {
    fWriter.write(SPACE);

    if ((prefix != null) && (prefix != XMLConstants.DEFAULT_NS_PREFIX)) {
        fWriter.write(prefix);
        fWriter.write(":");
    }

    fWriter.write(localName);
    fWriter.write("=\"");
    writeXMLContent(value,
            true,   // true = escapeChars
            true);  // true = escapeDoubleQuotes
    fWriter.write("\"");
}
项目:phoenix.webui.framework    文件:Validation.java   
/**
     * 利用xsd验证xml
     * @param xsdFile xsdFile
     * @param xmlInput xmlInput
     * @throws SAXException  SAXException
     * @throws IOException IOException
     */
    public static void validation(String xsdFile, InputStream xmlInput) throws SAXException, IOException
    {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL xsdURL = Validation.class.getClassLoader().getResource(xsdFile);
        if(xsdURL != null)
        {
            Schema schema = factory.newSchema(xsdURL);
            Validator validator = schema.newValidator();
//          validator.setErrorHandler(new AutoErrorHandler());

            Source source = new StreamSource(xmlInput);

            try(OutputStream resultOut = new FileOutputStream(new File(PathUtil.getRootDir(), xsdFile + ".xml")))
            {
                Result result = new StreamResult(resultOut);
                validator.validate(source, result);
            }
        }
        else
        {
            throw new FileNotFoundException(String.format("can not found xsd file [%s] from classpath.", xsdFile));
        }
    }
项目:Proyecto-DASI    文件:SchemaHelper.java   
/** Attempt to construct the specified object from this XML string
 * @param xml the XML string to parse
 * @param xsdFile the name of the XSD schema that defines the object
 * @param objclass the class of the object requested
 * @return if successful, an instance of class objclass that captures the data in the XML string
 */
static public Object deserialiseObject(String xml, String xsdFile, Class<?> objclass) throws JAXBException, SAXException, XMLStreamException
{
    Object obj = null;
    JAXBContext jaxbContext = getJAXBContext(objclass);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final String schemaResourceFilename = new String(xsdFile);
    URL schemaURL = MalmoMod.class.getClassLoader().getResource(schemaResourceFilename);
    Schema schema = schemaFactory.newSchema(schemaURL);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    jaxbUnmarshaller.setSchema(schema);

    StringReader stringReader = new StringReader(xml);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader XMLreader = xif.createXMLStreamReader(stringReader);

    obj = jaxbUnmarshaller.unmarshal(XMLreader);
    return obj;
}
项目:Proyecto-DASI    文件:SchemaHelper.java   
/** Attempt to construct the specified object from this XML string
 * @param xml the XML string to parse
 * @param xsdFile the name of the XSD schema that defines the object
 * @param objclass the class of the object requested
 * @return if successful, an instance of class objclass that captures the data in the XML string
 */
static public Object deserialiseObject(String xml, String xsdFile, Class<?> objclass) throws JAXBException, SAXException, XMLStreamException
{
    Object obj = null;
    JAXBContext jaxbContext = getJAXBContext(objclass);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final String schemaResourceFilename = new String(xsdFile);
    URL schemaURL = MalmoMod.class.getClassLoader().getResource(schemaResourceFilename);
    Schema schema = schemaFactory.newSchema(schemaURL);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    jaxbUnmarshaller.setSchema(schema);

    StringReader stringReader = new StringReader(xml);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader XMLreader = xif.createXMLStreamReader(stringReader);

    obj = jaxbUnmarshaller.unmarshal(XMLreader);
    return obj;
}
项目:openjdk-jdk10    文件:XPathWhiteSpaceTest.java   
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));
    } catch (SAXException e) {
        throw new RuntimeException(e.getMessage());
    }


}
项目:alfresco-repository    文件:StandardRenditionLocationResolverImpl.java   
public static String buildNamespaceDeclaration(final Document xml)
{
   final Element docEl = xml.getDocumentElement();
   final NamedNodeMap attributes = docEl.getAttributes();
   final StringBuilder result = new StringBuilder();
   for (int i = 0; i < attributes.getLength(); i++)
   {
      final Node a = attributes.item(i);
      if (a.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE))
      {
         final String prefix = a.getNodeName().substring((XMLConstants.XMLNS_ATTRIBUTE + ":").length());
         final String uri = a.getNodeValue();
         if (result.length() != 0)
         {
            result.append(",\n");
         }
         result.append("\"").append(prefix).append("\":\"").append(uri).append("\"");
      }
   }
   return "<#ftl ns_prefixes={\n" + result.toString() + "}>\n";
}
项目:openjdk-jdk10    文件:XMLStreamWriterImpl.java   
private void writenamespace(String prefix, String namespaceURI)
    throws IOException {
    fWriter.write(" xmlns");

    if ((prefix != null) && (!prefix.equals(XMLConstants.DEFAULT_NS_PREFIX))) {
        fWriter.write(":");
        fWriter.write(prefix);
    }

    fWriter.write("=\"");
    writeXMLContent(
            namespaceURI,
            true,   // true = escapeChars
            true);  // true = escapeDoubleQuotes
    fWriter.write("\"");
}
项目:openjdk-jdk10    文件:XSLTC.java   
/**
 * Return allowed protocols for accessing external stylesheet.
 * @param name the name of the property
 * @return the value of the property
 */
public Object getProperty(String name) {
    if (name.equals(XMLConstants.ACCESS_EXTERNAL_STYLESHEET)) {
        return _accessExternalStylesheet;
    }
    else if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
        return _accessExternalDTD;
    } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
        return _xmlSecurityManager;
    } else if (name.equals(XalanConstants.JDK_EXTENSION_CLASSLOADER)) {
        return _extensionClassLoader;
    } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) {
        return _catalogFeatures;
    } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) {
        return _cdataChunkSize;
    }
    return null;
}
项目:ARCLib    文件:ValidationChecker.java   
/**
 * Validates XML against XSD schema
 *
 * @param xml     XML in which the element is being searched
 * @param schemas XSD schemas against which the XML is validated
 * @throws SAXException if the XSD schema is invalid
 * @throws IOException  if the XML at the specified path is missing
 */
public static void validateWithXMLSchema(InputStream xml, InputStream[] schemas) throws IOException, SAXException {
    SchemaFactory factory =
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Source[] sources = new Source[schemas.length];
    for (int i = 0; i < schemas.length; i++) {
        sources[i] = new StreamSource(schemas[i]);
    }

    Schema schema = factory.newSchema(sources);
    Validator validator = schema.newValidator();

    try {
        validator.validate(new StreamSource(xml));
    } catch (SAXException e) {
        throw new GeneralException(e);
    }
}
项目:testing_security_development_enterprise_systems    文件:ConverterImpl.java   
@Override
public T fromXML(String xml) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);
        Unmarshaller u = context.createUnmarshaller();

        if(schemaLocation != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
            Schema schema = schemaFactory.newSchema(source);
            u.setSchema(schema);
        }

        StringReader reader = new StringReader(xml);
        T obj = (T) u.unmarshal(reader);

        return obj;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
项目:openjdk-jdk10    文件:CatalogSupportBase.java   
public void testValidation(boolean setUseCatalog, boolean useCatalog, String catalog,
        String xsd, LSResourceResolver resolver)
        throws Exception {

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // use resolver or catalog if resolver = null
    if (resolver != null) {
        factory.setResourceResolver(resolver);
    }
    if (setUseCatalog) {
        factory.setFeature(XMLConstants.USE_CATALOG, useCatalog);
    }
    factory.setProperty(CatalogFeatures.Feature.FILES.getPropertyName(), catalog);

    Schema schema = factory.newSchema(new StreamSource(new StringReader(xsd)));
    success("XMLSchema.dtd and datatypes.dtd are resolved.");
}
项目:openjdk-jdk10    文件:XmlUtil.java   
public static DocumentBuilderFactory newDocumentBuilderFactory(boolean disableSecurity) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    String featureToSet = XMLConstants.FEATURE_SECURE_PROCESSING;
    try {
        boolean securityOn = !xmlSecurityDisabled(disableSecurity);
        factory.setFeature(featureToSet, securityOn);
        factory.setNamespaceAware(true);
        if (securityOn) {
            factory.setExpandEntityReferences(false);
            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 e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support "+featureToSet+" feature!", new Object[] {factory.getClass().getName()} );
    }
    return factory;
}
项目:Hydrograph    文件:GridRowLoader.java   
private boolean validateXML(InputStream xml, InputStream xsd){
    try
    {
        SchemaFactory factory = 
                SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();

        validator.validate(new StreamSource(xml));
        return true;
    }
    catch( SAXException| IOException ex)
    {
        MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", Messages.IMPORT_XML_FORMAT_ERROR + "-\n" + ex.getMessage());
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return false;
    }
}
项目:OpenJSharp    文件:SAXBufferProcessor.java   
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);
}
项目:xpath-to-xml    文件:DomNavigator.java   
@Override
public DomNode createAttribute(DomNode parent, QName attribute) throws XmlBuilderException {
    final org.w3c.dom.Node parentNode = parent.getNode();
    if (org.w3c.dom.Node.ELEMENT_NODE != parentNode.getNodeType()) {
        throw new XmlBuilderException("Unable to append attribute to a non-element node " + parent);
    }

    try {
        Attr attr;
        final Element parentElement = (Element) parentNode;
        if (XMLConstants.NULL_NS_URI.equals(attribute.getNamespaceURI())) {
            attr = document.createAttribute(attribute.getLocalPart());
        } else {
            attr = document.createAttributeNS(attribute.getNamespaceURI(), attribute.getLocalPart());
            attr.setPrefix(attribute.getPrefix());
        }
        parentElement.setAttributeNode(attr);
        return new DomNode(attr);
    } catch (DOMException de) {
        throw new XmlBuilderException("Unable to create attribute: " + attribute, de);
    }
}
项目:openjdk-jdk10    文件:UnmarshallingContext.java   
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;
}
项目:javaide    文件:SdkStats.java   
/**
 * Helper method that returns a validator for our XSD, or null if the current Java
 * implementation can't process XSD schemas.
 *
 * @param version The version of the XML Schema.
 *        See {@link SdkStatsConstants#getXsdStream(int)}
 */
private Validator getValidator(int version) throws SAXException {
    InputStream xsdStream = SdkStatsConstants.getXsdStream(version);
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        if (factory == null) {
            return null;
        }

        // This may throw a SAX Exception if the schema itself is not a valid XSD
        Schema schema = factory.newSchema(new StreamSource(xsdStream));

        Validator validator = schema == null ? null : schema.newValidator();

        return validator;
    } finally {
        if (xsdStream != null) {
            try {
                xsdStream.close();
            } catch (IOException ignore) {}
        }
    }
}
项目:openjdk-jdk10    文件:FeaturePropagationTest.java   
public static void main(String[] args) throws Exception {
    InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
    StreamSource xsdSource = new StreamSource(reader);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    Schema schema = null;
    schema = schemaFactory.newSchema(xsdSource);

    Validator validator = schema.newValidator();

    if (validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        throw new RuntimeException("Feature set on the factory is not inherited!");
    }

}
项目:OpenJSharp    文件:UnmarshallingContext.java   
@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;
}
项目:jdk8u-jdk    文件:XMLSignatureInput.java   
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
项目:OpenJSharp    文件:SAXParserFactoryImpl.java   
/**
 * returns the particular property requested for in the underlying
 * implementation of org.xml.sax.XMLReader.
 */
public boolean getFeature(String name)
    throws ParserConfigurationException, SAXNotRecognizedException,
            SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException();
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return fSecureProcess;
    }
    // Check for valid name by creating a dummy XMLReader to get
    // feature value
    return newSAXParserImpl().getXMLReader().getFeature(name);
}
项目:incubator-netbeans    文件:CompletionUtil.java   
/**
 * Returns the appropriate AXIOM element for a given context.
 */
public static Element findAXIElementAtContext(
        CompletionContextImpl context) {
    List<QName> path = context.getPathFromRoot();
    if(path == null || path.size() == 0)
        return null;

    CompletionModel cm = null;
    QName tag = context.getPathFromRoot().get(0);
    String tns = tag.getNamespaceURI();
    if(tns != null && tns.equals(XMLConstants.NULL_NS_URI)) {
        cm = context.getActiveNoNSModel();
    } else {
        cm = context.getCompletionModelMap().get(tns);
    }
    if(cm == null)
        return null;

    AXIModel am = AXIModelFactory.getDefault().getModel(cm.getSchemaModel());
    AXIComponent parent = am.getRoot();
    if(parent == null)
        return null;

    AXIComponent child = null;
    for(QName qname : path) {
        child = findChildElement(parent, qname,context);
        parent = child;
    }

    if(child != null && (child instanceof Element))
        return (Element)child;

    return null;
}
项目:openjdk-jdk10    文件:Bug6309988.java   
public void testSAXSecureProcessingDefaultValue() {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        Assert.assertTrue(spf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), "Default value for secureProcessing feature should be true");

    } catch (Exception e) {
        Assert.fail("Exception " + e.getMessage());
    }
}
项目:incubator-netbeans    文件:CompletionContextImpl.java   
/**
 * Determines if this and previous tags are from same namespaces.
 */
private boolean fromSameNamespace(Node current, Node previous) {
    String prevPrefix = CompletionUtil.getPrefixFromTag(previous.getNodeName());
    String thisPrefix = CompletionUtil.getPrefixFromTag(current.getNodeName());
    String thisNS = (thisPrefix == null) ? declaredNamespaces.get(
        XMLConstants.XMLNS_ATTRIBUTE) :
        declaredNamespaces.get(XMLConstants.XMLNS_ATTRIBUTE+":"+thisPrefix);
    String prevNS = (prevPrefix == null) ? declaredNamespaces.get(
        XMLConstants.XMLNS_ATTRIBUTE) :
        declaredNamespaces.get(XMLConstants.XMLNS_ATTRIBUTE+":"+prevPrefix);

    return (thisNS == null && prevNS == null) ||
           (thisNS != null && thisNS.equals(prevNS)) ||
           (prevNS != null && prevNS.equals(thisNS));
}
项目:incubator-netbeans    文件:CompletionContextImpl.java   
public Boolean prefixConflicts(String prefix, String namespaceURI) {
    String n = getDeclaredNamespaces().get(XMLConstants.XMLNS_ATTRIBUTE+":"+prefix);
    if (n == null) {
        return null;
    } else {
        return n.equals(namespaceURI);
    }
}
项目:openjdk-jdk10    文件:JaxpIssue43Test.java   
@Test
public void test() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] sources = getSchemaSources();
    Schema schema = sf.newSchema(sources);
    Validator validator = schema.newValidator();
}
项目:incubator-netbeans    文件:ContextUtilities.java   
/**
 * Returns any prefix declared with this namespace. For example, if
 * the namespace was declared as xmlns:po, the prefix 'po' will be returned.
 * Returns null for declaration that contains no prefix.
 */
public static String getPrefixFromNamespaceDeclaration(String namespace) {
    if (!namespace.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) return null;
    int xmlnsLength = XMLConstants.XMLNS_ATTRIBUTE.length();
    if (namespace.length() == xmlnsLength) {
        return ""; // NOI18N
    }
    if (namespace.charAt(xmlnsLength) == ':') {
        return namespace.substring(xmlnsLength + 1);
    }
    return null;
}
项目:OpenJSharp    文件:XMLReaderManager.java   
/**
 * Get property value
 */
public Object getProperty(String name) {
    if (name.equals(XMLConstants.ACCESS_EXTERNAL_DTD)) {
        return _accessExternalDTD;
    } else if (name.equals(XalanConstants.SECURITY_MANAGER)) {
        return _xmlSecurityManager;
    }
    return null;
}
项目:openjdk-jdk10    文件:Bug6309988.java   
public void testDOMSecureProcessingDefaultValue() {
    try {
        dbf = DocumentBuilderFactory.newInstance();
        Assert.assertTrue(dbf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), "Default value for secureProcessing feature should be true");

    } catch (Exception e) {
        Assert.fail("Exception " + e.getMessage());
    }
}
项目:OpenJSharp    文件:TemplatesHandlerImpl.java   
/**
 * Default constructor
 */
protected TemplatesHandlerImpl(int indentNumber,
    TransformerFactoryImpl tfactory)
{
    _indentNumber = indentNumber;
    _tfactory = tfactory;

    // Instantiate XSLTC and get reference to parser object
    XSLTC xsltc = new XSLTC(tfactory.useServicesMechnism(), tfactory.getFeatureManager());
    if (tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING))
        xsltc.setSecureProcessing(true);

    xsltc.setProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,
            (String)tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET));
    xsltc.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD,
            (String)tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD));
    xsltc.setProperty(XalanConstants.SECURITY_MANAGER,
            tfactory.getAttribute(XalanConstants.SECURITY_MANAGER));


    if ("true".equals(tfactory.getAttribute(TransformerFactoryImpl.ENABLE_INLINING)))
        xsltc.setTemplateInlining(true);
    else
        xsltc.setTemplateInlining(false);

    _parser = xsltc.getParser();
}