Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java

License:Apache License

/**
 * Only when the source file is XLF, need re-wrap the off-line down-loaded
 * XLIFF file.//  ww w  .jav  a2s.  c  o  m
 */
private void reWrapXliff(Document doc, HashSet<Long> jobIds) {
    Element root = doc.getRootElement();
    Element bodyElement = root.element(XliffConstants.FILE).element(XliffConstants.BODY);

    // Find TU elements that are from XLF source file.
    List<Element> xlfTuElements = new ArrayList<Element>();
    for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
        Element foo = (org.dom4j.Element) i.next();
        if (isSrcFileXlf(foo, jobIds)) {
            xlfTuElements.add(foo);
        }
    }

    if (xlfTuElements.size() == 0)
        return;

    //
    StringBuffer xliffString = new StringBuffer();
    xliffString.append("<?xml version=\"1.0\"?>");
    xliffString.append("<xliff version=\"1.2\">");
    xliffString.append("<file>");
    xliffString.append("<body>");
    Attribute stateAttr = null;
    ArrayList<String> trgStates = new ArrayList<String>();
    for (Element foo : xlfTuElements) {
        Element sourceElement = foo.element(XliffConstants.SOURCE);
        String sourceContent = sourceElement.asXML();
        sourceContent = sourceContent.replaceFirst("<" + XliffConstants.SOURCE + "[^>]*>", "");
        sourceContent = sourceContent.replace("</" + XliffConstants.SOURCE + ">", "");

        Element targetElement = foo.element(XliffConstants.TARGET);

        String targetContent = targetElement.asXML();
        targetContent = targetContent.replaceFirst("<" + XliffConstants.TARGET + "[^>]*>", "");
        targetContent = targetContent.replace("</" + XliffConstants.TARGET + ">", "");

        xliffString.append("<trans-unit>");
        xliffString.append("<source>").append(sourceContent).append("</source>");
        xliffString.append("<target>").append(targetContent).append("</target>");
        xliffString.append("</trans-unit>");

        // Store the state attributes in sequence
        stateAttr = targetElement.attribute(XliffConstants.STATE);
        if (stateAttr == null) {
            trgStates.add("");
        } else {
            trgStates.add(stateAttr.getValue());
        }
    }
    xliffString.append("</body>");
    xliffString.append("</file>");
    xliffString.append("</xliff>");

    // Extract it to get re-wrapped segments.
    DiplomatAPI api = new DiplomatAPI();
    api.setEncoding("UTF-8");
    api.setLocale(new Locale("en_US"));
    api.setInputFormat("xlf");
    api.setSentenceSegmentation(false);
    api.setSegmenterPreserveWhitespace(true);
    api.setSourceString(xliffString.toString());

    ArrayList<String> sourceArray = new ArrayList<String>();
    ArrayList<String> targetArray = new ArrayList<String>();

    try {
        api.extract();
        Output output = api.getOutput();

        for (Iterator it = output.documentElementIterator(); it.hasNext();) {
            DocumentElement element = (DocumentElement) it.next();

            if (element instanceof TranslatableElement) {
                TranslatableElement trans = (TranslatableElement) element;

                SegmentNode src = (SegmentNode) (trans.getSegments().get(0));
                if (trans.getXliffPartByName().equals("source")) {
                    sourceArray.add("<source>" + replaceEntity(src.getSegment()) + "</source>");
                } else if (trans.getXliffPartByName().equals("target")) {
                    targetArray.add("<target>" + replaceEntity(src.getSegment()) + "</target>");
                }
            }
        }
    } catch (Exception e) {
        if (s_category.isDebugEnabled()) {
            s_category.error(e.getMessage(), e);
        }
    }

    // Replace source/target elements
    int index = 0;
    if (sourceArray != null && targetArray != null) {
        for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
            if (index >= sourceArray.size()) {
                break;
            }

            Element foo = (org.dom4j.Element) i.next();
            if (!isSrcFileXlf(foo, jobIds)) {
                continue;
            }

            TuImpl tu = getTu(foo, jobIds);
            GxmlElement srcGxmlElement = tu.getSourceTuv().getGxmlElement();
            String newSrc = "<segment>" + GxmlUtil.stripRootTag(sourceArray.get(index)) + "</segment>";
            GxmlElement trgGxmlElement = SegmentUtil2.getGxmlElement(newSrc);
            newSrc = SegmentUtil2.adjustSegmentAttributeValues(srcGxmlElement, trgGxmlElement, "xlf");
            newSrc = "<source>" + GxmlUtil.stripRootTag(newSrc) + "</source>";
            Element sourceElement = foo.element(XliffConstants.SOURCE);
            Element newSourceElement = getDom(newSrc).getRootElement();
            foo.remove(sourceElement);
            foo.add(newSourceElement);

            String newTrg = "<segment>" + GxmlUtil.stripRootTag(targetArray.get(index)) + "</segment>";
            trgGxmlElement = SegmentUtil2.getGxmlElement(newTrg);
            newTrg = SegmentUtil2.adjustSegmentAttributeValues(srcGxmlElement, trgGxmlElement, "xlf");
            newTrg = "<target>" + GxmlUtil.stripRootTag(newTrg) + "</target>";
            Element newTargetElement = getDom(newTrg).getRootElement();
            Element targetElement = foo.element(XliffConstants.TARGET);
            foo.remove(targetElement);
            // If target has "state" attribute, it should be preserved.
            try {
                if (!"".equals(trgStates.get(index))) {
                    newTargetElement.add(new DefaultAttribute(XliffConstants.STATE, trgStates.get(index)));
                }
            } catch (Exception ignore) {

            }

            foo.add(newTargetElement);
            index++;
        }
    }
}

