Java Code Examples for javax.xml.parsers.SAXParserFactory#setValidating()

The following examples show how to use javax.xml.parsers.SAXParserFactory#setValidating() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResolvingParser.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/** Initialize the parser. */
private void initParser() {
  catalogResolver = new CatalogResolver(catalogManager);
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(namespaceAware);
  spf.setValidating(validating);

  try {
    saxParser = spf.newSAXParser();
    parser = saxParser.getParser();
    documentHandler = null;
    dtdHandler = null;
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 2
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for the same imported schemas but will use SAXParserFactory and try
 * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this
 * test.
 *
 * @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 testGetOwnerItemList1() throws Exception {
    String xsdFile = XML_DIR + "coins.xsd";
    String xmlFile = XML_DIR + "coins.xml";
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);

    SAXParser sp = spf.newSAXParser();
    sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);

    MyErrorHandler eh = new MyErrorHandler();
    sp.parse(new File(xmlFile), eh);
    assertFalse(eh.isAnyError());
}
 
Example 3
Source File: EarProjectTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void validate(final File ddFile) throws Exception {
    SAXParserFactory f = SAXParserFactory.newInstance();
    f.setNamespaceAware(true);
    f.setValidating(true);
    SAXParser p = f.newSAXParser();
    URL schemaURL_1_4 = EarProjectTest.class.getResource("/org/netbeans/modules/j2ee/dd/impl/resources/application_1_4.xsd");
    URL schemaURL_5 = EarProjectTest.class.getResource("/org/netbeans/modules/j2ee/dd/impl/resources/application_5.xsd");
    assertNotNull("have access to schema", schemaURL_1_4);
    assertNotNull("have access to schema", schemaURL_5);
    p.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    p.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", new String[] {
        schemaURL_1_4.toExternalForm(),
        schemaURL_5.toExternalForm()
    });
    try {
        p.parse(ddFile.toURI().toString(), new Handler());
    } catch (SAXParseException e) {
        fail("Validation of XML document " + ddFile + " against schema failed. Details: " +
                e.getSystemId() + ":" + e.getLineNumber() + ": " + e.getLocalizedMessage());
    }
}
 
Example 4
Source File: ResolvingParser.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/** Initialize the parser. */
private void initParser() {
  catalogResolver = new CatalogResolver(catalogManager);
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(namespaceAware);
  spf.setValidating(validating);

  try {
    saxParser = spf.newSAXParser();
    parser = saxParser.getParser();
    documentHandler = null;
    dtdHandler = null;
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 5
Source File: Resolver.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Setup readers.
 */
public void setupReaders() {
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(true);
  spf.setValidating(false);

  SAXCatalogReader saxReader = new SAXCatalogReader(spf);

  saxReader.setCatalogParser(null, "XMLCatalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");

  saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
                             "catalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader");

  addReader("application/xml", saxReader);

  TR9401CatalogReader textReader = new TR9401CatalogReader();
  addReader("text/plain", textReader);
}
 
Example 6
Source File: Resolver.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Setup readers.
 */
public void setupReaders() {
  SAXParserFactory spf = JdkXmlUtils.getSAXFactory(catalogManager.overrideDefaultParser());
  spf.setValidating(false);

  SAXCatalogReader saxReader = new SAXCatalogReader(spf);

  saxReader.setCatalogParser(null, "XMLCatalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");

  saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
                             "catalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader");

  addReader("application/xml", saxReader);

  TR9401CatalogReader textReader = new TR9401CatalogReader();
  addReader("text/plain", textReader);
}
 
Example 7
Source File: AuctionItemRepository.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Testing set MaxOccursLimit to 10000 in the secure processing enabled for
 * SAXParserFactory.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMaxOccurLimitPos() throws Exception {
    String schema_file = XML_DIR + "toys.xsd";
    String xml_file = XML_DIR + "toys.xml";
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setFeature(FEATURE_SECURE_PROCESSING, true);
    setSystemProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000));
    SAXParser parser = factory.newSAXParser();
    parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file));
    try (InputStream is = new FileInputStream(xml_file)) {
        MyErrorHandler eh = new MyErrorHandler();
        parser.parse(is, eh);
        assertFalse(eh.isAnyError());
    }
}
 
Example 8
Source File: XmlUtils.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> extractCustomAttributes(final String xml) {
    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    try {
        final SAXParser saxParser = spf.newSAXParser();
        final XMLReader xmlReader = saxParser.getXMLReader();
        final CustomAttributeHandler handler = new CustomAttributeHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(new StringReader(xml)));
        return handler.getAttributes();
    } catch (final Exception e) {
    	log.error(e.getMessage(), e);
        return Collections.emptyMap();
    }
}
 
