javax.servlet.http.HttpUtils#javax.xml.parsers.DocumentBuilderFactory源码实例Demo

下面列出了javax.servlet.http.HttpUtils#javax.xml.parsers.DocumentBuilderFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Parses and normalizes the XML document available on the given stream.
 * 
 * @param stream
 *          The input stream.
 * @return A Document representing the XML document.
 * @throws IOException
 *           - failed to read input
 * @throws PIRException
 *           - file could not be parsed
 */
private Document parseXMLDocument(InputStream stream) throws IOException, PIRException
{
  Document doc;
  try
  {
    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    doc = dBuilder.parse(stream);
  } catch (ParserConfigurationException | SAXException e)
  {
    throw new PIRException("Schema parsing error", e);
  }
  doc.getDocumentElement().normalize();
  logger.info("Root element: " + doc.getDocumentElement().getNodeName());

  return doc;
}
 
源代码2 项目: JavaMainRepo   文件: EntityRepository.java
public ArrayList<T> load() throws ParserConfigurationException, SAXException, IOException {

		ArrayList<T> entities = new ArrayList<T>();

		File fXmlFile = new File(this.xmlFilename);

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();

		NodeList nodeList = doc.getElementsByTagName(this.entityTag);

		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) node;
				entities.add(getEntityFromXmlElement(element));

			}
		}
		return entities;
	}
 
源代码3 项目: jdk8u60   文件: EPRHeader.java
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
源代码4 项目: Hi-WAY   文件: GalaxyApplicationMaster.java
/**
 * A helper function for processing the Galaxy config file that specifies the extensions and python script locations for Galaxy's data types
 * 
 * @param file
 *            the Galaxy data type config file
 */
private void processDataTypes(File file) {
	try {
		WorkflowDriver.writeToStdout("Processing Galaxy data type config file " + file.getCanonicalPath());
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(file);
		NodeList datatypeNds = doc.getElementsByTagName("datatype");
		for (int i = 0; i < datatypeNds.getLength(); i++) {
			Element datatypeEl = (Element) datatypeNds.item(i);
			if (!datatypeEl.hasAttribute("extension") || !datatypeEl.hasAttribute("type") || datatypeEl.hasAttribute("subclass"))
				continue;
			String extension = datatypeEl.getAttribute("extension");
			String[] splitType = datatypeEl.getAttribute("type").split(":");
			galaxyDataTypes.put(extension, new GalaxyDataType(splitType[0], splitType[1], extension));
		}
	} catch (SAXException | IOException | ParserConfigurationException e) {
		e.printStackTrace(System.out);
		System.exit(-1);
	}
}
 
源代码5 项目: jframe   文件: XmlUtil.java
public static Map<String, String> fromXml(InputStream in) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document source = builder.parse(in);

    NodeList nodeList = source.getDocumentElement().getChildNodes();

    Map<String, String> map = new HashMap<>();
    Node node = null;
    for (int i = 0; i < nodeList.getLength(); i++) {
        node = nodeList.item(i);
        map.put(node.getNodeName(), node.getTextContent());
    }
    return map;
}
 
源代码6 项目: netbeans   文件: JaxRsStackSupportImpl.java
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
源代码7 项目: openjdk-jdk9   文件: Bug4967002.java
void setAttr(boolean setSrc) {
    DocumentBuilderFactory docBFactory = DocumentBuilderFactory.newInstance();
    Schema sch = createSchema();
    docBFactory.setSchema(sch);
    docBFactory.setNamespaceAware(true);
    docBFactory.setValidating(true);

    final String aSchemaLanguage = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    final String aSchemaSource = "http://java.sun.com/xml/jaxp/properties/schemaSource";

    docBFactory.setAttribute(aSchemaLanguage, "http://www.w3.org/2001/XMLSchema");
    // System.out.println("---- Set schemaLanguage: " +
    // docBFactory.getAttribute(aSchemaLanguage));
    if (setSrc) {
        docBFactory.setAttribute(aSchemaSource, new InputSource(new StringReader(schemaSource)));
        // System.out.println("---- Set schemaSource: " +
        // docBFactory.getAttribute(aSchemaSource));
    }

    try {
        docBFactory.newDocumentBuilder();
        Assert.fail("ParserConfigurationException expected");
    } catch (ParserConfigurationException pce) {
        return; // success
    }
}
 
源代码8 项目: xades4j   文件: DOMHelperTest.java
@Test
public void testGetChildElementsByTagNameNS() throws Exception
{
    String xml = "<root><a xmlns='urn:test'/><b/><n:a xmlns:n='urn:test'/><c/></root>";
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(xml)));
    
    Collection<Element> elements = DOMHelper.getChildElementsByTagNameNS(doc.getDocumentElement(), "urn:test", "a");
    
    Assert.assertNotNull(elements);
    Assert.assertEquals(2, elements.size());
    for (Element element : elements)
    {
        Assert.assertEquals("a", element.getLocalName());
    }
}
 
