Get XML document builder.

@param schema XML schema,
@param useNamespace flag to use name space.
@return XML document builder.
@throws ParserConfigurationException if document builder factory feature set fail.
344720
private static javax.xml.parsers.DocumentBuilder getDocumentBuilder(Schema schema, boolean useNamespace) throws ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setIgnoringComments(true);
		dbf.setIgnoringElementContentWhitespace(true);
		dbf.setCoalescing(true);

		if (schema != null) {
			// because schema is used throws fatal error if XML document contains DOCTYPE declaration
			dbf.setFeature(FEAT_DOCTYPE_DECL, true);

			// excerpt from document builder factory api:
			// Note that "the validation" here means a validating parser as defined in the XML recommendation. In other words,
			// it essentially just controls the DTD validation.
			// To use modern schema languages such as W3C XML Schema or RELAX NG instead of DTD, you can configure your parser
			// to be a non-validating parser by leaving the setValidating(boolean) method false, then use the setSchema(Schema)
			// method to associate a schema to a parser.
			dbf.setValidating(false);

			// XML schema validation requires namespace support
			dbf.setFeature(FEAT_SCHEMA_VALIDATION, true);
			dbf.setNamespaceAware(true);
			dbf.setSchema(schema);
		} else {
			// disable parser XML schema support; it is enabled by default
			dbf.setFeature(FEAT_SCHEMA_VALIDATION, false);
			dbf.setValidating(false);
			dbf.setNamespaceAware(useNamespace);
		}

		javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
		db.setEntityResolver(new EntityResolverImpl());
		db.setErrorHandler(new ErrorHandlerImpl());
		return db;
	}
1013924
public static XMLReader createXMLReader() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
        try {
            return (XMLReader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
                    Thread currThread = Thread.currentThread();
                    ClassLoader oldLoader = currThread.getContextClassLoader();
                    currThread.setContextClassLoader(ParserFactory.class.getClassLoader());
                    try {
                        /**
                         * Changed to use pluggable parser version. Needed for JDK 1.4.1
                         */
                        return SAXParserFactory.newInstance().newSAXParser().getXMLReader();
                        //return XMLReaderFactory.createXMLReader();
                    }
                                        finally {
                                            currThread.setContextClassLoader(oldLoader);
                                        }
                                    }
            });
        } catch (PrivilegedActionException pae) {
            Throwable t = pae.getCause();
            if (t instanceof SAXException) {
                throw (SAXException) t;
            } else if (t instanceof ParserConfigurationException) {
                throw (ParserConfigurationException) t;
            } else if (t instanceof FactoryConfigurationError) {
                throw (FactoryConfigurationError) t;
            }
        }
        return null;
    }
1312661
public Schema createSchema(SAXSource source, PropertyMap properties)
            throws IOException, SAXException, IncorrectSchemaException {
    ErrorHandler eh = properties.get(ValidateProperty.ERROR_HANDLER);
    CountingErrorHandler ceh = new CountingErrorHandler(eh);
    InputSource in = source.getInputSource();
    String systemId = in.getSystemId();
    IfValidHandler ifValidHandler = new IfValidHandler();
    ifValidHandler.setErrorHandler(ceh);
    try {
      SAXTransformerFactory factory = (SAXTransformerFactory)transformerFactoryClass.newInstance();
      initTransformerFactory(factory);
      TransformerHandler transformerHandler = factory.newTransformerHandler(schematron);
      ifValidHandler.setDelegate(transformerHandler);
      Transformer transformer = transformerHandler.getTransformer();
      String phase = properties.get(SchematronProperty.PHASE);
      if (phase != null)
        transformer.setParameter("phase", phase);
      boolean diagnose = properties.contains(SchematronProperty.DIAGNOSE);
      if (diagnose)
        transformer.setParameter("diagnose", Boolean.TRUE);
      PropertyMapBuilder builder = new PropertyMapBuilder(properties);
      builder.put(ValidateProperty.ERROR_HANDLER, ifValidHandler);
      Validator validator = schematronSchema.createValidator(builder.toPropertyMap());
      ifValidHandler.setValidator(validator.getContentHandler());
      XMLReader xr = source.getXMLReader();
      if (xr == null)
        xr = ResolverFactory.createResolver(properties).createXMLReader();
      xr.setContentHandler(ifValidHandler);      
      xr.setDTDHandler(validator.getDTDHandler());  // not strictly necessary
      factory.setErrorListener(new SAXErrorListener(ceh, systemId));
      TemplatesHandler templatesHandler = factory.newTemplatesHandler();
      templatesHandler.setSystemId(systemId);
      LocationFilter stage2 = new LocationFilter(new ErrorFilter(templatesHandler, ceh, localizer), systemId);
      transformerHandler.setResult(new SAXResult(stage2));
      xr.setErrorHandler(ceh);
      xr.parse(in);
      SAXException exception = stage2.getException();
      if (exception != null)
        throw exception;
      if (ceh.getHadErrorOrFatalError())
        throw new IncorrectSchemaException();
      // Getting the templates can cause errors to be generated.
      Templates templates = templatesHandler.getTemplates();
      if (ceh.getHadErrorOrFatalError())
        throw new IncorrectSchemaException();
      return new SchemaImpl(templates,
                            transformerFactoryClass,
                            properties,
                            supportedPropertyIds);
    }
    catch (SAXException e) {
      throw cleanupSAXException(e);
    }
    catch (TransformerConfigurationException e) {
      throw new SAXException(localizer.message("unexpected_schema_creation_error"));
    }
    catch (InstantiationException e) {
      throw new SAXException(e);
    }
    catch (IllegalAccessException e) {
      throw new SAXException(e);
    }
  }
