org.xml.sax.SAXNotRecognizedException#javax.xml.validation.Schema源码实例Demo

下面列出了org.xml.sax.SAXNotRecognizedException#javax.xml.validation.Schema 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: 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());
      }
  }
 
源代码2 项目: jpmml-model   文件: ValidationExample.java
@Override
public Unmarshaller createUnmarshaller() throws JAXBException {
	Unmarshaller unmarshaller = super.createUnmarshaller();

	Schema schema;

	try {
		schema = JAXBUtil.getSchema();
	} catch(Exception e){
		throw new RuntimeException(e);
	}

	unmarshaller.setSchema(schema);
	unmarshaller.setEventHandler(new SimpleValidationEventHandler());

	return unmarshaller;
}
 
源代码3 项目: cs-actions   文件: XmlResultValidator.java
private void validateAgainstXsdSchema(AbbyyInput abbyyInput, String xml) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream xsdStream = getClass().getResourceAsStream(xsdSchemaPath);
    Schema schema = factory.newSchema(new StreamSource(xsdStream));
    Validator xmlValidator = schema.newValidator();

    xml = EncodingUtils.toUTF8(xml, abbyyInput.getResponseCharacterSet())
            .trim().replaceFirst("^([\\W]+)<", "<")
            .replaceFirst("(\\uFFFD)+$", ">")
            .replace("xmlns:xsi=\"@link\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");

    try {
        StringReader xmlReader = new StringReader(xml);
        xmlValidator.validate(new StreamSource(xmlReader));
    } catch (SAXException ex) {
        throw new ValidationException(ExceptionMsgs.RESPONSE_VALIDATION_ERROR + ex.getMessage());
    }
}
 
源代码4 项目: validator   文件: ConversionService.java
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) {
    if (model == null) {
        throw new ConversionExeption("Can not serialize null");
    }
    try ( final StringWriter w = new StringWriter() ) {
        final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector();
        final Marshaller marshaller = getJaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setSchema(schema);
        marshaller.setEventHandler(handler);
        final XMLOutputFactory xof = XMLOutputFactory.newFactory();
        final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
        if (null == introspector.getElementName(model)) {
            final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
            marshaller.marshal(jaxbElement, xmlStreamWriter);
        } else {
            marshaller.marshal(model, xmlStreamWriter);
        }
        xmlStreamWriter.flush();
        return w.toString();
    } catch (final JAXBException | IOException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e);
    }
}
 
源代码5 项目: 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;
}
 
源代码6 项目: 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());
    }
}
 
源代码7 项目: ph-commons   文件: GenericJAXBMarshaller.java
/**
 * @param aClassLoader
 *        The class loader to be used for XML schema resolving. May be
 *        <code>null</code>.
 * @return The JAXB unmarshaller to use. Never <code>null</code>.
 * @throws JAXBException
 *         In case the creation fails.
 */
@Nonnull
private Unmarshaller _createUnmarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException
{
  final JAXBContext aJAXBContext = getJAXBContext (aClassLoader);

  // create an Unmarshaller
  final Unmarshaller aUnmarshaller = aJAXBContext.createUnmarshaller ();
  if (m_aVEHFactory != null)
  {
    // Create and set a new event handler
    final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aUnmarshaller.getEventHandler ());
    if (aEvHdl != null)
      aUnmarshaller.setEventHandler (aEvHdl);
  }

  // Set XSD (if any)
  final Schema aValidationSchema = createValidationSchema ();
  if (aValidationSchema != null)
    aUnmarshaller.setSchema (aValidationSchema);

  return aUnmarshaller;
}
 
源代码8 项目: arctic-sea   文件: EReportingHeaderEncoderTest.java
private void xmlValidation(ByteArrayOutputStream baos)
        throws XMLStreamException, OwsExceptionReport, IOException,
               SAXException, MalformedURLException {
    ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
    URL schemaFile = new URL(AqdConstants.NS_AQD_SCHEMA);
    Source xmlFile = new StreamSource(in);
    SchemaFactory schemaFactory = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    try {
        validator.validate(xmlFile);
    } catch (SAXException e) {
        Assertions.fail(e.getLocalizedMessage());
    }
}
 
源代码9 项目: proarc   文件: WorkflowProfiles.java
private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}
 
源代码10 项目: cxf   文件: AbstractJAXBProvider.java
protected Unmarshaller createUnmarshaller(Class<?> cls, Type genericType, boolean isCollection)
    throws JAXBException {
    JAXBContext context = isCollection ? getCollectionContext(cls)
                                       : getJAXBContext(cls, genericType);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (validateInputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            unmarshaller.setSchema(theSchema);
        }
    }
    if (eventHandler != null) {
        unmarshaller.setEventHandler(eventHandler);
    }
    if (unmarshallerListener != null) {
        unmarshaller.setListener(unmarshallerListener);
    }
    if (uProperties != null) {
        for (Map.Entry<String, Object> entry : uProperties.entrySet()) {
            unmarshaller.setProperty(entry.getKey(), entry.getValue());
        }
    }
    return unmarshaller;
}
 