From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java

License:Apache License

private String convertNode2Pseudo(Document doc, String tagName, String p_fileName, HashSet<Long> jobIds,
        PtagErrorPageWriter m_errWriter) {
    Element root = doc.getRootElement();
    Element foo;//  ww w  .ja v  a2  s . c  om
    String tuId = null;
    boolean hasError = false;

    Element bodyElement = root.element(XliffConstants.FILE).element(XliffConstants.BODY);
    for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
        try {
            foo = (org.dom4j.Element) i.next();
            Element sourceElement = foo.element(tagName);
            String textContent = sourceElement.asXML();
            textContent = textContent.replaceFirst("<" + tagName + "[^>]*>", "");
            textContent = textContent.replace("</" + tagName + ">", "");
            textContent = convertSegment2Pseudo(textContent, isSrcFileXlf(foo, jobIds), getTu(foo, jobIds));
            if (tagName.equalsIgnoreCase("target") && textContent.startsWith("#")) {
                textContent = textContent.replaceFirst("#", OfflineConstants.PONUD_SIGN);
            }
            sourceElement.setText(textContent);
        } catch (Exception e) {
            hasError = true;
            m_errWriter.addSegmentErrorMsg(tuId, e.getMessage());
        }
    }

    if (hasError)
        return m_errWriter.buildPage().toString();
    else
        return null;
}

From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java

License:Apache License

/**
 * Adds all comments to database. The path is trans-unit/note.
 * //w  w w .j a  v a2  s  .c  o m
 * @param doc
 *            The document of the xliff file.
 * @param p_user
 *            The user who uploaded the xliff file.
 */
private void addComment(Document doc, User p_user, HashSet<Long> jobIds) {
    XmlEntities entity = new XmlEntities();

    Element root = doc.getRootElement();
    Element file = root.element(XliffConstants.FILE);
    String target = file.attributeValue("target-language");
    target = target.replace("-", "_");

    org.dom4j.Element bodyElement = file.element(XliffConstants.BODY);
    for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
        Element foo = (Element) i.next();
        // For GBS-3643: if resname="SID", do not add note value as comment.
        String resName = foo.attributeValue("resname");
        if ("SID".equalsIgnoreCase(resName)) {
            continue;
        }

        for (Iterator notes = foo.elementIterator(XliffConstants.NOTE); notes.hasNext();) {
            Element note = (Element) notes.next();
            List elements = note.elements();
            String msg = m_resource.getString("msg_note_format_error");

            if (elements == null || note.content().size() == 0) {
                continue;
            }

            for (Object obj : note.content()) {
                if (!(obj instanceof DefaultText)) {
                    s_category.error(msg);
                    s_category.error("Error note: " + note.asXML());
                    throw new IllegalArgumentException(msg);
                }
            }

            String textContent = note.getText();
            if (textContent.startsWith("Match Type:")) {
                continue;
            }
            textContent = entity.decodeString(textContent, null);

            String tuId = foo.attributeValue("id");
            try {
                // As we can not get to know the job ID only by the tuId, we
                // have to loop jobIds until we can get the TU object.
                long jobId = -1;
                TuImpl tu = null;
                for (long id : jobIds) {
                    tu = SegmentTuUtil.getTuById(Long.parseLong(tuId), id);
                    jobId = id;
                    if (tu != null) {
                        break;
                    }
                }
                for (Object ob : tu.getTuvs(true, jobId)) {
                    TuvImpl tuv = (TuvImpl) ob;
                    TargetPage tPage = tuv.getTargetPage(jobId);
                    if (tuv.getGlobalSightLocale().toString().equalsIgnoreCase(target)) {
                        String title = String.valueOf(tu.getId());
                        String priority = "Medium";
                        String status = "open";
                        String category = "Type01";

                        IssueImpl issue = tuv.getComment();
                        if (issue == null) {
                            String key = CommentHelper.makeLogicalKey(tPage.getId(), tu.getId(), tuv.getId(),
                                    0);
                            issue = new IssueImpl(Issue.TYPE_SEGMENT, tuv.getId(), title, priority, status,
                                    category, p_user.getUserId(), textContent, key);
                            issue.setShare(false);
                            issue.setOverwrite(false);
                        } else {
                            issue.setTitle(title);
                            issue.setPriority(priority);
                            issue.setStatus(status);
                            issue.setCategory(category);
                            issue.addHistory(p_user.getUserId(), textContent);
                            issue.setShare(false);
                            issue.setOverwrite(false);
                        }

                        HibernateUtil.saveOrUpdate(issue);
                        break;
                    }
                }
            } catch (Exception e) {
                s_category.error("Failed to add comments", e);
            }
        }
    }
}

