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: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  a2s . 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.TmxUtil.java

License:Apache License

/**
 * Removes the given <sub> element from the segment. <sub> is special since
 * it does not only surround embedded tags but also text, which must be
 * pulled out of the <sub> and added to the parent tag.
 *///from ww w.j ava2  s. co  m
public static void removeSubElement(Element p_element) {
    Element parent = p_element.getParent();
    int index = parent.indexOf(p_element);

    // We copy the current content, clear out the parent, and then
    // re-add the old content, inserting the <sub>'s textual
    // content instead of the <sub> (this clears any embedded TMX
    // tags in the subflow).

    ArrayList newContent = new ArrayList();
    List content = parent.content();

    for (int i = content.size() - 1; i >= 0; --i) {
        Node node = (Node) content.get(i);

        newContent.add(node.detach());
    }

    Collections.reverse(newContent);
    parent.clearContent();

    for (int i = 0, max = newContent.size(); i < max; ++i) {
        Node node = (Node) newContent.get(i);

        if (i == index) {
            parent.addText(p_element.getText());
        } else {
            parent.add(node);
        }
    }
}

From source file:com.globalsight.everest.projecthandler.ProjectHandlerLocal.java

License:Apache License

/**
 * Import a workflow template info object based on the given new name
 * //  ww  w. j a v  a 2  s .c om
 * @param p_newName
 *            - The new name given to the workflow template info.
 * 
 * @exception RemoteException
 *                System or network related exception.
 * @exception ProjectHandlerException
 *                Component specific exception
 */
public void importWorkflowTemplates(Document doc, String p_newName, Collection p_localePairs,
        String p_displayRoleName, String projectId) throws RemoteException, ProjectHandlerException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    WorkflowTemplate workflowTemplate = new WorkflowTemplate();
    try {
        Iterator it = p_localePairs.iterator();
        // UnitOfWork uow = PersistenceService.getInstance()
        // .acquireUnitOfWork();

        while (it.hasNext()) {
            LocalePair localePair = (LocalePair) it.next();
            List rolesNodes = doc.selectNodes("/process-definition/task-node/task/assignment/roles");
            GlobalSightLocale source = localePair.getSource();
            GlobalSightLocale target = localePair.getTarget();
            Iterator iter = rolesNodes.iterator();

            while (iter.hasNext()) {
                Element rolesElement = (Element) iter.next();
                String content = rolesElement.getText();
                content = content.substring(0, content.indexOf(source.toString()) + source.toString().length());
                rolesElement.setText(content + " " + target.toString());
            }

            List rolesNameNodes = doc.selectNodes("/process-definition/task-node/task/assignment/role_name");
            Iterator ite = rolesNameNodes.iterator();

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

                element.setText(p_displayRoleName);
            }

            List rolesTypeNodes = doc.selectNodes("/process-definition/task-node/task/assignment/role_type");
            ite = rolesTypeNodes.iterator();

            while (ite.hasNext()) {
                Element element = (Element) ite.next();
                element.setText("false");
            }

            String name = generateAutoName(p_newName, localePair);
            c_category.info("The value of name is " + name);
            Attribute attribute = (Attribute) doc.selectSingleNode("/process-definition/@name");
            attribute.setValue(name);
            workflowTemplate.setName(name);
            WorkflowTemplateInfo workflowTemplateInfo = createNewWorkflowTemplateInfo(name, localePair,
                    projectId);

            WorkflowTemplate jbpmTemp = ServerProxy.getWorkflowServer().importWorkflowTemplate(workflowTemplate,
                    doc);

            workflowTemplateInfo.setWorkflowTemplate(jbpmTemp);
            // uow.registerObject(dupWorkflowTemplateInfo);
            session.save(workflowTemplateInfo);
        }
        // uow.commit();
        tx.commit();
    } catch (Exception e) {
        String[] args = new String[1];
        args[0] = workflowTemplate.getName();
        tx.rollback();
        throw new ProjectHandlerException(ProjectHandlerException.MSG_FAILED_TO_DUPLICATE_WFI, args, e);

    }
}

From source file:com.globalsight.everest.projecthandler.ProjectTmTuvT.java

License:Apache License

