Java Code Examples for org.dom4j.Element.addElement()

The following are Jave code examples for showing how to use addElement() of the org.dom4j.Element class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: unitimes   File: StudentExport.java   View Source Code Vote up 6 votes
@Override
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();
		
		Element root = document.addElement("students");
        root.addAttribute("campus", session.getAcademicInitiative());
        root.addAttribute("year", session.getAcademicYear());
        root.addAttribute("term", session.getAcademicTerm());
        
        document.addDocType("students", "-//UniTime//UniTime Students DTD/EN", "http://www.unitime.org/interface/Student.dtd");
        
        for (Student student: (List<Student>)getHibSession().createQuery(
        		"select s from Student s where s.session.uniqueId = :sessionId")
        		.setLong("sessionId", session.getUniqueId()).list()) {
        	
        	Element studentEl = root.addElement("student");
        	exportStudent(studentEl, student);
        }
        
           commitTransaction();
       } catch (Exception e) {
           fatal("Exception: "+e.getMessage(),e);
           rollbackTransaction();
	}
}
 
Example 2
Project: joai-project   File: EditorRenderer.java   View Source Code Vote up 6 votes
/**
 *  Render open/close widget for this element.
 *
 * @return    The collapseWidget value
 */
protected Element getCollapseWidget() {
	Element img_template = df.createElement("img")
		.addAttribute("id", "${id}_img")
		.addAttribute("border", "0")
		.addAttribute("hspace", "3")
		.addAttribute("height", "12")
		.addAttribute("width", "12");

	Element choose = df.createElement("c__choose");

	Element isOpen = choose.addElement("c__when")
		.addAttribute("test", "${" + formBeanName + ".collapseBean.isOpen}");

	Element openedImg = img_template.createCopy();
	isOpen.add(openedImg);
	openedImg.addAttribute("src", "../images/opened.gif");

	Element otherwise = choose.addElement("c__otherwise");
	Element closedImg = (Element) img_template.createCopy();
	otherwise.add(closedImg);
	closedImg.addAttribute("src", "../images/closed.gif");

	return choose;
}
 
Example 3
Project: automat   File: XmlUtil.java   View Source Code Vote up 6 votes
/**
 * 将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 4
Project: iBase4J-Common   File: XmlUtil.java   View Source Code Vote up 6 votes
/**
 * 将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 5
Project: joai-project   File: User.java   View Source Code Vote up 6 votes
/**
 *  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 6
Project: directory-ldap-api   File: AbstractRequestDsml.java   View Source Code Vote up 6 votes
/**
 * Creates the Request Element and adds RequestID and Controls.
 *
 * @param root the root element
 * @return the Request Element of the given name containing
 */
@Override
public Element toDsml( Element root )
{
    Element element = root.addElement( getRequestName() );

    // Request ID
    int requestID = getDecorated().getMessageId();
    if ( requestID > 0 )
    {
        element.addAttribute( "requestID", Integer.toString( requestID ) );
    }

    // Controls
    ParserUtils.addControls( getCodecService(), element, getDecorated().getControls().values() );

    return element;
}
 
