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

项目:openjdk-jdk10    文件:Bug6946312Test.java   
@Test
public void test() throws SAXException, ParserConfigurationException, IOException {
    Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(new StringReader(xmlSchema)));

    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 MyContentHandler());

    // InputStream input =
    // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");

    InputStream input = getClass().getResourceAsStream("Bug6946312.xml");
    System.out.println("Parse InputStream:");
    xmlReader.parse(new InputSource(input));
    if (!charEvent) {
        Assert.fail("missing character event");
    }
}
项目:oscm    文件:ProductImportParser.java   
/**
 * Parse the given XML string an create/update the corresponding entities
 * 
 * @param xml
 *            the XML string
 * @return the parse return code
 * @throws Exception
 */
public int parse(byte[] xml) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), getSchemaName())) {
        Schema schema = sf.newSchema(new StreamSource(inputStream));
        spf.setSchema(schema);
    }
    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX
            + Constants.DISALLOW_DOCTYPE_DECL_FEATURE, true);
    reader.setContentHandler(this);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
    return 0;
}
项目: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());
        }
    }

}
项目:incubator-netbeans    文件:XsdBasedValidator.java   
/**
 * Subclasses can use this to get a compiled schema object.
 * @param schemas Input stream of schemas.
 * @param lsResourceResolver  resolver can be supplied optionally. Otherwise pass null.
 * @return  Compiled Schema object.
 */
protected Schema getCompiledSchema(InputStream[] schemas,
        LSResourceResolver lsResourceResolver) {

    Schema schema = null;
    // Convert InputStream[] to StreamSource[]
    StreamSource[] schemaStreamSources = new StreamSource[schemas.length];
    for(int index1=0 ; index1<schemas.length ; index1++)
        schemaStreamSources[index1] = new StreamSource(schemas[index1]);

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

    return schema;
}
项目: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   
@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());
      }
  }
项目: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();
}
项目:xitk    文件:FileHttpServersConf.java   
public void setConfFile(String confFile) throws Exception {
    this.confFile = confFile;

    Object root;
    try {
        JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
        final SchemaFactory schemaFact = SchemaFactory.newInstance(
                javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = ObjectFactory.class.getResource("/xsd/httpserver.xsd");
        jaxbUnmarshaller.setSchema(schemaFact.newSchema(url));

        root = jaxbUnmarshaller.unmarshal(new File(confFile));
    } catch (Exception ex) {
        throw new Exception("parsing config file failed, message: " + ex.getMessage(), ex);
    }

    if (root instanceof Httpservers) {
        this.conf = (Httpservers) root;
    } else if (root instanceof JAXBElement) {
        this.conf = (Httpservers) ((JAXBElement<?>) root).getValue();
    } else {
        throw new Exception("invalid root element type");
    }
}
项目: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;
    }
}
项目: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);
    }
}
项目:sonar-php-rules    文件:IntegrationTest.java   
@Test
public void rulesXmlIsValid() {
    RulesXmlReaderFactory xmlFactory = new RulesXmlReaderFactory();

    try (Reader xmlReader = xmlFactory.newRulesXmlReader(); Reader xsdReader = xmlFactory.newRulesXsdReader()) {
        StreamSource xsdStreamSource = new StreamSource(xsdReader);
        StreamSource xmlStreamSource = new StreamSource(xmlReader);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(xsdStreamSource);
        Validator validator = schema.newValidator();

        validator.validate(xmlStreamSource);
    } catch (Exception e) {
        fail("rules.xml does not conform to schema!");
    }
}
项目:testing_security_development_enterprise_systems    文件:ConverterImpl.java   
@Override
public String toXML(T obj) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);

        Marshaller m = context.createMarshaller();
        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);
            m.setSchema(schema);
        }

        StringWriter writer = new StringWriter();

        m.marshal(obj, writer);
        String xml = writer.toString();

        return xml;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
项目: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;
    }
}
项目:lams    文件:XMLConfigurator.java   
/**
 * Constructor.
 * 
 * @param retainXML whether to retain the XML configuration elements within the {@link Configuration}.
 * 
 * @throws ConfigurationException thrown if the validation schema for configuration files can not be created
 * 
 * @deprecated this method will be removed once {@link Configuration} no longer has the option to store the XML configuration fragements
 */