/**
 * Reads the segment content from the <seg> element and fixes any missing
 * sub locType attributes and sub id values.
 * /*from   ww  w .  j a v  a 2 s.c o  m*/
 * @param p_root
 *            the TUV node in the DOM structure.
 * @return the segment text or XML value, encoded as XML.
 */
private String getSegmentValue(Element p_root) {
    StringBuffer result = new StringBuffer();
    Element seg = p_root.element("seg");
    seg = removeHiElements(seg);
    result.append(EditUtil.encodeXmlEntities(seg.getText()));
    return result.toString();
}

From source file:com.globalsight.everest.segmentationhelper.XmlLoader.java

License:Apache License

public static SegmentationRule parseSegmentationRule(String p_xmlText) throws Exception {
    Document doc = parseWithSAX(p_xmlText);
    Element root = doc.getRootElement();
    SegmentationRule segmentationRule = new SegmentationRule();
    SrxHeader header = new SrxHeader();
    HashMap<String, String> formathandle = new HashMap<String, String>();
    HashMap<String, ArrayList<Rule>> langrules = new HashMap<String, ArrayList<Rule>>();
    ArrayList<LanguageMap> langruleMap = new ArrayList<LanguageMap>();

    segmentationRule.setRootName(root.getQualifiedName());
    // Now it only supports SRX2.0.
    segmentationRule.setVersion(root.attributeValue("version"));

    Element headerElement = root.element("header");
    Element bodyElement = root.element("body");
    Element maprulesElement = bodyElement.element("maprules");
    // to get SRX header informations
    if (headerElement != null) {
        // option segmentsubflows
        String segsub = headerElement.attributeValue("segmentsubflows");
        if (segsub == null) {
            // Take default value.
            header.isSegmentsubflows(true);
        } else {/*from   ww  w . j a  v a 2s .co m*/
            header.isSegmentsubflows(!segsub.equalsIgnoreCase("no"));
        }

        // option cascade
        String cascade = headerElement.attributeValue("cascade");
        if (cascade == null) {
            header.isCascade(false);
        } else {
            header.isCascade(!cascade.equalsIgnoreCase("no"));
        }

        // elements : formathandle
        List formatList = headerElement.elements("formathandle");
        Iterator formatIter = formatList != null ? formatList.iterator() : (new ArrayList()).iterator();
        // If the header does not contain formathandle elements
        // we use the default values
        if (!formatIter.hasNext()) {
            formathandle.put("start", "no");
            formathandle.put("end", "yes");
            formathandle.put("isolated", "no");
        }
        // If the header contains formathandle elements
        // we use the values specified by formathandle elements
        else {
            while (formatIter.hasNext()) {
                Element formatElement = (Element) formatIter.next();
                String type = formatElement.attributeValue("type");
                String include = formatElement.attributeValue("include");
                formathandle.put(type, include);
            }
        }
        header.setFormatHandle(formathandle);

        // okpsrx extension
        Element okpOptions = headerElement.element("options");
        Element okpSample = headerElement.element("sample");
        Element okpRangeRule = headerElement.element("rangeRule");

        if (okpOptions != null) {
            String oneSegmentIncludesAll = okpOptions.attributeValue("oneSegmentIncludesAll");
            String trimLeadingWs = okpOptions.attributeValue("trimLeadingWhitespaces");
            String trimTrailingWs = okpOptions.attributeValue("trimTrailingWhitespaces");

            header.setOneSegmentIncludesAll("yes".equalsIgnoreCase(oneSegmentIncludesAll));
            header.setTrimLeadingWhitespaces("yes".equalsIgnoreCase(trimLeadingWs));
            header.setTrimTrailingWhitespaces("yes".equalsIgnoreCase(trimTrailingWs));
        }

        if (okpSample != null) {
            String language = okpSample.attributeValue("language");
            String useMappedRules = okpSample.attributeValue("useMappedRules");
            String sample = okpSample.getText();

            header.setSample(sample);
            header.setSampleLanguage(language);
            header.setUseMappedRulesForSample(!"no".equalsIgnoreCase(useMappedRules));
        }

        if (okpRangeRule != null) {
            String rangeRule = okpRangeRule.getText();
            header.setRangeRule(rangeRule);
        }
    }

    if (bodyElement != null) {
        Element languagerulesElement = bodyElement.element("languagerules");
        if (languagerulesElement != null) {
            Iterator languageruleIter = languagerulesElement.elementIterator();
            while (languageruleIter.hasNext()) {
                Element languageruleElement = (Element) languageruleIter.next();
                String languageName = languageruleElement.attributeValue("languagerulename");
                Iterator ruleIter = languageruleElement.elementIterator();
                ArrayList<Rule> rules = new ArrayList<Rule>();
                while (ruleIter.hasNext()) {
                    Element ruleSub = (Element) ruleIter.next();
                    String breakvalue = ruleSub.attributeValue("break");
                    String beforebreak = ruleSub.elementText("beforebreak");
                    String afterbreak = ruleSub.elementText("afterbreak");
                    Rule rule = new Rule();
                    if (breakvalue == null) {
                        // Take default value.
                        rule.isBreak(true);
                    } else {
                        if (breakvalue.equalsIgnoreCase("no")) {
                            rule.isBreak(false);
                        } else {
                            rule.isBreak(true);
                        }
                    }

                    // System.out.println(rule.getBreak());
                    rule.setAfterBreak(afterbreak);
                    rule.setBeforeBreak(beforebreak);
                    rules.add(rule);
                }
                langrules.put(languageName, rules);
            }
        } // end languageruleElement
    } // end bodyElement

    if (maprulesElement != null) {
        Iterator languagemapIter = maprulesElement.elementIterator();
        while (languagemapIter.hasNext()) {
            Element languagemapElement = (Element) languagemapIter.next();
            String languagepattern = languagemapElement.attributeValue("languagepattern");
            String languagerulename = languagemapElement.attributeValue("languagerulename");
            LanguageMap langMap = new LanguageMap();
            langMap.setLanguagePattern(languagepattern);
            langMap.setLanguageruleName(languagerulename);
            langruleMap.add(langMap);
        }
    }

    segmentationRule.setHeader(header);
    segmentationRule.setLanguageMap(langruleMap);
    segmentationRule.setRules(langrules);
    return segmentationRule;
}

