org.dom4j.XPath Java Examples

The following examples show how to use org.dom4j.XPath. 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: 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 #2
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 #3
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 #4
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 #5
Source File: MeijoFormat.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private XPath makeFaceNeighbourXPath(int edgeID, int faceID) {
    String path = FACE_NEIGHBOUR_XPATH_STRING.replace("$edgeid", String.valueOf(edgeID)).replace("$faceid", String.valueOf(faceID));
    //        Logger.debug("Neighbour XPath: " + path);
    XPath result = DocumentHelper.createXPath(path);
    result.setNamespaceURIs(URIS);
    return result;
}
 
Example #6
Source File: CPManifestTreeModel.java    From olat with Apache License 2.0 5 votes vote down vote up
private GenericTreeNode buildNode(final Element item) {
    final GenericTreeNode gtn = new GenericTreeNode();

    // extract title
    String title = item.elementText("title");
    if (title == null) {
        title = item.attributeValue("identifier");
    }
    gtn.setAltText(title);
    gtn.setTitle(title);

    if (item.getName().equals("organization")) {
        gtn.setIconCssClass("o_cp_org");
        gtn.setAccessible(false);
    } else if (item.getName().equals("item")) {
        gtn.setIconCssClass("o_cp_item");
        // set resolved file path directly
        final String identifierref = item.attributeValue("identifierref");
        final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        meta.setNamespaceURIs(nsuris);
        final String href = (String) resources.get(identifierref);
        if (href != null) {
            gtn.setUserObject(href);
            // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text
            hrefToTreeNode.put(href, gtn);
        } else {
            gtn.setAccessible(false);
        }
    }

    final List chds = item.elements("item");
    final int childcnt = chds.size();
    for (int i = 0; i < childcnt; i++) {
        final Element childitem = (Element) chds.get(i);
        final GenericTreeNode gtnchild = buildNode(childitem);
        gtn.addChild(gtnchild);
    }
    return gtn;
}
 
Example #7
Source File: CPManifestTreeModel.java    From olat with Apache License 2.0 5 votes vote down vote up
private GenericTreeNode buildNode(final Element item) {
    final GenericTreeNode gtn = new GenericTreeNode();

    // extract title
    String title = item.elementText("title");
    if (title == null) {
        title = item.attributeValue("identifier");
    }
    gtn.setAltText(title);
    gtn.setTitle(title);

    if (item.getName().equals("organization")) {
        gtn.setIconCssClass("o_cp_org");
        gtn.setAccessible(false);
    } else if (item.getName().equals("item")) {
        gtn.setIconCssClass("o_cp_item");
        // set resolved file path directly
        final String identifierref = item.attributeValue("identifierref");
        final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        meta.setNamespaceURIs(nsuris);
        final String href = (String) resources.get(identifierref);
        if (href != null) {
            gtn.setUserObject(href);
            // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text
            hrefToTreeNode.put(href, gtn);
        } else {
            gtn.setAccessible(false);
        }
    }

    final List chds = item.elements("item");
    final int childcnt = chds.size();
    for (int i = 0; i < childcnt; i++) {
        final Element childitem = (Element) chds.get(i);
        final GenericTreeNode gtnchild = buildNode(childitem);
        gtn.addChild(gtnchild);
    }
    return gtn;
}
 
