Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element getAttribute.

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

Usage

From source file:se.miun.itm.input.model.mapping.Wrapper.java

License:Open Source License

private String initGetter(Element mapping, Element wrap, String localId) {
    if (wrap.getAttribute(Q.GET_ATTR) != null)
        return wrap.getAttributeValue(Q.GET_ATTR);
    return Q.GET_ATTR + localId;
}

From source file:shuffling.ConfigurationParser.java

public void readConfigs() {
    SAXBuilder sxb = new SAXBuilder();
    try {//w ww .  j a va2 s  .  c  o  m
        Document configDoc = sxb.build(Util.load(sConfigFile));
        //Document configDoc = sxb.build(new File(sConfigFile));
        Element rootElmt = configDoc.getRootElement();
        Iterator<Element> iterator = rootElmt.getChildren().iterator();

        while (iterator.hasNext()) {//for each wave
            Element waveElem = (Element) iterator.next();
            String waveName = waveElem.getName();
            if (waveName.equals("WaveDescription")) {

                String waveDscrpt = waveElem.getAttributeValue("Number");
                GameWave gamewave = new GameWave();//a new wave
                gamewave.setWaveDscrp(waveDscrpt);//set the wave description

                List listGames = waveElem.getChildren();
                Iterator igames = listGames.iterator();

                Setting setting = new Setting();

                ObjectSortingGame osgame = new ObjectSortingGame();

                while (igames.hasNext()) {
                    Element element = (Element) igames.next();

                    if (element.getName().equals("GeneralSetting")) {
                        Element screenSizeChild = element.getChild("ScreenSize");
                        setting.screenSize[0] = Integer.valueOf(screenSizeChild.getAttributeValue("x"));
                        setting.screenSize[1] = Integer.valueOf(screenSizeChild.getAttributeValue("y"));
                        List<Element> settingElements = element.getChildren("Object");
                        for (Element element2 : settingElements) {
                            Color color = new Color(Integer.valueOf(element2.getAttributeValue("r")),
                                    Integer.valueOf(element2.getAttributeValue("g")),
                                    Integer.valueOf(element2.getAttributeValue("b")));
                            setting.objectColors.put(Integer.valueOf(element2.getAttributeValue("type")),
                                    color);
                        }
                        Element settingElement = element.getChild("SourceAttender");
                        Element colorElement = settingElement.getChild("SelfColor");
                        Color color = new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                Integer.valueOf(colorElement.getAttributeValue("g")),
                                Integer.valueOf(colorElement.getAttributeValue("b")));
                        setting.soSelfColor = color;
                        colorElement = settingElement.getChild("OtherColor");
                        color = new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                Integer.valueOf(colorElement.getAttributeValue("g")),
                                Integer.valueOf(colorElement.getAttributeValue("b")));
                        setting.soOtherColor = color;
                        setting.soSelfSize = Integer.valueOf(settingElement.getChild("SelfSize").getValue());
                        setting.soOtherSize = Integer.valueOf(settingElement.getChild("OtherSize").getValue());
                        setting.soSpeedCarrying = Integer
                                .valueOf(settingElement.getChild("SpeedCarrying").getValue());
                        setting.soSpeedUnladen = Integer
                                .valueOf(settingElement.getChild("SpeedUnladen").getValue());
                        settingElement = element.getChild("SinkAttender");
                        colorElement = settingElement.getChild("SelfColor");
                        color = new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                Integer.valueOf(colorElement.getAttributeValue("g")),
                                Integer.valueOf(colorElement.getAttributeValue("b")));
                        setting.siSelfColor = color;
                        colorElement = settingElement.getChild("OtherColor");
                        color = new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                Integer.valueOf(colorElement.getAttributeValue("g")),
                                Integer.valueOf(colorElement.getAttributeValue("b")));
                        setting.siOtherColor = color;
                        setting.siSelfSize = Integer.valueOf(settingElement.getChild("SelfSize").getValue());
                        setting.siOtherSize = Integer.valueOf(settingElement.getChild("OtherSize").getValue());
                        setting.siSpeedCarrying = Integer
                                .valueOf(settingElement.getChild("SpeedCarrying").getValue());
                        setting.siSpeedUnladen = Integer
                                .valueOf(settingElement.getChild("SpeedUnladen").getValue());
                        // SOURCE READ
                    } else if (element.getName().equals("SourceDescription")) {
                        setting.line1Position = Integer.valueOf(element.getChild("LeftBoundary").getValue());
                        List<Element> sourceList = element.getChildren("Source");
                        for (Element sourceElement : sourceList) {
                            Source source = new Source();
                            source.setId(sourceElement.getAttributeValue("Number"));
                            List<Element> objects = sourceElement.getChild("Proportions").getChildren();
                            double sum = 0;
                            for (Element element2 : objects) {
                                source.getProportionMap().put(
                                        Integer.valueOf(element2.getAttributeValue("type")),
                                        Double.valueOf(element2.getAttributeValue("proportion")));
                                sum += Double.valueOf(element2.getAttributeValue("proportion"));
                            }
                            if (sum != 1) {
                                throw new Exception("Proportion values should add up to 1");
                            }
                            source.setPosition(new int[] {
                                    Integer.valueOf(
                                            sourceElement.getChild("Location").getChild("X").getValue()),
                                    Integer.valueOf(
                                            sourceElement.getChild("Location").getChild("Y").getValue()) });
                            source.setSize(Integer
                                    .valueOf(sourceElement.getChild("Appearance").getChild("Size").getValue()));
                            Element colorElement = sourceElement.getChild("Appearance").getChild("Color");
                            source.setColor(new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                    Integer.valueOf(colorElement.getAttributeValue("g")),
                                    Integer.valueOf(colorElement.getAttributeValue("b"))));
                            setting.sourceList.add(source);
                        }
                        // SINK READ
                    } else if (element.getName().equals("SinkDescription")) {
                        setting.line2Position = Integer.valueOf(element.getChild("RightBoundary").getValue());
                        List<Element> sinkList = element.getChildren("Sink");
                        for (Element sinkElement : sinkList) {
                            Sink sink = new Sink();
                            sink.setId(sinkElement.getAttributeValue("Number"));
                            sink.setPosition(new int[] {
                                    Integer.valueOf(sinkElement.getChild("Location").getChild("X").getValue()),
                                    Integer.valueOf(
                                            sinkElement.getChild("Location").getChild("Y").getValue()) });
                            sink.setAcceptingObject(
                                    Integer.valueOf(sinkElement.getChild("TargetType").getValue()));
                            sink.setSize(Integer
                                    .valueOf(sinkElement.getChild("Appearance").getChild("Size").getValue()));
                            Element colorElement = sinkElement.getChild("Appearance").getChild("Color");
                            sink.setColor(new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                    Integer.valueOf(colorElement.getAttributeValue("g")),
                                    Integer.valueOf(colorElement.getAttributeValue("b"))));
                            setting.sinkList.add(sink);
                        }
                        // BASE READ
                    } else if (element.getName().equals("BaseDescription")) {
                        List<Element> baseList = element.getChildren();
                        for (Element baseElement : baseList) {
                            Base base = new Base();
                            base.setId(baseElement.getAttributeValue("Number"));
                            base.setPosition(new int[] {
                                    Integer.valueOf(baseElement.getChild("Location").getChild("X").getValue()),
                                    Integer.valueOf(
                                            baseElement.getChild("Location").getChild("Y").getValue()) });
                            base.setSize(Integer
                                    .valueOf(baseElement.getChild("Appearance").getChild("Size").getValue()));
                            Element colorElement = baseElement.getChild("Appearance").getChild("Color");
                            base.setColor(new Color(Integer.valueOf(colorElement.getAttributeValue("r")),
                                    Integer.valueOf(colorElement.getAttributeValue("g")),
                                    Integer.valueOf(colorElement.getAttributeValue("b"))));
                            if (baseElement.getAttribute("enabled").getBooleanValue()) {
                                setting.baseList.add(base);
                            }
                        }
                    } else if (element.getName().equals("FeedbackDisplay")) {
                        setting.gameEndCriterion = Integer
                                .valueOf(element.getChild("GameEndCriterion").getValue());
                        setting.maxDropOffRate = Integer.valueOf(element.getChild("MaxDropOffRate").getValue());
                        setting.timeWindow = Integer.valueOf(element.getChild("TimeWindow").getValue());
                    } else if (element.getName().equals("GameParameters")) {
                        long maxRunningTime = Long.valueOf(element.getChild("TimeOut").getValue());
                        osgame.setGameTime(maxRunningTime);
                    } else if (element.getName().equals("Game")) {

                        List listGroups = element.getChildren();
                        Iterator igroups = listGroups.iterator();

                        while (igroups.hasNext()) {//for each group
                            Element groupElmt = (Element) igroups.next();

                            Setting temp = new Setting();
                            temp.copyGeneralInfo(setting);
                            GameStatus status = new GameStatus();
                            if (groupElmt.getName().equals("Group")) {
                                List<Element> playerList = groupElmt.getChildren();
                                for (Element playerElement : playerList) {
                                    Player player = new Player();
                                    player.setId(playerElement.getAttributeValue("Number"));
                                    player.setSpeedMultiplier(Double
                                            .valueOf(playerElement.getChild("SpeedMultiplier").getValue()));
                                    player.setPosition(new int[] {
                                            Integer.valueOf(playerElement.getChild("Location").getChild("X")
                                                    .getValue()),
                                            Integer.valueOf(playerElement.getChild("Location").getChild("Y")
                                                    .getValue()) });
                                    player.setSourceAttender(
                                            (playerElement.getChild("Type").getValue().equals("1")));

                                    temp.playerList.add(player);
                                    status.players.add(player);
                                    status.playerDropOffMap.put(player.getId(), new ArrayList<Long>());

                                }
                                osgame.groupSettingList.add(temp);
                                osgame.groupStatusList.add(status);
                            }
                        } //end of each group 
                    } //end of each game
                }
                gamewave.addGame(osgame);
                this.gameWaveList.add(gamewave);
            } //end of if

        } //for each wave
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error Reading Setting File: \n" + e.getMessage());
    }
}

