List of usage examples for org.dom4j Element elementText
String elementText(QName qname);
From source file:com.xuan.sdk.msg.InMsgParser.java
License:Apache License
/** * ?//from w w w . j ava 2s.c om * 1text ? * 2image ? * 3voice ? * 4video ? * 5location ??? * 6link ? * 7event */ private static InMsg doParse(String xml) throws DocumentException { Document doc = DocumentHelper.parseText(xml); Element root = doc.getRootElement(); String toUserName = root.elementText("ToUserName"); String fromUserName = root.elementText("FromUserName"); Integer createTime = Integer.parseInt(root.elementText("CreateTime")); String msgType = root.elementText("MsgType"); if ("text".equals(msgType)) return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType); if ("image".equals(msgType)) return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType); if ("voice".equals(msgType)) return parseInVoiceMsgAndInSpeechRecognitionResults(root, toUserName, fromUserName, createTime, msgType); if ("video".equals(msgType)) return parseInVideoMsg(root, toUserName, fromUserName, createTime, msgType); if ("location".equals(msgType)) return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType); if ("link".equals(msgType)) return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType); if ("event".equals(msgType)) return parseInEvent(root, toUserName, fromUserName, createTime, msgType); throw new RuntimeException( "? " + msgType + "??"); }
From source file:com.xuan.sdk.msg.InMsgParser.java
License:Apache License
private static InMsg parseInEvent(Element root, String toUserName, String fromUserName, Integer createTime, String msgType) {/*from w ww .j a v a2 s .co m*/ String event = root.elementText("Event"); String eventKey = root.elementText("EventKey"); // /??????????? if (("subscribe".equals(event) || "unsubscribe".equals(event)) && StrKit.isBlank(eventKey)) { InFollowEvent e = new InFollowEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); return e; } // ???? 1: ?? String ticket = root.elementText("Ticket"); if ("subscribe".equals(event) && StrKit.notBlank(eventKey) && eventKey.startsWith("qrscene_")) { InQrCodeEvent e = new InQrCodeEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setEventKey(eventKey); e.setTicket(ticket); return e; } // ???? 2: ? if ("SCAN".equals(event)) { InQrCodeEvent e = new InQrCodeEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setEventKey(eventKey); e.setTicket(ticket); return e; } // ?? if ("LOCATION".equals(event)) { InLocationEvent e = new InLocationEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setLatitude(root.elementText("Latitude")); e.setLongitude(root.elementText("Longitude")); e.setPrecision(root.elementText("Precision")); return e; } // ?? 1????? if ("CLICK".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setEventKey(eventKey); return e; } // ?? 2??? if ("VIEW".equals(event)) { InMenuEvent e = new InMenuEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setEventKey(eventKey); return e; } // ????? if ("TEMPLATESENDJOBFINISH".equals(event)) { InTemplateMsgEvent e = new InTemplateMsgEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setMsgId(root.elementText("MsgID")); e.setStatus(root.elementText("Status")); return e; } // ????? if ("MASSSENDJOBFINISH".equals(event)) { InMassEvent e = new InMassEvent(toUserName, fromUserName, createTime, msgType); e.setEvent(event); e.setMsgId(root.elementText("MsgID")); e.setStatus(root.elementText("Status")); e.setTotalCount(root.elementText("TotalCount")); e.setFilterCount(root.elementText("FilterCount")); e.setSentCount(root.elementText("SentCount")); e.setErrorCount(root.elementText("ErrorCount")); return e; } throw new RuntimeException( "" + event + "??"); }
From source file:com.yinghua.translation.rest.PhoneResourceRESTService.java
License:Apache License
/** * /*from ww w.j av a 2 s.c om*/ * * @param params * @return */ @POST @Path("/weixinNotify") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public String weixinNotify(String params) { String req = null; Document reqDoc = DocumentHelper.createDocument(); Element reqRoot = reqDoc.addElement("xml"); Element reqCode = reqRoot.addElement("return_code"); try { Document doc = DocumentHelper.parseText(params); Element root = doc.getRootElement(); Element returnCode = root.element("return_code"); if ("SUCCESS".equals(returnCode.getText())) { String orderNo = root.elementText("out_trade_no"); MemberOrder order = memberOrderBean.findByOrderNo(orderNo); if (order != null && "SUCCESS".equals(root.elementText("result_code"))) { if (order.getState() != OrderStatus.FINISHED) {//???? order.setState(OrderStatus.FINISHED); if (System.currentTimeMillis() >= order.getServiceTime().getTime()) { Account account = accountBean.findByMemberNo(order.getMemberNumber()); int addCall = order.getSurplusCallDuration() + account.getSurplusCallDuration(); account.setSurplusCallDuration(addCall); accountBean.updateAccount(account); order.setUseState(OrderUseStatus.USING); } memberOrderBean.updateOrder(order); System.out.println("orderNo:" + order.getOrderNo() + "|orderState:" + order.getState() + "|orderUseState:" + order.getUseState()); } } else { System.out.println("??"); } PayWeixinLog pwl = new PayWeixinLog(); pwl.setAppid(root.elementText("appid")); pwl.setMchId(root.elementText("mch_id")); if (root.element("device_info") != null) pwl.setDeviceInfo(root.elementText("device_info")); pwl.setNonceStr(root.elementText("nonce_str")); pwl.setSign(root.elementText("sign")); pwl.setResultCode(root.elementText("result_code")); if (root.element("err_code") != null) pwl.setErrCode(root.elementText("err_code")); if (root.element("err_code_des") != null) pwl.setErrCodeDes(root.elementText("err_code_des")); pwl.setOpenid(root.elementText("openid")); if (root.element("is_subscribe") != null) pwl.setIsSubscribe(root.elementText("is_subscribe")); pwl.setTradeType(root.elementText("trade_type")); pwl.setBankType(root.elementText("bank_type")); pwl.setTotalFee(Integer.parseInt(root.elementText("total_fee"))); if (root.element("fee_type") != null) pwl.setFeeType(root.elementText("fee_type")); if (root.element("cash_fee") != null) pwl.setCashFee(Integer.parseInt(root.elementText("cash_fee"))); if (root.element("cash_fee_type") != null) pwl.setCashFeeType(root.elementText("cash_fee_type")); pwl.setTransationId(root.elementText("transation_id")); pwl.setOutTradeNo(root.elementText("out_trade_no")); if (root.element("attach") != null) pwl.setAttach(root.elementText("attach")); pwl.setTimeEnd(root.elementText("time_end")); payWeixinLogBean.createPayWeixinLog(pwl); reqCode.setText("SUCCESS"); } else { reqCode.setText("FAIL"); Element returnMsg = root.element("return_msg"); returnMsg.setText(root.elementText("retrun_msg")); } } catch (Exception e) { e.printStackTrace(); reqCode.setText("FAIL"); Element reqMsg = reqRoot.addElement("return_msg"); reqMsg.setText(""); } req = reqDoc.asXML(); return req; }
From source file:com.zimbra.common.localconfig.LocalConfig.java
License:Open Source License
public LocalConfig(String file) throws DocumentException, ConfigException { mConfigFile = file;/* ww w. ja va2 s . c o m*/ if (mConfigFile == null) { mConfigFile = defaultConfigFile(); } File cf = new File(mConfigFile); if (cf.exists() && cf.canRead()) { try (FileInputStream fis = new FileInputStream(cf)) { Document document = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(fis); Element root = document.getRootElement(); if (!root.getName().equals(E_LOCALCONFIG)) throw new DocumentException("config file " + mConfigFile + " root tag is not " + E_LOCALCONFIG); for (Iterator<?> iter = root.elementIterator(E_KEY); iter.hasNext();) { Element ekey = (Element) iter.next(); String key = ekey.attributeValue(A_NAME); String value = ekey.elementText(E_VALUE); set(key, value); } } catch (IOException | XmlParseException e) { Logging.warn(String.format("Problem parsing local config file '%s'", cf), e); throw new DocumentException(String.format("Problem parsing local config file '%s'", cf)); } } else { Logging.warn("local config file `" + cf + "' is not readable"); } expandAll(); }
From source file:com.zrsf.push.xmpp.handler.IQAuthHandler.java
License:Open Source License
/** * Handles the received IQ packet./*from ww w. j a v a 2s .c o m*/ * * @param packet the packet * @return the response to send back * @throws UnauthorizedException if the user is not authorized */ public IQ handleIQ(IQ packet) throws UnauthorizedException { IQ reply = null; ClientSession session = sessionManager.getSession(packet.getFrom()); if (session == null) { log.error("Session not found for key " + packet.getFrom()); reply = IQ.createResultIQ(packet); reply.setChildElement(packet.getChildElement().createCopy()); reply.setError(PacketError.Condition.internal_server_error); return reply; } try { Element iq = packet.getElement(); Element query = iq.element("query"); Element queryResponse = probeResponse.createCopy(); if (IQ.Type.get == packet.getType()) { // get query String username = query.elementText("username"); if (username != null) { queryResponse.element("username").setText(username); } reply = IQ.createResultIQ(packet); reply.setChildElement(queryResponse); if (session.getStatus() != Session.STATUS_AUTHENTICATED) { reply.setTo((JID) null); } } else { // set query String resource = query.elementText("resource"); String username = query.elementText("username"); String password = query.elementText("password"); // Verify the resource if (resource != null) { try { resource = JID.resourceprep(resource); } catch (StringprepException e) { throw new UnauthorizedException("Invalid resource: " + resource, e); } } else { throw new IllegalArgumentException("Invalid resource (empty or null)."); } // Verify the username if (username == null || username.trim().length() == 0) { throw new UnauthorizedException("Invalid username (empty or null)."); } try { Stringprep.nodeprep(username); } catch (StringprepException e) { throw new UnauthorizedException("Invalid username: " + username, e); } username = username.toLowerCase(); // Verify that username and password are correct AuthToken token = null; if (password != null && AuthManager.isPlainSupported()) { token = AuthManager.authenticate(username, password); } if (token == null) { throw new UnauthenticatedException(); } // Set the session authenticated successfully session.setAuthToken(token, resource); packet.setFrom(session.getAddress()); log.info(session); reply = IQ.createResultIQ(packet); } } catch (Exception ex) { log.error(ex); reply = IQ.createResultIQ(packet); reply.setChildElement(packet.getChildElement().createCopy()); if (ex instanceof IllegalArgumentException) { reply.setError(PacketError.Condition.not_acceptable); } else if (ex instanceof UnauthorizedException) { reply.setError(PacketError.Condition.not_authorized); } else if (ex instanceof UnauthenticatedException) { reply.setError(PacketError.Condition.not_authorized); } else { reply.setError(PacketError.Condition.internal_server_error); } } // Send the response directly to the session if (reply != null) { session.process(reply); } return null; }
From source file:conviz.gr.server.ConvizResultTab.java
License:Apache License
@Override protected void fillModel(final @NotNull Map<String, Object> model, @NotNull HttpServletRequest request, @NotNull SBuild build) {/*from w ww . j av a2s . c o m*/ try { List<ResultVIewBean> diagrams = new ArrayList<ResultVIewBean>(); List<ResultVIewBean> reports = new ArrayList<ResultVIewBean>(); final List<BuildArtifact> reportArtifacts = new ArrayList<BuildArtifact>(); build.getArtifacts(BuildArtifactsViewMode.VIEW_ALL) .iterateArtifacts(new BuildArtifacts.BuildArtifactsProcessor() { @NotNull @Override public Continuation processBuildArtifact(@NotNull BuildArtifact artifact) { if (artifact.getName().matches(REPORT_FILE_PREFIX + ".*" + REPORT_FILE_SUFFIX)) { reportArtifacts.add(artifact); } return Continuation.CONTINUE; } }); for (BuildArtifact report : reportArtifacts) { String reportText = FileCopyUtils .copyToString(new BufferedReader(new InputStreamReader(report.getInputStream()))); Document doc = DocumentHelper.parseText(reportText); for (Element diagram : new ArrayList<Element>(doc.getRootElement().elements(REPORT_ELEMENT_IMG))) { diagrams.add(new ResultVIewBean(diagram.elementText(REPORT_EL_ID), diagram.elementText(REPORT_EL_FILE))); } for (Element customReport : new ArrayList<Element>( doc.getRootElement().elements(REPORT_ELEMENT_HTML))) { reports.add(new ResultVIewBean(customReport.elementText(REPORT_EL_ID), customReport.elementText(REPORT_EL_FILE))); } } model.put("diagrams", diagrams); model.put("reports", reports); } catch (Exception e) { LoggerFactory.getLogger(this.getClass()).error("ConViz failed to construct display tab view: ", e); model.put("conviz.view.error", true); model.put("conviz.error.text", e.toString()); } }
From source file:darks.orm.core.config.sqlmap.DMLConfigReader.java
License:Apache License
/** * Read and parse aspect XMLs file//from www . j a v a2s . c om * * @param element Aspect tags * @return Aspect data */ private AspectData parseAspectXml(Element element) { Element aspectEl = element.element("aspect"); if (aspectEl == null) return null; AspectData aspectData = new AspectData(); boolean isNext = false; Element jythonEl = aspectEl.element("jython"); if (jythonEl != null) { aspectData.setAspectType(AspectType.JYTHON); Attribute attr = jythonEl.attribute("className"); if (attr == null) return null; aspectData.setClassName(attr.getValue().trim()); String text = jythonEl.getText(); if (text == null || "".equals(text.trim())) { String before = jythonEl.elementText("before"); String after = jythonEl.elementText("after"); if (before == null || "".equals(before.trim())) { if (after == null || "".equals(after.trim())) return null; } text = PythonBuilder.buildBody(aspectData.getClassName(), before, after); } aspectData.setContent(text); isNext = true; } Element pyfileEl = aspectEl.element("pyfile"); if (pyfileEl != null && isNext == false) { aspectData.setAspectType(AspectType.PYFILE); Attribute attr = pyfileEl.attribute("className"); if (attr == null) return null; aspectData.setClassName(attr.getValue().trim()); aspectData.setContent(pyfileEl.getTextTrim()); isNext = true; } Element javaClassEl = aspectEl.element("javaClass"); if (javaClassEl != null && isNext == false) { aspectData.setAspectType(AspectType.JAVACLASS); aspectData.setClassName(javaClassEl.getTextTrim()); isNext = true; } Element jsEl = aspectEl.element("javascript"); if (jsEl != null && isNext == false) { aspectData.setAspectType(AspectType.JAVASCRIPT); aspectData.setContent(jsEl.getTextTrim()); isNext = true; } Element jsfileEl = aspectEl.element("jsfile"); if (jsfileEl != null && isNext == false) { aspectData.setAspectType(AspectType.JSFILE); aspectData.setContent(jsfileEl.getTextTrim()); isNext = true; } if (isNext) { return aspectData; } return null; }
From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java
License:Apache License
/** * Creates a Jenkins Job List if authorization is required * @return Jenkins Job List/* ww w . j a v a2 s. c om*/ */ @SuppressWarnings("unchecked") private List<JenkinsJob> getJobListByServerAuth(String urlJenkinsServer, String view, I18nHelper i18nHelper) throws MalformedURLException, DocumentException { List<JenkinsJob> jobList = new ArrayList<JenkinsJob>(); String jobListUrl = urlJenkinsServer + (StringUtils.isNotEmpty(view) ? "view/" + view : "") + "/api/xml?depth=1"; PostMethod post = new PostMethod(jobListUrl); post.setDoAuthentication(true); Document jobsDocument = null; try { client.executeMethod(post); jobsDocument = new SAXReader().read(post.getResponseBodyAsStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SSLException e) { if (e.getMessage().equals("Unrecognized SSL message, plaintext connection?")) { urlJenkinsServer = urlJenkinsServer.replaceFirst("s", ""); this.getJobListByServerAuth(urlJenkinsServer, view, i18nHelper); return jobList; } else { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { post.releaseConnection(); } // if jenkinsUrl is invalid if (jobsDocument == null) { return jobList; } // get all jobs from xml and add them to list for (Element job : (List<Element>) jobsDocument.getRootElement().elements("job")) { // create a new job and set all params from xml JenkinsJob hJob = new JenkinsJob(); String jobName = job.elementText("name"); hJob.setName(jobName); hJob.setUrl(job.elementText("url")); hJob.setBuildTrigger(hJob.getUrl() + "/build"); hJob.setColor(job.elementText("color")); hJob.setLastSuccBuild(createBuildAuth(urlJenkinsServer, jobName, BuildType.LAST_SUCCESS, i18nHelper)); hJob.setLastFailBuild(createBuildAuth(urlJenkinsServer, jobName, BuildType.LAST_FAIL, i18nHelper)); jobList.add(hJob); } return jobList; }
From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java
License:Apache License
/** * Creates a Jenkins Job List if no authorization is required * @return Jenkins Job List/* w w w .ja v a 2 s . co m*/ */ @SuppressWarnings("unchecked") private List<JenkinsJob> getJobListByServer(String urlJenkinsServer, String view, I18nHelper i18nHelper) throws MalformedURLException, DocumentException { List<JenkinsJob> jobList = new ArrayList<JenkinsJob>(); String jobListUrl = urlJenkinsServer + (StringUtils.isNotEmpty(view) ? "view/" + view : "") + "/api/xml?depth=1"; Document jobsDocument = new SAXReader().read(new URL(jobListUrl)); // get all jobs from xml and add them to list for (Element job : (List<Element>) jobsDocument.getRootElement().elements("job")) { // create a new job and set all params from xml JenkinsJob hJob = new JenkinsJob(); String jobName = job.elementText("name"); hJob.setName(jobName); hJob.setUrl(job.elementText("url")); hJob.setBuildTrigger(hJob.getUrl() + "/build"); hJob.setColor(job.elementText("color")); hJob.setLastSuccBuild(createBuild(urlJenkinsServer, jobName, BuildType.LAST_SUCCESS, i18nHelper)); hJob.setLastFailBuild(createBuild(urlJenkinsServer, jobName, BuildType.LAST_FAIL, i18nHelper)); jobList.add(hJob); } return jobList; }
From source file:de.codecentric.jira.jenkins.plugin.servlet.RecentBuildsServlet.java
License:Apache License
@SuppressWarnings("unchecked") private List<JenkinsBuild> readBuilds(Document buildRss, int maxBuilds, I18nHelper i18nHelper) { List<JenkinsBuild> builds = new ArrayList<JenkinsBuild>(); //if jenkinsUrl is invalid but authorization was provided if (buildRss == null) { return builds; }//from w w w. j a v a 2 s. co m SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z"); List<Element> elements = buildRss.getRootElement().elements("entry"); Iterator<Element> it = elements.iterator(); while (it.hasNext() && builds.size() < maxBuilds) { Element rssElement = it.next(); JenkinsBuild build = new JenkinsBuild(); build.setI18nHelper(i18nHelper); String title = rssElement.elementText("title"); build.setName(title); String url = rssElement.element("link").attributeValue("href"); build.setUrl(url); try { String publishedDate = rssElement.elementText("published"); build.setTimestamp(df.parse(publishedDate.substring(0, publishedDate.length() - 1) + " UTC")); } catch (ParseException e) { e.printStackTrace(); } build.setNumber(url.substring(url.lastIndexOf('/', url.length() - 2) + 1, url.length() - 1)); String buildResult = title.substring(title.lastIndexOf('(') + 1, title.lastIndexOf(')')); if (buildResult.equals("Wieder normal")) { buildResult = "Stabil"; } else if (buildResult.substring(0, 6).equals("Defekt")) { buildResult = "FAILURE"; } build.setResult(BuildResult.valueOf(buildResult)); builds.add(build); } return builds; }