Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

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

Prototype

List<Element> elements(QName qName);

Source Link

Document

Returns the elements contained in this element with the given fully qualified name.

Usage

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

/**
 * Converts a MultiTerm MTF concept group to a GlobalSight concept
 * group. Differences:// w  ww. ja v  a  2  s. co  m
 *
 *  - <system type="entryClass|status"> -->
 *    <descrip type="entryClass|status">
 *
 *  - <language type="English" lang="EN" /> -->
 *    <language name="English" locale="en_US" />
 *
 *  - <descripGrp><descrip type="note"> -->
 *    <noteGrp><note>
 *
 *  - <descripGrp><descrip type="source"> -->
 *    <sourceGrp><source>
 *
 *  - descripGrp is recursive, must map to noteGrps or delete.
 *
 *  - remove empty descripGrp <descrip type="Graphic"/>
 */
private Element convertMtf(Element p_elem) {
    List nodes;
    Node node;
    Element elem;
    Iterator it;
    ListIterator lit;

    // fix <system>
    nodes = p_elem.elements("system");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        p_elem.remove(elem);
        p_elem.addElement("descrip").addAttribute("type", elem.attributeValue("type")).addText(elem.getText());
    }

    // fix Graphic; we cannot handle them, so remove them
    nodes = p_elem.selectNodes("descripGrp[descrip/@type='Graphic']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();
        p_elem.remove(elem);
    }

    // convert <descripGrp><descrip type="note"> to noteGrp
    nodes = p_elem.selectNodes(".//descripGrp[descrip/@type='note']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        convertToNoteGrp(elem);
    }

    // convert <descripGrp><descrip type="source"> to sourceGrp
    nodes = p_elem.selectNodes(".//descripGrp[descrip/@type='source']");
    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        convertToSourceGrp(elem);
    }

    // Convert recursive descripGrps to noteGrps if possible.
    convertRecursiveDescripGrps(p_elem, ".//conceptGrp/descripGrp");
    convertRecursiveDescripGrps(p_elem, ".//languageGrp/descripGrp");
    convertRecursiveDescripGrps(p_elem, ".//termGrp/descripGrp");

    // Remove the recursive descripGrps that are left over.
    // (In case there are doubly recursive descrips and stuff.)
    removeRecursiveDescripGrps(p_elem);

    // fix <language>
    nodes = p_elem.selectNodes("languageGrp/language");

    for (it = nodes.iterator(); it.hasNext();) {
        elem = (Element) it.next();

        Attribute nameAttr = elem.attribute("type");
        Attribute langAttr = elem.attribute("lang");

        String langName = nameAttr.getValue();
        String langLocale = langAttr.getValue();

        // locales in entries consist of 2 letter codes.
        langLocale = langLocale.substring(0, 2).toLowerCase();

        elem.remove(nameAttr);
        elem.remove(langAttr);

        elem.addAttribute("name", langName);
        elem.addAttribute("locale", langLocale);
    }

    return p_elem;
}

From source file:com.globalsight.util.file.XliffFileUtil.java

License:Apache License