From source file:com.globalsight.everest.edit.offline.page.terminology.HtmlTermHelp.java

License:Apache License

@Override
public String getLanguage(Locale locale, String terminology, String xml) {
    ArrayList fieldList = new ArrayList();
    ArrayList valueList = new ArrayList();
    String htmlCotent = "";

    if (xml == null || xml.trim().equals("")) {
        htmlCotent = "<SPAN class=\"vfieldlabel\"></SPAN><br/>" + "<SPAN class=\"vfieldvalue\"><P></P></SPAN>";
    } else {//from  w w w  .j av a  2  s. c om
        try {
            xml = "<desc>" + xml + "</desc>";
            Entry entry = new Entry(xml);
            Document dom = entry.getDom();
            Element root = dom.getRootElement();
            List descrip = root.selectNodes("//desc/descripGrp/descrip");

            for (int i = 0; i < descrip.size(); i++) {
                Element content = (Element) descrip.get(i);
                String field = content.attributeValue("type");
                String xmlContent = content.getStringValue();
                htmlCotent = htmlCotent + "<SPAN class=\"vfieldlabel\">" + field + "</SPAN><br/>"
                        + "<SPAN class=\"vfieldvalue\"><P>" + xmlContent + "</P></SPAN>";
            }
        } catch (Exception e) {
        }
    }

    String lanString = "<DIV class=\"vlanguageGrp\">" + "<SPAN class=\"vfakeLanguageGrp\">"
            + "<SPAN class=\"vlanguagelabel\">Language</SPAN>"
            + "<SPAN class=\"vlanguage\" unselectable=\"on\" locale=\"" + locale.getDisplayLanguage(LOCALE)
            + "\">" + locale.getCountry().toUpperCase() + "</SPAN>" + "</SPAN>" + "<DIV class=\"vtermGrp\">"
            + "<DIV class=\"vfakeTermGrp\">" + "<SPAN class=\"vtermlabel\">Term</SPAN>"
            + "<SPAN class=\"vterm\">" + terminology + "</SPAN>" + "<DIV class=\"vfieldGrp\">" + htmlCotent
            + "</DIV></DIV></DIV></DIV>";

    return lanString;
    /*
    return MessageFormat.format(LANGUAGE_GRP, locale
        .getDisplayLanguage(LOCALE), locale.getCountry().toUpperCase(),
        terminology, xmlContent, field);
        */
}

From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java

License:Apache License

private static String convertToTmxLevel(String p_xml, int p_tmxLevel) {
    Document dom = null;
    try {/*from w  w w  .  j ava2  s  .  c  o  m*/
        // normal operation
        dom = getDom("<seg>" + p_xml + "</seg>");
    } catch (RuntimeException re) {
        // p_xml may contain "<" or ">" which will result in parse error,so
        // encode it.
        String p_xml2 = EditUtil.encodeHtmlEntities(p_xml);
        dom = getDom("<seg>" + p_xml2 + "</seg>");
    }

    Element root = dom.getRootElement();
    if (p_tmxLevel == TMX_LEVEL_ONE) {
        String[] strs = { "//bpt", "//ept", "//ph", "//it", "//ut", "//hi" };
        replaceNbsps(root);
        for (int i = 0; i < strs.length; i++) {
            removeNodes(root, strs[i]);
        }
    } else if (p_tmxLevel == TMX_LEVEL_TWO) {
        String[] attributes = { "locType", "wordcount", "erasable", "movable" };
        // TMX Compliance: nbsp must be output as character.
        replaceNbsps(root);
        // Remove any SUB tags (but TM2 doesn't contain any).
        removeSubElements(root);
        removeUncompliantAttributes(root, attributes);
        removeAttributeForNode(root, "it", new String[] { "i" });
    }

    return root.asXML();
}

From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java

License:Apache License

