Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

Usage

From source file:com.devoteam.srit.xmlloader.core.Parameter.java

License:Open Source License

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);/*from w  w  w .ja v  a2s.c  o  m*/
    }
    // 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) {
        xml = "<?xml version='1.0'?>" + 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) {
            add(node.asXML());
        }
    } else if (obj instanceof DefaultElement) {
        Node node = (Node) obj;
        add(node.asXML());
    } else if (obj instanceof DefaultAttribute) {
        Node node = (Node) obj;
        add(node.getStringValue());
    } else if (obj instanceof DefaultText) {
        Node node = (Node) obj;
        add(node.getText());
    } else {
        add(obj.toString());
    }
}

From source file:com.devoteam.srit.xmlloader.core.utils.Utils.java

License:Open Source License

public static Document stringParseXML(String xml, boolean deleteNS) throws Exception {
    // remove beginning to '<' character
    int iPosBegin = xml.indexOf('<');
    if (iPosBegin > 0) {
        xml = xml.substring(iPosBegin);/*  ww w  . j a va  2  s .c  om*/
    }
    // 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) {
        xml = "<?xml version='1.0'?>" + 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);
    return document;
}

From source file:com.devoteam.srit.xmlloader.genscript.Param.java

License:Open Source License

public String applySubstitution(String text, Msg msg) throws Exception {

    String msgAvecParametres = "";

    if (getRegle() != null) {
        String[] regexTab = getRegle().split("#");

        // Si la regle est sous forme d'expression rgulire
        if (regexTab[0].toUpperCase().contains("REGEX")) {
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                    "Replace parameter " + getRegle() + " => " + name);
            String[] regexRule = Arrays.copyOfRange(regexTab, 1, regexTab.length);
            msgAvecParametres = regexRemplace(regexRule, 0, text);
        }/*from   w  w w . j  av  a  2s .  c o m*/
        // Si la regle est sous forme de xpath
        else if (regexTab[0].toUpperCase().contains("XPATH")) {
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                    "Replace parameter " + getRegle() + " => " + name);
            // Rcupration des paramtres
            String xpathRule = regexTab[1];
            String attribut = regexTab[2];

            attribut = attribut.replace("@", "");

            // Cration de l'arbre DOM correspondant au message
            SAXReader reader = new SAXReader();
            try {
                Document document = reader.read(new ByteArrayInputStream(text.getBytes("UTF-8")));
                // Cration de l'objet XPATH ) selectionner 
                XPath xpath = new DefaultXPath(xpathRule);

                // Rcupration des noeuds correspondants
                List<Node> nodes = xpath.selectNodes(document.getRootElement(), xpath);

                // Pour chaque noeuds  modifier
                Element aRemplacer = null;
                for (Node n : nodes) {
                    setRemplacedValue(n.getText());
                    if (n instanceof Element) {
                        aRemplacer = (Element) n;
                    } else {
                        aRemplacer = n.getParent();
                    }
                    String newValue = getName();
                    String oldValue = aRemplacer.attribute(attribut).getValue();
                    // On regarde si on est dans le cas de paramtres mixtes
                    if (regexTab.length > 3) {
                        if (regexTab[3].equals("REGEX")) {
                            setRemplacedValue(null);
                            String[] regexRule = Arrays.copyOfRange(regexTab, 4, regexTab.length);
                            newValue = regexRemplace(regexRule, 0, oldValue);
                        }
                    }
                    aRemplacer.setAttributeValue(attribut, newValue);
                }

                // Convertion en chane de caractre de l'arbre DOM du message
                msgAvecParametres = document.getRootElement().asXML();
            } catch (Exception e) {

            }
        }
        // si la rgle est sous forme de pathkey
        else if (regexTab[0].toUpperCase().contains("PATHKEY")) {

            String valeurARemplacer = null;
            // On rcupre la valeur  remplacer
            String pathKeyWord = regexTab[1];
            if (msg != null) {
                Parameter valeurParamARemplacer = msg.getParameter(pathKeyWord);
                if (valeurParamARemplacer.length() > 0) {
                    valeurARemplacer = valeurParamARemplacer.get(0).toString();
                }

                // On remplace dans tout le message par le parametre
                if (valeurARemplacer != null) {
                    msgAvecParametres = text.replace(valeurARemplacer, getName());
                    if (!msgAvecParametres.equals(text)) {
                        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                                "Replace parameter " + valeurARemplacer + " => " + name);
                        setRemplacedValue(valeurARemplacer);
                    }
                }
            }
        }
    }
    // Si le message n'a pas subit de modification, on retourne null
    if (!isUsed()) {
        return null;
    }

    // Sinon on retourne le message modifi avec les paramtres
    return msgAvecParametres;
}

