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.tm.importer.TmxReaderThread.java

License:Apache License

/**
 * Removes the given TMX 1.4 <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.  ja  va 2s . co m*/
 */
private 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.util.trados.TradosHtmlTmxToGxml.java

License:Apache License

/**
 * Main method to call, returns the new filename of the result.
 *///  w  w  w. j av  a  2 s. com
public String convertToGxml(String p_url) throws Exception {
    final String baseName = getBaseName(p_url);
    final String extension = getExtension(p_url);

    info("Converting TMX file to GXML: `" + p_url + "'");

    startOutputFile(baseName);

    m_entryCount = 0;

    // Reading from a file, need to use Xerces.
    SAXReader reader = new SAXReader();
    reader.setXMLReaderClassName("org.apache.xerces.parsers.SAXParser");
    reader.setEntityResolver(DtdResolver.getInstance());
    reader.setValidation(true);

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx", new ElementHandler() {
        public void onStart(ElementPath path) {
            Element element = path.getCurrent();

            m_version = element.attributeValue("version");
        }

        public void onEnd(ElementPath path) {
        }
    });

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx/header", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();
            setOldHeader(element);
            createNewHeader();

            // prune the current element to reduce memory
            element.detach();

            element = null;
        }
    });

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx/body/tu", new ElementHandler() {
        public void onStart(ElementPath path) {
            ++m_entryCount;
            m_tuError = false;
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();

            if (m_tuError) {
                m_errorCount++;
            } else {
                writeEntry(element.asXML());
            }

            // prune the current element to reduce memory
            element.detach();

            element = null;

            if (m_entryCount % 1000 == 0) {
                debug("Entry " + m_entryCount);
            }
        }
    });

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx/body/tu/tuv/seg", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();

            try {
                element = removeUtElements(element);

                String gxml = handleTuv(element.getText());
                Document doc = parse("<root>" + gxml + "</root>");

                // Remove old content of seg
                List content = element.content();
                for (int i = content.size() - 1; i >= 0; --i) {
                    ((Node) content.get(i)).detach();
                }

                // Add new GXML content (backwards)
                content = doc.getRootElement().content();
                Collections.reverse(content);
                for (int i = content.size() - 1; i >= 0; --i) {
                    Node node = (Node) content.get(i);
                    element.add(node.detach());
                }
            } catch (Throwable ex) {
                m_tuError = true;
            }
        }
    });

    Document document = reader.read(p_url);

    closeOutputFile();

    info("Processed " + m_entryCount + " TUs into file `" + m_filename + "', " + m_errorCount + " errors.");

    return m_filename;
}

From source file:com.globalsight.everest.tm.util.trados.TradosTmxToRtf.java

License:Apache License

/**
 * Main method to call, returns the new filename of the result.
 */// ww w.  j ava2s.  c o  m
public String convertToRtf(String p_url) throws Exception {
    final String baseName = getBaseName(p_url);
    final String extension = getExtension(p_url);

    info("Converting TMX file to RTF: `" + p_url + "'");

    startOutputFile(baseName);

    m_entryCount = 0;

    // Reading from a file, need to use Xerces.
    SAXReader reader = new SAXReader();
    reader.setXMLReaderClassName("org.apache.xerces.parsers.SAXParser");
    reader.setEntityResolver(DtdResolver.getInstance());
    reader.setValidation(true);

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx", new ElementHandler() {
        public void onStart(ElementPath path) {
            Element element = path.getCurrent();

            m_version = element.attributeValue("version");
        }

        public void onEnd(ElementPath path) {
        }
    });

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx/header", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();
            setOldHeader(element);

            Element prop = (Element) element.selectSingleNode("/prop[@type='RTFFontTable']");

            if (prop != null)
                writeEntry(prop.getText());

            prop = (Element) element.selectSingleNode("/prop[@type='RTFStyleSheet']");

            if (prop != null)
                writeEntry(prop.getText());

            writeOtherRtfHeader();

            writeDummyParagraph();

            // prune the current element to reduce memory
            element.detach();

            element = null;
        }
    });

    // enable element complete notifications to conserve memory
    reader.addHandler("/tmx/body/tu", new ElementHandler() {
        public void onStart(ElementPath path) {
            ++m_entryCount;
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();

            element = removeUtElements(element);

            writeEntry(replaceUnicodeChars(removeRtfParagraphs(element.asXML())));
            writeEntry("\\par");

            // prune the current element to reduce memory
            element.detach();

            element = null;

            if (m_entryCount % 1000 == 0) {
                debug("Entry " + m_entryCount);
            }
        }
    });

    Document document = reader.read(p_url);

    closeOutputFile();

    info("Processed " + m_entryCount + " TUs into file `" + m_filename + "'");

    return m_filename;
}