@Test
public void marshalEmptyDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	DOMResult domResult = new DOMResult();
	marshaller.marshal(flights, domResult);
	assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
	Document result = (Document) domResult.getNode();
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
源代码10 项目: proarc   文件: CejshBuilder.java
public CejshBuilder(CejshConfig config, ExportOptions options)
        throws TransformerConfigurationException, ParserConfigurationException, XPathExpressionException {
    this.gcalendar = new GregorianCalendar(UTC);
    this.logLevel = config.getLogLevel();
    this.options = options;
    TransformerFactory xslFactory = TransformerFactory.newInstance();
    tranformationErrorHandler = new TransformErrorListener();
    bwmetaXsl = xslFactory.newTransformer(new StreamSource(config.getCejshXslUrl()));
    if (bwmetaXsl == null) {
        throw new TransformerConfigurationException("Cannot load XSL: " + config.getCejshXslUrl());
    }
    bwmetaXsl.setOutputProperty(OutputKeys.INDENT, "yes");
    bwmetaXsl.setErrorListener(tranformationErrorHandler);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    db = dbf.newDocumentBuilder();
    XPathFactory xPathFactory = ProarcXmlUtils.defaultXPathFactory();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("m", ModsConstants.NS));
    issnPath = xpath.compile("m:mods/m:identifier[@type='issn' and not(@invalid)]");
    partNumberPath = xpath.compile("m:mods/m:titleInfo/m:partNumber");
    dateIssuedPath = xpath.compile("m:mods/m:originInfo/m:dateIssued");
    reviewedArticlePath = xpath.compile("m:mods/m:genre[text()='article' and @type='peer-reviewed']");
}
 
源代码11 项目: photon   文件: OutputProfileList.java
/**
 * A method that confirms if the inputStream corresponds to a OutputProfileList document instance.
 *
 * @param resourceByteRangeProvider corresponding to the OutputProfileList XML file.
 * @return a boolean indicating if the input file is a OutputProfileList document
 * @throws IOException - any I/O related error is exposed through an IOException
 */
public static boolean isOutputProfileList(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException {
    try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1);) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(inputStream);

        //obtain root node
        NodeList nodeList = document.getElementsByTagNameNS(outputProfileList_QNAME.getNamespaceURI(), outputProfileList_QNAME.getLocalPart());
        if (nodeList != null && nodeList.getLength() == 1) {
            return true;
        }
    } catch (ParserConfigurationException | SAXException e) {
        return false;
    }
    return false;
}
 
源代码12 项目: sarl   文件: StandardSREInstallTest.java
@Test
public void setFromXML() throws Exception {
	String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
			"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
					+ "\" standalone=\"true\">",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
					+ "\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
	StringBuilder b = new StringBuilder();
	for (String s : expected) {
		b.append(s);
		// b.append("\n");
	}
	try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		Element root = parser.parse(new InputSource(bais)).getDocumentElement();
		this.sre.setFromXML(root);
		assertTrue(this.sre.isStandalone());
		assertEquals(this.path, this.sre.getJarFile());
		assertEquals("Hello", this.sre.getName());
		assertEquals("io.sarl.Boot", this.sre.getMainClass());
	}
}
 
源代码13 项目: container   文件: DocumentConverter.java
/**
 * Converts a given String to a XML document
 *
 * @return Document - converted xml Document
 */
private static Document getDocument(final String documentString) {
    if (documentString.isEmpty()) {
        return emptyDocument();
    }
    // start conversion
    final InputSource iSource = new InputSource(new StringReader(documentString));
    Document doc = null;
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setIgnoringComments(true);
        final DocumentBuilder db = dbf.newDocumentBuilder();

        // parse
        doc = db.parse(iSource);
        doc.getDocumentElement().normalize();
    } catch (final ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return doc;
}
 
源代码14 项目: RDFS   文件: TestJobTrackerXmlJsp.java
/**
 * Read the jobtracker.jspx status page and validate that the XML is well formed.
 */
public void testXmlWellFormed() throws IOException, ParserConfigurationException, SAXException {
  MiniMRCluster cluster = getMRCluster();
  int infoPort = cluster.getJobTrackerRunner().getJobTrackerInfoPort();

  String xmlJspUrl = "http://localhost:" + infoPort + "/jobtracker.jspx";
  LOG.info("Retrieving XML from URL: " + xmlJspUrl);

  DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = parser.parse(xmlJspUrl);

  // If we get here, then the document was successfully parsed by SAX and is well-formed.
  LOG.info("Document received and parsed.");

  // Make sure it has a <cluster> element as top-level.
  NodeList clusterNodes = doc.getElementsByTagName("cluster");
  assertEquals("There should be exactly 1 <cluster> element", 1, clusterNodes.getLength());
}
 