源代码11 项目: openjdk-jdk9   文件: Bug7014246Test.java
@Test
public void test() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(Bug7014246Test.class.getResourceAsStream("Bug7014246.xsd")));
        Assert.fail("STATUS:Failed.The negative testcase unexpectedly passed.");
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
 
源代码12 项目: xmlunit   文件: XmlAssertValidationTest.java
@Test
public void testIsValidAgainst_withExternallyCreatedSchemaInstance_shouldPass() throws Exception {
    StreamSource xml = new StreamSource(new File(TestResources.TEST_RESOURCE_DIR + "BookXsdGenerated.xml"));
    StreamSource xsd = new StreamSource(new File(TestResources.BOOK_XSD));

    SchemaFactory factory = SchemaFactory.newInstance(Languages.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(xsd);

    assertThat(xml).isValidAgainst(schema);
}
 
源代码13 项目: openjdk-jdk9   文件: Bug6964720Test.java
@Test
public void test() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(Bug6964720Test.class.getResourceAsStream("Bug6964720.xsd")));
        Assert.fail("should produce an error message");
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    }
}
 
源代码14 项目: photon   文件: IMFCPLSerializer.java
/**
 * A method that serializes the CompositionPlaylistType root element to an XML file
 *
 * @param cplType the composition playlist object
 * @param output stream to which the resulting serialized XML document is written to
 * @param formatted a boolean to indicate if the serialized XML should be formatted (good idea to have it set to true always)
 * @throws IOException - any I/O related error will be exposed through an IOException
 * @throws org.xml.sax.SAXException - any issues with instantiating a schema object with the schema sources will be exposed
 * through a SAXException
 * @throws javax.xml.bind.JAXBException - any issues in serializing the XML document using JAXB will be exposed through a JAXBException
 */

public void write(CompositionPlaylistType cplType, OutputStream output, boolean formatted) throws IOException, org.xml.sax.SAXException, JAXBException {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try(
            InputStream cplSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_3_2013/imf-cpl.xsd");
            InputStream dcmlSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st0433_2008/dcmlTypes/dcmlTypes.xsd");
            InputStream dsigSchemaAsAStream = contextClassLoader.getResourceAsStream("org/w3/_2000_09/xmldsig/xmldsig-core-schema.xsd");
            InputStream coreConstraintsSchemaAsAStream = contextClassLoader.getResourceAsStream("org/smpte_ra/schemas/st2067_2_2013/imf-core-constraints-20130620-pal.xsd")
    )
    {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI );
        StreamSource[] schemaSources = new StreamSource[4];
        schemaSources[0] = new StreamSource(dsigSchemaAsAStream);
        schemaSources[1] = new StreamSource(dcmlSchemaAsAStream);
        schemaSources[2] = new StreamSource(cplSchemaAsAStream);
        schemaSources[3] = new StreamSource(coreConstraintsSchemaAsAStream);
        Schema schema = schemaFactory.newSchema(schemaSources);

        JAXBContext jaxbContext = JAXBContext.newInstance("org.smpte_ra.schemas.st2067_2_2013");
        Marshaller marshaller = jaxbContext.createMarshaller();
        ValidationEventHandlerImpl validationEventHandler = new ValidationEventHandlerImpl(true);
        marshaller.setEventHandler(validationEventHandler);
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);

        /*marshaller.marshal(cplType, output);
        workaround for 'Error: unable to marshal type "CompositionPlaylistType" as an element because it is missing an @XmlRootElement annotation'
        as found at https://weblogs.java.net/blog/2006/03/03/why-does-jaxb-put-xmlrootelement-sometimes-not-always
         */
        marshaller.marshal(new JAXBElement<>(new QName("http://www.smpte-ra.org/schemas/2067-3/2013", "CompositionPlaylist"), CompositionPlaylistType.class, cplType), output);


        if(validationEventHandler.hasErrors())
        {
            throw new IOException(validationEventHandler.toString());
        }
    }
}
 