From source file:com.globalsight.everest.webapp.pagehandler.tm.management.TmExportPageHandler.java

License:Apache License

/**
 * Invoke this PageHandler./*from  w  w  w .  j a va2s . c o  m*/
 *
 * @param p_pageDescriptor the page desciptor
 * @param p_request the original request sent from the browser
 * @param p_response the original response object
 * @param p_context context the Servlet context
 */
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, EnvoyServletException {
    HttpSession session = p_request.getSession();
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

    Locale uiLocale = (Locale) session.getAttribute(UILOCALE);
    ResourceBundle bundle = getBundle(session);

    String action = (String) p_request.getParameter(TM_ACTION);
    String options = (String) p_request.getParameter(TM_EXPORT_OPTIONS);
    String tmid = (String) p_request.getParameter(RADIO_TM_ID);
    String name = null;
    String definition = null;
    String tmtype = "TM2";
    String jobAttribute = "";
    Tm tm = null;

    IExportManager exporter = (IExportManager) sessionMgr.getAttribute(TM_EXPORTER);

    ProcessStatus status = (ProcessStatus) sessionMgr.getAttribute(TM_TM_STATUS);

    try {
        if (tmid != null) {
            // tm = s_manager.getTmById(Long.parseLong(tmid));
            tm = s_manager.getProjectTMById(Long.parseLong(tmid), false);
            name = tm.getName();

            // JSP needs the language names, so get the statistics
            // and pass that as long as a TM has no proper definition.
            // Note that the JSP uses both the languages and whether or 
            // not the TM is empty.
            StatisticsInfo tmStatistics = LingServerProxy.getTmCoreManager().getTmExportInformation(tm,
                    uiLocale);
            definition = tmStatistics.asXML(true);

            Long tm3id = tm.getTm3Id();
            tmtype = tm3id == null ? "TM2" : "TM3";
            jobAttribute = getAttributes(tm.getId(), tm.getTm3Id(), tm.getCompanyId());
        }

        if (options != null) {
            // options are posted as UTF-8 string
            options = EditUtil.utf8ToUnicode(options);
            int index = options.indexOf("</exportOptions>");
            if (index > 0) {
                options = options.substring(0, index + "</exportOptions>".length());
            }
        }

        if (action.equals(TM_ACTION_EXPORT)) {
            if (tmid == null || p_request.getMethod().equalsIgnoreCase(REQUEST_METHOD_GET)) {
                p_response.sendRedirect("/globalsight/ControlServlet?activityName=tm");
                return;
            }
            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("initializing export");
            }

            //exporter = s_manager.getExporter(name);
            exporter = TmManagerLocal.getProjectTmExporter(name);

            options = exporter.getExportOptions();

            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("initial options = " + options);
            }

            sessionMgr.setAttribute(TM_TM_NAME, name);
            sessionMgr.setAttribute(TM_TM_ID, tmid);
            sessionMgr.setAttribute(TM_DEFINITION, definition);
            sessionMgr.setAttribute(TM_PROJECT, definition);
            sessionMgr.setAttribute(TM_EXPORT_OPTIONS, options);
            sessionMgr.setAttribute(TM_EXPORTER, exporter);
            sessionMgr.setAttribute(TM_TYPE, tmtype);
            sessionMgr.setAttribute(TM_ATTRIBUTE, jobAttribute);
        } else if (action.equals(TM_ACTION_ANALYZE_TM)) {
            if (p_request.getMethod().equalsIgnoreCase(REQUEST_METHOD_GET)) {
                p_response.sendRedirect("/globalsight/ControlServlet?activityName=tm");
                return;
            }
            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("options from client= " + options);
            }

            // pass down new options from client (won't reanalyze files)
            exporter.setExportOptions(options);

            // then retrieve new options
            options = exporter.analyze();

            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("analysis options = " + options);
            }

            sessionMgr.setAttribute(TM_EXPORT_OPTIONS, options);
        } else if (action.equals(TM_ACTION_SET_EXPORT_OPTIONS)) {
            if (p_request.getMethod().equalsIgnoreCase(REQUEST_METHOD_GET)) {
                p_response.sendRedirect("/globalsight/ControlServlet?activityName=tm");
                return;
            }
            // pass down new options from client (won't reanalyze files)

            // testrun may come here without setting options
            if (options != null) {
                if (CATEGORY.isDebugEnabled()) {
                    CATEGORY.debug("options from client = " + options);
                }

                exporter.setExportOptions(options);
            } else {
                options = exporter.getExportOptions();
            }

            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("options = " + options);
            }
            Document dom = DocumentHelper.parseText(options);
            Element root = dom.getRootElement();
            Element elem = (Element) root.selectSingleNode("//filterOptions/stringId");
            String sid = elem.getText();
            if (StringUtils.isNotBlank(sid) && sid.indexOf("\\") != -1) {
                sid = sid.replace("\\", "\\\\");
            }
            elem.setText(sid);
            options = dom.asXML().substring(dom.asXML().indexOf("<exportOptions>"));
            sessionMgr.setAttribute(TM_EXPORT_OPTIONS, options);
        } else if (action.equals(TM_ACTION_START_EXPORT)) {
            if (p_request.getMethod().equalsIgnoreCase(REQUEST_METHOD_GET)) {
                p_response.sendRedirect("/globalsight/ControlServlet?activityName=tm");
                return;
            }
            if (CATEGORY.isDebugEnabled()) {
                CATEGORY.debug("running export with options = " + options);
            }

            // pass down new options from client
            exporter.setExportOptions(options);

            // Let the jsp page show progress of export
            sessionMgr.setAttribute(TM_EXPORT_OPTIONS, options);

            // Start export in a separate thread.
            try {
                status = new ProcessStatus();
                status.setResourceBundle(bundle);
                sessionMgr.setAttribute(TM_TM_STATUS, status);

                exporter.attachListener(status);
                exporter.doExport();
            } catch (Throwable ex) {
                CATEGORY.error("Export error occured ", ex);
            }
        } else if (action.equals(TM_ACTION_CANCEL_EXPORT)) {
            status.interrupt();
        } else if (action.equals(TM_ACTION_CANCEL) || action.equals(TM_ACTION_DONE)) {
            // we don't come here, do we??
            sessionMgr.removeElement(TM_EXPORTER);
            sessionMgr.removeElement(TM_EXPORT_OPTIONS);
            sessionMgr.removeElement(TM_TM_STATUS);
        }
    } catch (Throwable ex) {
        CATEGORY.error("export error", ex);
        // JSP needs to clear this.
        sessionMgr.setAttribute(TM_ERROR, ex.getMessage());
    }

    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:com.globalsight.everest.workflow.WorkflowNodeParameter.java