Example 7
Project: JAVA-   File: XmlUtil.java   View Source Code Vote up 6 votes
/**
 * 将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 8
Project: pndao   File: DaoGenHelper.java   View Source Code Vote up 5 votes
private Consumer<String> addUpdateFor(DaoGen daoGen, String key, MapperMethod method, Element root) {
    return (prefix) -> {
        Element sql = root.addElement("update");
        sql.addComment(COMMENT);
        sql.addAttribute("id", key);

        StringBuilder updateSql = new StringBuilder(50);
        updateSql.append("update ")
                .append(method.getDaoEnv().getTableName())
                .append(" set \n");

        String left = key.replaceFirst(prefix, "");
        List<String> fields = split(left, daoGen.separator()).stream().map(this::lowerFirst).collect(Collectors.toList());
        fields.add(method.getDaoEnv().getUpdateTime());
        String pk = daoGen.primaryKey();
        updateSql.append(
                Joiner.on(", ").join(
                        fields.stream().filter((field -> !field.equals(pk) &&
                                !method.getDaoEnv().getCreateTime().equals(field)))
                                .map((field -> {
                                    if (method.getDaoEnv().getUpdateTime().equals(field))
                                        return "`" + field + "` = " + "now() ";
                                    else return "`" + field + "` = " + "#{" + field + "} ";
                                }))
                                .iterator()));

        updateSql.append("Where `")
                .append(pk)
                .append("` = ")
                .append("#{")
                .append(pk)
                .append("}");
        sql.addText(updateSql.toString());
    };
}
 
Example 9
Project: EasyML   File: JoinNodeDef.java   View Source Code Vote up 5 votes
@Override
public void append2XML(Element root) {
	Element join = root.addElement("join");
	join.addAttribute("name", getName());

	NodeDef toNode = outNodes.iterator().next();
	join.addAttribute("to", toNode.getName());
}
 
Example 10
Project: unitimes   File: ScriptExportXML.java   View Source Code Vote up 5 votes
@Override
public void export(ExportHelper helper) throws IOException {
	String s = helper.getParameter("script");
	if (s == null) throw new IllegalArgumentException("No script provided, please set the script parameter.");
	Script script = ScriptDAO.getInstance().get(Long.valueOf(s));
	if (script == null) throw new IllegalArgumentException("Stript " + s + " does not exist.");
	
	helper.getSessionContext().checkPermission(Right.ScriptEdit);
	
	helper.setup("text/xml", script.getName().replace('/', '-').replace('\\', '-').replace(':', '-') + ".xml", false);
	
	Document document = DocumentHelper.createDocument();
	Element scriptEl = document.addElement("script");
       scriptEl.addAttribute("name", script.getName());
       if (script.getPermission() != null)
       	scriptEl.addAttribute("permission", script.getPermission());
       scriptEl.addAttribute("engine", script.getEngine());
       if (script.getDescription() != null)
       	scriptEl.addElement("description").add(new DOMCDATA(script.getDescription()));
       for (ScriptParameter parameter: script.getParameters()) {
       	Element paramEl = scriptEl.addElement("parameter");
       	paramEl.addAttribute("name", parameter.getName());
       	if (parameter.getLabel() != null)
       		paramEl.addAttribute("label", parameter.getLabel());
       	paramEl.addAttribute("type", parameter.getType());
       	if (parameter.getDefaultValue() != null)
       		paramEl.addAttribute("default", parameter.getDefaultValue());
       }
       if (script.getScript() != null)
       	scriptEl.addElement("body").add(new DOMCDATA(script.getScript()));
	scriptEl.addAttribute("created", new Date().toString());
       
       OutputStream out = helper.getOutputStream();
       new XMLWriter(out, OutputFormat.createPrettyPrint()).write(document);
}
 
Example 11
Project: unitimes   File: AcademicSessionSetupExport.java   View Source Code Vote up 5 votes
protected void exportManagers(Element root, Session session) {
	Element managersEl = root.addElement("managers");
	for (TimetableManager m: new TreeSet<TimetableManager>((List<TimetableManager>)getHibSession().createQuery(
			"select distinct m from TimetableManager m inner join m.departments d where d.session.uniqueId = :sessionId"
			).setLong("sessionId", session.getUniqueId()).list())) {
		Element managerEl = managersEl.addElement("manager");
		managerEl.addAttribute("externalId", m.getExternalUniqueId());
		if (m.getFirstName() != null)
			managerEl.addAttribute("firstName", m.getFirstName());
		if (m.getMiddleName() != null)
			managerEl.addAttribute("middleName", m.getMiddleName());
		if (m.getLastName() != null)
			managerEl.addAttribute("lastName", m.getLastName());
		if (m.getAcademicTitle() != null)
			managerEl.addAttribute("acadTitle", m.getAcademicTitle());
		if (m.getEmailAddress() != null)
			managerEl.addAttribute("email", m.getEmailAddress());
		if (m.getFirstName() != null)
			managerEl.addAttribute("firstName", m.getFirstName());
		for (Department d: m.getDepartments()) {
			if (session.equals(d.getSession()))
				managerEl.addElement("department").addAttribute("code", d.getDeptCode());
		}
		for (ManagerRole r: m.getManagerRoles()) {
			Element roleEl = managerEl.addElement("role");
			roleEl.addAttribute("reference", r.getRole().getReference());
			if (r.getPrimary() != null && r.getPrimary().booleanValue())
				roleEl.addAttribute("primary", "true");
			if (r.getReceiveEmails() != null)
				roleEl.addAttribute("emails", r.getReceiveEmails() ? "true" : "false");
		}
	}
}
 
Example 12
Project: unitimes   File: AcademicSessionSetupExport.java   View Source Code Vote up 5 votes
protected void exportSolverGroups(Element root, Session session) {
	Element groupsEl = root.addElement("solverGroups");
	for (SolverGroup g: new TreeSet<SolverGroup>((List<SolverGroup>)getHibSession().createQuery(
			"from SolverGroup where session = :sessionId").setLong("sessionId", session.getUniqueId()).list())) {
		Element groupEl = groupsEl.addElement("solverGroup");
		groupEl.addAttribute("abbreviation", g.getAbbv());
		if (g.getName() != null)
			groupEl.addAttribute("name", g.getName());
		for (TimetableManager m: g.getTimetableManagers())
			groupEl.addElement("manager").addAttribute("externalId", m.getExternalUniqueId());
		for (Department d: g.getDepartments())
			groupEl.addElement("department").addAttribute("code", d.getDeptCode());
	}
}
 
Example 13
Project: unitimes   File: PermissionsExport.java   View Source Code Vote up 5 votes
public void saveXml(Document document, Session session, Properties parameters) throws Exception {
	try {
		beginTransaction();

        Element root = document.addElement("permissions");
        root.addAttribute("created", new Date().toString());

        document.addDocType("permissions", "-//UniTime//DTD University Course Timetabling/EN", "http://www.unitime.org/interface/Permissions.dtd");
        
		for (Roles role: RolesDAO.getInstance().findAll(getHibSession(), Order.asc("abbv"))) {
			Element r = root.addElement("role");
			r.addAttribute("reference", role.getReference());
			r.addAttribute("name", role.getAbbv());
			r.addAttribute("manager", role.isManager() ? "true" : "false");
			r.addAttribute("enabled", role.isEnabled() ? "true" : "false");
			r.addAttribute("instructor", role.isInstructor() ? "true" : "false");
			for (Right right: Right.values()) {
				if (role.hasRight(right))
					r.addElement("right").setText(right.name());
			}
		}

        commitTransaction();
    } catch (Exception e) {
        fatal("Exception: "+e.getMessage(),e);
        rollbackTransaction();
    }
}
 
Example 14
Project: unitimes   File: ExportPreferences.java   View Source Code Vote up 5 votes
public void exportClassInstructor(Element parent, ClassInstructor classInstructor) {
	Element el = parent.addElement("instructor");
	el.addAttribute("uniqueId", classInstructor.getInstructor().getUniqueId().toString());
	el.addAttribute("isLead", classInstructor.isLead().toString());
	el.addAttribute("percentShare", classInstructor.getPercentShare().toString());
	el.addAttribute("puid", classInstructor.getInstructor().getExternalUniqueId());
	if (classInstructor.getResponsibility() != null)
		el.addAttribute("responsibility", classInstructor.getResponsibility().getReference());
}
 
Example 15
Project: directory-ldap-api   File: CompareRequestDsml.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public Element toDsml( Element root )
{
    Element element = super.toDsml( root );

    CompareRequest request = getDecorated();

    // Dn
    if ( request.getName() != null )
    {
        element.addAttribute( "dn", request.getName().getName() );
    }

    // Assertion
    Element assertionElement = element.addElement( "assertion" );
    if ( request.getAttributeId() != null )
    {
        assertionElement.addAttribute( "name", request.getAttributeId() );
    }
    if ( request.getAssertionValue() != null )
    {
        assertionElement.addElement( "value" ).setText( request.getAssertionValue().getValue() );
    }

    return element;
}
 
Example 16
Project: unitimes   File: AcademicSessionSetupExport.java   View Source Code Vote up 5 votes
protected void exportStudentGroups(Element root, Session session) {
	Element groupsEl = root.addElement("studentGroups");
	for (StudentGroup group: (List<StudentGroup>)getHibSession().createQuery(
			"from StudentGroup where session = :sessionId order by groupAbbreviation").setLong("sessionId", session.getUniqueId()).list()) {
		Element groupEl = groupsEl.addElement("studentGroup");
		if (group.getExternalUniqueId() != null)
			groupEl.addAttribute("externalId", group.getExternalUniqueId());
		if (group.getGroupAbbreviation() != null)
			groupEl.addAttribute("code", group.getGroupAbbreviation());
		if (group.getGroupName() != null)
			groupEl.addAttribute("name", group.getGroupName());
	}
}
 
Example 17
Project: PackagePlugin   File: FileUtil.java   View Source Code Vote up 4 votes
/**
 * 保存http请求信息到xml
 *
 * @param hc
 * @return
 * @throws Exception
 */
