Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

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

Prototype

List<Element> elements();

Source Link

Document

Returns the elements contained in this element.

Usage

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

private void convertToSourceGrp(Element p_elem) {
    Element sourceGrp = p_elem.createCopy("sourceGrp");

    // sourceGrp contains noteGrp, remove all non-noteGrp
    // children, remembering the <descrip type="source"> itself
    for (ListIterator lit = sourceGrp.elements().listIterator(); lit.hasNext();) {
        Element child = (Element) lit.next();

        if (child.getName().equals("descrip")) {
            Element source = child.createCopy("source");
            source.remove(source.attribute("type"));

            lit.set(source);/* ww w  . j  a v a2  s .co m*/
        } else if (!child.getName().equals("noteGrp")) {
            lit.remove();
        }
    }

    Element parent = p_elem.getParent();
    parent.content().set(parent.indexOf(p_elem), sourceGrp);
}

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

private void convertRecursiveDescripGrps(Element p_elem, String p_path) {
    List nodes = p_elem.selectNodes(p_path);
    for (Iterator it = nodes.iterator(); it.hasNext();) {
        Element descripGrp = (Element) it.next();

        for (ListIterator lit = descripGrp.elements().listIterator(); lit.hasNext();) {
            Element elem = (Element) lit.next();

            if (elem.getName().equals("descripGrp")) {
                convertToNoteGrp(elem);//from   www  .ja va  2 s .c o m
            }
        }
    }
}

From source file:com.globalsight.terminology.importer.MtfReaderThread.java

License:Apache License

private void removeRecursiveDescripGrps(Element p_elem) {
    List nodes = p_elem.selectNodes(".//descripGrp[descripGrp]");
    for (Iterator it = nodes.iterator(); it.hasNext();) {
        Element descripGrp = (Element) it.next();

        for (ListIterator lit = descripGrp.elements().listIterator(); lit.hasNext();) {
            Element elem = (Element) lit.next();

            if (elem.getName().equals("descripGrp")) {
                elem.detach();//www. j a  va  2s  . c  o m
            }
        }
    }
}

From source file:com.globalsight.terminology.indexer.Writer.java

License:Apache License

private void getIndexableText(Element p_root, ArrayList p_result) {
    if (p_root == null || p_root.nodeCount() == 0) {
        return;/*ww w. j  a va  2s  . co  m*/
    }

    List elements = p_root.elements();

    for (int i = 0, max = elements.size(); i < max; i++) {
        Element elem = (Element) elements.get(i);
        String name = elem.getName();

        Element field = null;
        String type = null;

        if (name.equals("descripGrp")) {
            getIndexableText(elem, p_result);
        } else if (name.equals("sourceGrp")) {
            getIndexableText(elem, p_result);
        } else if (name.equals("noteGrp")) {
            getIndexableText(elem, p_result);
        } else if (name.equals("descrip")) {
            field = elem;
            type = field.attributeValue("type");
        } else if (name.equals("source")) {
            field = elem;
            type = "source";
        } else if (name.equals("note")) {
            field = elem;
            type = "note";
        }

        if (field == null || type == null) {
            continue;
        }

        if (isIndexableField(type)) {
            p_result.add(EntryUtils.getInnerText(field));
        }
    }
}

From source file:com.globalsight.terminology.searchreplace.TbMaintance.java

License:Apache License