From source file:com.devoteam.srit.xmlloader.genscript.ScriptGenerator.java

License:Open Source License

public void generateTest() throws Exception {

    // Si le fichier n'existe pas dj
    if (!fileRoot.exists()) {
        test = new Test("Genscript", "Script converted from capture");
    }//from ww  w. j  av a  2s . c o m
    // Si le fichier de sortie existe dj
    else {
        // On ouvre le fichier existant
        File xml = fileRoot;
        Document testDoc;
        SAXReader reader = new SAXReader();
        testDoc = reader.read(xml);
        Element testExistant = testDoc.getRootElement();

        // On gnre un nouvel objet test  partir de l'lment existant dans le fichier
        test = new Test(testExistant.attributeValue("name"), testExistant.attributeValue("description"));
        test.setTest(testExistant);
    }

    // On tente de rcuprer le testcase  gnrer
    Element testcaseExistant = null;
    for (Iterator i = test.getTest().elements().iterator(); i.hasNext();) {
        Element elem = (Element) i.next();
        if (elem.getName().equals("testcase") && elem.attribute("name").getText().equals(testcaseName)) {
            testcaseExistant = elem;
        }
    }

    // On rcupre les paramtres existants
    for (Iterator i = test.getTest().elements().iterator(); i.hasNext();) {
        Element elem = (Element) i.next();
        if (elem.getName().equals("parameter")) {
            Param p = new Param(elem.attributeValue("name"), "test",
                    elem.attributeValue("operation") + "," + elem.attributeValue("value"), null,
                    Param.TARGET_SENDCLIENT);
            p.setName(p.getFamily());
            p.setRemplacedValue(elem.attributeValue("value"));
            ParamGenerator.getInstance().recordParam(p);
        }
    }

    // Si le testcase n'existe pas encore
    if (testcaseExistant == null) {
        // On le crait
        testcase = new TestCase(testcaseName, "Testcase generate from capture", "true");
        test.getTest().add(testcase.getTestCase());
    }
    // Sinon on gnre un testcase  partir de celui existant dans le fichier
    else {
        testcase = new TestCase(testcaseExistant.attributeValue("name"),
                testcaseExistant.attributeValue("description"), testcaseExistant.attributeValue("state"));
        testcase.setTestCase(testcaseExistant);

        // On rcupre les paramtres existants
        for (Iterator i = testcase.getTestCase().elements().iterator(); i.hasNext();) {
            Element elem = (Element) i.next();
            if (elem.getName().equals("parameter")) {
                Param p = new Param(elem.attributeValue("name"), "testcase",
                        elem.attributeValue("operation") + "," + elem.attributeValue("value"), null,
                        Param.TARGET_SENDCLIENT);
                p.setName(p.getFamily());
                p.setRemplacedValue(elem.attributeValue("value"));
                ParamGenerator.getInstance().recordParam(p);
            }
        }
    }
    // On ajoute le testcase dans le test
    test.addTestCase(testcase);

    // On tente de rcuprer le scenario
    Element scenarioExistant = null;
    // On enregistre les scenarios de ce testcase
    for (Iterator j = testcase.getTestCase().elements().iterator(); j.hasNext();) {
        Element elem = (Element) j.next();
        if (elem.getName().equals("scenario")
                && elem.getText().contains(listeFiltre.get(0).getHostPort().toString())) {
            scenarioExistant = elem;
        } else if (elem.getName().equals("scenario")) {
            Scenario sc = new Scenario(elem.attributeValue("name"), elem.getText(), listeFiltre);
            testcase.addScenario(sc);
        }
    }

    // Si le scenario n'existe pas encore
    if (scenarioExistant == null) {
        // On le crait
        scenario = new Scenario(getScenarioName(), getScenarioPath(), listeFiltre);
        testcase.getTestCase().add(scenario.toXmlElement());
    } else {
        scenario = new Scenario(scenarioExistant.attributeValue("name"), scenarioExistant.getText(),
                listeFiltre);
        scenario.setScenario(scenarioExistant);
    }

    // On ajoute ce scenario au testcase
    testcase.addScenario(scenario);

}

From source file:com.devoteam.srit.xmlloader.gtppr.GtppDictionary.java

License:Open Source License

