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.tm.util.ttx.TtxClean.java

License:Apache License

/**
 * Main method to call, returns the new filename of the result.
 *//*from  w ww .  j  a v a2s  . c om*/
public String cleanTtx(String p_url, boolean p_cleanTarget, String p_encoding) throws Exception {
    m_cleanTarget = p_cleanTarget;

    // File is called <file>.<ext>.<ttx>
    final String origName = getBaseName(p_url);
    final String baseName = getBaseName(origName);
    final String extension = getExtension(origName);

    info("Cleaning TTX file to " + (m_cleanTarget ? "target" : "source") + ": `" + p_url + "'");

    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);

    // Fetch the version info early.
    reader.addHandler("/TRADOStag", new ElementHandler() {
        public void onStart(ElementPath path) {
            Element element = path.getCurrent();

            m_version = element.attributeValue(Ttx.VERSION);
        }

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

    // Fetch the header info early.
    reader.addHandler("/TRADOStag/FrontMatter", new ElementHandler() {
        public void onStart(ElementPath path) {
        }

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

            setOldHeader(element);
        }
    });

    // Read in the entire file (it's not too big normally).
    Document document = reader.read(p_url);

    Element body = (Element) document.getRootElement().selectSingleNode("//Body/Raw");

    // Remove <ut>, <df> and pull out one TUV.
    processBody(body);

    String content = getInnerText(body);
    String encoding;

    if (m_cleanTarget) {
        if (p_encoding != null) {
            encoding = p_encoding;
        } else {
            encoding = "UTF-8";
        }
    } else {
        // reuse original encoding
        encoding = m_header.getOriginalEncoding();
    }

    String locale;

    if (m_cleanTarget) {
        locale = m_header.getTargetLanguage();
    } else {
        locale = m_header.getSourceLanguage();
    }

    startOutputFile(baseName, locale, extension, encoding);
    writeEntry(content);
    closeOutputFile();

    info("Result written to 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 av a 2s  .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

/**
  * Converts the configure file to standard format and parse the xml stream
  * to the document./* ww w  .ja v a2 s .c  om*/
  * 
  * @param configure
  *            The configure string to be read.
  * @return The {@code Document}
  */
private void init(String configure) {
    String value = XML_ROOT.replaceAll(XML_ROOT_CONTENT, configure);
    Document document = null;
    try {
        document = reader.read(new StringReader(value));
        this.rootElement = document.getRootElement();
    } catch (DocumentException e) {
        c_category.error("Error occured when read the string " + configure);
        c_category.error("The string " + configure, e);
    }

}

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

License:Apache License

/**
 * Sends the import initiator an email that this review-only task is ready
 * for acceptance. This sends an email to the person that initiated the
 * first file in the job.//from  ww w.  ja v  a2  s.co m
 */
private void notifyImportInitiator(TaskInfo p_taskInfo, TaskEmailInfo p_emailInfo, int p_mailerMessageType,
        Object p_args[]) {
    XmlParser xmlParser = null;
    try {
        Task task = (Task) ServerProxy.getTaskManager().getTask(p_taskInfo.getId());
        String companyIdStr = String.valueOf(task.getCompanyId());
        List sourcePages = task.getSourcePages();
        SourcePage sp1 = (SourcePage) sourcePages.get(0);
        String efxml = sp1.getRequest().getEventFlowXml();

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

        Document document = xmlParser.parseXml(efxml);
        Element root = document.getRootElement();
        org.dom4j.Node node = root.selectSingleNode("/eventFlowXml/source/@importInitiatorId");
        if (node != null) {
            String importInitatorId = node.getText();
            if (importInitatorId != null && importInitatorId.length() > 0) {
                EmailInformation emailInfo = getEmailInfo(importInitatorId);
                s_logger.debug("Emailing about review-only task to import initator " + importInitatorId);
                String subject = getEmailSubject(p_mailerMessageType);
                String message = getEmailMessage(p_mailerMessageType);
                sendMail(importInitatorId, emailInfo, subject, message, p_args, companyIdStr);
            }
        }
    } catch (Exception e) {
        s_logger.error("Failed to send e-mail to the import initiator about a review-only task.", e);
    } finally {
        if (xmlParser != null) {
            XmlParser.fire(xmlParser);
        }
    }
}

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

License:Apache License

/**
 * Adds the workflow tasks to the template xml.
 * /*from www.j av  a2s. com*/
 * @param p_document
 *            - the xml document of the workflow template.
 * @param p_workflowTemplate
 *            - the workflow template.
 * @param p_workflowOwners
 *            - the owner(s) of the workflow instances.
 * @throws Exception
 */
private void createTemplateNodes(Document p_document, WorkflowTemplate p_workflowTemplate,
        WorkflowOwners p_workflowOwners) throws Exception {
    Vector workflowTasks = p_workflowTemplate.getWorkflowTasks();
    int size = workflowTasks == null ? 0 : workflowTasks.size();
    Element root = p_document.getRootElement();

    for (int i = 0; i < size; i++) {
        WorkflowTask wfTask = (WorkflowTask) workflowTasks.get(i);
        if (wfTask.getStructuralState() != WorkflowConstants.REMOVED) {
            switch (wfTask.getType()) {
            case WorkflowConstants.START:
                createStartState(root, wfTask);
                m_startTask = wfTask;
                break;
            case WorkflowConstants.ACTIVITY:
                createActivityNodes(root, wfTask, p_workflowOwners);
                break;
            case WorkflowConstants.CONDITION:
                createDecisionNodes(root, wfTask);
                break;
            }
        }
    }
    createEndState(root, workflowTasks, p_workflowTemplate, p_workflowOwners);
}

From source file:com.globalsight.exporter.ExportOptions.java

License:Apache License

/**
 * Initializes this object (and derived objects) from an XML string.
 * Derived objects must implement initOther().
 *///from  w  w w.j  av  a2 s . c o m
public void init(String p_options) throws ExporterException {
    XmlParser parser = null;
    Document dom;

    try {
        parser = XmlParser.hire();
        dom = parser.parseXml(p_options);

        Element root = dom.getRootElement();

        Element elem = (Element) root.selectSingleNode("//fileOptions");
        m_fileOptions.m_name = elem.elementText("fileName");
        m_fileOptions.m_type = elem.elementText("fileType");
        m_fileOptions.m_encoding = elem.elementText("fileEncoding");
        m_fileOptions.m_entryCount = elem.elementText("entryCount");
        m_fileOptions.m_status = elem.elementText("status");
        m_fileOptions.m_errorMessage = elem.elementText("errorMessage");

        initOther(root);
    } catch (ExporterException e) {
        throw e;
    } catch (Exception e) {
        // cast exception and throw
        error(e.getMessage(), e);
    } finally {
        XmlParser.fire(parser);
    }
}

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

License:Apache License

/**
 * Initializes this object (and derived objects) from an XML string.
 * Derived objects must implement initOther().
 *//*  ww  w .j  a  va 2 s  .  co m*/
public void init(String p_options) throws ImporterException {
    XmlParser parser = null;
    Document dom = null;

    try {
        parser = XmlParser.hire();
        dom = parser.parseXml(p_options);

        Element root = dom.getRootElement();

        Node node = root.selectSingleNode("//fileOptions");

        // This used to use node.valueOf("childnode") but then
        // entities were incorrectly decoded by the Jaxen library,
        // i.e. "A&amp;B" became "A & B" instead of "A&B".

        Element elem = (Element) node;
        m_fileOptions.m_name = elem.elementText("fileName");
        m_fileOptions.m_type = elem.elementText("fileType");
        m_fileOptions.m_encoding = elem.elementText("fileEncoding");
        m_fileOptions.m_separator = elem.elementText("separator");
        m_fileOptions.m_ignoreHeader = elem.elementText("ignoreHeader");
        m_fileOptions.m_entryCount = elem.elementText("entryCount");
        m_fileOptions.m_status = elem.elementText("status");
        m_fileOptions.m_errorMessage = elem.elementText("errorMessage");

        initOther(root);
    } catch (ImporterException e) {
        throw e;
    } catch (Exception e) {
        CATEGORY.error("", e);
        // cast exception and throw
        error(e.getMessage(), e);
    } finally {
        XmlParser.fire(parser);
    }
}

From source file:com.globalsight.jobsAutoArchiver.AutoArchiver.java

License:Apache License

public void doWork() throws Exception {
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new File(Constants.CONFIG_FILE_NAME));
    Element rootElt = document.getRootElement();
    runOnce = document.selectSingleNode("//runOnce").getText();
    intervalTime = Integer.valueOf(document.selectSingleNode("//intervalTime").getText());
    Iterator serverIter = rootElt.elementIterator("server");
    while (serverIter.hasNext()) {
        final Element serverElement = (Element) serverIter.next();

        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    String hostName = serverElement.elementTextTrim("host");
                    int port = Integer.valueOf(serverElement.elementTextTrim("port"));
                    boolean isUseHTTPS = Boolean.valueOf(serverElement.elementTextTrim("https"));
                    int intervalTimeForArchive = Integer
                            .valueOf(serverElement.elementTextTrim("intervalTimeForArchive"));
                    Iterator usersIter = serverElement.elementIterator("users");
                    while (usersIter.hasNext()) {
                        Element usersElement = (Element) usersIter.next();
                        Iterator userIter = usersElement.elementIterator("user");
                        while (userIter.hasNext()) {
                            Element userElement = (Element) userIter.next();
                            String userName = userElement.elementTextTrim("username");
                            String password = userElement.elementTextTrim("password");
                            autoArchive(hostName, port, isUseHTTPS, userName, password, intervalTimeForArchive);
                        }//from  w w w  .java  2  s  . c  o m
                    }
                } catch (Throwable e) {
                    LogUtil.info("error : " + e);
                }
            }
        };
        Thread t = new Thread(runnable);
        t.start();
    }
}