From source file:com.globalsight.everest.tm.exporter.TmxWriter.java

License:Apache License

/**
 * Removes the given <sub> element from the segment. <sub> is special since
 * it does not only surround embedded tags but also text, which must be
 * pulled out of the <sub> and added to the parent tag.
 *///from  w  w  w. j ava 2s .  c  o m
private static void removeSubElement(Element p_element) {
    Element parent = p_element.getParent();
    int index = parent.indexOf(p_element);

    // We copy the current content, clear out the parent, and then
    // re-add the old content, inserting the <sub>'s textual
    // content instead of the <sub> (this clears any embedded TMX
    // tags in the subflow).

    ArrayList newContent = new ArrayList();
    List content = parent.content();

    for (int i = content.size() - 1; i >= 0; --i) {
        Node node = (Node) content.get(i);

        newContent.add(node.detach());
    }

    Collections.reverse(newContent);
    parent.clearContent();

    for (int i = 0, max = newContent.size(); i < max; ++i) {
        Node node = (Node) newContent.get(i);

        if (i == index) {
            parent.addText(p_element.getText());
        } else {
            parent.add(node);
        }
    }
}

From source file:com.globalsight.everest.tm.importer.ImportOptions.java

License:Apache License

/**
 * Reads and validates a ImportOptions XML string.
 *///from  w w w. j  a va 2  s.  c  o  m
protected void initOther(Element p_root) throws ImporterException {
    try {
        List list;
        Element locale;

        Element elem = (Element) p_root.selectSingleNode("//syncOptions");
        m_syncOptions.m_syncMode = elem.elementText("syncMode");

        elem = (Element) p_root.selectSingleNode("//sourceTmOptions");
        m_sourceTmOptions.m_sourceTmName = elem.elementText("sourceTmName");

        elem = (Element) p_root.selectSingleNode("//localeOptions");

        m_localeOptions.clear();

        list = elem.selectNodes("./sourceLocales/locale");
        for (int i = 0, max = list.size(); i < max; i++) {
            locale = (Element) list.get(i);
            m_localeOptions.m_sourceLocales.add(locale.getText());
        }

        list = elem.selectNodes("./targetLocales/locale");
        for (int i = 0, max = list.size(); i < max; i++) {
            locale = (Element) list.get(i);
            m_localeOptions.m_targetLocales.add(locale.getText());
        }

        m_localeOptions.m_selectedSource = elem.elementText("selectedSource");

        list = elem.selectNodes("./selectedTargets/locale");
        for (int i = 0, max = list.size(); i < max; i++) {
            locale = (Element) list.get(i);
            m_localeOptions.m_selectedTargets.add(locale.getText());
        }
    } catch (Exception e) {
        // cast exception and throw
        error(e.getMessage(), e);
    }
}

