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.smtp.StackSmtp.java

License:Open Source License

/** Creates a specific Msg */
@Override/*  www  . ja  va 2s .  c o  m*/
public Channel parseChannelFromXml(Element root, String protocol) throws Exception {
    String name = root.attributeValue("name");
    // deprecated part //
    if (name == null)
        name = root.attributeValue("sessionName");
    // deprecated part //
    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 {
        return new ChannelSmtp(name, localHost, localPort, remoteHost, remotePort, protocol);
    }
}

From source file:com.devoteam.srit.xmlloader.smtp.StackSmtp.java

License:Open Source License

public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    String text = root.getText();
    MsgSmtp msgSmtp = new MsgSmtp(text);
    String transactionIdStr = root.attributeValue("transactionId");

    if (transactionIdStr != null) {
        TransactionId transactionId = new TransactionId(transactionIdStr);
        msgSmtp.setTransactionId(transactionId);
        Msg requestSmtp = StackFactory.getStack(StackFactory.PROTOCOL_SMTP).getInTransaction(transactionId)
                .getBeginMsg();/* www  .  ja va 2s  . com*/
        msgSmtp.setType(requestSmtp.getType());
    } else {
        String channelName = root.attributeValue("channel");
        // deprecated part //
        if (channelName == null)
            channelName = root.attributeValue("sessionName");
        // deprecated part //
        Channel channel = getChannel(channelName);
        if (channel == null) {
            throw new ExecutionException("The channel <name=" + channelName + "> does not exist");
        }
        msgSmtp.setChannel(getChannel(channelName));
    }
    return msgSmtp;
}

From source file:com.devoteam.srit.xmlloader.snmp.StackSnmp.java

License:Open Source License

