Java 类javax.xml.validation.Schema 实例源码

项目:openjdk-jdk10    文件:JaxpIssue49.java   
@Test
public void testValidatorTest() throws Exception {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        String file = getClass().getResource("types.xsd").getFile();
        Source[] sources = new Source[] { new StreamSource(new FileInputStream(file), file) };
        Schema schema = sf.newSchema(sources);
        validator = schema.newValidator();
        validate();
    } catch (Exception e) {
        Node node = (Node) validator.getProperty("http://apache.org/xml/properties/dom/current-element-node");
        if (node != null) {
            System.out.println("Node: " + node.getLocalName());
        } else
            Assert.fail("No node returned");
    }
}
项目:incubator-netbeans    文件:XsdBasedValidator.java   
protected Schema getCompiledSchema(Source[] schemas,
        LSResourceResolver lsResourceResolver,
        ErrorHandler errorHandler) {

    Schema schema = null;

    // Create a compiled Schema object.
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(lsResourceResolver);
    schemaFactory.setErrorHandler(errorHandler);
    try {
        schema = schemaFactory.newSchema(schemas);            
    } catch(SAXException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getCompiledSchema", ex);
    } 

    return schema;
}
项目:incubator-netbeans    文件:SchemaXsdBasedValidator.java   
protected Schema getSchema(Model model) {
    if (! (model instanceof SchemaModel)) {
        return null;
    }

    // This will not be used as validate(.....) method is being overridden here.
    // So just return a schema returned by newSchema().
    if(schema == null) {
        try {
            schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema();
        } catch(SAXException ex) {
            assert false: "Error while creating compiled schema for"; //NOI18N
        }
    }
    return schema;
}
项目:incubator-netbeans    文件:SchemaXsdBasedValidator.java   
@Override
  protected void validate(Model model, Schema schema, XsdBasedValidator.Handler handler) {
      try {
          SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
          CatalogModel cm = (CatalogModel) model.getModelSource().getLookup()
.lookup(CatalogModel.class);
   if (cm != null) {
              sf.setResourceResolver(cm);
          }
          sf.setErrorHandler(handler);
          Source saxSource = getSource(model, handler);
          if (saxSource == null) {
              return;
          }
          sf.newSchema(saxSource);
      } catch(SAXException sax) {
          //already processed by handler
      } catch(Exception ex) {
          handler.logValidationErrors(Validator.ResultType.ERROR, ex.getMessage());
      }
  }
项目:incubator-netbeans    文件:XMLUtil.java   
/**
 * Check whether a DOM tree is valid according to a schema.
 * Example of usage:
 * <pre>
 * Element fragment = ...;
 * SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 * Schema s = f.newSchema(This.class.getResource("something.xsd"));
 * try {
 *     XMLUtil.validate(fragment, s);
 *     // valid
 * } catch (SAXException x) {
 *     // invalid
 * }
 * </pre>
 * @param data a DOM tree
 * @param schema a parsed schema
 * @throws SAXException if validation failed
 * @since org.openide.util 7.17
 */
public static void validate(Element data, Schema schema) throws SAXException {
    Validator v = schema.newValidator();
    final SAXException[] error = {null};
    v.setErrorHandler(new ErrorHandler() {
        public @Override void warning(SAXParseException x) throws SAXException {}
        public @Override void error(SAXParseException x) throws SAXException {
            // Just rethrowing it is bad because it will also print it to stderr.
            error[0] = x;
        }
        public @Override void fatalError(SAXParseException x) throws SAXException {
            error[0] = x;
        }
    });
    try {
        v.validate(new DOMSource(fixupAttrs(data)));
    } catch (IOException x) {
        assert false : x;
    }
    if (error[0] != null) {
        throw error[0];
    }
}
项目: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));
        }
    }
项目:joai-project    文件:XMLValidator.java   
/**
 *  Constructor for the XMLValidator object
 *
 * @param  uri            NOT YET DOCUMENTED
 * @exception  Exception  NOT YET DOCUMENTED
 */
