Java Code Examples for org.dom4j.DocumentHelper

The following are top voted examples for showing how to use org.dom4j.DocumentHelper. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: urule   File: RepositoryServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
public List<UserPermission> loadResourceSecurityConfigs(String companyId) throws Exception{
	List<UserPermission> configs=new ArrayList<UserPermission>();
	String filePath=RESOURCE_SECURITY_CONFIG_FILE+(companyId == null ? "" : companyId);
	Node rootNode=getRootNode();
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("user-permission")) {
			continue;
		}
		UserPermission userResource=new UserPermission();
		userResource.setUsername(element.attributeValue("username"));
		userResource.setProjectConfigs(parseProjectConfigs(element));
		configs.add(userResource);
	}
	return configs;
}
 
Example 2
Project: joai-project   File: InfoXML.java   Source Code and License 7 votes vote down vote up
private Element getTagElement (String _tag, String _namespacePrefix, String _namespaceURI ) {
	
	Element tagElement = null; // caller is responsible for handling null
	
	try {
		// TODO  this isn't complete, as we can have any arbitrary tag and values for them infinitely deep
		XPath xpath = DocumentHelper.createXPath( "//" + ( _namespacePrefix != null ? _namespacePrefix + ":" : "" ) + _tag.trim() );
		SimpleNamespaceContext ns = new SimpleNamespaceContext();
		ns.addNamespace( _namespacePrefix, _namespaceURI );  
		xpath.setNamespaceContext(ns);

		tagElement = ((Element)xpath.selectSingleNode(this.infoxmlDoc));
		
	}  catch ( Exception e ) {
		e.printStackTrace();
	}
	
	return tagElement;		
}
 
Example 3
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param map 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2Xml(Map map, String pRootNodeName) {
    Document document = DocumentHelper.createDocument();
    // 增加一个根元素节点
    document.addElement(pRootNodeName);
    Element root = document.getRootElement();
    Iterator keyIterator = map.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = (String)keyIterator.next();
        String value = (String)map.get(key);
        Element leaf = root.addElement(key);
        leaf.setText(value);
    }
    // 将XML的头声明信息截去
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 4
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于属性值形式)
 * 
 * @param map 传入的Dto对象
 * @param pRootNodeName 根节点名
 * @param pFirstNodeName 一级节点名
 * @return string 返回XML格式字符串
 */
public static final String parseMap2Xml(Map map, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    // 增加一个根元素节点
    document.addElement(pRootNodeName);
    Element root = document.getRootElement();
    root.addElement(pFirstNodeName);
    Element firstEl = (Element)document.selectSingleNode("/" + pRootNodeName + "/" + pFirstNodeName);
    Iterator keyIterator = map.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = (String)keyIterator.next();
        String value = (String)map.get(key);
        firstEl.addAttribute(key, value);
    }
    // 将XML的头声明信息丢去
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 5
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点属性值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2Xml(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element elRoot = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map)pList.get(i);
        Element elRow = elRoot.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            elRow.addAttribute((String)entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 6
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element output = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map)pList.get(i);
        Element elRow = output.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            Element leaf = elRow.addElement((String)entry.getKey());
            leaf.setText(String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 7
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将mq查询结果包装成list--dto的形式,dto内容为item中的内容
 * 
 * @param recv
 * @return
 */
public static Map MqResToDto(String recv) {
    // System.out.println("####recv"+recv);
    List res = new ArrayList();
    Map map = new HashMap();
    try {
        Document doc = DocumentHelper.parseText(recv);
        List list = doc.selectNodes("//item");
        Iterator<DefaultElement> it = list.iterator();
        while (it.hasNext()) {
            Map elementdto = XmlUtil.Dom2Map(it.next());
            res.add(elementdto);
        }
        map.put("resultList", res);// 放入结果集
        /* 如果存在REC_MNT,说明是分页查询类,需要将总记录数返回 */
        Node de = doc.selectSingleNode("//REC_MNT");
        if (DataUtil.isNotEmpty(de)) {
            map.put("countInteger", de.getText());
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    return map;
}
 
Example 8
Project: JAVA-   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点属性值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2Xml(List pList, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	Element elRoot = document.addElement(pRootNodeName);
	for (int i = 0; i < pList.size(); i++) {
		Map map = (Map) pList.get(i);
		Element elRow = elRoot.addElement(pFirstNodeName);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			elRow.addAttribute((String) entry.getKey(), String.valueOf(entry.getValue()));
		}
	}
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 9
Project: unitimes   File: StudentSectioningQueue.java   Source Code and License 6 votes vote down vote up
protected static void addItem(org.hibernate.Session hibSession, UserContext user, Long sessionId, Type type, Long... ids) {
	StudentSectioningQueue q = new StudentSectioningQueue();
	q.setTimeStamp(new Date());
	q.setType(type.ordinal());
	q.setSessionId(sessionId);
	Document d = DocumentHelper.createDocument();
	Element root = d.addElement("generic");
	if (user != null) {
		Element e = root.addElement("user");
		e.addAttribute("id", user.getExternalUserId()).setText(user.getName());
	}
	if (ids != null && ids.length > 0) {
		for (Long id: ids)
			root.addElement("id").setText(id.toString());
	}
	q.setMessage(d);
	hibSession.save(q);
}
 
Example 10
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml) {
	Map map = new HashMap();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);

	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取根节点
	Element elNode = document.getRootElement();
	// 遍历节点属性值将其压入Dto
	for (Iterator it = elNode.elementIterator(); it.hasNext();) {
		Element leaf = (Element) it.next();
		map.put(leaf.getName().toLowerCase(), leaf.getData());
	}
	return map;
}
 
Example 11
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param dto 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2Xml(Map map, String pRootNodeName) {
	Document document = DocumentHelper.createDocument();
	// 增加一个根元素节点
	document.addElement(pRootNodeName);
	Element root = document.getRootElement();
	Iterator keyIterator = map.keySet().iterator();
	while (keyIterator.hasNext()) {
		String key = (String) keyIterator.next();
		String value = (String) map.get(key);
		Element leaf = root.addElement(key);
		leaf.setText(value);
	}
	// 将XML的头声明信息截去
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 12
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param dto 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2XmlHasHead(Map map, String pRootNodeName) {
	Document document = DocumentHelper.createDocument();
	// 增加一个根元素节点
	document.addElement(pRootNodeName);
	Element root = document.getRootElement();
	Iterator keyIterator = map.keySet().iterator();
	while (keyIterator.hasNext()) {
		String key = (String) keyIterator.next();
		String value = (String) map.get(key);
		Element leaf = root.addElement(key);
		leaf.setText(value);
	}
	// 将XML的头声明信息截去
	// String outXml = document.asXML().substring(39);
	String outXml = document.asXML();
	return outXml;
}
 
Example 13
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于属性值形式)
 * 
 * @param map 传入的Dto对象
 * @param pRootNodeName 根节点名
 * @param pFirstNodeName 一级节点名
 * @return string 返回XML格式字符串
 */
public static final String parseMap2Xml(Map map, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	// 增加一个根元素节点
	document.addElement(pRootNodeName);
	Element root = document.getRootElement();
	root.addElement(pFirstNodeName);
	Element firstEl = (Element) document.selectSingleNode("/" + pRootNodeName + "/" + pFirstNodeName);
	Iterator keyIterator = map.keySet().iterator();
	while (keyIterator.hasNext()) {
		String key = (String) keyIterator.next();
		String value = (String) map.get(key);
		firstEl.addAttribute(key, value);
	}
	// 将XML的头声明信息丢去
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 14
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点属性值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2Xml(List pList, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	Element elRoot = document.addElement(pRootNodeName);
	for (int i = 0; i < pList.size(); i++) {
		Map map = (Map) pList.get(i);
		Element elRow = elRoot.addElement(pFirstNodeName);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			elRow.addAttribute((String) entry.getKey(), String.valueOf(entry.getValue()));
		}
	}
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 15
Project: automat   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	Element output = document.addElement(pRootNodeName);
	for (int i = 0; i < pList.size(); i++) {
		Map map = (Map) pList.get(i);
		Element elRow = output.addElement(pFirstNodeName);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Element leaf = elRow.addElement((String) entry.getKey());
			leaf.setText(String.valueOf(entry.getValue()));
		}
	}
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 16
Project: IPE-LWM2M   File: SimpleLwm2mServer.java   Source Code and License 6 votes vote down vote up
private void emitValue(String path, String content){
    
    Document document = DocumentHelper.createDocument();
    Element eleRoot = document.addElement("msg");
    
    Element elePath = eleRoot.addElement("path");
    Element eleContent = eleRoot.addElement("value");
    
    elePath.setText(path);
    eleContent.setText(content);

    String msg = document.asXML();
    
    if(handler != null){
    	MsgReceiveEvent event = new MsgReceiveEvent(this, msg);
    	handler.receiveMsgEvent(event);
    }
}
 
Example 17
Project: xpath-to-xml   File: XmlBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBuildDocumentFromSetOfXPaths() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties.keySet())
            .build(DocumentHelper.createDocument());

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey());
        if (null != namespaceContext) {
            xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext));
        }
        assertThat(xpath.evaluate(builtDocument)).isNotNull();
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutXml());
}
 
