Java Code Examples for org.dom4j.XPath#selectNodes()

The following examples show how to use org.dom4j.XPath#selectNodes() . 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: GetXmlData.java    From hop with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
private boolean applyXPath() {
  try {
    XPath xpath = data.document.createXPath( data.PathValue );
    if ( meta.isNamespaceAware() ) {
      xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) );
      xpath.setNamespaceURIs( data.NAMESPACE );
    }
    // get nodes list
    data.an = xpath.selectNodes( data.document );
    data.nodesize = data.an.size();
    data.nodenr = 0;
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) );
    return false;
  }
  return true;
}
 
Example 2
Source File: Update1To2.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
private void convertTableSettings(final Document doc) {
	XPath xpathSelector = DocumentHelper.createXPath("/settings/columns/column");
	List<?> results = xpathSelector.selectNodes(doc);
	List<String> tableColumnNames = new ArrayList<String>();
	List<String> tableColumnVisible = new ArrayList<String>();
	for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
		Element element = (Element) iter.next();
		Attribute name = element.attribute("name");
		Attribute visible = element.attribute("visible");
		tableColumnNames.add(name.getText());
		if (visible.getText().equals("true")) {
			tableColumnVisible.add(name.getText());
		}
	}
	String mode = convertFlag(doc);
	writeTableSettings(doc, mode, tableColumnNames, tableColumnVisible);
}
 
Example 3
Source File: Update1To2.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
private String convertFlag(final Document doc) {
	XPath flagSelector = DocumentHelper.createXPath("/settings/flags/flag");
	List<?> flagResults = flagSelector.selectNodes(doc);
	boolean text = false;
	boolean window = false;
	for (Iterator<?> iter = flagResults.iterator(); iter.hasNext();) {
		Element element = (Element) iter.next();
		Attribute key = element.attribute("key");
		Attribute visible = element.attribute("enabled");
		if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_TEXT")) {
			text = visible.getText().equals("true");
			element.detach();
		}
		if (key.getText().equals("FLAG_AUTO_RESIZE_COLUMNS_WINDOW")) {
			window = visible.getText().equals("true");
			element.detach();
		}
	}
	if (text) {
		return "TEXT";
	}
	if (window) {
		return "WINDOW";
	}
	return "NONE";
}
 
Example 4
Source File: GetXMLData.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
private boolean applyXPath() {
  try {
    XPath xpath = data.document.createXPath( data.PathValue );
    if ( meta.isNamespaceAware() ) {
      xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) );
      xpath.setNamespaceURIs( data.NAMESPACE );
    }
    // get nodes list
    data.an = xpath.selectNodes( data.document );
    data.nodesize = data.an.size();
    data.nodenr = 0;
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) );
    return false;
  }
  return true;
}
 
Example 5
Source File: Update1To2.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
private void convertModes(final Document doc) {
	XPath xpathSelector = DocumentHelper.createXPath("/settings/filters/filter/row");
	List<?> results = xpathSelector.selectNodes(doc);
	for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
		Element elem = (Element) iter.next();
		Attribute attr = elem.attribute("mode");
		String currentValue = attr.getText();
		attr.setText(convertMode(currentValue));
	}
}
 
Example 6
Source File: Update1To2.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
private void convertDefaultPriceModes(final Document doc) {
	XPath xpathSelector = DocumentHelper.createXPath("/settings/marketstat");
	List<?> results = xpathSelector.selectNodes(doc);
	for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
		Element elem = (Element) iter.next();
		Attribute attr = elem.attribute("defaultprice");
		if (attr != null) { //May not exist (in early versions)
			String currentValue = attr.getText();
			attr.setText(convertDefaultPriceMode(currentValue));
		}
	}
}
 
Example 7
Source File: SearchProxy.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void writeResponse(InputStream input, OutputStream output)
    throws IOException
{
    if (response.getContentType().startsWith(MimetypeMap.MIMETYPE_ATOM) ||
        response.getContentType().startsWith(MimetypeMap.MIMETYPE_RSS))
    {
        // Only post-process ATOM and RSS feeds
        // Replace all navigation links with "proxied" versions
        SAXReader reader = new SAXReader();
        try
        {
            Document document = reader.read(input);
            Element rootElement = document.getRootElement();

            XPath xpath = rootElement.createXPath(ATOM_LINK_XPATH);
            Map<String,String> uris = new HashMap<String,String>();
            uris.put(ATOM_NS_PREFIX, ATOM_NS_URI);
            xpath.setNamespaceURIs(uris);

            List nodes = xpath.selectNodes(rootElement);
            Iterator iter = nodes.iterator();
            while (iter.hasNext())
            {
                Element element = (Element)iter.next();
                Attribute hrefAttr = element.attribute("href");
                String mimetype = element.attributeValue("type");
                if (mimetype == null || mimetype.length() == 0)
                {
                    mimetype = MimetypeMap.MIMETYPE_HTML;
                }
                String url = createUrl(engine, hrefAttr.getValue(), mimetype);
                if (url.startsWith("/"))
                {
                    url = rootPath + url;
                }
                hrefAttr.setValue(url);
            }
            
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(output, outputFormat);
            writer.write(rootElement);
            writer.flush();                
        }
        catch(DocumentException e)
        {
            throw new IOException(e.toString());
        }
    }
    else
    {
        super.writeResponse(input, output);
    }
}
 
