List of usage examples for org.w3c.dom Element appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:Main.java
private static Element copyNode(Document destDocument, Element dest, Element src) { NamedNodeMap namedNodeMap = src.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Attr attr = (Attr) namedNodeMap.item(i); dest.setAttribute(attr.getName(), attr.getValue()); }/*from w ww . j a va 2s . co m*/ NodeList childNodeList = src.getChildNodes(); for (int i = 0; i < childNodeList.getLength(); i++) { Node child = childNodeList.item(i); if (child.getNodeType() == Node.TEXT_NODE) { Text text = destDocument.createTextNode(child.getTextContent()); dest.appendChild(text); } else if (child.getNodeType() == Node.ELEMENT_NODE) { Element element = destDocument.createElement(((Element) child).getTagName()); element = copyNode(destDocument, element, (Element) child); dest.appendChild(element); } } return dest; }
From source file:Main.java
/** * Add the breadcrumbs element to the document. This contains the * information for navigating back up through the application hierarchy. * * This creates a breadcrumbs element with child path elements in order * (each with a name and path attribute). The breadcrumbs element itself * also has a path attribute that specifies the root path. * * @param document/*w w w . java 2 s . co m*/ * @param pathPrefix * @param relativePath */ public static void addBreadcrumbs(Document document, String pathPrefix, String relativePath) { if (document != null) { Element root = document.getDocumentElement(); if (root != null) { // Create the breadcrumbs element with the associated path being // the root path for the set of paths. Element element = document.createElement("breadcrumbs"); element.setAttribute("path", pathPrefix); StringBuilder path = new StringBuilder(pathPrefix); if (!"".equals(pathPrefix) && !pathPrefix.endsWith("/")) { path.append("/"); } boolean first = true; for (String term : relativePath.split("/")) { if (!"".equals(term) && !".".equals(term)) { if (!first) { path.append("/"); } path.append(term); Element pathElement = document.createElement("crumb"); pathElement.setAttribute("name", term); pathElement.setAttribute("path", path.toString()); element.appendChild(pathElement); first = false; } } root.appendChild(element); } } }
From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV4.java
public static void buildSubtree(final Element parent, final JsonNode node) { final String v4AnnotationPrefix = "@"; final Iterator<String> fieldNameItor = node.fieldNames(); final Iterator<JsonNode> nodeItor = node.elements(); while (nodeItor.hasNext()) { final JsonNode child = nodeItor.next(); final String name = fieldNameItor.hasNext() ? fieldNameItor.next() : ""; // no name? array item if (name.isEmpty()) { final Element element = parent.getOwnerDocument().createElementNS(ODataConstants.NS_DATASERVICES, ODataConstants.PREFIX_DATASERVICES + ODataConstants.ELEM_ELEMENT); parent.appendChild(element); if (child.isValueNode()) { if (child.isNull()) { element.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_NULL, Boolean.toString(true)); } else { element.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); }//from ww w .j a v a 2 s . co m } if (child.isContainerNode()) { buildSubtree(element, child); } } else if (!name.contains("@") && !ODataConstants.JSON_TYPE.equals(name)) { final Element property = parent.getOwnerDocument().createElementNS(ODataConstants.NS_DATASERVICES, ODataConstants.PREFIX_DATASERVICES + name); parent.appendChild(property); boolean typeSet = false; if (node.hasNonNull(name + "@" + ODataConstants.JSON_TYPE)) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, node.get(name + "@" + ODataConstants.JSON_TYPE).textValue()); typeSet = true; } if (child.isNull()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_NULL, Boolean.toString(true)); } else if (child.isValueNode()) { if (!typeSet) { if (child.isInt()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int32.toString()); } if (child.isLong()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Int64.toString()); } if (child.isBigDecimal()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Decimal.toString()); } if (child.isDouble()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Double.toString()); } if (child.isBoolean()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.Boolean.toString()); } if (child.isTextual()) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, EdmSimpleType.String.toString()); } } property.appendChild(parent.getOwnerDocument().createTextNode(child.asText())); } else if (child.isContainerNode()) { if (!typeSet && child.hasNonNull(v4AnnotationPrefix + ODataConstants.JSON_TYPE)) { property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, child.get(v4AnnotationPrefix + ODataConstants.JSON_TYPE).textValue()); } final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE); if (StringUtils.isNotBlank(type) && EdmSimpleType.isGeospatial(type)) { if (EdmSimpleType.Geography.toString().equals(type) || EdmSimpleType.Geometry.toString().equals(type)) { final String geoType = child.get(ODataConstants.ATTR_TYPE).textValue(); property.setAttributeNS(ODataConstants.NS_METADATA, ODataConstants.ATTR_M_TYPE, geoType.startsWith("Geo") ? EdmSimpleType.namespace() + "." + geoType : type + geoType); } if (child.has(ODataConstants.JSON_COORDINATES) || child.has(ODataConstants.JSON_GEOMETRIES)) { GeospatialJSONHandler.deserialize(child, property, property.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { buildSubtree(property, child); } } } } }
From source file:main.java.vasolsim.common.file.ExamBuilder.java
/** * writes an editable, unlocked exam to a file * * @param exam the exam to be written * @param examFile the target file//from w w w. j a va 2 s. c o m * @param overwrite if an existing file can be overwritten * * @return if the file write was successful * * @throws VaSolSimException */ public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite) throws VaSolSimException { /* * check the file creation status and handle it */ //if it exists if (examFile.isFile()) { //can't overwrite if (!overwrite) { throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } //can overwrite, clear the existing file else { PrintWriter printWriter; try { printWriter = new PrintWriter(examFile); } catch (FileNotFoundException e) { throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } //no file, create one else { if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { if (!examFile.createNewFile()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } /* * initialize the document */ Document examDoc; Transformer examTransformer; try { examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); examTransformer = TransformerFactory.newInstance().newTransformer(); examTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); examTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); examTransformer.setOutputProperty(INDENTATION_KEY, "4"); } catch (ParserConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } catch (TransformerConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } /* * build exam info */ Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME); examDoc.appendChild(root); Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME); root.appendChild(info); //exam info GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc); GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc); GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc); GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc); //start security xml section Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME); root.appendChild(security); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME, Boolean.toString(exam.isReportingStats()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME, Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsDestinationEmail(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME, exam.getStatsSenderSMTPAddress(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME, Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc); ArrayList<QuestionSet> questionSets = exam.getQuestionSets(); if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) { for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) { QuestionSet qSet = questionSets.get(setsIndex); Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME); root.appendChild(qSetElement); GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME, (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME, qSet.getResourceType().toString(), qSetElement, examDoc); if (qSet.getResources() != null) { for (BufferedImage img : qSet.getResources()) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); out.flush(); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME, convertBytesToHexString(out.toByteArray()), qSetElement, examDoc); } catch (IOException e) { throw new VaSolSimException("Error: cannot write images to byte array for transport"); } } } for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) { Question question = qSet.getQuestions().get(setIndex); Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME); qSetElement.appendChild(qElement); GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME, (question.getName() == null || question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME, Boolean.toString(question.getScrambleAnswers()), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME, Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc); for (AnswerChoice answer : question.getCorrectAnswerChoices()) { GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(), qElement, examDoc); } for (int questionIndex = 0; questionIndex < question.getAnswerChoices() .size(); questionIndex++) { AnswerChoice ac = question.getAnswerChoices().get(questionIndex); Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME); qElement.appendChild(acElement); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME, Integer.toString(questionIndex + 1), acElement, examDoc); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME, ac.getVisibleChoiceID(), acElement, examDoc); GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement, examDoc); } } } } return true; }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from ww w.j a v a 2 s. c om DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_MOBILE, "Response"); root.appendChild(response); //Add culture to to response Element culture = xmlDoc.createElement("Culture"); culture.appendChild(xmlDoc.createTextNode("en:en")); response.appendChild(culture); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EMailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); response.appendChild(user); //Action Element action = xmlDoc.createElement("Action"); Element settings = xmlDoc.createElement("Settings"); Element server = xmlDoc.createElement("Server"); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("MobileSync")); server.appendChild(type); Element url = xmlDoc.createElement("Url"); url.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(url); Element name = xmlDoc.createElement("Name"); name.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(name); settings.appendChild(server); action.appendChild(settings); response.appendChild(action); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); //manually generate xmlns for Autodiscover and Response element, this works //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns // StringBuilder str = new StringBuilder(); // str.append("<?xml version=\"1.0\"?>\n"); // str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\""); // str.append(" xmlns:xsi=\"").append(XSI_NS).append("\""); // str.append(" xmlns=\"").append(NS).append("\">\n"); // int respIndex = xml.indexOf("<Response>"); // str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">"); // str.append(xml.substring(respIndex + "<Response>".length(), xml.length())); // return str.toString(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:com.connexta.arbitro.utils.PolicyUtils.java
/** * This creates XML representation of condition element using ConditionElementDT0 object * * @param conditionElementDT0 ConditionElementDT0 * @param doc Document// www.ja va 2 s. c om * @return DOM element * @throws PolicyBuilderException throws */ public static Element createConditionElement(ConditionElementDT0 conditionElementDT0, Document doc) throws PolicyBuilderException { Element conditionElement = doc.createElement(PolicyConstants.CONDITION_ELEMENT); if (conditionElementDT0.getApplyElement() != null) { conditionElement.appendChild(createApplyElement(conditionElementDT0.getApplyElement(), doc)); } else if (conditionElementDT0.getAttributeValueElementDTO() != null) { Element attributeValueElement = createAttributeValueElement( conditionElementDT0.getAttributeValueElementDTO(), doc); conditionElement.appendChild(attributeValueElement); } else if (conditionElementDT0.getAttributeDesignator() != null) { AttributeDesignatorDTO attributeDesignatorDTO = conditionElementDT0.getAttributeDesignator(); conditionElement.appendChild(createAttributeDesignatorElement(attributeDesignatorDTO, doc)); } else if (conditionElementDT0.getFunctionFunctionId() != null) { Element functionElement = doc.createElement(PolicyConstants.FUNCTION_ELEMENT); functionElement.setAttribute(PolicyConstants.FUNCTION_ID, conditionElementDT0.getFunctionFunctionId()); conditionElement.appendChild(functionElement); } else if (conditionElementDT0.getVariableId() != null) { Element variableReferenceElement = doc.createElement(PolicyConstants.VARIABLE_REFERENCE); variableReferenceElement.setAttribute(PolicyConstants.VARIABLE_ID, conditionElementDT0.getVariableId()); conditionElement.appendChild(variableReferenceElement); } return conditionElement; }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct) throws Exception { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(acct); String cn = server.getCn();/*from ww w . ja v a 2 s . c o m*/ String name = server.getName(); String acctId = acct.getId(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response"); root.appendChild(response); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EmailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); Element depId = xmlDoc.createElement("DeploymentId"); depId.appendChild(xmlDoc.createTextNode(acctId)); user.appendChild(depId); response.appendChild(user); //Action Element account = xmlDoc.createElement("Account"); Element acctType = xmlDoc.createElement("AccountType"); acctType.appendChild(xmlDoc.createTextNode("email")); account.appendChild(acctType); response.appendChild(account); Element action = xmlDoc.createElement("Action"); action.appendChild(xmlDoc.createTextNode("settings")); account.appendChild(action); Element protocol = xmlDoc.createElement("Protocol"); account.appendChild(protocol); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("EXCH")); protocol.appendChild(type); Element ews = xmlDoc.createElement("EwsUrl"); protocol.appendChild(ews); ews.appendChild(xmlDoc.createTextNode(serviceUrl)); Element as = xmlDoc.createElement("ASUrl"); protocol.appendChild(as); as.appendChild(xmlDoc.createTextNode(serviceUrl)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java
/** * Creates the state element.//from w ww . j a v a 2 s. c o m * * @param parent the parent element to use. * @return the state element. */ public static Element createStateElement(Element parent) { Element state = DOMUtil.findFirstChildNS(parent, NamespaceConstants.BETTERFORM_NS, UIElementState.STATE_ELEMENT); if (state != null) { return state; } Document document = parent.getOwnerDocument(); state = document.createElementNS(NamespaceConstants.BETTERFORM_NS, NamespaceConstants.BETTERFORM_PREFIX + ":" + UIElementState.STATE_ELEMENT); parent.appendChild(state); return state; }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * This method sets a text node to the given DOM element. * * @param document root document/*from ww w . j a va2s.c o m*/ * @param parentDom parent node * @param text text to be added */ public static void setTextNode(final Document document, final Element parentDom, final String text) { final Text textNode = document.createTextNode(text); parentDom.appendChild(textNode); }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * Creates a DOM Document object of the specified type with its document element. * * @param namespaceURI the namespace URI of the document element to create or null * @param qualifiedName the qualified name of the document element to be created or null * @param element document {@code Element} * @return {@code Document}/* w w w .ja v a2 s . c om*/ */ public static Document createDocument(final String namespaceURI, final String qualifiedName, final Element element) { ensureDocumentBuilder(); DOMImplementation domImpl; try { domImpl = dbFactory.newDocumentBuilder().getDOMImplementation(); } catch (ParserConfigurationException e) { throw new DSSException(e); } final Document newDocument = domImpl.createDocument(namespaceURI, qualifiedName, null); final Element newElement = newDocument.getDocumentElement(); newDocument.adoptNode(element); newElement.appendChild(element); return newDocument; }