javax.xml.parsers.DocumentBuilder#newDocument ( )源码实例Demo

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

源代码1 项目: container   文件: XMLHelper.java
public static Document withRootNode(Collection<Element> any, String string) {
    if (any == null) {
        return null;
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // YA we dun fucked up...
        // LOGGER.error(e);
        return null;
    }
    Document result = builder.newDocument();
    Node root = result.createElement(string);
    any.forEach(root::appendChild);
    Node imported = result.importNode(root, true);
    result.appendChild(imported);
    return result;
}
 
源代码2 项目: pentaho-metadata   文件: QueryXmlHelper.java
public Document toDocument( Query query ) {

    if ( query == null ) {
      logger.error( Messages.getErrorString( "QueryXmlHelper.ERROR_0000_QUERY_MUST_NOT_BE_NULL" ) ); //$NON-NLS-1$
      return null;
    }

    Document doc;
    try {
      // create an XML document
      DocumentBuilderFactory dbf = XmiParser.createSecureDocBuilderFactory();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.newDocument();
      Element mqlElement = doc.createElement( "mql" ); //$NON-NLS-1$
      doc.appendChild( mqlElement );

      if ( addToDocument( mqlElement, doc, query ) ) {
        return doc;
      } else {
        return null;
      }
    } catch ( Exception e ) {
      logger.error( Messages.getErrorString( "QueryXmlHelper.ERROR_0002_TO_DOCUMENT_FAILED" ), e ); //$NON-NLS-1$
    }
    return null;
  }
 
源代码3 项目: openjdk-8   文件: DomSerializer.java
public DomSerializer(DOMResult domResult) {
    Node node = domResult.getNode();

    if (node == null) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
            domResult.setNode(doc);
            serializer = new SaxSerializer(new Dom2SaxAdapter(doc),null,false);
        } catch (ParserConfigurationException pce) {
            throw new TxwException(pce);
        }
    } else {
        serializer = new SaxSerializer(new Dom2SaxAdapter(node),null,false);
    }
}
 
源代码4 项目: sakai   文件: Section.java
/**
 * add section ref
 *
 * @param sectionId section id
 */
public void addSectionRef(String sectionId)
{
  if (log.isDebugEnabled())
  {
    log.debug("addSection(String " + sectionId + ")");
  }
  try {
  	String xpath = basePath;
  	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  	DocumentBuilder db = dbf.newDocumentBuilder();
  	Document document = db.newDocument();
  	Element element = document.createElement(QTIConstantStrings.SECTIONREF);
  	element.setAttribute(QTIConstantStrings.LINKREFID, sectionId);
  	this.addElement(xpath, element);
  } catch(ParserConfigurationException pce) {
  	log.error("Exception thrown from addSectionRef() : " + pce.getMessage());
  }
}
 
源代码5 项目: openbd-core   文件: XmlNew.java
public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
	boolean caseSensitive = false;
	if (parameters.size() == 1)
		caseSensitive = cfBooleanData.getcfBooleanData(parameters.get(0).getString()).getBoolean();
	try {
		DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
		fact.setNamespaceAware(true);
		DocumentBuilder parser = fact.newDocumentBuilder();

		Document doc = parser.newDocument();
		doc.normalize();
		return new cfXmlData(doc, caseSensitive);
	} catch (ParserConfigurationException ex) {
		throw new cfmRunTimeException(catchDataFactory.javaMethodException("errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
	}
}
 
private static Document getDocument(UserStoreDTO userStoreDTO, boolean editSecondaryUserStore,
                                    DocumentBuilder documentBuilder, String existingDomainName)
        throws IdentityUserStoreMgtException {

    Document doc = documentBuilder.newDocument();

    //create UserStoreManager element
    Element userStoreElement = doc.createElement(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER);
    doc.appendChild(userStoreElement);

    Attr attrClass = doc.createAttribute("class");
    if (userStoreDTO != null) {
        attrClass.setValue(userStoreDTO.getClassName());
        userStoreElement.setAttributeNode(attrClass);
        if (userStoreDTO.getClassName() != null) {
            addProperties(existingDomainName, userStoreDTO.getClassName(), userStoreDTO.getProperties(),
                    doc, userStoreElement, editSecondaryUserStore);
        }
        addProperty(UserStoreConfigConstants.DOMAIN_NAME, userStoreDTO.getDomainId(), doc, userStoreElement, false);
        addProperty(UserStoreConfigurationConstant.DESCRIPTION, userStoreDTO.getDescription(), doc,
                    userStoreElement, false);
    }
    return doc;
}
 
源代码7 项目: jdk8u60   文件: DomSerializer.java
public DomSerializer(DOMResult domResult) {
    Node node = domResult.getNode();

    if (node == null) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
            domResult.setNode(doc);
            serializer = new SaxSerializer(new Dom2SaxAdapter(doc),null,false);
        } catch (ParserConfigurationException pce) {
            throw new TxwException(pce);
        }
    } else {
        serializer = new SaxSerializer(new Dom2SaxAdapter(node),null,false);
    }
}
 
