List of usage examples for org.dom4j Element elements
List<Element> elements(QName qName);
From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java
License:Apache License
private static void removeAttributeForNode(Element root, String nodeName, String[] attributes) { List elements = root.elements(nodeName); Iterator it = elements.iterator(); while (it.hasNext()) { Element element = (Element) it.next(); for (int i = 0; i < attributes.length; i++) { Attribute attribute = element.attribute(attributes[i]); if (attribute != null) { element.remove(element.attribute(attributes[i])); }/* w ww .java 2 s . co m*/ } } }
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 {// w ww . jav a 2 s . 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.importer.TmxReaderThread.java
License:Apache License
/** * Converts a DOM TU to a GS SegmentTmTu, thereby converting any TMX * format specialities as best as possible. *///from w w w . j ava 2s . c om private SegmentTmTu createTu(Element p_root) throws Exception { SegmentTmTu result = new SegmentTmTu(); // Optional TU attributes: // Original TU id, if known String id = p_root.attributeValue(Tmx.TUID); if (id != null && id.length() > 0) { try { long lid = Long.parseLong(id); result.setId(lid); } catch (Throwable ignore) { // <TU tuid> can be an alphanumeric token. // If it is not a simple number, we ignore it. } } // Datatype of the TU (html, javascript etc) String format = p_root.attributeValue(Tmx.DATATYPE); if (format == null || format.length() == 0) { format = m_tmx.getDatatype(); } result.setFormat(format); // Locale of Source TUV (use default from header) String lang = p_root.attributeValue(Tmx.SRCLANG); if (lang == null || lang.length() == 0) { lang = m_defaultSrcLang; } try { String locale = ImportUtil.normalizeLocale(lang); result.setSourceLocale(ImportUtil.getLocaleByName(locale)); } catch (Throwable ex) { CATEGORY.warn("invalid locale " + lang); throw new Exception("cannot handle locale " + lang); } // TODO: other optional attributes String usageCount = p_root.attributeValue(Tmx.USAGECOUNT); String usageDate = p_root.attributeValue(Tmx.LASTUSAGEDATE); //String tool = p_root.attributeValue(Tmx.CREATIONTOOL); //String toolversion = p_root.attributeValue(Tmx.CREATIONTOOLVERSION); // used in createTuv() //String creationDate = p_root.attributeValue(Tmx.CREATIONDATE); //String creationUser = p_root.attributeValue(Tmx.CREATIONID); //String changeDate = p_root.attributeValue(Tmx.CHANGEDATE); //String changeUser = p_root.attributeValue(Tmx.CHANGEID); // GlobalSight-defined properties: // Segment type (text, css-color, etc) String segmentType = "text"; Node node = p_root.selectSingleNode(".//prop[@type = '" + Tmx.PROP_SEGMENTTYPE + "']"); if (node != null) { segmentType = node.getText(); } result.setType(segmentType); //Read SID node = p_root.selectSingleNode(".//prop[@type= '" + Tmx.PROP_TM_UDA_SID + "']"); if (node != null) { result.setSID(node.getText()); } // TU type (T or L) boolean isTranslatable = true; node = p_root.selectSingleNode(".//prop[@type = '" + Tmx.PROP_TUTYPE + "']"); if (node != null) { isTranslatable = node.getText().equals(Tmx.VAL_TU_TRANSLATABLE); } if (isTranslatable) { result.setTranslatable(); } else { result.setLocalizable(); } // prop with Att:: List propNodes = p_root.elements("prop"); for (int i = 0; i < propNodes.size(); i++) { Element elem = (Element) propNodes.get(i); ProjectTmTuTProp prop = createProp(result, elem); if (prop != null) result.addProp(prop); } // TUVs List nodes = p_root.elements("tuv"); for (int i = 0; i < nodes.size(); i++) { Element elem = (Element) nodes.get(i); SegmentTmTuv tuv = createTuv(result, elem); result.addTuv(tuv); } if (com.globalsight.everest.tm.importer.ImportOptions.TYPE_TMX_WORLD_SERVER .equals(m_options.getFileType())) { result.setFromWorldServer(true); } return result; }
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. ja v a2 s. c om*/ * * @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
/** * Validates the sub elements inside a TMX tag. This means adding * a <sub locType="..."> attribute. * * TODO.// w ww . j a va 2 s . c o m */ private void validateSubs(Element p_tuv, Element p_elem, IntHolder p_x_count) throws Exception { List subs = p_elem.elements("sub"); for (int i = 0, max = subs.size(); i < max; i++) { Element sub = (Element) subs.get(i); validateSegment(p_tuv, sub, p_x_count); } }
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;//w w w. ja va 2 s . c om 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; }
From source file:com.globalsight.smartbox.bussiness.process.Usecase02PostProcess.java
License:Apache License
/** * Convert xml to csv or txt file// www. j a v a2 s. c om * * @param format * @param originFile * @return * @throws Exception */ private File convertXMLToCSVTXT(String format, String targetFile, String outputFilePath) throws Exception { File xmlFile = new File(targetFile); File outputFile = new File(outputFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(xmlFile); Element aElement = document.getRootElement(); String encoding = aElement.attributeValue("BomInfo"); FileOutputStream fos = new FileOutputStream(outputFilePath); FileUtil.writeBom(fos, encoding); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, encoding)); List<Element> rows = aElement.elements("row"); for (Element row : rows) { List<String> rowStr = new ArrayList<String>(); rowStr.add(row.elementText("sid")); rowStr.add(row.elementText("sourceLocaleName")); rowStr.add(row.elementText("sourceLocaleCode")); rowStr.add(row.elementText("unknown")); rowStr.add(row.elementText("translationSource")); rowStr.add(row.elementText("targetLocale")); rowStr.add(row.elementText("creationDate")); List<Element> segments = row.elements("segment"); for (Element element : segments) { rowStr.add(element.getText()); } StringBuffer sb = new StringBuffer(); if ("csv".equals(format)) { for (String str : rowStr) { sb.append("\"").append(str).append("\"").append(","); } } else { for (String str : rowStr) { sb.append(str).append("|"); } } sb.deleteCharAt(sb.length() - 1); bw.write(sb.toString()); bw.newLine(); } bw.close(); fos.close(); return outputFile; }
From source file:com.globalsight.terminology.EntryUtils.java
License:Apache License
/** * Finds the preferred term in the given language. The preferred * term is the one that has a usage='preferred' field. If no term * is qualified as preferred, the first term is returned. * * @return preferred term as string if found, else null. *//*from w w w . j a v a 2 s . c o m*/ static public String getPreferredTbxTerm(Entry p_entry, String p_language) throws TermbaseException { Document dom = p_entry.getDom(); Element root = dom.getRootElement(); String result = null; List langSets = root.elements("langSet"); if (langSets.size() == 0) { return null; } for (int i = 0; i < langSets.size(); i++) { Element langSet = (Element) langSets.get(i); if (EntryUtils.getLanguageName(langSet.attribute("lang").getText()).equals(p_language)) { if (langSet.elements("ntig").size() != 0) { result = langSet.element("ntig").element("termGrp").element("term").getText(); } if (langSet.elements("tig").size() != 0) { result = langSet.element("tig").element("term").getText(); } break; } } return result; }
From source file:com.globalsight.terminology.EntryUtils.java
License:Apache License
/** * Used to merge Tag ntig or tig of TBX files. * TBX files may contain several same languages in a single termentry, * when merging two new files, all the same languages should totally considered. * @param sameLangSetsInATermentry/* w w w . jav a 2 s .com*/ * @param p_one * @param p_two * @param p_comp */ private static void mergeTbxNtigsOrTigs(List sameLangSetsInATermentry, Element p_one, Element p_two, NodeComparator p_comp) { for (Iterator it = p_two.elementIterator(); it.hasNext();) { Element node = (Element) it.next(); it.remove(); node.detach(); String name = node.getName(); if (name.equals("ntig")) { String newTerm = node.element("termGrp").element("term").getText(); List<String> oldTerms = new ArrayList<String>(); for (int i = 0; i < sameLangSetsInATermentry.size(); i++) { Element tmp = (Element) sameLangSetsInATermentry.get(i); List<Element> ntigs = tmp.elements("ntig"); for (int j = 0; j < ntigs.size(); j++) { try { String oldTerm = ntigs.get(j).element("termGrp").element("term").getText(); oldTerms.add(oldTerm); } catch (Exception e) { //langSet or termGrp is empty } } } if (!oldTerms.contains(newTerm)) { p_one.add(node); } } if (name.equals("tig")) { String newTerm = node.element("term").getText(); List<String> oldTerms = new ArrayList<String>(); for (int i = 0; i < sameLangSetsInATermentry.size(); i++) { Element tmp = (Element) sameLangSetsInATermentry.get(i); List<Element> tigs = p_one.elements("tig"); for (int j = 0; j < tigs.size(); j++) { try { String oldTerm = tigs.get(j).element("term").getText(); oldTerms.add(oldTerm); } catch (Exception e) { //langSet or termGrp is empty } } } if (!oldTerms.contains(newTerm)) { p_one.add(node); } } } }
From source file:com.globalsight.terminology.EntryUtils.java
License:Apache License
private static void mergeLangSet(Element p_one, Element p_two, Element node, NodeComparator p_comp) { String languageName = node.attribute("lang").getText(); List langSets = p_one.elements("langSet"); List<Element> langSetsWithEqualLanguageName = new ArrayList<Element>(); for (int i = 0; i < langSets.size(); i++) { Element tmp = (Element) langSets.get(i); if (tmp.attribute("lang").getText().equals(languageName)) { langSetsWithEqualLanguageName.add(tmp); }//from w w w . j av a 2 s. c om } if (langSetsWithEqualLanguageName.size() == 0) { p_one.add(node); return; } mergeTbxNtigsOrTigs(langSetsWithEqualLanguageName, langSetsWithEqualLanguageName.get(0), node, p_comp); }