Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

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

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

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

License:Open Source License

/** Creates a Channel specific to each Stack */
@Override/*from  w ww  .j ava2s. c o m*/
public Channel parseChannelFromXml(Element root, String protocol) throws Exception {
    String name = root.attributeValue("name");
    String localHost = root.attributeValue("localHost");
    String localPort = root.attributeValue("localPort");
    String remoteHost = root.attributeValue("remoteHost");
    String remotePort = root.attributeValue("remotePort");

    if (existsChannel(name)) {
        return getChannel(name);
    } else {
        if (null != localHost)
            localHost = InetAddress.getByName(localHost).getHostAddress();
        else
            localHost = "0.0.0.0";

        if (null != remoteHost)
            remoteHost = InetAddress.getByName(remoteHost).getHostAddress();

        return new ChannelUcp(name, localHost, localPort, remoteHost, remotePort, protocol);
    }
}

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

License:Open Source License

/** Creates a specific Msg */
@Override/* w  w w .  j  a  v  a  2  s . c  om*/
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    UcpMessage ucpMessage = new UcpMessage();

    // header
    Element header = root.element("header");
    String msgName = header.attributeValue("name");
    String msgOT = header.attributeValue("OT");

    if ((msgOT != null) && (msgName != null))
        throw new Exception("OT and name of the message " + msgName + " must not be set both");

    if ((msgOT == null) && (msgName == null))
        throw new Exception("One of the parameter OT and name of the message header must be set");

    if (msgName != null) {
        ucpMessage.setName(msgName);
        ucpMessage.setOperationType(ucpDictionary.getMessageOperationTypeFromName(msgName));
        if (ucpMessage.getOperationType() == null)
            throw new Exception("Message <" + msgName + "> is unknown in the dictionary");
    }

    if (msgOT != null) {
        ucpMessage.setName(ucpDictionary.getMessageNameFromOperationType(msgOT));
        if (ucpMessage.getName() == null)
            throw new Exception("Message with OperationType <" + msgOT + "> is unknown in the dictionary");
        ucpMessage.setOperationType(msgOT);
    }

    ucpMessage.setMessageType(header.attributeValue("MT"));
    ucpMessage.setTransactionNumber(header.attributeValue("TRN"));

    parseAttributes(root, ucpMessage);
    ucpMessage.calculLength();//calcul the length with attribute from the attribute
    return new MsgUcp(ucpMessage);
}

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  w  w  .j a  v a  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"));
        }
        msg.addAttribute(att);
    }
}

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

License:Open Source License