323546
public static DocumentBuilder newDocumentBuilder(final DocumentBuilderFactory factory)
   {
      try
      {
         final DocumentBuilder builder = factory.newDocumentBuilder();
         return builder;
      }
      catch (Exception e)
      {
         throw MESSAGES.unableToCreateInstanceOf(e, DocumentBuilder.class.getName());
      }
   }
256807
public static Document createDocument() {
		try {
			DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
			fact.setNamespaceAware(true);
			DocumentBuilder db = fact.newDocumentBuilder();
			return db.newDocument();
		} catch (ParserConfigurationException e) {
			//will probably never be thrown because we're not doing anything fancy with the configuration
			throw new RuntimeException(e);
		}
	}
942500
public static void main(String[] args) throws TransformerConfigurationException, SAXException{
        XSDocument xsd = new XSDocument(new StreamResult(System.out), false, 4, null);
        xsd.startDocument();
        {
            String n1 = "http://www.example.com/N1";
            String n2 = "http://www.example.com/N2";
            xsd.xml().declarePrefix("n1", n1);
            xsd.xml().declarePrefix("n2", n2);
            xsd.startSchema(n1);
            {
                xsd.addImport(n2, "imports/b.xsd");
                xsd.startComplexType().name("MyType");
                {
                    xsd.startCompositor(Compositor.SEQUENCE);
                    xsd.startElement().ref(n1, "e1").endElement();
                    xsd.endCompositor();
                }
                xsd.endComplexType();
                xsd.startElement().name("root").type(n1, "MyType").endElement();
            }
            xsd.endSchema();
        }
        xsd.endDocument();
    }
1211312
private NamespaceContext buildNamespaceContext(Node node) {
        SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
        Map<String, String> namespaces = XMLUtils.lookupNamespaces(node.getOwnerDocument());

        // add default namespace mappings
        namespaces.putAll(namespaceContextBuilder.getNamespaceMappings());

        simpleNamespaceContext.setBindings(namespaces);

        return simpleNamespaceContext;
    }
611965
public String toCanonicalXml3(TransformerFactory factory, XMLReader resultParser, String inxml, boolean stripSpace)
			throws Exception {
		mStrip = stripSpace;
		mOut = new StringWriter();
		Transformer t = factory.newTransformer();
		SAXSource ss = new SAXSource(resultParser, new InputSource(new StringReader(inxml)));
		ss.setSystemId("http://localhost/string-input");
		t.setOutputProperty(OutputKeys.METHOD, "xml");
		t.setOutputProperty(OutputKeys.INDENT, "no");
		t.transform(ss, new SAXResult(this));
		return mOut.toString();
	}
1095271
public static DocumentBuilderFactory getControlDocumentBuilderFactory() {
        if (controlBuilderFactory == null) {
            controlBuilderFactory = DocumentBuilderFactory.newInstance();
            controlBuilderFactory.setNamespaceAware(true);
            if (enableXXEProtection) {
                DocumentBuilderFactoryConfigurer.Default.configure(controlBuilderFactory);
            }
        }
        return controlBuilderFactory;
    }
1272714
private String parse(DocumentContext document) throws ParseException {
    if (document.namespaceDeclaration() != null) {
      setCurrentNamespace(
        document.namespaceDeclaration().qualifiedIdentifier().value);
    } else {
      setCurrentNamespace("");
    }

    setCurrentImports(document.importDeclarations());
    NamedDataSchema schema = parseNamedType(document.namedTypeDeclaration());
    topLevelSchemas.add(schema);
    return schema.getFullName();
  }
