Java Code Examples for org.dom4j.Element#selectSingleNode()

The following examples show how to use org.dom4j.Element#selectSingleNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SelectTagTests.java    From spring-analysis-note with MIT License 8 votes vote down vote up
private void assertStringArray() throws JspException, DocumentException {
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	assertTrue(output.startsWith("<select "));
	assertTrue(output.endsWith("</select>"));

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals("select", rootElement.getName());
	assertEquals("name", rootElement.attribute("name").getValue());

	List children = rootElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element e = (Element) rootElement.selectSingleNode("option[text() = 'Rob']");
	assertEquals("Rob node not selected", "selected", e.attribute("selected").getValue());
}
 
Example 2
Source File: SelectTagTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void validateOutput(String output, boolean selected) throws DocumentException {
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals("select", rootElement.getName());
	assertEquals("country", rootElement.attribute("name").getValue());

	List children = rootElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element e = (Element) rootElement.selectSingleNode("option[@value = 'UK']");
	Attribute selectedAttr = e.attribute("selected");
	if (selected) {
		assertTrue(selectedAttr != null && "selected".equals(selectedAttr.getValue()));
	}
	else {
		assertNull(selectedAttr);
	}
}
 
Example 3
Source File: RemoteArticleService.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public String getArticleXML(Long articleId) {
    Article article = articleDao.getEntity(articleId);
    if(article == null 
    		|| checkBrowsePermission(article.getChannel().getId() ) < 0 ) {
    	return ""; // 如果文章不存在 或 对文章所在栏目没有浏览权限
    }
    
    String pubUrl = article.getPubUrl();
    Document articleDoc = XMLDocUtil.createDocByAbsolutePath2(pubUrl);
    Element articleElement = articleDoc.getRootElement();
    Element hitRateNode = (Element) articleElement.selectSingleNode("//hitCount");
    hitRateNode.setText(article.getHitCount().toString()); // 更新点击率
    
    Document doc = org.dom4j.DocumentHelper.createDocument();
    Element articleInfoElement = doc.addElement("Response").addElement("ArticleInfo");
    articleInfoElement.addElement("rss").addAttribute("version", "2.0").add(articleElement);

    // 添加文章点击率;
    HitRateManager.getInstanse("cms_article").output(articleId);
    
    return doc.asXML();
}
 
Example 4
Source File: ItemContext.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Method setUp.
 * 
 * @param assessInstance
 * @param el_orig_item
 * @param sw
 */
public void setUp(AssessmentInstance assessInstance, Element el_orig_item, Switches sw) {
    this.assessInstance = assessInstance;
    this.el_shuffled_item = shuffle(el_orig_item);
    this.qtiItem = new Item(el_shuffled_item);

    if (sw == null) { // no section switches dominate, take item switches
        // retrieve item switches
        Element el_control = (Element) el_orig_item.selectSingleNode("itemcontrol");
        if (el_control != null) {
            String feedbackswitch = el_control.attributeValue("feedbackswitch");
            String hintswitch = el_control.attributeValue("hintswitch");
            String solutionswitch = el_control.attributeValue("solutionswitch");
            boolean newFeedback = (feedbackswitch == null) ? true : feedbackswitch.equals("Yes");
            boolean newHints = (hintswitch == null) ? true : hintswitch.equals("Yes");
            boolean newSolutions = (solutionswitch == null) ? true : solutionswitch.equals("Yes");
            sw = new Switches(newFeedback, newHints, newSolutions);
        }
    }

    this.feedback = (sw != null ? sw.isFeedback() : true);
    this.solutions = (sw != null ? sw.isSolutions() : true);
    this.hints = (sw != null ? sw.isHints() : true);
    init();
}
 
Example 5
Source File: SurveyFileResourceValidator.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(final File unzippedDir) {
    // with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed.
    final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
    final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
    // getDocument(..) ensures that InputStream is closed in every case.
    final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
    // if doc is null an error loading the document occured
    if (doc == null) {
        return false;
    }
    final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
    for (final Iterator iter = metas.iterator(); iter.hasNext();) {
        final Element el_metafield = (Element) iter.next();
        final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
        final String label = el_label.getText();
        if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
            final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
            final String entry = el_entry.getText();
            return entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY);
        }
    }

    return false;
}
 