Example 18
Project: JAVA-   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将mq查询结果包装成list--dto的形式,dto内容为item中的内容
 * 
 * @param recv
 * @return
 */
public static Map MqResToDto(String recv) {
	// System.out.println("####recv"+recv);
	List res = new ArrayList();
	Map map = new HashMap();
	try {
		Document doc = DocumentHelper.parseText(recv);
		List list = doc.selectNodes("//item");
		Iterator<DefaultElement> it = list.iterator();
		while (it.hasNext()) {
			Map elementdto = XmlUtil.Dom2Map(it.next());
			res.add(elementdto);
		}
		map.put("resultList", res);// 放入结果集
		/*
		 * 如果存在REC_MNT,说明是分页查询类,需要将总记录数返回
		 */
		Node de = doc.selectSingleNode("//REC_MNT");
		if (DataUtil.isNotEmpty(de)) {
			map.put("countInteger", de.getText());
		}
	} catch (Exception e) {
		log.error(XmlUtil.class, e);
	}
	return map;
}
 
Example 19
Project: sbc-qsystem   File: NetCommander.java   Source Code and License 6 votes vote down vote up
/**
 * Получение конфигурации главного табло - ЖК или плазмы. Это XML-файл лежащий в папку
 * приложения mainboard.xml
 *
 * @param netProperty параметры соединения с сервером
 * @return корень XML-файла mainboard.xml
 * @throws DocumentException принятый текст может не преобразоваться в XML
 */
public static Element getBoardConfig(INetProperty netProperty) throws DocumentException {
    QLog.l().logger().info("Получение конфигурации главного табло - ЖК или плазмы.");
    // загрузим ответ
    final String res;
    try {
        res = send(netProperty, Uses.TASK_GET_BOARD_CONFIG, null);
    } catch (QException e) {
        throw new ClientException(Locales.locMes("bad_response") + "\n" + e.toString());
    }
    final Gson gson = GsonPool.getInstance().borrowGson();
    final RpcGetSrt rpc;
    try {
        rpc = gson.fromJson(res, RpcGetSrt.class);
    } catch (JsonSyntaxException ex) {
        throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
    } finally {
        GsonPool.getInstance().returnGson(gson);
    }
    return DocumentHelper.parseText(rpc.getResult()).getRootElement();
}
 
Example 20
Project: xpath-to-xml   File: XmlBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(DocumentHelper.createDocument());

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey());
        if (null != namespaceContext) {
            xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext));
        }
        assertThat(xpath.selectSingleNode(builtDocument).getText()).isEqualTo(xpathToValuePair.getValue());
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
 
Example 21
Project: joai-project   File: User.java   Source Code and License 6 votes vote down vote up
/**
 *  Description of the Method
 *
 *@return    Description of the Return Value
 */