源代码8 项目: pra   文件: FXml.java
public static void sample()throws Exception {
  int no = 2;

  String root = "EnterRoot";
  DocumentBuilderFactory dbf =   DocumentBuilderFactory.newInstance();
  DocumentBuilder db =  dbf.newDocumentBuilder();
  Document d = db.newDocument();
  Element eRoot = d.createElement(root);
      d.appendChild(eRoot);
  for (int i = 1; i <= no; i++){

    String element = "EnterElement";
    String data = "Enter the data";
    
    Element e = d.createElement(element);
    e.appendChild(d.createTextNode(data));
    eRoot.appendChild(e);
  }
  TransformerFactory tf = TransformerFactory.newInstance();
   Transformer t = tf.newTransformer();
   DOMSource source = new DOMSource(d);
   StreamResult result =  new StreamResult(System.out);
   t.transform(source, result);

}
 
源代码9 项目: photon   文件: AbstractApplicationComposition.java
private List<Node> getEssenceDescriptorDOMNodes(Composition.HeaderPartitionTuple headerPartitionTuple) throws IOException {
    IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
        List<InterchangeObject.InterchangeObjectBO> essenceDescriptors = headerPartitionTuple.getHeaderPartition().getEssenceDescriptors();
        List<Node> essenceDescriptorNodes = new ArrayList<>();
        for (InterchangeObject.InterchangeObjectBO essenceDescriptor : essenceDescriptors) {
            try {
                KLVPacket.Header essenceDescriptorHeader = essenceDescriptor.getHeader();
                List<KLVPacket.Header> subDescriptorHeaders = this.getSubDescriptorKLVHeader(headerPartitionTuple.getHeaderPartition(), essenceDescriptor);
                /*Create a dom*/
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document document = docBuilder.newDocument();

                DocumentFragment documentFragment = this.getEssenceDescriptorAsDocumentFragment(document, headerPartitionTuple, essenceDescriptorHeader, subDescriptorHeaders);
                Node node = documentFragment.getFirstChild();
                essenceDescriptorNodes.add(node);
            } catch (ParserConfigurationException e) {
                imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.INTERNAL_ERROR,
                        IMFErrorLogger.IMFErrors
                        .ErrorLevels.FATAL, e.getMessage());
            }
        }
        if(imfErrorLogger.hasFatalErrors()) {
            throw new IMFException("Failed to get Essence Descriptor for a resource", imfErrorLogger);
        }
        return essenceDescriptorNodes;

}
 