Example 6
Source File: ResultsBuilder.java    From olat with Apache License 2.0 5 votes vote down vote up
private static void addStaticsPath(final Element el_in, final AssessmentInstance ai) {
    Element el_staticspath = (Element) el_in.selectSingleNode(STATICS_PATH);
    if (el_staticspath == null) {
        final DocumentFactory df = DocumentFactory.getInstance();
        el_staticspath = df.createElement(STATICS_PATH);
        final Resolver resolver = ai.getResolver();
        el_staticspath.addAttribute("ident", resolver.getStaticsBaseURI());
        el_in.add(el_staticspath);
    }
}
 
Example 7
Source File: AssessmentContext.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
  * Method calcFeedBack.
  */
 private void calcFeedBack() {
     if (feedbacktesting) {
List<?> el_ofts = el_assessment.selectNodes("outcomes_processing/outcomes_feedback_test");
         feedbackavailable = false;
for (Iterator<?> it_oft = el_ofts.iterator(); it_oft.hasNext();) {
	Element el_oft = (Element) it_oft.next();
             // <!ELEMENT outcomes_feedback_test (test_variable , displayfeedback+)>
	Element el_testvar = (Element) el_oft.selectSingleNode("test_variable");
             // must exist: dtd
             // <!ELEMENT test_variable (variable_test | and_test | or_test |
             // not_test)>
	Element el_varandornot = (Element) el_testvar.selectSingleNode("variable_test|and_test|or_test|not_test");
	String elname = el_varandornot.getName();
	ScoreBooleanEvaluable sbe = QTIHelper.getSectionBooleanEvaluableInstance(elname);
	float totalscore = getScore();
	boolean fulfilled = sbe.eval(el_varandornot, totalscore);
             if (fulfilled) {
                 // get feedback
		Element el_displayfeedback = (Element) el_oft.selectSingleNode("displayfeedback");
		String linkRefId = el_displayfeedback.attributeValue("linkrefid");
                 // must exist (dtd)
                 // ignore feedbacktype, since we section or assess feedback only
                 // accepts material, no hints or solutions
		Element el_resolved = (Element) el_assessment.selectSingleNode(".//assessfeedback[@ident='" + linkRefId + "']");
                 getOutput().setEl_response(new AssessFeedback(el_resolved));
                 // give the whole assessmentfeedback to render
                 feedbackavailable = true;
             }
         }
     }
 }
 
Example 8
Source File: OptionsTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void withoutItemsEnumParentWithExplicitLabelsAndValues() throws Exception {
	BeanWithEnum testBean = new BeanWithEnum();
	testBean.setTestEnum(TestEnum.VALUE_2);
	getPageContext().getRequest().setAttribute("testBean", testBean);

	this.selectTag.setPath("testBean.testEnum");
	this.tag.setItemLabel("enumLabel");
	this.tag.setItemValue("enumValue");

	this.selectTag.doStartTag();
	int result = this.tag.doStartTag();
	assertEquals(BodyTag.SKIP_BODY, result);
	result = this.tag.doEndTag();
	assertEquals(Tag.EVAL_PAGE, result);
	this.selectTag.doEndTag();

	String output = getWriter().toString();
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();

	assertEquals(2, rootElement.elements().size());
	Node value1 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_1']");
	Node value2 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_2']");
	assertEquals("Label: VALUE_1", value1.getText());
	assertEquals("Label: VALUE_2", value2.getText());
	assertEquals(value2, rootElement.selectSingleNode("option[@selected]"));
}
 
Example 9
Source File: OptionsTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void withoutItemsEnumParent() throws Exception {
	BeanWithEnum testBean = new BeanWithEnum();
	testBean.setTestEnum(TestEnum.VALUE_2);
	getPageContext().getRequest().setAttribute("testBean", testBean);

	this.selectTag.setPath("testBean.testEnum");

	this.selectTag.doStartTag();
	int result = this.tag.doStartTag();
	assertEquals(BodyTag.SKIP_BODY, result);
	result = this.tag.doEndTag();
	assertEquals(Tag.EVAL_PAGE, result);
	this.selectTag.doEndTag();

	String output = getWriter().toString();
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();

	assertEquals(2, rootElement.elements().size());
	Node value1 = rootElement.selectSingleNode("option[@value = 'VALUE_1']");
	Node value2 = rootElement.selectSingleNode("option[@value = 'VALUE_2']");
	assertEquals("TestEnum: VALUE_1", value1.getText());
	assertEquals("TestEnum: VALUE_2", value2.getText());
	assertEquals(value2, rootElement.selectSingleNode("option[@selected]"));
}
 