From source file:com.globalsight.jobsAutoArchiver.AutoArchiver.java

License:Apache License

private void autoArchive(String hostName, int port, boolean isUseHTTPS, String userName, String password,
        int intervalTimeForArchive) {
    try {/*  w ww .java2s.  c  om*/
        Ambassador ambassador = WebServiceClientHelper.getClientAmbassador(hostName, port, userName, password,
                isUseHTTPS);
        String accessToken = ambassador.login(userName, password);
        String result = ambassador.fetchJobsByState(accessToken, Constants.JOB_STATE_EXPORTED, 0, 100, false);
        if (result == null) {
            LogUtil.info(
                    "server " + hostName + " , user " + userName + " : no jobs that are in exported state.");
        } else {
            LogUtil.info("server " + hostName + " , user " + userName
                    + " , returning of fetchJobsByState API:\n" + result);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
            long diffInHours = 0;
            long now = (new Date()).getTime();

            SAXReader saxReader = new SAXReader();
            Document document2 = saxReader.read(new ByteArrayInputStream(result.getBytes("UTF-8")));
            Element rootEltJob = document2.getRootElement();
            Iterator iterJob = rootEltJob.elementIterator("Job");
            Set<Long> jobIds = new HashSet<Long>();
            while (iterJob.hasNext()) {
                String jobId = null;
                String completedDateStr = null;
                try {
                    Element jobElement = (Element) iterJob.next();
                    jobId = jobElement.elementTextTrim("id");
                    completedDateStr = jobElement.elementTextTrim("completedDate");
                    Date completedDate = sdf.parse(completedDateStr.substring(0, 18).trim());
                    long completedDateLong = completedDate.getTime();
                    diffInHours = (now - completedDateLong) / 1000 / 60 / 60;
                    if (diffInHours >= intervalTimeForArchive) {
                        jobIds.add(Long.parseLong(jobId));
                    }
                } catch (Exception e) {
                    LogUtil.info("Error to check job with jobID: " + jobId + " and completedDate '"
                            + completedDateStr + "'.", e);
                }
            }
            StringBuffer jobs = new StringBuffer();
            for (long id : jobIds) {
                jobs.append(id).append(",");
            }
            if (jobs.length() > 0 && jobs.toString().endsWith(",")) {
                String jobs2 = jobs.toString().substring(0, jobs.length() - 1);
                ambassador.archiveJob(accessToken, jobs2);
                String[] jobs2_array = jobs2.toString().split(",");
                for (String job : jobs2_array) {
                    LogUtil.info("server " + hostName + ", user " + userName + " : the job " + job
                            + " can be archived");
                }
            } else {
                LogUtil.info("server " + hostName + ", user " + userName + " : no jobs that can be archived.");
            }
        }
    } catch (Exception e) {
        LogUtil.info("server " + hostName + ", user " + userName + ", error : " + e);
    }
}