private Element rolesMapToElement() {
	Element rolesElement = DocumentHelper.createElement("roles");
	if (!this.isAdminUser()) {
		for (Iterator i = this.getRoleMap().keySet().iterator(); i.hasNext(); ) {
			String collection = (String) i.next();

			// TODO - eliminate "default" collection. this can be removed after user files
			// for each User instance are written.

			Roles.Role role = this.getAssignedRole(collection);
			if (role != Roles.NO_ROLE) {
				Element roleElement = rolesElement.addElement("role");
				roleElement.addElement("rolename").setText(role.toString());
				roleElement.addElement("collection").setText(collection);

			}
		}
	}
	return rolesElement;
}
 
Example 22
Project: joai-project   File: DevelTools.java   Source Code and License 6 votes vote down vote up
public static void addAgent (String id) throws Exception {
	NdrRequest request = new NdrRequest ();
	request.setObjectType(NDRObjectType.AGENT);
	request.setVerb ("addAgent");
	
	Element identifier = DocumentHelper.createElement("identifier");
	identifier.setText (id);
	identifier.addAttribute ("type", "HOST");
	request.addCommand ("property", identifier);
	request.addCommand ("relationship", "memberOf", "2200/test.20070806193858997T");
	String title = "Agent for mud collection";
	String description = "its all about mud";
	String subject = "none that i can see";
	NsdlDcWriter dc_stream = new NsdlDcWriter(title, description, subject);
	
	request.addDCStreamCmd(dc_stream.asElement());
	
	request.submit();
}
 