public static boolean saveHttpConfig(HttpConfig hc) throws Exception {
    SAXReader reader = new SAXReader();
    File xml = new File(HTTP_CONFIG_FILE);
    Document doc = null;
    Element root = null;
    boolean isNew = true;
    if (!xml.exists()) {
        doc = DocumentHelper.createDocument();
        root = DocumentHelper.createElement("root");
        root.addElement("configs");
        doc.add(root);
    }
    if (doc == null) {
        try (FileInputStream in = new FileInputStream(xml); Reader read = new InputStreamReader(in, "UTF-8")) {
            doc = reader.read(read);
            root = doc.getRootElement();
        }
    }
    Element cfg = (Element) root.selectSingleNode("/root/configs");
    Element e = (Element) root.selectSingleNode("/root/configs/config[@name='" + hc.getName() + "']");
    if (e != null) {
        isNew = false;
        cfg.remove(e);
    }
    CONFIG_MAP.put(hc.getName(), hc);

    Element cfg1 = cfg.addElement("config");
    cfg1.addAttribute("name", hc.getName());
    cfg1.addAttribute("encodeType", hc.getEncodeType());
    cfg1.addAttribute("charset", hc.getCharset());
    cfg1.addAttribute("requestType", hc.getRequestType());
    cfg1.addAttribute("sendXML", hc.getSendXML().toString());
    cfg1.addAttribute("packHead", hc.getPackHead().toString());
    cfg1.addAttribute("lowercaseEncode", hc.getLowercaseEncode().toString());

    cfg1.addElement("url").setText(hc.getUrl());
    cfg1.addElement("header").setText(hc.getHeaderStr());
    cfg1.addElement("parameter").setText(hc.getParameterStr());
    cfg1.addElement("encodeField").setText(hc.getEncodeFieldName());
    cfg1.addElement("encodeKey").setText(hc.getEncodeKey());

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format);
    writer.write(doc);
    writer.close();
    return isNew;
}
 
