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.glaf.wechat.sdk.WeixinExecutor.java
License:Apache License
private void parseInputStream() throws Exception { SAXReader xmlReader = new SAXReader(); Document doc = null;/*from w ww.jav a 2 s . com*/ try { doc = xmlReader.read(request.getInputStream()); } catch (DocumentException ex) { ex.printStackTrace(); doc = xmlReader.read(new ByteArrayInputStream(request.getParameter("xml").getBytes("UTF-8"))); } String uri = request.getRequestURI(); String id = uri.substring(uri.lastIndexOf("/") + 1); Long accountId = Long.parseLong(id); WxUser user = WxIdentityFactory.getUserByAccountId(accountId); Element root = doc.getRootElement(); logger.debug(root.asXML()); String type = root.elementText(IMessage.TAG_MSGTYPE); if (StringUtils.equalsIgnoreCase(type, MESSAGE_TEXT)) { message = new TextMessage(); messageHandler = new TextMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_EVENT)) { // do subscribe event message = new EventMessage(); messageHandler = new EventMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_IMAGE)) { message = new ImageMessage(); messageHandler = new ImageMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_LINK)) { message = new LinkMessage(); messageHandler = new LinkMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_LOCATION)) { message = new LocationMessage(); messageHandler = new LocationMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_VOICE)) { message = new VoiceMessage(); messageHandler = new VoiceMessageHandler(); } else if (StringUtils.equalsIgnoreCase(type, MESSAGE_VIDEO)) { message = new VideoMessage(); messageHandler = new VideoMessageHandler(); } message.setRoot(root); message.setAccountId(accountId); message.setCustomer(user.getActorId()); message.setContextPath(request.getContextPath()); message.setRequestParameters(RequestUtils.getParameterMap(request)); String serviceUrl = WechatUtils.getServiceUrl(request); message.setServiceUrl(serviceUrl); message.setRemoteIPAddr(RequestUtils.getIPAddress(request)); // do the default/common parse! messageHandler.parseMessage(message, root); }
From source file:com.glaf.wechat.util.MessageUtils.java
License:Apache License
/** * ???XML//from w w w .ja v a2 s . c o m * * @param request * @return * @throws Exception */ @SuppressWarnings("unchecked") public static Map<String, String> parseXml(HttpServletRequest request) { // ?HashMap Map<String, String> map = new java.util.concurrent.ConcurrentHashMap<String, String>(); // request?? InputStream inputStream = null; // ?? SAXReader reader = new SAXReader(); try { inputStream = request.getInputStream(); Document document = reader.read(inputStream); // xml Element root = document.getRootElement(); // ? List<Element> elementList = root.elements(); // ??? for (Element e : elementList) { map.put(e.getName(), e.getText()); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { try { // ? if (inputStream != null) { inputStream.close(); inputStream = null; } } catch (IOException ex) { } } return map; }
From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java
License:Apache License
public static Document getDocument(String xml) throws DocumentException { SAXReader reader = new SAXReader(); return reader.read(new InputSource(new StringReader(xml))); }
From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java
License:Apache License
private DetectionResult determineUploadFormat(File p_tmpFile, User p_user) throws Exception { DetectionResult rslt = new DetectionResult(); try {//from ww w . j a v a 2s. co m // First we assume the basics - that this is a text file upload FormatTwoEncodingSniffer conv = new FormatTwoEncodingSniffer(); FileInputStream is = new FileInputStream(p_tmpFile); InputStreamReader isr = conv.convertFileToUnicode(is); BufferedReader br = new BufferedReader(isr); String content = br.readLine(); RE rtfRe = new RE(RE_RTF1_FILE_SIGNATURE); RE txtRe = new RE(RE_OFFLINE_TEXT_FILE_SIGNATURE); if (rtfRe.match(content)) { RtfAPI api = new RtfAPI(); RtfDocument doc = api.parse(br); doc = api.optimize(doc); if (isParaViewOneWorkFile(doc)) { s_category.debug("Detected UPLOAD_TYPE_GS_PARAVIEW_1"); rslt.m_type = UPLOAD_TYPE_GS_PARAVIEW_1; rslt.m_rtfDoc = doc; rslt.m_reader = br; } else if (isRtfWrappedTextWorkFile(doc)) { s_category.debug("Detected UPLOAD_TYPE_GS_RTF_WRAPPED_UNICODE_TEXT"); rslt.m_type = UPLOAD_TYPE_GS_WRAPPED_UNICODE_TEXT; rslt.m_rtfDoc = doc; rslt.m_reader = br; } else { s_category.debug("Detected UPLOAD_TYPE_UNKNOWN"); rslt.m_type = UPLOAD_TYPE_UNKNOWN; rslt.m_rtfDoc = null; rslt.m_reader = null; } } else if (txtRe.match(content)) { s_category.debug("Detected UPLOAD_TYPE_GS_UNICODE_TEXT."); rslt.m_type = UPLOAD_TYPE_GS_UNICODE_TEXT; // RESET NOTE: We reset the reader by creating a new // one using the detected encoding. // The number of characters read by readLine() is // dependent on whether or not there are any carriage // returns in the file, so it is too risky. According // to the mark method, reset may fail. rslt.m_reader = new BufferedReader( new InputStreamReader(new FileInputStream(p_tmpFile), isr.getEncoding())); } else if (content.indexOf("<?xml") > -1) { content = br.readLine(); // read the second non-null line while (content == null || "".equals(content.trim())) { content = br.readLine(); } // Xliff file if (content.indexOf("<xliff") > -1) { if (content.contains("2.0")) { rslt.m_type = UPLOAD_TYPE_XLF20; } else { rslt.m_type = UPLOAD_TYPE_XLF; } } // TTX file else if (content.indexOf("<TRADOStag") > -1) { rslt.m_type = UPLOAD_TYPE_TTX; String ttxContent = ""; try { SAXReader reader = new SAXReader(); Document doc = reader.read(p_tmpFile); TTXParser parser = new TTXParser(); boolean isParsingTTXForGS = true; ttxContent = parser.parseToTxt(doc, isParsingTTXForGS); } catch (Exception de) { s_category.error("ttx parse error"); s_category.error(de.getMessage(), de); isXlfOrTtxException = true; throw de; } StringReader sr = new StringReader(ttxContent); rslt.m_reader = new BufferedReader(sr); } } else { // Now, we may have correctly detected unicode but it // lacks our signature. At this point we can only // assume this is a native **unextracted** unicode // text file. s_category.debug("Detected UPLOAD_TYPE_UNKNOWN_UNICODE_TEXT."); rslt.m_type = UPLOAD_TYPE_UNKNOWN_UNICODE_TEXT; // see the "RESET NOTE:" above rslt.m_reader = new BufferedReader( new InputStreamReader(new FileInputStream(p_tmpFile), isr.getEncoding())); } } catch (Exception ex) { boolean isExHandled = false; try { // If we received an exception while trying to convert // the file to unicode text above, we know the file is // not a standard offlineTextFile. So now lets try RTF. // Note: rtf is always ASCII. FileInputStream is = new FileInputStream(p_tmpFile); InputStreamReader isr = new InputStreamReader(is, "ASCII"); BufferedReader br = new BufferedReader(isr); // First - confirm we have some form of RTF String tmp = br.readLine(); RE matcher = new RE(RE_RTF1_FILE_SIGNATURE); if (matcher.match(tmp)) { isExHandled = true; // If we have RTF, parse it into an RTF object model. // see the "RESET NOTE:" above br = new BufferedReader(new InputStreamReader(new FileInputStream(p_tmpFile), "ASCII")); RtfAPI api = new RtfAPI(); RtfDocument doc = api.parse(br); doc = api.optimize(doc); if (isParaViewOneWorkFile(doc)) { s_category.debug("Detected UPLOAD_TYPE_GS_PARAVIEW_1"); rslt.m_type = UPLOAD_TYPE_GS_PARAVIEW_1; rslt.m_rtfDoc = doc; rslt.m_reader = br; } else if (isRtfWrappedTextWorkFile(doc)) { s_category.debug("Detected UPLOAD_TYPE_GS_RTF_WRAPPED_UNICODE_TEXT"); rslt.m_type = UPLOAD_TYPE_GS_WRAPPED_UNICODE_TEXT; rslt.m_rtfDoc = doc; rslt.m_reader = br; } else { s_category.debug("Detected UPLOAD_TYPE_UNKNOWN"); rslt.m_type = UPLOAD_TYPE_UNKNOWN; rslt.m_rtfDoc = null; rslt.m_reader = null; } } } catch (Exception ex2) { s_category.error("Failed to run the RTF detection process. " + "Retuning UPLOAD_TYPE_DETECTION_ERROR. The exception follows: \n" + ex2.toString()); rslt.m_type = UPLOAD_TYPE_DETECTION_ERROR; } if (isXlfOrTtxException) { throw ex; } if (!isExHandled) { // throw ex; s_category.debug("Detected UPLOAD_TYPE_UNKNOWN"); rslt.m_type = UPLOAD_TYPE_UNKNOWN; rslt.m_rtfDoc = null; rslt.m_reader = null; } } return rslt; }
From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java
License:Apache License
/** * Convert xliff elements to Pseudo//from www .j ava2 s. c o m * * @param file * : the file to offline upload. * @return * @throws Exception */ private String convertXlif2Pseudo(DetectionResult detect, File file, User p_user, String p_fileName) throws Exception { String errMsg = null; org.dom4j.Document doc = null; try { SAXReader reader = new SAXReader(); doc = reader.read(file); } catch (Exception e) { s_category.error(e.getMessage(), e); throw new AmbassadorDwUpException(AmbassadorDwUpExceptionConstants.INVALID_FILE_FORMAT, e); } // Get all jobIds from uploading file. If combined, there will be // multiple tasks/pages/jobs in one file. HashSet<Long> jobIds = getJobIdsFromDoc(doc); PtagErrorPageWriter errWriter = new PtagErrorPageWriter(); errWriter.setFileName(p_fileName); errWriter.setPageId(XliffFileUtil.getPageId(doc)); errWriter.setTaskId(XliffFileUtil.getTaskId(doc)); errWriter.setWorkflowId(XliffFileUtil.getWorkflowId(doc)); reWrapXliff(doc, jobIds); errMsg = convertNode2Pseudo(doc, XliffConstants.SOURCE, p_fileName, jobIds, errWriter); if (errMsg != null) return errMsg; errMsg = convertNode2Pseudo(doc, XliffConstants.TARGET, p_fileName, jobIds, errWriter); if (errMsg != null) return errMsg; Transaction tx = HibernateUtil.getTransaction(); try { addComment(doc, p_user, jobIds); HibernateUtil.commit(tx); } catch (Exception e) { HibernateUtil.rollback(tx); throw e; } try { XlfParser parser = new XlfParser(); String xlfContent = parser.parseToTxt(doc); StringReader sr = new StringReader(xlfContent); detect.m_reader = new BufferedReader(sr); } catch (Exception e) { s_category.error(e.getMessage(), e); throw e; } return errMsg; }
From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java
License:Apache License
public Document getDocument(Reader reader) throws DocumentException { SAXReader saxReader = new SAXReader(); Document document = (Document) saxReader.read(reader); return document; }
From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java
License:Apache License
public Document getDocument(File file) throws Exception { SAXReader saxReader = new SAXReader(); Document document = (Document) saxReader.read(file); return document; }
From source file:com.globalsight.everest.edit.offline.xliff.ListViewWorkXLIFFWriter.java
License:Apache License
private String repairForAltTrans(String segment, SAXReader reader) { try {/*from w w w . j a va2 s .co m*/ reader.read(new StringReader("<target>" + segment + "</target>")); } catch (DocumentException e) { return EditUtil.encodeXmlEntities(segment); } return segment; }
From source file:com.globalsight.everest.projecthandler.importer.XmlReader.java
License:Apache License
/** * Reads an XML file and checks its correctness by validating * against the TMX DTD. If there's any error in the file, an * exception is thrown.//from w w w .ja v a 2 s.c o m */ private void analyzeXml(String p_url) throws Exception { CATEGORY.debug("Analyzing document: " + p_url); SAXReader reader = new SAXReader(); // TODO: Read the DTD and validate. // See com.globalsight.everest.tm.util.DtdResolver; // reader.setEntityResolver(DtdResolver.getInstance()); // reader.setValidation(true); // enable element complete notifications to conserve memory //TODO reader.addHandler("/projectdata/data", new ElementHandler() { public void onStart(ElementPath path) { ++m_entryCount; } public void onEnd(ElementPath path) { Element element = path.getCurrent(); // prune the current element to reduce memory element.detach(); } }); Document document = reader.read(p_url); // all done }
From source file:com.globalsight.everest.projecthandler.importer.XmlReaderThread.java
License:Apache License
public void run() { try {/*from ww w .j a v a 2 s . c om*/ SAXReader reader = new SAXReader(); // TODO: Read the DTD and validate. // See com.globalsight.everest.tm.util.DtdResolver; // reader.setEntityResolver(DtdResolver.getInstance()); // reader.setValidation(true); reader.addHandler("/projectdata", new ElementHandler() { public void onStart(ElementPath path) { Element element = path.getCurrent(); } public void onEnd(ElementPath path) { } }); // enable pruning to call me back as each Element is complete reader.addHandler("/projectdata/data", new ElementHandler() { public void onStart(ElementPath path) { m_count++; } public void onEnd(ElementPath path) { Element element = path.getCurrent(); // prune the current element to reduce memory element.detach(); m_result = m_results.hireResult(); try { // TODO: Create data objects Object o = /*createObject*/(element); if (CATEGORY.isDebugEnabled()) { CATEGORY.debug(o); } m_result.setResultObject(o); } catch (Throwable ex) { m_result.setError(ex.toString()); CATEGORY.warn("Error in object " + m_count, ex); } boolean done = m_results.put(m_result); m_result = null; // Stop reading the file. if (done) { throw new ThreadDeath(); } } }); String url = m_options.getFileName(); Document document = reader.read(url); } catch (ThreadDeath ignore) { CATEGORY.info("ReaderThread: interrupted"); } catch (Throwable ignore) { // Should never happen, and I don't know how to handle // this case other than passing the exception in // m_results, which I won't do for now. CATEGORY.error("unexpected error", ignore); } finally { if (m_result != null) { m_results.fireResult(m_result); } m_results.producerDone(); m_results = null; CATEGORY.debug("ReaderThread: done."); } }