源代码15 项目: openjdk-jdk9   文件: TransformerTest02.java
/**
 * Unit test for transform(StreamSource, StreamResult).
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "transformer02.out";
    String goldFile = GOLDEN_DIR + "transformer02GF.out";
    String xsltFile = XML_DIR + "cities.xsl";
    String xmlFile = XML_DIR + "cities.xml";

    try (FileInputStream fis = new FileInputStream(xmlFile);
            FileOutputStream fos = new FileOutputStream(outputFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DOMSource domSource = new DOMSource(dbf.newDocumentBuilder().
                parse(new File(xsltFile)));

        Transformer transformer = TransformerFactory.newInstance().
                newTransformer(domSource);
        StreamSource streamSource = new StreamSource(fis);
        StreamResult streamResult = new StreamResult(fos);

        transformer.setOutputProperty("indent", "no");
        transformer.transform(streamSource, streamResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
源代码16 项目: carbon-apimgt   文件: Util.java
/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws Exception
 */
public static XMLObject unmarshall(String authReqStr) throws Exception {
    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = getSecuredDocumentBuilder();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setIgnoringComments(true);
        Document document = getDocument(documentBuilderFactory, authReqStr);
        if (isSignedWithComments(document)) {
            documentBuilderFactory.setIgnoringComments(false);
            document = getDocument(documentBuilderFactory, authReqStr);
        }
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        throw new Exception("Error in constructing AuthRequest from " +
                "the encoded String ", e);
    }
}
 
源代码17 项目: openjdk-8-source   文件: EPRHeader.java
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
源代码18 项目: openjdk-jdk9   文件: XMLStreamWriterTest.java
/**
 * @bug 8139584
 * Verifies that the resulting XML contains the standalone setting.
 */
@Test
public void testCreateStartDocument_DOMWriter()
        throws ParserConfigurationException, XMLStreamException {

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    XMLEventWriter eventWriter = xof.createXMLEventWriter(new DOMResult(doc));
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true);
    eventWriter.add(event);
    eventWriter.flush();
    Assert.assertEquals(doc.getXmlEncoding(), "iso-8859-15");
    Assert.assertEquals(doc.getXmlVersion(), "1.0");
    Assert.assertTrue(doc.getXmlStandalone());
}
 
源代码19 项目: jasperreports   文件: SimpleFontExtensionHelper.java
/**
 *
 */
private SimpleFontExtensionHelper()
{
	try
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setFeature(JRXmlUtils.FEATURE_DISALLOW_DOCTYPE, true);
		
		documentBuilder = factory.newDocumentBuilder();
		documentBuilder.setErrorHandler(this);
	}
	catch (ParserConfigurationException e)
	{
		throw new JRRuntimeException(e);
	}
}
 
源代码20 项目: jdk8u-jdk   文件: TruncateHMAC.java
public static void main(String[] args) throws Exception {

        Init.init();
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        validate("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", false);
        validate("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", false);
        // this one should pass
        validate("signature-enveloping-hmac-sha1.xml", true);
        generate_hmac_sha1_40();

        if (atLeastOneFailed) {
            throw new Exception
                ("At least one signature did not validate as expected");
        }
    }
 
源代码21 项目: jdk8u60   文件: DTMManagerDefault.java
/**
 * Method createDocumentFragment
 *
 *
 * NEEDSDOC (createDocumentFragment) @return
 */
synchronized public DTM createDocumentFragment()
{

  try
  {
    DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(super.useServicesMechnism());
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Node df = doc.createDocumentFragment();

    return getDTM(new DOMSource(df), true, null, false, false);
  }
  catch (Exception e)
  {
    throw new DTMException(e);
  }
}
 
源代码22 项目: hbase   文件: TestConfServlet.java
@Test
public void testWriteXml() throws Exception {
  StringWriter sw = new StringWriter();
  ConfServlet.writeResponse(getTestConf(), sw, "xml");
  String xml = sw.toString();

  DocumentBuilderFactory docBuilderFactory
    = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(xml)));
  NodeList nameNodes = doc.getElementsByTagName("name");
  boolean foundSetting = false;
  for (int i = 0; i < nameNodes.getLength(); i++) {
    Node nameNode = nameNodes.item(i);
    String key = nameNode.getTextContent();
    System.err.println("xml key: " + key);
    if (TEST_KEY.equals(key)) {
      foundSetting = true;
      Element propertyElem = (Element)nameNode.getParentNode();
      String val = propertyElem.getElementsByTagName("value").item(0).getTextContent();
      assertEquals(TEST_VAL, val);
    }
  }
  assertTrue(foundSetting);
}
 