public static String convertXlfToTmxFormat(String p_xml) {
    s_logger.debug("Begin convert xlf to tmx: " + p_xml);
    Document dom = null;

    try {//from w ww. j  a  v a 2  s . c  om
        dom = getDom("<seg>" + p_xml + "</seg>");
    } catch (RuntimeException e) {
        return p_xml;
    }

    Element root = dom.getRootElement();
    // String[] strs = { "//bpt", "//ept", "//ph", "//it", "//ut", "//hi" };
    String[] attributes = { "locType", "wordcount", "erasable", "movable" };
    // removeEmbedTags(root);
    // TMX Compliance: nbsp must be output as character.
    // GBS-587, comment out nbsp converting for testing patch 7.1.4.1
    // replaceNbsps(root);
    // Remove any SUB tags (but TM2 doesn't contain any).
    removeSubElements(root);
    removeUncompliantAttributes(root, attributes);
    removeAttributeForNode(root, "it", new String[] { "i" });
    String result = root.asXML();

    s_logger.debug("The result string: " + result);

    int firstIndex = 5;
    int endIndex = result.length() - 6;

    if (endIndex < firstIndex) {
        return "";
    }

    return result.substring(firstIndex, endIndex);
}

From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java

License:Apache License

private static String convertToTmx(String p_segment) {
    StringBuffer result = new StringBuffer();
    Document dom = getDom(p_segment);
    result.append("<seg>");
    result.append(getInnerXml(dom.getRootElement()));
    result.append("</seg>\r\n");

    return result.toString();
}

From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java

License:Apache License

/**
 * Parse offline uploading TTX file for uploading purpose.
 * /*from ww w  .  j  av  a 2s.com*/
 * @param doc
 * @param isParsingTTXForGS
 *            :True for GS uploading;False for common TTX file parsing.
 * @return
 * @throws Exception
 */
public String parseToTxt(Document doc, boolean isParsingTTXForGS) throws Exception {
    this.isParsingTTXForGS = isParsingTTXForGS;

    Element root = doc.getRootElement();// TRADOStag element
    // toolSettings
    parseToolSettings(root);

    // userSettings
    parseUserSettings(root);

    Element bodyElement = root.element(TTXConstants.BODY);
    Element rawElement = bodyElement.element(TTXConstants.RAW);
    // parse header info such as "pageId","taskId" etc.
    parseHeaderInfo(rawElement);
    // append header info
    appendHeaderInfo();

    // main contents
    if (rawElement.nodeCount() > 0) {
        Iterator nodesIt = rawElement.nodeIterator();
        while (nodesIt.hasNext()) {
            Node node = (Node) nodesIt.next();
            String nodeStr = node.asXML();
            domNodehandler(node, false);
        }
    }

    appendEndInfo();

    return results.toString();
}

From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java

License:Apache License

public Element getRootNode(Document doc) throws Exception {
    Element root = doc.getRootElement();
    return root;
}

From source file:com.globalsight.everest.page.pageexport.ExportEventObserverLocal.java

License:Apache License

/**
 * Notifies the person who initiated the job about the export being
 * complete. The job's first request's event flow xml is retrieved and the
 * importInitiatorId plucked from that./*from w  ww  . j  a v  a 2 s . c  o m*/
 * 
 * @param p_batchEvent
 * @param p_args
 * @param p_subject
 * @param p_msgKey
 */
private void notifyImportInitiator(ExportBatchEvent p_batchEvent, String[] p_args, String p_subject,
        String p_msgKey) {
    XmlParser xmlParser = null;
    try {
        // first get back the event flow xml
        Job job = p_batchEvent.getJob();
        Collection requests = job.getRequestList();
        Iterator iter = requests.iterator();
        Request firstRequest = (Request) iter.next();
        String efxml = firstRequest.getEventFlowXml();
        String companyIdStr = String.valueOf(job.getCompanyId());

        // parse the efxml for the import initiator id
        xmlParser = XmlParser.hire();

        Document document = xmlParser.parseXml(efxml);
        Element root = document.getRootElement();
        Node node = root.selectSingleNode("/eventFlowXml/source/@importInitiatorId");
        if (node != null) {
            String importInitatorId = node.getText();
            if (importInitatorId != null && importInitatorId.length() > 0) {
                User user = ServerProxy.getUserManager().getUser(importInitatorId);
                s_logger.debug("Emailing import initator " + importInitatorId + " at email address "
                        + user.getEmail());
                ExportEventObserverHelper.sendEmail(user, p_args, p_subject, p_msgKey, companyIdStr);
            }
        }
    } catch (Exception ex) {
        s_logger.error(
                "Failed to send e-mail to the import initiator. The export process has completed but\r\n"
                        + "the user will not receive e-mail notification due to the following exception:\r\n",
                ex);
    } finally {
        if (xmlParser != null) {
            XmlParser.fire(xmlParser);
        }
    }
}