License:Apache License

/**
  * Gets the text of the given name. <br>
  * The default value will be returned when the element is not exist or the
  * text value is null./*from  w ww . java  2s.  co m*/
  * 
  * @param name
  *            The name of the parameter.
  * @param defaultValue
  *            The default value when the element or the text is null.
  * @return The attribute value.
  */
public String getAttribute(String name, String defaultValue) {
    Element element = rootElement.element(name);
    if (element != null) {
        String text = element.getText();
        return text == null ? defaultValue : text;
    } else {
        return defaultValue;
    }
}

From source file:com.globalsight.reports.handler.MissingTermsReportHandler.java

License:Apache License

/**
 * Figures out what languages are in the Termbase. These are the user
 * specified language names.//from w  w  w  .  ja  va  2 s.c om
 * 
 * @param p_xmlDefinition
 *            termbase def xml
 */
private void setTermbaseLangs(String p_xmlDefinition) throws Exception {
    XmlParser parser = XmlParser.hire();
    Document dom = parser.parseXml(p_xmlDefinition);
    Element root = dom.getRootElement();
    List langGrps = root.selectNodes(LANGUAGEDEFINITION);
    m_termbaseLangs = new ArrayList();

    for (int i = 0; i < langGrps.size(); i++) {
        Element e = (Element) langGrps.get(i);
        String lang = e.getText();
        m_termbaseLangs.add(lang);
    }

    XmlParser.fire(parser);
}