Example #8
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 #9
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 #10
Source File: MeijoFormat.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Pair<List<GMLDirectedEdge>, List<Integer>> readEdges(Element e, GMLMap map, int faceID) {
    List<GMLDirectedEdge> edges = new ArrayList<GMLDirectedEdge>();
    List<Integer> neighbours = new ArrayList<Integer>();

    //        Logger.debug("Reading edges for face " + faceID);
    for (Object next : e.elements(Common.GML_DIRECTED_EDGE_QNAME)) {
        Element dEdge = (Element)next;
        boolean passable = "+".equals(dEdge.attributeValue(Common.GML_ORIENTATION_QNAME));
        int edgeID = Integer.parseInt(dEdge.attributeValue(Common.XLINK_HREF_QNAME).substring(1));
        //            Logger.debug("Edge ID: " + edgeID);
        //            Logger.debug("Passable? " + passable);
        edges.add(new GMLDirectedEdge(map.getEdge(edgeID), true));
        XPath xpath = makeFaceNeighbourXPath(edgeID, faceID);
        //            FACE_NEIGHBOUR_XPATH_CONTEXT.setVariableValue("edgeid", String.valueOf(edgeID));
        //            FACE_NEIGHBOUR_XPATH_CONTEXT.setVariableValue("faceid", String.valueOf(faceID));
        Object o = xpath.evaluate(e);
        //            Logger.debug("Neighbours: " + o);
        if (o == null) {
            neighbours.add(null);
        }
        else if (o instanceof Collection && ((Collection)o).isEmpty()) {
            neighbours.add(null);
        }
        else {
            int neighbourID = Integer.parseInt(((Attribute)o).getValue().substring(1));
            neighbours.add(neighbourID);
        }
        //            Logger.debug("Edge list     : " + edges);
        //            Logger.debug("Neighbour list: " + neighbours);
    }
    //        Logger.debug("Finished reading edges for face " + faceID);
    return new Pair<List<GMLDirectedEdge>, List<Integer>>(edges, neighbours);
}
 
Example #11
Source File: Dom4jProxy.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public XPath createXPath(String xpath) throws InvalidXPathException {
	return target().createXPath( xpath );
}
 
Example #12
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 #13
Source File: Parameter.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception
  {
// remove beginning to '<' character
int iPosBegin = xml.indexOf('<');
if (iPosBegin > 0)
{
	xml = xml.substring(iPosBegin);
}
// remove from '>' character to the end
int iPosEnd = xml.lastIndexOf('>');
if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1))
{
	xml = xml.substring(0, iPosEnd + 1);
}

int iPosXMLLine = xml.indexOf("<?xml");
if (iPosXMLLine < 0)
{
	// when java writes string, it is in ISO-8859-nn format
	xml = "<?xml version='1.0' encoding=\"ISO-8859-15\"?>\n" + xml;
}

// remove the namespace because the parser does not support them if there are not declare in the root node
if (deleteNS)
{
	xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<");
	xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</");
}
// remove doctype information (dtd files for the XML syntax)
xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", "");

InputStream input = new ByteArrayInputStream(xml.getBytes());
   SAXReader reader = new SAXReader(false);
   reader.setEntityResolver(new XMLLoaderEntityResolver());
   Document document = reader.read(input);
   
   XPath xpathObject = document.createXPath(xpath);
   Object obj = xpathObject.evaluate(document.getRootElement());
	
   if (obj instanceof List)
   {
       List<Node> list = (List<Node>) obj;
       for (Node node : list)
       {
       	addObject(node);
       }
   }
   else 
   {
   	addObject(obj);
   }
  }
 
Example #14
Source File: CPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor of the content packaging tree model
 * 
 * @param manifest
 *            the imsmanifest.xml file
 */
public CPManifestTreeModel(final VFSLeaf manifest) {
    final Document doc = loadDocument(manifest);
    // 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 Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AssertException("could not find element organization");
    }

    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);
    }
    final GenericTreeNode gtn = buildNode(orgaEl);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}
 
Example #15
Source File: ElementWrapper.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public XPath createXPath(String xpath) throws InvalidXPathException {
	return element.createXPath( xpath );
}
 