From source file:com.globalsight.everest.tm.importer.TmxReaderThread.java

License:Apache License

/**
 * Converts a DOM TUV to a GS SegmentTmTuv, thereby converting any
 * TMX format specialities as best as possible.
 *
 * Note: if the attributes in one TUV are incorrect and can not be
 * repaired so we cannot create correct GXML (which depends on
 * correct i/x attributes and type), we need to process all TUVs
 * together; if one encounters an error, all TUVs should be
 * imported without tags as Level 1.//from w  w  w  .  java 2s .c  o  m
 *
 * @param p_root the TUV node in the DOM structure.
 */
private SegmentTmTuv createTuv(SegmentTmTu p_tu, Element p_root) throws Exception {
    SegmentTmTuv result = new SegmentTmTuv();
    result.setOrgSegment(p_root.asXML());

    // need to set backpointer to tuv, or SegmentTmTuv.equals() fails.
    result.setTu(p_tu);

    // language of the TUV "EN-US", case insensitive
    String lang = p_root.attributeValue(Tmx.LANG);

    try {
        String locale = ImportUtil.normalizeLocale(lang);
        result.setLocale(ImportUtil.getLocaleByName(locale));
    } catch (Throwable ex) {
        throw new Exception("unknown locale " + lang + ",you can create it in system then retry.");
    }

    // Creation user - always set to a known value
    String user = p_root.attributeValue(Tmx.CREATIONID);
    if (user == null) {
        user = p_root.getParent().attributeValue(Tmx.CREATIONID);
    }

    result.setCreationUser(user != null ? user : Tmx.DEFAULT_USER);

    // Modification user - only set if known
    user = p_root.attributeValue(Tmx.CHANGEID);
    if (user == null) {
        user = p_root.getParent().attributeValue(Tmx.CHANGEID);
    }

    if (user != null) {
        result.setModifyUser(user);
    }

    // Timestamps (should be expressed using java.util.Date).
    // In TMX, timestamps use the short form: yyyymmddThhmmssZ,
    // so prepare for both short and long form.
    Date now = new Date();
    Date date;

    // Creation date - always set to a known value
    String ts = p_root.attributeValue(Tmx.CREATIONDATE);
    if (ts == null) {
        ts = p_root.getParent().attributeValue(Tmx.CREATIONDATE);
    }

    if (ts != null) {
        date = UTC.parseNoSeparators(ts);
        if (date == null) {
            date = UTC.parse(ts);
        }
        result.setCreationDate(new Timestamp(date.getTime()));
    } else {
        result.setCreationDate(new Timestamp(now.getTime()));
    }

    // Modification date - only set if known (note: currently
    // AbstractTmTuv sets the modification date to NOW)
    ts = p_root.attributeValue(Tmx.CHANGEDATE);
    if (ts == null) {
        ts = p_root.getParent().attributeValue(Tmx.CHANGEDATE);
    }

    if (ts != null) {
        date = UTC.parseNoSeparators(ts);
        if (date == null) {
            date = UTC.parse(ts);
        }
        result.setModifyDate(new Timestamp(date.getTime()));
    } else {
        // If no "changedate", set it same as "creationdate".
        result.setModifyDate(result.getCreationDate());
    }

    ts = p_root.attributeValue(Tmx.LASTUSAGEDATE);
    if (ts == null) {
        ts = p_root.getParent().attributeValue(Tmx.LASTUSAGEDATE);
    }
    if (ts != null) {
        date = UTC.parseNoSeparators(ts);
        if (date == null) {
            date = UTC.parse(ts);
        }
        result.setLastUsageDate(new Timestamp(date.getTime()));
    }

    List tuvPropNodes = p_root.elements("prop");
    for (int i = 0; i < tuvPropNodes.size(); i++) {
        Element elem = (Element) tuvPropNodes.get(i);
        String type = elem.attributeValue("type");
        String value = elem.getText();
        if (Tmx.PROP_PREVIOUS_HASH.equalsIgnoreCase(type)) {
            result.setPreviousHash(Long.parseLong(value));
        } else if (Tmx.PROP_NEXT_HASH.equalsIgnoreCase(type)) {
            result.setNextHash(Long.parseLong(value));
        } else if (Tmx.PROP_JOB_ID.equalsIgnoreCase(type)) {
            result.setJobId(Long.parseLong(value));
        } else if (Tmx.PROP_JOB_NAME.equalsIgnoreCase(type)) {
            result.setJobName(value);
        } else if (Tmx.PROP_CREATION_PROJECT.equalsIgnoreCase(type)) {
            result.setUpdatedProject(value);
        }
    }
    // Segment text: need to produce root elements <translatable>
    // and <localizable> depending on TU type.
    StringBuffer segment = new StringBuffer();

    if (p_tu.isTranslatable()) {
        segment.append("<segment>");
    } else {
        segment.append("<localizable>");
    }

    segment.append(getSegmentValue(p_root));

    if (p_tu.isTranslatable()) {
        segment.append("</segment>");
    } else {
        segment.append("</localizable>");
    }

    result.setSid(p_tu.getSID());
    //End of Added
    result.setSegment(segment.toString());

    return result;
}