From source file:com.globalsight.reports.handler.MissingTermsReportHandler.java

License:Apache License

/**
 * Returns the term's text in some language (most likely English). This
 * really just grabs the first language out of the entryXml <br>
 * /*www . j av  a2 s  . c o m*/
 * @param p_tb
 *            termbase
 * @param p_entryId
 *            entry (concept) id
 * @return term text
 */
private String getTerm(ITermbase p_tb, long p_entryId) throws Exception {
    String entryXml = p_tb.getEntry(p_entryId);
    XmlParser parser = XmlParser.hire();
    Document dom = parser.parseXml(entryXml);
    Element root = dom.getRootElement();
    List langGrps = root.selectNodes(TERMBASEXML);
    Element firstTerm = (Element) langGrps.get(0);
    String termText = firstTerm.getText();
    XmlParser.fire(parser);
    return termText;
}

From source file:com.globalsight.reports.MissingTermsReplet.java

License:Apache License

/**
 * Figures out what languages are in the Termbase. These are the user
 * specified language names.// w ww. j  a v  a 2s.  c o  m
 * 
 * @param p_xmlDefinition
 *            termbase def xml
 */
private void setTermbaseLangs(String p_xmlDefinition) throws Exception {
    XmlParser parser = XmlParser.hire();
    Document dom = parser.parseXml(p_xmlDefinition);
    Element root = dom.getRootElement();
    List langGrps = root.selectNodes("/definition/languages/language/name");
    m_termbaseLangs = new ArrayList();
    for (int i = 0; i < langGrps.size(); i++) {
        Element e = (Element) langGrps.get(i);
        String lang = e.getText();
        m_termbaseLangs.add(lang);
    }
    XmlParser.fire(parser);

}

From source file:com.globalsight.reports.MissingTermsReplet.java

License:Apache License

/**
 * Returns the term's text in some language (most likely English). This
 * really just grabs the first language out of the entryXml
 * /*from  w w w . j  a v a  2 s.  c o  m*/
 * @param p_tb
 *            termbase
 * @param p_entryId
 *            entry (concept) id
 * @return term text
 */
private String getTerm(ITermbase p_tb, long p_entryId) throws Exception {
    String entryXml = p_tb.getEntry(p_entryId);
    XmlParser parser = XmlParser.hire();
    Document dom = parser.parseXml(entryXml);
    Element root = dom.getRootElement();
    List langGrps = root.selectNodes("/conceptGrp/languageGrp/termGrp/term");
    Element firstTerm = (Element) langGrps.get(0);
    String termText = firstTerm.getText();
    XmlParser.fire(parser);
    return termText;
}

From source file:com.globalsight.selenium.testcases.util.DownloadUtil.java

License:Apache License

public static String download(String jobName) throws Exception {
    String wsdlUrl = ConfigUtil.getConfigData("serverUrl") + "/globalsight/services/AmbassadorWebService?wsdl";

    AmbassadorServiceLocator loc = new AmbassadorServiceLocator();
    Ambassador service = loc.getAmbassadorWebService(new URL(wsdlUrl));
    String token = service.login(ConfigUtil.getConfigData("adminName"),
            ConfigUtil.getConfigData("adminPassword"));
    String fileXml = null;/*from   www  . j  av a  2s .  c  o  m*/

    String waitTimeStr = ConfigUtil.getConfigData("middleWait");
    String checkTimesStr = ConfigUtil.getConfigData("checkTimes");
    int checkTimes = 30, times = 0;
    long waitTime = 60000;

    try {
        checkTimes = Integer.parseInt(checkTimesStr);
        waitTime = Long.parseLong(waitTimeStr);
    } catch (Exception e) {
        checkTimes = 30;
        waitTime = 60000;
    }

    while (times < checkTimes) {
        fileXml = service.getJobExportFiles(token, jobName);
        if (fileXml != null)
            break;
        else {
            Thread.sleep(waitTime);
            times++;
        }
    }

    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new StringReader(fileXml));
    Element rootElement = document.getRootElement();
    String root = rootElement.elementText("root");
    ArrayList<Element> paths = (ArrayList<Element>) rootElement.elements("paths");
    for (Element element : paths) {
        String filePath = element.getText();

        File outputFile = downloadHttp(root + File.separator + filePath);
    }
    return null;
}