public XMLConfigurator(boolean retainXML) throws ConfigurationException {
    retainXMLConfiguration = retainXML;
    parserPool = new BasicParserPool();
    SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source schemaSource = new StreamSource(XMLConfigurator.class
            .getResourceAsStream(XMLConstants.XMLTOOLING_SCHEMA_LOCATION));
    try {
        configurationSchema = factory.newSchema(schemaSource);

        parserPool.setIgnoreComments(true);
        parserPool.setIgnoreElementContentWhitespace(true);
        parserPool.setSchema(configurationSchema);
    } catch (SAXException e) {
        throw new ConfigurationException("Unable to read XMLTooling configuration schema", e);
    }
}
项目:nifi-registry    文件:StandardProviderFactory.java   
@PostConstruct
@Override
public synchronized void initialize() throws ProviderFactoryException {
    if (providersHolder.get() == null) {
        final File providersConfigFile = properties.getProvidersConfigurationFile();
        if (providersConfigFile.exists()) {
            try {
                // find the schema
                final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                final Schema schema = schemaFactory.newSchema(StandardProviderFactory.class.getResource(PROVIDERS_XSD));

                // attempt to unmarshal
                final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
                unmarshaller.setSchema(schema);

                // set the holder for later use
                final JAXBElement<Providers> element = unmarshaller.unmarshal(new StreamSource(providersConfigFile), Providers.class);
                providersHolder.set(element.getValue());
            } catch (SAXException | JAXBException e) {
                throw new ProviderFactoryException("Unable to load the providers configuration file at: " + providersConfigFile.getAbsolutePath(), e);
            }
        } else {
            throw new ProviderFactoryException("Unable to find the providers configuration file at " + providersConfigFile.getAbsolutePath());
        }
    }
}
项目: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;
}
项目:page-content-tester    文件:XmlErrorHandler.java   
@SneakyThrows
public void validateXml(String xsdPath, boolean namespaceAware, String schemaLanguage, String pageBody) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(namespaceAware);

    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(pageBody)));

    SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
    Source schemaSource = new StreamSource(getClass().getResourceAsStream(xsdPath));

    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    Source source = new DOMSource(document);
    validator.setErrorHandler(new XmlErrorHandler());
    validator.validate(source);
}
项目: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.");
}
项目:OpenJSharp    文件:SchemaCache.java   
public ValidatorHandler newValidator() {
    synchronized(this) {
        if(schema==null) {
            try {
                // do not disable secure processing - these are well-known schemas
                SchemaFactory sf = XmlFactory.createSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI, false);
                schema = allowExternalAccess(sf, "file", false).newSchema(source);
            } catch (SAXException e) {
                // we make sure that the schema is correct before we ship.
                throw new AssertionError(e);
            }
        }
    }

    ValidatorHandler handler = schema.newValidatorHandler();
    return handler;
}
项目:OpenJSharp    文件:DOMForest.java   
/**
 * Checks the correctness of the XML Schema documents and return true
 * if it's OK.
 *
 * <p>
 * This method performs a weaker version of the tests where error messages
 * are provided without line number information. So whenever possible
 * use {@link SchemaConstraintChecker}.
 *
 * @see SchemaConstraintChecker
 */
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
    try {
        boolean disableXmlSecurity = false;
        if (options != null) {
            disableXmlSecurity = options.disableXmlSecurity;
        }
        SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
        ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
        sf.setErrorHandler(filter);
        Set<String> roots = getRootDocuments();
        Source[] sources = new Source[roots.size()];
        int i=0;
        for (String root : roots) {
            sources[i++] = new DOMSource(get(root),root);
        }
        sf.newSchema(sources);
        return !filter.hadError();
    } catch (SAXException e) {
        // the errors should have been reported
        return false;
    }
}
项目: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;
 }
}
项目: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;
    }
}
项目: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);
    }
}
项目:Hydrograph    文件:DebugUtils.java   
/**
 * Creates the object of type {@link HydrographDebugInfo} from the graph xml of type
 * {@link Document}.
 * <p>
 * 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 HydrographDebugInfo}
 * @throws SAXException
 */