public XMLValidator(URI uri) throws Exception {
    this.uri = uri;
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    try {
        String uriScheme = uri.getScheme();
        if (uriScheme != null && uriScheme.equals("http"))
            schema = factory.newSchema(uri.toURL());
        else
            schema = factory.newSchema(new File(uri));
        if (schema == null)
            throw new Exception("Schema could not be read from " + uri.toString());
    } catch (Throwable t) {
        throw new Exception("Validator init error: " + t.getMessage());
    }

    this.validator = schema.newValidator();
}
项目:joai-project    文件:ValidatorTester.java   
public ValidatorTester (String schemaURI) throws Exception {
    this.schemaURI = schemaURI;
    prtln ("schemaNS_URI: " + XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Schema schema = null;
    try {
        if (schemaURI.startsWith("http://"))
            schema = factory.newSchema(new URL (schemaURI));
        else
            schema = factory.newSchema(new File (schemaURI));
        if (schema == null)
            throw new Exception ("Schema could not be read from " + schemaURI);
    } catch (Throwable t) {
        throw new Exception ("Validator init error: " + t.getMessage());
    }

    this.validator = schema.newValidator();
}
项目:oscm    文件:ServiceProvisioningServiceBeanImportExportSchemaIT.java   
private void verifyXML(byte[] xml) throws IOException, SAXException,
        ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

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

    ClassLoader classLoader = Thread.currentThread()
            .getContextClassLoader();
    if (classLoader == null) {
        classLoader = getClass().getClassLoader();
    }

    final Schema schema;
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), "TechnicalServices.xsd")) {
        schema = sf.newSchema(new StreamSource(inputStream));
    }
    spf.setSchema(schema);

    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    ErrorHandler errorHandler = new MyErrorHandler();
    reader.setErrorHandler(errorHandler);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
}
项目:openjdk-jdk10    文件:CR6708840Test.java   
@Test
public final void testStream() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();
        Source xmlSource = new javax.xml.transform.stream.StreamSource(new File(CR6708840Test.class.getResource("gMonths.xml").toURI()));
        schemaValidator.validate(xmlSource);

    } catch (NullPointerException ne) {
        Assert.fail("NullPointerException when result is not specified.");
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
项目:oscm    文件:BillingDataRetrievalServiceBean.java   
@Override
public Schema loadSchemaFiles() {
    try (InputStream brStream = ResourceLoader.getResourceAsStream(
            BillingDataRetrievalServiceBean.class, "BillingResult.xsd");
            InputStream localeStream = ResourceLoader.getResourceAsStream(
                    BillingDataRetrievalServiceBean.class, "Locale.xsd")) {

        URL billingResultUri = ResourceLoader.getResource(
                BillingDataRetrievalServiceBean.class, "BillingResult.xsd");
        URL localeUri = ResourceLoader.getResource(
                BillingDataRetrievalServiceBean.class, "Locale.xsd");
        SchemaFactory schemaFactory = SchemaFactory
                .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        StreamSource[] sourceDocuments = new StreamSource[] {
                new StreamSource(localeStream, localeUri.getPath()),
                new StreamSource(brStream, billingResultUri.getPath()) };
        return schemaFactory.newSchema(sourceDocuments);
    } catch (SAXException | IOException e) {
        throw new BillingRunFailed("Schema files couldn't be loaded", e);
    }
}
项目:openjdk-jdk10    文件:Bug4971605.java   
@Test
public void test1() throws Exception {
    String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <element name='test'/>\n" + "</schema>\n";

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
    Assert.assertNotNull(document);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
    Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
项目:openjdk-jdk10    文件:Bug6975265Test.java   
@Test
public void test() {
    try {
        File dir = new File(Bug6975265Test.class.getResource("Bug6975265").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) {
                System.out.println(spe.getMessage());
                continue;
            }
        }
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
项目:openjdk-jdk10    文件:Bug6943252Test.java   
@Test
public void test() {

    String dir = Bug6943252Test.class.getResource("Bug6943252In").getPath();
    File inputs = new File(dir);
    File[] files = inputs.listFiles();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (int i = 0; i < files.length; i++) {
        try {
            Schema schema = schemaFactory.newSchema(new StreamSource(files[i]));
            Assert.fail(files[i].getName() + "should fail");
        } catch (SAXException e) {
            // expected
            System.out.println(files[i].getName() + ":");
            System.out.println(e.getMessage());
        }
    }

}
项目: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());
    }


}
项目:Hydrograph    文件:HydrographJobGenerator.java   
/**
 * Creates the object of type {@link HydrographJob} from the graph xml of type
 * {@link Document}.
 * 
 * The method uses jaxb framework to unmarshall the xml document
 * 
 * @param graphDocument
 *            the xml document with all the graph contents to unmarshall
 * @return an object of type "{@link HydrographJob}
 * @throws SAXException
 * @throws IOException
 */
