Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:condorclient.utilities.XMLHandler.java

public String getNRun(String file) {
    SAXReader reader = new SAXReader();
    Document doc = null;// w  ww  .j  ava 2  s .  com
    try {
        doc = reader.read(new File(file));
    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    // XML?String    
    String xmlStr = doc.asXML();
    //System.out.println("xmlStr:" + xmlStr);  
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    String s = null;
    try {
        Document document = reader.read(is);
        Element root = document.getRootElement();
        Element ee = root.element("SimTimeDef");
        Element eee = ee.element("NRun");
        s = eee.getText();
        // System.out.println("getText" + eee.getText()+"getName"+eee.getName()+"path:"+eee.getPath());

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return s;
}

From source file:cz.muni.stanse.reachabilitychecker.ReachabilityChecker.java

License:GNU General Public License

/**
 * @brief Does the source code checking itself.
 *
 * Method searches through source code to find nodes (except start node)
 * with no predecessors.//from w  ww .  j av  a  2 s . c om
 *
 * @return List of errors found in the source code.
 * @see cz.muni.stanse.checker.Checker#check(java.util.List)
 */
@Override
public CheckingResult check(final LazyInternalStructures internals, final CheckerErrorReceiver errReceiver,
        final CheckerProgressMonitor monitor) {
    CheckingResult result = new CheckingSuccess();
    monitor.write("Starting Reachability Checker");
    for (CFGHandle cfg : internals.getCFGHandles()) {
        CFGNode start = cfg.getStartNode();
        CFGNode end = cfg.getEndNode();
        for (CFGNode node : cfg.getAllNodesReverse()) {
            if (node.equals(start) || node.equals(end))
                continue;
            if (!node.getPredecessors().isEmpty())
                continue;
            if (!node.getOptPredecessors().isEmpty())
                continue;
            Element nodeElem = node.getElement();
            String elemPath = nodeElem.getPath();

            /* we don't do CFGs of statements inside expressions ({ .. }) */
            if (exprCompoundPattern.matcher(elemPath).find())
                continue;
            if (retCompoundPattern.matcher(elemPath).find())
                continue;

            String elemName = nodeElem.getName();
            if (elemName.equals("intConst") && nodeElem.getText().equals("0"))
                continue;
            int importance = 0;
            StringBuilder fullDesc = new StringBuilder("The code is " + "unreachable by any path.");
            monitor.write("An error found");
            if (elemName.equals("emptyStatement") || elemName.equals("breakStatement")
                    || elemName.equals("returnStatement")) {
                importance += 3;
                fullDesc.append(" Superfluous semicolon, break or return " + "statement.");
            }
            Element parentElem = nodeElem.getParent();
            if (parentElem != null && parentElem.getName().equals("forStatement")
                    && nodeElem.equals(parentElem.elements().get(2))) {
                importance += 5;
                fullDesc.append(" The third 'for' expression is never " + "used.");
            }
            errReceiver.receive(new CheckerError("Unreachable code", fullDesc.toString(), importance,
                    ReachabilityCheckerCreator.getNameForCheckerFactory(), Make.<CFGNode>linkedList(node, node),
                    "This node is unreachable", "", "This node is unreachable", internals));
        }
    }
    monitor.write("Reachability Checker finished");
    return result;
}

From source file:cz.muni.stanse.utils.xmlpatterns.XMLAlgo.java

License:GNU General Public License

/**
 * Check if two elements are (recursively) equal
 *
 * TODO: remove and use equality tester from dom4j pkg
 *
 * @param e1 first element//w  ww  .ja  va  2s .c  om
 * @param e2 second element
 */
public static boolean equalElements(final Element e1, final Element e2) {
    if (!e1.getName().equals(e2.getName()))
        return false;
    if (!e1.getText().equals(e2.getText()))
        return false;

    for (final Object attrObj : e1.attributes()) {
        final Attribute attr = (Attribute) attrObj;
        if (!attr.getName().equals("bl") && !attr.getName().equals("bc")
                && !attr.getValue().equals(e2.attributeValue(attr.getName())))
            return false;
    }

    final Iterator i = e1.elementIterator();
    final Iterator j = e2.elementIterator();
    while (i.hasNext() && j.hasNext())
        if (!equalElements((Element) i.next(), (Element) j.next()))
            return false;
    if (i.hasNext() || j.hasNext())
        return false;

    return true;
}

From source file:cz.muni.stanse.utils.xmlpatterns.XMLPattern.java

License:GNU General Public License

private Pair<Boolean, XMLPatternVariablesAssignment> matchesNode(final CFGNode node, Element xmlPivot,
        AliasResolver aliasResolver) {/* www.j  a v a 2  s .  c  om*/
    if (node.getNodeType() == null || !node.getNodeType().equals(xmlPivot.attributeValue("type")))
        return Pair.make(false, null);

    XMLPatternVariablesAssignment varsAssignment = new XMLPatternVariablesAssignment();

    Iterator<Element> i = xmlPivot.elementIterator();
    Iterator<CFGNode.Operand> j = node.getOperands().iterator();
    while (i.hasNext() && j.hasNext()) {
        Element elem = i.next();

        if (elem.getName().equals("any"))
            return Pair.make(true, varsAssignment);

        CFGNode.Operand op = j.next();

        if (elem.getName().equals("ignore"))
            continue;

        if (elem.getName().equals("var")) {
            if (elem.attribute("target") != null) {
                if (op.type == CFGNode.OperandType.varptr) {
                    varsAssignment.put(elem.attribute("target").getValue(),
                            new CFGNode.Operand(CFGNode.OperandType.varval, op.id));
                } else {
                    return Pair.make(false, null);
                }
            } else {
                varsAssignment.put(elem.attribute("name").getValue(), op);
            }
            continue;
        }

        if (op.type == CFGNode.OperandType.nodeval) {
            if (!elem.getName().equals("node"))
                return Pair.make(false, null);

            Pair<Boolean, XMLPatternVariablesAssignment> nested = matchesNode((CFGNode) op.id, elem,
                    aliasResolver);
            if (!nested.getFirst())
                return nested;
            varsAssignment.merge(nested.getSecond());
        } else {
            if (!op.type.toString().equals(elem.getName()))
                return Pair.make(false, null);

            if (!aliasResolver.match(elem.getText(), op.id.toString()))
                return Pair.make(false, null);
        }
    }

    if (i.hasNext() || j.hasNext())
        return Pair.make(false, null);

    return Pair.make(true, varsAssignment);
}

From source file:cz.muni.stanse.utils.xmlpatterns.XMLPattern.java

License:GNU General Public License

private static boolean matchingElements(final Element XMLpivot, final Element XMLelement,
        final XMLPatternVariablesAssignment varsAssignment) {
    if (XMLpivot.getName().equals("nested")) {
        final String elementName = XMLelement.getName();
        for (final Iterator<Attribute> j = XMLpivot.attributeIterator(); j.hasNext();)
            if (elementName.equals(j.next().getValue()))
                return false;
        return onNested(XMLpivot, XMLelement, varsAssignment);
    }//from   w ww. j  av  a 2  s .  c o m
    if (XMLpivot.getName().equals("ignore"))
        return true;
    if (XMLpivot.getName().equals("var")) {
        if (!satisfyVarConstraints(XMLelement.getName(), XMLpivot.attribute("match"),
                XMLpivot.attribute("except")))
            return false;
        varsAssignment.put(XMLpivot.attribute("name").getValue(), XMLelement);
        return true;
    }

    if (!XMLpivot.getName().equals(XMLelement.getName()))
        return false;
    if (!matchingAttributes(XMLpivot.attributes(), XMLelement))
        return false;
    if (XMLpivot.isTextOnly() != XMLelement.isTextOnly())
        return false;
    if (XMLpivot.isTextOnly() && !XMLpivot.getText().equals(XMLelement.getText()))
        return false;

    final Iterator<Element> i = XMLpivot.elementIterator();
    final Iterator<Element> j = XMLelement.elementIterator();
    while (i.hasNext() && j.hasNext()) {
        final Element pivotNext = i.next();
        if (pivotNext.getName().equals("any"))
            return true;
        if (!matchingElements(pivotNext, j.next(), varsAssignment))
            return false;
    }
    if (i.hasNext() || j.hasNext())
        return false;

    return true;
}

From source file:darks.orm.core.config.sqlmap.DMLConfigReader.java

License:Apache License

/**
 * Read and parse aspect XMLs file/*from  ww  w . j  a  v a2  s.c om*/
 * 
 * @param element Aspect tags
 * @return Aspect data
 */
private AspectData parseAspectXml(Element element) {
    Element aspectEl = element.element("aspect");
    if (aspectEl == null)
        return null;
    AspectData aspectData = new AspectData();
    boolean isNext = false;
    Element jythonEl = aspectEl.element("jython");
    if (jythonEl != null) {
        aspectData.setAspectType(AspectType.JYTHON);
        Attribute attr = jythonEl.attribute("className");
        if (attr == null)
            return null;
        aspectData.setClassName(attr.getValue().trim());
        String text = jythonEl.getText();
        if (text == null || "".equals(text.trim())) {
            String before = jythonEl.elementText("before");
            String after = jythonEl.elementText("after");
            if (before == null || "".equals(before.trim())) {
                if (after == null || "".equals(after.trim()))
                    return null;
            }
            text = PythonBuilder.buildBody(aspectData.getClassName(), before, after);
        }
        aspectData.setContent(text);
        isNext = true;
    }

    Element pyfileEl = aspectEl.element("pyfile");
    if (pyfileEl != null && isNext == false) {
        aspectData.setAspectType(AspectType.PYFILE);
        Attribute attr = pyfileEl.attribute("className");
        if (attr == null)
            return null;
        aspectData.setClassName(attr.getValue().trim());
        aspectData.setContent(pyfileEl.getTextTrim());
        isNext = true;
    }

    Element javaClassEl = aspectEl.element("javaClass");
    if (javaClassEl != null && isNext == false) {
        aspectData.setAspectType(AspectType.JAVACLASS);
        aspectData.setClassName(javaClassEl.getTextTrim());
        isNext = true;
    }

    Element jsEl = aspectEl.element("javascript");
    if (jsEl != null && isNext == false) {
        aspectData.setAspectType(AspectType.JAVASCRIPT);
        aspectData.setContent(jsEl.getTextTrim());
        isNext = true;
    }

    Element jsfileEl = aspectEl.element("jsfile");
    if (jsfileEl != null && isNext == false) {
        aspectData.setAspectType(AspectType.JSFILE);
        aspectData.setContent(jsfileEl.getTextTrim());
        isNext = true;
    }

    if (isNext) {
        return aspectData;
    }
    return null;
}

From source file:de.ailis.wlandsuite.game.parts.LibraryAction.java

License:Open Source License

/**
 * Creates and returns a new Library object by reading its data from XML.
 *
 * @param element/*from w  w  w . ja  v a2 s. c  o m*/
 *            The XML element
 * @return The library data
 */

public static LibraryAction read(final Element element) {
    LibraryAction library;

    library = new LibraryAction();
    library.name = element.attributeValue("name", "");
    library.message = StringUtils.toInt(element.attributeValue("message", "0"));
    library.newActionClass = StringUtils.toInt(element.attributeValue("newActionClass", "255"));
    library.newAction = StringUtils.toInt(element.attributeValue("newAction", "255"));

    final List<?> elements = element.elements("skill");
    library.skills = new int[elements.size()];
    int i = 0;
    for (final Object item : elements) {
        final Element subElement = (Element) item;
        library.skills[i] = StringUtils.toInt(subElement.getText());
        i++;
    }

    return library;
}

From source file:de.ailis.wlandsuite.game.parts.StoreAction.java

License:Open Source License

/**
 * Creates and returns a new Store object by reading its data from XML.
 *
 * @param element//w ww . j a  v  a2 s  .c o  m
 *            The XML element
 * @return The store data
 */

public static StoreAction read(final Element element) {
    StoreAction store;

    store = new StoreAction();
    store.name = element.attributeValue("name", "");
    store.message = StringUtils.toInt(element.attributeValue("message", "0"));
    store.buyFactor = StringUtils.toInt(element.attributeValue("buyFactor", "0"));
    store.sellFactor = StringUtils.toInt(element.attributeValue("sellFactor", "1"));
    store.itemList = StringUtils.toInt(element.attributeValue("itemList", "0"));
    store.newActionClass = StringUtils.toInt(element.attributeValue("newActionClass", "255"));
    store.newAction = StringUtils.toInt(element.attributeValue("newAction", "255"));

    final List<?> elements = element.elements("itemType");
    store.itemTypes = new int[elements.size()];
    int i = 0;
    for (final Object item : elements) {
        final Element subElement = (Element) item;
        store.itemTypes[i] = StringUtils.toInt(subElement.getText());
        i++;
    }

    return store;
}

From source file:de.ailis.wlandsuite.game.parts.Strings.java

License:Open Source License

/**
 * Creates and returns a new Strings object read from the specified XML
 * element.//w  ww .j  av a 2s.  co m
 *
 * @param element
 *            The XML element
 * @return The Strings object
 */

public static Strings read(final Element element) {
    Strings strings;

    // Create new strings object
    strings = new Strings(element.elements().size());

    // Read all the strings
    for (final Object subElement : element.elements("string")) {
        Element string;
        String text;
        int id;

        string = (Element) subElement;
        text = StringUtils.unescape(string.getText(), "ASCII");
        id = StringUtils.toInt(string.attributeValue("id"));
        if (id == strings.size()) {
            strings.add(text);
        } else if (id < strings.size()) {
            strings.set(id, text);
        } else {
            for (int i = strings.size(); i < id; i++) {
                strings.add("");
            }
            strings.add(text);
        }
    }

    // Return the newly created Strings object
    return strings;
}

From source file:de.ailis.xadrian.data.Complex.java

License:Open Source License

/**
 * Loads a complex from the specified XML document and returns it.
 *
 * @param document/*from   ww  w.  j  av  a  2  s  .co m*/
 *            The XML document
 * @return The complex
 * @throws DocumentException
 *             If XML file could not be read
 */
public static Complex fromXML(final Document document) throws DocumentException {
    final Element root = document.getRootElement();

    // Check the version
    final String versionStr = root.attributeValue("version");
    int version = 1;
    if (versionStr != null)
        version = Integer.parseInt(versionStr);
    if (version > 4)
        throw new DocumentException(I18N.getString("error.fileFormatTooNew"));

    // Determine the game for this complex.
    String gameId = "x3tc";
    if (version == 4)
        gameId = root.attributeValue("game");
    final Game game = GameFactory.getInstance().getGame(gameId);

    final Complex complex = new Complex(game);
    final FactoryFactory factoryFactory = game.getFactoryFactory();
    final SectorFactory sectorFactory = game.getSectorFactory();
    final WareFactory wareFactory = game.getWareFactory();
    final SunFactory sunsFactory = game.getSunFactory();

    complex.setSuns(sunsFactory.getSun(Integer.parseInt(root.attributeValue("suns"))));
    complex.setSector(sectorFactory.getSector(root.attributeValue("sector")));
    complex.setAddBaseComplex(Boolean.parseBoolean(root.attributeValue("addBaseComplex", "false")));
    complex.showingProductionStats = Boolean
            .parseBoolean(root.attributeValue("showingProductionStats", "false"));
    complex.showingShoppingList = Boolean.parseBoolean(root.attributeValue("showingShoppingList", "false"));
    complex.showingStorageCapacities = Boolean
            .parseBoolean(root.attributeValue("showingStorageCapacities", "false"));
    complex.showingComplexSetup = Boolean.parseBoolean(root.attributeValue("showingComplexSetup", "true"));

    // Get the factories parent element (In older version this was the root
    // node)
    Element factoriesE = root.element("complexFactories");
    if (factoriesE == null)
        factoriesE = root;

    // Read the complex factories
    for (final Object item : factoriesE.elements("complexFactory")) {
        final Element element = (Element) item;
        final Factory factory = factoryFactory.getFactory(element.attributeValue("factory"));
        final ComplexFactory complexFactory;
        final Element yieldsE = element.element("yields");
        if (yieldsE == null) {
            final int yield = Integer.parseInt(element.attributeValue("yield", "0"));
            final int quantity = Integer.parseInt(element.attributeValue("quantity"));
            complexFactory = new ComplexFactory(game, factory, quantity, yield);
        } else {
            final List<Integer> yields = new ArrayList<Integer>();
            for (final Object yieldItem : yieldsE.elements("yield")) {
                final Element yieldE = (Element) yieldItem;
                yields.add(Integer.parseInt(yieldE.getText()));
            }
            complexFactory = new ComplexFactory(game, factory, yields);
        }
        if (Boolean.parseBoolean(element.attributeValue("disabled", "false")))
            complexFactory.disable();
        complex.addFactory(complexFactory);
    }

    // Read the complex wares
    final Element waresE = root.element("complexWares");
    if (waresE != null) {
        complex.customPrices.clear();
        for (final Object item : waresE.elements("complexWare")) {
            final Element element = (Element) item;
            final Ware ware = wareFactory.getWare(element.attributeValue("ware"));
            final boolean use = Boolean.parseBoolean(element.attributeValue("use"));
            final int price = Integer.parseInt(element.attributeValue("price"));
            complex.customPrices.put(ware, use ? price : -price);
        }
    }

    final Element builtE = root.element("built");
    if (builtE != null) {
        complex.builtKits = Integer.parseInt(builtE.attributeValue("kits", "0"));
        for (final Object item : builtE.elements("factory")) {
            final Element element = (Element) item;
            final String id = element.attributeValue("id");
            final int quantity = Integer.parseInt(element.attributeValue("quantity"));
            complex.builtFactories.put(id, quantity);
        }
    }

    complex.calculateBaseComplex();
    return complex;
}