Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

In this page you can find the example usage for org.dom4j Element elements.

Prototype

List<Element> elements(QName qName);

Source Link

Document

Returns the elements contained in this element with the given fully qualified name.

Usage

From source file:com.devoteam.srit.xmlloader.ucp.data.UcpMessage.java

License:Open Source License

public void parseAttributes(Element root) throws Exception {
    List<Element> attributes = root.elements("attribute");
    List<Element> imbricateAttributes = null;
    List<Element> xserAttributes = null;
    UcpAttribute att = null;/*from w w  w .  j a  va 2 s. c o m*/
    UcpAttribute att2 = null;

    for (Element element : attributes) {
        att = new UcpAttribute();
        att.setName(element.attributeValue("name"));

        //check imbricate attribute + extra service(xser) to send
        imbricateAttributes = element.selectNodes("attribute");
        xserAttributes = element.selectNodes("xser");

        if (imbricateAttributes.size() != 0) {
            att.setValue(new Vector<UcpAttribute>());
            for (Element element2 : imbricateAttributes) {
                att2 = new UcpAttribute();
                att2.setName(element2.attributeValue("name"));
                att2.setValue(element2.attributeValue("value"));
                ((Vector<UcpAttribute>) att.getValue()).add(att2);
            }
        } else if (xserAttributes.size() != 0) {
            parseXser(xserAttributes, att);
        } else {
            String encoding = element.attributeValue("encoding");
            if ((encoding != null) && (encoding.equalsIgnoreCase("true"))) {
                att.setFormat("encodedString");
            }
            att.setValue(element.attributeValue("value"));
        }
        this.addAttribute(att);
    }
}

From source file:com.devoteam.srit.xmlloader.ucp.MsgUcp.java

License:Open Source License

private void parseAttributes(Element root, UcpMessage msg) throws Exception {
    List<Element> attributes = root.elements("attribute");
    List<Element> imbricateAttributes = null;
    List<Element> xserAttributes = null;
    UcpAttribute att = null;/*from  ww  w  . j  ava2 s. co  m*/
    UcpAttribute att2 = null;

    for (Element element : attributes) {
        att = new UcpAttribute();
        att.setName(element.attributeValue("name"));

        //check imbricate attribute + extra service(xser) to send
        imbricateAttributes = element.selectNodes("attribute");
        xserAttributes = element.selectNodes("xser");

        if (imbricateAttributes.size() != 0) {
            att.setValue(new Vector<UcpAttribute>());
            for (Element element2 : imbricateAttributes) {
                att2 = new UcpAttribute();
                att2.setName(element2.attributeValue("name"));
                att2.setValue(element2.attributeValue("value"));
                ((Vector<UcpAttribute>) att.getValue()).add(att2);
            }
        } else if (xserAttributes.size() != 0) {
            parseXser(xserAttributes, att);
        } else {
            String encoding = element.attributeValue("encoding");
            if ((encoding != null) && (encoding.equalsIgnoreCase("true"))) {
                att.setFormat("encodedString");
            }
            att.setValue(element.attributeValue("value"));
        }
        msg.addAttribute(att);
    }
}

From source file:com.devoteam.srit.xmlloader.ucp.StackUcp.java

License:Open Source License

public void parseAttributes(Element root, UcpMessage msg) throws Exception {
    List<Element> attributes = root.elements("attribute");
    List<Element> imbricateAttributes = null;
    List<Element> xserAttributes = null;
    UcpAttribute att = null;/*from w  ww  . java 2  s.c om*/
    UcpAttribute att2 = null;

    for (Element element : attributes) {
        att = new UcpAttribute();
        att.setName(element.attributeValue("name"));

        //check imbricate attribute + extra service(xser) to send
        imbricateAttributes = element.selectNodes("attribute");
        xserAttributes = element.selectNodes("xser");

        if (imbricateAttributes.size() != 0) {
            att.setValue(new Vector<UcpAttribute>());
            for (Element element2 : imbricateAttributes) {
                att2 = new UcpAttribute();
                att2.setName(element2.attributeValue("name"));
                att2.setValue(element2.attributeValue("value"));
                ((Vector<UcpAttribute>) att.getValue()).add(att2);
            }
        } else if (xserAttributes.size() != 0) {
            parseXser(xserAttributes, att);
        } else {
            String encoding = element.attributeValue("encoding");
            if ((encoding != null) && (encoding.equalsIgnoreCase("true"))) {
                att.setFormat("encodedString");
            }
            att.setValue(element.attributeValue("value"));
        }
        msg.addAttribute(att);
    }
}