Example 10
Source File: QTI_item.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param uic
 */
public void evalAnswer(final ItemContext uic) {
    final QTI_resprocessing resprocessing = QTIHelper.getQTI_resprocessing();
    final Element item = uic.getEl_item();
    final Element curQtiElement = (Element) item.selectSingleNode("resprocessing");
    if (curQtiElement != null) {
        resprocessing.evalAnswer(curQtiElement, uic);
    }
}
 
Example 11
Source File: SectionContext.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Method calcFeedBack.
 */
private void calcFeedBack() {
    List el_ofts = el_section.selectNodes("outcomes_processing/outcomes_feedback_test");
    feedbackavailable = false;
    for (Iterator it_oft = el_ofts.iterator(); it_oft.hasNext();) {
        Element el_oft = (Element) it_oft.next();
        // <!ELEMENT outcomes_feedback_test (test_variable , displayfeedback+)>
        Element el_testvar = (Element) el_oft.selectSingleNode("test_variable");
        // must exist: dtd
        // <!ELEMENT test_variable (variable_test | and_test | or_test |
        // not_test)>
        Element el_varandornot = (Element) el_testvar.selectSingleNode("variable_test|and_test|or_test|not_test");
        String elname = el_varandornot.getName();
        ScoreBooleanEvaluable sbe = QTIHelper.getSectionBooleanEvaluableInstance(elname);
        float totalscore = getScore();
        boolean fulfilled = sbe.eval(el_varandornot, totalscore);
        if (fulfilled) {
            // get feedback
            Element el_displayfeedback = (Element) el_oft.selectSingleNode("displayfeedback");
            String linkRefId = el_displayfeedback.attributeValue("linkrefid");
            // must exist (dtd)
            // ignore feedbacktype, since we section or assess feedback only accepts
            // material, no hints or solutions
            Element el_resolved = (Element) el_section.selectSingleNode(".//sectionfeedback[@ident='" + linkRefId + "']");
            getOutput().setEl_response(new SectionFeedback(el_resolved));
            // give the whole sectionfeedback to render
            feedbackavailable = true;
        }
    }
}
 
Example 12
Source File: FileDetailsFormEBL.java    From olat with Apache License 2.0 5 votes vote down vote up
public String extractObjectivesFromDocument() {
    if (isNullDocument()) {
        return "";
    }
    String objectives = "-";
    final Element el_objectives = (Element) document.selectSingleNode("//questestinterop/assessment/objectives");
    if (el_objectives != null) {
        final Element el_mat = (Element) el_objectives.selectSingleNode("material/mattext");
        if (el_mat != null) {
            objectives = el_mat.getTextTrim();
        }
    }
    return objectives;
}
 
Example 13
Source File: QTI_item.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param uic
 */
public void evalAnswer(final ItemContext uic) {
    final QTI_resprocessing resprocessing = QTIHelper.getQTI_resprocessing();
    final Element item = uic.getEl_item();
    final Element curQtiElement = (Element) item.selectSingleNode("resprocessing");
    if (curQtiElement != null) {
        resprocessing.evalAnswer(curQtiElement, uic);
    }
}
 
Example 14
Source File: OptionsTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void withoutItemsEnumParentWithExplicitLabelsAndValues() throws Exception {
	BeanWithEnum testBean = new BeanWithEnum();
	testBean.setTestEnum(TestEnum.VALUE_2);
	getPageContext().getRequest().setAttribute("testBean", testBean);

	this.selectTag.setPath("testBean.testEnum");
	this.tag.setItemLabel("enumLabel");
	this.tag.setItemValue("enumValue");

	this.selectTag.doStartTag();
	int result = this.tag.doStartTag();
	assertEquals(BodyTag.SKIP_BODY, result);
	result = this.tag.doEndTag();
	assertEquals(Tag.EVAL_PAGE, result);
	this.selectTag.doEndTag();

	String output = getWriter().toString();
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();

	assertEquals(2, rootElement.elements().size());
	Node value1 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_1']");
	Node value2 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_2']");
	assertEquals("Label: VALUE_1", value1.getText());
	assertEquals("Label: VALUE_2", value2.getText());
	assertEquals(value2, rootElement.selectSingleNode("option[@selected]"));
}
 