Example 9
Source File: Bug4674384_MAX_OCCURS_Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public final void testLargeMaxOccurs() {

    String XML_FILE_NAME = "Bug4674384_MAX_OCCURS_Test.xml";

    try {
        // create and initialize the parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(true);

        SAXParser parser = spf.newSAXParser();
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");

        File xmlFile = new File(getClass().getResource(XML_FILE_NAME).getPath());

        parser.parse(xmlFile, new DefaultHandler());
    } catch (Exception e) {
        System.err.println("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
        e.printStackTrace();
        Assert.fail("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.  " + e.getMessage());
    }

    System.out.println("Success: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
}
 
Example 10
Source File: XMLHelper.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
private static SAXParser newSAXParser(URL schema, InputStream schemaStream,
        boolean loadExternalDtds) throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    parserFactory.setValidating(canUseSchemaValidation && (schema != null));
    if (!loadExternalDtds && canDisableExternalDtds(parserFactory)) {
        parserFactory.setFeature(XERCES_LOAD_EXTERNAL_DTD, false);
    }
    SAXParser parser = parserFactory.newSAXParser();

    if (canUseSchemaValidation && schema != null) {
        try {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            parser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream);
        } catch (SAXNotRecognizedException ex) {
            Message.warn("problem while setting JAXP validating property on SAXParser... "
                    + "XML validation will not be done", ex);
            canUseSchemaValidation = false;
            parserFactory.setValidating(false);
            parser = parserFactory.newSAXParser();
        }
    }

    parser.getXMLReader().setFeature(XML_NAMESPACE_PREFIXES, true);
    return parser;
}
 
Example 11
Source File: Parser.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(true);
        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);
    }
}
 
Example 12
Source File: XmlUtil.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static SAXParser newSAXParser(boolean namespaceAware, boolean validating, Schema schema1) throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(validating);
    factory.setNamespaceAware(namespaceAware);
    factory.setSchema(schema1);
    return factory.newSAXParser();
}
 