public static boolean containsFileTag(String p_filename) {
    if (StringUtil.isEmpty(p_filename))
        return false;

    try {//  ww  w.j  a va2  s  .  c  om
        SAXReader saxReader = new SAXReader();
        Document document = null;
        Element rootElement = null;

        File file = new File(p_filename);
        if (file.exists() && file.isFile()) {
            document = saxReader.read(file);
            rootElement = document.getRootElement();
            String tag = "";
            List fileTags = rootElement.elements("file");
            if (fileTags != null) {
                for (int i = 0; i < fileTags.size(); i++) {
                    Element element = (Element) fileTags.get(i);
                    String attr = element.attributeValue("tool");
                    if (attr == null)
                        return false;
                    else {
                        if (attr.toLowerCase().contains("worldserver"))
                            return true;
                    }
                }
            }
        }
        return false;
    } catch (Exception e) {
        logger.error("Can not verify if current file contains multiple file tags.", e);
        return false;
    }
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

/**
 * Validates the sub elements inside a TMX tag. This means adding a <sub
 * locType="..."> attribute.//from   w  ww. j a v a  2  s. com
 * 
 * @param p_elem
 * @param p_x_count
 * @throws Exception
 */
private void validateSubs(Element p_elem, IntHolder p_x_count) throws Exception {
    List subs = p_elem.elements("sub");

    for (int i = 0, max = subs.size(); i < max; i++) {
        Element sub = (Element) subs.get(i);
        validateSegment(sub, p_x_count);
    }
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

/**
 * Converts a DOM TU to a GS SegmentTmTu, thereby converting any TMX format
 * specialities as best as possible./*from   w w  w.  j  a v  a2s .co m*/
 * 
 * @param p_root
 *            Element
 * @param ptm
 * @throws Exception
 */
private void editTm2Tu(Element p_root) throws Exception {
    // Original TU id, if known
    String id = p_root.attributeValue(Tmx.TUID);
    ProjectTmTuT tu = null;
    try {
        if (id != null && id.length() > 0) {
            long lid = Long.parseLong(id);
            tu = HibernateUtil.get(ProjectTmTuT.class, lid);
            if (tu == null) {
                throw new Exception("Can not find tu with id: " + lid);
            }
        } else {
            throw new Exception("Can not find tu id");
        }
        // Datatype of the TU (html, javascript etc)
        String format = p_root.attributeValue(Tmx.DATATYPE);
        if (format == null || format.length() == 0) {
            format = "html";
        }
        tu.setFormat(format.trim());
        // Locale of Source TUV (use default from header)
        String lang = p_root.attributeValue(Tmx.SRCLANG);
        if (lang == null || lang.length() == 0) {
            lang = "en_US";
        }
        String locale = ImportUtil.normalizeLocale(lang);
        LocaleManagerLocal manager = new LocaleManagerLocal();
        tu.setSourceLocale(manager.getLocaleByString(locale));
        // Segment type (text, css-color, etc)
        String segmentType = "text";
        Node node = p_root.selectSingleNode(".//prop[@type = '" + Tmx.PROP_SEGMENTTYPE + "']");
        if (node != null) {
            segmentType = node.getText();
        }
        tu.setType(segmentType);
        // Sid
        node = p_root.selectSingleNode(".//prop[@type= '" + Tmx.PROP_TM_UDA_SID + "']");
        if (node != null) {
            tu.setSid(node.getText());
        }
        // TUVs
        List nodes = p_root.elements("tuv");
        for (int i = 0; i < nodes.size(); i++) {
            Element elem = (Element) nodes.get(i);
            ProjectTmTuvT tuv = new ProjectTmTuvT();
            tuv.reconvertFromTmx(elem, tu);

            // Check the locale
            List<ProjectTmTuvT> savedTuvs = new ArrayList<ProjectTmTuvT>();
            for (ProjectTmTuvT savedTuv : tu.getTuvs()) {
                if (savedTuv.getLocale().equals(tuv.getLocale())) {
                    savedTuvs.add(savedTuv);
                }
            }

            if (savedTuvs.size() == 0) {
                throw new WebServiceException(
                        "Can not find tuv with tu id: " + tu.getId() + ", locale: " + tuv.getLocale());
            }

            // More than one tuv have the locale, than go to check the
            // create
            // date.
            if (savedTuvs.size() > 1) {
                boolean find = false;
                for (ProjectTmTuvT savedTuv : savedTuvs) {
                    if (savedTuv.getCreationDate().getTime() == tuv.getCreationDate().getTime()) {
                        find = true;
                        savedTuv.merge(tuv);
                        HibernateUtil.save(savedTuv);
                    }
                }
                if (!find) {
                    throw new WebServiceException("Can not find tuv with tu id: " + tu.getId() + ", locale: "
                            + tuv.getLocale() + ", creation date:" + tuv.getCreationDate());
                }
            } else {
                ProjectTmTuvT savedTuv = savedTuvs.get(0);
                savedTuv.merge(tuv);
                HibernateUtil.save(savedTuv);
            }
        }
        HibernateUtil.save(tu);
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

private void editTm3Tu(Element p_root, ProjectTM ptm) throws Exception {
    String tuId = p_root.attributeValue(Tmx.TUID);
    BaseTm tm = TM3Util.getBaseTm(ptm.getTm3Id());
    TM3Tu tm3Tu = tm.getTu(Long.parseLong(tuId));

    TM3Attribute typeAttr = TM3Util.getAttr(tm, TYPE);
    TM3Attribute formatAttr = TM3Util.getAttr(tm, FORMAT);
    TM3Attribute sidAttr = TM3Util.getAttr(tm, SID);
    TM3Attribute translatableAttr = TM3Util.getAttr(tm, TRANSLATABLE);
    TM3Attribute fromWsAttr = TM3Util.getAttr(tm, FROM_WORLDSERVER);
    TM3Attribute projectAttr = TM3Util.getAttr(tm, UPDATED_BY_PROJECT);
    SegmentTmTu tu = TM3Util.toSegmentTmTu(tm3Tu, ptm.getId(), formatAttr, typeAttr, sidAttr, fromWsAttr,
            translatableAttr, projectAttr);

    // Datatype of the TU (html, javascript etc)
    String format = p_root.attributeValue(Tmx.DATATYPE);
    if (format == null || format.length() == 0) {
        format = "html";
    }/*from  ww w .j  a v  a  2  s  .  c  o  m*/
    tu.setFormat(format.trim());
    // Locale of Source TUV (use default from header)
    String lang = p_root.attributeValue(Tmx.SRCLANG);
    if (lang == null || lang.length() == 0) {
        lang = "en_US";
    }
    String locale = ImportUtil.normalizeLocale(lang);
    LocaleManagerLocal manager = new LocaleManagerLocal();
    tu.setSourceLocale(manager.getLocaleByString(locale));
    // Segment type (text, css-color, etc)
    String segmentType = "text";
    Node node = p_root.selectSingleNode(".//prop[@type = '" + Tmx.PROP_SEGMENTTYPE + "']");
    if (node != null) {
        segmentType = node.getText();
    }
    tu.setType(segmentType);
    // Sid
    String sid = null;
    node = p_root.selectSingleNode(".//prop[@type= '" + Tmx.PROP_TM_UDA_SID + "']");
    if (node != null) {
        sid = node.getText();
        tu.setSID(sid);
    }
    // TUVs
    List nodes = p_root.elements("tuv");
    List<SegmentTmTuv> tuvsToBeUpdated = new ArrayList<SegmentTmTuv>();
    for (int i = 0; i < nodes.size(); i++) {
        Element elem = (Element) nodes.get(i);
        SegmentTmTuv tuv = new SegmentTmTuv();
        PageTmTu pageTmTu = new PageTmTu(-1, -1, "plaintext", "text", true);
        tuv.setTu(pageTmTu);
        tuv.setSid(sid);
        TmxUtil.convertFromTmx(elem, tuv);

        Collection splitSegments = tuv.prepareForSegmentTm();

        Iterator itSplit = splitSegments.iterator();
        while (itSplit.hasNext()) {
            AbstractTmTuv.SegmentAttributes segAtt = (AbstractTmTuv.SegmentAttributes) itSplit.next();
            String segmentString = segAtt.getText();
            tuv.setSegment(segmentString);
        }
        // Check the locale
        List<SegmentTmTuv> savedTuvs = new ArrayList<SegmentTmTuv>();
        for (BaseTmTuv savedTuv : tu.getTuvs()) {
            if (savedTuv.getLocale().equals(tuv.getLocale())) {
                savedTuvs.add((SegmentTmTuv) savedTuv);
            }
        }

        if (savedTuvs.size() > 1) {
            boolean find = false;
            for (SegmentTmTuv savedTuv : savedTuvs) {
                if (savedTuv.getCreationDate().getTime() == tuv.getCreationDate().getTime()) {
                    find = true;
                    savedTuv.merge(tuv);
                    tuvsToBeUpdated.add(savedTuv);
                }
            }
            if (!find) {
                throw new WebServiceException("Can not find tuv with tu id: " + tu.getId() + ", locale: "
                        + tuv.getLocale() + ", creation date:" + tuv.getCreationDate());
            }
        } else {
            SegmentTmTuv savedTuv = savedTuvs.get(0);
            savedTuv.merge(tuv);
            tuvsToBeUpdated.add(savedTuv);
        }
    }

    ptm.getSegmentTmInfo().updateSegmentTmTuvs(ptm, tuvsToBeUpdated);
}

From source file:com.google.jenkins.flakyTestHandler.junit.FlakySuiteResult.java

License:Open Source License

private static void parseSuite(File xmlReport, boolean keepLongStdio, List<FlakySuiteResult> r, Element root)
        throws DocumentException, IOException {
    // nested test suites
    @SuppressWarnings("unchecked")
    List<Element> testSuites = (List<Element>) root.elements("testsuite");
    for (Element suite : testSuites)
        parseSuite(xmlReport, keepLongStdio, r, suite);

    // child test cases
    // FIXME: do this also if no testcases!
    if (root.element("testcase") != null || root.element("error") != null)
        r.add(new FlakySuiteResult(xmlReport, root, keepLongStdio));
}

From source file:com.google.jenkins.flakyTestHandler.junit.FlakySuiteResult.java

License:Open Source License

/**
 * @param xmlReport/*from  w w w .j av  a 2s .  co  m*/
 *      A JUnit XML report file whose top level element is 'testsuite'.
 * @param suite
 *      The parsed result of {@code xmlReport}
 */
private FlakySuiteResult(File xmlReport, Element suite, boolean keepLongStdio)
        throws DocumentException, IOException {
    this.file = xmlReport.getAbsolutePath();
    String name = suite.attributeValue("name");
    if (name == null)
        // some user reported that name is null in their environment.
        // see http://www.nabble.com/Unexpected-Null-Pointer-Exception-in-Hudson-1.131-tf4314802.html
        name = '(' + xmlReport.getName() + ')';
    else {
        String pkg = suite.attributeValue("package");
        if (pkg != null && pkg.length() > 0)
            name = pkg + '.' + name;
    }
    this.name = TestObject.safe(name);
    this.timestamp = suite.attributeValue("timestamp");
    this.id = suite.attributeValue("id");

    Element ex = suite.element("error");
    if (ex != null) {
        // according to junit-noframes.xsl l.229, this happens when the test class failed to load
        addCase(new FlakyCaseResult(this, suite, "<init>", keepLongStdio));
    }

    @SuppressWarnings("unchecked")
    List<Element> testCases = (List<Element>) suite.elements("testcase");
    for (Element e : testCases) {
        // https://issues.jenkins-ci.org/browse/JENKINS-1233 indicates that
        // when <testsuites> is present, we are better off using @classname on the
        // individual testcase class.

        // https://issues.jenkins-ci.org/browse/JENKINS-1463 indicates that
        // @classname may not exist in individual testcase elements. We now
        // also test if the testsuite element has a package name that can be used
        // as the class name instead of the file name which is default.
        String classname = e.attributeValue("classname");
        if (classname == null) {
            classname = suite.attributeValue("name");
        }

        // https://issues.jenkins-ci.org/browse/JENKINS-1233 and
        // http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
        // are at odds with each other --- when both are present,
        // one wants to use @name from <testsuite>,
        // the other wants to use @classname from <testcase>.

        addCase(new FlakyCaseResult(this, e, classname, keepLongStdio));
    }

    String stdout = FlakyCaseResult.possiblyTrimStdio(cases, keepLongStdio, suite.elementText("system-out"));
    String stderr = FlakyCaseResult.possiblyTrimStdio(cases, keepLongStdio, suite.elementText("system-err"));
    if (stdout == null && stderr == null) {
        // Surefire never puts stdout/stderr in the XML. Instead, it goes to a separate file (when ${maven.test.redirectTestOutputToFile}).
        Matcher m = SUREFIRE_FILENAME.matcher(xmlReport.getName());
        if (m.matches()) {
            // look for ***-output.txt from TEST-***.xml
            File mavenOutputFile = new File(xmlReport.getParentFile(), m.group(1) + "-output.txt");
            if (mavenOutputFile.exists()) {
                try {
                    stdout = FlakyCaseResult.possiblyTrimStdio(cases, keepLongStdio, mavenOutputFile);
                } catch (IOException e) {
                    throw new IOException("Failed to read " + mavenOutputFile, e);
                }
            }
        }
    }

    this.stdout = stdout;
    this.stderr = stderr;
}

From source file:com.gote.importexport.ExportTournamentForOpenGotha.java

License:Apache License

/**
 * Update a document according to Tournament state
 * //from w w w .  j  a  va  2 s.com
 * @param pDocument Document
 * @param pTournament Tournament
 */
private void updateDocument(Document pDocument, Tournament pTournament) {
    Element pElementTournament = pDocument.getRootElement();
    Element elementGames = pElementTournament.element(TournamentOpenGothaUtil.TAG_GAMES);
    @SuppressWarnings("unchecked")
    List<Element> listOfGames = (List<Element>) elementGames.elements(TournamentOpenGothaUtil.TAG_GAME);
    for (Element game : listOfGames) {
        // Check if there is no result for the game before checking games
        if (game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_RESULT) != null
                && !TournamentOpenGothaUtil.VALUE_GAME_RESULT_UNKNOWN
                        .equals(game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_RESULT).getValue())) {
            if (game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_ROUND) != null
                    && game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_BLACK_PLAYER) != null
                    && game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_WHITE_PLAYER) != null) {
                game.addAttribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_RESULT,
                        pTournament.getGameResultWithCompleteName(
                                Integer.parseInt(game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_ROUND)
                                        .getValue()),
                                game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_BLACK_PLAYER).getValue(),
                                game.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_WHITE_PLAYER)
                                        .getValue()));
            } else {
                LOGGER.log(Level.SEVERE,
                        "Either the round number, black player name or white player name has not been found for game : "
                                + game + ". Update impossible");
            }
        }
    }
}