private void searchNode(Element node, ArrayList array, long conceptId, long levelId) {
    String field = node.getText();
    String searchText = rp.getSearchText();
    String fieldType = rp.getSearchType();

    if (!field.isEmpty()) {
        //String name = node.getName();
        boolean flag = false;

        if (rp.isCaseInsensitive()) {
            if (rp.isWholeWord()) {
                if (field.equals(searchText)) {
                    flag = true;//from ww  w  .ja  v a2s. c om
                }
            } else {
                if (field.indexOf(searchText) > -1) {
                    flag = true;
                }
            }
        } else {
            if (rp.isWholeWord()) {
                if (field.toLowerCase().equals(searchText.toLowerCase())) {
                    flag = true;
                }
            } else {
                if (field.toLowerCase().indexOf(searchText.toLowerCase()) > -1) {
                    flag = true;
                }
            }
        }

        if (flag) {
            boolean judge = false;
            String typeValue = node.attributeValue("type");

            if (typeValue == null) {
                //if attribute type is null, get the node name to judge
                String nodeName = node.getName();
                typeValue = nodeName;
            }

            if (fieldType == null || fieldType.trim().equals("")) {
                //if no select field type, select all
                judge = true;
            } else {
                if (typeValue != null) {
                    //if attribute type is not null, judge the type
                    if (typeValue.toLowerCase().trim().indexOf(fieldType.toLowerCase().trim()) > -1) {
                        judge = true;
                    }
                }
            }

            if (judge) {
                SearchResult p_result = new SearchResult();
                p_result.setConceptId(conceptId);
                p_result.setLevelId(levelId);
                p_result.setFiled(field);
                p_result.setType(typeValue);
                array.add(p_result);
            }
        }
    } else {
        List children = node.elements();

        for (int i = 0, max = children.size(); i < max; i++) {
            Element child = (Element) children.get(i);
            searchNode(child, array, conceptId, levelId);
        }
    }
}

From source file:com.globalsight.terminology.searchreplace.TbMaintance.java

License:Apache License