源代码10 项目: PolyGlot   文件: DeclensionNodeTest.java
@Test
public void testWriteXMLTemplate() {
    System.out.println("DeclensionNodeTest.testWriteXMLTemplate");
    
    String expectedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
            +"<dictionary>"
            + "<declensionNode>"
            + "<declensionId>1</declensionId>" 
            + "<declensionText>value</declensionText>"
            + "<declensionNotes>notes</declensionNotes>"
            + "<declensionTemplate>1</declensionTemplate>"
            + "<declensionRelatedId>1</declensionRelatedId>"
            + "<declensionDimensionless>F</declensionDimensionless>"
            + "<dimensionNode>"
            + "<dimensionId>0</dimensionId>"
            + "<dimensionName>zot</dimensionName>"
            + "</dimensionNode></declensionNode></dictionary>";
    int relatedId = 1;
    DeclensionDimension dim = new DeclensionDimension();
    dim.setValue("zot");
    
    testNode.getBuffer().setEqual(dim);
    testNode.getBuffer().setId(0);
    
    try {
        testNode.insertBuffer();
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(PGTUtil.DICTIONARY_XID);
        doc.appendChild(rootElement);

        testNode.writeXMLTemplate(doc, rootElement, relatedId);
        
        assertTrue(TestResources.textXmlDocEquals(doc, expectedXml));
    } catch (Exception e) {
        fail(e);
    }
}
 
源代码11 项目: cxf   文件: SymmetricBindingTest.java
private DOMSource createDOMRequest() throws ParserConfigurationException {
    // Creating a DOMSource Object for the request
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document requestDoc = db.newDocument();
    Element root = requestDoc.createElementNS("http://www.example.org/schema/DoubleIt", "ns2:DoubleIt");
    root.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:ns2", "http://www.example.org/schema/DoubleIt");
    Element number = requestDoc.createElementNS(null, "numberToDouble");
    number.setTextContent("25");
    root.appendChild(number);
    requestDoc.appendChild(root);
    return new DOMSource(requestDoc);
}
 
private static Element createSignatureType() throws ParserConfigurationException {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setNamespaceAware(true);
   DocumentBuilder builder = dbf.newDocumentBuilder();
   Document doc = builder.newDocument();
   Element signatureType = doc.createElementNS("urn:oasis:names:tc:dss:1.0:core:schema", "SignatureType");
   signatureType.setTextContent("urn:ietf:rfc:3447");
   return signatureType;
}
 
源代码13 项目: obevo   文件: CatoResources.java
private void saveResources(String saveLocation) throws CatoResourcesException {
    if (this.resourcesFilePath == null) {
        LOG.error("Save is unavailable as the resources file path is null/empty.");
        throw new CatoResourcesException(
                "Save is unavailable as the resources file path is null/empty.");
    }
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document resourcesDocument = db.newDocument();
        Element resElem = resourcesDocument.createElement("CatoResources");
        Element reconsElem = resourcesDocument.createElement("Recons");
        Element dataSourcesElem = resourcesDocument
                .createElement("DataSources");
        resElem.appendChild(reconsElem);
        resElem.appendChild(dataSourcesElem);
        resourcesDocument.appendChild(resElem);

        this.writeReconsToElement(reconsElem);
        this.writeDataSourcesToElement(dataSourcesElem);

        this.writeDocument(resourcesDocument, saveLocation);
    } catch (ParserConfigurationException e) {
        throw new CatoResourcesException(
                "Uable to create a new resources document.", e);
    }
}
 
源代码14 项目: cxf   文件: TransportBindingTest.java
private DOMSource createDOMRequest() throws ParserConfigurationException {
    // Creating a DOMSource Object for the request
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document requestDoc = db.newDocument();
    Element root = requestDoc.createElementNS("http://www.example.org/schema/DoubleIt", "ns2:DoubleIt");
    root.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:ns2", "http://www.example.org/schema/DoubleIt");
    Element number = requestDoc.createElementNS(null, "numberToDouble");
    number.setTextContent("25");
    root.appendChild(number);
    requestDoc.appendChild(root);
    return new DOMSource(requestDoc);
}
 
源代码15 项目: latexdraw   文件: TestSVGSVGElement.java
@Test
void testGetMeta() throws ParserConfigurationException {
	final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	final DocumentBuilder builder = factory.newDocumentBuilder();
	final Document document = builder.newDocument();
	final Element n = document.createElement(SVGElements.SVG_SVG);
	n.setAttribute("xmlns", SVGDocument.SVG_NAMESPACE);
	n.appendChild(document.createElement(SVGElements.SVG_METADATA));
	e = new SVGSVGElement(n, null);
	assertNotNull(e.getMeta());
}
 