public HydrographJob createHydrographJob(Document graphDocument, String xsdLocation) throws SAXException {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(ClassLoader.getSystemResource(xsdLocation));
        LOG.trace("Creating HydrographJob object from jaxb");
        context = JAXBContext.newInstance(Graph.class);
        unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ComponentValidationEventHandler());
        graph = (Graph) unmarshaller.unmarshal(graphDocument);
        HydrographJob hydrographJob = new HydrographJob(graph);
        LOG.trace("HydrographJob object created successfully");
        return hydrographJob;

    } catch (JAXBException e) {
        LOG.error("Error while creating JAXB objects from job XML.", e);
        throw new RuntimeException("Error while creating JAXB objects from job XML.", e);
    }
}
项目:lams    文件:SchemaBuilder.java   
/**
 * Builds a schema from the given schema sources.
 * 
 * @param lang schema language, must not be null
 * @param schemaFilesOrDirectories files or directories which contains schema sources
 * 
 * @return the constructed schema
 * 
 * @throws SAXException thrown if there is a problem converting the schema sources in to a schema
 */
public static Schema buildSchema(SchemaLanguage lang, File[] schemaFilesOrDirectories) throws SAXException {
    if(schemaFilesOrDirectories == null || schemaFilesOrDirectories.length == 0){
        return null;
    }

    ArrayList<File> schemaFiles = new ArrayList<File>();
    getSchemaFiles(lang, schemaFilesOrDirectories, schemaFiles);

    if(schemaFiles.isEmpty()){
        return null;
    }

    ArrayList<Source> schemaSources = new ArrayList<Source>();
    for(File schemaFile : schemaFiles){
        schemaSources.add(new StreamSource(schemaFile));
    }
    return buildSchema(lang, schemaSources.toArray(new Source[]{}));
}
项目: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());
    }


}
项目:lams    文件:SchemaBuilder.java   
/**
 * Builds a schema from the given schema sources.
 * 
 * @param lang schema language, must not be null
 * @param schemaSources schema sources, must not be null
 * 
 * @return the constructed schema
 * 
 * @throws SAXException thrown if there is a problem converting the schema sources in to a schema
 */
protected static Schema buildSchema(SchemaLanguage lang, Source[] schemaSources) throws SAXException {
    if(lang == null){
        throw new IllegalArgumentException("Schema language may not be null");
    }

    if(schemaSources == null){
        throw new IllegalArgumentException("Schema sources may not be null");
    }

    SchemaFactory schemaFactory;

    if (lang == SchemaLanguage.XML) {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    } else {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI);
    }

    schemaFactory.setErrorHandler(new LoggingErrorHandler(LoggerFactory.getLogger(SchemaBuilder.class)));
    return schemaFactory.newSchema(schemaSources);
}
项目:openjdk-jdk10    文件:Bug6967214Test.java   
@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();

    }
}
项目:trust-java    文件:ValidationUtils.java   
/**
 * Validates provided XML API response against the XSD {@link Schema}
 *
 * @param schema W3C XML {@link Schema} instance
 * @param xmlApiResponsePayload XML API response payload
 */
public static void validateApiResponseAgainstXsd(Schema schema,
                                                 String xmlApiResponsePayload)
        throws ParserConfigurationException, SAXException, IOException {
    if(StringUtils.
            isNotBlank(
                    xmlApiResponsePayload)) {
        LOG.info("About to validate the API response against the XSD Schema ...");

        DocumentBuilderFactory documentBuilderFactory =
                DocumentBuilderFactory.
                        newInstance();
        documentBuilderFactory.
                setNamespaceAware(true);

        schema.newValidator().
                validate(
                        new DOMSource(
                                documentBuilderFactory.
                                        newDocumentBuilder().
                                        parse(new InputSource(
                                                new StringReader(
                                                        xmlApiResponsePayload)))));
    }
}
项目:jmx-prometheus-exporter    文件:SchemaGenerator.java   
public static @NotNull Optional<Schema> load(@NotNull JAXBContext context) {
  try {
    final List<ByteArrayOutputStream> outputs = new ArrayList<>();
    context.generateSchema(new SchemaOutputResolver() {
      @Override
      public @NotNull Result createOutput(@NotNull String namespace, @NotNull String suggestedFileName) {
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        outputs.add(output);
        final StreamResult result = new StreamResult(output);
        result.setSystemId("");
        return result;
      }
    });
    return Optional.ofNullable(
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(outputs.stream()
                .map(ByteArrayOutputStream::toByteArray)
                .map(ByteArrayInputStream::new)
                .map(input -> new StreamSource(input, ""))
                .toArray(StreamSource[]::new))
    );
  } catch (IOException | SAXException e) {
    logger.error("Failed to load schema", e);
    return Optional.empty();
  }
}
项目: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) {}
        }
    }
}
项目:javaide    文件:AddonsListFetcher.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 SdkAddonsListConstants#getXsdStream(int)}
 */