源代码23 项目: protoc-jar   文件: MavenUtil.java
static String parseLastReleaseBuild(File mdFile, ProtocVersion protocVersion) throws IOException {
	int lastBuild = 0;
	try {
		DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document xmlDoc = xmlBuilder.parse(mdFile);
		NodeList versions = xmlDoc.getElementsByTagName("version");
		for (int i = 0; i < versions.getLength(); i++) {
			Node ver = versions.item(i);
			String verStr = ver.getTextContent();
			if (verStr.startsWith(protocVersion.mVersion+"-build")) {
				String buildStr = verStr.substring(verStr.indexOf("-build")+"-build".length());
				int build = Integer.parseInt(buildStr);
				if (build > lastBuild) lastBuild = build;
			}
		}
	}
	catch (Exception e) {
		throw new IOException(e);
	}
	if (lastBuild > 0) return protocVersion.mVersion+"-build"+lastBuild;
	return null;
}
 
源代码24 项目: carbon-apimgt   文件: AbstractWSDLProcessor.java
/**
 * Returns a secured document builder to avoid XXE attacks
 *
 * @return secured document builder to avoid XXE attacks
 */
private DocumentBuilderFactory getSecuredDocumentBuilder() {
    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) {
        // Skip throwing the error as this exception doesn't break actual DocumentBuilderFactory creation
        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, e);
    }
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);
    return dbf;
}
 
源代码25 项目: openjdk-8   文件: EPRHeader.java
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
源代码26 项目: j-road   文件: XTeeSoapProvider.java
@Override
protected void populatePort(Definition definition, Port port) throws WSDLException {
  super.populatePort(definition, port);
  ExtensionRegistry extensionRegistry = definition.getExtensionRegistry();
  extensionRegistry.mapExtensionTypes(Port.class,
                                      new QName(XTeeWsdlDefinition.XROAD_NAMESPACE,
                                                "address",
                                                XTeeWsdlDefinition.XROAD_PREFIX),
                                      UnknownExtensibilityElement.class);
  UnknownExtensibilityElement element =
      (UnknownExtensibilityElement) extensionRegistry.createExtension(Port.class,
                                                                      new QName(XTeeWsdlDefinition.XROAD_NAMESPACE,
                                                                                "address",
                                                                                XTeeWsdlDefinition.XROAD_NAMESPACE));
  Document doc;
  try {
    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  } catch (ParserConfigurationException e) {
    throw new RuntimeException(e);
  }
  Element xRoadAddr = doc.createElementNS(XTeeWsdlDefinition.XROAD_NAMESPACE, "address");
  xRoadAddr.setPrefix(XTeeWsdlDefinition.XROAD_PREFIX);
  xRoadAddr.setAttribute("producer", xRoadDatabase);
  element.setElement(xRoadAddr);
  port.addExtensibilityElement(element);
}
 
源代码27 项目: MeteoInfo   文件: LayersLegend.java
/**
 * Import project XML content
 *
 * @param fileName XML file name
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public void importProjectXML(String fileName) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new File(fileName));

    Element root = doc.getDocumentElement();

    Properties property = System.getProperties();
    String path = System.getProperty("user.dir");
    property.setProperty("user.dir", new File(fileName).getAbsolutePath());
    String pPath = new File(fileName).getParent();

    this.getActiveMapFrame().getMapView().setLockViewUpdate(true);
    this.importProjectXML(pPath, root);
    this.getActiveMapFrame().getMapView().setLockViewUpdate(false);
    this.paintGraphics();
    this.getActiveMapFrame().getMapView().paintLayers();

    property.setProperty("user.dir", path);
}
 
源代码28 项目: io   文件: DavCmpEsImpl.java
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
源代码29 项目: sakai   文件: I18nXmlUtility.java
/**
 * Gets a DocumentBuilder instance
 */
public static DocumentBuilder getDocumentBuilder() {
	try {
		if (documentBuilderFactory == null) {
			documentBuilderFactory = DocumentBuilderFactory.newInstance();
		}
		if (documentBuilder == null) {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
		}

		return documentBuilder;
	}
	catch (Exception e) {
		throw new ContentReviewProviderException("Failed to produce an XML Document Builder", e);
	}
}
 
private static Document createDocument(String content) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(content)));
    doc.getDocumentElement().normalize();
    // Don't want to add these settings to the jfc-files we ship since they
    // are not useful to configure. They are however needed to make the test
    // pass.
    insertSetting(doc, "com.oracle.jdk.ActiveSetting", "stackTrace", "false");
    insertSetting(doc, "com.oracle.jdk.ActiveSetting", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.ActiveRecording", "stackTrace", "false");
    insertSetting(doc, "com.oracle.jdk.ActiveRecording", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.JavaExceptionThrow", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.JavaErrorThrow", "threshold", "0 ns");
    return doc;
}