/** Method calcFeedBack. */ private void calcFeedBack() { if (feedbacktesting) { List<?> el_ofts = el_assessment.selectNodes("outcomes_processing/outcomes_feedback_test"); feedbackavailable = false; for (Iterator<?> it_oft = el_ofts.iterator(); it_oft.hasNext(); ) { Element el_oft = (Element) it_oft.next(); // <!ELEMENT outcomes_feedback_test (test_variable , displayfeedback+)> Element el_testvar = (Element) el_oft.selectSingleNode("test_variable"); // must exist: dtd // <!ELEMENT test_variable (variable_test | and_test | or_test | // not_test)> Element el_varandornot = (Element) el_testvar.selectSingleNode("variable_test|and_test|or_test|not_test"); String elname = el_varandornot.getName(); ScoreBooleanEvaluable sbe = QTIHelper.getSectionBooleanEvaluableInstance(elname); float totalscore = getScore(); boolean fulfilled = sbe.eval(el_varandornot, totalscore); if (fulfilled) { // get feedback Element el_displayfeedback = (Element) el_oft.selectSingleNode("displayfeedback"); String linkRefId = el_displayfeedback.attributeValue("linkrefid"); // must exist (dtd) // ignore feedbacktype, since we section or assess feedback only // accepts material, no hints or solutions Element el_resolved = (Element) el_assessment.selectSingleNode(".//assessfeedback[@ident='" + linkRefId + "']"); getOutput().setEl_response(new AssessFeedback(el_resolved)); // give the whole assessmentfeedback to render feedbackavailable = true; } } } }
public static void main(String[] args) { try { Records records = new Records(); List<RecordBean> recordList = new ArrayList<RecordBean>(); SAXReader saxReader = new SAXReader(); Document document = saxReader.read("test.xml"); Element root = document.getRootElement(); List<Element> elements = root.selectNodes("//RECORD"); System.out.println(elements.size()); for (Element element : elements) { RecordBean recordBean = new RecordBean(); recordBean.setAuthor(element.elementText("FRatingNum")); recordBean.setImage(element.elementText("FDesc")); recordBean.setTitle(element.elementText("FTitle")); recordBean.setItemId(element.elementText("FItemId")); recordList.add(recordBean); } records.setRecords(recordList); JSONObject jsonObject = JSONObject.fromObject(records); System.out.println(jsonObject.toString()); } catch (DocumentException e) { e.printStackTrace(); } }
private void initSections(Element assessment, Switches sw) { sectionContexts = new ArrayList<SectionContext>(2); // <!ELEMENT sectionref (#PCDATA)> // <!ATTLIST sectionref %I_LinkRefId; > List<?> sections = assessment.selectNodes("section|sectionref"); for (Iterator<?> iter = sections.iterator(); iter.hasNext(); ) { Element el_section = (Element) iter.next(); // resolve sectionref into the correct sections if (el_section.getName().equals("sectionref")) { String linkRefId = el_section.attributeValue("linkrefid"); el_section = (Element) el_section.selectSingleNode("//section[@ident='" + linkRefId + "']"); if (el_section == null) { throw new RuntimeException( "sectionref with ref '" + linkRefId + "' could not be resolved"); } } SectionContext sc = new SectionContext(); sc.setUp(assessInstance, el_section, sw); sectionContexts.add(sc); } }
@SuppressWarnings("unchecked") private void storeDirectSubmissions(Handler loadHandler) { List<Element> directSubMissionElements = xmlMissionNode.selectNodes("./mission"); for (Element e : directSubMissionElements) { directSubMissions.add(Mission.create(e.attributeValue("id"), this, e, loadHandler)); } }
/** * 获取配置项列表 * * @param fileName 文件名 * @param path 路径 * @return 结果 */ public static List<Element> getElements(String fileName, String path) { Element root = getRoot(fileName); if (root == null) { return null; } return root.selectNodes(path); }
/** * TODO: Maybe we can move this into class {@link MissionActivity}. And do the same with a copy of * this method in {@link InteractiveMission}. * * @param ruleList * @param xpath */ @SuppressWarnings("unchecked") private void addRulesToList(List<Rule> ruleList, String xpath) { List<Element> xmlRuleNodes; xmlRuleNodes = xmlMissionNode.selectNodes(xpath); for (Element xmlRule : xmlRuleNodes) { ruleList.add(Rule.createFromXMLElement(xmlRule)); } }
public static java.util.ArrayList<Company> FromXml(Element elemCompanies) { java.util.ArrayList<Company> companies = new java.util.ArrayList<Company>(); for (Object objCmpyOn : elemCompanies.selectNodes("company")) { Element elemCmpyOn = (Element) objCmpyOn; companies.add(new Company(elemCmpyOn)); } return companies; }
/** 分析XML数据 */ protected void parseXmlData() { Element el = this.xmlDoc.getRootElement(); List attrList = el.selectNodes("./fields/field"); for (int i = 0; i < attrList.size(); i++) { Element e = (Element) attrList.get(i); this.attr.put(e.attributeValue("id"), e.getText()); } }
/** * @方法功能描述: 根据子节点名称得到指定的子节点 @方法名:getChildElement * * @param parent * @param childName @返回类型:Element */ @SuppressWarnings("unchecked") public static List<Element> getChildElements(Element parent, String childName) { childName = childName.trim(); if (parent == null) return null; childName += "//"; List<Element> childElements = parent.selectNodes(childName); return childElements; }
public NewsItem(String filePath) throws Exception { Document doc = XmlHelp.getDocument(filePath); Element root = doc.getRootElement(); Element data = (Element) root.selectSingleNode("//datas"); this.title = data.selectSingleNode(".//title").getStringValue(); this.keyword = data.selectSingleNode(".//keyword").getStringValue(); this.description = data.selectSingleNode(".//description").getStringValue(); this.author = data.selectSingleNode(".//author").getStringValue(); this.source = data.selectSingleNode(".//source").getStringValue(); this.published = data.selectSingleNode(".//published").getStringValue(); this.url = data.selectSingleNode(".//url").getStringValue(); this.summary = data.selectSingleNode(".//summary").getStringValue(); logger.info(title); List<Element> tags = data.selectNodes(".//tag"); for (Element element : tags) { // tagList.add(index, element); } this.relationList = data.selectNodes(".//relation"); }
/** * 处理待跳转的url * * @param request * @param response * @param filterChain * @throws IOException */ public static boolean doRedirectUrl( ServletRequest request, ServletResponse response, FilterChain filterChain, String pUrl) { try { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Element thisNode = null; for (Object nodeObj : RmLoadConfig.getRmClusterDoc() .selectNodes( "/rm/org.quickbundle.project.login.RmSsoLogin/redirectGroup[@enable='true']/redirectUrls/url")) { Element node = (Element) nodeObj; if (node.getText().equals(pUrl)) { thisNode = node; break; } } if (thisNode == null) { throw new RmRuntimeException("配置文件读取错误"); } String targetUrlPrefix = null; for (Object baseUrlObj : thisNode.selectNodes("../../redirectTargets/baseUrl")) { // TODO 可扩展为负载均衡算法 Element eleUrlPrefix = (Element) baseUrlObj; targetUrlPrefix = eleUrlPrefix.getText(); break; } if (targetUrlPrefix.length() == 0) { throw new RmRuntimeException("未配置跳转到的目标地址"); } // 带着sso信息跳转到目标服务器 if (RmClusterConfig.getLocalhostInfo() != null && targetUrlPrefix.startsWith(RmClusterConfig.getLocalhostInfo().getLocalhostUrlPath())) { // throw new RmRuntimeException("不能跳转到自身,可能导致循环跳转"); // 如果判断为跳到本机,忽略跳转 filterChain.doFilter(request, response); return true; } res.sendRedirect(rebuildUri(req, targetUrlPrefix)); return true; } catch (Exception e) { log.error("doRedirectUrl():" + e.toString() + " cause:" + e.getCause()); // save error request.setAttribute("org.apache.struts.action.EXCEPTION", e); return false; } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType(CONTENT_TYPE); SAXReader reader = new SAXReader(); PrintWriter out = response.getWriter(); StringBuffer responseString = new StringBuffer(); responseString.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><success>Bing Go!</success></root>"); try { Document doc = reader.read(request.getInputStream()); List telephoneInfoList = doc.selectNodes("//telephoneInfo"); List telephoneNumberList; VisitingCardService visitingCardService = new VisitingCardService(); TelephoneNumberService telephoneNumberService = new TelephoneNumberService(); String visitingCardId = null, telephoneNumberId = null; VisitingCard visitingCard; TelephoneNumber telephoneNumber; for (Object object : telephoneInfoList) { Element e = (Element) object; // System.out.println(e.elementText("name")); visitingCard = new VisitingCard(); visitingCardId = "visitingCard" + Long.toString(System.currentTimeMillis()); visitingCard.setId(visitingCardId); visitingCard.setName(e.elementText("name")); visitingCardService.saveVisitingCard(visitingCard); telephoneNumberList = e.selectNodes("telephoneNumbers/telephoneNumber"); for (Object obj : telephoneNumberList) { Element telephoneNumberNode = (Element) obj; // System.out.println(telephoneNumberNode.getText()); telephoneNumberId = "telephoneNumber" + Long.toString(System.currentTimeMillis()); telephoneNumber = new TelephoneNumber(); telephoneNumber.setId(telephoneNumberId); telephoneNumber.setVisitCardId(visitingCardId); telephoneNumber.setTelephoneNumber(telephoneNumberNode.getText()); telephoneNumberService.saveTelephoneNumber(telephoneNumber); } } } catch (DocumentException e) { e.printStackTrace(); } out.write(responseString.toString()); out.close(); }
@Override public void importSite(String configLocation) { Document document = loadConfiguration(configLocation); if (document != null) { Element root = document.getRootElement(); List<Node> siteNodes = root.selectNodes("site"); if (siteNodes != null) { for (Node siteNode : siteNodes) { String name = siteNode.valueOf("name"); String buildDataLocation = siteNode.valueOf("build-data-location"); String publishingChannelGroup = siteNode.valueOf("publish-channel-group"); String publishStr = siteNode.valueOf("publish"); boolean publish = (!StringUtils.isEmpty(publishStr) && publishStr.equalsIgnoreCase("true")); String publishSize = siteNode.valueOf("publish-chunk-size"); int chunkSize = (!StringUtils.isEmpty(publishSize) && StringUtils.isNumeric(publishSize)) ? Integer.valueOf(publishSize) : -1; Node foldersNode = siteNode.selectSingleNode("folders"); String sourceLocation = buildDataLocation + "/" + name; String delayIntervalStr = siteNode.valueOf("delay-interval"); int delayInterval = (!StringUtils.isEmpty(delayIntervalStr) && StringUtils.isNumeric(delayIntervalStr)) ? Integer.valueOf(delayIntervalStr) : -1; String delayLengthStr = siteNode.valueOf("delay-length"); int delayLength = (!StringUtils.isEmpty(delayLengthStr) && StringUtils.isNumeric(delayLengthStr)) ? Integer.valueOf(delayLengthStr) : -1; importFromConfigNode( name, publishingChannelGroup, foldersNode, sourceLocation, "/", publish, chunkSize, delayInterval, delayLength); } } } }
/** * 解析自助设备请求XML * * @param requestXML * @return */ private static Map<String, String> explainDeviceRequestXml(String requestXML) throws Exception { Map<String, String> resultMap = new HashMap<String, String>(); try { Document docs = DocumentHelper.parseText(requestXML); Element root = docs.getRootElement(); List<Element> data_eles = root.selectNodes("/Root/Data"); for (Element head : data_eles) { List<Element> headInfos = head.elements(); for (Element element : headInfos) { resultMap.put(element.getName(), element.getText()); } } } catch (Exception e) { e.printStackTrace(); throw new BusinessException("解析请求2015009请求XML异常"); } return resultMap; }
/** * 获取历史记录信息 * * @param id 相关字段,为空获取所有字段的历史记录 * @return 返回历史记录信息 List<HistoryLine> */ public List getHistoryLines(String id) { List list = new ArrayList(); Element el = (Element) this.xmlDoc.getRootElement().selectSingleNode("./historys"); if (el == null) return list; List els = el.selectNodes("./history"); for (int i = 0; i < els.size(); i++) { Element el2 = (Element) els.get(i); if (id != null && !id.equals(el2.attributeValue("id"))) continue; HistoryLine line = new HistoryLine(); line.setDate(el2.attributeValue("operDate")); line.setId(el2.attributeValue("id")); line.setNewValue(el2.attributeValue("newVal")); line.setOldValue(el2.attributeValue("oldVal")); line.setOperName(el2.attributeValue("operName")); list.add(line); } return list; }
private static Map<String, Element> parseDrawXml(Set transitionSet, Element rootEl) { Map map = new LinkedHashMap(); List<Element> figures = rootEl.selectNodes("/drawing/figures/*"); for (Element el : figures) { String id = el.attributeValue("id"); String ref = el.attributeValue("ref"); if ("transition".equals(el.getQualifiedName())) { transitionSet.add(el); } else if (id != null) { map.put(id, el); } else if (ref != null) { Node figureNode = rootEl.selectSingleNode("/drawing/figures//*[@id='" + ref + "']"); map.put(ref, figureNode); } } return map; }
protected Object resolveXP(Element el, String xpr) { List<Object> nodes = el.selectNodes(xpr); if (nodes.size() == 1) { return nodes.get(0); } else if (nodes.size() > 1) { // Workaround for NXP-11834 if (xpr.endsWith("text()")) { String value = ""; for (Object node : nodes) { if (!(node instanceof DefaultText)) { String msg = "Text selector must return a string (expr:\"%s\") element %s"; log.error(String.format(msg, xpr, el.getStringValue())); return value; } value += ((DefaultText) node).getText(); } return new DefaultText(value); } return nodes; } return null; }
public static Map<String, String> getDecisionConditions( String processXml, String decisionNodeId) { Map<String, String> map = new HashMap<String, String>(); processXml = processXml.replace( "xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"", "xmlns:bpm='hotent'"); Document doc = Dom4jUtil.loadXml(processXml); Element root = doc.getRootElement(); List<Element> nodes = root.selectNodes("//sequenceFlow[@sourceRef='" + decisionNodeId + "']"); for (Element el : nodes) { String id = el.attributeValue("targetRef"); String condition = ""; Element conditionNode = el.element("conditionExpression"); if (conditionNode != null) { condition = conditionNode.getText().trim(); condition = StringUtils.trimPrefix(condition, "${"); condition = StringUtils.trimSufffix(condition, "}"); } map.put(id, condition); } return map; }
@SuppressWarnings("unchecked") private void initFields() { configs.clear(); for (Element elmConfig : (List<Element>) doc.selectNodes("/StoreDevicesConfig/*")) { Map<String, Device> devices = new HashMap<String, Device>(); for (Element elmDevice : (List<Element>) elmConfig.selectNodes("StoreDevice")) { devices.put( elmDevice.elementText("DeviceName"), new Device( elmDevice.elementText("DeviceName"), StringUtils.toBoolean(elmDevice.elementText("UserDefined")), elmDevice.elementText("Protocol"), elmDevice.elementText("URL"))); } Config defaultConfig = elmConfig.getName().equalsIgnoreCase("DefaultConfig") ? new Config(devices) : new Config(elmConfig.attributeValue("platform"), devices); configs.put(defaultConfig.getPlatform(), defaultConfig); } }
/** * @Title: parseSqlXML @Description: 使用DOM4J解析xml文件 * * @param root xml 根节点 * @param _node xml节点 * @return String */ @SuppressWarnings("rawtypes") public static Element parseSqlXML(Element root, String _node) { if ((null != _node && !"".equals(_node))) { try { // 从当前节点的子节点中选择名称为_node的节点 List rootList = root.selectNodes(_node); // xml元素 Element element = null; // 循环此节点,并取出对应的文本信息 for (Object obj : rootList) { element = (Element) obj; } return element; } catch (Exception e) { e.getStackTrace(); } } return null; }
/** Parse Node /apps/app */ @SuppressWarnings("unchecked") private boolean parseAppNode(AppConfig config, Element appElm, int index) throws Exception { if (null == appElm) { return false; } // String version = null == versionOnZones ? "1.0" : versionOnZones; // Attribute versonAttr = (Attribute) // appNode.selectSingleNode("@version"); // if (null != versonAttr) { // version = versonAttr.getStringValue(); // } assert config != null; try { String name = XMLHelper.getTextTrim(appElm, "name"); String displayName = XMLHelper.getTextTrim(appElm, "display-name", Strings.EMPTY_STRING); String logo = XMLHelper.getTextTrim(appElm, "logo", Strings.EMPTY_STRING); String version = XMLHelper.getTextTrim(appElm, "version", Strings.EMPTY_STRING); String desc = XMLHelper.getTextTrim(appElm, "description", Strings.EMPTY_STRING); String authorInfo = XMLHelper.getTextTrim(appElm, "author-info"); Date createTime = DateUtil.safeParseDate(XMLHelper.getTextTrim(appElm, "create-time"), DateUtil.ssdf); config.setName(name); config.setDisplayName(displayName); config.setLogo(logo); config.setVersion(version); config.setDesc(desc); config.setAuthorInfo(authorInfo); config.setCreateTime(createTime); String configVersion = XMLHelper.getAttributeString(appElm, "@version", "1.0"); String type = XMLHelper.getAttributeString(appElm, "@type"); String buildInAppName = XMLHelper.getTextTrim(appElm, "buildin-app-name"); Short shortType = AppConstants.DISPLAY_APP_TYPE.inverse().get(type); if (null == type) { throw new AppException("Type invalid for " + name); } config.setType(null == shortType ? AppConstants.APPTYEP_EMPTY : shortType); config.setBuildInAppName(buildInAppName); List<Element> zones = (List<Element>) appElm.selectNodes("zones/zone"); if (null != zones) { for (Element zone : zones) { String zoneType = XMLHelper.getAttributeString(zone, "@type", type); if (null == zoneType) { continue; } AppZone appZone = new AppZone(); Short zoneTypeCode = AppConstants.DISPLAY_APP_TYPE.inverse().get(zoneType); appZone.setAppType(zoneTypeCode); appZone.setSize(XMLHelper.getAttributeString(zone, "@zoneSize")); appZone.setHeight(XMLHelper.getTextTrim(zone, "height")); appZone.setWidth(XMLHelper.getTextTrim(zone, "width")); // for buildin app if (AppConstants.APPTYPE_BUILDIN == zoneTypeCode) { appZone.setBuildinAppName( XMLHelper.getTextTrim(zone, "buildin-app-name", buildInAppName)); } else if (AppConstants.APPTYPE_IFRAME == zoneTypeCode) { appZone.setBuildinAppName(IFramePortlet.class.getSimpleName()); appZone.setPathTemplate(XMLHelper.getTextTrim(zone, "path")); } else if (AppConstants.APPTYPE_URL == zoneTypeCode) { appZone.setBuildinAppName(URLPortlet.class.getSimpleName()); appZone.setPathTemplate(XMLHelper.getTextTrim(zone, "path")); } else if (AppConstants.APPTYEP_EMPTY == zoneTypeCode) { // appZone.setBuildinAppName(URLPortlet.class.getSimpleName()); // appZone.setPathTemplate(XMLHelper.getTextTrim(zone, // "path")); } config.addPage(appZone); } } String status = XMLHelper.getTextTrim(appElm, "status"); if ("disabled".equalsIgnoreCase(status)) { config.setStatus(AppConstants.STATUS_DISABLED); } else if ("platform".equalsIgnoreCase(status)) { config.setStatus(AppConstants.STATUS_PENDING); } else { config.setStatus(AppConstants.STATUS_PENDING); } } catch (Exception e) { e.printStackTrace(); config.setStatus(AppConstants.STATUS_CONFIG_ERROR); config.setStatusString( String.format( "Parse Config Error, Exception: [%s:%s] found for: %s", e.getClass().getSimpleName(), e.getMessage(), appElm.asXML())); } return true; }
public static ShapeMeta transGraph(String xml) throws Exception { xml = xml.replace("xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"", ""); Document doc = Dom4jUtil.loadXml(xml); Element root = doc.getRootElement(); List list = root.selectNodes("//bpmndi:BPMNShape"); int minx = 100000; int miny = 100000; int maxw = 0; int maxh = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size(); i++) { Element el = (Element) list.get(i); Element tmp = (Element) el.selectSingleNode("omgdc:Bounds"); int x = (int) Float.parseFloat(tmp.attributeValue("x")); int y = (int) Float.parseFloat(tmp.attributeValue("y")); int w = x + (int) Float.parseFloat(tmp.attributeValue("width")); int h = y + (int) Float.parseFloat(tmp.attributeValue("height")); minx = Math.min(x, minx); miny = Math.min(y, miny); maxw = Math.max(w, maxw); maxh = Math.max(h, maxh); } List pointList = root.selectNodes("//omgdi:waypoint"); for (int i = 0; i < pointList.size(); i++) { Element tmp = (Element) pointList.get(i); int x = (int) Float.parseFloat(tmp.attributeValue("x")); int y = (int) Float.parseFloat(tmp.attributeValue("y")); minx = Math.min(x, minx); miny = Math.min(y, miny); } for (int i = 0; i < list.size(); i++) { Element el = (Element) list.get(i); Element tmp = (Element) el.selectSingleNode("omgdc:Bounds"); int x = (int) Float.parseFloat(tmp.attributeValue("x")); int y = (int) Float.parseFloat(tmp.attributeValue("y")); int w = (int) Float.parseFloat(tmp.attributeValue("width")); int h = (int) Float.parseFloat(tmp.attributeValue("height")); x = x - minx + 5; y = y - miny + 5; String id = el.attributeValue("bpmnElement"); Element procEl = (Element) root.selectSingleNode("//process/descendant::*[@id='" + id + "']"); String type = procEl.getName(); if (type.equals("serviceTask")) { String attribute = procEl.attributeValue("class"); if (attribute != null) { if (attribute.equals("com.hotent.platform.service.bpm.MessageTask")) { type = "email"; } else if (attribute.equals("com.hotent.platform.service.bpm.ScriptTask")) { type = "script"; } } } Element multiObj = procEl.element("multiInstanceLoopCharacteristics"); if (multiObj != null) type = "multiUserTask"; Element parent = procEl.getParent(); String name = procEl.attributeValue("name"); int zIndex = 10; String parentName = parent.getName(); if (parentName.equals("subProcess")) { zIndex = 11; } DivShape shape = new DivShape(name, x, y, w, h, zIndex, id, type); sb.append(shape); } ShapeMeta shapeMeta = new ShapeMeta(maxw, maxh, sb.toString()); return shapeMeta; }
private void processTarget(Element targetNode, Element outProjectNode) throws IOException, DocumentException { String targetName = targetNode.attributeValue("name"); log("Processing target: " + targetName, Project.MSG_DEBUG); // Add documentation // Get comment element before the target element to extract target doc String commentText = ""; List children = targetNode.selectNodes("preceding-sibling::node()"); if (children.size() > 0) { // Scan past the text nodes, which are most likely whitespace int index = children.size() - 1; Node child = (Node) children.get(index); while (index > 0 && child.getNodeType() == Node.TEXT_NODE) { index--; child = (Node) children.get(index); } // Check if there is a comment node if (child.getNodeType() == Node.COMMENT_NODE) { Comment targetComment = (Comment) child; commentText = targetComment.getStringValue().trim(); log(targetName + " comment: " + commentText, Project.MSG_DEBUG); } else { log("Target has no comment: " + targetName, Project.MSG_WARN); } Node previousNode = (Node) children.get(children.size() - 1); } if (!commentText.contains("Private:")) { Element outTargetNode = outProjectNode.addElement("target"); addTextElement(outTargetNode, "name", targetNode.attributeValue("name")); addTextElement(outTargetNode, "ifDependency", targetNode.attributeValue("if")); addTextElement(outTargetNode, "unlessDependency", targetNode.attributeValue("unless")); addTextElement(outTargetNode, "description", targetNode.attributeValue("description")); addTextElement(outTargetNode, "tasks", String.valueOf(targetNode.elements().size())); // Add location Project project = getProject(); Target antTarget = (Target) project.getTargets().get(targetName); if (antTarget == null) return; addTextElement(outTargetNode, "location", antTarget.getLocation().toString()); // Add dependencies Enumeration dependencies = antTarget.getDependencies(); while (dependencies.hasMoreElements()) { String dependency = (String) dependencies.nextElement(); Element dependencyElement = addTextElement(outTargetNode, "dependency", dependency); dependencyElement.addAttribute("type", "direct"); } callAntTargetVisitor(targetNode, outTargetNode, outProjectNode); // Process the comment text as MediaWiki syntax and convert to HTML insertDocumentation(outTargetNode, commentText); // Get names of all properties used in this target ArrayList properties = new ArrayList(); Visitor visitor = new AntPropertyVisitor(properties); targetNode.accept(visitor); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { String property = (String) iterator.next(); addTextElement(outTargetNode, "propertyDependency", property); } // Add the raw XML content of the element String targetXml = targetNode.asXML(); // Replace the CDATA end notation to avoid nested CDATA sections targetXml = targetXml.replace("]]>", "] ]>"); addTextElement(outTargetNode, "source", targetXml, true); } }
private void processMacro(Element macroNode, Element outProjectNode, String antFile) throws IOException, DocumentException { String macroName = macroNode.attributeValue("name"); log("Processing macro: " + macroName, Project.MSG_DEBUG); Element outmacroNode = outProjectNode.addElement("macro"); addTextElement(outmacroNode, "name", macroNode.attributeValue("name")); addTextElement(outmacroNode, "description", macroNode.attributeValue("description")); // Add location // Project project = getProject(); // Macro antmacro = (Macro) project.getTargets().get(macroName); // System.out.println(project.getMacroDefinitions()); // System.out.println(macroName); // MacroInstance antmacro = (MacroInstance) // project.getMacroDefinitions().get("http://www.nokia.com/helium:" + // macroName); // Add the location with just the file path for now and a dummy line // number. // TODO - Later we should find the line number from the XML input. addTextElement(outmacroNode, "location", antFile + ":1:"); List<Node> statements = macroNode.selectNodes( "//scriptdef[@name='" + macroName + "']/attribute | //macrodef[@name='" + macroName + "']/attribute"); String usage = ""; for (Node statement : statements) { String defaultval = statement.valueOf("@default"); if (defaultval.equals("")) defaultval = "value"; else defaultval = "<i>" + defaultval + "</i>"; usage = usage + " " + statement.valueOf("@name") + "=\"" + defaultval + "\""; } String macroElements = ""; statements = macroNode.selectNodes( "//scriptdef[@name='" + macroName + "']/element | //macrodef[@name='" + macroName + "']/element"); for (Node statement : statements) { macroElements = "<" + statement.valueOf("@name") + "/>\n" + macroElements; } if (macroElements.equals("")) addTextElement(outmacroNode, "usage", "<hlm:" + macroName + " " + usage + "/>"); else addTextElement( outmacroNode, "usage", "<hlm:" + macroName + " " + usage + ">\n" + macroElements + "</hlm:" + macroName + ">"); // Add dependencies // Enumeration dependencies = antmacro.getDependencies(); // while (dependencies.hasMoreElements()) // { // String dependency = (String) dependencies.nextElement(); // Element dependencyElement = addTextElement(outmacroNode, // "dependency", dependency); // dependencyElement.addAttribute("type","direct"); // } callAntTargetVisitor(macroNode, outmacroNode, outProjectNode); // Add documentation // Get comment element before the macro element to extract macro doc List children = macroNode.selectNodes("preceding-sibling::node()"); if (children.size() > 0) { // Scan past the text nodes, which are most likely whitespace int index = children.size() - 1; Node child = (Node) children.get(index); while (index > 0 && child.getNodeType() == Node.TEXT_NODE) { index--; child = (Node) children.get(index); } // Check if there is a comment node String commentText = null; if (child.getNodeType() == Node.COMMENT_NODE) { Comment macroComment = (Comment) child; commentText = macroComment.getStringValue().trim(); log(macroName + " comment: " + commentText, Project.MSG_DEBUG); } else { log("Macro has no comment: " + macroName, Project.MSG_WARN); } insertDocumentation(outmacroNode, commentText); Node previousNode = (Node) children.get(children.size() - 1); } // Get names of all properties used in this macro ArrayList properties = new ArrayList(); Visitor visitor = new AntPropertyVisitor(properties); macroNode.accept(visitor); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { String property = (String) iterator.next(); addTextElement(outmacroNode, "propertyDependency", property); } }
private void addEntity( String pkg, Element entityElement, Object parentEntity, String callString) { try { // 根据包名和类名,得到全路径类名 String clz = pkg + "." + entityElement.attributeValue("class"); // 根据全路径类名,创建实体对象 Object entity = Class.forName(clz).newInstance(); // 给entity对象赋值 // 即提取出当前Element中的所有属性,并用反射机制给entity对象赋值 Iterator iterator = entityElement.attributeIterator(); while (iterator.hasNext()) { Attribute attribute = (Attribute) iterator.next(); String propertyName = attribute.getName(); if (!propertyName.equals("class") && !propertyName.equals("call") && !propertyName.equals("parentName")) { String propertyValue = attribute.getValue(); // 给entity相应的属性赋值,这里使用的是apache-commons-beanutils工具包,所以需要加入这个依赖包 BeanUtils.copyProperty(entity, propertyName, propertyValue); } } /** * 提取出当前Element下面所有的非entity元素,这些元素也当作是本Entity属性的一部分 举个例子: <entity class="Form" name="请假单" * content="这里是请假单的内容" ...></entity> 像上面这样定义当然是可以的,但是有些属性的值可能会包含特殊字符,或者内容比较庞大,所以,可能 * 像下面这样来定义更加合理,如: <entity class="Form" name="请假单" ...> <content> <![CDATA[ * * <p>这是一个请假单 请假者姓名:<input type="text" name="leaverName" > .... ]]> </content> </entity> * 这样,比较复杂的文本属性,也可以定义 */ // 查找本元素下所有名称不是entity的元素 List subPropertyElements = entityElement.selectNodes("*[name()!='entity']"); if (subPropertyElements != null && !subPropertyElements.isEmpty()) for (Iterator iterator2 = subPropertyElements.iterator(); iterator2.hasNext(); ) { Element e = (Element) iterator2.next(); String propertyName = e.getName(); String propertyValue = e.getText(); BeanUtils.copyProperty(entity, propertyName, propertyValue); } // 判断parentEntity是否为空,如果不是空,则给parent对象赋值 if (parentEntity != null) { String parentName = entityElement.attributeValue("parentName"); if (parentName == null) { // 如果不配置父属性的名称,默认为parent parentName = "parent"; } parentName = StringUtils.capitalize(parentName); // 首字母变成大写 String setParentName = "set" + parentName; Method[] ms = entity.getClass().getMethods(); for (Method m : ms) { if (m.getName().equals(setParentName)) { m.invoke(entity, parentEntity); } } } // 要调用哪个服务对象的哪个方法 String call = entityElement.attributeValue("call"); if (call != null) { callString = call; } if (callString == null) { throw new RuntimeException("没有找到call属性,无法获知要调用哪个服务对象的哪个方法!请配置call属性!"); } // 得到服务对象的ID String serviceId = callString.substring(0, callString.indexOf(".")); // 得到要调用的方法名称 String methodName = callString.substring(callString.indexOf(".") + 1); // 通过BeanFactory得到服务对象 Object service = factory.getBean(serviceId); // 得到service对象的所有方法 Method[] ms = service.getClass().getMethods(); for (Method m : ms) { if (m.getName().equals(methodName)) { // 调用其中我们想要调用的方法 m.invoke(service, entity); } } // 判断当前entity下面是否还有其他的entity元素 List subEntityElements = entityElement.elements("entity"); for (Iterator iterator2 = subEntityElements.iterator(); iterator2.hasNext(); ) { Element e = (Element) iterator2.next(); // 递归插入本entity元素下面的其它entity对象 addEntity(pkg, e, entity, callString); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
/** * Method setUp. * * @param assessInstance */ public void setUp(AssessmentInstance assessInstance) { this.assessInstance = assessInstance; init(); Document el_questestinterop = assessInstance.getResolver().getQTIDocument(); el_assessment = (Element) el_questestinterop.selectSingleNode("questestinterop/assessment"); ident = el_assessment.attributeValue("ident"); title = el_assessment.attributeValue("title"); Element dur = (Element) el_assessment.selectSingleNode("duration"); if (dur == null) { durationLimit = -1; // no limit } else { String sdur = dur.getText(); durationLimit = QTIHelper.parseISODuration(sdur); if (durationLimit == 0) durationLimit = -1; // Assesst Designer fix } // get objectives Element el_objectives = (Element) el_assessment.selectSingleNode("objectives"); if (el_objectives != null) objectives = new Objectives(el_objectives); // set feedback, hint, and solutions switches // <!ENTITY % I_FeedbackSwitch " feedbackswitch (Yes | No ) 'Yes'"> // <!ENTITY % I_HintSwitch " hintswitch (Yes | No ) 'Yes'"> // <!ENTITY % I_SolutionSwitch " solutionswitch (Yes | No ) 'Yes'"> // <!ELEMENT assessment (qticomment? , duration? , qtimetadata* , // objectives* , assessmentcontrol* , rubric* , presentation_material? , // outcomes_processing* , assessproc_extension? , assessfeedback* , // selection_ordering? , reference? , (sectionref | section)+)> // <!ELEMENT assessmentcontrol (qticomment?)> Element el_control = (Element) el_assessment.selectSingleNode("assessmentcontrol"); if (el_control != null) { String feedbackswitch = el_control.attributeValue("feedbackswitch"); String hintswitch = el_control.attributeValue("hintswitch"); String solutionswitch = el_control.attributeValue("solutionswitch"); boolean feedback = (feedbackswitch == null) ? true : feedbackswitch.equals("Yes"); boolean hints = (hintswitch == null) ? true : hintswitch.equals("Yes"); boolean solutions = (solutionswitch == null) ? true : solutionswitch.equals("Yes"); switches = new Switches(feedback, hints, solutions); } // scoring model and outcomes processing Element el_outpro = (Element) el_assessment.selectSingleNode("outcomes_processing"); if (el_outpro != null) { // get the scoring model: we need it later for calculating the score // <!ENTITY % I_ScoreModel " scoremodel CDATA #IMPLIED"> scoremodel = el_outpro.attributeValue("scoremodel"); // may be null -> then assume SumOfScores // set the cutvalue if given (only variable score) cutvalue = QTIHelper.getFloatAttribute(el_outpro, "outcomes/decvar[@varname='SCORE']", "cutvalue"); List<?> el_oft = el_outpro.selectNodes("outcomes_feedback_test"); if (el_oft.size() != 0) { feedbacktesting = true; } } initSections(el_assessment, switches); init(); }
/** * Parse dataX job configuration file. * * @param filename Job configure filename. * @return a JobConf instance which describes this Job configuration file. */ @SuppressWarnings("unchecked") public static JobConf loadJobConfig(String filename) { JobConf job = new JobConf(); Document document; try { SAXReader reader = new SAXReader(); document = reader.read(new File(filename)); Element rootElement = document.getRootElement(); } catch (DocumentException e) { LOG.error("DataX Can not find " + filename + " ."); throw new DataExchangeException(e.getCause()); } catch (Exception e) { LOG.error(String.format("DataX read config file %s failed .", filename)); throw new DataExchangeException(e.getCause()); } String xpath = "/jobs/job"; Element jobE = (Element) document.selectSingleNode(xpath); job.setId( jobE.attributeValue("id") == null ? "DataX_is_still_a_virgin" : jobE.attributeValue("id").trim()); JobPluginConf readerJobConf = new JobPluginConf(); Element readerE = (Element) document.selectSingleNode(xpath + "/loader"); if (null == readerE) readerE = (Element) document.selectSingleNode(xpath + "/reader"); String readerId = readerE.attributeValue("id"); readerJobConf.setId(readerId == null ? "virgin-reader" : readerId.trim()); Element readerPluinE = (Element) readerE.selectSingleNode("plugin"); readerJobConf.setName( readerPluinE.getStringValue().trim().replace("loader", "reader").toLowerCase()); Map<String, String> readerParamMap = new HashMap<String, String>(); /* * for historic reason, we need to check concurrency node first add by * bazhen.csy */ if (readerE.selectSingleNode("concurrency") != null) { Element readerConcurrencyE = (Element) readerE.selectSingleNode("concurrency"); readerParamMap.put( "concurrency", StrUtils.replaceString(readerConcurrencyE.attributeValue("core"))); } List<Element> readerParamE = (List<Element>) readerE.selectNodes("param"); for (Element e : readerParamE) { readerParamMap.put( e.attributeValue("key").toLowerCase(), StrUtils.replaceString(e.attributeValue("value").trim())); } PluginParam readerPluginParam = new DefaultPluginParam(readerParamMap); // if (!readerPluginParam.hasValue("concurrency") // || readerPluginParam.getIntValue("concurrency", 1) < 0) { // throw new IllegalArgumentException( // "Reader option [concurrency] error !"); // } readerJobConf.setPluginParams(readerPluginParam); List<JobPluginConf> writerJobConfs = new ArrayList<JobPluginConf>(); List<Element> writerEs = (List<Element>) document.selectNodes(xpath + "/dumper"); if (null == writerEs || 0 == writerEs.size()) writerEs = (List<Element>) document.selectNodes(xpath + "/writer"); for (Element writerE : writerEs) { JobPluginConf writerPluginConf = new JobPluginConf(); String writerId = writerE.attributeValue("id"); writerPluginConf.setId(writerId == null ? "virgin-writer" : writerId.trim()); String destructLimit = writerE.attributeValue("destructlimit"); if (destructLimit != null) { writerPluginConf.setDestructLimit(Integer.valueOf(destructLimit)); } Element writerPluginE = (Element) writerE.selectSingleNode("plugin"); writerPluginConf.setName( writerPluginE.getStringValue().trim().replace("dumper", "writer").toLowerCase()); Map<String, String> writerParamMap = new HashMap<String, String>(); /* * for historic reason, we need to check concurrency node add by * bazhen.csy */ if (writerE.selectSingleNode("concurrency") != null) { Element writerConcurrencyE = (Element) writerE.selectSingleNode("concurrency"); writerParamMap.put( "concurrency", StrUtils.replaceString(writerConcurrencyE.attributeValue("core"))); } List<Element> writerParamE = (List<Element>) writerE.selectNodes("param"); for (Element e : writerParamE) { writerParamMap.put( e.attributeValue("key").toLowerCase(), StrUtils.replaceString(e.attributeValue("value").trim())); } PluginParam writerPluginParam = new DefaultPluginParam(writerParamMap); writerPluginConf.setPluginParams(writerPluginParam); writerJobConfs.add(writerPluginConf); } job.setReaderConf(readerJobConf); job.setWriterConfs(writerJobConfs); return job; }