源代码16 项目: JReFrameworker   文件: BuildFile.java
/**
 * Creates a new build file
 * @param project
 * @return
 * @throws JavaModelException 
 */
public static BuildFile createBuildFile(IJavaProject jProject) {
	try {
		File buildXMLFile = new File(jProject.getProject().getLocation().toFile().getAbsolutePath() + File.separator + XML_BUILD_FILENAME);
		String base = jProject.getProject().getLocation().toFile().getCanonicalPath();
		String relativeBuildFilePath = buildXMLFile.getCanonicalPath().substring(base.length());
		if(relativeBuildFilePath.charAt(0) == File.separatorChar){
			relativeBuildFilePath = relativeBuildFilePath.substring(1);
		}

		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("build");
		doc.appendChild(rootElement);
		
		// save the original classpath
		Element targets = doc.createElement("targets");
		rootElement.appendChild(targets);

		// write the content into xml file
		writeBuildFile(buildXMLFile, doc);
		
		if(JReFrameworkerPreferences.isVerboseLoggingEnabled()) {
			Log.info("Created Build XML File: " + relativeBuildFilePath);
		}
		
		return new BuildFile(buildXMLFile);
	} catch (ParserConfigurationException pce) {
		Log.error("ParserConfigurationException", pce);
	} catch (TransformerException tfe) {
		Log.error("TransformerException", tfe);
	} catch (IOException ioe) {
		Log.error("IOException", ioe);
	} catch (DOMException dome) {
		Log.error("DOMException", dome);
	}
	throw new RuntimeException("Unable to create build file.");
}
 
@Override
public Exchange invoke(final Exchange exchange) {

    LOG.debug("Invoking IA on remote OpenTOSCA Container.");
    final Message message = exchange.getIn();
    final Object body = message.getBody();

    // IA invocation request containing the input parameters
    final IAInvocationRequest invocationRequest = parseBodyToInvocationRequest(body);

    // create request message and add the input parameters as body
    final BodyType requestBody = new BodyType(invocationRequest);
    final CollaborationMessage request = new CollaborationMessage(new KeyValueMap(), requestBody);

    // perform remote IA operation
    final Exchange responseExchange = requestSender.sendRequestToRemoteContainer(message, RemoteOperations.INVOKE_IA_OPERATION, request, 0);

    LOG.debug("Received a response for the invocation request!");

    if (!(responseExchange.getIn().getBody() instanceof CollaborationMessage)) {
        LOG.error("Received message has invalid class: {}", responseExchange.getIn().getBody().getClass());
        return exchange;
    }

    // extract the body and process the contained response
    final CollaborationMessage responseMessage = responseExchange.getIn().getBody(CollaborationMessage.class);
    final BodyType responseBody = responseMessage.getBody();

    if (Objects.isNull(responseBody)) {
        LOG.error("Collaboration message contains no body.");
        return exchange;
    }

    final IAInvocationRequest invocationResponse = responseBody.getIAInvocationRequest();

    if (Objects.isNull(invocationResponse)) {
        LOG.error("Body contains no IAInvocationRequest object with the result.");
        return exchange;
    }

    // process output of the response
    if (invocationResponse.getParams() != null) {
        LOG.debug("Response contains output as HashMap:");

        final HashMap<String, String> outputParamMap = new HashMap<>();

        for (final KeyValueType outputParam : invocationResponse.getParams().getKeyValuePair()) {
            LOG.debug("Key: {}, Value: {}", outputParam.getKey(), outputParam.getValue());
            outputParamMap.put(outputParam.getKey(), outputParam.getValue());
        }
        message.setBody(outputParamMap, HashMap.class);
    } else {
        if (invocationResponse.getDoc() != null) {
            LOG.debug("Response contains output as Document");

            try {
                final DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
                final DocumentBuilder build = dFact.newDocumentBuilder();
                final Document document = build.newDocument();

                final Element element = invocationResponse.getDoc().getAny();

                document.adoptNode(element);
                document.appendChild(element);

                message.setBody(document, Document.class);
            } catch (final Exception e) {
                LOG.error("Unable to parse Document: {}", e.getMessage());
            }
        } else {
            LOG.warn("Response contains no output.");
            message.setBody(null);
        }
    }

    return exchange;
}
 