From source file:com.gote.importexport.ImportTournamentFromOpenGotha.java

License:Apache License

/**
 * Init players list//from   ww  w . j  av  a  2s  .c om
 * 
 * @param pTournament Tournament being builded
 * @param pElementPlayers Element in OpenGotha document
 * @return boolean, true if everything worked as expected
 */
public boolean initPlayers(Tournament pTournament, Element pElementPlayers) {
    LOGGER.log(Level.INFO, "Players initialization");
    boolean init = false;
    @SuppressWarnings("unchecked")
    List<Element> listOfPlayers = (List<Element>) pElementPlayers.elements(TournamentOpenGothaUtil.TAG_PLAYER);
    init = (listOfPlayers != null && !listOfPlayers.isEmpty());
    if (init) {
        List<Player> tournamentPlayers = new ArrayList<Player>();

        for (Element playerElement : listOfPlayers) {
            Player player = new Player();
            player.setPseudo(playerElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_PLAYER_NAME).getValue());
            player.setFirstname(
                    playerElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_PLAYER_FIRSTNAME).getValue());
            player.setRank(playerElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_PLAYER_RANK).getValue());
            tournamentPlayers.add(player);
        }

        pTournament.setParticipantsList(tournamentPlayers);
    }

    return init;
}

From source file:com.gote.importexport.ImportTournamentFromOpenGotha.java