Example 8
Source File: ImsCPFileResource.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Check for title and at least one resource.
 * 
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    final Map nsuris = new HashMap(1);
    nsuris.put("ns", nsuri);

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource>, which will serve as an entry point.
    // This is mandatory, as we need an entry point as the user has the option of setting
    // CPDisplayController to not display a menu at all, in which case the first <item>/<resource>
    // element pair gets displayed.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("resource.no.item"); // no <item> element.
    }
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        if (elResource.attribute("scormtype") != null) {
            return false;
        }
        if (elResource.attribute("scormType") != null) {
            return false;
        }
        if (elResource.attribute("SCORMTYPE") != null) {
            return false;
        }
        if (elResource.attributeValue("href") != null) {
            return true; // success.
        }
    }
    return false;
    // throw new AddingResourceException("resource.general.error");
}
 
Example 9
Source File: ScormCPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor of the content packaging tree model
 * 
 * @param scormFolderPath
 *            the imsmanifest.xml file
 * @param itemStatus
 *            a Map containing the status of each item like "completed, not attempted, ..."
 */
public ScormCPManifestTreeModel(final String scormFolderPath, final Map itemStatus) {
    ScormEBL scormEbl = CoreSpringFactory.getBean(ScormEBL.class);
    this.itemStatus = itemStatus;
    final Document doc = loadDocument(scormEbl.getManifestFile(scormFolderPath));
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);

    final XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    final Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AssertException("could not find element resources");
    }

    final List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (final Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        final Element elRes = (Element) iter.next();
        final String identVal = elRes.attributeValue("identifier");
        String hrefVal = elRes.attributeValue("href");
        if (hrefVal != null) { // href is optional element for resource element
            try {
                hrefVal = URLDecoder.decode(hrefVal, "UTF-8");
            } catch (final UnsupportedEncodingException e) {
                // each JVM must implement UTF-8
            }
        }
        resources.put(identVal, hrefVal);
    }
    /*
     * Get all organizations
     */
    List organizations = new LinkedList();
    organizations = meta.selectNodes(rootElement);
    if (organizations.isEmpty()) {
        throw new AssertException("could not find element organization");
    }
    final GenericTreeNode gtn = buildTreeNodes(organizations);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}
 
Example 10
Source File: ImsCPFileResource.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Check for title and at least one resource.
 * 
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    final Map nsuris = new HashMap(1);
    nsuris.put("ns", nsuri);

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource>, which will serve as an entry point.
    // This is mandatory, as we need an entry point as the user has the option of setting
    // CPDisplayController to not display a menu at all, in which case the first <item>/<resource>
    // element pair gets displayed.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("resource.no.item"); // no <item> element.
    }
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        if (elResource.attribute("scormtype") != null) {
            return false;
        }
        if (elResource.attribute("scormType") != null) {
            return false;
        }
        if (elResource.attribute("SCORMTYPE") != null) {
            return false;
        }
        if (elResource.attributeValue("href") != null) {
            return true; // success.
        }
    }
    return false;
    // throw new AddingResourceException("resource.general.error");
}
 
Example 11
Source File: ScormCPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor of the content packaging tree model
 * 
 * @param scormFolderPath
 *            the imsmanifest.xml file
 * @param itemStatus
 *            a Map containing the status of each item like "completed, not attempted, ..."
 */
public ScormCPManifestTreeModel(final String scormFolderPath, final Map itemStatus) {
    ScormEBL scormEbl = CoreSpringFactory.getBean(ScormEBL.class);
    this.itemStatus = itemStatus;
    final Document doc = loadDocument(scormEbl.getManifestFile(scormFolderPath));
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);

    final XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    final Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AssertException("could not find element resources");
    }

    final List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (final Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        final Element elRes = (Element) iter.next();
        final String identVal = elRes.attributeValue("identifier");
        String hrefVal = elRes.attributeValue("href");
        if (hrefVal != null) { // href is optional element for resource element
            try {
                hrefVal = URLDecoder.decode(hrefVal, "UTF-8");
            } catch (final UnsupportedEncodingException e) {
                // each JVM must implement UTF-8
            }
        }
        resources.put(identVal, hrefVal);
    }
    /*
     * Get all organizations
     */
    List organizations = new LinkedList();
    organizations = meta.selectNodes(rootElement);
    if (organizations.isEmpty()) {
        throw new AssertException("could not find element organization");
    }
    final GenericTreeNode gtn = buildTreeNodes(organizations);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}