Example 18
Project: joai-project   File: MdeMultiChoice.java   View Source Code Vote up 4 votes
/**
 *  Renders input that is presented when a choice has not yet been made for
 *  this element.
 *
 * @return    jsp element for firstChoiceSelect input
 */
Element firstChoiceSelect() {
	// check for an empty choice (does the parent (aka xpath) have no memebers)?
	Element newChoiceTest = DocumentHelper.createElement("logic__empty")
		.addAttribute("name", formBeanName)
		.addAttribute("property", "membersOf(" + xpath + "/*)");

	Element newChoiceDiv = DocumentHelper.createElement("div");
	newChoiceTest.add(newChoiceDiv);

	/*
			Add a hidden element here so that the validator
			will detect non-made choices.
		*/
	Element hidden = newChoiceDiv.addElement("input")
		.addAttribute("type", "hidden")
		.addAttribute("name", "valueOf(" + xpath + ")")
		.addAttribute("value", "");

	Element label = DocumentHelper.createElement("div")
		.addAttribute("class", "field-label");

	Element textElement = label.addElement("div");

	if (this.choiceCompositor.isRequiredChoice()) {
		textElement.addAttribute("class", "required-choice");
		textElement.setText("required choice");
	}
	else {
		textElement.addAttribute("class", "optional-choice");
		textElement.setText("optional choice");
	}

	Element input = getChoiceSelect();

	Element choiceField =
		this.renderer.getRenderedField(xpath, label, input);

	// add label and value elements as a table to newChoiceDiv
	newChoiceDiv.add(choiceField);
	return newChoiceTest;
}
 