Example 13
Source File: ResolvingParser.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Initialize the parser. */
private void initParser() {
  catalogResolver = new CatalogResolver(catalogManager);
  SAXParserFactory spf = JdkXmlUtils.getSAXFactory(catalogManager.overrideDefaultParser());
  spf.setValidating(validating);

  try {
    saxParser = spf.newSAXParser();
    parser = saxParser.getParser();
    documentHandler = null;
    dtdHandler = null;
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 14
Source File: ItemsXmlValidator.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
public ItemsXmlValidator(final IRuleSet ruleSet, final IResultFactory resultFactory) throws ParserConfigurationException, SAXException {
	final SAXParserFactory factory = SAXParserFactory.newInstance();
       factory.setValidating(true);
       factory.setNamespaceAware(true);
       this.sp = factory.newSAXParser();
       sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
	
       this.ruleSet = ruleSet;
	this.resultFactory = resultFactory;
}
 
Example 15
Source File: Bug4934208.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void parse(InputSource is) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    SAXParser parser = spf.newSAXParser();

    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", Bug4934208.class.getResourceAsStream("test.xsd"));

    XMLReader r = parser.getXMLReader();

    r.setErrorHandler(new DraconianErrorHandler());
    r.parse(is);
}
 
Example 16
Source File: ResolvingParser.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/** Initialize the parser. */
private void initParser() {
  catalogResolver = new CatalogResolver(catalogManager);
  SAXParserFactory spf = JdkXmlUtils.getSAXFactory(catalogManager.overrideDefaultParser());
  spf.setValidating(validating);

  try {
    saxParser = spf.newSAXParser();
    parser = saxParser.getParser();
    documentHandler = null;
    dtdHandler = null;
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 17
Source File: CLDRConverter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static Map<String, Object> getCLDRBundle(String id) throws Exception {
    Map<String, Object> bundle = cldrBundles.get(id);
    if (bundle != null) {
        return bundle;
    }
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    enableFileAccess(parser);
    LDMLParseHandler handler = new LDMLParseHandler(id);
    File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
    if (!file.exists()) {
        // Skip if the file doesn't exist.
        return Collections.emptyMap();
    }

    info("..... main directory .....");
    info("Reading file " + file);
    parser.parse(file, handler);

    bundle = handler.getData();
    cldrBundles.put(id, bundle);
    String country = getCountryCode(id);
    if (country != null) {
        bundle = handlerSuppl.getData(country);
        if (bundle != null) {
            //merge two maps into one map
            Map<String, Object> temp = cldrBundles.remove(id);
            bundle.putAll(temp);
            cldrBundles.put(id, bundle);
        }
    }
    return bundle;
}
 
Example 18
Source File: XmlParser.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
public Element parse(InputStream stream) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
Document doc = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// xxe protection
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setXIncludeAware(false);
		factory.setExpandEntityReferences(false);
			
		factory.setNamespaceAware(true);
		if (policy == ValidationPolicy.EVERYTHING) {
		  // The SAX interface appears to not work when reporting the correct version/encoding.
		  // if we can, we'll inspect the header/encoding ourselves 
		  if (stream.markSupported()) {
		    stream.mark(1024);
		    version = checkHeader(stream);
		    stream.reset();
		  }
			// use a slower parser that keeps location data
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer nullTransformer = transformerFactory.newTransformer();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			doc = docBuilder.newDocument();
			DOMResult domResult = new DOMResult(doc);
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			spf.setValidating(false);
  		// xxe protection
		  spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
      spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			SAXParser saxParser = spf.newSAXParser();
			XMLReader xmlReader = saxParser.getXMLReader();
  		// xxe protection
		  xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
		  xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
	   			
			XmlLocationAnnotator locationAnnotator = new XmlLocationAnnotator(xmlReader, doc);
			InputSource inputSource = new InputSource(stream);
			SAXSource saxSource = new SAXSource(locationAnnotator, inputSource);
			nullTransformer.transform(saxSource, domResult);
		} else {
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(stream);
		}
	} catch (Exception e) {
    logError(0, 0, "(syntax)", IssueType.INVALID, e.getMessage(), IssueSeverity.FATAL);
    doc = null;
	}
	if (doc == null)
		return null;
	else
    return parse(doc);
}
 
Example 19
Source File: ManualAlignMode.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Import landmarks from XML file. */
public boolean importLandmarks() {
	if (!this.m.isEmpty() && !Utils.checkYN("Remove current landmarks and import new landmarks from a file?")) return false;

	// copy for restore in case of failure:
	final HashMap<Layer,Landmarks> current = new HashMap<Layer,Landmarks>(this.m);
	InputStream istream = null;
	try {
		final String[] fs = Utils.selectFile("Choose landmarks XML file");
		if (null == fs || null == fs[0] || null == fs[1]) return false;
		final File f = new File(fs[0] + fs[1]);
		if (!f.exists() || !f.canRead()) {
			Utils.log("ERROR: cannot read file at " + f.getAbsolutePath());
			return false;
		}
		// Clear current landmarks and parse from file:
		this.m.clear();
		final SAXParserFactory ft = SAXParserFactory.newInstance();
		ft.setValidating(false);
		final SAXParser parser = ft.newSAXParser();
		istream = Utils.createStream(fs[0] + fs[1]);
		parser.parse(new InputSource(istream), new LandmarksParser());

		// Warn on inconsistencies
		final HashSet<Integer> sizes = new HashSet<Integer>();
		for (final Landmarks lm : this.m.values()) {
			sizes.add(lm.points.size());
		}
		if (sizes.size() > 1) {
			Utils.log("WARNING: different number of landmarks in at least one layer.");
		}
		Display.repaint();

	} catch (final Throwable t) {
		IJError.print(t);
		Utils.log("ERROR: did not import any landmarks.");
		this.m.clear();
		this.m.putAll(current);
		return false;
	} finally {
		try {
			if (null != istream) istream.close();
		} catch (final Exception e) {}
	}
	return true;
}
 
Example 20
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization(KeycloakSession session) {
    resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
    FastServiceLocator locator = (FastServiceLocator) ServiceLocator.getInstance();

    JpaConnectionProviderFactory jpaConnectionProvider = (JpaConnectionProviderFactory) session
            .getKeycloakSessionFactory().getProviderFactory(JpaConnectionProvider.class);

    // register our custom databases
    locator.register(new PostgresPlusDatabase());
    locator.register(new UpdatedMySqlDatabase());
    locator.register(new UpdatedMariaDBDatabase());
    
    // registers only the database we are using
    try (Connection connection = jpaConnectionProvider.getConnection()) {
        Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
        if (database.getDatabaseProductName().equals(MySQLDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        } else if (database.getDatabaseProductName().equals(MariaDBDatabase.PRODUCT_NAME)) {
            // Adding CustomVarcharType for MySQL 8 and newer
            DataTypeFactory.getInstance().register(MySQL8VarcharType.class);
        }

        DatabaseFactory.getInstance().clearRegistry();
        locator.register(database);
    } catch (Exception cause) {
        throw new RuntimeException("Failed to configure Liquibase database", cause);
    }

    // disables XML validation
    for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
        if (parser instanceof XMLChangeLogSAXParser) {
            Method getSaxParserFactory = null;
            try {
                getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
                getSaxParserFactory.setAccessible(true);
                SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
                saxParserFactory.setValidating(false);
                saxParserFactory.setSchema(null);
            } catch (Exception e) {
                logger.warnf("Failed to disable liquibase XML validations");
            } finally {
                if (getSaxParserFactory != null) {
                    getSaxParserFactory.setAccessible(false);
                }
            }
        }
    }
}