List of usage examples for org.dom4j Element getTextTrim
String getTextTrim();
From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java
License:Open Source License
private static void populateDimensions(Element mondrianCube, Element ssasDatabase, Element ssasMeasureGroup, Table factTable, List<Table> allTables) throws AggDesignerException { // add dimensions List measureDimensions = ssasMeasureGroup.selectNodes("assl:Dimensions/assl:Dimension"); for (int j = 0; j < measureDimensions.size(); j++) { Element measureDimension = (Element) measureDimensions.get(j); String cubeDimensionId = getXPathNodeText(measureDimension, "assl:CubeDimensionID"); Element cubeDimension = (Element) ssasMeasureGroup .selectSingleNode("../../assl:Dimensions/assl:Dimension[assl:ID='" + cubeDimensionId + "']"); String databaseDimensionId = getXPathNodeText(cubeDimension, "assl:DimensionID"); Element databaseDimension = (Element) ssasDatabase .selectSingleNode("assl:Dimensions/assl:Dimension[assl:ID='" + databaseDimensionId + "']"); Element mondrianDimension = DocumentFactory.getInstance().createElement("Dimension"); String dimensionName = getXPathNodeText(cubeDimension, "assl:Name"); mondrianDimension.addAttribute("name", dimensionName); // locate the key attribute Element keyAttribute = (Element) databaseDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:Usage='Key']"); String keyAttributeID = getXPathNodeText(keyAttribute, "assl:ID"); String foreignKey = null; // first look in the dimension object within the measures List nodes = measureDimension.selectNodes("assl:Attributes/assl:Attribute[assl:AttributeID='" + keyAttributeID + "']/assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); if (nodes.size() > 1) { logger.warn("(1) Key Column foreign key contains more than one column in dimension " + dimensionName + ", SKIPPING DIMENSION"); continue; }//from w w w . ja va 2s . com Element keyTableObject = (Element) measureDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:AttributeID='" + keyAttributeID + "']/assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); if (keyTableObject == null) { keyTableObject = (Element) keyAttribute .selectSingleNode("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); nodes = keyAttribute.selectNodes("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); if (nodes.size() > 1) { logger.warn("(2) Key Column foreign key contains more than one column in dimension " + dimensionName + ", SKIPPING DIMENSION"); continue; } } if (keyTableObject != null) { String tableID = keyTableObject.getTextTrim(); List<Table> tables = findTables(allTables, tableID); for (Table table : tables) { if (table == factTable) { Element keyColumnObject = (Element) measureDimension.selectSingleNode( "assl:Attributes/assl:Attribute[assl:AttributeID='" + keyAttributeID + "']/assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); if (keyColumnObject == null) { keyColumnObject = (Element) keyAttribute .selectSingleNode("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); } foreignKey = keyColumnObject.getTextTrim(); break; } Key foreignKeyObject = table.getFactForeignKey(factTable); if (foreignKeyObject != null) { if (foreignKeyObject.columns.size() > 1) { logger.warn("FOREIGN KEY " + foreignKeyObject + " CONTAINS MORE THAN ONE COLUMN IN DIMENSION " + dimensionName); } else { foreignKey = foreignKeyObject.columns.get(0); if (foreignKey != null) { break; } } } } } else { logger.warn("FAILED TO FIND FOREIGN KEY!"); } if (foreignKey == null) { logger.warn("FAILED TO FIND FOREIGN KEY. Excluding Dimension " + dimensionName); continue; } Column foreignKeyObject = factTable.findColumn(foreignKey); mondrianDimension.addAttribute("foreignKey", foreignKeyObject.dbName); // get hierarchies populateHierarchies(mondrianDimension, cubeDimension, databaseDimension, keyAttribute, factTable, allTables, foreignKey); mondrianCube.add(mondrianDimension); } }
From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java
License:Open Source License
private static void populateHierarchies(Element mondrianDimension, Element ssasCubeDimension, Element ssasDatabaseDimension, Element ssasDimensionKeyAttribute, Table factTable, List<Table> allTables, String factForeignKey) throws AggDesignerException { // first do parent child hierarchies // for each attribute in cube dimension, see if it's database dimension attribute is USAGE PARENT // SSAS 2005 only supports one parent child hierarchy per dimension List cubeAttributes = ssasCubeDimension.selectNodes("assl:Attributes/assl:Attribute"); for (int i = 0; i < cubeAttributes.size(); i++) { Element cubeAttribute = (Element) cubeAttributes.get(i); // retrieve database attribute String attribID = getXPathNodeText(cubeAttribute, "assl:AttributeID"); Element databaseAttribute = (Element) ssasDatabaseDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:ID='" + attribID + "']"); Element usageElement = (Element) databaseAttribute.selectSingleNode("assl:Usage"); if (usageElement != null && "Parent".equals(usageElement.getTextTrim())) { populateParentChildHierarchy(mondrianDimension, databaseAttribute, ssasDimensionKeyAttribute, ssasDatabaseDimension, factTable, factForeignKey, allTables, attribID); }//from www .j a v a 2s . co m } // handle the traditional hierarchies List hierarchies = ssasCubeDimension.selectNodes("assl:Hierarchies/assl:Hierarchy"); for (int k = 0; k < hierarchies.size(); k++) { Element hierarchy = (Element) hierarchies.get(k); String databaseHierarchyID = getXPathNodeText(hierarchy, "assl:HierarchyID"); Element databaseHierarchy = (Element) ssasDatabaseDimension .selectSingleNode("assl:Hierarchies/assl:Hierarchy[assl:ID='" + databaseHierarchyID + "']"); if (databaseHierarchy == null) { throw new AggDesignerException("Failed to locate hierarchy " + databaseHierarchyID); } Element mondrianHierarchy = DocumentFactory.getInstance().createElement("Hierarchy"); mondrianHierarchy.addAttribute("name", getXPathNodeText(databaseHierarchy, "assl:Name")); String tableID = getXPathNodeText(ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); Table primaryKeyTable = findTable(allTables, tableID); String primaryKey = getXPathNodeText(ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); Column primaryKeyColumn = primaryKeyTable.findColumn(primaryKey); mondrianHierarchy.addAttribute("primaryKey", primaryKeyColumn.dbName); Element allMemberName = (Element) databaseHierarchy.selectSingleNode("assl:AllMemberName"); if (allMemberName != null && allMemberName.getTextTrim().length() != 0) { mondrianHierarchy.addAttribute("allMemberName", allMemberName.getTextTrim()); mondrianHierarchy.addAttribute("hasAll", "true"); } else { mondrianHierarchy.addAttribute("hasAll", "false"); } // determine if this hierarchy is a snow flake // we can tell this by looking at the levels // preprocess levels to determine snowflake-ness List ssasLevels = databaseHierarchy.selectNodes("assl:Levels/assl:Level"); List<String> tables = new ArrayList<String>(); for (int l = 0; l < ssasLevels.size(); l++) { Element level = (Element) ssasLevels.get(l); String sourceAttribID = getXPathNodeText(level, "assl:SourceAttributeID"); Element sourceAttribute = (Element) ssasDatabaseDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:ID='" + sourceAttribID + "']"); String levelTableID = getXPathNodeText(sourceAttribute, "assl:NameColumn/assl:Source/assl:TableID"); if (!tables.contains(levelTableID)) { // insert the table in the correct order tables.add(0, levelTableID); } } // skip if degenerate dimension if (tables.size() != 1 || !tables.get(0).equals(factTable.logicalName)) { populateHierarchyRelation(mondrianHierarchy, tables, ssasDatabaseDimension, factTable, allTables, databaseHierarchyID, factForeignKey); } else { mondrianHierarchy.add(DocumentFactory.getInstance().createComment("Degenerate Hierarchy")); } // render levels populateHierarchyLevels(mondrianHierarchy, ssasLevels, ssasDatabaseDimension, allTables, tables.size() > 1); mondrianDimension.add(mondrianHierarchy); } // finally, do attribute hierarchies populateAttributeHierarchies(mondrianDimension, cubeAttributes, ssasDatabaseDimension, ssasDimensionKeyAttribute, factTable, factForeignKey, allTables); }
From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java
License:Open Source License
/** * generates <Level> mondrian tags *//*from w ww .java 2 s . c om*/ private static void populateHierarchyLevels(Element mondrianHierarchy, List ssasLevels, Element ssasDatabaseDimension, List<Table> allTables, boolean includeTableName) throws AggDesignerException { for (int l = 0; l < ssasLevels.size(); l++) { Element level = (Element) ssasLevels.get(l); Element mondrianLevel = DocumentFactory.getInstance().createElement("Level"); mondrianLevel.addAttribute("name", getXPathNodeText(level, "assl:Name")); String sourceAttribID = getXPathNodeText(level, "assl:SourceAttributeID"); Element sourceAttribute = (Element) ssasDatabaseDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:ID='" + sourceAttribID + "']"); Element keyUniquenessGuarantee = (Element) sourceAttribute .selectSingleNode("assl:KeyUniquenessGuarantee"); boolean keyUniqueness = false; if (keyUniquenessGuarantee != null) { keyUniqueness = "true".equals(keyUniquenessGuarantee.getTextTrim()); } mondrianLevel.addAttribute("uniqueMembers", "" + keyUniqueness); String levelTableID = getXPathNodeText(sourceAttribute, "assl:NameColumn/assl:Source/assl:TableID"); Table levelTable = findTable(allTables, levelTableID); if (includeTableName) { mondrianLevel.addAttribute("table", levelTable.dbName); // tableName); } // don't assume single column for keys List<Element> nodes = (List<Element>) sourceAttribute .selectNodes("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); // get the last key column in the list. String keyColumn = nodes.get(nodes.size() - 1).getTextTrim(); // String keyColumn = getXPathNodeText(sourceAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); String nameColumn = getXPathNodeText(sourceAttribute, "assl:NameColumn/assl:Source/assl:ColumnID"); if (keyColumn == null || keyColumn.equals(nameColumn)) { Column nameColumnObj = levelTable.findColumn(nameColumn); nameColumnObj.addToMondrian(mondrianLevel, "column", "KeyExpression"); } else { Column keyColumnObj = levelTable.findColumn(keyColumn); keyColumnObj.addToMondrian(mondrianLevel, "column", "KeyExpression"); Column nameColumnObj = levelTable.findColumn(nameColumn); nameColumnObj.addToMondrian(mondrianLevel, "nameColumn", "NameExpression"); } String datatype = getXPathNodeText(sourceAttribute, "assl:NameColumn/assl:DataType"); // TODO: create example with numeric column, // this code is more stubbed then tested if (datatype.equals("Numeric")) { mondrianLevel.addAttribute("type", "Numeric"); } mondrianHierarchy.add(mondrianLevel); } }
From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java
License:Open Source License
/** * generates ssas attribute hierarchies/*from w w w . java2 s . com*/ */ private static void populateAttributeHierarchies(Element mondrianDimension, List cubeAttributes, Element ssasDatabaseDimension, Element ssasDimensionKeyAttribute, Table factTable, String factForeignKey, List<Table> allTables) throws AggDesignerException { mondrianDimension.add(DocumentFactory.getInstance().createComment("Attribute Hierarchies")); for (int i = 0; i < cubeAttributes.size(); i++) { Element cubeAttribute = (Element) cubeAttributes.get(i); // retrieve database attribute String attribID = getXPathNodeText(cubeAttribute, "assl:AttributeID"); Element databaseAttribute = (Element) ssasDatabaseDimension .selectSingleNode("assl:Attributes/assl:Attribute[assl:ID='" + attribID + "']"); // note: databaseAttribute also has an AttributeHierarchyEnabled flag // should we also check "visible"? if (cubeAttribute.selectSingleNode("assl:AttributeHierarchyEnabled") != null && "true".equals(getXPathNodeText(cubeAttribute, "assl:AttributeHierarchyEnabled"))) { Element usageElement = (Element) databaseAttribute.selectSingleNode("assl:Usage"); if (usageElement != null && "Parent".equals(usageElement.getTextTrim())) { // skip parent hierarchies continue; } Element mondrianHierarchy = DocumentFactory.getInstance().createElement("Hierarchy"); String attribName = getXPathNodeText(databaseAttribute, "assl:Name"); mondrianHierarchy.addAttribute("name", attribName); String tableID = getXPathNodeText(ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID"); Table table = findTable(allTables, tableID); String primaryKey = getXPathNodeText(ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); Column primaryKeyColumn = table.findColumn(primaryKey); List<Element> nodes = (List<Element>) ssasDimensionKeyAttribute .selectNodes("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); if (nodes.size() > 1) { logger.warn("SKIPPING ATTRIBUTE HIERARCHY " + attribName + ", MORE THAN ONE FOREIGN KEY"); continue; } mondrianHierarchy.addAttribute("primaryKey", primaryKeyColumn.dbName); // AttributeAllMemberName Element allMemberName = (Element) ssasDatabaseDimension .selectSingleNode("assl:AttributeAllMemberName"); if (allMemberName != null && allMemberName.getTextTrim().length() != 0) { mondrianHierarchy.addAttribute("allMemberName", allMemberName.getTextTrim()); mondrianHierarchy.addAttribute("hasAll", "true"); } else { mondrianHierarchy.addAttribute("hasAll", "false"); } String levelTableID = getXPathNodeText(databaseAttribute, "assl:NameColumn/assl:Source/assl:TableID"); List<String> tables = new ArrayList<String>(); tables.add(tableID); if (levelTableID != null && !levelTableID.equals(tableID)) { tables.add(levelTableID); table = findTable(allTables, levelTableID); } // skip if degenerate dimension if (tables.size() != 1 || !tables.get(0).equals(factTable.logicalName)) { populateHierarchyRelation(mondrianHierarchy, tables, ssasDatabaseDimension, factTable, allTables, attribID, factForeignKey); } Element mondrianLevel = DocumentFactory.getInstance().createElement("Level"); mondrianLevel.addAttribute("name", attribName); Element keyUniquenessGuarantee = (Element) databaseAttribute .selectSingleNode("assl:KeyUniquenessGuarantee"); boolean keyUniqueness = false; if (keyUniquenessGuarantee != null) { keyUniqueness = "true".equals(keyUniquenessGuarantee.getTextTrim()); } mondrianLevel.addAttribute("uniqueMembers", "" + keyUniqueness); if (tables.size() > 1) { mondrianLevel.addAttribute("table", table.dbName); // tableName); } nodes = (List<Element>) databaseAttribute .selectNodes("assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID"); String keyColumn = nodes.get(nodes.size() - 1).getTextTrim(); String nameColumn = getXPathNodeText(databaseAttribute, "assl:NameColumn/assl:Source/assl:ColumnID"); if (keyColumn == null || keyColumn.equals(nameColumn)) { Column nameColumnObject = table.findColumn(nameColumn); nameColumnObject.addToMondrian(mondrianLevel, "column", "KeyExpression"); } else { Column keyColumnObject = table.findColumn(keyColumn); keyColumnObject.addToMondrian(mondrianLevel, "column", "KeyExpression"); Column nameColumnObject = table.findColumn(nameColumn); nameColumnObject.addToMondrian(mondrianLevel, "nameColumn", "NameExpression"); } String datatype = getXPathNodeText(databaseAttribute, "assl:NameColumn/assl:DataType"); // TODO: create example with numeric column, // this code is more stubbed then tested if (datatype.equals("Numeric")) { mondrianLevel.addAttribute("type", "Numeric"); } mondrianHierarchy.add(mondrianLevel); mondrianDimension.add(mondrianHierarchy); } } }
From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java
License:Open Source License
/** * generates <Measure> mondrian tags *//*from ww w .j a v a2 s . com*/ private static void populateCubeMeasures(Element mondrianCube, Element ssasMeasureGroup, Table factTable, String cubeName) throws AggDesignerException { List allMeasures = ssasMeasureGroup.selectNodes("assl:Measures/assl:Measure"); for (int j = 0; j < allMeasures.size(); j++) { Element measure = (Element) allMeasures.get(j); // assert Source/Source xsi:type="ColumnBinding" if (measure.selectSingleNode("assl:Source/assl:Source[@xsi:type='ColumnBinding']") == null && measure.selectSingleNode("assl:Source/assl:Source[@xsi:type='RowBinding']") == null) { logger.warn("SKIPPING MEASURE, INVALID MEASURE IN CUBE " + cubeName + " : " + measure.asXML()); continue; } Element mondrianMeasure = DocumentFactory.getInstance().createElement("Measure"); String measureName = getXPathNodeText(measure, "assl:Name"); mondrianMeasure.addAttribute("name", measureName); logger.trace("MEASURE: " + measureName); String aggType = "sum"; Element aggFunction = (Element) measure.selectSingleNode("assl:AggregateFunction"); if (aggFunction != null) { aggType = aggFunction.getTextTrim().toLowerCase(); } if (aggType.equals("distinctcount")) { aggType = "distinct-count"; } mondrianMeasure.addAttribute("aggregator", aggType); if (measure.selectSingleNode("assl:Source/assl:Source[@xsi:type='ColumnBinding']") != null) { String column = getXPathNodeText(measure, "assl:Source/assl:Source/assl:ColumnID"); Column columnObj = factTable.findColumn(column); columnObj.addToMondrian(mondrianMeasure, "column", "MeasureExpression"); } else { // select the first fact column in the star mondrianMeasure.addAttribute("column", factTable.columns.get(0)); } mondrianCube.add(mondrianMeasure); } }
From source file:org.pentaho.platform.plugin.services.cache.CacheManager.java
License:Open Source License
/** * Populates the properties object from the pentaho.xml * /*from w ww . j a v a 2 s .c o m*/ * @param settings * The Pentaho ISystemSettings object */ private Properties getCacheProperties(final ISystemSettings settings) { Properties cacheProperties = new Properties(); List propertySettings = settings.getSystemSettings("cache-provider/properties/*"); //$NON-NLS-1$ for (int i = 0; i < propertySettings.size(); i++) { Object obj = propertySettings.get(i); Element someProperty = (Element) obj; String propertyName = XmlDom4JHelper.getNodeText("@name", someProperty, null); //$NON-NLS-1$ if (propertyName != null) { String propertyValue = someProperty.getTextTrim(); if (propertyValue != null) { cacheProperties.put(propertyName, propertyValue); } } } return cacheProperties; }
From source file:org.pentaho.platform.web.servlet.PentahoXmlaServlet.java
License:Open Source License
@Override protected RepositoryContentFinder makeContentFinder(String dataSourcesUrl) { // It is safe to cache these for now because their lambda doesn't // do anything with security. // BEWARE before making modifications that check security rights or all // other kind of stateful things. @SuppressWarnings("rawtypes") Set keys = cacheMgr.getAllKeysFromRegionCache(CACHE_REGION); if (!keys.contains(dataSourcesUrl)) { cacheMgr.putInRegionCache(CACHE_REGION, dataSourcesUrl, new DynamicContentFinder(dataSourcesUrl) { @Override/*from w ww. ja v a 2 s . c o m*/ public String getContent() { try { String original = generateInMemoryDatasourcesXml(); EntityResolver loader = new PentahoEntityResolver(); Document originalDocument = XmlDom4JHelper.getDocFromString(original, loader); if (PentahoXmlaServlet.logger.isDebugEnabled()) { PentahoXmlaServlet.logger.debug(Messages.getInstance() .getString("PentahoXmlaServlet.DEBUG_ORIG_DOC", originalDocument.asXML())); //$NON-NLS-1$ } Document modifiedDocument = (Document) originalDocument.clone(); List<Node> nodesToRemove = getNodesToRemove(modifiedDocument); if (PentahoXmlaServlet.logger.isDebugEnabled()) { PentahoXmlaServlet.logger.debug( Messages.getInstance().getString("PentahoXmlaServlet.DEBUG_NODES_TO_REMOVE", //$NON-NLS-1$ String.valueOf(nodesToRemove.size()))); } for (Node node : nodesToRemove) { node.detach(); } if (PentahoXmlaServlet.logger.isDebugEnabled()) { PentahoXmlaServlet.logger.debug(Messages.getInstance() .getString("PentahoXmlaServlet.DEBUG_MOD_DOC", modifiedDocument.asXML())); //$NON-NLS-1$ } return modifiedDocument.asXML(); } catch (XmlParseException e) { PentahoXmlaServlet.logger.error(Messages.getInstance() .getString("PentahoXmlaServlet.ERROR_0004_UNABLE_TO_GET_DOCUMENT_FROM_STRING"), e); //$NON-NLS-1$ return null; } } private List<Node> getNodesToRemove(Document doc) { List<Node> nodesToRemove = doc.selectNodes("/DataSources/DataSource/Catalogs/Catalog"); CollectionUtils.filter(nodesToRemove, new Predicate() { @Override public boolean evaluate(Object o) { Element el = ((DefaultElement) o).element("DataSourceInfo"); if (el == null || el.getText() == null || el.getTextTrim().length() == 0) { throw new XmlaException(SERVER_FAULT_FC, UNKNOWN_ERROR_CODE, UNKNOWN_ERROR_FAULT_FS, new MondrianException("DataSourceInfo not defined for " + ((DefaultElement) o).attribute("name").getText())); } return el.getText().matches("(?i).*EnableXmla=['\"]?false['\"]?"); } }); return nodesToRemove; } }); } return (RepositoryContentFinder) cacheMgr.getFromRegionCache(CACHE_REGION, dataSourcesUrl); }
From source file:org.prettyx.Common.XMLParser.java
License:Open Source License
/** * traverse the xml document by recursion * * @param element/* w w w .j a va 2 s.co m*/ * the rootElement */ @SuppressWarnings("unchecked") private static void getElementList(Element element) { List elements = element.elements(); if (elements.size() == 0) { String xpath = element.getPath(); String value = element.getTextTrim(); elementMap.put(xpath, value); } else { for (Object object : element.elements()) { Element local = (Element) object; getElementList(local); } } }
From source file:org.projectforge.web.FavoritesMenu.java
License:Open Source License
private MenuEntry readFromXml(final Element item, final MenuBuilderContext context) { if ("item".equals(item.getName()) == false) { log.error("Tag 'item' expected instead of '" + item.getName() + "'. Ignoring this tag."); return null; }// w w w .ja v a 2 s . c o m String id = item.attributeValue("id"); MenuItemDef menuItemDef = null; if (id != null && id.startsWith("c-") == true) { id = id.substring(2); } if (id != null && menu != null) { // menu is only null for FavoritesMenuTest. final MenuEntry origEntry = menu.findById(id); menuItemDef = origEntry != null ? origEntry.menuItemDef : null; } final MenuEntry menuEntry; if (menuItemDef != null) { menuEntry = menu.getMenuEntry(menuItemDef); } else { menuEntry = new MenuEntry(); } menuEntry.setSorted(false); if (item != null) { final String trimmedTitle = item.getTextTrim(); if (trimmedTitle != null) { // menuEntry.setName(StringEscapeUtils.escapeXml(trimmedTitle)); if (StringUtils.isBlank(trimmedTitle) == true) { menuEntry.setName("???"); } else { menuEntry.setName(trimmedTitle); } } } for (final Iterator<?> it = item.elementIterator("item"); it.hasNext();) { if (menuItemDef != null) { log.warn("Menu entry shouldn't have children, because it's a leaf node."); } final Element child = (Element) it.next(); final MenuEntry childMenuEntry = readFromXml(child, context); if (childMenuEntry != null) { menuEntry.addMenuEntry(childMenuEntry); } } return menuEntry; }
From source file:org.sapia.util.xml.confix.Dom4jProcessor.java
License:Open Source License
private Object process(Object aParent, Element anElement, String setterName) throws ProcessingException { String aName = anElement.getName(); if (setterName == null) { setterName = aName;//from www . j a v a 2 s . c om } CreationStatus status = null; try { status = getObjectFactory().newObjectFor(anElement.getNamespace().getPrefix(), anElement.getNamespace().getURI(), aName, aParent); } catch (ObjectCreationException oce) { if (aParent == null) { String aMessage = "Unable to create an object for the element " + anElement; throw new ProcessingException(aMessage, oce); } List children; if ((aParent != null) && (containsMethod("set", aParent, aName) || containsMethod("add", aParent, aName)) && ((children = anElement.elements()).size() == 1)) { Element child = (Element) children.get(0); process(aParent, child, setterName); return aParent; } try { String aValue = anElement.getTextTrim(); invokeSetter(aParent.getClass().getName(), aParent, aName, aValue); return aParent; } catch (ConfigurationException ce) { String aMessage = "Unable to create an object nor to call a setter for the element " + anElement; oce.printStackTrace(); throw new ProcessingException(aMessage, ce); } } String text = anElement.getTextTrim(); if (text.length() > 0) { try { invokeSetter(aName, status.getCreated(), "Text", text); } catch (ConfigurationException ce) { String aMessage = "The object '" + aName + "' does not accept free text"; throw new ProcessingException(aMessage, ce); } } try { // Process the attributes of the DOM element for (Iterator it = anElement.attributeIterator(); it.hasNext();) { Attribute attr = (Attribute) it.next(); invokeSetter(aName, status.getCreated(), attr.getName(), attr.getValue()); } // Process the child elements for (Iterator it = anElement.elementIterator(); it.hasNext();) { Element child = (Element) it.next(); if (status.getCreated() instanceof Dom4jHandlerIF) { ((Dom4jHandlerIF) status.getCreated()).handleElement(child); } else if (status.getCreated() instanceof XMLConsumer) { XMLConsumer cons = (XMLConsumer) status.getCreated(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLWriter writer; try { writer = new XMLWriter(bos, OutputFormat.createPrettyPrint()); } catch (UnsupportedEncodingException e) { throw new ProcessingException("Could not instantiate XMLWriter", e); } try { Element copy = child.createCopy(); copy.setDocument(null); writer.write(DocumentHelper.createDocument(copy)); ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray()); InputSource is = new InputSource(in); cons.consume(is); } catch (Exception e) { throw new ProcessingException("Could not pipe content of element: " + child.getQualifiedName() + " to XMLConsumer", e); } } else { process(status.getCreated(), child); } } // before assigning to parent, check if object // implements ObjectCreationCallback. if (status.getCreated() instanceof ObjectCreationCallback) { status._created = ((ObjectCreationCallback) status.getCreated()).onCreate(); } // assign obj to parent through setXXX or addXXX if ((aParent != null) && !status.wasAssigned() && !(status.getCreated() instanceof NullObject)) { assignToParent(aParent, status.getCreated(), setterName); } if (status.getCreated() instanceof NullObject) { return null; } return status.getCreated(); } catch (ConfigurationException ce) { String aMessage = "Unable to process the content of the element " + aName; throw new ProcessingException(aMessage, ce); } }