From source file:site.util.EvXmlUtil.java

License:BSD License

/**
 * Checks if name and attributes equal, not content
 *//*from  ww w  . j a v a2  s . co  m*/
public static boolean elementsEqual(Element a, Element b) {
    if (a.getName().equals(b.getName())) {
        for (Object o : a.getAttributes()) {
            Attribute attra = (Attribute) o;
            Attribute attrb = b.getAttribute(attra.getName());
            if (attrb == null)
                return false;
            if (!attra.getValue().equals(attrb.getValue()))
                return false;
        }
        for (Object o : b.getAttributes()) {
            Attribute attrb = (Attribute) o;
            Attribute attra = a.getAttribute(attrb.getName());
            if (attra == null)
                return false;
            if (!attrb.getValue().equals(attra.getValue()))
                return false;
        }
        return true;
    } else
        return false;
}

From source file:strategies.HeldStock.java

public void LoadFromXml(Element heldElement) {
    Attribute attribute = heldElement.getAttribute("ticker");
    tickerSymbol = attribute.getValue();

    List<Element> purchaseElements = heldElement.getChildren();
    for (Element purchaseElement : purchaseElements) {
        StockPurchase purchase = new StockPurchase();
        purchase.LoadFromXml(purchaseElement);
        purchases.add(purchase);//from   ww  w  . j a v a  2s  .  co  m
    }
}