private void parseFile(InputStream stream) throws Exception {
    Element node = null;/*  w w w  . j  a v  a 2 s . com*/
    GtppMessage msg = null;
    Tag tlv = null;
    String length = null;
    String format = null;
    int i = 0;

    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++) {
        node = (Element) listMessages.get(i);

        msg = new GtppMessage();
        msg.setHeader(new GtpHeaderPrime());
        msg.getHeader().setName(node.attributeValue("name"));
        msg.getHeader().setMessageType(Integer.parseInt(node.attributeValue("messageType")));

        for (Iterator it = node.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();

            String name = element.getName();
            if (name.equalsIgnoreCase("tv") || name.equalsIgnoreCase("tlv") || name.equalsIgnoreCase("tliv")) {
                if (name.equalsIgnoreCase("tv")) {
                    tlv = new TagTV();
                } else if (name.equalsIgnoreCase("tlv")) {
                    tlv = new TagTLIV();
                } else if (name.equalsIgnoreCase("tliv")) {
                    tlv = new TagTLIV();
                }

                tlv.setName(element.attributeValue("name"));
                String value = element.attributeValue("mandatory");
                if (value != null && !value.equalsIgnoreCase("cond")) {
                    tlv.setMandatory(Boolean.parseBoolean(value));
                } else//case of cond, considered as optional
                {
                    tlv.setMandatory(false);
                }
                msg.addTLV(tlv);
            }
        }

        messagesList.put(msg.getHeader().getName(), msg);
        messageTypeToNameList.put(msg.getHeader().getMessageType(), msg.getHeader().getName());
        messageNameToTypeList.put(msg.getHeader().getName(), msg.getHeader().getMessageType());
    }

    //parsing des TLV
    List listTLV = document.selectNodes("/dictionary/tv | /dictionary/tlv | /dictionary/tliv");
    for (i = 0; i < listTLV.size(); i++) {
        node = (Element) listTLV.get(i);

        String name = node.getName();
        if (name.equalsIgnoreCase("tv")) {
            tlv = new TagTV();
        } else if (name.equalsIgnoreCase("tlv")) {
            tlv = new TagTLV();
        } else if (name.equalsIgnoreCase("tliv")) {
            tlv = new TagTLIV();
        }
        tlv.setName(node.attributeValue("name"));
        tlv.setTag(Integer.parseInt(node.attributeValue("tag")));
        length = node.attributeValue("length");
        if (length != null) {
            tlv.setLength(Integer.parseInt(length));
            tlv.setFixedLength(true);
        }
        format = node.attributeValue("format");
        if (format != null) {
            tlv.setFormat(format);
            if (format.equals("list")) {
                tlv.setValue(new LinkedList<GtppAttribute>());
                parseAtt((Attribute) tlv, node);
            }
        }

        tlvList.put(tlv.getName(), tlv);
        tlvTagToNameList.put(tlv.getTag(), tlv.getName());
        tlvNameToTagList.put(tlv.getName(), tlv.getTag());
    }
}

From source file:com.devoteam.srit.xmlloader.sigtran.fvo.FvoDictionary.java

License:Open Source License

/**
 * Parse the dictionary from the XML file
 * /*from   w  w w. jav a  2s.  co m*/
 * @param stream      :fvoDictionary XML file
 * @throws Exception
 */
final void parseFile(InputStream stream) throws Exception {
    SAXReader reader = new SAXReader();
    Document document = reader.read(stream);

    //HEADER
    Node headerNode = document.selectSingleNode("/dictionary/header");
    if (headerNode != null) {
        Element root = (Element) headerNode;
        header = parseParameter(root);
        header.setMessageLength(Integer.decode(root.attributeValue("length")));
    }

    //MESSAGES
    List listMessages = document.selectNodes("/dictionary/messages/message");
    for (Object object : listMessages) {
        Element root = (Element) object;
        FvoMessage message = new FvoMessage(null, this);

        String typeName = root.attributeValue("typeName");
        message.setName(typeName);
        String typeCode = root.attributeValue("typeCode");
        message.setMessageType(Integer.decode(typeCode));
        List parameters = root.elements("parameter");
        //PARAMETER OF EACH MESSAGE
        for (int j = 0; j < parameters.size(); j++) {
            Element param = (Element) parameters.get(j);

            String name = param.attributeValue("name");

            FvoParameter parameter;
            // try to find a detailed definition of the parameter
            Element def = (Element) document
                    .selectSingleNode("/dictionary/parameters/parameter[@name=\"" + name + "\"]");
            if (null != def) {
                parameter = parseParameter(def);
            } else {
                parameter = new FvoParameter(null);
            }
            if (name != null) {
                parameter.setName(name);
            }
            String type = param.attributeValue("type");
            if (type != null) {
                parameter.setType(type);
            }
            String length = param.attributeValue("length");
            if (length != null) {
                parameter.setMessageLength(Integer.decode(length));
            }
            String littleEndian = param.attributeValue("littleEndian");
            if (littleEndian != null) {
                parameter.setLittleEndian(Boolean.parseBoolean(littleEndian));
            }

            if (parameter.getType().equalsIgnoreCase("F")) {
                message.getFparameters().add(parameter);
            }
            if (parameter.getType().equalsIgnoreCase("V")) {
                message.getVparameters().add(parameter);
            }
            if (parameter.getType().equalsIgnoreCase("O")) {
                message.getOparameters().add(parameter);
            }
        }
        this.codeToMessage.put(message.getMessageType(), message);
    }

    //ENUMERATIONS
    //TODO
}