From source file:com.globalsight.everest.tm.importer.TmxReaderThread.java

License:Apache License

private ProjectTmTuTProp createProp(SegmentTmTu p_tu, Element p_root) throws Exception {
    ProjectTmTuTProp result = null;// w  ww .  j  a  v  a 2s .  com
    String type = p_root.attributeValue("type");

    if (type != null && type.startsWith(ProjectTmTuTProp.TYPE_ATT_PREFIX)) {
        result = new ProjectTmTuTProp();
        result.setPropType(type);
        result.setPropValue(p_root.getText());
    }

    // When a TM is imported: for each TUV: for each TUV attribute defined on the TM: 
    // if the attribute exists in the imported TMX file, then the attribute is created 
    // and the value is set from the imported TM. 
    if (result != null && m_database instanceof ProjectTM) {
        String attName = result.getAttributeName();
        ProjectTM ptm = (ProjectTM) m_database;
        List<String> tmAttNames = ptm.getAllTMAttributenames();

        // ignore the tu attributes if not defined in TM.
        if (!tmAttNames.contains(attName)) {
            result = null;
        }
    }

    return result;
}

From source file:com.globalsight.everest.tm.importer.TmxReaderThread.java

License:Apache License

/**
 * Reads the segment content from the <seg> element and fixes any
 * missing sub locType attributes and sub id values.
 *
 * @param p_root the TUV node in the DOM structure.
 * @return the segment text or XML value, encoded as XML.
 *///w  w  w.  j a  va  2  s.  c o m
private String getSegmentValue(Element p_root) {
    StringBuffer result = new StringBuffer();

    Element seg = p_root.element("seg");

    // TODO for all formats: strip the TMX 1.4 <hi> element.
    seg = removeHiElements(seg);

    if (m_tmxLevel == ImportUtil.TMX_LEVEL_1) {
        // Level 1: discard any embedded TMX tags.
        result.append(EditUtil.encodeXmlEntities(seg.getText()));
    } else if (m_tmxLevel == ImportUtil.TMX_LEVEL_TRADOS_RTF
            || m_tmxLevel == ImportUtil.TMX_LEVEL_TRADOS_HTML) {
        // Trados TMX: converted to native GXML in analysis phase,
        // this is a no-op.
        result.append(EditUtil.encodeXmlEntities(seg.getText()));
    } else {
        // Level 2 and native: preserve embedded TMX tags.
        try {
            // First, ensure we have all G-TMX attributes (i, x, type)
            seg = validateSegment(p_root, seg);

            // Thu May 15 18:15:26 2003 CvdL
            // For now, strip out all sub segments.
            seg = removeSubElements(seg);

            result.append(ImportUtil.getInnerXml(seg));
        } catch (Throwable ex) {
            // On error, import as level 1.
            result.append(EditUtil.encodeXmlEntities(seg.getText()));
        }

    }

    return result.toString();
}