Example #16
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 #17
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 #18
Source File: ScormCPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
private GenericTreeNode buildNode(final Element item) {
    final GenericTreeNode treeNode = new GenericTreeNode();

    // extract title
    String title = item.elementText("title");
    if (title == null) {
        title = item.attributeValue("identifier");
    }
    treeNode.setAltText(title);
    treeNode.setTitle(title);

    if (item.getName().equals("organization")) {
        treeNode.setIconCssClass("o_scorm_org");
        treeNode.setAccessible(false);
    } else if (item.getName().equals("item")) {
        scormIdToNode.put(new Integer(nodeId).toString(), treeNode);
        nodeToId.put(treeNode, new Integer(nodeId));

        // set node images according to scorm sco status
        final String itemStatusDesc = (String) itemStatus.get(Integer.toString(nodeId));
        treeNode.setIconCssClass("o_scorm_item");
        if (itemStatusDesc != null) {
            // add icon decorator for current status
            treeNode.setIconDecorator1CssClass("o_scorm_" + itemStatusDesc);
        }

        nodeId++;
        // set resolved file path directly
        final String identifierref = item.attributeValue("identifierref");
        final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        meta.setNamespaceURIs(nsuris);
        final String href = (String) resources.get(identifierref);
        if (href != null) {
            treeNode.setUserObject(href);
            // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text
            hrefToTreeNode.put(href, treeNode);
        } else {
            treeNode.setAccessible(false);
        }
    }

    final List chds = item.elements("item");
    final int childcnt = chds.size();
    for (int i = 0; i < childcnt; i++) {
        final Element childitem = (Element) chds.get(i);
        final GenericTreeNode gtnchild = buildNode(childitem);
        treeNode.addChild(gtnchild);
    }
    return treeNode;
}
 
Example #19
Source File: CPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor of the content packaging tree model
 * 
 * @param manifest
 *            the imsmanifest.xml file
 */
public CPManifestTreeModel(final VFSLeaf manifest) {
    final Document doc = loadDocument(manifest);
    // 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 Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AssertException("could not find element organization");
    }

    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);
    }
    final GenericTreeNode gtn = buildNode(orgaEl);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}
 
Example #20
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 #21
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 #22
Source File: ScormCPManifestTreeModel.java    From olat with Apache License 2.0 4 votes vote down vote up
private GenericTreeNode buildNode(final Element item) {
    final GenericTreeNode treeNode = new GenericTreeNode();

    // extract title
    String title = item.elementText("title");
    if (title == null) {
        title = item.attributeValue("identifier");
    }
    treeNode.setAltText(title);
    treeNode.setTitle(title);

    if (item.getName().equals("organization")) {
        treeNode.setIconCssClass("o_scorm_org");
        treeNode.setAccessible(false);
    } else if (item.getName().equals("item")) {
        scormIdToNode.put(new Integer(nodeId).toString(), treeNode);
        nodeToId.put(treeNode, new Integer(nodeId));

        // set node images according to scorm sco status
        final String itemStatusDesc = (String) itemStatus.get(Integer.toString(nodeId));
        treeNode.setIconCssClass("o_scorm_item");
        if (itemStatusDesc != null) {
            // add icon decorator for current status
            treeNode.setIconDecorator1CssClass("o_scorm_" + itemStatusDesc);
        }

        nodeId++;
        // set resolved file path directly
        final String identifierref = item.attributeValue("identifierref");
        final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        meta.setNamespaceURIs(nsuris);
        final String href = (String) resources.get(identifierref);
        if (href != null) {
            treeNode.setUserObject(href);
            // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text
            hrefToTreeNode.put(href, treeNode);
        } else {
            treeNode.setAccessible(false);
        }
    }

    final List chds = item.elements("item");
    final int childcnt = chds.size();
    for (int i = 0; i < childcnt; i++) {
        final Element childitem = (Element) chds.get(i);
        final GenericTreeNode gtnchild = buildNode(childitem);
        treeNode.addChild(gtnchild);
    }
    return treeNode;
}
 
Example #23
Source File: VersionedXmlDoc.java    From onedev with MIT License 4 votes vote down vote up
public XPath createXPath(String xpathExpression)
		throws InvalidXPathException {
	return getWrapped().createXPath(xpathExpression);
}