Example 23
Project: WechatBot   File: WechatBot.java   Source Code and License 6 votes vote down vote up
private Map<String, String> parseInitData(String data) {
    try {
        Map<String, String> ussData = new HashMap<>();
        Document document = DocumentHelper.parseText(data);
        Element root = document.getRootElement();
        Iterator iter = root.elementIterator();
        while (iter.hasNext()) {
            Element ele = (Element) iter.next();
            log.debug("name:" + ele.getName() + " value:" + ele.getStringValue());
            ussData.put(ele.getName(), ele.getStringValue());
        }

        // 随机device id
        String deviceID = "e";
        for (int i = 0; i < 3; i++) {
            int randomNum = ThreadLocalRandom.current().nextInt(10000, 99999);
            deviceID += randomNum;
        }
        ussData.put("deviceID", deviceID);
        return ussData;
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 24
Project: iBase4J   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param dto 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2Xml(Map map, String pRootNodeName) {
	Document document = DocumentHelper.createDocument();
	// 增加一个根元素节点
	document.addElement(pRootNodeName);
	Element root = document.getRootElement();
	Iterator keyIterator = map.keySet().iterator();
	while (keyIterator.hasNext()) {
		String key = (String) keyIterator.next();
		String value = (String) map.get(key);
		Element leaf = root.addElement(key);
		leaf.setText(value);
	}
	// 将XML的头声明信息截去
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 25
Project: unitimes   File: StudentSectioningQueue.java   Source Code and License 6 votes vote down vote up
protected static void addItem(org.hibernate.Session hibSession, UserContext user, Long sessionId, Type type, Collection<Long> ids) {
	StudentSectioningQueue q = new StudentSectioningQueue();
	q.setTimeStamp(new Date());
	q.setType(type.ordinal());
	q.setSessionId(sessionId);
	Document d = DocumentHelper.createDocument();
	Element root = d.addElement("generic");
	if (user != null) {
		Element e = root.addElement("user");
		e.addAttribute("id", user.getExternalUserId()).setText(user.getName());
	}
	if (ids != null && !ids.isEmpty()) {
		for (Long id: ids)
			root.addElement("id").setText(id.toString());
	}
	q.setMessage(d);
	hibSession.save(q);
}
 
Example 26
Project: JAVA-   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	Element output = document.addElement(pRootNodeName);
	for (int i = 0; i < pList.size(); i++) {
		Map map = (Map) pList.get(i);
		Element elRow = output.addElement(pFirstNodeName);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Element leaf = elRow.addElement((String) entry.getKey());
			leaf.setText(String.valueOf(entry.getValue()));
		}
	}
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 27
Project: unitimes   File: DataExchangeConnector.java   Source Code and License 6 votes vote down vote up
@Override
public void doPost(ApiHelper helper) throws IOException {
	helper.getSessionContext().checkPermissionAnyAuthority(Right.ApiDataExchangeConnector);
	
	Document document = helper.getRequest(Document.class);
	Document output = DocumentHelper.createDocument();
	final Element messages = output.addElement("html");
	try {
		DataExchangeHelper.importDocument(document, helper.getSessionContext().isAuthenticated() ? helper.getSessionContext().getUser().getExternalUserId() : null, new LogWriter() {
			@Override
			public void println(String message) {
				messages.addElement("p").setText(message);
			}
		});
		helper.setResponse(output);
	} catch (Exception e) {
		throw new IOException(e.getMessage(), e);
	}
}
 
Example 28
Project: urule   File: FrameServletHandler.java   Source Code and License 6 votes vote down vote up
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String path=req.getParameter("path");
	path=Utils.decodeURL(path);
	InputStream inputStream=repositoryService.readFile(path,null);
	String content=IOUtils.toString(inputStream,"utf-8");
	inputStream.close();
	String xml=null;
	try{
		Document doc=DocumentHelper.parseText(content);
		OutputFormat format=OutputFormat.createPrettyPrint();
		StringWriter out=new StringWriter();
		XMLWriter writer=new XMLWriter(out, format);
		writer.write(doc);
		xml=out.toString();
	}catch(Exception ex){
		xml=content;
	}
	Map<String,Object> result=new HashMap<String,Object>();
	result.put("content", xml);
	writeObjectToJson(resp, result);
}
 
Example 29
Project: iBase4J   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将mq查询结果包装成list--dto的形式,dto内容为item中的内容
 * 
 * @param recv
 * @return
 */
public static Map MqResToDto(String recv) {
	// System.out.println("####recv"+recv);
	List res = new ArrayList();
	Map map = new HashMap();
	try {
		Document doc = DocumentHelper.parseText(recv);
		List list = doc.selectNodes("//item");
		Iterator<DefaultElement> it = list.iterator();
		while (it.hasNext()) {
			Map elementdto = XmlUtil.Dom2Map(it.next());
			res.add(elementdto);
		}
		map.put("resultList", res);// 放入结果集
		/*
		 * 如果存在REC_MNT,说明是分页查询类,需要将总记录数返回
		 */
		Node de = doc.selectSingleNode("//REC_MNT");
		if (DataUtil.isNotEmpty(de)) {
			map.put("countInteger", de.getText());
		}
	} catch (Exception e) {
		log.error(XmlUtil.class, e);
	}
	return map;
}
 
Example 30
Project: urule   File: RuleSetReferenceUpdater.java   Source Code and License 5 votes vote down vote up
public String update(String oldPath, String newPath, String xml) {
	try{
		boolean modify=false;
		Document doc=DocumentHelper.parseText(xml);
		Element element=doc.getRootElement();
		for(Object obj:element.elements()){
			if(!(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			boolean match=false;
			if(name.equals("import-variable-library")){
				match=true;
			}else if(name.equals("import-constant-library")){
				match=true;
			}else if(name.equals("import-action-library")){
				match=true;
			}else if(name.equals("import-parameter-library")){
				match=true;
			}
			if(!match){
				continue;
			}
			String path=ele.attributeValue("path");
			if(path.endsWith(oldPath)){
				ele.addAttribute("path", newPath);
				modify=true;
			}
		}
		if(modify){
			return xmlToString(doc);
		}
		return null;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}
 
Example 31
Project: sbc-qsystem   File: QIndicatorHtmlboard.java   Source Code and License 5 votes vote down vote up
@Override
public Element getConfig() {
    String tr = "<Параметры>\n"
        + "   <Параметер Наименование=\"top.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().topSize + "\"/>\n"
        + "   <Параметер Наименование=\"top.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().topUrl + "\"/>\n"
        + "   <Параметер Наименование=\"left.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().leftSize + "\"/>\n"
        + "   <Параметер Наименование=\"left.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().leftUrl + "\"/>\n"
        + "   <Параметер Наименование=\"right.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().rightSize + "\"/>\n"
        + "   <Параметер Наименование=\"right.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().rightUrl + "\"/>\n"
        + "   <Параметер Наименование=\"bottom.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().bottomSize + "\"/>\n"
        + "   <Параметер Наименование=\"bottom.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().bottomUrl + "\"/>\n"
        + "   <Параметер Наименование=\"need_reload\" Тип=\"4\" Значение=\"" + (
        HtmlBoardProps.getInstance().needReload ? "1" : "0") + "\"/>\n";

    for (String key : HtmlBoardProps.getInstance().getAddrs().keySet()) {
        tr = tr + "   <Параметер Наименование=\"" + key + "\" Тип=\"3\" Значение=\""
            + HtmlBoardProps
            .getInstance().getAddrs().get(key) + "\" " + Uses.TAG_BOARD_READ_ONLY
            + "=\"true\"/>\n";
    }

    tr = tr + "</Параметры>";
    final Document document;
    try {
        document = DocumentHelper.parseText(tr);
    } catch (DocumentException ex) {
        throw new ServerException(ex);
    }
    return document.getRootElement();
}
 
Example 32
Project: iBase4J-Common   File: XmlUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 将XML规范的字符串转为List对象(XML基于节点属性值的方式)
 * 
 * @param pStrXml 传入的符合XML格式规范的字符串
 * @return list 返回List对象
 */
public static final List parseXml2List(String pStrXml) {
    List lst = new ArrayList();
    String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    Document document = null;
    try {
        if (pStrXml.indexOf("<?xml") < 0) pStrXml = strTitle + pStrXml;
        document = DocumentHelper.parseText(pStrXml);
    } catch (DocumentException e) {
        logger.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
    }
    // 获取到根节点
    Element elRoot = document.getRootElement();
    // 获取根节点的所有子节点元素
    Iterator elIt = elRoot.elementIterator();
    while (elIt.hasNext()) {
        Element el = (Element)elIt.next();
        Iterator attrIt = el.attributeIterator();
        Map map = new HashMap();
        while (attrIt.hasNext()) {
            Attribute attribute = (Attribute)attrIt.next();
            map.put(attribute.getName().toLowerCase(), attribute.getData());
        }
        lst.add(map);
    }
    return lst;
}
 
Example 33
Project: directory-ldap-api   File: BatchRequestDsml.java   Source Code and License 5 votes vote down vote up
/**
 * Converts this Batch Request to its XML representation in the DSMLv2 format.
 * 
 * @return the XML representation in DSMLv2 format
 */
public String toDsml()
{
    Document document = DocumentHelper.createDocument();
    Element element = document.addElement( "batchRequest" );

    // RequestID
    if ( requestID != 0 )
    {
        element.addAttribute( "requestID", Integer.toString( requestID ) );
    }

    // ResponseOrder
    if ( responseOrder == ResponseOrder.UNORDERED )
    {
        element.addAttribute( "responseOrder", "unordered" );
    }

    // Processing
    if ( processing == Processing.PARALLEL )
    {
        element.addAttribute( "processing", "parallel" );
    }

    // On Error
    if ( onError == OnError.RESUME )
    {
        element.addAttribute( "onError", "resume" );
    }

    // Requests
    for ( DsmlDecorator<? extends Request> request : requests )
    {
        request.toDsml( element );
    }

    return ParserUtils.styleDocument( document ).asXML();
}
 
Example 34
Project: YiDu-Novel   File: WeixinUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Give body, parse result to `result` map
 *
 * @param body
 * @param result
 * @throws DocumentException
 */
public static void parseWxMessage(String body, Map<String, String> result) throws DocumentException {
    Element root = DocumentHelper.parseText(body).getRootElement();
    for (Iterator i = root.elementIterator(); i.hasNext(); ) {
        Element element = (Element) i.next();
        result.put(element.getName(), element.getText());
    }
}
 
Example 35
Project: zookeeper-test-demo   File: ConfigUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 输出string为xml文件
 * 
 * @param xmlText
 *            xml内容
 * @param storePath
 *            保存路径
 * @throws Exception
 */
public static void writeToXML(String xmlText, String storePath) throws Exception {
	try {
		Document doc = DocumentHelper.parseText(xmlText);
		FileOutputStream xmlOs = new FileOutputStream(new File(storePath));
		byte[] data = xmlText.getBytes();
		xmlOs.write(data, 0, data.length);
		xmlOs.flush();

		xmlOs.close();
	} catch (Exception e) {
		throw new Exception("输入的xml文本有问题或者传入的路径有出入", e);
	}
}
 
Example 36
Project: joai-project   File: DataStreamWrapper.java   Source Code and License 5 votes vote down vote up
public void setDataStream( String _format, String _metadataXML ) throws Exception {	
	if (_metadataXML == null)
		this.dataStreams.put (_format, null);
	else {
		Document doc = DocumentHelper.parseText(_metadataXML);
		this.setDataStream(_format, doc.getRootElement());
	}
}
 
Example 37
Project: urule   File: FlowDefinitionReferenceUpdater.java   Source Code and License 5 votes vote down vote up
public boolean contain(String path, String xml) {
	try{
		Document doc=DocumentHelper.parseText(xml);
		Element element=doc.getRootElement();
		for(Object obj:element.elements()){
			if(!(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			boolean match=false;
			if(name.equals("import-variable-library")){
				match=true;
			}else if(name.equals("import-constant-library")){
				match=true;
			}else if(name.equals("import-action-library")){
				match=true;
			}else if(name.equals("import-parameter-library")){
				match=true;
			}
			if(!match){
				continue;
			}
			String filePath=ele.attributeValue("path");
			if(filePath.endsWith(path)){
				return true;
			}
		}
		return false;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}
 
Example 38
Project: urule   File: AbstractBuilder.java   Source Code and License 5 votes vote down vote up
protected Element parseResource(String content){
	try {
		Document document = DocumentHelper.parseText(content);
		Element root=document.getRootElement();
		return root;
	} catch (DocumentException e) {
		throw new RuleException(e);
	}
}
 
Example 39
Project: minlia-iot   File: XmlSignatureAnnotationHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 预检验签名
 *
 * @param xml xml字符串
 * @param salt partnerApiKey
 * @param clazz 类型
 * @return 是否通过验证
 */
@SuppressWarnings("unchecked")
public static boolean prepareCheckSign(String xml, String salt, Boolean excludeSaltParameter,
    Class<?> clazz,
    SignatureAlgorithmic algorithmic, String saltParameterPrefix, String charset,
    CaseControl caseControl, String delimiter) {
  Field signField = signField(clazz);
  XmlElement xmlElementAnnotation = signField.getAnnotation(XmlElement.class);
  try {
    Document document = DocumentHelper.parseText(xml);
    Element rootElement = document.getRootElement();
    List<FieldPaired> fieldPaireds = new LinkedList<>();
    String targetSign = null;
    for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) {
      Element element = iterator.next();
      if (element.getName().equals(xmlElementAnnotation.name())) {
        targetSign = element.getTextTrim();
      } else {
        String text = element.getTextTrim();
        if (StringUtils.isNotBlank(text)) {
          fieldPaireds.add(new FieldPaired(element.getName(), text));
        }
      }
    }
    if (StringUtils.isBlank(targetSign)) {
      log.warn("Sign shoud not be empty.");
    }
    String signStr = "";

    signStr = makeSignBySinpleFieldList(fieldPaireds, salt, excludeSaltParameter, algorithmic,
        saltParameterPrefix, charset, caseControl, delimiter);
    return signStr.equals(targetSign);
  } catch (DocumentException e) {
    e.printStackTrace();
    return false;
  }
}
 
Example 40
Project: unitimes   File: CurriculaCourseDemands.java   Source Code and License 5 votes vote down vote up
@Override
public void teardown(org.hibernate.Session hibSession) {
	if (iUpdateClassification) {
		// Save into the cache
		Document doc = DocumentHelper.createDocument();
		iModel.saveAsXml(doc.addElement(getCacheName()), iAssignment);
		// sLog.debug("Model:\n" + doc.asXML());
		iClassification.setStudentsDocument(doc);

		hibSession.update(iClassification);
	}

	// Save results
	String majors = "";
	for (PosMajor major: iClassification.getCurriculum().getMajors()) {
		if (!majors.isEmpty()) majors += ",";
		majors += major.getCode();
	}
	for (CurStudent s: iModel.getStudents()) {
		WeightedStudentId student = new WeightedStudentId(- iLastStudentId.newId(), iClassification);
		if (iCreateStudentGroups)
			student.getGroups().add(new Group(-iClassification.getUniqueId(), iClassification.getCurriculum().getAbbv() + " " + iClassification.getAcademicClassification().getCode()));
		Set<WeightedCourseOffering> studentCourses = new HashSet<WeightedCourseOffering>();
		iStudentRequests.put(student.getStudentId(), studentCourses);
		Hashtable<Long, Double> priorities = new Hashtable<Long, Double>(); iEnrollmentPriorities.put(student.getStudentId(), priorities);
		for (CurCourse course: s.getCourses(iAssignment)) {
			CourseOffering co = iCourses.get(course.getCourseId());
			if (course.getPriority() != null) priorities.put(co.getUniqueId(), course.getPriority());
			Set<WeightedStudentId> courseStudents = iDemands.get(co.getUniqueId());
			if (courseStudents == null) {
				courseStudents = new HashSet<WeightedStudentId>();
				iDemands.put(co.getUniqueId(), courseStudents);
			}
			courseStudents.add(student);
			studentCourses.add(new WeightedCourseOffering(co, student.getWeight()));
		}
	}
}
 
Example 41
Project: urule   File: DecisionTableReferenceUpdater.java   Source Code and License 5 votes vote down vote up
public String update(String oldPath, String newPath, String xml) {
	try{
		boolean modify=false;
		Document doc=DocumentHelper.parseText(xml);
		Element element=doc.getRootElement();
		for(Object obj:element.elements()){
			if(!(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			boolean match=false;
			if(name.equals("import-variable-library")){
				match=true;
			}else if(name.equals("import-constant-library")){
				match=true;
			}else if(name.equals("import-action-library")){
				match=true;
			}else if(name.equals("import-parameter-library")){
				match=true;
			}
			if(!match){
				continue;
			}
			String path=ele.attributeValue("path");
			if(path.endsWith(oldPath)){
				ele.addAttribute("path", newPath);
				modify=true;
			}
		}
		if(modify){
			return xmlToString(doc);
		}
		return null;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}
 
Example 42
Project: GraphicsViewJambi   File: ExportNetworkToXML.java   Source Code and License 5 votes vote down vote up
public ExportNetworkToXML()
{
	document = DocumentHelper.createDocument(); 		//创建文档的根节点
	root = DocumentHelper.createElement("localnetwork");//创建文档的 根元素节点
	document.setRootElement(root);
	
	//给根节点添加属性
	//----------------------------------------------------------------
	Date dateNow = new Date();
	SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy kk:mm:ss");
	root.addAttribute("time", ft.format(dateNow));
}
 
Example 43
Project: joai-project   File: MetadataReader.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the "nsdl_dc" datastream as a dom4j.Document
 *
 * @return                The canonicalNsdlDcItemRecord value
 * @exception  Exception  NOT YET DOCUMENTED
 */
public Document getCanonicalNsdlDcItemRecord() throws Exception {
	Element root = this.getCanonicalNsdlDcDataStream();
	if (root == null)
		throw new Exception("canonicalNsdlDcItemRecord not found in " + this.getHandle());
	try {
		return DocumentHelper.createDocument(root);
	} catch (Throwable t) {
		throw new Exception("could not create canonicalNsdlDcItemRecord for " + this.getHandle() + ": " + t.getMessage());
	}
}
 
Example 44
Project: joai-project   File: HarvestInfoReader.java   Source Code and License 5 votes vote down vote up
private String getValue(String xpath) {
	XPath xpathObj = DocumentHelper.createXPath(xpath);
	xpathObj.setNamespaceURIs(getNSMap());
	Node node = xpathObj.selectSingleNode(doc);
	if (node != null)
		return node.getText();
	else
		return null;
}
 
Example 45
Project: joai-project   File: HarvestInfoReader.java   Source Code and License 5 votes vote down vote up
private List getValues(String xpath) {
	XPath xpathObj = DocumentHelper.createXPath(xpath);
	xpathObj.setNamespaceURIs(getNSMap());
	List nodes = xpathObj.selectNodes(doc);
	List values = new ArrayList();
	for (Iterator i = nodes.iterator(); i.hasNext(); ) {
		values.add(((Node) i.next()).getText());
	}
	return values;
}
 
Example 46
Project: joai-project   File: InfoXML.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs the infoXML abstraction based on the input
 * given.
 * 
 * @param _xml
 */
public InfoXML ( String _xml )
{
	try {
		// TODO : BARFS on the xsi: attribute on return saying :
		//			org.dom4j.DocumentException: Error on line 1 of document  : 
		//			The prefix "xsi" for attribute "xsi:schemaLocation" associated with 
		//			an element type "NSDLDataRepository" is not bound. 
		//			Nested exception: The prefix "xsi" for attribute "xsi:schemaLocation" 
		//			associated with an element type "NSDLDataRepository" is not bound.

		this.contentRaw = _xml;
		this.infoxmlDoc = DocumentHelper.parseText( this.contentRaw );
					
		XPath xpath = DocumentHelper.createXPath( "//ndr:error" ); // for error node checks

		// TODO : though the default namespace is NOT called NDR,
		// http://www.xslt.com/html/xsl-list/2005-03/msg01059.html indicates we must give
		// it one if we are to use it in an XPath.  How fun is that!
		SimpleNamespaceContext ns = new SimpleNamespaceContext();
		ns.addNamespace("ndr", "http://ns.nsdl.org/ndr/response_v1.00/");
		
		xpath.setNamespaceContext(ns);
		
		// select the error node
    	Element error = (Element)xpath.selectSingleNode(this.infoxmlDoc);
    	
    	if ( error != null )
    	{
    		this.hasErrors = true;
    		this.errorString = error.getText();
    	}
    	
	} catch ( Exception e ) {
		this.contentRaw = _xml;
		this.errorString = "Fatal error in InfoXML construction.";
		// e.printStackTrace();
	}		
}
 
Example 47
Project: joai-project   File: NdrUtils.java   Source Code and License 5 votes vote down vote up
/**
 *  NOT YET DOCUMENTED
 *
 * @param  xml  NOT YET DOCUMENTED
 */
public static void pp(String xml) {
	if (xml == null || "".equals(xml)) {
		prtln("prettyPrint: no input supplied");
	}

	try {
		pp(DocumentHelper.parseText(xml));
	} catch (Throwable t) {
		prtln("ERROR: unable to process xml ..." + t.getMessage());
		prtln(xml);
	}
}
 
Example 48
Project: joai-project   File: OAISetsXMLConfigManager.java   Source Code and License 5 votes vote down vote up
private static Element createTextQueryElement(String fieldName, String fieldType, String termOrPhrase) throws Exception {
	/* if (fieldName == null || fieldName.trim().length() == 0)
		throw new Exception("fieldName must not be empty or null");
	if (fieldType == null || fieldType.trim().length() == 0)
		throw new Exception("fieldType must not be empty or null");
	if (!fieldType.equals("matchAnyTerm") && !fieldType.equals("matchPhrase"))
		throw new Exception("fieldType must be either 'matchAnyTerm' or 'matchPhrase'"); */
	Document document = DocumentHelper.createDocument();
	Element fieldQuery = document.addElement("textQuery");
	if (fieldName != null)
		fieldQuery.addAttribute("field", fieldName);
	fieldQuery.addAttribute("type", fieldType);
	fieldQuery.addText(termOrPhrase);
	return fieldQuery;
}
 
Example 49
Project: bdf2   File: PageOutputer.java   Source Code and License 5 votes vote down vote up
private String generateView(PageInfo page, String path,String pageName) throws Exception,
		IOException {
	RuleSet ruleSet=ruleSetHelper.getRuleSet();
	Rule viewConfigRule=ruleSet.getRule("ViewConfig");
	BaseElement rootElement=new BaseElement(viewConfigRule.getNodeName());
	for(IBuilder builder:builders){
		rootElement.add(builder.build(page,ruleSet));
	}
	File f=new File(path);
	if(!f.exists()){
		f.mkdirs();
	}
	if(StringUtils.isEmpty(pageName)){
		pageName=page.getName();			
	}
	String targetFilePath=path+"/"+pageName+".view.xml";
	
	OutputStream out=new FileOutputStream(targetFilePath);
	Document document=DocumentHelper.createDocument(rootElement);
	OutputFormat format=OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	XMLWriter xmlWriter=new XMLWriter(out, format);
	try{
		xmlWriter.write(document);			
	}finally{
		xmlWriter.close();		
		out.close();
	}
	return pageName;
}
 
Example 50
Project: joai-project   File: OAISetsXMLConfigManager.java   Source Code and License 5 votes vote down vote up
private static Element createBooleanQueryElement(String type, List clauseElements) throws Exception {
	if (type == null || (!type.equals("OR") && !type.equals("AND")))
		throw new Exception("boolean type must be either 'OR' or 'AND'");
	if (clauseElements == null || clauseElements.size() == 0)
		throw new Exception("boolean clause Elements List is empty or null");

	Document document = DocumentHelper.createDocument();
	Element booleanQuery = document.addElement("booleanQuery ");
	booleanQuery.addAttribute("type", type);
	for (int i = 0; i < clauseElements.size(); i++)
		booleanQuery.add((Element) clauseElements.get(i));
	return booleanQuery;
}
 
Example 51
Project: unitimes   File: HQLExportXML.java   Source Code and License 5 votes vote down vote up
@Override
public void export(ExportHelper helper) throws IOException {
	String s = helper.getParameter("id");
	if (s == null)
		throw new IllegalArgumentException("No report provided, please set the id parameter.");
	SavedHQL report = SavedHQLDAO.getInstance().get(Long.valueOf(s));
	if (report == null)
		throw new IllegalArgumentException("Report " + s + " does not exist.");

	helper.getSessionContext().checkPermission(report, Right.HQLReportEdit);

	helper.setup("text/xml", report.getName().replace('/', '-').replace('\\', '-').replace(':', '-') + ".xml",
			false);

	Document document = DocumentHelper.createDocument();
	document.addDocType("report", "-//UniTime//UniTime HQL Reports DTD/EN",
			"http://www.unitime.org/interface/Reports.dtd");
	Element reportEl = document.addElement("report");
	reportEl.addAttribute("name", report.getName());
	for (SavedHQL.Flag flag : SavedHQL.Flag.values()) {
		if (report.isSet(flag))
			reportEl.addElement("flag").setText(flag.name());
	}
	if (report.getDescription() != null)
		reportEl.addElement("description").add(new DOMCDATA(report.getDescription()));
	if (report.getQuery() != null)
		reportEl.addElement("query").add(new DOMCDATA(report.getQuery()));
	reportEl.addAttribute("created", new Date().toString());

	OutputStream out = helper.getOutputStream();
	new XMLWriter(out, OutputFormat.createPrettyPrint()).write(document);
}
 
Example 52
Project: unitimes   File: RoomAvailabilityService.java   Source Code and License 5 votes vote down vote up
protected Document createRequest(CacheElement cache) {
    Document request = DocumentHelper.createDocument();
    Element params = request.addElement("parameters");
    params.addAttribute("created", new Date().toString());
    params.addElement("year").addAttribute("value", cache.getYear());
    params.addElement("term").addAttribute("value", cache.getTerm());
    params.addElement("campus").addAttribute("value", cache.getCampus());
    params.addElement("beginDate").addAttribute("value", new SimpleDateFormat("MM/dd/yyyy").format(cache.getTimeFrame().getStartTime()));
    params.addElement("endDate").addAttribute("value", new SimpleDateFormat("MM/dd/yyyy").format(cache.getTimeFrame().getEndTime()));
    params.addElement("startTime").addAttribute("value", new SimpleDateFormat("HH:mm").format(cache.getTimeFrame().getStartTime()));
    params.addElement("endTime").addAttribute("value", new SimpleDateFormat("HH:mm").format(cache.getTimeFrame().getEndTime()));
    return request;
}
 
Example 53
Project: joai-project   File: ADNToOAIDCFormatConverter.java   Source Code and License 5 votes vote down vote up
/**
 *  Performs XML conversion from ADN to oai_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  docReader  A lucene doc reader for this record.
 * @param  context    The servlet context where this is running.
 * @return            XML in the converted 'oai_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
		Transformer adn_to_oai_transformer = XSLTransformer.getTransformer(adn_to_oai_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_oai_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);
					
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs in the relation field only
		handleRelationField("//oai_dc:dc/dc:relation",document);
	
		// Dom4j automatically writes using UTF-8, unless otherwise specified.
		OutputFormat format = OutputFormat.createPrettyPrint();
		StringWriter outputWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(outputWriter, format);
		writer.write(document);
		outputWriter.close();
		writer.close();
		return outputWriter.toString();			
	} catch (Throwable e) {
		System.err.println("ADNToOAIDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 54
Project: joai-project   File: CollectionAdopter.java   Source Code and License 5 votes vote down vote up
/**
 *  Constructor for the CollectionAdopter object
 *
 * @param  mdpHandle      NOT YET DOCUMENTED
 * @exception  Exception  NOT YET DOCUMENTED
 */
public CollectionAdopter(String mdpHandle) throws Exception {
	SimpleNdrRequest.setDebug(true);
	SimpleNdrRequest.setVerbose(false);
	MetadataProviderReader mdp = new MetadataProviderReader(mdpHandle);
	List itemHandles = mdp.getItemHandles();
	prtln("There are " + itemHandles.size() + " records to retrieve");
	for (Iterator i = itemHandles.iterator(); i.hasNext(); ) {
		String itemHandle = (String) i.next();
		MetadataReader mdReader = new MetadataReader(itemHandle);
		// prtln ("\n" + mdReader.getHandle());
		Element nsdl_dc_stream = (mdReader.getDataStream("nsdl_dc"));
		// pp (nsdl_dc_stream);
		// prtln ("----------");
		Element ncs_item_stream = this.getNcsItemStream(nsdl_dc_stream);
		// pp (ncs_item_stream);

		Element root = DocumentHelper.createElement("ndrMetadataInfo");

		Element ndrHandle_element = root.addElement("ndrHandle");
		ndrHandle_element.setText(itemHandle);
		Element nsdl_dc_element = root.addElement("nsdl_dc");
		if (nsdl_dc_stream != null)
			nsdl_dc_element.add(nsdl_dc_stream);
		Element ncs_item_element = root.addElement("ncs_item");
		if (ncs_item_stream != null)
			ncs_item_element.add(ncs_item_stream);
		Document doc = DocumentHelper.createDocument(root);
		// pp (doc);
		this.writeDoc(doc);
	}
}
 
Example 55
Project: Spring-Boot-Server   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
public static List<PageData> getAssetDatas(String xmlStr) throws Exception {
		Document document = DocumentHelper.parseText(xmlStr);
		List<PageData> res = null;
		if(null != document){
			res = new ArrayList<PageData>();
			//获取文档的根节点
			Element root = document.getRootElement();
			//取得某个节点的子节点
			Element element_sentence_list = root.element("ContentList");
			//取得某节点下所有名为“Program”的子节点,并进行遍历
			List nodes = element_sentence_list.elements("Program");
			for (Iterator it = nodes.iterator(); it.hasNext();) {
				PageData pd_tmp = new PageData();
				Element elm = (Element) it.next();
				pd_tmp.put("name", elm.attribute("name").getText());
				pd_tmp.put("resourceCode", elm.attribute("contentID").getText());
				//取得某节点下所有名为“Series”的子节点,并进行遍历
				List nodes1 = elm.elements("PictureList");
				for (Iterator it1 = nodes1.iterator(); it1.hasNext();) {
					Element elm1 = (Element) it1.next();
					List nodes2 = elm1.elements("Picture"); 
					for (Iterator it2 = nodes2.iterator(); it2.hasNext();) {
						Element elm2 = (Element) it2.next();
						pd_tmp.put("picFileURL", elm2.attribute("fileURL").getText());
//						System.out.println(elm.attribute("contentId").getText() + "-" + elm.attribute("name").getText() + "-" + elm2.attribute("fileURL").getText());
						res.add(pd_tmp);
					}
					break;
				}
			}
		}
		return res;
	}
 
Example 56
Project: joai-project   File: NDRAction.java   Source Code and License 5 votes vote down vote up
/**
 *  Execute an ndrRequest (constructed from request parameters) and store the
 *  results in the Form as an XML document before forwarding to "proxy.response".
 *
 * @param  mapping        NOT YET DOCUMENTED
 * @param  form           NOT YET DOCUMENTED
 * @param  request        NOT YET DOCUMENTED
 * @param  response       NOT YET DOCUMENTED
 * @return                NOT YET DOCUMENTED
 * @exception  Exception  NOT YET DOCUMENTED
 */
private ActionForward handleNdrProxy(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
	NDRForm ndrForm = (NDRForm) form;

	String verb = request.getParameter("verb");
	if (verb == null || verb.trim().length() == 0)
		throw new Exception("no verb supplied");

	String handle = request.getParameter("handle");
	if (handle == null || handle.trim().length() == 0) {
		handle = null;
	}

	String inputXML = request.getParameter("inputXML");
	if (inputXML == null || inputXML.trim().length() == 0)
		throw new Exception("no inputXML supplied");

	// make sure the inputXML is well-formed
	Document doc = null;
	try {
		doc = DocumentHelper.parseText(inputXML);
		// prtln("\n===============\nproxyRequest\n" + inputXML);
	} catch (Throwable t) {
		prtlnErr("BAD inputXML: " + inputXML);
		throw new Exception("inputXML was not parsable XML");
	}

	NdrRequest ndrRequest = new NdrRequest();
	ndrRequest.setVerb(verb);
	ndrRequest.setHandle(handle);
	InfoXML proxyResponse = ndrRequest.submit(inputXML);

	doc = DocumentHelper.parseText(proxyResponse.getResponse());
	ndrForm.setProxyResponse(Dom4jUtils.prettyPrint(doc));
	return mapping.findForward("proxy.response");
}
 
Example 57
Project: joai-project   File: RendererHelper.java   Source Code and License 5 votes vote down vote up
/**
 *  NOT YET DOCUMENTED
 *
 * @param  target       NOT YET DOCUMENTED
 * @param  displayText  NOT YET DOCUMENTED
 * @param  borderColor  NOT YET DOCUMENTED
 */
public void attachElementDebugInfo(Element target, String displayText, String borderColor) {
	if (showElementDebugInfo) {
		Element info = DocumentHelper.createElement("div")
			.addAttribute("class", "element-debug-info");
		// s + "  (" + getLevel() + ")";
		info.addText(displayText);
		target.add(info);
		if (borderColor != null)
			target.addAttribute("style", "border__thin dashed " + borderColor);
	}
}
 
Example 58
Project: joai-project   File: RendererHelper.java   Source Code and License 5 votes vote down vote up
/**
 *  Creates a test for the existence of a node in the instance document at the
 *  given path
 *
 * @param  path  Description of the Parameter
 * @return       Element that performs test when embedded in JSP
 */
public Element nodeExistsTest(String path) {
	Element tester = DocumentHelper.createElement("logic__equal")
		.addAttribute("name", formBeanName)
		.addAttribute("property", "nodeExists(" + path + ")")
		.addAttribute("value", "true");
	return tester;
}
 
Example 59
Project: joai-project   File: RendererHelper.java   Source Code and License 5 votes vote down vote up
/**
 *  NOT YET DOCUMENTED
 *
 * @param  path  NOT YET DOCUMENTED
 * @return       NOT YET DOCUMENTED
 */
public Element nodeHasChildrenTest(String path) {
	Element tester = DocumentHelper.createElement("logic__greaterThan")
		.addAttribute("name", formBeanName)
		.addAttribute("property", "childElementCountOf(" + path + ")")
		.addAttribute("value", "0");
	return tester;
}
 
Example 60
Project: joai-project   File: RendererHelper.java   Source Code and License 5 votes vote down vote up
/**
 *  NOT YET DOCUMENTED
 *
 * @param  path  NOT YET DOCUMENTED
 * @return       NOT YET DOCUMENTED
 */
public Element nodeHasMembersTest(String path) {
	Element tester = DocumentHelper.createElement("logic__greaterThan")
		.addAttribute("name", formBeanName)
		.addAttribute("property", "memberCountOf(" + path + ")")
		.addAttribute("value", "0");
	return tester;
}