License:Apache License

/**
 * Init rounds and games// ww w. j a v  a  2  s  .c  o m
 * 
 * @param pTournament Tournament being builded
 * @param pElementGames Element in OpenGotha document
 * @return boolean, true if everything worked as expected
 */
public boolean initRounds(Tournament pTournament, Element pElementGames) {
    LOGGER.log(Level.INFO, "Rounds initialization");
    boolean init = false;
    @SuppressWarnings("unchecked")
    List<Element> listOfGames = (List<Element>) pElementGames.elements(TournamentOpenGothaUtil.TAG_GAME);
    init = (listOfGames != null && !listOfGames.isEmpty());
    if (init) {

        List<Round> tournamentRounds = new ArrayList<Round>();

        for (Element gameElement : listOfGames) {

            // Check round game number, if it exists, add it to the round if it does not exists create
            // the round first
            String roundNumberAsText = gameElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_ROUND)
                    .getValue();

            int roundPlacement = -1;
            List<Game> games = new ArrayList<Game>();
            Round round = new Round();

            if (roundNumberAsText != null && !roundNumberAsText.isEmpty()) {
                roundPlacement = getRoundPlacement(tournamentRounds, new Integer(roundNumberAsText));
            } else {
                LOGGER.log(Level.WARNING,
                        "No round number in configuration file. Line is : " + gameElement.toString());
            }

            if (roundPlacement > -1) {
                games = tournamentRounds.get(roundPlacement).getGameList();
            } else {
                LOGGER.log(Level.INFO, "Round " + roundNumberAsText + " is new and will be created.");
                round.setNumber(new Integer(roundNumberAsText));
            }

            Game game = new Game();

            Player black = pTournament.getParticipantWithCompleteName(
                    gameElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_BLACK_PLAYER).getValue());
            Player white = pTournament.getParticipantWithCompleteName(
                    gameElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_WHITE_PLAYER).getValue());
            String result = gameElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_RESULT).getValue();
            String handicap = gameElement.attribute(TournamentOpenGothaUtil.ATTRIBUTE_GAME_HANDICAP).getValue();

            game.setBlack(black);
            game.setWhite(white);
            game.setResult(result);
            game.setHandicap(handicap);
            games.add(game);

            if (roundPlacement < 0) {
                round.setGameList(games);
                round.setDateStart(pTournament.getStartDate());
                round.setDateEnd(pTournament.getEndDate());
                tournamentRounds.add(round);
            }

        }

        pTournament.setRounds(tournamentRounds);
    }

    return init;
}