private void parseFile(InputStream stream) throws Exception {
    Element messageElement = null;
    Element attributeElement = null;
    Element group = null;/*w w w. j a v a  2 s.c om*/
    UcpMessage msg = null;
    UcpAttribute att = null;
    UcpAttribute attImbricate = null;
    UcpChoice attChoice = null;
    UcpGroup attGroup = null;
    Vector<UcpGroup> choiceList = null;
    Vector<UcpAttribute> imbricateAtt = null;
    List groupList = null;
    int i = 0;
    int j = 0;
    int msgNumber = 0;
    String value = null;

    SAXReader reader = new SAXReader();
    Document document = reader.read(stream);

    //parsing des messages
    List listMessages = document.selectNodes("/dictionary/message");
    for (i = 0; i < listMessages.size(); i++) {
        messageElement = (Element) listMessages.get(i);

        msg = new UcpMessage();
        msg.setName(messageElement.attributeValue("name"));
        msg.setOperationType(messageElement.attributeValue("id"));
        value = messageElement.attributeValue("type");
        if (value.equals("operation")) {
            msg.setMessageType("O");
        } else if (value.equals("response")) {
            msg.setMessageType("R");
        }

        for (Iterator it = messageElement.elementIterator(); it.hasNext();) {
            attributeElement = (Element) it.next();
            value = attributeElement.getName();

            if (value.equals("attribute")) {
                att = setAttribute(attributeElement);

                //check if attribute imbricate in attribute
                List listAtt = attributeElement.selectNodes(
                        "//attribute[@name='" + attributeElement.attributeValue("name") + "']/attribute");
                if (listAtt.size() > 0) {
                    att.setValue(new Vector<UcpAttribute>());
                    for (j = 0; j < listAtt.size(); j++) {
                        attImbricate = setAttribute((Element) listAtt.get(j));
                        ((Vector<UcpAttribute>) att.getValue()).add(attImbricate);
                    }
                }
                msg.addAttribute(att);
            } else if (value.equals("choice")) {
                msgNumber = i + 1;
                groupList = attributeElement.selectNodes("/dictionary/message[" + msgNumber + "]/choice/group");
                choiceList = new Vector<UcpGroup>();

                attChoice = new UcpChoice();
                //work because att is the last attribute set and is the att base on choice
                attChoice.setChoiceAttribute(att);

                //parse all group of the choice, could be only an attribute or a group of attribute
                for (j = 0; j < groupList.size(); j++) {
                    group = (Element) groupList.get(j);
                    //create an attribute for each group
                    attGroup = new UcpGroup();

                    attGroup.setChoiceValue(group.attributeValue("value"));
                    imbricateAtt = new Vector<UcpAttribute>();

                    //parse attribute present in the group
                    for (Iterator iter = group.elementIterator(); iter.hasNext();) {
                        imbricateAtt.add(setAttribute((Element) iter.next()));
                    }

                    attGroup.setValue(imbricateAtt);
                    choiceList.add(attGroup);
                }
                attChoice.setValue(choiceList);
                msg.addAttribute(attChoice);
            }
        }

        if (msg.getMessageType().equals("O"))//operation = request
        {
            requestsList.put(msg.getName(), msg);
            //these two hashmap are used by the response or request
            messageOperationTypeToNameList.put(msg.getOperationType(), msg.getName());
            messageNameToOperationTypeList.put(msg.getName(), msg.getOperationType());
        } else if (msg.getMessageType().equals("R"))//response
        {
            if (msg.getAttribute("ACK") != null) {
                positivesResponsesList.put(msg.getName(), msg);
            } else if (msg.getAttribute("NACK") != null) {
                negativesResponsesList.put(msg.getName(), msg);
            }
        }
    }

    //        //affichage des message
    //        Collection<UcpMessage> collecMsg = requestsList.values();
    //        System.out.println("\r\nnb de message dans la collection de requetes: " + collecMsg.size());
    //        for(Iterator<UcpMessage> iter = collecMsg.iterator(); iter.hasNext();)
    //        {
    //            UcpMessage msgEle = (UcpMessage)iter.next();
    //            //affichage des attributs
    //            System.out.println(msgEle.toString());
    //        }
    //
    //        //affichage des message
    //        collecMsg = positivesResponsesList.values();
    //        System.out.println("\r\nnb de message dans la collection de reponses positives: " + collecMsg.size());
    //        for(Iterator<UcpMessage> iter = collecMsg.iterator(); iter.hasNext();)
    //        {
    //            UcpMessage msgEle = (UcpMessage)iter.next();
    //            //affichage des attributs
    //            System.out.println(msgEle.toString());
    //        }
    //
    //        //affichage des message
    //        collecMsg = negativesResponsesList.values();
    //        System.out.println("\r\nnb de message dans la collection de reponses negatives: " + collecMsg.size());
    //        for(Iterator<UcpMessage> iter = collecMsg.iterator(); iter.hasNext();)
    //        {
    //            UcpMessage msgEle = (UcpMessage)iter.next();
    //            //affichage des attributs
    //            System.out.println(msgEle.toString());
    //        }
}

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

License:Open Source License

public UcpAttribute setAttribute(Element element) throws Exception {
    UcpAttribute att = new UcpAttribute();
    String value = null;/*from www  .  ja v  a2  s .c  o m*/

    att.setName(element.attributeValue("name"));
    att.setFormat(element.attributeValue("format"));
    value = element.attributeValue("size");
    if (value != null)
        att.setLength(Integer.parseInt(value));

    att.setValue(element.attributeValue("value"));
    value = element.attributeValue("mandatory");
    if (value != null) {
        att.setMandatory(Boolean.parseBoolean(value));
    } else {
        att.setNotApplicable(true);
    }

    value = element.attributeValue("numberOfTime");
    if (value != null) {
        att.setOccurenceAttribute(value);
    }
    return att;
}

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

License:Open Source License

/** 
 * Parse the message from XML element /*  ww w  .j  a  v  a 2s .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 Channel specific to each Stack */
// deprecated part //
@Override//from ww  w .ja  va  2  s . c o m
public Channel parseChannelFromXml(Element root, String protocol) throws Exception {
    String name = root.attributeValue("socketName");
    String localHost = root.attributeValue("localHost");
    String localPort = root.attributeValue("localPort");
    String remoteHost = root.attributeValue("remoteHost");
    String remotePort = root.attributeValue("remotePort");
    String connected = root.attributeValue("connected");

    if (existsChannel(name)) {
        return getChannel(name);
    } else {
        return new ChannelUdp(name, localHost, localPort, remoteHost, remotePort, protocol,
                Boolean.parseBoolean(connected));
    }
}

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

License:Open Source License

/** Creates a specific Msg */
@Override/*from   www . j  av  a 2 s. co  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, ..."
 *//*from  w w w . j a v a 2  s  .c  o  m*/
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);//w  w  w. ja v a 2s  .  c o m
    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;
}