private void doNodeVistor(Element node, String oldFieldText, String replaceText) {
    String field = node.getText();

    if (!field.isEmpty()) {
        if (field.indexOf(oldFieldText) > -1) {
            node.setText(replaceText);//from   w w w.  ja v  a 2  s  .co  m
        }
    } else {
        List children = node.elements();

        for (int i = 0, max = children.size(); i < max; i++) {
            Element child = (Element) children.get(i);
            doNodeVistor(child, oldFieldText, replaceText);
        }
    }
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

/**
 * Edit job detail info.//from   www . j  ava2 s.com
 * 
 * @param p_accessToken
 *            - The access token received from the login.
 * @param p_jobId
 *            - Job id is not empty and exist in GS server.
 * @param p_jobName
 *            - Job name can be empty.
 * @param p_estimatedDateXml
 *            - EstimatedDateXml can be empty. If not empty,example :
 *            <estimatedDates> <workflow> <targetLocale>zh_CN</targetLocale>
 *            <estimatedTranslateCompletionDate>yyyyMMdd
 *            HHmmss</estimatedTranslateCompletionDate>
 *            <estimatedWorkflowCompletionDate>yyyyMMdd
 *            HHmmss</estimatedWorkflowCompletionDate> </workflow>
 *            <workflow> ... ... </workflow> </estimatedDates>
 * @param p_priority
 *            Priority can be empty.If not empty,priority must be 1,2,3,4 or
 *            5;
 * */
public String editJobDetailInfo(String p_accessToken, String p_jobId, String p_jobName,
        String p_estimatedDateXml, String p_priority) throws WebServiceException {
    checkAccess(p_accessToken, EDIT_JOB_DETAIL_INFO);
    checkPermission(p_accessToken, Permission.JOBS_DETAILS);
    String userName = getUsernameFromSession(p_accessToken);
    Map<Object, Object> activityArgs = new HashMap<Object, Object>();
    activityArgs.put("loggedUserName", userName);
    activityArgs.put("jobId", p_jobId);
    activityArgs.put("jobName", p_jobName);
    activityArgs.put("estimatedDateXml", p_estimatedDateXml);
    activityArgs.put("priority", p_priority);
    WebServicesLog.Start activityStart = WebServicesLog.start(Ambassador.class,
            "editJobDetailInfo(p_accessToken,p_jobId,p_jobName,p_estimatedDateXml,p_priority)", activityArgs);

    Map<String, Object> paramter = new HashMap<String, Object>();
    try {
        if (!Assert.assertNotEmpty(p_jobId)) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Job id can not be empty");
        }
        Assert.assertIsInteger(p_jobId);
        if (StringUtil.isNotEmpty(p_priority)) {
            Assert.assertIsInteger(p_priority);

            int priority = Integer.parseInt(p_priority);
            if (priority != 1 && priority != 2 && priority != 3 && priority != 4 && priority != 5) {
                return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid priority: " + p_priority
                        + ", it should be limited in 1, 2, 3, 4, 5 or empty.");
            }
            paramter.put("priority", p_priority);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return makeErrorXml(EDIT_JOB_DETAIL_INFO, e.getMessage());
    }

    Job job = null;
    try {
        job = ServerProxy.getJobHandler().getJobById(Long.parseLong(p_jobId));
        if (job == null) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid job id: " + p_jobId);
        }

        if (!isInSameCompany(userName, String.valueOf(job.getCompanyId()))) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO,
                    "Invalid job id: " + p_jobId + ", current user is not in the same company with the job.");
        }

        if (!job.getDisplayState().equalsIgnoreCase("ready") && StringUtil.isNotEmpty(p_jobName)) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Only job in ready state is allowed to modify job name.");
        }

        paramter.put("jobId", p_jobId);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return makeErrorXml(EDIT_JOB_DETAIL_INFO, e.getMessage());
    }

    // get unique job name
    if (StringUtil.isNotEmpty(p_jobName)) {
        try {
            p_jobName = EditUtil.removeCRLF(p_jobName);
            if (p_jobName.length() > 120) {
                return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid job name: " + p_jobName
                        + ",  the max lenght for job name limits to 120 characters.");
            }
            Job checkJob = ServerProxy.getJobHandler().getJobByJobName(p_jobName);
            if (checkJob == null) {
                paramter.put("jobName", p_jobName);
            } else {
                if (checkJob.getId() == Long.parseLong(p_jobId)) {
                    return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid job name: " + p_jobName
                            + ", the modify name is identical to current one.");
                } else {
                    return makeErrorXml(EDIT_JOB_DETAIL_INFO,
                            "Invalid job name: " + p_jobName + ", job name already exists.");
                }
            }
        } catch (Exception e) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO, e.getMessage());
        }
    }

    if (StringUtil.isNotEmpty(p_estimatedDateXml)) {
        Document doc;
        SimpleDateFormat sfm = new SimpleDateFormat("yyyyMMdd HHmmss");
        String userId = UserUtil.getUserIdByName(userName);
        try {
            User user = ServerProxy.getUserManager().getUser(userId);
            TimeZone timeZone = ServerProxy.getCalendarManager().findUserTimeZone(userId);
            Timestamp ts = new Timestamp(Timestamp.DATE, timeZone);
            Locale uiLocale = new Locale(user.getDefaultUILocale());
            ts.setLocale(uiLocale);
            doc = DocumentHelper.parseText(p_estimatedDateXml);
            Element rootElt = doc.getRootElement();
            List elements = rootElt.elements();
            Map<Long, Map<String, Date>> workMap = new HashMap<Long, Map<String, Date>>();
            for (int i = 0; i < elements.size(); i++) {
                Element et = (Element) elements.get(i);
                Map<String, Date> dateMap = new HashMap<String, Date>();

                String targetLocale = null;
                String tranComDateStr = null;
                String workComDateStr = null;
                try {
                    targetLocale = et.element("targetLocale").getText();
                    tranComDateStr = et.element("estimatedTranslateCompletionDate").getText();
                    workComDateStr = et.element("estimatedWorkflowCompletionDate").getText();
                } catch (Exception e) {
                    return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid estimatedDateXml,xml spelling errors.");
                }

                if (StringUtil.isEmpty(targetLocale)) {
                    return makeErrorXml(EDIT_JOB_DETAIL_INFO,
                            "Invalid estimatedDateXml: target locale can not be empty.");
                }
                GlobalSightLocale targetGSLocale = null;
                try {
                    targetGSLocale = getLocaleByName(targetLocale);
                    if (targetGSLocale == null) {
                        return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid target locale: " + targetLocale);
                    }

                    long sameId = -1;
                    for (Workflow wf : job.getWorkflows()) {
                        if (targetGSLocale.getId() == wf.getTargetLocale().getId()) {
                            sameId = wf.getTargetLocale().getId();
                        }
                    }
                    if (sameId == -1) {
                        return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid target locale: " + targetLocale
                                + ", current job has no workflow with this target locale.");
                    }
                } catch (Exception e) {
                    return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid target locale: " + targetLocale);
                }

                if (StringUtil.isNotEmpty(tranComDateStr)) {
                    try {
                        Date tranComDate = sfm.parse(tranComDateStr);
                        ts.setDate(tranComDate);
                        dateMap.put("estimatedTranslateCompletionDate", ts.getDate());
                    } catch (ParseException e) {
                        return makeErrorXml(EDIT_JOB_DETAIL_INFO,
                                "Invalid estimatedTranslateCompletionDate: " + tranComDateStr);
                    }
                }

                if (StringUtil.isNotEmpty(workComDateStr)) {
                    try {
                        Date workComDate = sfm.parse(workComDateStr);
                        ts.setDate(workComDate);
                        dateMap.put("estimatedWorkflowCompletionDate", ts.getDate());
                    } catch (ParseException e) {
                        return makeErrorXml(EDIT_JOB_DETAIL_INFO,
                                "Invalid estimatedWorkflowCompletionDate: " + workComDateStr);
                    }
                }

                if (!dateMap.isEmpty() && !workMap.containsKey(targetGSLocale.getId())) {
                    workMap.put(targetGSLocale.getId(), dateMap);
                }
            }
            // put workflow date paramter
            paramter.put("estimatedDates", workMap);
        } catch (Exception e) {
            return makeErrorXml(EDIT_JOB_DETAIL_INFO, "Invalid estimatedDateXml: XML parse error.");
        }
    }

    String returnStr = updateJobDetailInfo(paramter);
    activityStart.end();
    return returnStr;
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

