List of usage examples for org.dom4j Document getRootElement
Element getRootElement();
From source file:com.globalsight.terminology.util.GSEntryParse.java
License:Apache License
/** * Gets the entry's concept ID./* w w w . java 2s.c o m*/ * * @return 0 if the entry has no ID yet, else a positive number. */ public String getConceptId(Entry p_entry) throws TermbaseException { Document dom = p_entry.getDom(); Element root = dom.getRootElement(); Element concept = root.element("concept"); if (concept == null || concept.getText().length() == 0) { return null; } else { return concept.getText(); } }
From source file:com.globalsight.terminology.util.TBXEntryParse.java
License:Apache License
/** * Get TBX files entry id/* w w w . j a v a2 s . c o m*/ * * @param entry * @return * @throws TermbaseException */ public String getConceptId(Entry entry) throws TermbaseException { Document dom = entry.getDom(); Element root = dom.getRootElement(); if (root.attribute("id") == null || root.attribute("id").getText().length() == 0) { return null; } else { return root.attribute("id").getText(); } }
From source file:com.globalsight.util.file.XliffFileUtil.java
License:Apache License
/** * Check if specified file contains multiple <File> tags * /* w w w.j a v a2 s.c o m*/ * @param p_filename * File name * @return Return true if file contains multiple <File> tags, otherwise * return false * * @version 1.0 * @since 8.2.2 */ public static boolean isMultipleFileTags(String p_filename) { if (StringUtil.isEmpty(p_filename)) return false; int numOfFileTags = 0; try { SAXReader saxReader = new SAXReader(); Document document = null; Element rootElement = null; File file = new File(p_filename); if (file.exists() && file.isFile()) { document = saxReader.read(file); rootElement = document.getRootElement(); String tag = ""; for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext();) { tag = iterator.next().getName().trim().toLowerCase(); if ("file".equals(tag)) numOfFileTags++; } } return numOfFileTags > 1; } catch (Exception e) { logger.error("Can not verify if current file contains multiple file tags.", e); return false; } }
From source file:com.globalsight.util.file.XliffFileUtil.java
License:Apache License
public static boolean containsFileTag(String p_filename) { if (StringUtil.isEmpty(p_filename)) return false; try {//from w w w .j a v a 2 s. co m SAXReader saxReader = new SAXReader(); Document document = null; Element rootElement = null; File file = new File(p_filename); if (file.exists() && file.isFile()) { document = saxReader.read(file); rootElement = document.getRootElement(); String tag = ""; List fileTags = rootElement.elements("file"); if (fileTags != null) { for (int i = 0; i < fileTags.size(); i++) { Element element = (Element) fileTags.get(i); String attr = element.attributeValue("tool"); if (attr == null) return false; else { if (attr.toLowerCase().contains("worldserver")) return true; } } } } return false; } catch (Exception e) { logger.error("Can not verify if current file contains multiple file tags.", e); return false; } }
From source file:com.globalsight.util.file.XliffFileUtil.java
License:Apache License
/** * Generate separated files in single file level according with content in * orignal Xliff file/*from ww w . j a v a2 s .c om*/ * * @param multipleFileTagsXliff * Object contains all separated files * @param absoluteFilename * File name with absolute path * @param header * Header content of original Xliff file * @param content * Main content of original Xliff file * @param footer * Footer content of original Xliff file * * @version 1.0 * @since 8.2.2 */ private static void generateSeparatedFiles(MultipleFileTagsXliff multipleFileTagsXliff, String absoluteFilename, String header, String content, String footer) { try { String absolutePath = getBaseAbsoluatePath(absoluteFilename); String mainName = getMainFilename(absoluteFilename); String separatedDirPath = mainName + SEPARATE_FLAG; String absouateSeparatedPath = absolutePath + File.separator + separatedDirPath; File file = new File(absouateSeparatedPath); file.mkdirs(); int lengthOfFileEndTag = "</file>".length(); int beginIndex = -1, endIndex = -1; String subContent = ""; SAXReader saxReader = new SAXReader(); Document document = null; Element rootElement = null, fileTagElement = null, fileHeaderElement = null; String originalSubFilename = ""; String segAssetId = ""; BufferedWriter fout = null; ArrayList<String> separatedFiles = new ArrayList<String>(); String subFilename = ""; int count = 1; while ((beginIndex = content.indexOf("<file ")) > -1) { endIndex = content.indexOf("</file>") + lengthOfFileEndTag; subContent = header + content.substring(beginIndex, endIndex) + footer; // Use XML parser to get element value document = saxReader.read(new StringReader(subContent)); rootElement = document.getRootElement(); fileTagElement = rootElement.element("file"); originalSubFilename = fileTagElement.attributeValue("original").replace("/", File.separator); originalSubFilename = originalSubFilename .substring(originalSubFilename.lastIndexOf(File.separator) + 1); fileHeaderElement = fileTagElement.element("header"); if (fileHeaderElement != null && fileHeaderElement.element("asset-data") != null) { segAssetId = fileHeaderElement.element("asset-data").elementText("seg_asset_id"); } // Generate file name of separated file subFilename = originalSubFilename + "_" + segAssetId + "_" + count + ".xlf"; // Write separated file into disk file = new File(absouateSeparatedPath, subFilename); fout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); fout.write(subContent); fout.close(); separatedFiles.add(getRelativePath(file.getAbsolutePath())); content = content.substring(endIndex); count++; } multipleFileTagsXliff.setCount(count); multipleFileTagsXliff.setSeparatedFiles(separatedFiles); multipleFileTagsXliff.setSeparatedFolderName(separatedDirPath); } catch (Exception e) { logger.error("Error in generateExtractedFile.", e); } }
From source file:com.globalsight.util.file.XliffFileUtil.java
License:Apache License
private static String getItemFromNote(Document p_doc, String item) { String result = null;//www. ja v a2 s . c o m try { Element root = p_doc.getRootElement(); Element noteElement = root.element(XliffConstants.FILE).element(XliffConstants.HEADER) .element(XliffConstants.NOTE); String notes = noteElement.getText(); int index = notes.indexOf(item); notes = notes.substring(index); notes = notes.substring(0, notes.indexOf("#")).trim(); notes = notes.substring(notes.indexOf(":") + 1).trim(); result = notes; } catch (Exception e) { logger.error(e.getMessage(), e); } return result; }
From source file:com.globalsight.webservices.Ambassador.java
License:Apache License
/** * Edit job detail info.//from w w w . jav a2 s . c o m * * @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// w ww . j a v 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, "&", "&"); 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
private String nextTm3Tus(ProjectTM ptm, GlobalSightLocale srcGSLocale, GlobalSightLocale trgGSLocale, long tuIdToStart, int size) throws WebServiceException { Connection conn = null;/*from w ww .j a v a 2 s .com*/ try { conn = DbUtil.getConnection(); String tuTable = "tm3_tu_shared_" + ptm.getCompanyId(); String tuvTable = "tm3_tuv_shared_" + ptm.getCompanyId(); StatementBuilder sb = new StatementBuilder(); if (trgGSLocale != null) { sb.append("SELECT tuv.tuId FROM ").append(tuvTable).append(" tuv,"); sb.append(" (SELECT id FROM ").append(tuTable).append(" tu ").append("WHERE tu.tmid = ? ") .addValue(ptm.getTm3Id()).append(" AND tu.srcLocaleId = ? ").addValue(srcGSLocale.getId()) .append(" AND tu.id > ? ").addValue(tuIdToStart).append(" ORDER BY tu.id LIMIT 0, ") .append(String.valueOf(10 * size)).append(") tuids "); sb.append(" WHERE tuv.tuId = tuids.id"); sb.append(" AND tuv.localeId = ? ").addValue(trgGSLocale.getId()); sb.append(" AND tuv.tmId = ? ").addValue(ptm.getTm3Id()); sb.append(" ORDER BY tuv.tuId "); sb.append(" LIMIT 0, ").append(String.valueOf(size)).append(";"); } else { sb.append("SELECT id FROM ").append(tuTable).append(" WHERE tmid = ? ").addValue(ptm.getTm3Id()) .append(" AND srcLocaleId = ? ").addValue(srcGSLocale.getId()).append(" AND id > ? ") .addValue(tuIdToStart).append(" ORDER BY id ").append("LIMIT 0,").append(size + ";"); } List<Long> tuIds = SQLUtil.execIdsQuery(conn, sb); if (tuIds == null || tuIds.size() == 0) { return null; } BaseTm tm = TM3Util.getBaseTm(ptm.getTm3Id()); List<TM3Tu> tm3Tus = tm.getTu(tuIds); TM3Attribute typeAttr = TM3Util.getAttr(tm, TYPE); TM3Attribute formatAttr = TM3Util.getAttr(tm, FORMAT); TM3Attribute sidAttr = TM3Util.getAttr(tm, SID); TM3Attribute translatableAttr = TM3Util.getAttr(tm, TRANSLATABLE); TM3Attribute fromWsAttr = TM3Util.getAttr(tm, FROM_WORLDSERVER); TM3Attribute projectAttr = TM3Util.getAttr(tm, UPDATED_BY_PROJECT); List<SegmentTmTu> segTmTus = new ArrayList<SegmentTmTu>(); for (TM3Tu tm3Tu : tm3Tus) { segTmTus.add(TM3Util.toSegmentTmTu(tm3Tu, ptm.getId(), formatAttr, typeAttr, sidAttr, fromWsAttr, translatableAttr, projectAttr)); } List<GlobalSightLocale> targetLocales = null; if (trgGSLocale != null) { targetLocales = new ArrayList<GlobalSightLocale>(); targetLocales.add(trgGSLocale); } StringBuffer result = new StringBuffer(); IExportManager exporter = null; String options = null; exporter = TmManagerLocal.getProjectTmExporter(ptm.getName()); options = exporter.getExportOptions(); Document doc = DocumentHelper.parseText(options); Element rootElt = doc.getRootElement(); Iterator fileIter = rootElt.elementIterator("fileOptions"); while (fileIter.hasNext()) { Element fileEle = (Element) fileIter.next(); Element fileTypeElem = fileEle.element("fileType"); fileTypeElem.setText("xml"); } Iterator filterIter = rootElt.elementIterator("filterOptions"); while (filterIter.hasNext()) { Element filterEle = (Element) filterIter.next(); Element language = filterEle.element("language"); if (trgGSLocale != null) { language.setText(trgGSLocale.getLanguage() + "_" + trgGSLocale.getCountry()); } } options = doc.asXML().substring(doc.asXML().indexOf("<exportOptions>")); exporter.setExportOptions(options); Tmx tmx = new Tmx(); tmx.setSourceLang(Tmx.DEFAULT_SOURCELANG); tmx.setDatatype(Tmx.DATATYPE_HTML); TmxWriter tmxWriter = new TmxWriter(exporter.getExportOptionsObject(), ptm, tmx); for (SegmentTmTu segTmTu : segTmTus) { result.append(tmxWriter.getSegmentTmForXml(segTmTu)); } return result.toString(); } catch (Exception e) { logger.error(e); throw new WebServiceException(e.getMessage()); } finally { DbUtil.silentReturnConnection(conn); } }
From source file:com.globalsight.webservices.Ambassador.java
License:Apache License
/** * Updates a tu in database. Only work for TM2. * //from ww w. j a va 2s .c o m * @param accessToken * To judge caller has logon or not, can not be null. you can get * it by calling method <code>login(username, password)</code>. * @param tmx * A tmx formate string inlcluding all tu information. * @return * @deprecated only work for TM2. * * @throws WebServiceException */ public String editTu(String accessToken, String tmx) throws WebServiceException { long tuId = -1; SAXReader reader = new SAXReader(); try { Document doc = reader.read(new StringReader("<root>" + tmx + "</root>")); List tuNodes = doc.getRootElement().selectNodes("//tu"); if (tuNodes != null && tuNodes.size() > 0) { Iterator nodeIt = tuNodes.iterator(); while (nodeIt.hasNext()) { Element tuEle = (Element) nodeIt.next(); tuId = Long.parseLong(tuEle.attributeValue(Tmx.TUID)); break; } } ProjectTmTuT tu = HibernateUtil.get(ProjectTmTuT.class, tuId); if (tu == null) { throw new WebServiceException("Can not find tu with id :" + tuId); } ProjectTM ptm = tu.getProjectTm(); Company company = ServerProxy.getJobHandler().getCompanyById(ptm.getCompanyId()); return editTu(accessToken, ptm.getName(), company.getName(), tmx); } catch (Exception e) { throw new WebServiceException(e.getMessage()); } }