@Override
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {
    // header/*from  ww w.j  a v a  2 s . c  o  m*/
    Element header = root.element("header");
    String version = header.attributeValue("version");
    String community = header.attributeValue("community");

    if (version == null)//get version given in config if not present in sendMessage
        version = getConfig().getString("protocol.version", "1");

    if (!Utils.isInteger(version))
        throw new Exception("attribute version must be integer");

    Integer versionInt = Integer.parseInt(version);
    if (versionInt == 1)
        versionInt = SnmpConstants.version1;
    else if (versionInt == 2)
        versionInt = SnmpConstants.version2c;
    else if (versionInt == 3)
        versionInt = SnmpConstants.version3;
    else
        throw new Exception("possible version for SNMP are 1, 2 or 3 exclusively");

    Element pdu = root.element("pdu");
    String name = pdu.attributeValue("name");
    String type = pdu.attributeValue("type");
    String requestId = pdu.attributeValue("requestId");
    String errorStatus = pdu.attributeValue("errorStatus");
    String errorIndex = pdu.attributeValue("errorIndex");
    String nonRepeaters = pdu.attributeValue("nonRepeaters");
    String maxRepetitions = pdu.attributeValue("maxRepetitions");

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

    if ((type == null) && (name == null))
        throw new Exception("One of the parameter type or name of the message header must be set");

    if ((type != null) && !Utils.isInteger(type))
        throw new Exception("attribute type must be integer");

    Integer typeInt = null;
    if (type == null) {
        if (name.equalsIgnoreCase("trap") && (versionInt == SnmpConstants.version1))
            typeInt = PDU.V1TRAP;
        else {
            typeInt = PDU.getTypeFromString(name.toUpperCase());
            if (typeInt < -100)
                throw new Exception("the type " + name + " specified is unknown in the SNMP protocol");
        }
    } else
        typeInt = Integer.parseInt(type);

    if (((errorStatus != null) || (errorIndex != null)) && ((nonRepeaters != null) || (maxRepetitions != null)))
        throw new Exception(
                "The attributes errorStatus or errorIndex must not be set with nonRepeaters or maxRepetitions");

    if ((requestId == null) || !Utils.isInteger(requestId))
        throw new Exception("attribute requestId must be integer");

    if (((errorStatus != null) && !Utils.isInteger(errorStatus))
            || ((errorIndex != null) && !Utils.isInteger(errorIndex)))
        throw new Exception("attribute errorStatus and errorIndex must be integer");

    if (((nonRepeaters != null) && !Utils.isInteger(nonRepeaters))
            || ((maxRepetitions != null) && !Utils.isInteger(maxRepetitions)))
        throw new Exception("attribute nonRepeaters and maxRepetitions must be integer");

    Integer requestIdInt = (requestId != null) ? Integer.parseInt(requestId) : null;
    Integer errorStatusInt = (errorStatus != null) ? Integer.parseInt(errorStatus) : null;
    Integer errorIndexInt = (errorIndex != null) ? Integer.parseInt(errorIndex) : null;
    Integer nonRepeatersInt = (nonRepeaters != null) ? Integer.parseInt(nonRepeaters) : null;
    Integer maxRepetitionsInt = (maxRepetitions != null) ? Integer.parseInt(maxRepetitions) : null;

    MsgSnmp msgSmtp = new MsgSnmp(versionInt, community, typeInt, requestIdInt, errorStatusInt, errorIndexInt,
            nonRepeatersInt, maxRepetitionsInt);

    //specific parameter for snmpv1 Trap  to check and add to pdu
    if ((msgSmtp.getPdu() instanceof PDUv1) && (typeInt == PDU.V1TRAP)) {
        String enterprise = pdu.attributeValue("enterprise");
        String agentAddress = pdu.attributeValue("agentAddress");
        String genericTrap = pdu.attributeValue("genericTrap");
        String specificTrap = pdu.attributeValue("specificTrap");
        String timestamp = pdu.attributeValue("timestamp");

        if (genericTrap.equalsIgnoreCase("enterpriseSpecific") && !Utils.isInteger(specificTrap))
            throw new Exception(
                    "specificTrap attribute must be an integer when enterpriseSpecific if given for genereicTrap in SNMPV1 TRAP message");
        if (!Utils.isInteger(timestamp))
            throw new Exception("timestamp must be an integer");

        int genericTrapInt = 0;
        if (genericTrap.equalsIgnoreCase("coldStart"))
            genericTrapInt = PDUv1.COLDSTART;
        else if (genericTrap.equalsIgnoreCase("warmStart"))
            genericTrapInt = PDUv1.WARMSTART;
        else if (genericTrap.equalsIgnoreCase("linkDown"))
            genericTrapInt = PDUv1.LINKDOWN;
        else if (genericTrap.equalsIgnoreCase("linkUp"))
            genericTrapInt = PDUv1.LINKUP;
        else if (genericTrap.equalsIgnoreCase("authenticationFailure"))
            genericTrapInt = PDUv1.AUTHENTICATIONFAILURE;
        else if (genericTrap.equalsIgnoreCase("egpNeighborLoss"))
            genericTrapInt = 5;//specified in rfc 1157, but not present in snmp4j stack
        else if (genericTrap.equalsIgnoreCase("enterpriseSpecific"))
            genericTrapInt = PDUv1.ENTERPRISE_SPECIFIC;
        else
            throw new Exception("genericTrap attribute is unknown");

        ((PDUv1) msgSmtp.getPdu()).setEnterprise(new OID(enterprise));
        ((PDUv1) msgSmtp.getPdu()).setAgentAddress(new IpAddress(agentAddress));
        ((PDUv1) msgSmtp.getPdu()).setGenericTrap(genericTrapInt);
        ((PDUv1) msgSmtp.getPdu()).setSpecificTrap(Integer.parseInt(specificTrap));
        ((PDUv1) msgSmtp.getPdu()).setTimestamp(Integer.parseInt(timestamp));
    }

    List<Element> variables = pdu.elements("variableBinding");
    for (Element var : variables) {
        parseVariableBinding(var, msgSmtp.getPdu());
    }
    return msgSmtp;
}

From source file:com.devoteam.srit.xmlloader.snmp.StackSnmp.java

License:Open Source License