源代码15 项目: hyperjaxb3   文件: JAXBTest.java
public void testValidate() throws SAXException, JAXBException {

		final PurchaseOrderType purchaseOrder = objectFactory
				.createPurchaseOrderType();
		purchaseOrder.setShipTo(objectFactory.createUSAddress());
		purchaseOrder.setBillTo(objectFactory.createUSAddress());
		final JAXBElement<PurchaseOrderType> purchaseOrderElement = objectFactory
				.createPurchaseOrder(purchaseOrder);

		final SchemaFactory schemaFactory = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		final Schema schema = schemaFactory.newSchema(new StreamSource(
				getClass().getClassLoader().getResourceAsStream("po.xsd")));

		final Marshaller marshaller = context.createMarshaller();

		marshaller.setSchema(schema);

		final List<ValidationEvent> events = new LinkedList<ValidationEvent>();

		marshaller.setEventHandler(new ValidationEventHandler() {
			public boolean handleEvent(ValidationEvent event) {
				events.add(event);
				return true;
			}
		});
		marshaller.marshal(purchaseOrderElement, new DOMResult());

		assertFalse("List of validation events must not be empty.", events
				.isEmpty());
		
		System.out.println(events.get(0));
	}
 
源代码16 项目: ph-commons   文件: XMLSchemaValidationHelper.java
@Nonnull
public static IErrorList validate (@Nonnull final Schema aSchema, @Nonnull final Source aXML)
{
  final ErrorList aErrorList = new ErrorList ();
  validate (aSchema, aXML, aErrorList);
  return aErrorList;
}
 
源代码17 项目: pmd-designer   文件: TestXmlDumper.java
public static void dumpXmlTests(Writer outWriter, TestCollection collection) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = schemaFactory.newSchema(DesignerUtil.getResource("testschema/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = getDocumentBuilder(dbf);


        Document doc = builder.newDocument();
        Element root = doc.createElementNS(NS, "test-data");
        doc.appendChild(root);

        root.setAttribute("xmlns", NS);
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("xsi:schemaLocation", SCHEMA_LOCATION);

        new TestXmlDumper().appendTests(doc, collection.getStash());

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{" + NS + "}code");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // FIXME whatever i try this indents by 3 spaces which is not
        //  compatible with our style
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");


        transformer.transform(new DOMSource(doc), new StreamResult(outWriter));
    } finally {
        outWriter.close();
    }

}
 
源代码18 项目: dragonwell8_jdk   文件: AnyURITest.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));
        throw new RuntimeException("Illegal URI // should be rejected.");
    } catch (SAXException e) {
        //expected:
        //Enumeration value '//' is not in the value space of the base type, anyURI.
    }


}
 
源代码19 项目: openjdk-jdk9   文件: Bug4969732.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();
}
 
源代码20 项目: openjdk-jdk9   文件: Bug4970402.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();
}
 
源代码21 项目: arcusplatform   文件: ChangeLogDeserializer.java
private void validate(XMLStreamReader reader) throws XMLStreamException {
   try {
      Source source = new StreamSource(getClass().getClassLoader().getResourceAsStream(SCHEMA_LOCATION));
      Schema schema = schemaFactory.newSchema(source);
      Validator validator = schema.newValidator();
      validator.validate(new StAXSource(reader));
   } catch(Exception e) {
      throw new XMLStreamException(e);
   }
}
 
源代码22 项目: TencentKona-8   文件: AnyURITest.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));
        throw new RuntimeException("Illegal URI // should be rejected.");
    } catch (SAXException e) {
        //expected:
        //Enumeration value '//' is not in the value space of the base type, anyURI.
    }


}
 
源代码23 项目: fix-orchestra   文件: RepositoryValidator.java
private Document validateSchema(ErrorListener errorHandler)
    throws ParserConfigurationException, SAXException, IOException {
  // parse an XML document into a DOM tree
  final DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
  parserFactory.setNamespaceAware(true);
  parserFactory.setXIncludeAware(true);
  final DocumentBuilder parser = parserFactory.newDocumentBuilder();
  final Document document = parser.parse(inputStream);

  // create a SchemaFactory capable of understanding WXS schemas
  final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  final ResourceResolver resourceResolver = new ResourceResolver();
  factory.setResourceResolver(resourceResolver);

  // load a WXS schema, represented by a Schema instance
  final URL resourceUrl = this.getClass().getClassLoader().getResource("xsd/repository.xsd");
  final String path = resourceUrl.getPath();
  final String parentPath = path.substring(0, path.lastIndexOf('/'));
  final URL baseUrl = new URL(resourceUrl.getProtocol(), null, parentPath);
  resourceResolver.setBaseUrl(baseUrl);

  final Source schemaFile = new StreamSource(resourceUrl.openStream());
  final Schema schema = factory.newSchema(schemaFile);

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

  validator.setErrorHandler(errorHandler);

  // validate the DOM tree
  validator.validate(new DOMSource(document));
  return document;
}
 
