Java Code Examples for javax.xml.parsers.DocumentBuilder#newDocument()
The following examples show how to use
javax.xml.parsers.DocumentBuilder#newDocument() .
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: DomSerializer.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
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); } }
Example 2
Source File: FXml.java From pra with MIT License | 6 votes |
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); }
Example 3
Source File: DomSerializer.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
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); } }
Example 4
Source File: SecondaryUserStoreConfigurationUtil.java From carbon-identity-framework with Apache License 2.0 | 6 votes |
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; }
Example 5
Source File: XmlNew.java From openbd-core with GNU General Public License v3.0 | 6 votes |
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)); } }
Example 6
Source File: Section.java From sakai with Educational Community License v2.0 | 6 votes |
/** * 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()); } }
Example 7
Source File: QueryXmlHelper.java From pentaho-metadata with GNU Lesser General Public License v2.1 | 6 votes |
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; }
Example 8
Source File: DeclensionNodeTest.java From PolyGlot with MIT License | 5 votes |
@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); } }
Example 9
Source File: SymmetricBindingTest.java From cxf with Apache License 2.0 | 5 votes |
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); }
Example 10
Source File: AbstractApplicationComposition.java From photon with Apache License 2.0 | 5 votes |
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; }
Example 11
Source File: DigitalSignatureServiceProxy.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
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; }
Example 12
Source File: CatoResources.java From obevo with Apache License 2.0 | 5 votes |
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); } }
Example 13
Source File: TransportBindingTest.java From cxf with Apache License 2.0 | 5 votes |
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); }
Example 14
Source File: TestSVGSVGElement.java From latexdraw with GNU General Public License v3.0 | 5 votes |
@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()); }
Example 15
Source File: BuildFile.java From JReFrameworker with MIT License | 4 votes |
/** * 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."); }
Example 16
Source File: ManagementBusInvocationPluginRemote.java From container with Apache License 2.0 | 4 votes |
@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; }
Example 17
Source File: LogUtils.java From teamengine with Apache License 2.0 | 4 votes |
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; } }
Example 18
Source File: BodyImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
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; }
Example 19
Source File: EnumerationTypeDefinition.java From regxmllib with BSD 2-Clause "Simplified" License | 3 votes |
@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; }