Example 15
Source File: ResultsBuilder.java    From olat with Apache License 2.0 5 votes vote down vote up
private static void addStaticsPath(final Element el_in, final AssessmentInstance ai) {
    Element el_staticspath = (Element) el_in.selectSingleNode(STATICS_PATH);
    if (el_staticspath == null) {
        final DocumentFactory df = DocumentFactory.getInstance();
        el_staticspath = df.createElement(STATICS_PATH);
        final Resolver resolver = ai.getResolver();
        el_staticspath.addAttribute("ident", resolver.getStaticsBaseURI());
        el_in.add(el_staticspath);
    }
}
 
Example 16
Source File: ServicesConfigImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
* load services configuration
*
*/
   protected SiteConfigTO loadConfiguration(String site) {
       Document document = null;
       SiteConfigTO siteConfig = null;
       try {
           document = configurationService.getConfigurationAsDocument(site, MODULE_STUDIO, getConfigFileName(),
                   studioConfiguration.getProperty(CONFIGURATION_ENVIRONMENT_ACTIVE));
       } catch (DocumentException | IOException e) {
           LOGGER.error("Error while loading configuration for " + site + " at " + getConfigFileName(), e);
       }
       if (document != null) {
           Element root = document.getRootElement();
           Node configNode = root.selectSingleNode("/site-config");
           String name = configNode.valueOf("display-name");
           siteConfig = new SiteConfigTO();
           siteConfig.setName(name);
           siteConfig.setWemProject(configNode.valueOf("wem-project"));
           siteConfig.setTimezone(configNode.valueOf("default-timezone"));
           String sandboxBranch = configNode.valueOf(SITE_CONFIG_ELEMENT_SANDBOX_BRANCH);
           if (StringUtils.isEmpty(sandboxBranch)) {
               sandboxBranch = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
           }
           siteConfig.setSandboxBranch(sandboxBranch);
           String stagingEnvironmentEnabledValue =
                   configNode.valueOf(SITE_CONFIG_XML_ELEMENT_PUBLISHED_REPOSITORY +
                   "/" + SITE_CONFIG_XML_ELEMENT_ENABLE_STAGING_ENVIRONMENT);
           if (StringUtils.isEmpty(stagingEnvironmentEnabledValue)) {
               siteConfig.setStagingEnvironmentEnabled(false);
           } else {
               siteConfig.setStagingEnvironmentEnabled(Boolean.valueOf(stagingEnvironmentEnabledValue));
           }

           String stagingEnvironment = configNode.valueOf(SITE_CONFIG_XML_ELEMENT_PUBLISHED_REPOSITORY + "/" +
                   SITE_CONFIG_XML_ELEMENT_STAGING_ENVIRONMENT);
           if (StringUtils.isEmpty(stagingEnvironment)) {
               stagingEnvironment = studioConfiguration.getProperty(REPO_PUBLISHED_STAGING);
           }
           siteConfig.setStagingEnvironment(stagingEnvironment);
           String liveEnvironment = configNode.valueOf(SITE_CONFIG_XML_ELEMENT_PUBLISHED_REPOSITORY + "/" +
                   SITE_CONFIG_XML_ELEMENT_LIVE_ENVIRONMENT);
           if (StringUtils.isEmpty(liveEnvironment)) {
               liveEnvironment = studioConfiguration.getProperty(REPO_PUBLISHED_LIVE);
           }
           siteConfig.setLiveEnvironment(liveEnvironment);

           loadSiteUrlsConfiguration(siteConfig, configNode.selectSingleNode(SITE_CONFIG_ELEMENT_SITE_URLS));

           String adminEmailAddressValue = configNode.valueOf(SITE_CONFIG_ELEMENT_ADMIN_EMAIL_ADDRESS);
           siteConfig.setAdminEmailAddress(adminEmailAddressValue);

           loadSiteRepositoryConfiguration(siteConfig, configNode.selectSingleNode("repository"));
           // set the last updated date
           siteConfig.setLastUpdated(ZonedDateTime.now(ZoneOffset.UTC));

           loadFacetConfiguration(configNode, siteConfig);

           siteConfig.setPluginFolderPattern(configNode.valueOf(SITE_CONFIG_ELEMENT_PLUGIN_FOLDER_PATTERN));
       } else {
           LOGGER.error("No site configuration found for " + site + " at " + getConfigFileName());
       }
       return siteConfig;
   }
 
