Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setAttribute()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setAttribute() . 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: TaskUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static Document convertToDocument(File file) throws TaskException {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    fac.setNamespaceAware(true);
    fac.setXIncludeAware(false);
    fac.setExpandEntityReferences(false);
    try {
        fac.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        fac.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        fac.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(0);
        fac.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);
        return fac.newDocumentBuilder().parse(file);
    } catch (Exception e) {
        throw new TaskException("Error in creating an XML document from file: " + e.getMessage(),
                                TaskException.Code.CONFIG_ERROR, e);
    }
}
 
Example 2
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check usage of TypeInfo interface introduced in DOM L3.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testGetTypeInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(new MyErrorHandler());

    Document document = docBuilder.parse(xmlFile);
    Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
    TypeInfo typeInfo = userId.getSchemaTypeInfo();
    assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
    assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));

    Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
    TypeInfo roletypeInfo = role.getSchemaTypeInfo();
    assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
    assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
 
Example 3
Source File: CacheonixXsdTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Document parse(final InputStream testFileInputStream) throws ParserConfigurationException, SAXException,
        IOException {

   final Document document;
   final InputStream xsdStream = getClass().getClassLoader().getResourceAsStream("META-INF/cacheonix-config-2.0.xsd");
   try {

      // Create parser factory
      final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      documentBuilderFactory.setNamespaceAware(true);
      documentBuilderFactory.setValidating(true);
      documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
      documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, xsdStream);

      // Create parser
      final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      documentBuilder.setErrorHandler(new ErrorHandler());
      document = documentBuilder.parse(testFileInputStream);
   } finally {
      IOUtils.closeHard(xsdStream);
   }
   return document;
}
 
Example 4
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create DocumentBuilderFactory with the XXE and XEE prevention measurements.
 *
 * @return DocumentBuilderFactory instance
 */
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    } catch (ParserConfigurationException e) {
        log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " +
                Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE +
                " or secure-processing.");
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;

}
 
Example 5
Source File: PAPPolicyReader.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private PAPPolicyReader(PolicyFinder policyFinder) {


        this.policyFinder = policyFinder;
        // create the factory
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setIgnoringComments(true);
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        // now use the factory to create the document builder
        try {
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
            builder = documentBuilderFactory.newDocumentBuilder();
            builder.setEntityResolver(new CarbonEntityResolver());
            builder.setErrorHandler(this);
        } catch (ParserConfigurationException pce) {
            throw new IllegalArgumentException("Failed to create the DocumentBuilder. : ", pce);
        }
    }
 
Example 6
Source File: RDFReader.java    From jdmn with Apache License 2.0 6 votes vote down vote up
public RDFModel readModel(String modelName, InputStream inputStream) throws Exception {
    logger.info(String.format("Reading model '%s'", modelName));
    StopWatch watch = new StopWatch();
    watch.start();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
    dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(inputStream);
    RDFModel rdfModel = new RDFModel(document);

    watch.stop();
    logger.info("RDF reading time: " + watch.toString());

    return rdfModel;
}
 
Example 7
Source File: ResXmlPatcher.java    From ratel with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param file File to load into Document
 * @return Document
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public static Document loadDocument(File file)
        throws IOException, SAXException, ParserConfigurationException {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setFeature(FEATURE_DISABLE_DOCTYPE_DECL, true);
    docFactory.setFeature(FEATURE_LOAD_DTD, false);

    try {
        docFactory.setAttribute(ACCESS_EXTERNAL_DTD, " ");
        docFactory.setAttribute(ACCESS_EXTERNAL_SCHEMA, " ");
    } catch (IllegalArgumentException ex) {
        LOGGER.warning("JAXP 1.5 Support is required to validate XML");
    }

    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    // Not using the parse(File) method on purpose, so that we can control when
    // to close it. Somehow parse(File) does not seem to close the file in all cases.
    FileInputStream inputStream = new FileInputStream(file);
    try {
    	return docBuilder.parse(inputStream);
    } finally {
    	inputStream.close();
    }
}
 
Example 8
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checking Text content in XML file.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMoreUserInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element account = (Element)document
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
    String textContent = account.getTextContent();
    assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6));
    assertEquals(textContent, "RachelGreen744");

    Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
    assertTrue(accountID.getTextContent().trim().equals("1"));

    assertFalse(eh.isAnyError());
}
 
Example 9
Source File: MicroIntegratorBaseUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private static DocumentBuilderFactory getSecuredDocumentBuilder() {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);
        try {
            dbf.setFeature(org.apache.xerces.impl.Constants.SAX_FEATURE_PREFIX +
                    org.apache.xerces.impl.Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
            dbf.setFeature(org.apache.xerces.impl.Constants.SAX_FEATURE_PREFIX +
                    org.apache.xerces.impl.Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
            dbf.setFeature(org.apache.xerces.impl.Constants.XERCES_FEATURE_PREFIX +
                    org.apache.xerces.impl.Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        } catch (ParserConfigurationException e) {

        }

        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        dbf.setAttribute(org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX +
                org.apache.xerces.impl.Constants.SECURITY_MANAGER_PROPERTY, securityManager);
        return dbf;
    }
 
Example 10
Source File: XSLTTransformer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
                                                                                    ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX +
            Constants.SECURITY_MANAGER_PROPERTY, securityManager);
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
        }
    });
    return documentBuilder;
}
 