private Validator getValidator(int version) throws SAXException {
    InputStream xsdStream = SdkAddonsListConstants.getXsdStream(version);
    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;
}
项目:openjdk-jdk10    文件:Issue682Test.java   
@Test
public void test() {
    try {
        Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(testFile));
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setSchema(schema);
        // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
        // true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(new DefaultHandler());
        // InputStream input =
        // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");
        InputStream input = getClass().getResourceAsStream("Issue682.xml");
        System.out.println("Parse InputStream:");
        xmlReader.parse(new InputSource(input));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

}
项目:nifi-registry    文件:IdentityProviderFactory.java   
private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();

    // load the users from the specified file
    if (loginIdentityProvidersConfigurationFile.exists()) {
        try {
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

            // attempt to unmarshal
            XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the login identity provider configuration file at: " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the login identity provider configuration file at " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
    }
}
项目:openjdk-jdk10    文件:AuctionController.java   
/**
 * Check grammar caching with imported schemas.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/coins.xsd">coins.xsd</a>
 * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
 */
@Test
public void testGetOwnerItemList() throws Exception {
    String xsdFile = XML_DIR + "coins.xsd";
    String xmlFile = XML_DIR + "coins.xml";

    try(FileInputStream fis = new FileInputStream(xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
        dbf.setValidating(false);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(((xsdFile))));

        MyErrorHandler eh = new MyErrorHandler();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(eh);

        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document document = docBuilder.parse(fis);
        validator.validate(new DOMSource(document), new DOMResult());
        assertFalse(eh.isAnyError());
    }
}
项目:Artemis-JON-plugin    文件:PluginDescriptorUtil.java   
/**
 * Transforms the given string into a plugin descriptor object.
 *
 * @param string The plugin descriptor specified as a string
 * @return The {@link PluginDescriptor}
 */
public static PluginDescriptor toPluginDescriptor(String string) {
   try {
      JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);
      URL pluginSchemaURL = PluginMetadataParser.class.getClassLoader().getResource("rhq-plugin.xsd");
      Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(pluginSchemaURL);

      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      ValidationEventCollector vec = new ValidationEventCollector();
      unmarshaller.setEventHandler(vec);
      unmarshaller.setSchema(pluginSchema);

      StringReader reader = new StringReader(string);

      return (PluginDescriptor) unmarshaller.unmarshal(reader);
   }
   catch (Exception e) {
      throw new RuntimeException(e);
   }
}
项目: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    文件:Bug6531160.java   
@Test
public void testDOMLevel1Validation() throws Exception {
    SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = fact.newSchema(new StreamSource(new StringReader(XSD)));
    DocumentBuilderFactory docfact = DocumentBuilderFactory.newInstance();
    docfact.setNamespaceAware(true);

    Document doc = docfact.newDocumentBuilder().newDocument();
    doc.appendChild(doc.createElement("root"));

    try {
        schema.newValidator().validate(new DOMSource(doc));
    } catch (SAXParseException e) {
        Assert.fail("Validation failed: " + e.getMessage());
    }
}
项目:openjdk-jdk10    文件:ValidatorTest.java   
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));

        // Get a Validator which can be used to validate instance document
        // against this grammar.
        Validator validator = schema.newValidator();
        ErrorHandler eh = new ErrorHandlerImpl();
        validator.setErrorHandler(eh);

        // Validate this instance document against the
        // Instance document supplied
        validator.validate(src, result);
    } catch (Exception ex) {
        throw ex;
    }
}
项目:keycloak-protocol-cas    文件:ServiceResponseTest.java   
/**
 * Parse XML document and validate against CAS schema
 */