源代码18 项目: teamengine   文件: LogUtils.java
public static Document readLog(File logDir, String callpath)
         throws Exception {
     File dir = new File(logDir, callpath);
     File f = new File(dir, "log.xml");
     if (f.exists()) {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.newDocument();
         TransformerFactory tf = TransformerFactory.newInstance();
    	     // Fortify Mod: prevent external entity injection
         tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
         Transformer t = tf.newTransformer();
         t.setErrorListener(new com.occamlab.te.NullErrorListener());
         try {
             t.transform(new StreamSource(f), new DOMResult(doc));
         } catch (Exception e) {
             // The log may not have been closed properly.
             // Try again with a closing </log> tag
             RandomAccessFile raf = new RandomAccessFile(f, "r");
             int l = new Long(raf.length()).intValue();
             byte[] buf = new byte[l + 8];
             raf.read(buf);
             raf.close();
             buf[l] = '\n';
             buf[l + 1] = '<';
             buf[l + 2] = '/';
             buf[l + 3] = 'l';
             buf[l + 4] = 'o';
             buf[l + 5] = 'g';
             buf[l + 6] = '>';
             buf[l + 7] = '\n';
             doc = db.newDocument();
             tf.newTransformer().transform(
                     new StreamSource(new ByteArrayInputStream(buf)),
                     new DOMResult(doc));
         }
         return doc;
     } else {
         return null;
     }
 }
 
源代码19 项目: openjdk-jdk8u   文件: BodyImpl.java
public Document extractContentAsDocument() throws SOAPException {

        Iterator eachChild = getChildElements();
        javax.xml.soap.Node firstBodyElement = null;

        while (eachChild.hasNext() &&
               !(firstBodyElement instanceof SOAPElement))
            firstBodyElement = (javax.xml.soap.Node) eachChild.next();

        boolean exactlyOneChildElement = true;
        if (firstBodyElement == null)
            exactlyOneChildElement = false;
        else {
            for (org.w3c.dom.Node node = firstBodyElement.getNextSibling();
                 node != null;
                 node = node.getNextSibling()) {

                if (node instanceof Element) {
                    exactlyOneChildElement = false;
                    break;
                }
            }
        }

        if(!exactlyOneChildElement) {
            log.log(Level.SEVERE,
                    "SAAJ0250.impl.body.should.have.exactly.one.child");
            throw new SOAPException("Cannot extract Document from body");
        }

        Document document = null;
        try {
            DocumentBuilderFactory factory =
                new com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.newDocument();

            Element rootElement = (Element) document.importNode(
                                                firstBodyElement,
                                                true);

            document.appendChild(rootElement);

        } catch(Exception e) {
            log.log(Level.SEVERE,
                    "SAAJ0251.impl.cannot.extract.document.from.body");
            throw new SOAPExceptionImpl(
                "Unable to extract Document from body", e);
        }

        firstBodyElement.detachNode();

        return document;
    }
 
源代码20 项目: regxmllib   文件: EnumerationTypeDefinition.java
@Override
public Object marshal(ArrayList<Element> v) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    org.w3c.dom.Element elem = doc.createElementNS(MetaDictionary.XML_NS, "Elements");

    for (Element e : v) {

        org.w3c.dom.Element e1 = doc.createElementNS(MetaDictionary.XML_NS, "Name");

        e1.setTextContent(e.getName());

        elem.appendChild(e1);

        e1 = doc.createElementNS(MetaDictionary.XML_NS, "Value");

        e1.setTextContent(Integer.toString(e.getValue()));

        elem.appendChild(e1);

        if (e.getDescription() != null) {
            e1 = doc.createElementNS(MetaDictionary.XML_NS, "Description");

            e1.setTextContent(e.getDescription());

            elem.appendChild(e1);
        }

    }

    return elem;
}