From source file:com.globalsight.ling.docproc.DiplomatWordCounter.java

License:Apache License

/**
 * Counts words in a segment node and the individual subflows.
 *//* w  w  w.  j a  v a  2 s  . c o  m*/
private int countSegment(SegmentNode p_segment) throws DiplomatWordCounterException {
    int segmentWordCount = 0;

    try {
        String segment = p_segment.getSegment();
        // replace internal text and internal tags as " "
        if (segment.contains("internal=\"yes\"")) {
            segment = removeInternalTagsForWordCounter(segment);
        }
        // GBS-3997&GBS-4066, remove emoji alias occurrences before word
        // counting
        segment = segment.replaceAll(EmojiUtil.TYPE_EMOJI + ":[^:]*?:", "");

        Document doc = parse("<AllYourBaseAreBelongToUs>" + segment + "</AllYourBaseAreBelongToUs>");
        Element root = doc.getRootElement();
        segmentWordCount = countWords(root);

        // for has Sub, does not have Ph code
        String oriSegment = p_segment.getSegment();
        Document oridoc = parse("<AllYourBaseAreBelongToUs>" + oriSegment + "</AllYourBaseAreBelongToUs>");
        Element oriroot = oridoc.getRootElement();
        int oriCount = countWords(root);
        boolean hasSub = countSubs(oriroot);
        boolean noPh = oriSegment != null && oriSegment.indexOf("<ph") == -1;

        if (noPh || hasSub) {
            p_segment.setSegment(getInnerXml(oriroot));
        }
    } catch (Exception e) {
        throw new DiplomatWordCounterException(ExtractorExceptionConstants.DIPLOMAT_XML_PARSE_ERROR, e);
    }

    return segmentWordCount;
}