/**
 * check if some jobs is downloadable or delete them from backup file in
 * client//from  w  w w.  j av a  2 s  . com
 * 
 * @param p_accessToken
 * @param p_message
 * @return xml String result <jobs> <job> <name>job name</name>
 *         <status>downloadable | create_error | unknown</status> </job>
 *         </jobs>
 * @throws WebServiceException
 */
public String getDownloadableJobs(String p_accessToken, String p_msg) throws WebServiceException {
    checkAccess(p_accessToken, GET_DOWNLOADABLE_JOBS);

    p_msg = StringUtil.replace(p_msg, "&", "&amp;");
    XmlParser parser = new XmlParser();
    Document doc = null;
    try {
        doc = parser.parseXml(p_msg);
    } catch (Exception e) {
        throw new WebServiceException(makeErrorXml("getDownloadableJobs",
                "Invalid xml content in parameter p_msg. " + e.getMessage()));
    }
    try {
        Element root = doc.getRootElement();
        List jobList = root.elements();
        if (jobList.size() > 0) {
            HashMap<Long, Set<String>> jobDirMap = new HashMap<Long, Set<String>>();

            Job job = null;
            String status = "";
            for (Iterator iter = jobList.iterator(); iter.hasNext();) {
                status = "unknown";
                Element jobElement = (Element) iter.next();
                String jobName = jobElement.element("name").getText();

                try {
                    job = queryJob(jobName, p_accessToken);
                    if (job != null) {
                        long companyId = job.getCompanyId();
                        if (jobDirMap.get(companyId) == null) {
                            Set<String> jobDirs = new HashSet<String>();
                            File diExportedDir = AmbFileStoragePathUtils.getDesktopIconExportedDir(companyId);
                            File[] files = diExportedDir.listFiles();
                            for (File file : files) {
                                jobDirs.add(file.getName());
                            }
                            jobDirMap.put(companyId, jobDirs);
                        }

                        Set<String> jobDirs2 = jobDirMap.get(companyId);
                        /*
                         * For old jobs created before 8.4, they use job
                         * name as folder name. After 8.4, it use job id
                         * instead of job name
                         */
                        if (jobDirs2.contains(jobName)) {
                            status = "downloadable";
                        } else {
                            String jobIdStr = String.valueOf(job.getJobId());
                            if (jobDirs2.contains(jobIdStr)) {
                                status = "downloadable";
                            }
                        }
                    }
                } catch (WebServiceException ignore) {

                }

                jobElement.element("status").setText(status);
            }
        }

        return doc.asXML();
    } catch (Exception e) {
        logger.error(GET_DOWNLOADABLE_JOBS, e);
        String message = makeErrorXml(GET_DOWNLOADABLE_JOBS, e.getMessage());
        throw new WebServiceException(message);
    }
}