private Document parseAndValidate(String xml) throws Exception {
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(getClass().getResource("cas-response-schema.xsd"));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setSchema(schema);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new FatalAdapter(new DefaultHandler()));
    return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
}
项目:openjdk-jdk10    文件:Bug6970890Test.java   
@Test
public void test_RegexTest_1319() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(Bug6970890Test.class.getResourceAsStream("Bug6970890.xsd")));

    } catch (SAXException e) {
        e.printStackTrace();
        Assert.fail("The - character is a valid character range at the beginning or end of a positive character group");
    }
}
项目:openjdk-jdk10    文件:CR6708840Test.java   
/**
 * workaround before the fix: provide a result
 */
@Test
public final void testStAXWResult() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        File resultFile = new File(USER_DIR + "gMonths.result.xml");
        if (resultFile.exists()) {
            resultFile.delete();
        }

        Result xmlResult = new javax.xml.transform.stax.StAXResult(XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(resultFile)));
        schemaValidator.validate(staxSrc, xmlResult);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:Bug4969042.java   
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    StringReader reader = new StringReader(xsd);
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
项目:incubator-netbeans    文件:XsdBasedValidator.java   
/**
 * Entry point to validate a model.
 * @param model Model to validate.
 * @param validation Reference to Validation object.
 * @param validationType Type of validation. Complete(slow) or partial(fast).
 * @return ValidationResults.
 */
public ValidationResult validate(Model model, Validation validation, Validation.ValidationType validationType) {
    Schema schema = getSchema(model);

    if (schema == null) {
        return null;
    }
    Handler handler = new Handler(model);
    validate(model, schema, handler);
    Collection<ResultItem> results = handler.getResultItems();
    List<Model> validateds = Collections.singletonList(model);

    return new ValidationResult(results, validateds);
}
项目:openjdk-jdk10    文件:Bug6977201Test.java   
public void validate(String xsd, String xml) {
    try {
        Schema schema = schemaFactory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        Assert.fail("should report error");
    } catch (Exception e) {
        System.out.println(e.getMessage());
        // e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:Bug4966232.java   
@Test
public void testSchemaFactory01() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    InputSource is = new InputSource(Bug4966232.class.getResourceAsStream("test.xsd"));
    SAXSource ss = new SAXSource(is);
    Schema s = sf.newSchema(ss);
    Assert.assertNotNull(s);
}
项目:openjdk-jdk10    文件:Bug6509668.java   
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
项目:xitk    文件:P11Conf.java   
public P11Conf(InputStream confStream, PasswordResolver passwordResolver)
        throws InvalidConfException, IOException {
    ParamUtil.requireNonNull("confStream", confStream);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        SchemaFactory schemaFact = SchemaFactory.newInstance(
                javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFact.newSchema(getClass().getResource( "/xsd/pkcs11-conf.xsd"));
        unmarshaller.setSchema(schema);
        @SuppressWarnings("unchecked")
        JAXBElement<PKCS11ConfType> rootElement = (JAXBElement<PKCS11ConfType>)
                unmarshaller.unmarshal(confStream);
        PKCS11ConfType pkcs11Conf = rootElement.getValue();
        ModulesType modulesType = pkcs11Conf.getModules();

        Map<String, P11ModuleConf> confs = new HashMap<>();
        for (ModuleType moduleType : modulesType.getModule()) {
            P11ModuleConf conf = new P11ModuleConf(moduleType, passwordResolver);
            confs.put(conf.name(), conf);
        }

        if (!confs.containsKey(P11CryptServiceFactory.DEFAULT_P11MODULE_NAME)) {
            throw new InvalidConfException("module '"
                    + P11CryptServiceFactory.DEFAULT_P11MODULE_NAME + "' is not defined");
        }
        this.moduleConfs = Collections.unmodifiableMap(confs);
        this.moduleNames = Collections.unmodifiableSet(new HashSet<>(confs.keySet()));
    } catch (JAXBException | SAXException ex) {
        final String exceptionMsg = (ex instanceof JAXBException)
                ? getMessage((JAXBException) ex) : ex.getMessage();
        LogUtil.error(LOG, ex, exceptionMsg);
        throw new InvalidConfException("invalid PKCS#11 configuration");
    } finally {
        confStream.close();
    }
}