From source file:strategies.StatusDataForNinety.java

public void LoadTradingStatus() {

    heldStocks.clear();//  w  w w  .  j  a  v  a2  s  .  c o  m
    try {
        File inputFile = new File(FilePaths.tradingStatusPathFileInput);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(inputFile);

        Element rootElement = document.getRootElement();

        Element moneyElement = rootElement.getChild("money");

        Attribute attribute = moneyElement.getAttribute("currentCash");
        currentCash = attribute.getDoubleValue();

        attribute = moneyElement.getAttribute("currentFees");
        currentFees = attribute.getDoubleValue();

        List<Element> heldStocksElements = rootElement.getChild("heldPositions").getChildren();

        for (Element heldElement : heldStocksElements) {
            HeldStock held = new HeldStock();
            held.LoadFromXml(heldElement);

            heldStocks.put(held.tickerSymbol, held);
        }
    } catch (JDOMException e) {
        logger.severe("Error in loading from XML: JDOMException.\r\n" + e);
    } catch (IOException ioe) {
        logger.severe("Error in loading from XML: IOException.\r\n" + ioe);
    }
}

From source file:strategies.StockPurchase.java

void LoadFromXml(Element purchaseElement) {
    try {/*from  ww  w. ja va 2s.c  o  m*/
        Attribute attribute = purchaseElement.getAttribute("priceForOne");
        priceForOne = attribute.getDoubleValue();

        attribute = purchaseElement.getAttribute("position");
        position = attribute.getIntValue();

        attribute = purchaseElement.getAttribute("portions");
        portions = attribute.getIntValue();

        attribute = purchaseElement.getAttribute("date");
        date = LocalDate.parse(attribute.getValue());

    } catch (DataConversionException ex) {
        logger.severe("Error in loading from XML: Failed to convert values in purchases. " + ex.getMessage());
    }
}