From source file:com.globalsight.webservices.Ambassador.java

License:Apache License

/**
 * Validates the segment, and try to repair it if the format is wrong.
 * /*from w w w  .j av  a2 s.c  o  m*/
 * <p>
 * Will throw out a exception if the format is wrong and can not be
 * repaired.
 * 
 * @param p_seg
 *            The segment string to validate
 * @param p_x_count
 *            The value of x
 * @return Repaired segment
 * @throws Exception
 */
private Element validateSegment(Element p_seg, IntHolder p_x_count) throws Exception {
    String attr;

    List elems = p_seg.elements();

    for (Iterator it = elems.iterator(); it.hasNext();) {
        Element elem = (Element) it.next();
        String name = elem.getName();

        if (name.equals("bpt")) {
            attr = elem.attributeValue("x"); // mandatory only in 1.4
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("x", String.valueOf(p_x_count.inc()));
            }

            attr = elem.attributeValue("i"); // mandatory
            if (attr == null || attr.length() == 0) {
                throw new Exception("A <bpt> tag is lacking the mandatory i attribute.");
            }

            attr = elem.attributeValue("type");
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("type", DEFAULT_TYPE);
            }
        } else if (name.equals("ept")) {
            attr = elem.attributeValue("i"); // mandatory
            if (attr == null || attr.length() == 0) {
                throw new Exception("A <ept> tag is lacking the mandatory i attribute.");
            }
        } else if (name.equals("it")) {
            attr = elem.attributeValue("x"); // mandatory only in 1.4
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("x", String.valueOf(p_x_count.inc()));
            }

            attr = elem.attributeValue("pos"); // mandatory
            if (attr == null || attr.length() == 0) {
                throw new Exception("A <it> tag is lacking the mandatory pos attribute.");
            }

            attr = elem.attributeValue("type");
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("type", DEFAULT_TYPE);
            }
        } else if (name.equals("ph")) {
            attr = elem.attributeValue("x"); // mandatory only in 1.4
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("x", String.valueOf(p_x_count.inc()));
            }

            attr = elem.attributeValue("type");
            if (attr == null || attr.length() == 0) {
                elem.addAttribute("type", DEFAULT_TYPE);
            }

            // GXML doesn't care about assoc, just preserve it.
            // attr = elem.attributeValue("assoc");
        } else if (name.equals("ut")) {
            // TMX level 2 does not allow UT. We can either remove
            // it, or look inside and guess what it may be.
            it.remove();
            continue;
        }

        // Recurse into any subs.
        validateSubs(elem, p_x_count);
    }

    return p_seg;
}

From source file:com.globalsight.webservices.AmbassadorHelper.java

License:Apache License