源代码24 项目: aion-germany   文件: WalkerData.java
public void writeXml(int worldId) {
	Schema schema = null;
	SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

	try {
		schema = sf.newSchema(new File("./data/static_data/npc_walker/npc_walker.xsd"));
	}
	catch (SAXException e1) {
		log.error("Error while saving data: " + e1.getMessage(), e1.getCause());
		return;
	}

	File xml = new File("./data/static_data/npc_walker/walker_" + worldId + "_" + World.getInstance().getWorldMap(worldId).getName() + ".xml");
	JAXBContext jc;
	Marshaller marshaller;
	try {
		jc = JAXBContext.newInstance(WalkerData.class);
		marshaller = jc.createMarshaller();
		marshaller.setSchema(schema);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(this, xml);
	}
	catch (JAXBException e) {
		log.error("Error while saving data: " + e.getMessage(), e.getCause());
		return;
	}
}
 
源代码25 项目: dss   文件: XMLEncUtilsTest.java
@Test
public void test() throws JAXBException, SAXException {
	JAXBContext jaxbContext = xmlEncUtils.getJAXBContext();
	assertNotNull(jaxbContext);

	Schema schema = xmlEncUtils.getSchema();
	assertNotNull(schema);
}
 
源代码26 项目: validator   文件: SchemaBuilderTest.java
@Test
public void testStringLocation() {
    final SchemaBuilder builder = schema("myname").schemaLocation("simple.xsd");
    final Result<Pair<ValidateWithXmlSchema, Schema>, String> result = builder.build(Simple.createContentRepository());
    assertThat(result).isNotNull();
    assertThat(result.isValid()).isTrue();
}
 
源代码27 项目: cxf   文件: XSDResourceTypeIdentifier.java
public XSDResourceTypeIdentifier(Source xsd, ResourceTransformer resourceTransformer) {
    try {
        this.resourceTransformer = resourceTransformer;
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(xsd);
        this.validator = schema.newValidator();
    } catch (SAXException ex) {
        LOG.severe(ex.getLocalizedMessage());
        throw new SoapFault("Internal error", getSoapVersion().getReceiver());
    }
}
 
源代码28 项目: carbon-identity-framework   文件: SchemaBuilder.java
/**
 * Builds the policy schema map. There are three schemas.
 *
 * @param configHolder holder EntitlementConfigHolder
 * @throws SAXException if fails
 */
public void buildPolicySchema() throws SAXException {

    if (!"true".equalsIgnoreCase((String) configHolder.getEngineProperties().get(
            EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) {
        log.warn("PDP schema validation disabled.");
        return;
    }

    String[] schemaNSs = new String[]{PDPConstants.XACML_1_POLICY_XMLNS,
            PDPConstants.XACML_2_POLICY_XMLNS,
            PDPConstants.XACML_3_POLICY_XMLNS};

    for (String schemaNS : schemaNSs) {

        String schemaFile;

        if (PDPConstants.XACML_1_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_1_POLICY_SCHEMA_FILE;
        } else if (PDPConstants.XACML_2_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_2_POLICY_SCHEMA_FILE;
        } else {
            schemaFile = PDPConstants.XACML_3_POLICY_SCHEMA_FILE;
        }

        InputStream schemaFileStream = EntitlementExtensionBuilder.class.getResourceAsStream("/" + schemaFile);
        try{
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new StreamSource(schemaFileStream));
            configHolder.getPolicySchemaMap().put(schemaNS, schema);
        } finally {
            IdentityIOStreamUtils.closeInputStream(schemaFileStream);
        }
    }
}
 
源代码29 项目: openjdk-jdk9   文件: Bug6941169Test.java
@Test
public void testValidation_SAX_withoutServiceMech() {
    System.out.println("Validation using SAX Source;  Service mechnism is turned off;  SAX Impl should be the default:");
    InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
    SAXSource ss = new SAXSource(is);
    setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
    long start = System.currentTimeMillis();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
        Schema schema = factory.newSchema(new StreamSource(_xsd));
        Validator validator = schema.newValidator();
        validator.validate(ss, null);
    } catch (Exception e) {
        // e.printStackTrace();
        String error = e.getMessage();
        if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
            Assert.fail(e.getMessage());
        } else {
            System.out.println("Default impl is used");
        }

        // System.out.println(e.getMessage());

    }
    long end = System.currentTimeMillis();
    double elapsedTime = ((end - start));
    System.out.println("Time elapsed: " + elapsedTime);
    clearSystemProperty(SAX_FACTORY_ID);
}
 
源代码30 项目: cxf   文件: AbstractJAXBProvider.java
protected void validateObjectIfNeeded(Marshaller marshaller, Class<?> cls, Object obj)
    throws JAXBException {
    if (validateOutputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            marshaller.setEventHandler(eventHandler);
            marshaller.setSchema(theSchema);
            if (validateBeforeWrite) {
                marshaller.marshal(obj, new DefaultHandler());
                marshaller.setSchema(null);
            }
        }
    }
}