Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

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

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

License:Apache License

@SuppressWarnings("rawtypes")
public String handleFiles(String pageId, String content, String targetLocale, String sourceLocale,
        MindTouchPageInfo pageInfo) throws DocumentException {
    String filesXml = getPageFiles(pageId);
    if (StringUtil.isEmpty(filesXml)) {
        return content;
    }/*from   ww w . j av a  2  s  .  c om*/

    HashMap<String, String> fileMap = new HashMap<String, String>();
    Document doc = getDocument(filesXml);
    List propertyNodes = doc.selectNodes("//contents ");
    Iterator it = propertyNodes.iterator();
    String sourceFileUrl = null;
    while (it.hasNext()) {
        Element propertyNode = (Element) it.next();
        sourceFileUrl = propertyNode.attributeValue("href");
        String filePath = getPageFile(sourceFileUrl);
        if (filePath != null) {
            fileMap.put(sourceFileUrl, filePath);
        }
    }

    if (fileMap.size() > 0) {
        for (String tempSourceFileUrl : fileMap.keySet()) {
            String fileXml = putPageFile(fileMap.get(tempSourceFileUrl), targetLocale, sourceLocale, pageInfo);
            if (StringUtil.isNotEmpty(fileXml)) {
                doc = getDocument(fileXml);
                propertyNodes = doc.selectNodes("//contents ");
                it = propertyNodes.iterator();
                while (it.hasNext()) {
                    Element propertyNode = (Element) it.next();
                    String targetFileUrl = propertyNode.attributeValue("href");
                    fileMap.put(tempSourceFileUrl, targetFileUrl);
                }
            }
        }

        for (String tempSourceFileUrl : fileMap.keySet()) {
            content = StringUtil.replace(content, tempSourceFileUrl, fileMap.get(tempSourceFileUrl));
        }
    }

    return content;
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

License:Apache License

/**
 * Parse page info xml from "getPageInfo()" method.
 * /* w w w.ja v a  2  s  .  c  o m*/
 * @param pageInfoXml
 * @return MindTouchPage
 * @throws DocumentException
 */
@SuppressWarnings("rawtypes")
public MindTouchPage parsePageInfoXml(String pageInfoXml) throws DocumentException {
    MindTouchPage mtp = new MindTouchPage();
    Document doc = getDocument(pageInfoXml);

    String id = null;
    String href = null;
    List pageNodes = doc.selectNodes("//page");
    if (pageNodes != null && pageNodes.size() > 0) {
        Element pageNode = (Element) pageNodes.get(0);
        // page id
        id = pageNode.attributeValue("id");
        mtp.setId(Long.parseLong(id));
        // href
        href = pageNode.attributeValue("href");
        mtp.setHref(href);

        String name = null;
        String text = null;
        Iterator subNodeIt = pageNode.nodeIterator();
        while (subNodeIt.hasNext()) {
            Element node = (Element) subNodeIt.next();
            name = node.getName();
            text = node.getText();
            if ("uri.ui".equals(name)) {
                mtp.setUriUi(text);
            } else if ("title".equals(name)) {
                mtp.setTitle(text);
            } else if ("path".equals(name)) {
                mtp.setPath(text);
            } else if ("date.created".equals(name)) {
                mtp.setDateCreated(text);
            }
        }
    }

    return mtp;
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

License:Apache License

/**
 * Return an XML like// w ww.  ja v a  2s. c o m
 * "<properties><property name="name1"><contents type="text/plain">yes</contents></property><property name="name2"/></properties>"
 * 
 * @param propertiesXml
 * @return String
 * @throws DocumentException
 */
@SuppressWarnings("rawtypes")
private String getPropertiesContentsXml(String propertiesXml, HashMap<String, String> etagMap)
        throws DocumentException {
    StringBuffer titles = new StringBuffer();
    titles.append("<properties>");

    Document doc = getDocument(propertiesXml);
    List propertyNodes = doc.selectNodes("//property");
    Iterator it = propertyNodes.iterator();
    String name = null;
    String content = null;
    while (it.hasNext()) {
        Element propertyNode = (Element) it.next();
        name = propertyNode.attributeValue("name");
        Element contentNode = (Element) propertyNode.selectSingleNode("contents");
        content = contentNode.getTextTrim();
        if (content != null && content.length() > 0) {
            content = StringUtil.replace(content, "&", "&amp;");
            content = StringUtil.replace(content, "<", "&lt;");
            content = StringUtil.replace(content, ">", "&gt;");
            titles.append("<property name=\"").append(name).append("\" etag=\"").append(etagMap.get(name))
                    .append("\"><contents type=\"text/plain; charset=UTF-8\">").append(content)
                    .append("</contents></property>");
        }
    }
    titles.append("</properties>");

    return titles.toString();
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

License:Apache License

@SuppressWarnings("rawtypes")
private HashMap<String, String> getePropertiesEtagMap(String propertiesXml) {
    HashMap<String, String> etagMap = new HashMap<String, String>();
    try {//from   w  w w.  j av  a  2s  . c om
        if (propertiesXml != null) {
            Document doc = getDocument(propertiesXml);
            List propertyNodes = doc.selectNodes("//property");
            Iterator it = propertyNodes.iterator();
            String name = null;
            String etag = null;
            while (it.hasNext()) {
                Element propertyNode = (Element) it.next();
                name = propertyNode.attributeValue("name");
                etag = propertyNode.attributeValue("etag");
                etagMap.put(name, etag);
            }
        }
    } catch (DocumentException e) {
        logger.warn(e);
    }
    return etagMap;
}

From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java

License:Apache License

/**
* As the "title" need to be translated, get the translated title from
* target file./* www  .j  a v  a  2 s  . c  o m*/
* 
* @param contentXml
* @return title
*/
private String getTitleFromTranslatedContentXml(String contentXml) {
    try {
        contentXml = fixTitleValueInContentXml(contentXml);
        int index = contentXml.indexOf("<body>");
        if (index == -1) {
            index = contentXml.indexOf("<body");
        }
        String content = contentXml.substring(0, index);
        content = content.replace("&nbsp;", " ");
        content += "</content>";
        Element root = getDocument(content).getRootElement();
        String title = root.attributeValue("title");
        if (title.trim().length() > 0) {
            // Encode the whole title is the right behavior, but as
            // MindTouch does not decode title, we have to only encode # = &
            // title = URLEncoder.encode(title);
            title = title.replace("#", "%23");
            title = title.replace("=", "%3D");
            title = title.replace("&", "%26");
            return new String(title.trim().getBytes("UTF-8"), "UTF-8");
        }
    } catch (Exception e) {
        logger.error("Fail to get title from translated contents xml: " + contentXml, e);
        return null;
    }
    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.
 * /*from w w  w.  ja  v a2  s.co 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 {/* w ww  . java2  s  . c  o  m*/
        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

public static void findNbspElements(ArrayList p_result, Element p_element) {
    // Depth-first traversal: add embedded <ph x-nbspace> to the list first.
    for (int i = 0, max = p_element.nodeCount(); i < max; i++) {
        Node child = (Node) p_element.node(i);

        if (child instanceof Element) {
            findNbspElements(p_result, (Element) child);
        }/* w w w  .  java2 s  .com*/
    }

    if (p_element.getName().equals("ph")) {
        String attr = p_element.attributeValue("type");

        if (attr != null && attr.equals("x-nbspace")) {
            p_result.add(p_element);
        }
    }
}

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

License:Apache License

public static void convertFromTmx(Element p_root, SegmentTmTuv tuv) throws Exception {
    // language of the TUV "EN-US", case insensitive
    String lang = p_root.attributeValue(Tmx.LANG);

    String locale = ImportUtil.normalizeLocale(lang);
    LocaleManagerLocal manager = new LocaleManagerLocal();
    tuv.setLocale(manager.getLocaleByString(locale));

    // 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);
    }/*from   ww  w .  j a  v  a2 s  .c o m*/
    tuv.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) {
        tuv.setModifyUser(user);
    }

    Date now = new Date();
    Date date;
    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);
        }
        tuv.setCreationDate(new Timestamp(date.getTime()));
    } else {
        tuv.setCreationDate(new Timestamp(now.getTime()));
    }

    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);
        }
        tuv.setModifyDate(new Timestamp(date.getTime()));
    }

    StringBuffer segment = new StringBuffer();
    segment.append("<segment>");
    segment.append(getSegmentValue(p_root));
    segment.append("</segment>");
    tuv.setSegment(segment.toString());
}

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

License:Apache License

/**
 * Reads and validates a ImportOptions XML string.
 *
 * Xml Format://w  ww  .  j a  v  a 2  s . co m
 */
protected void initOther(Element p_root) throws ImporterException {
    try {
        clearColumns();

        List columns = p_root.selectNodes("/importOptions/columnOptions/column");
        for (int i = 0; i < columns.size(); ++i) {
            Element col = (Element) columns.get(i);
            ColumnDescriptor desc = new ColumnDescriptor();

            desc.m_position = Integer.parseInt(col.attributeValue("id"));
            desc.m_name = col.elementText("name");
            desc.m_example = col.elementText("example");
            desc.m_type = col.elementText("type");
            desc.m_subtype = col.elementText("subtype");

            m_columns.add(desc);
        }

        Element elem = (Element) p_root.selectSingleNode("/importOptions/syncOptions");

        m_syncOptions.m_syncMode = elem.elementText("syncMode");
    } catch (Exception e) {
        // cast exception and throw
        error(e.getMessage(), e);
    }
}