/**
 * Parse roles information from XML format string.
 * The XML format string is like below:/* w w w . ja va2  s  . c o m*/
 * <?xml version=\"1.0\"?>
 * <roles>
 *   <role>
 *     <sourceLocale>en_US</sourceLocale>
 *     <targetLocale>de_DE</targetLocale>
 *     <activities>
 *       <activity>
 *         <name>Dtp1</name>
 *       </activity>
 *       <activity>
 *         <name>Dtp2</name>
 *       </activity>
 *     </activities>
 *   </role>
 * </roles>
 * 
 * @param p_user -- User
 * @param p_xml -- Roles information
 * @return List<UserRole>
 */
@SuppressWarnings({ "unused", "rawtypes" })
private List<UserRole> parseRoles(User p_user, String p_xml) {
    if (StringUtil.isEmpty(p_xml))
        return null;

    ArrayList<UserRole> roles = new ArrayList<UserRole>();
    try {
        XmlParser parser = new XmlParser();
        Document doc = parser.parseXml(p_xml);
        Element root = doc.getRootElement();
        List rolesList = root.elements();
        if (rolesList == null || rolesList.size() == 0)
            return null;

        String sourceLocale, targetLocale, activityId, activityName, activityDisplayName, activityUserType,
                activityType;
        Activity activity = null;
        UserRole role = null;
        LocalePair localePair = null;

        UserManagerWLRemote userManager = ServerProxy.getUserManager();
        JobHandlerWLRemote jobManager = ServerProxy.getJobHandler();
        Company loggedCompany = CompanyWrapper.getCompanyByName(p_user.getCompanyName());

        for (Iterator iter = rolesList.iterator(); iter.hasNext();) {
            Element roleElement = (Element) iter.next();
            sourceLocale = roleElement.element("sourceLocale").getText();
            targetLocale = roleElement.element("targetLocale").getText();
            String localeCompanyName = null;
            Company localeCompany = null;
            Element node = (Element) roleElement.selectSingleNode("companyName");
            if (CompanyWrapper.SUPER_COMPANY_ID.equals(String.valueOf(loggedCompany.getId()))) {
                if (node == null)
                    return null;
                localeCompanyName = roleElement.element("companyName").getText();
                localeCompany = CompanyWrapper.getCompanyByName(localeCompanyName.trim());
                if (localeCompany == null)
                    return null;
            } else {
                if (node != null)
                    return null;
            }

            if (localeCompany == null)
                localePair = getLocalePairBySourceTargetAndCompanyStrings(sourceLocale, targetLocale,
                        loggedCompany.getId());
            else
                localePair = getLocalePairBySourceTargetAndCompanyStrings(sourceLocale, targetLocale,
                        localeCompany.getId());

            if (localePair == null)
                return null;

            List activitiesList = roleElement.elements("activities");
            if (activitiesList == null || activitiesList.size() == 0)
                return null;

            for (Iterator iter1 = activitiesList.iterator(); iter1.hasNext();) {
                Element activitiesElement = (Element) iter1.next();

                List activityList = activitiesElement.elements();
                for (Iterator iter2 = activityList.iterator(); iter2.hasNext();) {
                    Element activityElement = (Element) iter2.next();
                    activityName = activityElement.element("name").getText();
                    if (localeCompany != null) {
                        activity = jobManager.getActivityByCompanyId(activityName + "_" + localeCompany.getId(),
                                String.valueOf(localeCompany.getId()));
                    } else {
                        activity = jobManager.getActivityByCompanyId(activityName + "_" + loggedCompany.getId(),
                                String.valueOf(loggedCompany.getId()));
                    }

                    if (activity == null)
                        return null;

                    role = userManager.createUserRole();
                    ((Role) role).setActivity(activity);
                    ((Role) role).setSourceLocale(sourceLocale);
                    ((Role) role).setTargetLocale(targetLocale);
                    // role.setUser(p_user.getUserId());
                    roles.add(role);
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    }
    return roles;
}