public static HydrographDebugInfo createHydrographDebugInfo(Document graphDocument, String debugXSDLocation) throws SAXException {
    try {
        LOG.trace("Creating DebugJAXB object.");
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(ClassLoader.getSystemResource(debugXSDLocation));
        JAXBContext context = JAXBContext.newInstance(Debug.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ComponentValidationEventHandler());
        Debug debug = (Debug) unmarshaller.unmarshal(graphDocument);
        HydrographDebugInfo hydrographDebugInfo = new HydrographDebugInfo(debug);
        LOG.trace("DebugJAXB object created successfully");
        return hydrographDebugInfo;
    } catch (JAXBException e) {
        LOG.error("Error while creating JAXB objects from debug XML.", e);
        throw new RuntimeException("Error while creating JAXB objects from debug XML.", e);
    }
}
项目: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();
  }
}
项目:MaxSim    文件:Parser.java   
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(false);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
项目:MaxSim    文件:Parser.java   
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(false);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
项目: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    文件:TypeInfoProviderTest.java   
@Test
public void test() throws SAXException, ParserConfigurationException, IOException {

    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File(XML_DIR + "shiporder11.xsd"));
    validatorHandler = schema.newValidatorHandler();
    MyDefaultHandler myDefaultHandler = new MyDefaultHandler();
    validatorHandler.setContentHandler(myDefaultHandler);

    InputSource is = new InputSource(filenameToURL(XML_DIR + "shiporder11.xml"));

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader();
    xmlReader.setContentHandler(validatorHandler);
    xmlReader.parse(is);

}
项目:openjdk-jdk10    文件:Bug5072946.java   
@Test
public void test1() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd"));
    Validator v = s.newValidator();

    DOMResult r = new DOMResult();
    // r.setNode(dbf.newDocumentBuilder().newDocument());
    v.validate(new DOMSource(dom), r);

    Node node = r.getNode();
    Assert.assertNotNull(node);
    Node fc = node.getFirstChild();
    Assert.assertTrue(fc instanceof Element);
    Element e = (Element) fc;

    Assert.assertEquals("value", e.getAttribute("foo"));
}
项目:openjdk-jdk10    文件:Bug7143711Test.java   
@Test
public void testValidation_SAX_withSM() {
    System.out.println("Validation using SAX Source with security manager:");
    setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");

    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // should not allow
        factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
        if ((boolean) factory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
            Assert.fail("should not override in secure mode");
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());

    } finally {
        clearSystemProperty(SAX_FACTORY_ID);
    }
}
项目:openjdk-jdk10    文件:DOMForest.java   
/**
 * Checks the correctness of the XML Schema documents and return true
 * if it's OK.
 *
 * <p>
 * This method performs a weaker version of the tests where error messages
 * are provided without line number information. So whenever possible
 * use {@link SchemaConstraintChecker}.
 *
 * @see SchemaConstraintChecker
 */
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
    try {
        boolean disableXmlSecurity = false;
        if (options != null) {
            disableXmlSecurity = options.disableXmlSecurity;
        }
        SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
        ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
        sf.setErrorHandler(filter);
        Set<String> roots = getRootDocuments();
        Source[] sources = new Source[roots.size()];
        int i=0;
        for (String root : roots) {
            sources[i++] = new DOMSource(get(root),root);
        }
        sf.newSchema(sources);
        return !filter.hadError();
    } catch (SAXException e) {
        // the errors should have been reported
        return false;
    }
}
项目: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());
    }

}
项目: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();
    }
}
项目:openjdk-jdk10    文件:ParticlesIg004Test.java   
@Test
public void testParticleslg004() {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        String xsdFile = "particlesIg004.xsd";
        Schema schema = sf.newSchema(new File(getClass().getResource(xsdFile).toURI()));
        Validator validator = schema.newValidator();
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}
项目:openjdk-jdk10    文件:ValidationWarningsTest.java   
void doOneTestIteration() throws Exception {
    Source src = new StreamSource(new StringReader(xml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXSource xsdSource = new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes())));
    Schema schema = schemaFactory.newSchema(xsdSource);
    Validator v = schema.newValidator();
    v.validate(src);
}
项目:joai-project    文件:ValidatorTester.java   
public static void validate (String xmlPath, String xsdPath) throws Exception {

    // create a SchemaFactory capable of understanding WXS schemas
    prtln ("schemaNS_URI: " + XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Schema schema = null;

    /* use schema from file */
    schema = factory.newSchema(new File(xsdPath));

    /* use schema from web */
    // String adnURI = "http://www.dlese.org/Metadata/adn-item/0.6.50/record.xsd";
    // schema = factory.newSchema(new URL(adnURI));

    /* use schema from instance document */
    // schema = factory.newSchema();

    /* create a Validator instance, which can be used to validate an instance document */
    Validator validator = schema.newValidator();

    /* the xml to be validated */
    Source mysource = new StreamSource (xmlPath);

    // validation errors passed as SAXException message
    try {
        validator.validate(mysource);
    } catch (SAXException e) {
        prtln (e.getMessage());
    }
}
项目: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();
    }
}