Example 17
Source File: ContentServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected Document updateContentOnCopy(Document document, String filename, String folder, Map<String,
    String> params, String modifier)
        throws ServiceLayerException {

    //update pageId and groupId with the new one
    Element root = document.getRootElement();
    String originalPageId = null;
    String originalGroupId = null;

    Node filenameNode = root.selectSingleNode("//" + DmXmlConstants.ELM_FILE_NAME);
    if (filenameNode != null) {
        filenameNode.setText(filename);
    }

    Node folderNode = root.selectSingleNode("//" + DmXmlConstants.ELM_FOLDER_NAME);
    if (folderNode != null) {
        folderNode.setText(folder);
    }

    Node pageIdNode = root.selectSingleNode("//" + DmXmlConstants.ELM_PAGE_ID);
    if (pageIdNode != null) {
        originalPageId = pageIdNode.getText();
        pageIdNode.setText(params.get(DmConstants.KEY_PAGE_ID));
    }

    if(modifier != null) {
        Node internalNameNode = root.selectSingleNode("//" + DmXmlConstants.ELM_INTERNAL_NAME);
        if (internalNameNode != null) {
            String internalNameValue = internalNameNode.getText();
            internalNameNode.setText(internalNameValue + " " + modifier);
        }
    }

    Node groupIdNode = root.selectSingleNode("//" + DmXmlConstants.ELM_GROUP_ID);
    if (groupIdNode != null) {
        originalGroupId = groupIdNode.getText();
        groupIdNode.setText(params.get(DmConstants.KEY_PAGE_GROUP_ID));
    }

    List<Node> keys = root.selectNodes("//key");
    if (keys != null) {
        for(Node keyNode : keys) {
            String keyValue = keyNode.getText();
            keyValue = keyValue.replaceAll(originalPageId, params.get(DmConstants.KEY_PAGE_ID));
            keyValue = keyValue.replaceAll(originalGroupId, params.get(DmConstants.KEY_PAGE_GROUP_ID));

            if(keyValue.contains("/page")) {
                keyNode.setText(keyValue);
            }
        }
    }

    List<Node> includes = root.selectNodes("//include");
    if (includes != null) {
        for(Node includeNode : includes) {
            String includeValue = includeNode.getText();
            includeValue = includeValue.replaceAll(originalPageId, params.get(DmConstants.KEY_PAGE_ID));
            includeValue = includeValue.replaceAll(originalGroupId, params.get(DmConstants.KEY_PAGE_GROUP_ID));

            if(includeValue.contains("/page")) {
                includeNode.setText(includeValue);
            }
        }
    }

    return document;
}
 
Example 18
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private Node findPropertyNode(Element contextNode, String propertyName) {
	return contextNode.selectSingleNode("//property[@name='" + propertyName + "']");
}
 
Example 19
Source File: TestFileResourceValidator.java    From olat with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validate(final File unzippedDir) {

    // with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if
    // no longer needed.
    final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
    final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
    // getDocument(..) ensures that InputStream is closed in every case.
    final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
    // if doc is null an error loading the document occured
    if (doc == null) {
        return false;
    }
    // check if this is marked as test
    final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
    for (final Iterator iter = metas.iterator(); iter.hasNext();) {
        final Element el_metafield = (Element) iter.next();
        final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
        final String label = el_label.getText();
        if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
            final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
            final String entry = el_entry.getText();
            if (!(entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SELF) || entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_ASSESS))) {
                return false;
            }
        }
    }

    // check if at least one section with one item
    final List sectionItems = doc.selectNodes("questestinterop/assessment/section/item");
    if (sectionItems.size() == 0) {
        return false;
    }

    for (final Iterator iter = sectionItems.iterator(); iter.hasNext();) {
        final Element it = (Element) iter.next();
        final List sv = it.selectNodes("resprocessing/outcomes/decvar[@varname='SCORE']");
        // the QTIv1.2 system relies on the SCORE variable of items
        if (sv.size() != 1) {
            return false;
        }
    }

    return true;
}
 
Example 20
Source File: ConversionUtil.java    From pentaho-aggdesigner with GNU General Public License v2.0 4 votes vote down vote up
/**
 * generates <Measure> mondrian tags
 */
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 );
  }
}