private void parseVariableBinding(Element variable, PDU pdu) throws Exception {
    String name = variable.attributeValue("name");
    String value = variable.attributeValue("value");
    String type = variable.attributeValue("type");
    String mibName = null;/*from   ww  w . j  ava 2s  .c  o  m*/

    if (name == null) {
        throw new Exception("ERROR : The variablebinding name is required to send the variable.");
    }

    VariableBinding varBind = null;
    boolean found = false;
    if (name.startsWith("1."))//if name begin with digit 1 follow by a dot, it is an oid, else we consider it's a variable mib
    {
        varBind = new VariableBinding(new OID(name));
        found = true;
    } else {
        if (name.contains(".")) {
            mibName = name.substring(0, name.indexOf('.'));
            name = name.substring(name.indexOf('.') + 1);
        }

        Mib[] mibs = mibLoader.getAllMibs();
        for (int i = 0; (i < mibs.length) && !found; i++) {
            Collection symbols = mibs[i].getAllSymbols();
            for (Object symb : symbols) {
                if (symb instanceof MibValueSymbol) {
                    if (((MibValueSymbol) symb).getName().equalsIgnoreCase(name)) {
                        if ((mibName == null)
                                || ((MibValueSymbol) symb).getMib().getName().equalsIgnoreCase(mibName)) {
                            varBind = new VariableBinding(
                                    new OID(((MibValueSymbol) symb).getValue().toString()));

                            if (type == null) {
                                type = findType((MibValueSymbol) symb);
                            }
                            found = true;
                            break;
                        }
                    }
                } else if (symb instanceof MibTypeSymbol) {
                    //                        System.out.println("mibTypeSymbol " + ((MibTypeSymbol)symb).getName() + " for mib name " + mibs[i].getName());
                } else if (symb instanceof MibMacroSymbol) {
                    //                        System.out.println("mibMacroSymbol " + ((MibMacroSymbol)symb).getName() + " for mib name " + mibs[i].getName());
                } else {
                    throw new Exception(
                            "ERROR : Unknown class for variablebinding \"" + symb.getClass() + "\"");
                }
            }
        }
    }
    if (!found) {
        throw new Exception("ERROR : Unknown varbinding name \"" + name + "\" not found in the MIB files.");
    }

    if (type == null)///if type not set, search in mib
    {
        Mib[] mibs = mibLoader.getAllMibs();
        for (int i = 0; (i < mibs.length); i++) {
            MibValueSymbol symbol = mibs[i].getSymbolByValue(varBind.getOid().toString());

            if (symbol != null) {
                //set type in function of information in variable
                type = findType(symbol);
                break;
            }
        }
    }

    if ((value != null) && (value.length() > 0)) {
        if (type == null) {
            throw new Exception(
                    "ERROR : The variablebinding type is required : it is not defined nor in XML script nor in MIB files.");
        }
        if (type.equalsIgnoreCase("counter64")) {
            varBind.setVariable(new Counter64(Long.parseLong(value)));
        } else if (type.equalsIgnoreCase("integer32")) {
            varBind.setVariable(new Integer32(Integer.parseInt(value)));
        } else if (type.equalsIgnoreCase("octetString") || type.equalsIgnoreCase("octet string")) {
            varBind.setVariable(new OctetString(value));
        } else if (type.equalsIgnoreCase("opaque")) {
            varBind.setVariable(new Opaque(value.getBytes()));
        } else if (type.equalsIgnoreCase("oid")) {
            varBind.setVariable(new OID(value));
        } else if (type.equalsIgnoreCase("genericAddress")) {
            GenericAddress add = new GenericAddress();
            add.setValue(value);
            varBind.setVariable(add);
        } else if (type.equalsIgnoreCase("ipAddress")) {
            varBind.setVariable(new IpAddress(value));
        } else if (type.equalsIgnoreCase("unsignedInteger32")) {
            varBind.setVariable(new UnsignedInteger32(Integer.parseInt(value)));
        } else if (type.equalsIgnoreCase("counter32")) {
            varBind.setVariable(new Counter32(Long.parseLong(value)));
        } else if (type.equalsIgnoreCase("gauge32")) {
            varBind.setVariable(new Gauge32(Long.parseLong(value)));
        } else if (type.equalsIgnoreCase("timeTicks")) {
            varBind.setVariable(new TimeTicks(Long.parseLong(value)));
        } else {
            throw new Exception("Error : Unknown variablebinding type \"" + type
                    + "\" : not understood by the application");
        }
    }

    pdu.add(varBind);
}

From source file:com.devoteam.srit.xmlloader.stun.MsgStun.java

License:Open Source License

MsgStun(Element root) {
    super();// w w  w  . j  a  v  a2  s.c o  m
    header = new HeaderStun();
    parseHeader(root.element("header"));

    List<Element> attributes = root.elements("attribute");
    for (Element attribute : attributes) {
        if (attribute.attributeValue("type").equalsIgnoreCase("realm")) {
            this.longTermCredential = true;
        }
        parseAttribute(attribute);
    }
}

From source file:com.devoteam.srit.xmlloader.stun.MsgStun.java

License:Open Source License

private void parseHeader(Element elem) {
    header.setType(Integer.parseInt(elem.attributeValue("type")));
    header.setTransactionId(Array.fromHexString(elem.attributeValue("transactionID")));

}

From source file:com.devoteam.srit.xmlloader.stun.MsgStun.java

License:Open Source License

