List of usage examples for org.dom4j.io SAXReader read
public Document read(InputSource in) throws DocumentException
Reads a Document from the given InputSource
using SAX
From source file:com.globalsight.webservices.Ambassador.java
License:Apache License
/** * Try to repair the segment.//from w w w. ja va 2s. c o m * <p> * Will throw out a WebServiceException if the format is wrong and can not * be repaired. * <p> * * @see SegmentHandler * @see #validateSegment(Element, IntHolder) * * @param s * The segment to be repaired * @return The repaired segment * @throws WebServiceException */ private String repairSegment(String s) throws WebServiceException { Assert.assertNotEmpty(s, "segment"); SAXReader reader = new SAXReader(); SegmentHandler segmentHandler = new SegmentHandler(s); reader.addHandler("/segment", segmentHandler); try { reader.read(new StringReader(s)); if (segmentHandler.hasError()) { throw new WebServiceException(segmentHandler.getError()); } return segmentHandler.getSegment(); } catch (DocumentException e) { logger.error(e.getMessage(), e); throw new WebServiceException(e.getMessage()); } }
From source file:com.globalsight.webservices.Ambassador.java
License:Apache License
/** * Updates a tu in database. Only work for TM2. * /* w w w . j a v a 2 s .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()); } }
From source file:com.globalsight.webservices.Ambassador.java
License:Apache License
/** * Updates a tu in database.// w ww . ja v a 2 s . c om * * @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 tmName * TM name, will used to get tm id. * @param companyName * company name, will used to get tm id. * @param tmx * A tmx formate string inlcluding all tu information. * @return "true" if succeed * @throws WebServiceException */ public String editTu(String accessToken, String tmName, String companyName, String tmx) throws WebServiceException { try { Assert.assertNotEmpty(accessToken, "access token"); Assert.assertNotEmpty(tmx, "tmx format"); } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebServiceException(e.getMessage()); } checkAccess(accessToken, "editEntry"); checkPermission(accessToken, Permission.TM_EDIT_ENTRY); Company company = getCompanyByName(companyName); if (company == null) { throw new WebServiceException("Can not find the company with name (" + companyName + ")"); } final ProjectTM ptm = getProjectTm(tmName, company.getIdAsLong()); if (ptm == null) { throw new WebServiceException( "Can not find the tm with tm name (" + tmName + ") and company name (" + companyName + ")"); } SAXReader reader = new SAXReader(); ElementHandler handler = new ElementHandler() { public void onStart(ElementPath path) { } public void onEnd(ElementPath path) { Element element = path.getCurrent(); element.detach(); try { normalizeTu(element); validateTu(element); if (ptm.getTm3Id() == null) { editTm2Tu(element); } else { editTm3Tu(element, ptm); } } catch (Throwable ex) { logger.error(ex.getMessage(), ex); throw new ThreadDeath(); } } }; reader.addHandler("/tu", handler); WebServicesLog.Start activityStart = null; try { String loggedUserName = this.getUsernameFromSession(accessToken); Map<Object, Object> activityArgs = new HashMap<Object, Object>(); activityArgs.put("loggedUserName", loggedUserName); activityStart = WebServicesLog.start(Ambassador.class, "editTu(accessToken,tmx)", activityArgs); reader.read(new StringReader(tmx)); } catch (DocumentException e) { logger.error(e.getMessage(), e); throw new WebServiceException(e.getMessage()); } finally { if (activityStart != null) { activityStart.end(); } } return "true"; }
From source file:com.google.gdt.handler.impl.ExcelxHandler.java
License:Open Source License
/** * // w w w.ja v a 2 s .co m * @param inputFile * @throws IOException * @throws InvalidFormatException */ @Override public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException { String outPutFile = getOuputFileName(inputFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile)); ZipEntry zipEntry; int wordCount = 0; int pBarUpdate = 0; while ((zipEntry = zis.getNextEntry()) != null) { if (zipEntry.getName().equals("xl/sharedStrings.xml")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER]; int len; while ((len = zis.read(buffer)) > 0) { baos.write(buffer, 0, len); } baos.flush(); InputStream clone = new ByteArrayInputStream(baos.toByteArray()); SAXReader saxReader = new SAXReader(); Document doc = null; Map<String, String> nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("xmlns", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); try { XPath xPath = new Dom4jXPath("//xmlns:t"); xPath.setNamespaceContext(new SimpleNamespaceContext(nameSpaceMap)); doc = saxReader.read(clone); List<Node> nodes = xPath.selectNodes(doc); wordCount = nodes.size(); pLevel.setValue(0); pLevel.setMaxValue(wordCount); pLevel.setStringPainted(true); pLevel.setTrFileName(outPutFile); pBarUpdate = 0; for (Node node : nodes) { pBarUpdate++; pLevel.setValue(pBarUpdate); if (isInterrupted) { zis.close(); zout.close(); new File(outPutFile).delete(); pLevel.setString("cancelled"); return; } String inputText = ""; try { inputText = node.getText(); String translatedTxt = inputText; translatedTxt = translator.translate(inputText); node.setText(translatedTxt); } catch (Exception e) { logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e); } } } catch (DocumentException e) { logger.log(Level.SEVERE, "cannot parse slide", e); } catch (JaxenException e) { e.printStackTrace(); } zout.putNextEntry(new ZipEntry(zipEntry.getName())); byte data[] = doc.asXML().getBytes("UTF8"); zout.write(data, 0, data.length); } else { zout.putNextEntry(new ZipEntry(zipEntry.getName())); int len; byte data[] = new byte[BUFFER]; while ((len = zis.read(data, 0, BUFFER)) != -1) { zout.write(data, 0, len); } } } zis.close(); zout.close(); pLevel.setValue(wordCount); pLevel.setString("done"); }
From source file:com.google.gdt.handler.impl.PowerpointxHandler.java
License:Open Source License
/** * //from w w w .ja v a2s .c om * @param inputFile * @param pLevel * @throws IOException * @throws InvalidFormatException */ @Override public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException { String outPutFile = getOuputFileName(inputFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile)); int slideCount = getSlideCount(inputFile); pLevel.setValue(0); pLevel.setMaxValue(slideCount); pLevel.setStringPainted(true); pLevel.setTrFileName(outPutFile); ZipEntry zipEntry; int pBarUpdate = 0; while ((zipEntry = zis.getNextEntry()) != null) { if (zipEntry.getName().contains("ppt/slides/slide")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER]; int len; while ((len = zis.read(buffer)) > 0) { baos.write(buffer, 0, len); } baos.flush(); InputStream clone = new ByteArrayInputStream(baos.toByteArray()); SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(clone); List<Node> nodes = doc.selectNodes("//a:t"); for (Node node : nodes) { if (isInterrupted) { zis.close(); zout.close(); new File(outPutFile).delete(); pLevel.setString("cancelled"); return; } String inputText = ""; try { inputText = node.getText(); if ((null == inputText) || (inputText.trim().equals(""))) continue; String translatedText = translator.translate(inputText); node.setText(translatedText); } catch (Exception e) { logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e); } } } catch (DocumentException e) { logger.log(Level.SEVERE, "cannot parse slide", e); } zout.putNextEntry(new ZipEntry(zipEntry.getName())); byte data[] = doc.asXML().getBytes("UTF8"); zout.write(data, 0, data.length); pBarUpdate++; pLevel.setValue(pBarUpdate); } else { zout.putNextEntry(new ZipEntry(zipEntry.getName())); int len; byte data[] = new byte[BUFFER]; while ((len = zis.read(data, 0, BUFFER)) != -1) { zout.write(data, 0, len); } } } zis.close(); zout.close(); pLevel.setValue(slideCount); pLevel.setString("done"); }
From source file:com.google.gdt.handler.impl.WordxHandler.java
License:Open Source License
/** * //from w w w. j a va 2s .c o m * @param inputFile * @param pLevel * @throws IOException * @throws InvalidFormatException */ @Override public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException { String outPutFile = getOuputFileName(inputFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile)); ZipEntry zipEntry; int wordCount = 0; int pBarUpdate = 0; while ((zipEntry = zis.getNextEntry()) != null) { if (zipEntry.getName().equals("word/document.xml")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER]; int len; while ((len = zis.read(buffer)) > 0) { baos.write(buffer, 0, len); } baos.flush(); InputStream clone = new ByteArrayInputStream(baos.toByteArray()); SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(clone); List<Node> nodes = doc.selectNodes("//w:t"); wordCount = nodes.size(); pLevel.setValue(0); pLevel.setMaxValue(wordCount); pLevel.setStringPainted(true); pLevel.setTrFileName(outPutFile); pBarUpdate = 0; for (Node node : nodes) { if (isInterrupted) { zis.close(); zout.close(); new File(outPutFile).delete(); pLevel.setString("cancelled"); return; } String inputText = ""; try { inputText = node.getText(); pBarUpdate++; pLevel.setValue(pBarUpdate); if ((null == inputText) || (inputText.trim().equals(""))) continue; String translatedText = translator.translate(inputText); node.setText(translatedText); } catch (Exception e) { logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e); } } } catch (DocumentException e) { logger.log(Level.SEVERE, "cannot parse slide", e); } zout.putNextEntry(new ZipEntry(zipEntry.getName())); byte data[] = doc.asXML().getBytes("UTF8"); zout.write(data, 0, data.length); } else { zout.putNextEntry(new ZipEntry(zipEntry.getName())); int len; byte data[] = new byte[BUFFER]; while ((len = zis.read(data, 0, BUFFER)) != -1) { zout.write(data, 0, len); } } } zis.close(); zout.close(); pLevel.setValue(wordCount); pLevel.setString("done"); }
From source file:com.google.gdt.util.HttpTranslator.java
License:Open Source License
/** * parse the response from google server and extracts the desired translated Text * @param response/*from w w w. j a va 2 s . c o m*/ * @return translatedText */ private String parseResponse(String response) { // System.out.println(response); String translatedText = ""; InputSource is = new InputSource(new StringReader(response)); SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(is); } catch (DocumentException e) { logger.log(Level.SEVERE, "Not able to parse response : " + response, e); return ""; } Element root = doc.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); translatedText += element.getText(); } return translatedText; }
From source file:com.google.jenkins.flakyTestHandler.junit.FlakySuiteResult.java
License:Open Source License
/** * Parses the JUnit XML file into {@link FlakySuiteResult}s. * This method returns a collection, as a single XML may have multiple <testsuite> * elements wrapped into the top-level <testsuites>. *//*from w w w . j a v a 2s .c o m*/ static List<FlakySuiteResult> parse(File xmlReport, boolean keepLongStdio) throws DocumentException, IOException, InterruptedException { List<FlakySuiteResult> r = new ArrayList<FlakySuiteResult>(); // parse into DOM SAXReader saxReader = new SAXReader(); ParserConfigurator.applyConfiguration(saxReader, new SuiteResultParserConfigurationContext(xmlReport)); Document result = saxReader.read(xmlReport); Element root = result.getRootElement(); parseSuite(xmlReport, keepLongStdio, r, root); return r; }
From source file:com.googlecode.starflow.engine.xml.Dom4jProcDefParser.java
License:Apache License
/** * ???/*from w w w .j a v a2 s.c o m*/ * * @param processDefine * @return */ public static ProcessDefine parserProcessInfo(ProcessDefine processDefine) { SAXReader reader = new SAXReader(); Document document = null; try { document = reader.read(new StringReader(processDefine.getProcessDefContent())); Element rootElement = document.getRootElement(); String _name = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_NAME); String _chname = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_CHNAME); String _version = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_VERSION); String _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_DESC); String _description = rootElement.selectSingleNode(_xpath).getText(); _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_LIMITTIME); String _limitTime = rootElement.selectSingleNode(_xpath).getText(); processDefine.setProcessDefName(_name); if (_chname != null) processDefine.setProcessCHName(_chname); else processDefine.setProcessCHName(_name); processDefine.setVersionSign(_version); processDefine.setDescription(_description); processDefine.setLimitTime(Long.parseLong(_limitTime)); } catch (Exception e) { throw new StarFlowParserException("???", e); } return processDefine; }
From source file:com.googlecode.starflow.engine.xml.Dom4jProcDefParser.java
License:Apache License
/** * ?ID??//from w ww . j a v a 2 s . c o m * * @param document * @param activityDefId * @return */ public static Element parserActivityInfo(String processDefContent, String activityDefId) { SAXReader reader = new SAXReader(); Document document = null; Element element = null; try { document = reader.read(new StringReader(processDefContent)); element = parserActivityInfo(document, activityDefId); } catch (Exception e) { throw new StarFlowParserException("???", e); } return element; }