From source file:com.devoteam.srit.xmlloader.udp.MsgUdp.java

License:Open Source License

/** 
 * Parse the message from XML element /*from   w  ww. j a v a  2 s. c  o m*/
 */
@Override
public void parseFromXml(Boolean request, Element root, Runner runner) throws Exception {
    List<Element> elements = root.elements("data");
    List<byte[]> datas = new LinkedList<byte[]>();

    try {
        for (Element element : elements) {
            if (element.attributeValue("format").equalsIgnoreCase("text")) {
                String text = element.getText();
                // change the \n caractre to \r\n caracteres because the dom librairy return only \n.
                // this could make some trouble when the length is calculated in the scenario
                text = Utils.replaceNoRegex(text, "\r\n", "\n");
                text = Utils.replaceNoRegex(text, "\n", "\r\n");
                datas.add(text.getBytes("UTF8"));
            } else if (element.attributeValue("format").equalsIgnoreCase("binary")) {
                String text = element.getTextTrim();
                datas.add(Utils.parseBinaryString(text));
            }
        }
    } catch (Exception e) {
        throw new ExecutionException("StackUDP: Error while parsing data", e);
    }

    //
    // Compute total length
    //
    int dataLength = 0;
    for (byte[] data : datas) {
        dataLength += data.length;
    }

    this.data = new byte[dataLength];
    int i = 0;
    for (byte[] aData : datas) {
        for (int j = 0; j < aData.length; j++) {
            this.data[i] = aData[j];
            i++;
        }
    }

    String length = root.attributeValue("length");
    if (length != null) {
        dataLength = Integer.parseInt(length);
        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                "fixed length of the datagramPacket to be sent:  ", dataLength);
        if (this.data.length != dataLength) {
            GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
                    "data.length different from chosen fixed length");
        }
    }
}

From source file:com.devoteam.srit.xmlloader.udp.StackUdp.java

License:Open Source License

/** Creates a specific Msg */
@Override/*w  w  w  .  j  a  v  a  2  s .c o m*/
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    //
    // Parse all <data ... /> tags
    //
    List<Element> elements = root.elements("data");
    List<byte[]> datas = new LinkedList<byte[]>();

    try {
        for (Element element : elements) {
            if (element.attributeValue("format").equalsIgnoreCase("text")) {
                String text = element.getText();
                // change the \n caractre to \r\n caracteres because the dom librairy return only \n.
                // this could make some trouble when the length is calculated in the scenario
                text = Utils.replaceNoRegex(text, "\r\n", "\n");
                text = Utils.replaceNoRegex(text, "\n", "\r\n");
                datas.add(text.getBytes("UTF8"));
            } else if (element.attributeValue("format").equalsIgnoreCase("binary")) {
                String text = element.getTextTrim();
                datas.add(Utils.parseBinaryString(text));
            }
        }
    } catch (Exception e) {
        throw new ExecutionException("StackUDP: Error while parsing data", e);
    }

    //
    // Compute total length
    //
    int dataLength = 0;
    for (byte[] data : datas) {
        dataLength += data.length;
    }

    byte[] data = new byte[dataLength];
    int i = 0;
    for (byte[] aData : datas) {
        for (int j = 0; j < aData.length; j++) {
            data[i] = aData[j];
            i++;
        }
    }

    String length = root.attributeValue("length");
    if (length != null) {
        dataLength = Integer.parseInt(length);
        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL,
                "fixed length of the datagramPacket to be sent:  ", dataLength);
        if (data.length != dataLength) {
            GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL,
                    "data.length different from chosen fixed length");
        }
    }

    MsgUdp msgUdp = new MsgUdp(data, dataLength);

    String remoteHost = root.attributeValue("remoteHost");
    String remotePort = root.attributeValue("remotePort");

    // deprecated part //
    String name = root.attributeValue("socketName");
    if (name != null) {
        Channel channel = getChannel(name);
        if (channel == null) {
            throw new ExecutionException("StackUDP: The connection <name=" + name + "> does not exist");
        }

        if (remoteHost != null) {
            channel.setRemoteHost(remoteHost);
        }
        if (remotePort != null) {
            channel.setRemotePort(new Integer(remotePort).intValue());
        }
        msgUdp.setChannel(channel);
    } // deprecated part //
    else {
        name = root.attributeValue("listenpoint");
        Listenpoint listenpoint = getListenpoint(name);
        if (listenpoint == null) {
            throw new ExecutionException("StackUDP: The listenpoint <name=" + name + "> does not exist");
        }

        if (remoteHost != null) {
            msgUdp.setRemoteHost(remoteHost);
        }
        if (remotePort != null) {
            msgUdp.setRemotePort(new Integer(remotePort).intValue());
        }
        msgUdp.setListenpoint(listenpoint);
    }

    return msgUdp;
}