Example 19
Project: directory-ldap-api   File: AddRequestDsml.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public Element toDsml( Element root )
{
    Element element = super.toDsml( root );

    // Dn
    if ( getDecorated().getEntry() != null )
    {
        element.addAttribute( "dn", getDecorated().getEntry().getDn().getName() );
    }

    // Attributes
    Entry entry = getDecorated().getEntry();
    if ( entry != null )
    {
        for ( Attribute attribute : entry )
        {
            Element attributeElement = element.addElement( "attr" );
            attributeElement.addAttribute( "name", attribute.getId() );
            // Looping on Values
            for ( Value value : attribute )
            {
                if ( ParserUtils.needsBase64Encoding( value.getValue() ) )
                {
                    Namespace xsdNamespace = new Namespace( "xsd", ParserUtils.XML_SCHEMA_URI );
                    Namespace xsiNamespace = new Namespace( "xsi", ParserUtils.XML_SCHEMA_INSTANCE_URI );
                    attributeElement.getDocument().getRootElement().add( xsdNamespace );
                    attributeElement.getDocument().getRootElement().add( xsiNamespace );

                    Element valueElement = attributeElement.addElement( "value" ).addText(
                        ParserUtils.base64Encode( value.getValue() ) );
                    valueElement
                        .addAttribute( new QName( "type", xsiNamespace ), "xsd:" + ParserUtils.BASE64BINARY );
                }
                else
                {
                    attributeElement.addElement( "value" ).addText( value.getValue() );
                }
            }
        }
    }

    return element;
}
 
Example 20
Project: joai-project   File: DCSSchemEditAction.java   View Source Code Vote up 4 votes
/**
 *  Supports asyncronous request in support of the ServiceHelper (to obtain
 *  values from the current instance document).
 *
 *@param  mapping        the ActionMapping
 *@param  form           the ActionForm
 *@param  request        the Request
 *@param  response       the Response
 *@return                Description of the Return Value
 *@exception  Exception  Description of the Exception
 */
private ActionForward handleAsyncRequest(ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	SchemEditForm sef = (SchemEditForm) form;
	// update the DocMap so we are working with current data from the instance doc
	SchemEditValidator validator = getValidator(form, mapping, request);
	validator.updateMultiValueFields();

	sef.setAsyncJason("");
	CATServiceHelper helper = this.initSuggestionServiceHelper(sef);

	String field = request.getParameter("updatefield");
	Element asyncResponse = null;
	if (field == null) {
		throw new Exception("Update Field expected");
	} else if (field.equals("gradeRanges")) {
		asyncResponse = DocumentHelper.createElement("gradeRanges");
		
		// new approach - selectedOptionValues
		Element selectedValue = asyncResponse.addElement("startGrade");
		selectedValue.setText(helper.getDerivedCATStartGrade());
		selectedValue = asyncResponse.addElement("endGrade");
		selectedValue.setText(helper.getDerivedCATEndGrade());
	} else if (field.equals("keywords")) {
		// String [] gradeRanges = sef.getEnumerationValuesOf(helper.getKeywordPath());
		String[] keywords = helper.getRecordKeywords();
		asyncResponse = DocumentHelper.createElement("keywords");
		if (keywords != null) {
			for (int i = 0; i < keywords.length; i++) {
				Element keyword = DocumentHelper.createElement("keyword");
				keyword.setText(keywords[i]);
				asyncResponse.add(keyword);
			}
		}
	} else if (field.equals("description")) {
		// String [] gradeRanges = sef.getEnumerationValuesOf(helper.getKeywordPath());
		String description = helper.getRecordDescription();
		asyncResponse = DocumentHelper.createElement("description");
		asyncResponse.setText (description);
	} else {
		throw new Exception("unhandled field: " + field);
	}

	Document responseDoc = DocumentHelper.createDocument(asyncResponse);
	// prtln ("\nAsync response" + Dom4jUtils.prettyPrint(responseDoc));
	org.json.JSONObject json = org.json.XML.toJSONObject(responseDoc.asXML());
	// prtln ("\nJson response");
	// prtln(json.toString(2));
	sef.setAsyncJason(json.toString());
	return mapping.findForward("async.json");
}