Example 11
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example 12
Source File: NDataSourceHelper.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static Element stringToElement(String xml) {
	if (xml == null || xml.trim().length() == 0) {
		return null;
	}
	try {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		docFactory.setNamespaceAware(false);
		docFactory.setXIncludeAware(false);
		docFactory.setExpandEntityReferences(false);

		docFactory.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);

		docFactory.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);

		docFactory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);

		SecurityManager securityManager = new SecurityManager();
		securityManager.setEntityExpansionLimit(0);
		docFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY,
				securityManager);

		DocumentBuilder db = docFactory.newDocumentBuilder();
		return db.parse(new ByteArrayInputStream(xml.getBytes())).getDocumentElement();
	} catch (Exception e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 13
Source File: DefaultDocumentLoader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create the {@link DocumentBuilderFactory} instance.
 * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD}
 * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD})
 * @param namespaceAware whether the returned factory is to provide support for XML namespaces
 * @return the JAXP DocumentBuilderFactory
 * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory
 */
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
		throws ParserConfigurationException {

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(namespaceAware);

	if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
		factory.setValidating(true);
		if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
			// Enforce namespace aware for XSD...
			factory.setNamespaceAware(true);
			try {
				factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
			}
			catch (IllegalArgumentException ex) {
				ParserConfigurationException pcex = new ParserConfigurationException(
						"Unable to validate using XSD: Your JAXP provider [" + factory +
						"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
						"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
				pcex.initCause(ex);
				throw pcex;
			}
		}
	}

	return factory;
}
 
Example 14
Source File: XMLUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static DocumentBuilderFactory getDocumentBuilderFactory() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
    for (String feature : DISABLED_FEATURES) {
        documentBuilderFactory.setFeature(feature, false);
    }
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    return documentBuilderFactory;
}
 
Example 15
Source File: Bug4966142.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
    dbf.setAttribute(SCHEMA_SOURCE, Bug4966142.class.getResource("Bug4966142.xsd").toExternalForm());

    Document document = dbf.newDocumentBuilder().parse(Bug4966142.class.getResource("Bug4966142.xml").toExternalForm());

    TypeInfo type = document.getDocumentElement().getSchemaTypeInfo();

    Assert.assertFalse(type.isDerivedFrom("testNS", "Test", TypeInfo.DERIVATION_UNION));
}
 
Example 16
Source File: UserRegistrationService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new CarbonEntityResolver());
    return documentBuilder;
}
 
Example 17
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 5 votes vote down vote up
static Document getDocument() throws ParserConfigurationException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setExpandEntityReferences(false);
    factory.setFeature(FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    factory.setAttribute(ACCESS_EXTERNAL_DTD, "");
    factory.setAttribute(ACCESS_EXTERNAL_SCHEMA, "");
    return factory.newDocumentBuilder().newDocument();
}
 
Example 18
Source File: DefaultDocumentLoader.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create the {@link DocumentBuilderFactory} instance.
 * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD}
 * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD})
 * @param namespaceAware whether the returned factory is to provide support for XML namespaces
 * @return the JAXP DocumentBuilderFactory
 * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory
 */
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
		throws ParserConfigurationException {

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(namespaceAware);

	if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
		factory.setValidating(true);
		if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
			// Enforce namespace aware for XSD...
			factory.setNamespaceAware(true);
			try {
				factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
			}
			catch (IllegalArgumentException ex) {
				ParserConfigurationException pcex = new ParserConfigurationException(
						"Unable to validate using XSD: Your JAXP provider [" + factory +
						"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
						"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
				pcex.initCause(ex);
				throw pcex;
			}
		}
	}

	return factory;
}
 
Example 19
Source File: ConfigParser.java    From wisp with Apache License 2.0 4 votes vote down vote up
public Map<String, TableConfig> parse(InputStream xmlPath) throws Exception {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        Document document = null;
        DocumentBuilder docBuilder = null;
        docBuilder = factory.newDocumentBuilder();
        DefaultHandler handler = new DefaultHandler();
        docBuilder.setEntityResolver(handler);
        docBuilder.setErrorHandler(handler);

        document = docBuilder.parse(xmlPath);

        Element rootEl = document.getDocumentElement();

        NodeList children = rootEl.getChildNodes();

        BaseConfig currentBaseConfig = null;
        Map<String, TableConfig> allTableConfigMap = new HashMap<String, TableConfig>();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;

                if (elementNameMatch(element, "base")) {

                    currentBaseConfig = parseBase(element);

                } else if (elementNameMatch(element, "dbs")) {

                    allTableConfigMap = parseDbs(element, currentBaseConfig);
                }

            }
        }

        return allTableConfigMap;
    }
 
Example 20
Source File: ConfigParser.java    From wisp with Apache License 2.0 4 votes vote down vote up
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}