From source file:com.digiaplus.modules.scorm.ScormCPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * @param manifest the imsmanifest.xml file
 * @param itemStatus a Map containing the status of each item like "completed, not attempted, ..."
 *///w ww.j a va  2s  .c  om
public ScormCPManifestTreeModel(File manifest, Map itemStatus) {
    this.itemStatus = itemStatus;
    Document doc = loadDocument(manifest);
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

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

    XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null)
        throw new DAPRuntimeException(this.getClass(), "could not find element resources");

    List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        Element elRes = (Element) iter.next();
        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 (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 DAPRuntimeException(this.getClass(), "could not find element organization");
    }
    GenericTreeNode gtn = buildTreeNodes(organizations);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}

From source file:com.digiaplus.modules.scorm.ScormCPManifestTreeModel.java

License:Apache License

private GenericTreeNode buildNode(Element item) {
    GenericTreeNode treeNode = new GenericTreeNode();

    // extract title
    String title = item.elementText("title");
    if (title == null)
        title = item.attributeValue("identifier");
    treeNode.setAltText(title);//from  w ww  . ja v  a2s  . c  om
    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
        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
        String identifierref = item.attributeValue("identifierref");
        XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        meta.setNamespaceURIs(nsuris);
        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);
    }

    List chds = item.elements("item");
    int childcnt = chds.size();
    for (int i = 0; i < childcnt; i++) {
        Element childitem = (Element) chds.get(i);
        GenericTreeNode gtnchild = buildNode(childitem);
        treeNode.addChild(gtnchild);
    }
    return treeNode;
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from ww w . j  a v  a 2s.c  om
public List<Record> authorizeByConnector(List<Record> records, Collection<UserCredentials> userCredentialsList,
        ConnectorManager connectorManager) {
    List<Record> authorizedRecords = new ArrayList<Record>();

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(ServletUtil.XMLTAG_AUTHZ_QUERY);
    Element connectorQueryElement = root.addElement(ServletUtil.XMLTAG_CONNECTOR_QUERY);

    Map<ConnectorInstance, UserCredentials> credentialsMap = new HashMap<ConnectorInstance, UserCredentials>();
    Set<ConnectorInstance> connectorsWithoutCredentials = new HashSet<ConnectorInstance>();
    Map<String, Record> recordsByURLMap = new HashMap<String, Record>();
    boolean recordToValidate = false;
    for (Record record : records) {
        // Use to accelerate the matching between response urls and actual entities
        recordsByURLMap.put(record.getUrl(), record);
        ConnectorInstance connectorInstance = record.getConnectorInstance();
        UserCredentials connectorCredentials = credentialsMap.get(connectorInstance);
        if (connectorCredentials == null && !connectorsWithoutCredentials.contains(connectorInstance)) {
            RecordCollection collection = connectorInstance.getRecordCollection();
            for (CredentialGroup credentialGroup : collection.getCredentialGroups()) {
                if (credentialGroup.getConnectorInstances().contains(connectorInstance)) {
                    for (UserCredentials userCredentials : userCredentialsList) {
                        if (userCredentials.getCredentialGroup().equals(credentialGroup)) {
                            connectorCredentials = userCredentials;
                            credentialsMap.put(connectorInstance, userCredentials);
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (connectorCredentials == null) {
            connectorsWithoutCredentials.add(connectorInstance);
            LOGGER.warning("Missing credentials for connector " + connectorInstance.getName());
        } else {
            String username = connectorCredentials.getUsername();
            if (StringUtils.isNotBlank(username)) {
                String password = EncryptionUtils.decrypt(connectorCredentials.getEncryptedPassword());
                String domain = connectorCredentials.getDomain();
                Element identityElement = connectorQueryElement.addElement(ServletUtil.XMLTAG_IDENTITY);
                identityElement.setText(username);
                if (StringUtils.isNotBlank(domain)) {
                    identityElement.addAttribute(ServletUtil.XMLTAG_DOMAIN_ATTRIBUTE, domain);
                }
                identityElement.addAttribute(ServletUtil.XMLTAG_PASSWORD_ATTRIBUTE, password);

                Element resourceElement = identityElement.addElement(ServletUtil.XMLTAG_RESOURCE);
                resourceElement.setText(record.getUrl());
                resourceElement.addAttribute(ServletUtil.XMLTAG_CONNECTOR_NAME_ATTRIBUTE,
                        connectorInstance.getName());
                recordToValidate = true;
            }
        }
    }

    if (recordToValidate) {
        Element response = ConnectorManagerRequestUtils.sendPost(connectorManager, "/authorization", document);
        Element authzResponseElement = response.element(ServletUtil.XMLTAG_AUTHZ_RESPONSE);
        List<Element> answerElements = authzResponseElement.elements(ServletUtil.XMLTAG_ANSWER);
        for (Element answerElement : answerElements) {
            Element decisionElement = answerElement.element(ServletUtil.XMLTAG_DECISION);
            boolean permit = decisionElement.getTextTrim().equals("Permit");
            if (permit) {
                Element resourceElement = answerElement.element(ServletUtil.XMLTAG_RESOURCE);
                String recordUrl = resourceElement.getTextTrim();
                Record record = recordsByURLMap.get(recordUrl);
                authorizedRecords.add(record);
            }
        }
    }
    return authorizedRecords;
}

From source file:com.doculibre.constellio.services.ElevateServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private synchronized void readCache(String collectionName) {
    Map<String, List<String>> solrCoreElevationCache = elevationCache.get(collectionName);
    if (solrCoreElevationCache == null) {
        solrCoreElevationCache = new HashMap<String, List<String>>();
        elevationCache.put(collectionName, solrCoreElevationCache);

        Map<String, List<String>> solrCoreExclusionCache = new HashMap<String, List<String>>();
        exclusionCache.put(collectionName, solrCoreExclusionCache);

        Document document = SolrServicesImpl.readXMLConfigInCloud(collectionName, "elevate.xml");

        Element rootElement = document.getRootElement();
        for (Element queryElement : (List<Element>) rootElement.elements("query")) {
            String queryText = queryElement.attributeValue("text");
            String queryDisplayText = queryElement.attributeValue("displayText");
            if (queryDisplayText != null && displayQueriesCache.get(queryText) == null) {
                displayQueriesCache.put(queryText, queryDisplayText);
            }/*from w  ww  .  j av a 2 s. c o  m*/

            List<String> elevatedDocIds = new ArrayList<String>();
            List<String> excludedDocIds = new ArrayList<String>();

            for (Element docElement : (List<Element>) queryElement.elements("doc")) {
                String docId = docElement.attributeValue("id");
                if ("true".equals(docElement.attributeValue("exclude"))) {
                    excludedDocIds.add(docId);
                } else {
                    elevatedDocIds.add(docId);
                }
            }
            if (!elevatedDocIds.isEmpty()) {
                solrCoreElevationCache.put(queryText, elevatedDocIds);
            }
            if (!excludedDocIds.isEmpty()) {
                solrCoreExclusionCache.put(queryText, excludedDocIds);
            }
        }
    }
}

From source file:com.doculibre.constellio.services.SolrServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private void updateSchemaFields(RecordCollection collection, Document schemaDocument) {
    Element fieldsElement = schemaDocument.getRootElement().element("fields");
    List<Element> fieldElements = fieldsElement.elements("field");
    for (Iterator<Element> it = fieldElements.iterator(); it.hasNext();) {
        it.next();//from  w  w  w .  j  a va  2 s .  co  m
        it.remove();
    }

    List<Element> copyFields = schemaDocument.getRootElement().elements("copyField");
    for (Iterator<Element> it = copyFields.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<Element> dynamicFieldElements = fieldsElement.elements("dynamicField");
    for (Iterator<Element> it = dynamicFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }

    List<String> addedFieldNames = new ArrayList<String>();
    Collection<IndexField> indexFields = collection.getIndexFields();
    for (IndexField indexField : indexFields) {
        if (!addedFieldNames.contains(indexField.getName())) {
            addedFieldNames.add(indexField.getName());

            FieldType fieldType = indexField.getFieldType();
            Analyzer analyzer = indexField.getAnalyzer();
            if (fieldType == null) {
                throw new RuntimeException(indexField.getName() + " has no type");
            }
            Element fieldElement;
            if (indexField.isDynamicField()) {
                fieldElement = DocumentHelper.createElement("dynamicField");
            } else {
                fieldElement = DocumentHelper.createElement("field");
            }
            fieldsElement.add(fieldElement);
            addNotNullAttribute(fieldElement, "name", indexField.getName());
            addNotNullAttribute(fieldElement, "type", fieldType.getName());
            addNotNullAttribute(fieldElement, "indexed", indexField.isIndexed());
            addNotNullAttribute(fieldElement, "stored", true);
            addNotNullAttribute(fieldElement, "multiValued", indexField.isMultiValued());
            if (analyzer != null) {
                fieldElement.addAttribute("analyzer", analyzer.getAnalyzerClass().getClassName());
            }
        }
    }

    // used by solrcloud
    Element fieldElement = DocumentHelper.createElement("field");
    addNotNullAttribute(fieldElement, "name", "_version_");
    addNotNullAttribute(fieldElement, "type", "long");
    addNotNullAttribute(fieldElement, "indexed", true);
    addNotNullAttribute(fieldElement, "stored", true);
    fieldsElement.add(fieldElement);

    List<Element> uniqueKeyElements = schemaDocument.getRootElement().elements("uniqueKey");
    for (Iterator<Element> it = uniqueKeyElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
    if (uniqueKeyField != null) {
        Element uniqueKeyElement = DocumentHelper.createElement("uniqueKey");
        uniqueKeyElement.setText(uniqueKeyField.getName());
        schemaDocument.getRootElement().add(uniqueKeyElement);
    }

    List<Element> defaultSearchFieldElements = schemaDocument.getRootElement().elements("defaultSearchField");
    for (Iterator<Element> it = defaultSearchFieldElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    IndexField defaultSearchField = collection.getDefaultSearchIndexField();
    if (defaultSearchField != null) {
        Element defaultSearchFieldElement = DocumentHelper.createElement("defaultSearchField");
        defaultSearchFieldElement.setText(defaultSearchField.getName());
        schemaDocument.getRootElement().add(defaultSearchFieldElement);
    }

    List<Element> solrQueryParserElements = schemaDocument.getRootElement().elements("solrQueryParser");
    for (Iterator<Element> it = solrQueryParserElements.iterator(); it.hasNext();) {
        it.next();
        it.remove();
    }
    String queryParserOperator = collection.getQueryParserOperator();
    if (queryParserOperator != null) {
        Element solrQueryParserElement = DocumentHelper.createElement("solrQueryParser");
        solrQueryParserElement.addAttribute("defaultOperator", queryParserOperator);
        schemaDocument.getRootElement().add(solrQueryParserElement);
    }

    for (IndexField indexField : indexFields) {
        if (!indexField.isDynamicField()) {
            for (CopyField copyFieldDest : indexField.getCopyFieldsDest()) {
                Element copyFieldElement = DocumentHelper.createElement("copyField");
                String source;
                if (copyFieldDest.isSourceAllFields()) {
                    source = "*";
                } else {
                    IndexField indexFieldSource = copyFieldDest.getIndexFieldSource();
                    source = indexFieldSource.getName();
                }
                copyFieldElement.addAttribute("source", source);
                copyFieldElement.addAttribute("dest", copyFieldDest.getIndexFieldDest().getName());
                addNotNullAttribute(copyFieldElement, "maxChars", copyFieldDest);
                // Ajout Rida
                schemaDocument.getRootElement().add(copyFieldElement);
            }
        }
    }

    writeSchema(collection.getName(), schemaDocument);
}