From source file:com.devoteam.srit.xmlloader.sigtran.tlv.TlvDictionary.java

License:Open Source License

private void parseFile(InputStream stream) throws Exception {
    //      variables
    int i = 0;/*from ww  w.  ja v  a  2s.  c o  m*/
    int j = 0;
    int k = 0;

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

    Element root = (Element) document.selectSingleNode("/dictionary");
    String ppidStr = root.attributeValue("ppid");
    _ppid = Integer.parseInt(ppidStr);

    //Class and type
    List listClassType = document.selectNodes("/dictionary/classType/class");
    for (i = 0; i < listClassType.size(); i++) {
        Element classNode = (Element) listClassType.get(i);
        String classId = classNode.attributeValue("id");
        String className = classNode.attributeValue("name");

        List listType = classNode.elements("type");
        for (j = 0; j < listType.size(); j++) {
            Element typeNode = (Element) listType.get(j);
            String typeId = typeNode.attributeValue("id");
            String typeName = typeNode.attributeValue("name");
            String class_Type = classId;
            class_Type += ":" + typeId;

            messageTypeValue.put(typeName, typeId);
            messageTypeName.put(class_Type, typeName);
        }
        try {
            messageClassValue.put(className, (Integer.decode(classId)));
            messageClassName.put((Integer.decode(classId)), className);
        } catch (Exception e) {
            throw new ExecutionException(
                    "a class id must be an Integer\n" + classNode.asXML().replace("   ", ""));
        }

    }
    //parameters

    List listParameters = document.selectNodes("/dictionary/parameters/parameter");
    for (i = 0; i < listParameters.size(); i++) {
        Element parameterNode = (Element) listParameters.get(i);
        String parameterName = parameterNode.attributeValue("name");
        String parameterTag = parameterNode.attributeValue("tag");
        TlvParameter parameter = new TlvParameter(null, this);
        if (parameterTag != null) {
            try {
                parameter.setTag(Integer.decode(parameterTag));
            } catch (Exception e) {
                throw new ExecutionException(
                        "a tag of a parameter must be an Integer\n" + parameterNode.asXML().replace("   ", ""));
            }
        }
        parameter.setName(parameterName);
        this.parameter.put(parameterName, parameter);
        this.parameterName.put(parameter.getTag(), parameterName);

        List listFields = parameterNode.elements("field");
        for (j = 0; j < listFields.size(); j++) {
            TlvField field = parseField((Element) listFields.get(j));
            parameter.getFields().add(field);

        }
    }

    //enumerations
    List listEnumeration = document.selectNodes("/dictionary/enumerations/enumeration");
    for (i = 0; i < listEnumeration.size(); i++) {
        Element enumerationNode = (Element) listEnumeration.get(i);
        List listValue = enumerationNode.elements("value");
        String enumerationName = enumerationNode.attributeValue("name");

        for (j = 0; j < listValue.size(); j++) //-value-
        {
            Element valueNode = (Element) listValue.get(j);
            List listField = valueNode.elements("field");
            String valueName = valueNode.attributeValue("name");
            String valueCode = valueNode.attributeValue("code");

            if (valueCode != null) {
                try {
                    Integer.decode(valueCode);
                } catch (Exception e) {
                    throw new ExecutionException(
                            "a valueCode must be an Integer\n" + valueNode.asXML().replace("   ", ""));
                }
            }

            String enumerationName_code = enumerationName + ":" + valueCode;
            enumerationFromCode.put(enumerationName_code, valueName);
            String enumerationName_name = enumerationName + ":" + valueName;
            enumerationFromName.put(enumerationName_name, valueCode);
        }
    }

}

From source file:com.devoteam.srit.xmlloader.smpp.SmppDictionary.java