1243924
private void registerXmlSchemaRepository(Element element, ParserContext parserContext) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(XsdSchemaRepository.class);
        BeanDefinitionParserUtils.setPropertyReference(builder, element.getAttribute("schema-mapping-strategy"), "schemaMappingStrategy");
        addLocationsToBuilder(element, builder);
        parseSchemasElement(element, builder, parserContext);
        parserContext.getRegistry().registerBeanDefinition(element.getAttribute(ID), builder.getBeanDefinition());
    }
231491
function (namespace, schemaContent, cb) {
    var self = this;

    if (multivalue.hasValue(self.parsedSchemas, namespace, schemaContent)) {
      cb(null, {});
      return;
    }

    xml2js.parseString(schemaContent, function (err, result) {
      if (err) {
        cb(err);
        return;
      }

      // Only one root element expected
      if (!result || _.size(result) !== 1) {
        cb("Invalid schema for " + namespace + ": " + util.inspect(result, false, null));
        return;
      }

      parseNamespacePrefixes(result, function (err, defaultNamespace, namespaces, xsPrefix) {
        if (err) {
          cb(err);
          return;
        }

        assert(result[xsPrefix + 'schema'], result);

        var schema = result[xsPrefix + 'schema'];

        if (schema.$ && schema.$.targetNamespace && schema.$.targetNamespace !== namespace) {
          cb("Schema does not have expected target namespace " + namespace + ": " + util.inspect(result, false, null));
          return;
        }

        var schemaParser = new XsdSchema(self, namespace, defaultNamespace, namespaces, xsPrefix);

        var importsAndIncludes = schemaParser.parseImportsAndIncludes(namespace, schema);

        var newElements = schemaParser.parseElements(schema, null);
        // TODO: Check if we are overriding anything
        _.extend(self.elements, newElements);

        var newAttributes = schemaParser.parseAttributes(schema);
        // TODO: Check if we are overriding anything
        _.extend(self.attributes, newAttributes);

        var newTypes = schemaParser.parseTypes(schema);
        // TODO: Check if we are overriding anything
        _.extend(self.types, newTypes);

        // TODO: Add support for element and attribute groups
        delete schema[xsPrefix + 'group'];
        delete schema[xsPrefix + 'attributeGroup'];

        // Previous parsing calls are destructive and should consume schema so that it is empty now
        assert(_.isEmpty(schema), schema);

        multivalue.addValue(self.parsedSchemas, namespace, schemaContent);

        cb(null, importsAndIncludes);
      });
    });
  }
898350
public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException
    {
        if(isValidating()) {
            try {
                return new ValidatingDocumentBuilder(
                    _WrappedFactory.newDocumentBuilder(),
                    _Schema.newVerifier());
            } catch(VerifierConfigurationException ex) {
                throw new ParserConfigurationException(ex.getMessage());
            }
        } else
            //if validation is disabled, we simply return the implementation of wrapped DocumentBuilder
            return _WrappedFactory.newDocumentBuilder();
    }
1006147
public Map<String, String> parseXmlConfiguration(final String path) {
    File xmlFile;
    xmlFile = new File(path);
    if (!xmlFile.exists()) {
      System.err.format("File %s does not exist.", path);
      return null;
    }
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
      docBuilder = docBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      System.err.format("Failed to create instance of DocumentBuilder for file: %s. %s. %n",
          path, e.getMessage());
      return null;
    }
    Document doc;
    try {
      doc = docBuilder.parse(xmlFile);
    } catch (IOException e) {
      System.err.format("An I/O error occured reading file %s. %s.%n", path, e.getMessage());
      return null;
    } catch (SAXException e) {
      System.err.format("A parsing error occured parsing file %s. %s.%n", path, e.getMessage());
      return null;
    }
    // Optional, but recommended.
    // Refer to http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();
    Map<String, String> ret = new HashMap<>();
    NodeList propNodeList = doc.getElementsByTagName("property");
    for (int i = 0; i < propNodeList.getLength(); i++) {
      Node propNode = propNodeList.item(i);
      if (propNode.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) propNode;
        ret.put(element.getElementsByTagName("name").item(0).getTextContent(),
            element.getElementsByTagName("value").item(0).getTextContent());
      }
    }
    return ret;
  }
91663
public static DocumentBuilder newDocumentBuilder(boolean nsAware, boolean validating) throws ParserConfigurationException{
        return newDocumentBuilder(nsAware, validating, false, false);
    }
1136427
private SAXParserFactory getSAXParserFactory() {

        final SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(this.namespaceAware);
        factory.setSchema(this.schema);
        return factory;
    }
1136367
public static synchronized DocumentBuilder createDocumentBuilder() {
        DocumentBuilder result;
        try {
            result = FACTORY_NON_VALIDATING.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("createDocumentBuilder failed", e);
        }
        result.setErrorHandler(ERROR_HANDLER);
        return result;
    }