private void parseAttribute(Element elem) {
    List<Element> children = elem.elements();
    for (Element child : children) {
        AttributeStun attribute = null;//from  ww  w .  j a  va 2s .c o m
        String typeInHexa = (String) DictionnaryStun.readProperties().get(elem.attributeValue("type"));
        if (child.getName().equalsIgnoreCase("address")) {
            attribute = new AttributeStunAddress(Array.fromHexString(typeInHexa),
                    Integer.parseInt(child.attributeValue("family")),
                    Integer.parseInt(child.attributeValue("port")), child.attributeValue("addressIP"));
        } else if (child.getName().equalsIgnoreCase("text")) {
            if (elem.attributeValue("type").equalsIgnoreCase("username"))//attribute username
            {
                this.username = child.attributeValue("text");
            }
            if (elem.attributeValue("type").equalsIgnoreCase("realm"))//attribute realm
            {
                this.realm = child.attributeValue("text");
            }

            attribute = new AttributeStunText(Array.fromHexString(typeInHexa), child.attributeValue("value"));

        } else if (child.getName().equalsIgnoreCase("binary")) {
            attribute = new AttributeStunBinary(Array.fromHexString(typeInHexa),
                    Array.fromHexString(child.attributeValue("value")));

        } else if (child.getName().equalsIgnoreCase("errorCode")) {
            attribute = new AttributeStunErrorCode(Array.fromHexString(typeInHexa),
                    Integer.parseInt(child.attributeValue("code")), child.attributeValue("reasonPhrase"));

        } else if (child.getName().equalsIgnoreCase("changeRequest")) {
            attribute = new AttributeStunChangeRequest(Array.fromHexString(typeInHexa),
                    child.attributeValue("changeIP"), child.attributeValue("changePort"));

        } else if (child.getName().equalsIgnoreCase("unknownAttribute")) {
            String[] tab = child.attributeValue("type").split(",");
            int[] tabType = new int[tab.length];
            for (int i = 0; i < tabType.length; i++) {
                tabType[i] = Integer.parseInt(tab[i]);
            }
            attribute = new AttributeStunUnknownAttribute(Array.fromHexString(typeInHexa), tabType);

        } else if (child.getName().equalsIgnoreCase("messageIntegrity")) {
            try {

                String valueMessageIntegrity = child.attributeValue("value");
                Array integrityArray = null;
                if (null != valueMessageIntegrity) {
                    try {
                        integrityArray = Array.fromHexString(valueMessageIntegrity);
                    } catch (Exception e) {
                        valueMessageIntegrity = null;
                    }
                }

                if (null == valueMessageIntegrity) {
                    if (this.longTermCredential) {
                        String key = username + ":" + realm + ":" + child.attributeValue("secret");
                        DigestArray keyarray = new DigestArray(new DefaultArray(key.getBytes()), "HmacMD5");
                        integrityArray = new MacArray(new DefaultArray(this.getBytesData()), "HmacSHA1",
                                keyarray);
                    } else {
                        DefaultArray arraysecret = new DefaultArray(child.attributeValue("secret").getBytes());
                        integrityArray = new MacArray(new DefaultArray(this.getBytesData()), "HmacSHA1",
                                arraysecret);
                    }
                }

                attribute = new AttributeStunBinary(Array.fromHexString(typeInHexa), integrityArray);

            } catch (Exception e) {
                throw new IllegalArgumentException("The secret can not be empty", e);
            }

        }
        this.listAttributeStun.add(attribute);
        header.setLength(header.getLength() + attribute.getPaddedLength() + 4);

    }

}

From source file:com.devoteam.srit.xmlloader.stun.StackStun.java

License:Open Source License

@Override
public Msg parseMsgFromXml(Boolean request, Element root, Runner runner) throws Exception {

    MsgStun msgstun = new MsgStun(root);

    // OBSOLETE instanciates the listenpoint (compatibility with old grammar)
    String listenpointName = root.attributeValue("providerName");
    Listenpoint listenpoint = getListenpoint(listenpointName);
    if (listenpoint == null && listenpointName != null) {
        throw new ExecutionException("The listenpoint <name=" + listenpointName + "> does not exist");
    }/*from  ww  w.  j a  va  2s. c  om*/
    msgstun.setListenpoint(listenpoint);

    if (request != null && request && !msgstun.isRequest()) {
        throw new ExecutionException(
                "You specify to send a request using a <sendRequestXXX ...> tag, but the message you will send is not really a request.");
    }
    if (request != null && !request && msgstun.isRequest()) {
        throw new ExecutionException(
                "You specify to send a response using a <sendResponseXXX ...> tag, but the message you will send is not really a response.");
    }

    return msgstun;
}

From source file:com.devoteam.srit.xmlloader.tcp.MsgTcp.java

License:Open Source License

/** 
 * Parse the message from XML element /*from   ww w  . java2  s.co 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(e);
    }

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

    byte[] data = new byte[length];

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

    decode(data);
}

From source file:com.devoteam.srit.xmlloader.tcp.StackTcp.java

License:Open Source License

/** Creates a Channel specific to each Stack */
@Override/*  w  w w . j  av a 2  s.  c  om*/
public Channel parseChannelFromXml(Element root, String protocol) throws Exception {
    String name = root.attributeValue("name");
    // deprecated part //
    if (name == null)
        name = root.attributeValue("connectionName");
    // deprecated part //
    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 {
        return new ChannelTcp(name, localHost, localPort, remoteHost, remotePort, protocol);
    }
}