List of usage examples for org.w3c.dom Document removeChild
public Node removeChild(Node oldChild) throws DOMException;
oldChild
from the list of children, and returns it. From source file:com.twinsoft.convertigo.engine.print.PrintHTML.java
@Override public String print(String location) throws IOException, EngineException, SAXException, TransformerFactoryConfigurationError, TransformerException, ParserConfigurationException { super.print(location); out.close();/*from w w w. j ava2 s.com*/ updateStatus("Create Ressources Directory", 70); //get the dom Document fopResult = XMLUtils.parseDOM(outputFile); Element root = fopResult.getDocumentElement(); String templateFileName = Engine.TEMPLATES_PATH + "/doc/doc.html.xsl"; File htmlFile = new File(templateFileName); Source xsltSrc = new StreamSource(new FileInputStream(htmlFile), localizedDir); //create the ressources repository String ressourcesFolder = outputFolder + "/ressources"; File repository = new File(ressourcesFolder); if (!repository.exists()) { repository.mkdir(); } //export images NodeList images = fopResult.getElementsByTagName("image"); Node image; String attrImg, attrImgName; InputStream imagesIn; OutputStream imagesOut; for (int i = 0; i < images.getLength(); i++) { image = images.item(i); attrImg = image.getAttributes().getNamedItem("url").getTextContent(); attrImgName = attrImg.replaceAll("(.*)/", ""); image.getAttributes().getNamedItem("url").setTextContent(attrImgName); imagesIn = new FileInputStream(attrImg); imagesOut = new FileOutputStream(ressourcesFolder + "/" + attrImgName); org.apache.commons.io.IOUtils.copy(imagesIn, imagesOut); imagesIn.close(); imagesOut.close(); } //export css FileInputStream cssIn = new FileInputStream(Engine.TEMPLATES_PATH + "/doc/style.css"); FileOutputStream cssOut = new FileOutputStream(ressourcesFolder + "/style.css"); org.apache.commons.io.IOUtils.copy(cssIn, cssOut); cssIn.close(); cssOut.close(); updateStatus("HTML Transformation", 85); // transformation of the dom Transformer xslt = TransformerFactory.newInstance().newTransformer(xsltSrc); Element xsl = fopResult.createElement("xsl"); xslt.transform(new DOMSource(fopResult), new DOMResult(xsl)); fopResult.removeChild(root); fopResult.appendChild(xsl.getFirstChild()); //write the dom String newOutputFileName = outputFolder + "/" + projectName + ".html"; outputFile = new File(newOutputFileName); out = new FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); OutputStreamWriter output = new OutputStreamWriter(out); output.write(XMLUtils.prettyPrintDOM(fopResult)); output.close(); //remove the temp file new File(outputFileName).delete(); updateStatus("Printing finished", 100); return newOutputFileName; }
From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java
protected Document parseResultDocument(String result, String expectedRootElement) throws Exception { Document doc = Util.parse(result); Element rootElement = doc.getDocumentElement(); if (!rootElement.getNodeName().equals(expectedRootElement)) { // When there is a null value in fields, the viewable fields sequence is not enclosed by expected element // FIXME Better to find out a solution at the underlying stage doc.removeChild(rootElement); Element resultElement = doc.createElement(expectedRootElement); resultElement.appendChild(rootElement); }//from w ww . j av a 2s . co m return doc; }
From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java
private void handlerPreviewFrameset(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems, User user) throws VerticalAdminException, VerticalEngineException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("page", formItems.get("page")); int unitKey;/*from ww w. j a v a2 s. com*/ String contentTitle; if (formItems.getBoolean("sessiondata", false) == false) { // Happens when previewing an uneditable version, i.e. there is not unsaved changes and we do not need to parse submitted content data final ContentKey contentKey = new ContentKey(formItems.getInt("contentkey")); final ContentEntity content = contentDao.findByKey(contentKey); parameters.put("contentkey", contentKey.toInt()); final ContentVersionKey versionKey; final ContentVersionEntity contentVersion; if (formItems.containsKey("versionkey")) { versionKey = new ContentVersionKey(formItems.getInt("versionkey")); contentVersion = contentVersionDao.findByKey(versionKey); } else { versionKey = content.getMainVersion().getKey(); contentVersion = contentVersionDao.findByKey(versionKey); } parameters.put("versionkey", versionKey); contentTitle = contentVersion.getTitle(); unitKey = content.getCategory().getUnit().getKey(); } else { // Happens when previewing an editable or unsaved version, i.e. there is unsaved changes and we need to parse submitted content data int contentKey = getContentKey(formItems, -1); boolean formDisabled = formItems.getBoolean("formdisabled", false) || alwaysDisabled; String xmlData = contentXMLBuilder.buildXML(formItems, user, contentKey < 0, false, formDisabled); contentTitle = formItems.getString(contentXMLBuilder.getTitleFormKey(), null); Document doc = XMLTool.domparse(xmlData); Element contentElem = doc.getDocumentElement(); doc.removeChild(contentElem); Element contentsElem = XMLTool.createElement(doc, "contents"); contentsElem.appendChild(contentElem); doc.appendChild(contentsElem); // add related contents buildRelatedContentsXML(admin, user, formItems, contentsElem); xmlData = XMLTool.documentToString(doc); XMLDocument xmlDocument = XMLDocumentFactory.create(xmlData); org.jdom.Document documentAsJDom = xmlDocument.getAsJDOMDocument(); org.jdom.Element contentEl = documentAsJDom.getRootElement().getChild("content"); ContentAndVersion parsedContentAndVersion = contentParserService .parseContentAndVersionForPreview(contentEl, null, true); NoLazyInitializationEnforcerForPreview .enforceNoLazyInitialization(parsedContentAndVersion.getContent()); // Putting the parsed content and version on the session so it can be picked up at the actual preview request session.setAttribute("_preview-content-and-version", parsedContentAndVersion); unitKey = formItems.getInt("selectedunitkey", -1); int contentTypeKey = getContentTypeKey(formItems); parameters.put("contenttypekey", contentTypeKey); if (contentKey >= 0) { parameters.put("contentkey", contentKey); } parameters.put("sessiondata", "true"); } if (formItems.containsKey("pagetemplatekey")) { parameters.put("pagetemplatekey", formItems.get("pagetemplatekey")); } addCommonParameters(admin, user, request, parameters, unitKey, -1); if (contentTitle != null) { parameters.put("contenttitle", contentTitle); } if (formItems.containsKey("menuitemkey")) { parameters.put("menuitemkey", formItems.get("menuitemkey")); } if (formItems.containsKey("menukey")) { parameters.put("menukey", formItems.get("menukey")); } Document doc = XMLTool.createDocument("data"); parameters.put("user-agent", request.getHeader("user-agent")); transformXML(request, response, doc, "contenttype_preview_frameset.xsl", parameters); }
From source file:org.alfresco.web.forms.xforms.XFormsBean.java
public void handleSubmit(Node result) { final Document instanceData = this.getXformsSession().getFormInstanceData(); Element documentElement = instanceData.getDocumentElement(); if (documentElement != null) { instanceData.removeChild(documentElement); }/*from w ww .j a va 2 s .c om*/ if (result instanceof Document) { result = ((Document) result).getDocumentElement(); } documentElement = (Element) instanceData.importNode(result.cloneNode(true), true); Schema2XForms.removePrototypeNodes(documentElement); instanceData.appendChild(documentElement); instanceData.normalizeDocument(); }
From source file:org.alfresco.web.ui.wcm.component.UIFormProcessor.java
/** * @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext) *//* ww w . ja va2 s . c o m*/ @SuppressWarnings("unchecked") public void encodeBegin(final FacesContext context) throws IOException { if (!isRendered()) { return; } final ResponseWriter out = context.getResponseWriter(); final Form form = this.getForm(); final FormProcessor fp = form.getFormProcessors().get(0); final FormProcessor.Session fps = this.getFormProcessorSession(); final Document fid = this.getFormInstanceData(); final String formInstanceDataName = this.getFormInstanceDataName(); try { if (fps != null && fps.getForm().equals(form) && fps.getFormInstanceData().equals(fid) && fps.getFormInstanceDataName().equals(formInstanceDataName)) { LOGGER.debug("reusing form processor session " + fps); fp.process(this.formProcessorSession, out); } else { if (fps != null) { this.setFormProcessorSession(null); LOGGER.debug("clearing form instance data " + fid); fid.removeChild(fid.getDocumentElement()); } LOGGER.debug("creating a new session for " + fid); this.setFormProcessorSession(fp.process(fid, formInstanceDataName, form, out)); } } catch (Throwable t) { Utils.addErrorMessage(t.getMessage(), t); out.write(t.toString()); } }
From source file:org.apache.ws.security.message.SignatureTest.java
/** * This is a test for WSS-234 - /*from ww w .j a v a 2 s .c o m*/ * "When a document contains a comment as its first child element, * wss4j will not find the SOAP body." */ @org.junit.Test public void testWSS234() throws Exception { WSSecSignature builder = new WSSecSignature(); builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); LOG.info("Before Signing...."); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document signedDoc = builder.build(doc, crypto, secHeader); // Add a comment node as the first node element org.w3c.dom.Node firstChild = signedDoc.getFirstChild(); org.w3c.dom.Node newNode = signedDoc.removeChild(firstChild); org.w3c.dom.Node commentNode = signedDoc.createComment("This is a comment"); signedDoc.appendChild(commentNode); signedDoc.appendChild(newNode); if (LOG.isDebugEnabled()) { LOG.debug("After Signing...."); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); }
From source file:org.apache.ws.security.saml.ext.OpenSAMLUtil.java
/** * Convert a SAML Assertion from a XMLObject to a DOM Element * * @param xmlObject of type XMLObject/* w ww.java2 s.co m*/ * @param doc of type Document * @param signObject whether to sign the XMLObject during marshalling * @return Element * @throws MarshallingException * @throws SignatureException */ public static Element toDom(XMLObject xmlObject, Document doc, boolean signObject) throws WSSecurityException { Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); Element element = null; DocumentFragment frag = doc == null ? null : doc.createDocumentFragment(); try { if (frag != null) { while (doc.getFirstChild() != null) { frag.appendChild(doc.removeChild(doc.getFirstChild())); } } try { if (doc == null) { element = marshaller.marshall(xmlObject); } else { element = marshaller.marshall(xmlObject, doc); } } catch (MarshallingException ex) { throw new WSSecurityException("Error marshalling a SAML assertion", ex); } if (signObject) { signXMLObject(xmlObject); } } finally { if (frag != null) { while (doc.getFirstChild() != null) { doc.removeChild(doc.getFirstChild()); } doc.appendChild(frag); } } return element; }
From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java
/** * updates the XMl with hashcode for the files *//*from w w w.ja v a 2 s .c o m*/ protected BudgetSubAwards updateXML(byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean, Budget budget) throws Exception { javax.xml.parsers.DocumentBuilderFactory domParserFactory = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents); org.w3c.dom.Document document = domParser.parse(byteArrayInputStream); byteArrayInputStream.close(); String namespace = null; String formName = null; if (document != null) { Node node; Element element = document.getDocumentElement(); NamedNodeMap map = element.getAttributes(); String namespaceHolder = element.getNodeName().substring(0, element.getNodeName().indexOf(':')); node = map.getNamedItem("xmlns:" + namespaceHolder); namespace = node.getNodeValue(); FormMappingInfo formMappingInfo = formMappingService.getFormInfo(namespace); formName = formMappingInfo.getFormName(); budgetSubAwardBean.setNamespace(namespace); budgetSubAwardBean.setFormName(formName); } String xpathEmptyNodes = "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']"; String xpathOtherPers = "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]"; removeAllEmptyNodes(document, xpathEmptyNodes, 0); removeAllEmptyNodes(document, xpathOtherPers, 1); removeAllEmptyNodes(document, xpathEmptyNodes, 0); changeDataTypeForNumberOfOtherPersons(document); List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms(); NodeList budgetYearList = XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']"); for (int i = 0; i < budgetYearList.getLength(); i++) { Node bgtYearNode = budgetYearList.item(i); String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod")); if (fedNonFedSubAwardForms.contains(namespace)) { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName()); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } else { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } } Node oldroot = document.removeChild(document.getDocumentElement()); Node newroot = document.appendChild(document.createElement("Forms")); newroot.appendChild(oldroot); org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName"); org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation"); org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType"); org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue"); org.w3c.dom.Node fileNode, hashNode, mimeTypeNode; org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap; String fileName; byte fileBytes[]; String contentId; List attachmentList = new ArrayList(); for (int index = 0; index < lstFileName.getLength(); index++) { fileNode = lstFileName.item(index); Node fileNameNode = fileNode.getFirstChild(); fileName = fileNameNode.getNodeValue(); fileBytes = (byte[]) fileMap.get(fileName); if (fileBytes == null) { throw new RuntimeException("FileName mismatch in XML and PDF extracted file"); } String hashVal = grantApplicationHashService.computeAttachmentHash(fileBytes); hashNode = lstHashValue.item(index); hashNodeMap = hashNode.getAttributes(); Node temp = document.createTextNode(hashVal); hashNode.appendChild(temp); hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm"); hashNode.setNodeValue(InfastructureConstants.HASH_ALGORITHM); fileNode = lstFileLocation.item(index); fileNodeMap = fileNode.getAttributes(); fileNode = fileNodeMap.getNamedItem("att:href"); contentId = fileNode.getNodeValue(); String encodedContentId = cleanContentId(contentId); fileNode.setNodeValue(encodedContentId); mimeTypeNode = lstMimeType.item(0); String contentType = mimeTypeNode.getFirstChild().getNodeValue(); BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment(); budgetSubAwardAttachmentBean.setData(fileBytes); budgetSubAwardAttachmentBean.setName(encodedContentId); budgetSubAwardAttachmentBean.setType(contentType); budgetSubAwardAttachmentBean.setBudgetSubAward(budgetSubAwardBean); attachmentList.add(budgetSubAwardAttachmentBean); } budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList); javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance() .newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(bos); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document); transformer.transform(source, result); budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray())); bos.close(); return budgetSubAwardBean; }
From source file:org.kuali.kra.proposaldevelopment.budget.service.impl.BudgetSubAwardServiceImpl.java
/** * updates the XMl with hashcode for the files */// ww w . j ava 2 s . c om protected BudgetSubAwards updateXML(byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean) throws Exception { javax.xml.parsers.DocumentBuilderFactory domParserFactory = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents); org.w3c.dom.Document document = domParser.parse(byteArrayInputStream); byteArrayInputStream.close(); String namespace = null; if (document != null) { Node node; String formName; Element element = document.getDocumentElement(); NamedNodeMap map = element.getAttributes(); String namespaceHolder = element.getNodeName().substring(0, element.getNodeName().indexOf(':')); node = map.getNamedItem("xmlns:" + namespaceHolder); namespace = node.getNodeValue(); FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace); formName = formMappingInfo.getFormName(); budgetSubAwardBean.setNamespace(namespace); budgetSubAwardBean.setFormName(formName); } String xpathEmptyNodes = "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']"; String xpathOtherPers = "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]"; removeAllEmptyNodes(document, xpathEmptyNodes, 0); removeAllEmptyNodes(document, xpathOtherPers, 1); removeAllEmptyNodes(document, xpathEmptyNodes, 0); changeDataTypeForNumberOfOtherPersons(document); List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms(); NodeList budgetYearList = XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']"); for (int i = 0; i < budgetYearList.getLength(); i++) { Node bgtYearNode = budgetYearList.item(i); String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod")); if (fedNonFedSubAwardForms.contains(namespace)) { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName()); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } else { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } } Node oldroot = document.removeChild(document.getDocumentElement()); Node newroot = document.appendChild(document.createElement("Forms")); newroot.appendChild(oldroot); org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName"); org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation"); org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType"); org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue"); if ((lstFileName.getLength() != lstFileLocation.getLength()) || (lstFileLocation.getLength() != lstHashValue.getLength())) { // throw new RuntimeException("Tag occurances mismatch in XML File"); } org.w3c.dom.Node fileNode, hashNode, mimeTypeNode; org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap; String fileName; byte fileBytes[]; String contentId; List attachmentList = new ArrayList(); for (int index = 0; index < lstFileName.getLength(); index++) { fileNode = lstFileName.item(index); Node fileNameNode = fileNode.getFirstChild(); fileName = fileNameNode.getNodeValue(); fileBytes = (byte[]) fileMap.get(fileName); if (fileBytes == null) { throw new RuntimeException("FileName mismatch in XML and PDF extracted file"); } String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes); hashNode = lstHashValue.item(index); hashNodeMap = hashNode.getAttributes(); Node temp = document.createTextNode(hashVal); hashNode.appendChild(temp); hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm"); hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM); fileNode = lstFileLocation.item(index); fileNodeMap = fileNode.getAttributes(); fileNode = fileNodeMap.getNamedItem("att:href"); contentId = fileNode.getNodeValue(); String encodedContentId = cleanContentId(contentId); fileNode.setNodeValue(encodedContentId); mimeTypeNode = lstMimeType.item(0); String contentType = mimeTypeNode.getFirstChild().getNodeValue(); BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment(); budgetSubAwardAttachmentBean.setAttachment(fileBytes); budgetSubAwardAttachmentBean.setContentId(encodedContentId); budgetSubAwardAttachmentBean.setContentType(contentType); budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId()); budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber()); attachmentList.add(budgetSubAwardAttachmentBean); } budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList); javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance() .newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(bos); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document); transformer.transform(source, result); budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray())); bos.close(); return budgetSubAwardBean; }
From source file:org.openengsb.openengsbplugin.base.ConfiguredMojo.java
protected void tryExtractLicenseHeader(Document doc) { Node firstNode = doc.getChildNodes().item(0); if (firstNode.getNodeType() == Node.COMMENT_NODE) { LOG.trace(String.format("found license header with content:\n%s", firstNode.getNodeValue())); licenseHeaderComment = doc.removeChild(firstNode); }//from w w w. j a va 2s . co m }