License:Open Source License

private void parseFile(InputStream stream) throws Exception {
    Element messageNode = null;// ww  w . j  a  va  2  s. c  o m
    Element group = null;
    SmppMessage msg = null;
    SmppAttribute att = null;
    SmppAttribute att2 = null;
    SmppGroup attGroup = null;
    SmppChoice attChoice = null;
    Vector<SmppGroup> choiceList = null;
    Vector<SmppAttribute> imbricateAtt = null;
    SmppTLV tlv = null;
    int i = 0;
    int j = 0;
    long id = 0;

    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++) {
        messageNode = (Element) listMessages.get(i);

        msg = new SmppMessage();
        msg.setName(messageNode.attributeValue("name"));
        id = Long.parseLong(messageNode.attributeValue("id"), 16);
        msg.setId((int) id);

        for (Iterator it = messageNode.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            String name = element.getName();

            if (name.equalsIgnoreCase("attribute")) {
                att = setAttribute(element); //for simple attribute

                //check if attribute imbricate in attribute or choice in attribute
                List listAtt = element.selectNodes("//attribute[@name='" + element.attributeValue("name")
                        + "']/attribute | //attribute[@name='" + element.attributeValue("name") + "']/choice");
                if (!listAtt.isEmpty()) {
                    ((Vector) att.getValue()).add(new Vector<SmppAttribute>());//set vector of imbricate attributes into the vector of occurence
                }

                for (j = 0; j < listAtt.size(); j++) {
                    if (((Element) listAtt.get(j)).getName().equalsIgnoreCase("attribute")) {
                        //add imbricate attribute to att
                        att2 = setAttribute((Element) listAtt.get(j));
                        ((Vector<SmppAttribute>) ((Vector) att.getValue()).get(0)).add(att2);
                    } else if (((Element) listAtt.get(j)).getName().equalsIgnoreCase("choice")) {
                        List groupList = element.selectNodes(
                                "//attribute[@name='" + element.attributeValue("name") + "']/choice/group");
                        attChoice = new SmppChoice();
                        choiceList = new Vector<SmppGroup>();

                        //work because last imbricate att is the last attribute set and is the att base on choice
                        attChoice.setChoiceAttribute(att2);

                        //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 SmppGroup();

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

                            for (Iterator iter = group.elementIterator(); iter.hasNext();) {
                                imbricateAtt.add(setAttribute((Element) iter.next()));
                            }

                            attGroup.setValue(imbricateAtt);
                            choiceList.add(attGroup);
                        }
                        attChoice.setValue(choiceList);
                        ((Vector<SmppChoice>) ((Vector) att.getValue()).get(0)).add(attChoice);
                    }
                }
                msg.addAttribut(att);
            } else if (name.equalsIgnoreCase("tlv")) {
                tlv = setTLV(element, msg);
                if (tlv != null)
                    msg.addTLV(tlv);
            }
        }

        messagesList.put(msg.getName(), msg);
        messageIdToNameList.put(msg.getId(), msg.getName());
        messageNameToIdList.put(msg.getName(), msg.getId());
    }

    //        //affichage des message
    //        Collection<SmppMessage> collecMsg = messagesList.values();
    //        System.out.println("\r\nnb de message dans la collection: " + collecMsg.size());
    //        for(Iterator<SmppMessage> iter = collecMsg.iterator(); iter.hasNext();)
    //        {
    //            SmppMessage msgEle = (SmppMessage)iter.next();
    //            if(msgEle.getName().equals("submit_multi"))
    //            {
    //                System.out.println(msgEle.getName());
    //                //affichage des attributs
    //                System.out.println(msgEle.toString());
    //            }
    //        }
}

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;/*from   w ww.j a  v a2s  . co m*/
    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.dockingsoftware.dockingpreference.PreferenceProcessor.java

License:Apache License

/**
 * Loads preference by filePath.//w  w w .j a v  a 2 s  . c  o m
 * 
 * @param filePath
 * @return 
 */
public Object load(String filePath) {
    Object obj = null;
    File file = new File(filePath);
    if (!file.exists()) {
        return null;
    }
    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(file);
        Element parent = doc.getRootElement();
        NodeInfo rootInfo = new NodeInfo(parent);
        obj = Class.forName(rootInfo.getClazz()).newInstance();
        load(obj, parent);
    } catch (DocumentException ex) {
        String errMsg = "The system cannot find the file specified path " + filePath + ".";
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, errMsg, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        String errMsg = "No-args constructor is missing for " + ex.getMessage();
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, errMsg, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return obj;
}