From source file:tds.itemscoringengine.itemscorers.QTIRubricScorer.java

License:Open Source License

public ItemScore scoreItem(ResponseInfo responseInfo) {
    ItemScore score = new ItemScore(-1, -1, ScoringStatus.NotScored, "overall", new ScoreRationale(),
            responseInfo.getContextToken()); // We
    // Shiva: I added the follow null check on the response as it makes it
    // easier to test it on the web
    // interface with a REST client.
    String response = responseInfo.getStudentResponse();
    if (response != null) {
        response = response.trim();/* w w  w  .  j a v a 2s .c o  m*/
        responseInfo.setStudentResponse(response);
    }

    // Max
    // score
    // is
    long startTime = System.currentTimeMillis();
    Map<String, String> identifiersAndResponses = new HashMap<String, String>();
    // first try to retrieve the item response, and the identifier
    try {
        XmlReader reader = new XmlReader(new StringReader(responseInfo.getStudentResponse()));
        Document doc = reader.getDocument();

        List<Element> responseNodes = new XmlElement(doc.getRootElement())
                .selectNodes("//itemResponse/response");
        for (Element elem : responseNodes) {
            String identifier = elem.getAttribute("id").getValue();
            List<String> responses = new ArrayList<String>();
            List<Element> valueNodes = new XmlElement(elem).selectNodes("value");
            for (Element valElem : valueNodes) {
                responses.add(new XmlElement(valElem).getInnerText());
            }

            identifiersAndResponses.put(identifier, StringUtils.join(responses, ","));
        }

    } catch (final Exception e) {
        e.printStackTrace();
        _logger.error("Error loading responses " + e.getMessage());
        score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
        score.getScoreInfo().getRationale().setMsg("Error loading response. Message: " + e.getMessage());
        score.getScoreInfo().getRationale().setException(e);
        return score;
    }

    if (identifiersAndResponses.size() == 0) {
        // This could be a response from a grid/ti/eq item being scored using a
        // QTI version of our proprietary rubrics
        // Check if this is a TI/GI/SIM/EQ and unfortunately, there is no clean
        // way to figure this out other than resorting to this hack
        response = responseInfo.getStudentResponse();

        if (!StringUtils.isEmpty(response) && ((response.toUpperCase().startsWith("<RESPONSESPEC>")
                || response.toUpperCase().startsWith("<RESPONSETABLE>")) || // TI
                (response.toUpperCase().startsWith("<RESPONSE>")) || // EQ
                (response.toUpperCase().contains("<ANSWERSET>"))) // GI
        ) {
            identifiersAndResponses.put("RESPONSE", responseInfo.getStudentResponse());
        } else {
            _logger.error("No responses found");
            score.getScoreInfo().getRationale().setMsg("No responses found");
            return score;
        }
    }

    try {
        if (wasThereErrorWithRubric()) {
            _logger.error(String.format("Error validating rubric. File %s. Message %s",
                    responseInfo.getRubric().toString(), getErrorMessageIfAny()));
            score.getScoreInfo().getRationale().setMsg(getErrorMessageIfAny());
            return score;
        }

        // now score the item
        String[] scoreArr = null;
        List<String[]> bindings = _rubric.evaluate(identifiersAndResponses);
        for (String[] binding : bindings) {
            if ("score".equalsIgnoreCase(binding[0]))
                scoreArr = binding;
        }

        // error check the score result
        if (scoreArr == null) {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale()
                    .setMsg("There was no SCORE identifier specified for the identifiers "
                            + StringUtils.join(identifiersAndResponses.keySet(), ','));
            return score;
        }
        if (scoreArr.length < 4 || StringUtils.isEmpty(scoreArr[3])) {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale().setMsg("There was no score specified for the identifiers "
                    + StringUtils.join(identifiersAndResponses.keySet(), ','));
            return score;
        }

        // try to parse the actual score value -- note the score value is
        // hardcoded to be at index 3
        _Ref<Double> dScore = new _Ref<>();
        if (JavaPrimitiveUtils.doubleTryParse(scoreArr[3], dScore)) {
            // note: we truncate the double score to be an int
            score.getScoreInfo().setPoints((int) Math.ceil(Math.max(dScore.get(), 0)));
            score.getScoreInfo().setStatus(ScoringStatus.Scored);
            score.getScoreInfo().getRationale().setMsg("successfully scored");

            // populate the requested outgoing bindings
            if (responseInfo.getOutgoingBindings() != null) {
                if (responseInfo.getOutgoingBindings().contains(VarBinding.ALL)) // All
                                                                                 // bindings
                                                                                 // requested
                {
                    score.getScoreInfo().getRationale().setBindings(new ArrayList<VarBinding>());

                    CollectionUtils.collect(bindings, new Transformer() {

                        @Override
                        public Object transform(Object arg0) {
                            final String[] variable = (String[]) arg0;
                            return new VarBinding() {
                                {
                                    setName(variable[0]);
                                    setType(variable[1]);
                                    setValue(variable[3]);
                                }
                            };
                        }
                    }, score.getScoreInfo().getRationale().getBindings());

                } else // Specific bindings requested
                {
                    score.getScoreInfo().getRationale().setBindings(new ArrayList<VarBinding>());
                    for (final VarBinding outgoingBinding : responseInfo.getOutgoingBindings()) {

                        final String[] binding = (String[]) CollectionUtils.find(bindings, new Predicate() {

                            @Override
                            public boolean evaluate(Object arg0) {
                                return StringUtils.equals(((String[]) arg0)[0], outgoingBinding.getName());
                            }
                        });

                        if (binding != null)
                            score.getScoreInfo().getRationale().getBindings().add(new VarBinding() {
                                {
                                    setName(binding[0]);
                                    setType(binding[1]);
                                    setValue(binding[3]);
                                }
                            });

                    }
                }
            }

            // populate any subscores that might have been recorded as internal
            // scoring state
            for (Object stateObj : _rubric.getResponseProcessingState()) {
                ItemScore subScore = (ItemScore) stateObj;
                if (subScore != null) {
                    if (score.getScoreInfo().getSubScores() == null)
                        score.getScoreInfo().setSubScores(new ArrayList<ItemScoreInfo>());

                    // remove any bindings from the subscore that is not requested as an
                    // outgoing binding
                    if (responseInfo.getOutgoingBindings() == null) {
                        // No bindings requested - clear everything
                        // TODO: Recursively go through the subscore's children to clear
                        // those bindings also.
                        subScore.getScoreInfo().getRationale().getBindings().clear();
                    } else if (responseInfo.getOutgoingBindings().contains(VarBinding.ALL)) {
                        // All bindings requested
                        // don't remove anything. let them all through
                    } else {
                        // specific bindings requested. Remove anything not explicitly
                        // asked for.
                        // TODO: Recursively go through the subscore's children to filter
                        // them also
                        VarBinding[] subScoreBindings = subScore.getScoreInfo().getRationale().getBindings()
                                .toArray(new VarBinding[subScore.getScoreInfo().getRationale().getBindings()
                                        .size()]);

                        for (int counter1 = 0; counter1 < subScoreBindings.length; ++counter1) {
                            final VarBinding subScoreBinding = subScoreBindings[counter1];
                            if (!CollectionUtils.exists(responseInfo.getOutgoingBindings(), new Predicate() {

                                @Override
                                public boolean evaluate(Object arg0) {
                                    return StringUtils.equals(((VarBinding) arg0).getName(),
                                            subScoreBinding.getName());
                                }
                            })) {
                                subScore.getScoreInfo().getRationale().getBindings().remove(counter1);
                                --counter1;
                            }
                        }

                    }
                    score.getScoreInfo().getSubScores().add(subScore.getScoreInfo());
                }

            }
            // note: ScoreLatency is miliseconds
            score.setScoreLatency(System.currentTimeMillis() - startTime);
            return score;

        } else {
            score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
            score.getScoreInfo().getRationale().setMsg("Error changing score to int, score array values='"
                    + StringUtils.join(scoreArr, ',') + "'.");
            return score;
        }

    } catch (final Exception e) {
        e.printStackTrace();
        _logger.error("Error : " + e.getMessage());
        score.getScoreInfo().setPoints(-1);
        score.getScoreInfo().setStatus(ScoringStatus.ScoringError);
        score.getScoreInfo().getRationale().setMsg("Error processing rubric. Message: " + e.getMessage());
        score.getScoreInfo().getRationale().setException(e);
        return score;
    }
}

From source file:tinyctrlscoringengine.CtrlCustomOpFactory.java

License:Open Source License

@Override
public boolean supportsOperator(Element customOperatorNode) {
    Element coElement = customOperatorNode;

    if (!StringUtils.equals(coElement.getAttribute("type").getValue(), "CTRL"))
        return false;

    return _ctrlConstructors.containsKey(coElement.getAttribute("functionName").getValue());
}

From source file:tinyctrlscoringengine.CtrlCustomOpFactory.java

License:Open Source License

@Override
public Expression createExpression(Element customOperatorNode) {
    Element coElement = customOperatorNode;
    return (Expression) _ctrlConstructors.get(coElement.getAttribute("functionName").getValue())
            .getExpression(coElement);//from ww w  .  j a  v  a2 s.c o m
}

From source file:tinyequationscoringengine.TinyEqCustomOpFactory.java

License:Open Source License

public boolean supportsOperator(Element customOperatorNode) {
    Element coElement = customOperatorNode;
    if (!"EQ".equals(coElement.getAttribute("type").getValue()))
        return false;

    return _eqConstructors.containsKey(coElement.getAttribute("functionName").getValue());
}