List of usage examples for org.w3c.dom Element getParentNode
public Node getParentNode();
From source file:org.alfresco.web.config.WebConfigRuntime.java
/** * @param typeName/*from w ww. j a va 2s . c om*/ * @param propertySheet * @return */ public boolean syncPropertySheet(HashMap<String, String> propertySheet) { boolean status = false; Element rootElement = (Element) webConfigDocument.getFirstChild(); String enableConfig = propertySheet.get("enable"); String config = propertySheet.get("config"); String typeOrAspectName = propertySheet.get("type-aspect-name"); Element typeElem = XmlUtils.findFirstElement( "config[@evaluator='" + config + "' and @condition='" + typeOrAspectName + "']", rootElement); if (typeElem == null) { if (enableConfig.equals("false")) { return status; } typeElem = webConfigDocument.createElement("config"); typeElem.setAttribute("evaluator", config); typeElem.setAttribute("condition", typeOrAspectName); appendChild(rootElement, typeElem); status = true; } Element propertySheetElem = XmlUtils.findFirstElement("property-sheet", typeElem); if (propertySheetElem == null) { if (enableConfig.equals("false")) { return status; } propertySheetElem = webConfigDocument.createElement("property-sheet"); appendChild(typeElem, propertySheetElem); status = true; } Element configElem = null; if (propertySheet.get("type").equals("property")) { configElem = XmlUtils.findFirstElement("show-property[@name='" + propertySheet.get("name") + "']", propertySheetElem); if (configElem == null) { if (enableConfig.equals("false")) { return status; } configElem = webConfigDocument.createElement("show-property"); appendChild(propertySheetElem, configElem); status = true; } } else if (propertySheet.get("type").equals("association")) { configElem = XmlUtils.findFirstElement("show-association[@name='" + propertySheet.get("name") + "']", propertySheetElem); if (configElem == null) { if (enableConfig.equals("false")) { return status; } configElem = webConfigDocument.createElement("show-association"); appendChild(propertySheetElem, configElem); status = true; } } else if (propertySheet.get("type").equals("child-association")) { if (enableConfig.equals("false")) { return status; } configElem = XmlUtils.findFirstElement( "show-child-association[@name='" + propertySheet.get("name") + "']", propertySheetElem); if (configElem == null) { configElem = webConfigDocument.createElement("show-child-association"); appendChild(propertySheetElem, configElem); status = true; } } else if (propertySheet.get("type").equals("separator")) { if (enableConfig.equals("false")) { return status; } configElem = XmlUtils.findFirstElement("separator[@name='" + propertySheet.get("name") + "']", propertySheetElem); if (configElem == null) { configElem = webConfigDocument.createElement("separator"); appendChild(propertySheetElem, configElem); status = true; } } if (enableConfig.equals("false")) { configElem.getParentNode().removeChild(configElem); status = true; return status; } if (configElem != null) { status = manageAttribute(configElem, "name", propertySheet) || status; status = manageAttribute(configElem, "display-label", propertySheet) || status; status = manageAttribute(configElem, "display-label-id", propertySheet) || status; status = manageAttribute(configElem, "converter", propertySheet) || status; status = manageAttribute(configElem, "read-only", propertySheet) || status; status = manageAttribute(configElem, "show-in-view-mode", propertySheet) || status; status = manageAttribute(configElem, "show-in-edit-mode", propertySheet) || status; status = manageAttribute(configElem, "component-generator", propertySheet) || status; if (propertySheet.get("type").equals("property")) { status = manageAttribute(configElem, "ignore-if-missing", propertySheet) || status; } } return status; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Extracts the id to be edited from an XForms instance. The DOM node * providing that id must be//from w w w. j ava2 s . co m * reset (i.e. emptied) so that subsequent editions can happen correctly on * the same form. * * @param node * @return the id, or null (this latter case should not happen if the Edit * button's action of * setting the <edit id> in the instance is done correctly). */ public EditNodeBean getEditNodeAndReset(Node node) { Element rootElt = ((Document) node).getDocumentElement(); // find the edit id element Element editIdElt = DOMUtil.getElementInDescentByNameNonNull(rootElt, MsgId.INT_INSTANCE_SIDEEDIT.getText()); if (editIdElt != null) { String id = editIdElt.getTextContent(); editIdElt.setTextContent(null); // <- reset the id. MANDATORY. // get the data type // #1510 String dataType = null; try { Element parent = (Element) editIdElt.getParentNode(); Element typeElt = DOMUtil.getChild(parent, MsgId.INT_INSTANCE_SIDETYPE.getText()); if (typeElt != null) { dataType = typeElt.getTextContent(); } } catch (Exception e) { // nothing to do } if (logger.isDebugEnabled()) { logger.debug("Getting edit id, found: '" + id + "' with data type: '" + dataType + "'"); } return new EditNodeBean(id, dataType); } if (logger.isErrorEnabled()) { logger.error("No id found for node edition."); } return null; }
From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java
/*** * Explore "config.xml", handle plugins and copy needed resources to appropriate platforms folders. * @param wwwDir/* w w w . j a v a2 s. c o m*/ * @param platform * @param cordovaDir */ private void processConfigXMLResources(File wwwDir, File cordovaDir) throws Throwable { try { File configFile = new File(cordovaDir, "config.xml"); Document doc = XMLUtils.loadXml(configFile); TwsCachedXPathAPI xpathApi = new TwsCachedXPathAPI(); Element singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/preference[@name='phonegap-version']"); // Changes icons and splashs src in config.xml file because it was moved to the parent folder NodeIterator nodeIterator = xpathApi.selectNodeIterator(doc, "//*[local-name()='splash' or local-name()='icon']"); singleElement = (Element) nodeIterator.nextNode(); while (singleElement != null) { String src = singleElement.getAttribute("src"); src = "www/" + src; File file = new File(cordovaDir, src); if (file.exists()) { singleElement.setAttribute("src", src); } singleElement = (Element) nodeIterator.nextNode(); } //ANDROID if (mobilePlatform instanceof Android) { singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/name"); if (singleElement != null) { String name = singleElement.getTextContent(); name = name.replace("\\", "\\\\"); name = name.replace("'", "\\'"); name = name.replace("\"", "\\\""); singleElement.setTextContent(name); } } //iOS // if (mobilePlatform instanceof IOs) { // } //WINPHONE if (mobilePlatform instanceof WindowsPhone8) { // Without these width and height the local build doesn't work but with these the remote build doesn't work singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform[@name='wp8']/icon[not(@role)]"); if (singleElement != null) { singleElement.setAttribute("width", "99"); singleElement.setAttribute("height", "99"); } singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform[@name='wp8']/icon[@role='background']"); if (singleElement != null) { singleElement.setAttribute("width", "159"); singleElement.setAttribute("height", "159"); } // /widget/platform[@name='wp8']/splash singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/platform/splash"); if (singleElement != null) { singleElement.setAttribute("width", "768"); singleElement.setAttribute("height", "1280"); } singleElement = (Element) xpathApi.selectSingleNode(doc, "/widget/plugin[@name='phonegap-plugin-push']/param[@name='SENDER_ID']"); if (singleElement != null) { // Remote build needs a node named 'param' and local build needs a node named 'variable' singleElement.getParentNode().appendChild(cloneNode(singleElement, "variable")); singleElement.getParentNode().removeChild(singleElement); } } // if (mobilePlatform instanceof Windows) { // TODO : Add platform Windows 8 // } // XMLUtils.saveXml(doc, configFile.getAbsolutePath()); // We have to add the root config.xml all our app's config.xml preferences. // Cordova will use this file to generates the platform specific config.xml // Get preferences from current config.xml NodeIterator preferences = xpathApi.selectNodeIterator(doc, "//preference"); // File configFile = new File(cordovaDir, "config.xml"); // doc = XMLUtils.loadXml(configFile); // The root config.xml NodeList preferencesList = doc.getElementsByTagName("preference"); // Remove old preferences while (preferencesList.getLength() > 0) { Element pathNode = (Element) preferencesList.item(0); // Remove empty lines Node prev = pathNode.getPreviousSibling(); if (prev != null && prev.getNodeType() == Node.TEXT_NODE && prev.getNodeValue().trim().length() == 0) { doc.getDocumentElement().removeChild(prev); } doc.getDocumentElement().removeChild(pathNode); } for (Element preference = (Element) preferences .nextNode(); preference != null; preference = (Element) preferences.nextNode()) { String name = preference.getAttribute("name"); String value = preference.getAttribute("value"); Element elt = doc.createElement("preference"); elt.setAttribute("name", name); elt.setAttribute("value", value); Engine.logEngine.info("Adding preference'" + name + "' with value '" + value + "'"); doc.getDocumentElement().appendChild(elt); } Engine.logEngine.trace("New config.xml is: " + XMLUtils.prettyPrintDOM(doc)); File resXmlFile = new File(cordovaDir, "config.xml"); // FileUtils.deleteQuietly(resXmlFile); XMLUtils.saveXml(doc, resXmlFile.getAbsolutePath()); // Last part, as all resources has been copied to the correct location, we can remove // our "www/res" directory before packaging to save build time and size... // FileUtils.deleteDirectory(new File(wwwDir, "res")); } catch (Exception e) { logException(e, "Unable to process config.xml in your project, check the file's validity"); } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private void tagParents(Element menuItemsElement) { Node tmpNode = menuItemsElement.getParentNode(); while (tmpNode != null && tmpNode.getNodeType() == Node.ELEMENT_NODE && !((Element) tmpNode).getTagName().equals("menu")) { ((Element) tmpNode).setAttribute("path", "true"); tmpNode = tmpNode.getParentNode().getParentNode(); }// w w w . j a va 2 s . c o m }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
/** * Builds a menu tree, typically used to present the menu in the menu ;) * * @param user The current user * @param getterSettings If given - build tree from these settings * @return A DOM document containing the menu tree *///from w w w . j a va 2s. c o m public Document getMenusForAdmin(User user, MenuGetterSettings getterSettings) { List<Integer> paramValues = new ArrayList<Integer>(2); StringBuffer sqlMenus = new StringBuffer(MENU_SELECT); if (getterSettings.hasMenuKeys()) { int[] menuKeys = getterSettings.getMenuKeys(); sqlMenus.append(" WHERE "); sqlMenus.append("men_lKey IN ("); for (int i = 0; i < menuKeys.length; i++) { if (i > 0) { sqlMenus.append(','); } sqlMenus.append(menuKeys[i]); } sqlMenus.append(')'); } // Selekterer bare menyer som brukeren har create eller administrate p if (user != null) { MenuCriteria criteria = getterSettings.getMenuCriteria(); getSecurityHandler().appendMenuSQL(user, sqlMenus, criteria); } Hashtable<String, Element> hashtable_menus = new Hashtable<String, Element>(); Connection con = null; PreparedStatement statement = null; ResultSet resultSet = null; Document doc = XMLTool.createDocument("menus"); try { con = getConnection(); statement = con.prepareStatement(sqlMenus.toString()); JDBCUtil.addValuesToPreparedStatement(statement, paramValues); try { // Frst selekterer vi ut menus... resultSet = statement.executeQuery(); while (resultSet.next()) { int curMenuKey = resultSet.getInt("men_lKey"); Element element_Menu = getMenuData(doc.getDocumentElement(), curMenuKey); Element accessRights = XMLTool.createElement(doc, element_Menu, "accessrights"); getSecurityHandler().appendAccessRightsOnDefaultMenuItem(user, curMenuKey, accessRights, true); XMLTool.createElement(doc, element_Menu, "menuitems"); // Lagrer referansen til kategori-elementet for raskt oppslag til senere bruk hashtable_menus.put(String.valueOf(curMenuKey), element_Menu); } } finally { close(resultSet); resultSet = null; close(statement); statement = null; } MenuItemCriteria menuItemCriteria = getterSettings.getMenuItemCriteria(); if (!menuItemCriteria.getDisableMenuItemLoadingForUnspecified() || menuItemCriteria.getMenuKey() >= 0) { // Legger s til menuitems til menyene Hashtable<String, Element> hashtable_MenuItems = appendMenuItemsBySettings(user, doc, hashtable_menus, getterSettings); // Hvis brukeren bare vil ha et fullt tree fra gitte menuItemKey, // s m vi fjerne alle ssken-noder til foreldre-nodene if (getterSettings.hasOnlyChildrenFromThisMenuItemKey()) { Element curMenuItem = hashtable_MenuItems .get(getterSettings.getMenuItemKeyAsInteger().toString()); while (curMenuItem != null) { XMLTool.removeAllSiblings(curMenuItem); // Move to first parent node (menuitems) curMenuItem = (Element) curMenuItem.getParentNode(); // Exit loop if we have reached the top if ("menus".equals(curMenuItem.getNodeName())) { break; } // Move to next parent node (menuitem/menu) if (curMenuItem != null) { curMenuItem = (Element) curMenuItem.getParentNode(); } } } if (getterSettings.hasTagParentsOfThisMenuItem()) { Element menuItem = hashtable_MenuItems .get(getterSettings.getTagParentsOfThisMenuItemKeyAsInteger().toString()); Node parent = menuItem.getParentNode(); String tagName = getterSettings.getTagParentsOfThisMenuItemTagName(); String tagValue = getterSettings.getTagParentsOfThisMenuItemTagValue(); while (parent != null) { if (parent instanceof Element) { ((Element) parent).setAttribute(tagName, tagValue); } parent = parent.getParentNode(); } } } if (!getterSettings.hasMenuKeys()) { String sqlMenuItems; sqlMenuItems = "SELECT DISTINCT mei_men_lKey FROM tMenuItem JOIN tMenu on tMenuItem.mei_men_lKey = tMenu.men_lKey "; sqlMenuItems = getSecurityHandler().appendMenuItemSQL(user, sqlMenuItems, menuItemCriteria); statement = con.prepareStatement(sqlMenuItems); resultSet = statement.executeQuery(); while (resultSet.next()) { String menuKey = resultSet.getString("mei_men_lKey"); if (!hashtable_menus.containsKey(menuKey)) { Element menuElement = getMenuData(doc.getDocumentElement(), Integer.parseInt(menuKey)); hashtable_menus.put(menuKey, menuElement); } } } } catch (SQLException sqle) { String message = "Failed to get the menus: %t"; VerticalEngineLogger.error(this.getClass(), 0, message, sqle); doc = XMLTool.createDocument("categories"); } finally { close(resultSet); close(statement); close(con); } return doc; }
From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java
private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context, Element elementToAdd, SOAPElement soapElement) throws SOAPException { SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild(); String targetNamespace = soapMethodResponseElement.getNamespaceURI(); String prefix = soapMethodResponseElement.getPrefix(); String nodeType = elementToAdd.getAttribute("type"); SOAPElement childSoapElement = soapElement; boolean elementAdded = true; boolean bTable = false; if (nodeType.equals("table")) { bTable = true;/*w ww. j av a 2s .c o m*/ /*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", ""); if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) { childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array"); }*/ childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName()); } else if (nodeType.equals("row")) { /*String elementType = context.transactionName + "_" + tableName + "_Row"; childSoapElement = soapElement.addChildElement(elementType, "");*/ childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName()); } else if (nodeType.equals("attachment")) { childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName()); if (context.requestedObject instanceof AbstractHttpTransaction) { AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd); if (attachment != null) { byte[] raw = attachment.getData(); if (raw != null) childSoapElement.addTextNode(Base64.encodeBase64String(raw)); } /* DON'T WORK YET *\ AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type")); ap.setContentId(key); ap.setContentLocation(elementToAdd.getAttribute("url")); responseMessage.addAttachmentPart(ap); \* DON'T WORK YET */ } } else { String elementNodeName = elementToAdd.getNodeName(); String elementNodeNsUri = elementToAdd.getNamespaceURI(); String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri); XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName); boolean isGlobal = xmlSchemaElement != null; if (isGlobal) { elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI(); elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri); } // ignore original SOAP message response elements // if ((elementNodeName.toUpperCase().indexOf("SOAP-ENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAP-ENV:") != -1)) || // (elementNodeName.toUpperCase().indexOf("SOAPENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAPENV:") != -1)) || // (elementNodeName.toUpperCase().indexOf("NS0:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1))) { // elementAdded = false; // } if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI()) || "http://schemas.xmlsoap.org/soap/envelope/" .equals(elementToAdd.getParentNode().getNamespaceURI()) || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 || elementNodeName.toUpperCase().indexOf("NS0:") != -1) { elementAdded = false; } else { if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) { if (elementNodePrefix == null) { childSoapElement = soapElement .addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace)); } else { childSoapElement = soapElement.addChildElement( soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri)); } } else { childSoapElement = soapElement.addChildElement(elementNodeName); } } } if (elementAdded && elementToAdd.hasAttributes()) { addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement); } if (elementToAdd.hasChildNodes()) { NodeList childNodes = elementToAdd.getChildNodes(); int len = childNodes.getLength(); if (bTable) { /*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) { childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]"); }*/ } org.w3c.dom.Node node; Element childElement; for (int i = 0; i < len; i++) { node = childNodes.item(i); switch (node.getNodeType()) { case org.w3c.dom.Node.ELEMENT_NODE: childElement = (Element) node; addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement); break; case org.w3c.dom.Node.CDATA_SECTION_NODE: case org.w3c.dom.Node.TEXT_NODE: String text = node.getNodeValue(); text = (text == null) ? "" : text; childSoapElement.addTextNode(text); break; default: break; } } /*org.w3c.dom.Node node; Element childElement; for (int i = 0 ; i < len ; i++) { node = childNodes.item(i); if (node instanceof Element) { childElement = (Element) node; addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement); } else if (node instanceof CDATASection) { Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE); String text = textNode.getNodeValue(); if (text == null) { text = ""; } childSoapElement.addTextNode(text); } else { Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE); if (textNode != null) { String text = textNode.getNodeValue(); if (text == null) { text = ""; } childSoapElement.addTextNode(text); } } }*/ } }
From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java
/** * #################################################################################### S T E P 6 Reparse ViewComponents / Content for Internal Links, Pics, Docs * #################################################################################### *///from w ww . j av a 2 s .co m private void reparseViewComponent(ViewComponentHbm vcl) throws Exception { // if (!context.getRollbackOnly()) { try { String ref = vcl.getReference(); if (log.isDebugEnabled()) log.debug("Reparsing VC: " + vcl.getDisplayLinkName()); switch (vcl.getViewType()) { case Constants.VIEW_TYPE_EXTERNAL_LINK: // dont do anythink at the external link case Constants.VIEW_TYPE_SEPARATOR: break; case Constants.VIEW_TYPE_INTERNAL_LINK: case Constants.VIEW_TYPE_SYMLINK: String newRefId = ref; try { newRefId = mappingVCs.get(new Integer(ref)).toString(); } catch (Exception exe) { log.warn("Error while changing ref: " + ref + " to " + newRefId + " : " + exe.getMessage()); } vcl.setReference(newRefId); break; case Constants.VIEW_TYPE_CONTENT: case Constants.VIEW_TYPE_UNIT: default: if (log.isDebugEnabled()) log.debug("Reparsing Content of VC to Ref: " + ref); if (ref != null && !ref.equalsIgnoreCase("") && !ref.equalsIgnoreCase("root")) { ContentHbm content = null; try { content = getContentHbmDao().load(new Integer(ref)); } catch (Exception e) { log.warn("Cannot find referenced content " + ref + " - continue import"); } if (content != null) { Collection cvlColl = content.getContentVersions(); Iterator cvlIt = cvlColl.iterator(); while (cvlIt.hasNext()) { ContentVersionHbm cvl = (ContentVersionHbm) cvlIt.next(); String text = cvl.getText(); if (text != null && !text.equalsIgnoreCase("")) { org.w3c.dom.Document doc = null; try { InputSource in = new InputSource(new StringReader(text)); doc = XercesHelper.inputSource2Dom(in); } catch (Exception exe) { } if (doc != null) { if (log.isDebugEnabled()) log.debug( "Found ContentVersion: " + cvl.getContentVersionId() + " with DOC"); Iterator itILinks = XercesHelper.findNodes(doc, "//internalLink/internalLink"); while (itILinks.hasNext()) { Element elm = (Element) itILinks.next(); String oldId = elm.getAttribute("viewid"); try { System.out.println("oldId " + oldId); String newId = mappingVCs.get(new Integer(oldId)).toString(); elm.setAttribute("viewid", newId); } catch (Exception exe) { } } Iterator itPics = XercesHelper.findNodes(doc, "//image[@src]"); while (itPics.hasNext()) { Element elm = (Element) itPics.next(); String oldId = elm.getAttribute("src"); try { String newId = mappingPics.get(new Integer(oldId)).toString(); if (log.isDebugEnabled()) log.debug("newId " + newId); elm.setAttribute("src", newId); ((Element) elm.getParentNode()).setAttribute("description", newId); } catch (Exception exe) { } } Iterator itDocs = XercesHelper.findNodes(doc, "//documents/document"); while (itDocs.hasNext()) { Element elm = (Element) itDocs.next(); String oldId = elm.getAttribute("src"); try { String newId = mappingDocs.get(new Integer(oldId)).toString(); elm.setAttribute("src", newId); content.setUpdateSearchIndex(true); } catch (Exception exe) { } } /* * Here the reparsing of the database components has to be called */ Iterator itAggregation = XercesHelper.findNodes(doc, "//aggregation//include"); while (itAggregation.hasNext()) { try { Element ndeInclude = (Element) itAggregation.next(); String type = ndeInclude.getAttribute("type"); Long id = new Long(ndeInclude.getAttribute("id")); if (type.equals("person")) { if (mappingPersons.containsKey(id)) { Long newId = mappingPersons.get(id); ndeInclude.setAttribute("id", newId.toString()); } } else if (type.equals("address")) { if (mappingAddresses.containsKey(id)) { Long newId = mappingAddresses.get(id); ndeInclude.setAttribute("id", newId.toString()); } } else if (type.equals("unit")) { // Unit hat Integer Primary Keys if (mappingUnits.containsKey(new Integer(id.intValue()))) { Integer newId = mappingUnits.get(new Integer(id.intValue())); ndeInclude.setAttribute("id", newId.toString()); } } else if (type.equals("department")) { if (mappingDepartments.containsKey(id)) { Long newId = mappingDepartments.get(id); ndeInclude.setAttribute("id", newId.toString()); } } else if (type.equals("talkTime")) { if (mappingTalktime.containsKey(id)) { Long newId = mappingTalktime.get(id); ndeInclude.setAttribute("id", newId.toString()); } } } catch (Exception exe) { log.error("Error during the replacement of database components:", exe); } } // READY text = XercesHelper.doc2String(doc); cvl.setText(text); } } } } } // children if (vcl.getFirstChild() != null) { reparseViewComponent(vcl.getFirstChild()); } break; } // next if (vcl.getNextNode() != null) { reparseViewComponent(vcl.getNextNode()); } } catch (Exception exe) { // context.setRollbackOnly(); throw exe; } // } }
From source file:com.enonic.vertical.engine.handlers.MenuHandler.java
private Element buildMenuItemXML(Document doc, Element menuItemsElement, ResultSet result, int tagItem, boolean complete, boolean includePageConfig, boolean includeHidden, boolean includeTypeSpecificXML, boolean tagItems, int levels) throws SQLException { int key = result.getInt("mei_lKey"); // check if menuitem is hidden: int hiddenInt = result.getInt("mei_bHidden"); boolean hidden = result.wasNull() || hiddenInt == 1; // propagate upwards in the XML and tag parents: if (key == tagItem) { tagParents(menuItemsElement);// www. j a v a 2s. co m } // simply return null if we don't want to include // hidden menuitems: if ((!includeHidden && hidden) || levels == 0) { // special case: if includeHidden is false, we must // check to see if the menuitem that is to be tagged // is a child of this menuitem if (tagItems) { if (tagItem != -1 && tagItem != key) { if (hasChild(key, tagItem, true)) { tagParents(menuItemsElement); if (hidden) { Node n = menuItemsElement.getParentNode(); if (n.getNodeType() == Node.ELEMENT_NODE) { ((Element) n).setAttribute("active", "true"); } } } } else if (tagItem == key) { Node n = menuItemsElement.getParentNode(); if (n.getNodeType() == Node.ELEMENT_NODE) { ((Element) n).setAttribute("active", "true"); } } } return null; } ////// + build xml for menu item Element menuItemElement = XMLTool.createElement(doc, menuItemsElement, "menuitem"); menuItemElement.setAttribute("key", String.valueOf(key)); // tag the menuitem? if (tagItem == key && !hidden) { menuItemElement.setAttribute("path", "true"); menuItemElement.setAttribute("active", "true"); } // attribute: owner menuItemElement.setAttribute("owner", result.getString("mei_usr_hOwner")); // attribute: modifier menuItemElement.setAttribute("modifier", result.getString("mei_usr_hModifier")); // attribute: order menuItemElement.setAttribute("order", result.getString("mei_lOrder")); // Add timestamp attribute menuItemElement.setAttribute("timestamp", CalendarUtil.formatTimestamp(result.getTimestamp("mei_dteTimestamp"))); // attribute: language int lanKey = result.getInt("lan_lKey"); String lanCode = result.getString("lan_sCode"); String lanDesc = result.getString("lan_sDescription"); if (lanDesc != null) { menuItemElement.setAttribute("languagekey", String.valueOf(lanKey)); menuItemElement.setAttribute("languagecode", lanCode); menuItemElement.setAttribute("language", lanDesc); } // attribute menykey: int menuKey = result.getInt("mei_men_lkey"); if (!result.wasNull()) { menuItemElement.setAttribute("menukey", String.valueOf(menuKey)); } // attribute parent: int parentKey = result.getInt("mei_lParent"); if (!result.wasNull()) { menuItemElement.setAttribute("parent", String.valueOf(parentKey)); } // element: name XMLTool.createElement(doc, menuItemElement, "name", result.getString("mei_sName")); // display-name XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_DISPLAY_NAME, result.getString(COLUMN_NAME_DISPLAY_NAME)); // short-name: String tmp = result.getString(COLUMN_NAME_ALTERNATIVE_NAME); if (!result.wasNull() && tmp.length() > 0) { XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_MENU_NAME, tmp); } menuItemElement.setAttribute("runAs", RunAsType.get(result.getInt("mei_lRunAs")).toString()); // description: String desc = result.getString("mei_sDescription"); if (!result.wasNull()) { XMLTool.createElement(doc, menuItemElement, "description", desc); } else { XMLTool.createElement(doc, menuItemElement, "description"); } // keywords: String keywords = result.getString("mei_sKeywords"); if (!result.wasNull()) { XMLTool.createElement(doc, menuItemElement, "keywords", keywords); } else { XMLTool.createElement(doc, menuItemElement, "keywords"); } // visibility: if (!hidden) { menuItemElement.setAttribute("visible", "yes"); } else { menuItemElement.setAttribute("visible", "no"); } // contentkey int contentKey = getMenuItemContentKey(key); if (contentKey != -1) { menuItemElement.setAttribute("contentkey", String.valueOf(contentKey)); } // element menuitemdata: InputStream is = result.getBinaryStream("mei_xmlData"); Element documentElem; if (result.wasNull()) { XMLTool.createElement(doc, menuItemElement, "parameters"); documentElem = XMLTool.createElement(doc, "document"); if (complete) { XMLTool.createElement(doc, menuItemElement, "data"); } } else { Document dataDoc = XMLTool.domparse(is); Element dataElem = (Element) doc.importNode(dataDoc.getDocumentElement(), true); Element parametersElem = XMLTool.getElement(dataElem, "parameters"); dataElem.removeChild(parametersElem); menuItemElement.appendChild(parametersElem); if (complete) { documentElem = XMLTool.getElement(dataElem, "document"); if (documentElem != null) { dataElem.removeChild(documentElem); menuItemElement.appendChild(documentElem); } menuItemElement.appendChild(dataElem); } else { documentElem = XMLTool.createElement(doc, "document"); } } // attribute: menu item type MenuItemType menuItemType = MenuItemType.get(result.getInt("mei_mid_lKey")); menuItemElement.setAttribute("type", menuItemType.getName()); if (includeTypeSpecificXML) { // build type-specific XML: switch (menuItemType) { case PAGE: buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig); break; case URL: buildURLTypeXML(result, doc, menuItemElement); break; case CONTENT: MenuItemKey sectionKey = getSectionHandler().getSectionKeyByMenuItem(new MenuItemKey(key)); if (sectionKey != null) { buildSectionTypeXML(key, menuItemElement); } buildDocumentTypeXML(menuItemElement, documentElem); buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig); break; case LABEL: break; case SECTION: buildSectionTypeXML(key, menuItemElement); break; case SHORTCUT: buildShortcutTypeXML(key, menuItemElement); break; } } return menuItemElement; }
From source file:com.concursive.connect.web.modules.wiki.utils.HTMLToWikiUtils.java
public static void processChildNodes(ArrayList<Node> nodeList, StringBuffer sb, int indentLevel, boolean doText, boolean withFormatting, boolean trim, String appendToCRLF, String contextPath, int projectId) { Iterator nodeI = nodeList.iterator(); while (nodeI.hasNext()) { Node n = (Node) nodeI.next(); if (n != null) { if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) { if (doText) { String value = n.getNodeValue(); // Escaped characters value = StringUtils.replace(value, "*", "\\*"); value = StringUtils.replace(value, "#", "\\#"); value = StringUtils.replace(value, "=", "\\="); value = StringUtils.replace(value, "|", "\\|"); value = StringUtils.replace(value, "[", "\\{"); value = StringUtils.replace(value, "]", "\\}"); if (trim && !nodeI.hasNext()) { // If within a cell, make sure returns include the cell value // String value = (appendToCRLF.length() > 0 ? StringUtils.replace(n.getNodeValue(), CRLF, CRLF + appendToCRLF) : n.getNodeValue()); LOG.trace(" <text:trim>"); // Output the value, trim is required sb.append(StringUtils.fromHtmlValue(value.trim())); } else { // If within a cell, make sure returns include the cell value if (appendToCRLF.length() > 0 && (hasParentNodeType(n, "th") || hasParentNodeType(n, "td")) && value.trim().length() == 0) { // This is an empty value... check to see if the previous line has content or not before appending a new line } else { LOG.trace(" <text>"); sb.append(StringUtils.fromHtmlValue((appendToCRLF.length() > 0 ? StringUtils.replace(value, CRLF, CRLF + appendToCRLF) : value))); }/*from ww w . jav a2 s. co m*/ } } } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = ((Element) n); String tag = element.getTagName(); LOG.trace(tag); if ("h1".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("= ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" =").append(CRLF + appendToCRLF); } else if ("h2".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" ==").append(CRLF + appendToCRLF); } else if ("h3".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("=== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" ===").append(CRLF + appendToCRLF); } else if ("h4".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("==== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" ====").append(CRLF + appendToCRLF); } else if ("h5".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("===== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" =====").append(CRLF + appendToCRLF); } else if ("h6".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("====== ").append(StringUtils.fromHtmlValue(element.getTextContent().trim())) .append(" ======").append(CRLF + appendToCRLF); } else if ("p".equals(tag) || "div".equals(tag)) { if (n.getChildNodes().getLength() > 0 && (hasTextContent(n) || hasImageNodes(n.getChildNodes()))) { // If this contains a Table, UL, OL, or object skip everything else to get there ArrayList<Node> subNodes = new ArrayList<Node>(); getNodes(n.getChildNodes(), subNodes, new String[] { "table", "ul", "ol", "object" }, false); if (subNodes.size() > 0) { LOG.trace(" nonTextNodes - yes"); processChildNodes(subNodes, sb, indentLevel, true, true, false, appendToCRLF, contextPath, projectId); } else { LOG.trace(" nonTextNodes - no"); startOnNewLine(sb, appendToCRLF); processChildNodes(getNodeList(n), sb, indentLevel, true, true, false, appendToCRLF, contextPath, projectId); } } } else if ("strong".equals(tag) || "b".equals(tag)) { if (n.getChildNodes().getLength() > 0) { if ("".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) { processChildNodes(getNodeList(n), sb, indentLevel, true, false, false, appendToCRLF, contextPath, projectId); } else { if (hasNonTextNodes(n.getChildNodes())) { processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, false, appendToCRLF, contextPath, projectId); } else { if (withFormatting) { sb.append("'''"); } processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, false, appendToCRLF, contextPath, projectId); if (withFormatting) { sb.append("'''"); } } } } } else if ("em".equals(tag) || "i".equals(tag)) { if (n.getChildNodes().getLength() > 0) { if ("".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) { processChildNodes(getNodeList(n), sb, indentLevel, true, false, trim, appendToCRLF, contextPath, projectId); } else { if (hasNonTextNodes(n.getChildNodes())) { processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim, appendToCRLF, contextPath, projectId); } else { if (withFormatting) { sb.append("''"); } processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim, appendToCRLF, contextPath, projectId); if (withFormatting) { sb.append("''"); } } } } } else if ("span".equals(tag)) { if (n.getChildNodes().getLength() > 0 && !"".equals(StringUtils.fromHtmlValue(n.getTextContent()).trim())) { if (element.hasAttribute("style")) { String value = element.getAttribute("style"); if (withFormatting) { if (value.contains("underline")) { sb.append("__"); } if (value.contains("line-through")) { sb.append("<s>"); } if (value.contains("bold")) { sb.append("'''"); } if (value.contains("italic")) { sb.append("''"); } } processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim, appendToCRLF, contextPath, projectId); if (withFormatting) { if (value.contains("italic")) { sb.append("''"); } if (value.contains("bold")) { sb.append("'''"); } if (value.contains("line-through")) { sb.append("</s>"); } if (value.contains("underline")) { sb.append("__"); } } } else { processChildNodes(getNodeList(n), sb, indentLevel, true, withFormatting, trim, appendToCRLF, contextPath, projectId); } } } else if ("ul".equals(tag) || "ol".equals(tag) || "dl".equals(tag)) { ++indentLevel; if (indentLevel == 1) { if (appendToCRLF.length() == 0) { startOnNewLine(sb, appendToCRLF); } else { // Something\n // ! // !* Item 1 // !* Item 2 if (!sb.toString().endsWith("|") && !sb.toString().endsWith(CRLF + appendToCRLF)) { LOG.trace("ul newline CRLF"); sb.append(CRLF + appendToCRLF); } } } if (indentLevel > 1 && !sb.toString().endsWith(CRLF + appendToCRLF)) { LOG.trace("ul indent CRLF"); sb.append(CRLF + appendToCRLF); } processChildNodes(getNodeList(n), sb, indentLevel, false, false, trim, appendToCRLF, contextPath, projectId); --indentLevel; } else if ("li".equals(tag)) { String parentTag = ((Element) element.getParentNode()).getTagName(); for (int counter = 0; counter < indentLevel; counter++) { if ("ul".equals(parentTag)) { sb.append("*"); } else if ("ol".equals(parentTag)) { sb.append("#"); } } sb.append(" "); processChildNodes(getNodeList(n), sb, indentLevel, true, false, true, appendToCRLF, contextPath, projectId); if (!sb.toString().endsWith(CRLF + appendToCRLF)) { LOG.trace("li CRLF"); sb.append(CRLF + appendToCRLF); } } else if ("dt".equals(tag) || "dd".equals(tag)) { processChildNodes(getNodeList(n), sb, indentLevel, true, false, trim, appendToCRLF, contextPath, projectId); if (!sb.toString().endsWith(CRLF + appendToCRLF)) { LOG.trace("dt CRLF"); sb.append(CRLF + appendToCRLF); } } else if ("pre".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("<pre>"); processChildNodes(getNodeList(n), sb, indentLevel, true, true, trim, appendToCRLF, contextPath, projectId); sb.append("</pre>"); if (nodeI.hasNext()) { sb.append(CRLF + appendToCRLF); sb.append(CRLF + appendToCRLF); } } else if ("code".equals(tag)) { startOnNewLine(sb, appendToCRLF); sb.append("<code>"); processChildNodes(getNodeList(n), sb, indentLevel, true, true, trim, appendToCRLF, contextPath, projectId); sb.append("</code>"); if (nodeI.hasNext()) { sb.append(CRLF + appendToCRLF); sb.append(CRLF + appendToCRLF); } } else if ("br".equals(tag)) { LOG.trace("br CRLF"); sb.append(CRLF + appendToCRLF); } else if ("table".equals(tag)) { // Always start a table on a new line startOnNewLine(sb, appendToCRLF); processTable(n.getChildNodes(), sb, 0, false, false, contextPath, projectId, 0); //if (nodeI.hasNext()) { // sb.append(CRLF); //} } else if ("form".equals(tag)) { // Always start a form on a new line startOnNewLine(sb, appendToCRLF); CustomForm form = processForm(n); convertFormToWiki(form, sb); } else if ("a".equals(tag)) { // Determine if the link is around text or around an image if (n.getChildNodes().getLength() > 0 && hasImageNodes(n.getChildNodes())) { // The link is around an image LOG.debug("Processing link as an image"); // Get the img tag and pass to processImage... ArrayList<Node> subNodes = new ArrayList<Node>(); getNodes(n.getChildNodes(), subNodes, new String[] { "img" }, false); processImage(sb, subNodes.get(0), (Element) subNodes.get(0), appendToCRLF, contextPath, projectId); } else { // The link is around text processLink(sb, element, appendToCRLF, contextPath, projectId); } } else if ("img".equals(tag)) { processImage(sb, n, element, appendToCRLF, contextPath, projectId); } else if ("object".equals(tag)) { startOnNewLine(sb, appendToCRLF); processVideo(sb, n, element, appendToCRLF, contextPath); } else { processChildNodes(getNodeList(n), sb, indentLevel, false, true, trim, appendToCRLF, contextPath, projectId); } } } } }
From source file:com.codename1.android.AndroidLayoutImporter.java
protected void convertElement(Element inputSrcElement, Element out) throws UnsupportedElementException { String id = inputSrcElement.getAttributeNS(NS_ANDROID, "id"); if (id != null) { id = id.substring(id.indexOf("/") + 1); out.setAttribute("name", id.replaceAll("[^a-zA-Z0-9]", "")); }//w ww .j av a 2s . c o m //out.setAttribute("uiid", "android."+inputSrcElement.getTagName()); out.setAttribute("type", "Container"); out.setAttribute("layout", "FlowLayout"); Node inputParentNode = inputSrcElement.getParentNode(); if (inputParentNode != null && inputParentNode instanceof Element) { Element inputParent = (Element) inputParentNode; if ("FrameLayout".equals(inputParent.getTagName())) { out.setAttribute("layout", "BorderLayout"); String gravity = inputSrcElement.getAttributeNS(NS_ANDROID, "layout_gravity"); String layoutConstraint = "CENTER"; switch (gravity) { case "top": layoutConstraint = "NORTH"; break; case "left": layoutConstraint = "WEST"; break; case "right": layoutConstraint = "EAST"; break; case "bottom": layoutConstraint = "SOUTH"; break; case "fill_vertical": case "center_vertical": case "center_horizontal": case "fill_horizontal": case "center": case "fill": layoutConstraint = "CENTER"; break; default: layoutConstraint = "CENTER"; } Element layoutConstraintEl = out.getOwnerDocument().createElement("layoutConstraint"); layoutConstraintEl.setAttribute("value", layoutConstraint); out.appendChild(layoutConstraintEl); } } switch (inputSrcElement.getTagName()) { case "LinearLayout": convertLinearLayout(inputSrcElement, out); break; case "android.support.v7.widget.RecyclerView": convertRecyclerView(inputSrcElement, out); break; case "FrameLayout": convertFrameLayout(inputSrcElement, out); break; case "android.support.design.widget.CoordinatorLayout": convertCoordinatorLayout(inputSrcElement, out); break; case "android.support.design.widget.CollapsingToolbarLayout": convertCollapsingToolbarLayout(inputSrcElement, out); break; case "android.support.design.widget.AppBarLayout": convertAppBarLayout(inputSrcElement, out); break; case "android.support.v7.widget.Toolbar": convertToolbar(inputSrcElement, out); break; case "android.support.design.widget.FloatingActionButton": convertFloatingActionButton(inputSrcElement, out); break; case "include": { try { convertInclude(inputSrcElement, out); } catch (IOException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex); } } break; case "android.support.v4.widget.NestedScrollView": convertNestedScrollView(inputSrcElement, out); break; case "ListView": convertListView(inputSrcElement, out); break; case "ProgressBar": convertProgressBar(inputSrcElement, out); break; case "TextView": convertTextView(inputSrcElement, out); break; case "Button": convertButton(inputSrcElement, out); break; case "ScrollView": convertScrollView(inputSrcElement, out); break; case "EditText": convertEditText(inputSrcElement, out); break; case "CheckBox": convertCheckBox(inputSrcElement, out); break; case "View": convertView(inputSrcElement, out); break; case "merge": convertMerge(inputSrcElement, out); break; case "RadioGroup": convertRadioGroup(inputSrcElement, out); break; case "RadioButton": convertRadioButton(inputSrcElement, out); break; case "Spinner": convertSpinner(inputSrcElement, out); break; case "RelativeLayout": convertRelativeLayout(inputSrcElement, out); break; case "ImageButton": convertImageButton(inputSrcElement, out); break; case "ImageView": convertImageView(inputSrcElement, out); break; case "SeekBar": convertSeekBar(inputSrcElement, out); break; case "QuickContactBadge": convertQuickContactBadge(inputSrcElement, out); break; case "ViewAnimator": convertViewAnimator(inputSrcElement, out); break; case "ViewStub": convertViewStub(inputSrcElement, out); break; case "Space": convertSpace(inputSrcElement, out); break; default: if (suppressUnsupportedElementExceptions) { this.convertOther(inputSrcElement, out); } else { throw new UnsupportedElementException(inputSrcElement); } } convertChildren(inputSrcElement, out); if (out.hasAttribute("layout") && "BorderLayout".equals(out.getAttribute("layout"))) { // Make sure that border layout children have appropriate constraint Set<String> allowable = new HashSet<String>( Arrays.asList(new String[] { "NORTH", "SOUTH", "EAST", "WEST", "CENTER" })); Map<String, Element> childMap = new HashMap<String, Element>(); List<ElementConstraint> childList = getBorderLayoutChildren(out); Set<ElementConstraint> used = new HashSet<ElementConstraint>(); for (ElementConstraint ec : childList) { if (ec.constraint != null && allowable.contains(ec.constraint) && !childMap.containsKey(ec.constraint)) { childMap.put(ec.constraint, ec.el); used.add(ec); } } childList.removeAll(used); if (!childList.isEmpty()) { // We weren't able to place all of the elements in the border layout // this is either because we filled all of the slots, or there were two // in some slots // Let's simplify things for now by just adding all of the extras in a // BoxLayout.Y inside the CENTER Element center = out.getOwnerDocument().createElement("component"); center.setAttribute("type", "Container"); applyBoxLayoutX(center); Element centerConstraint = out.getOwnerDocument().createElement("layoutConstraint"); centerConstraint.setAttribute("value", "CENTER"); center.appendChild(centerConstraint); if (childMap.containsKey("CENTER")) { //System.out.println("Removing center from "+childMap); out.removeChild(childMap.get("CENTER")); center.appendChild(childMap.get("CENTER")); } for (ElementConstraint ec : childList) { removeLayoutConstraint(ec.el); out.removeChild(ec.el); center.appendChild(ec.el); } out.appendChild(center); } } else if (out.hasAttribute("layout")) { // Not a boxlayout. NodeList children = out.getChildNodes(); int len = children.getLength(); for (int i = 0; i < len; i++) { Node n = children.item(i); if (n instanceof Element) { removeLayoutConstraint((Element) n); } } } applyStyles(inputSrcElement, out); }