List of usage examples for org.w3c.dom Element setTextContent
public void setTextContent(String textContent) throws DOMException;
From source file:vmTools.java
public String createVmXml(String jsonString, String server) { String ret = ""; ArrayList<String> ide = new ArrayList<String>(); ide.add("hda"); ide.add("hdb"); ide.add("hdc"); ide.add("hdd"); ide.add("hde"); ide.add("hdf"); ArrayList<String> scsi = new ArrayList<String>(); scsi.add("sda"); scsi.add("sdb"); scsi.add("sdc"); scsi.add("sdd"); scsi.add("sde"); scsi.add("sdf"); try {/*from ww w .j a v a 2 s. c om*/ JSONObject jo = new JSONObject(jsonString); // A JSONArray is an ordered sequence of values. Its external form is a // string wrapped in square brackets with commas between the values. // Get the JSONObject value associated with the search result key. String varName = jo.get("name").toString(); String domainType = jo.get("domain_type").toString(); String varMem = jo.get("memory").toString(); String varCpu = jo.get("vcpu").toString(); String varArch = jo.get("arch").toString(); // Get the JSONArray value associated with the Result key JSONArray diskArray = jo.getJSONArray("diskList"); JSONArray nicArray = jo.getJSONArray("nicList"); // Cration d'un nouveau DOM DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = fabrique.newDocumentBuilder(); Document document = constructeur.newDocument(); // Proprits du DOM document.setXmlStandalone(true); // Cration de l'arborescence du DOM Element domain = document.createElement("domain"); document.appendChild(domain); domain.setAttribute("type", domainType); //racine.appendChild(document.createComment("Commentaire sous la racine")); Element name = document.createElement("name"); domain.appendChild(name); name.setTextContent(varName); UUID varuid = UUID.randomUUID(); Element uid = document.createElement("uuid"); domain.appendChild(uid); uid.setTextContent(varuid.toString()); Element memory = document.createElement("memory"); domain.appendChild(memory); memory.setTextContent(varMem); Element currentMemory = document.createElement("currentMemory"); domain.appendChild(currentMemory); currentMemory.setTextContent(varMem); Element vcpu = document.createElement("vcpu"); domain.appendChild(vcpu); vcpu.setTextContent(varCpu); //<os> Element os = document.createElement("os"); domain.appendChild(os); Element type = document.createElement("type"); os.appendChild(type); type.setAttribute("arch", varArch); type.setAttribute("machine", jo.get("machine").toString()); type.setTextContent(jo.get("machine_type").toString()); JSONArray bootArray = jo.getJSONArray("bootList"); int count = bootArray.length(); for (int i = 0; i < count; i++) { JSONObject bootDev = bootArray.getJSONObject(i); Element boot = document.createElement("boot"); os.appendChild(boot); boot.setAttribute("dev", bootDev.get("dev").toString()); } Element bootmenu = document.createElement("bootmenu"); os.appendChild(bootmenu); bootmenu.setAttribute("enable", jo.get("bootMenu").toString()); //</os> //<features> Element features = document.createElement("features"); domain.appendChild(features); JSONArray featureArray = jo.getJSONArray("features"); int featureCount = featureArray.length(); for (int i = 0; i < featureCount; i++) { JSONObject jasonFeature = featureArray.getJSONObject(i); String newFeature = jasonFeature.get("opt").toString(); Element elFeature = document.createElement(newFeature); features.appendChild(elFeature); } //</features> Element clock = document.createElement("clock"); domain.appendChild(clock); // Clock settings clock.setAttribute("offset", jo.get("clock_offset").toString()); JSONArray timerArray = jo.getJSONArray("timers"); for (int i = 0; i < timerArray.length(); i++) { JSONObject jsonTimer = timerArray.getJSONObject(i); Element elTimer = document.createElement("timer"); clock.appendChild(elTimer); elTimer.setAttribute("name", jsonTimer.get("name").toString()); elTimer.setAttribute("present", jsonTimer.get("present").toString()); elTimer.setAttribute("tickpolicy", jsonTimer.get("tickpolicy").toString()); } Element poweroff = document.createElement("on_poweroff"); domain.appendChild(poweroff); poweroff.setTextContent(jo.get("on_poweroff").toString()); Element reboot = document.createElement("on_reboot"); domain.appendChild(reboot); reboot.setTextContent(jo.get("on_reboot").toString()); Element crash = document.createElement("on_crash"); domain.appendChild(crash); crash.setTextContent(jo.get("on_crash").toString()); //<devices> Element devices = document.createElement("devices"); domain.appendChild(devices); String varEmulator = jo.get("emulator").toString(); Element emulator = document.createElement("emulator"); devices.appendChild(emulator); emulator.setTextContent(varEmulator); int resultCount = diskArray.length(); for (int i = 0; i < resultCount; i++) { Element disk = document.createElement("disk"); devices.appendChild(disk); JSONObject newDisk = diskArray.getJSONObject(i); String diskType = newDisk.get("type").toString(); Element driver = document.createElement("driver"); Element target = document.createElement("target"); disk.appendChild(driver); disk.appendChild(target); if (diskType.equals("file")) { Element source = document.createElement("source"); disk.appendChild(source); source.setAttribute("file", newDisk.get("source").toString()); driver.setAttribute("cache", "none"); } disk.setAttribute("type", diskType); disk.setAttribute("device", newDisk.get("device").toString()); driver.setAttribute("type", newDisk.get("format").toString()); driver.setAttribute("name", newDisk.get("driver").toString()); //String diskDev = ide.get(0); //ide.remove(0); String diskDev = newDisk.get("bus").toString(); String diskBus = ""; if (diskDev.indexOf("hd") > -1) { diskBus = "ide"; } else if (diskDev.indexOf("sd") > -1) { diskBus = "scsi"; } else if (diskDev.indexOf("vd") > -1) { diskBus = "virtio"; } target.setAttribute("dev", diskDev); target.setAttribute("bus", diskBus); } resultCount = nicArray.length(); for (int i = 0; i < resultCount; i++) { JSONObject newNic = nicArray.getJSONObject(i); String macaddr = newNic.get("mac").toString().toLowerCase(); if (macaddr.indexOf("automatic") > -1) { Random rand = new Random(); macaddr = "52:54:00"; String hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; } Element netIf = document.createElement("interface"); devices.appendChild(netIf); Element netSource = document.createElement("source"); Element netDevice = document.createElement("model"); Element netMac = document.createElement("mac"); netIf.appendChild(netSource); netIf.appendChild(netDevice); netIf.appendChild(netMac); netIf.setAttribute("type", "network"); netSource.setAttribute("network", newNic.get("bridge").toString()); String portgroup = newNic.get("portgroup").toString(); if (!portgroup.equals("")) { netSource.setAttribute("portgroup", portgroup); } netDevice.setAttribute("type", newNic.get("device").toString()); netMac.setAttribute("address", macaddr); } JSONArray serialArray = jo.getJSONArray("serial"); count = serialArray.length(); for (int i = 0; i < count; i++) { JSONObject serialDev = serialArray.getJSONObject(i); Element serial = document.createElement("serial"); devices.appendChild(serial); serial.setAttribute("type", serialDev.get("type").toString()); Element target = document.createElement("target"); serial.appendChild(target); target.setAttribute("port", serialDev.get("port").toString()); } JSONArray consoleArray = jo.getJSONArray("console"); count = consoleArray.length(); for (int i = 0; i < count; i++) { JSONObject consoleDev = consoleArray.getJSONObject(i); Element console = document.createElement("console"); devices.appendChild(console); console.setAttribute("type", "pty"); Element target = document.createElement("target"); console.appendChild(target); target.setAttribute("port", consoleDev.get("port").toString()); target.setAttribute("type", consoleDev.get("type").toString()); } JSONArray inputArray = jo.getJSONArray("input"); count = inputArray.length(); for (int i = 0; i < count; i++) { JSONObject inputDev = inputArray.getJSONObject(i); Element input = document.createElement("input"); devices.appendChild(input); input.setAttribute("type", inputDev.get("type").toString()); input.setAttribute("bus", inputDev.get("bus").toString()); } JSONArray graphicsArray = jo.getJSONArray("graphics"); count = graphicsArray.length(); for (int i = 0; i < count; i++) { JSONObject graphicsDev = graphicsArray.getJSONObject(i); Element graphics = document.createElement("graphics"); devices.appendChild(graphics); graphics.setAttribute("type", graphicsDev.get("type").toString()); graphics.setAttribute("port", graphicsDev.get("port").toString()); graphics.setAttribute("autoport", graphicsDev.get("autoport").toString()); graphics.setAttribute("listen", graphicsDev.get("listen").toString()); graphics.setAttribute("keymap", graphicsDev.get("keymap").toString()); } JSONArray soundArray = jo.getJSONArray("sound"); count = soundArray.length(); for (int i = 0; i < count; i++) { JSONObject soundDev = soundArray.getJSONObject(i); Element sound = document.createElement("sound"); devices.appendChild(sound); sound.setAttribute("model", soundDev.get("model").toString()); } //sound.setAttribute("model", "ac97"); JSONArray videoArray = jo.getJSONArray("video"); count = videoArray.length(); for (int i = 0; i < count; i++) { JSONObject videoDev = videoArray.getJSONObject(i); Element video = document.createElement("video"); devices.appendChild(video); Element model = document.createElement("model"); video.appendChild(model); model.setAttribute("model", videoDev.get("type").toString()); model.setAttribute("model", videoDev.get("vram").toString()); model.setAttribute("model", videoDev.get("heads").toString()); } //write the content into xml file this.makeRelativeDirs("/" + server + "/vm/configs/" + varName); String pathToXml = RuntimeAccess.getInstance().getSession().getServletContext() .getRealPath("resources/data/" + server + "/vm/configs/" + varName + "/" + varName + ".xml"); File xmlOutput = new File(pathToXml); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(xmlOutput); transformer.transform(source, result); StringWriter stw = new StringWriter(); transformer.transform(source, new StreamResult(stw)); ret = stw.toString(); } catch (Exception e) { log(ERROR, "create xml file has failed", e); return e.toString(); } return ret; }
From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java
/** * This method takes the SOAP request that come from the WSP and removes * the elements that need to be removed per the SAML Profiles spec. * /* ww w .j a v a 2 s . com*/ * @param samlSession * @param authnState * @return true, if successful */ private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) { this.logger.debug("Step 3 of 5: Process SOAP Request"); try { String expression = "/S:Envelope/S:Header/paos:Request"; Document dom = authnState.getSoapRequestDom(); Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); if (node != null) { // Save the response consumer URL to samlSession String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL") .getTextContent(); logger.debug("Loaded response consumer URL {}", responseConsumerURL); authnState.setResponseConsumerURL(responseConsumerURL); // Save the PAOS MessageID, if present Node paosMessageID = node.getAttributes().getNamedItem("messageID"); if (paosMessageID != null) authnState.setPaosMessageID(paosMessageID.getTextContent()); else authnState.setPaosMessageID(null); // This removes the paos:Request node node.getParentNode().removeChild(node); // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response expression = "/S:Envelope/S:Header/ecp:RelayState"; node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); if (node != null) { Element relayStateElement = (Element) node; authnState.setRelayStateElement(relayStateElement); node.getParentNode().removeChild(node); } // On to the ecp:Request for removal expression = "/S:Envelope/S:Header/ecp:Request"; node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); node.getParentNode().removeChild(node); // Now add some namespace bindings to the SOAP Header expression = "/S:Envelope/S:Header"; Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE); // Add new elements to S:Header Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework"); newElement.setAttribute("version", "2.0"); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender"); newElement.setAttribute("providerID", samlSession.getPortalEntityID()); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID"); String messageID = generateMessageID(); newElement.setTextContent(messageID); soapHeader.appendChild(newElement); newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action"); newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest"); soapHeader.appendChild(newElement); // This is the wsse:Security element Element securityElement = dom.createElementNS( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:Security"); securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1"); Element createdElement = dom.createElement("wsu:Created"); // The examples use Zulu time zone, not local TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); sdf.setTimeZone(zuluTimeZone); createdElement.setTextContent(sdf.format(new Date())); newElement = dom.createElementNS( "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "wsu:Timestamp"); newElement.appendChild(createdElement); securityElement.appendChild(newElement); // Finally, insert the original SAML assertion Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(), true); securityElement.appendChild(samlAssertionNode); soapHeader.appendChild(securityElement); // Store the modified SOAP Request in the SAML Session String modifiedSOAPRequest = writeDomToString(dom); authnState.setModifiedSOAPRequest(modifiedSOAPRequest); logger.debug("Completed processing of SOAP request"); return true; } logger.debug("Failed to process SOAP request using expression {}", expression); } catch (XPathExpressionException ex) { logger.error("Programming error. Invalid XPath expression.", ex); throw new DelegatedAuthenticationRuntimeException("Programming error. Invalid XPath expression.", ex); } return false; }
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToForms.java
/** * Adds a DOM node for the implicit file content upload field, in case the form is content * enabled. If the instance refers to a live repository object, the content info is fetched. * /*from w w w. ja v a2 s . c om*/ * @param formType * @param formInstance * @param formElement * @param alfrescoId * the full node id */ private void appendFieldForContent(AlfrescoTransaction transaction, FormType formType, Document formInstance, Element formElement, String alfrescoId) { if (isContentEnabled(formType)) { Element nodeContentElt = formInstance.createElement(MsgId.INT_INSTANCE_SIDE_NODE_CONTENT.getText()); nodeContentElt.setAttribute("file", ""); nodeContentElt.setAttribute("type", ""); if (alfrescoId != null) { String contentInfo = controller.getNodeContentInfo(transaction, alfrescoId); nodeContentElt.setTextContent(contentInfo); } formElement.appendChild(nodeContentElt); if (loggertrace.isTraceEnabled()) { logger.debug(" appended content field '" + nodeContentElt.getNodeName() + "'"); } } }
From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java
public Element toXml(Document document) throws EngineException { Element element = document.createElement(getDatabaseType().toLowerCase()); element.setAttribute("classname", getClass().getName()); if (exportOptions.contains(ExportOption.bIncludeVersion)) { element.setAttribute("version", com.twinsoft.convertigo.beans.Version.version); }/*from ww w.ja v a2 s . c o m*/ // Storing the database object priority element.setAttribute("priority", new Long(priority).toString()); int len; PropertyDescriptor[] propertyDescriptors; PropertyDescriptor propertyDescriptor; Element propertyElement; try { BeanInfo bi = CachedIntrospector.getBeanInfo(getClass()); propertyDescriptors = bi.getPropertyDescriptors(); len = propertyDescriptors.length; if (exportOptions.contains(ExportOption.bIncludeDisplayName)) { element.setAttribute("displayName", bi.getBeanDescriptor().getDisplayName()); } } catch (IntrospectionException e) { throw new EngineException("Couldn't introspect the bean \"" + getName() + "\"", e); } for (int i = 0; i < len; i++) { propertyDescriptor = propertyDescriptors[i]; String name = propertyDescriptor.getName(); String displayName = propertyDescriptor.getDisplayName(); String shortDescription = propertyDescriptor.getShortDescription(); Method getter = propertyDescriptor.getReadMethod(); // Only analyze read propertyDescriptors. if (getter == null) { continue; } if (checkBlackListParentClass(propertyDescriptor)) { continue; } try { // Storing the database object bean properties Object uncompiledValue = getCompilablePropertySourceValue(name); Object compiledValue = null; Object cypheredValue = null; Object value = getter.invoke(this); if (uncompiledValue != null) { compiledValue = value; value = uncompiledValue; } // Only write non-null values if (value == null) { Engine.logBeans.warn("Attempting to store null property (\"" + name + "\"); skipping..."); continue; } propertyElement = document.createElement("property"); propertyElement.setAttribute("name", name); // Encrypts value if needed //if (isCipheredProperty(name) && !this.exportOptions.contains(ExportOption.bIncludeDisplayName)) { if (isCipheredProperty(name) && (this.exportOptions.contains(ExportOption.bHidePassword) || !this.exportOptions.contains(ExportOption.bIncludeDisplayName))) { cypheredValue = encryptPropertyValue(value); if (!value.equals(cypheredValue)) { value = cypheredValue; propertyElement.setAttribute("ciphered", "true"); } } // Stores the value Node node = null; if (exportOptions.contains(ExportOption.bIncludeCompiledValue)) { node = XMLUtils.writeObjectToXml(document, value, compiledValue); } else { node = XMLUtils.writeObjectToXml(document, value); } propertyElement.appendChild(node); // Add visibility for logs if (!isTraceableProperty(name)) { propertyElement.setAttribute("traceable", "false"); } if (exportOptions.contains(ExportOption.bIncludeBlackListedElements)) { Object propertyDescriptorBlackListValue = propertyDescriptor .getValue(MySimpleBeanInfo.BLACK_LIST_NAME); if (propertyDescriptorBlackListValue != null && (Boolean) propertyDescriptorBlackListValue) { propertyElement.setAttribute("blackListed", "blackListed"); } } if (exportOptions.contains(ExportOption.bIncludeDisplayName)) { propertyElement.setAttribute("displayName", displayName); propertyElement.setAttribute("isHidden", Boolean.toString(propertyDescriptor.isHidden())); propertyElement.setAttribute("isMasked", isMaskedProperty(Visibility.Platform, name) ? "true" : "false"); propertyElement.setAttribute("isExpert", Boolean.toString(propertyDescriptor.isExpert())); } if (exportOptions.contains(ExportOption.bIncludeShortDescription)) { propertyElement.setAttribute("shortDescription", shortDescription); } if (exportOptions.contains(ExportOption.bIncludeEditorClass)) { Class<?> pec = propertyDescriptor.getPropertyEditorClass(); String message = ""; if (pec != null) { message = propertyDescriptor.getPropertyEditorClass().toString().replaceFirst("(.)*\\.", ""); } else { message = "null"; } if (this instanceof ITagsProperty || (pec != null && Enum.class.isAssignableFrom(pec))) { String[] sResults = null; try { if (this instanceof ITagsProperty) { sResults = ((ITagsProperty) this).getTagsForProperty(name); } else { sResults = EnumUtils.toNames(pec); } } catch (Exception ex) { sResults = new String[0]; } if (sResults != null) { if (sResults.length > 0) { Element possibleValues = document.createElement("possibleValues"); Element possibleValue = null; for (int j = 0; j < sResults.length; j++) { possibleValue = document.createElement("value"); possibleValue.setTextContent(sResults[j]); possibleValues.appendChild(possibleValue); } propertyElement.appendChild(possibleValues); } } } propertyElement.setAttribute("editorClass", message); } element.appendChild(propertyElement); if (Boolean.TRUE.equals(propertyDescriptor.getValue("nillable"))) { try { Method method = this.getClass().getMethod("isNullProperty", new Class[] { String.class }); Object isNull = method.invoke(this, new Object[] { name }); propertyElement.setAttribute("isNull", isNull.toString()); } catch (Exception ex) { Engine.logBeans.error( "[Serialization] Skipping 'isNull' attribute for property \"" + name + "\".", ex); } } } catch (Exception e) { Engine.logBeans.error("[Serialization] Skipping property \"" + name + "\".", e); } } return element; }
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java
/** * Fills the appropriate node for an association and adds it to the form instance. * // w ww .ja v a 2 s . c om * @param xformsDocument * the form instance document * @param classElement * the root node of the document, which will contain all field nodes * @param alfrescoClass * the object being displayed on the form * @param association * the mapping entry for the association field * @param subMap * the sub map of URL parameters relevant for the field */ private void fillXFormsAssociationTypeSelect(Document xformsDocument, Element classElement, GenericClass alfrescoClass, AssociationType association, Map<String, String> subMap) { Element assoFieldElt = xformsDocument.createElement(association.getName()); assoFieldElt.setAttribute("multiple", "" + isMultiple(association)); Element item = xformsDocument.createElement(MsgId.INT_INSTANCE_ASSOCIATION_ITEM.getText()); assoFieldElt.appendChild(item); String initId = safeMapGet(subMap, "id"); // if present, overrides the existing associations if (initId == null) { initId = ""; List<GenericAssociation> alfAssociations = findAssociations(alfrescoClass, association); // build the space-separated list of ids boolean first = true; for (GenericAssociation asso : alfAssociations) { if (!first) { initId += " "; } initId += asso.getTarget(); first = false; } } item.setTextContent(initId); classElement.appendChild(assoFieldElt); }
From source file:com.bluexml.xforms.generator.mapping.MappingGenerator.java
/** * Writes a skeleton of the redirection file filled with default values. The * file is not created/*from ww w .ja v a 2 s. c o m*/ * if no workflow forms were generated. * <p/> * The format is: * * <pre> * <entry> * <name>FORM_NAME</name> * <url>URL</url> * <auto>false</auto> * <addParams>true</addParams> * </entry> *</pre> * * @throws IOException */ private void writeSkeletonRedirector() throws IOException { // redirector configuration Document doc = DOMUtil.getNewDocument(); if (doc != null) { List<JAXBElement<? extends CanisterType>> elements = mapping.getCanister(); Element entriesElt = doc.createElement("entries"); doc.appendChild(entriesElt); int numberOfEntries = 0; for (JAXBElement<? extends CanisterType> element : elements) { if (element.getValue() instanceof WorkflowTaskType) { WorkflowTaskType taskType = (WorkflowTaskType) element.getValue(); Element nameElt = doc.createElement(MsgId.INT_REDIRECTION_NAME.getText()); nameElt.setTextContent(taskType.getName()); Element urlElt = doc.createElement(MsgId.INT_REDIRECTION_URL.getText()); Element autoElt = doc.createElement(MsgId.INT_REDIRECTION_AUTO_ADVANCE.getText()); autoElt.setTextContent("false"); Element addElt = doc.createElement(MsgId.INT_REDIRECTION_ADD_PARAMS.getText()); addElt.setTextContent("true"); Element entryElt = doc.createElement(MsgId.INT_REDIRECTION_ENTRY.getText()); entryElt.appendChild(nameElt); entryElt.appendChild(urlElt); entryElt.appendChild(autoElt); entryElt.appendChild(addElt); entriesElt.appendChild(entryElt); numberOfEntries++; } } if (numberOfEntries > 0) { String docStr = DOMUtil.convertDocument2String(doc); FileWriter fw; fw = new FileWriter(RedirectFile); PrintWriter pw = new PrintWriter(fw); pw.print(docStr); pw.close(); } } }
From source file:org.alfresco.web.config.forms.FormConfigRuntime.java
/** * @param properties/*w w w.jav a 2 s . c o m*/ * @return */ public boolean syncForm(HashMap<String, Object> properties) { boolean status = false; Element currentElem = null; String configType = (String) properties.get("config-type"); if (configType != null) { if (configType.equals("node-type") || configType.equals("model-type") || configType.equals("aspect")) { String typeName = (String) properties.get("type-name"); String newTypeName = (properties.containsKey("new-type-name")) ? (String) properties.get("new-type-name") : null; String formId = (String) properties.get("form-id"); String newFormId = (properties.containsKey("new-form-id")) ? (String) properties.get("new-form-id") : null; if (typeName != null && formId != null) { Element configElem = XmlUtils.findFirstElement( "config[@evaluator='" + configType + "' and @condition='" + typeName + "']", (Element) configDocument.getFirstChild()); if (newTypeName != null && !newTypeName.equals(typeName) && configElem != null) { //configElem.getParentNode().removeChild(configElem); removeChild(configElem); typeName = newTypeName; configElem = null; status = true; } if (configElem == null) { configElem = configDocument.createElement("config"); manageAttribute(configElem, "evaluator", configType); manageAttribute(configElem, "condition", typeName); appendChild((Element) configDocument.getFirstChild(), configElem); status = true; } Element formsElem = XmlUtils.findFirstElement("forms", configElem); if (formsElem == null) { formsElem = configDocument.createElement("forms"); appendChild(configElem, formsElem); status = true; } String formXpath = formId.equals("") ? "form[not(@condition)]" : "form[@id='" + formId + "']"; Element formElem = XmlUtils.findFirstElement(formXpath, formsElem); if (newFormId != null && !newFormId.equals(formId) && formElem != null) { //formElem.getParentNode().removeChild(formElem); removeChild(formElem); formId = newFormId; formElem = null; status = true; } if (formElem == null) { formElem = configDocument.createElement("form"); manageAttribute(formElem, "id", formId); appendChild(formsElem, formElem); status = true; } FormConfigElement formConfig = (FormConfigElement) properties.get("form-config"); if (formConfig != null) { if (manageAttribute(formElem, "submission-url", formConfig.getSubmissionURL())) { status = true; } SyncStatus syncStatus = syncTemplateElement(formConfig.getViewTemplate(), "view-form", formElem, null); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } syncStatus = syncTemplateElement(formConfig.getEditTemplate(), "edit-form", formElem, currentElem); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } syncStatus = syncTemplateElement(formConfig.getCreateTemplate(), "create-form", formElem, currentElem); if (syncStatus.getElement() != null) { currentElem = syncStatus.getElement(); } if (syncStatus.isStatus()) { status = true; } Element visibilityInstructionElem = XmlUtils.findFirstElement("field-visibility", formElem); if (visibilityInstructionElem == null) { visibilityInstructionElem = configDocument.createElement("field-visibility"); insertChildAfter(formElem, visibilityInstructionElem, currentElem); currentElem = visibilityInstructionElem; status = true; } if (properties.containsKey("visibility-instructions") && properties .get("visibility-instructions") instanceof FieldVisibilityInstructionCustom[]) { FieldVisibilityInstructionCustom[] visibilityInstructions = (FieldVisibilityInstructionCustom[]) (properties .get("visibility-instructions")); boolean visibilityChanged = false; if (visibilityInstructions.length != visibilityInstructionElem.getChildNodes() .getLength()) { visibilityChanged = true; } else { for (FieldVisibilityInstruction fieldVisibilityInstruction : visibilityInstructions) { String fieldVisibilityXpath = fieldVisibilityInstruction.getShowOrHide() .equals(Visibility.SHOW) ? "show" : "hide"; fieldVisibilityXpath += "[@id='" + fieldVisibilityInstruction.getFieldId() + "'"; if (fieldVisibilityInstruction.getModes() != null) { if (fieldVisibilityInstruction.getModes().size() != Mode.values().length) { fieldVisibilityXpath += " and @for-mode='"; for (int i = 0; i < fieldVisibilityInstruction.getModes().size() - 1; i++) { fieldVisibilityXpath += fieldVisibilityInstruction.getModes().get(i) .toString() + ","; } fieldVisibilityXpath += fieldVisibilityInstruction.getModes() .get(fieldVisibilityInstruction.getModes().size() - 1) .toString() + "'"; } if (formConfig.getForcedFields() != null) { if (formConfig.getForcedFieldsAsList() .contains(fieldVisibilityInstruction.getFieldId())) { fieldVisibilityXpath += " and @force='true'"; } } } fieldVisibilityXpath += "]"; Element fieldVisibilityElem = XmlUtils.findFirstElement(fieldVisibilityXpath, visibilityInstructionElem); if (fieldVisibilityElem == null) { visibilityChanged = true; } } } if (visibilityChanged) { while (visibilityInstructionElem.getChildNodes().getLength() > 0) { //visibilityInstructionElem.getFirstChild().getParentNode().removeChild(visibilityInstructionElem.getFirstChild()); removeChild(visibilityInstructionElem.getFirstChild()); } for (FieldVisibilityInstructionCustom fieldVisibilityInstruction : visibilityInstructions) { String fieldVisibility = fieldVisibilityInstruction.getShowOrHide() .equals(Visibility.SHOW) ? "show" : "hide"; String fieldId = fieldVisibilityInstruction.getFieldId(); Element fieldVisibilityElem = configDocument.createElement(fieldVisibility); manageAttribute(fieldVisibilityElem, "id", fieldId); if (fieldVisibilityInstruction.getModes() != null) { if (fieldVisibilityInstruction.getModes().size() != Mode.values().length) { String fieldVisibilityMode = ""; for (int i = 0; i < fieldVisibilityInstruction.getModes().size() - 1; i++) { fieldVisibilityMode += fieldVisibilityInstruction.getModes().get(i) .toString() + ","; } fieldVisibilityMode += fieldVisibilityInstruction.getModes() .get(fieldVisibilityInstruction.getModes().size() - 1) .toString(); manageAttribute(fieldVisibilityElem, "for-mode", fieldVisibilityMode); } if (formConfig.getForcedFields() != null) { if (formConfig.getForcedFieldsAsList() .contains(fieldVisibilityInstruction.getFieldId())) { manageAttribute(fieldVisibilityElem, "for-mode", "true"); } } } manageAttribute(fieldVisibilityElem, "force", fieldVisibilityInstruction.getForce()); appendChild(visibilityInstructionElem, fieldVisibilityElem); } } } Element appearanceElem = XmlUtils.findFirstElement("appearance", formElem); if (appearanceElem == null) { appearanceElem = configDocument.createElement("appearance"); insertChildAfter(formElem, appearanceElem, currentElem); status = true; } Map<String, FormSet> sets = formConfig.getSets(); boolean setChanged = false; if (XmlUtils.findElements("set", appearanceElem).size() != sets.size() - 1) { setChanged = true; } else { for (Element fieldElement : XmlUtils.findElements("set", appearanceElem)) { if (!sets.keySet().contains(fieldElement.getAttribute("id"))) { setChanged = true; } } } if (setChanged) { for (Element setElement : XmlUtils.findElements("set", appearanceElem)) { //setElement.getParentNode().removeChild(setElement); removeChild(setElement); } status = true; } // now sync individual set element Element currentAppearanceElem = null; for (FormSet formSet : sets.values()) { String setId = formSet.getSetId(); if (!setId.equals("")) { Element setElement = XmlUtils.findFirstElement("set[@id='" + setId + "']", appearanceElem); if (setElement == null) { setElement = configDocument.createElement("set"); insertChildAfter(appearanceElem, setElement, currentAppearanceElem); } if (this.manageAttribute(setElement, "id", setId)) { status = true; } if (this.manageAttribute(setElement, "parent", formSet.getParentId())) { status = true; } if (this.manageAttribute(setElement, "label", formSet.getLabel())) { status = true; } if (this.manageAttribute(setElement, "label-id", formSet.getLabelId())) { status = true; } if (this.manageAttribute(setElement, "appearance", formSet.getAppearance())) { status = true; } if (this.manageAttribute(setElement, "template", formSet.getTemplate())) { status = true; } List<Element> setElems = XmlUtils.findElements("set", appearanceElem); currentAppearanceElem = setElems.get(setElems.size() - 1); } } Map<String, FormField> fields = formConfig.getFields(); int appearanceCounter = 0; for (FormField formField : fields.values()) { if (formField.getAttributes() != null) { appearanceCounter++; } } boolean fieldChanged = false; if (XmlUtils.findElements("field", appearanceElem).size() != appearanceCounter) { fieldChanged = true; } else { for (Element fieldElement : XmlUtils.findElements("field", appearanceElem)) { if (!fields.keySet().contains(fieldElement.getAttribute("id"))) { fieldChanged = true; } } if (!fieldChanged) { for (FormField formField : fields.values()) { if (formField.getAttributes() != null && isFieldChanged(appearanceElem, formField)) { fieldChanged = true; } } } } if (fieldChanged) { for (Element fieldElement : XmlUtils.findElements("field", appearanceElem)) { //fieldElement.getParentNode().removeChild(fieldElement); removeChild(fieldElement); } status = true; // now sync individual field element for (FormField formField : fields.values()) { if (formField.getAttributes() != null && !formField.getAttributes().isEmpty() && isFieldChanged(appearanceElem, formField)) { String formFieldId = formField.getId(); Element fieldElement = XmlUtils .findFirstElement("field[@id='" + formFieldId + "']", appearanceElem); if (fieldElement == null) { fieldElement = configDocument.createElement("field"); manageAttribute(fieldElement, "id", formFieldId); for (String key : formField.getAttributes().keySet()) { manageAttribute(fieldElement, key, formField.getAttributes().get(key)); } if (formField.getControl() != null) { Control control = formField.getControl(); Element controlElement = configDocument.createElement("control"); manageAttribute(controlElement, "template", control.getTemplate()); if (control.getParams() != null) { for (ControlParam param : control.getParams()) { Element paramElement = configDocument .createElement("control-param"); manageAttribute(paramElement, "name", param.getName()); paramElement.setTextContent(param.getValue()); appendChild(controlElement, paramElement); } } appendChild(fieldElement, controlElement); } if (formField.getConstraintDefinitionMap() != null) { Element constraintsElement = configDocument .createElement("constraint-handlers"); Map<String, ConstraintHandlerDefinition> constraints = formField .getConstraintDefinitionMap(); for (String constraintId : constraints.keySet()) { ConstraintHandlerDefinition constraint = constraints .get(constraintId); Element constraintElement = configDocument .createElement("constraint"); manageAttribute(constraintElement, "type", constraint.getType()); manageAttribute(constraintElement, "event", constraint.getEvent()); manageAttribute(constraintElement, "message", constraint.getMessage()); manageAttribute(constraintElement, "message-id", constraint.getMessageId()); manageAttribute(constraintElement, "validation-handler", constraint.getValidationHandler()); appendChild(constraintsElement, constraintElement); } appendChild(fieldElement, constraintsElement); } insertChildAfter(appearanceElem, fieldElement, currentAppearanceElem); currentAppearanceElem = fieldElement; } } } } } } } } return status; }
From source file:betullam.xmlmodifier.XMLmodifier.java
public void add(String mdFolder, String condStructureElements, String elementNames, String attrNames, String attrValues, String textValue, boolean allowDuplicate) { // Get the files that should be modified: Set<File> filesForInsertion = getFilesForInsertion(condStructureElements, mdFolder); // Backup XML-files before modifing them: makeBackupFiles(filesForInsertion);/* w w w. j a v a 2 s .c o m*/ // Iterate over all files in given directory and it's subdirectories. Works with Apache commons-io library (FileUtils). for (File xmlFile : filesForInsertion) { // DOM Parser: String filePath = xmlFile.getAbsolutePath(); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; Document xmlDoc = null; try { documentBuilder = documentFactory.newDocumentBuilder(); xmlDoc = documentBuilder.parse(filePath); // Get the elements we want to add another element. The name-attribute of the <goobi:metadata ...>-tag is important. List<Element> elementsForInsertion = getElementsForInsertion(condStructureElements, xmlDoc); if (!elementsForInsertion.isEmpty()) { List<String> lstElementNames = Arrays.asList(elementNames.split("\\s*,\\s*")); List<String> lstAttrNames = Arrays.asList(attrNames.split("\\s*,\\s*")); List<String> lstAttrValues = Arrays.asList(attrValues.split("\\s*,\\s*")); if (!lstElementNames.isEmpty()) { int noOfElements = lstElementNames.size(); if ((noOfElements == lstAttrNames.size()) && (noOfElements == lstAttrValues.size())) { Element lastElement = null; Element newElement = null; for (String elementName : lstElementNames) { int index = lstElementNames.indexOf(elementName); newElement = xmlDoc.createElement(elementName); String attrName = lstAttrNames.get(index); String attrValue = lstAttrValues.get(index); // Set attribute name and value: if (!attrName.equals("null") && !attrValue.equals("null")) { if (!attrName.isEmpty() && !attrValue.isEmpty()) { newElement.setAttribute(attrName, attrValue); } } // Set text content to the inner-most element: if ((noOfElements - 1) == index) { newElement.setTextContent(textValue); } // Add element to document: if (newElement != null) { for (Element rootElement : elementsForInsertion) { if (index == 0) { // Append element to root node if (allowDuplicate == false) { // Add only if element with same value does not already exist. if (!hasDuplicate(rootElement, elementName, attrName, attrValue, textValue)) { rootElement.appendChild(newElement); } } else { rootElement.appendChild(newElement); } } else { // Append element to previous element if (allowDuplicate == false) { // Add only if element with same value does not already exist. if (!hasDuplicate(lastElement, elementName, attrName, attrValue, textValue)) { lastElement.appendChild(newElement); } } else { lastElement.appendChild(newElement); } } lastElement = newElement; } } } } else { System.err.println( "The number of attribute names and values must be the same as the number of element names. Use \"null\" for attribute name and values if you don't want to add them."); } } else { System.err.println("You have to supply at least one element name."); } DOMSource source = new DOMSource(xmlDoc); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(filePath); transformer.transform(source, result); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
From source file:com.moviejukebox.writer.MovieJukeboxXMLWriter.java
/** * Generate the person/*from w ww. j a v a 2s . com*/ * * @param doc * @param person * @param includeVersion * @return */ private static Element writePerson(Document doc, Person person, boolean includeVersion) { Element ePerson = doc.createElement("person"); for (Map.Entry<String, String> e : person.getIdMap().entrySet()) { DOMHelper.appendChild(doc, ePerson, "id", e.getValue(), "persondb", e.getKey()); } // Add the version information to the output if (includeVersion) { DOMHelper.appendChild(doc, ePerson, "mjbVersion", GitRepositoryState.getVersion()); DOMHelper.appendChild(doc, ePerson, "mjbGitSHA", GIT.getCommitId()); DOMHelper.appendChild(doc, ePerson, "xmlGenerationDate", DateTimeTools.convertDateToString(new Date(), DateTimeTools.getDateFormatLongString())); } DOMHelper.appendChild(doc, ePerson, NAME, person.getName()); DOMHelper.appendChild(doc, ePerson, TITLE, person.getTitle()); DOMHelper.appendChild(doc, ePerson, BASE_FILENAME, person.getFilename()); if (!person.getAka().isEmpty()) { Element eAka = doc.createElement("aka"); for (String aka : person.getAka()) { DOMHelper.appendChild(doc, eAka, NAME, aka); } ePerson.appendChild(eAka); } DOMHelper.appendChild(doc, ePerson, "biography", person.getBiography()); DOMHelper.appendChild(doc, ePerson, "birthday", person.getYear()); DOMHelper.appendChild(doc, ePerson, "birthplace", person.getBirthPlace()); DOMHelper.appendChild(doc, ePerson, "birthname", person.getBirthName()); DOMHelper.appendChild(doc, ePerson, URL, person.getUrl()); DOMHelper.appendChild(doc, ePerson, "photoFile", person.getPhotoFilename()); DOMHelper.appendChild(doc, ePerson, "photoURL", person.getPhotoURL()); DOMHelper.appendChild(doc, ePerson, "backdropFile", person.getBackdropFilename()); DOMHelper.appendChild(doc, ePerson, "backdropURL", person.getBackdropURL()); DOMHelper.appendChild(doc, ePerson, "knownMovies", String.valueOf(person.getKnownMovies())); if (!person.getFilmography().isEmpty()) { Element eFilmography = doc.createElement("filmography"); for (Filmography film : person.getFilmography()) { Element eMovie = doc.createElement(MOVIE); eMovie.setAttribute("id", film.getId()); for (Map.Entry<String, String> e : film.getIdMap().entrySet()) { if (!e.getKey().equals(ImdbPlugin.IMDB_PLUGIN_ID)) { eMovie.setAttribute(ID + e.getKey(), e.getValue()); } } eMovie.setAttribute(NAME, film.getName()); eMovie.setAttribute(TITLE, film.getTitle()); eMovie.setAttribute(ORIGINAL_TITLE, film.getOriginalTitle()); eMovie.setAttribute(YEAR, film.getYear()); eMovie.setAttribute(RATING, film.getRating()); eMovie.setAttribute(CHARACTER, film.getCharacter()); eMovie.setAttribute(JOB, film.getJob()); eMovie.setAttribute(DEPARTMENT, film.getDepartment()); eMovie.setAttribute(URL, film.getUrl()); eMovie.setTextContent(film.getFilename()); eFilmography.appendChild(eMovie); } ePerson.appendChild(eFilmography); } // Write the indexes that the people belongs to Element eIndexes = doc.createElement("indexes"); String originalName; for (Entry<String, String> index : person.getIndexes().entrySet()) { Element eIndexEntry = doc.createElement(INDEX); eIndexEntry.setAttribute("type", index.getKey()); originalName = Library.getOriginalCategory(index.getKey(), Boolean.TRUE); eIndexEntry.setAttribute(ORIGINAL_NAME, originalName); eIndexEntry.setAttribute("encoded", FileTools.makeSafeFilename(index.getValue())); eIndexEntry.setTextContent(index.getValue()); eIndexes.appendChild(eIndexEntry); } ePerson.appendChild(eIndexes); DOMHelper.appendChild(doc, ePerson, "version", String.valueOf(person.getVersion())); DOMHelper.appendChild(doc, ePerson, "lastModifiedAt", person.getLastModifiedAt()); return ePerson; }
From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java
/** * Get CXF servlet definition element./* ww w . jav a2 s . c om*/ * * @param web Document representation of web.xml * @return Element representation of CXF servlet definition */ private Element getServletDefinition(Document web) { // Create servlet element Element servlet = web.createElement("servlet"); // Create servlet name and add it to servlet Element name = web.createElement("servlet-name"); name.setTextContent("CXFServlet"); servlet.appendChild(name); // Create servlet class and add it to servlet Element clas = web.createElement("servlet-class"); clas.setTextContent("org.apache.cxf.transport.servlet.CXFServlet"); servlet.appendChild(clas); return servlet; }