org.dom4j.Element Java Examples

The following examples show how to use org.dom4j.Element. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StackImap.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
/** Creates a specific Msg */
@Override
public Msg parseMsgFromXml(ParseFromXmlContext context, Element root, Runner runner) throws Exception
{
    Msg msg = super.parseMsgFromXml(context, root, runner);

    String channelName = root.attributeValue("channel");
    if (existsChannel(channelName))
    {
        ChannelImap channel = (ChannelImap) getChannel(channelName);

        // code imported from channel. we must now set the transaction ID BEFORE
        // sending the request (modifications on the generic stack)
        msg.setTransactionId(channel.getTransactionId());

        if(channel.isServer())//pour un server (envoi d'une reponse)
        {
            channel.checkTransationResponse(msg, channel.getChannel().getRemoteHost() + channel.getChannel().getRemotePort());
        }
        else//pour un client (envoi d'une requete)
        {
            msg = (MsgImap) channel.checkTransationRequest(msg, channel.getChannel().getLocalHost() + channel.getChannel().getLocalPort());
        }
    }
    return msg;
}
 
Example #2
Source File: WeixinInMsgParser.java    From seed with Apache License 2.0 6 votes vote down vote up
private static WeixinInMsg doParse(String xml) throws DocumentException {
    Document doc = DocumentHelper.parseText(xml);
    Element root = doc.getRootElement();
    String toUserName = root.elementText("ToUserName");
    String fromUserName = root.elementText("FromUserName");
    long createTime = Long.parseLong(root.elementText("CreateTime"));
    String msgType = root.elementText("MsgType");
    if("text".equals(msgType)){
        return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("image".equals(msgType)){
        return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("location".equals(msgType)){
        return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("link".equals(msgType)){
        return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    if("event".equals(msgType)){
        return parseInEventMsg(root, toUserName, fromUserName, createTime, msgType);
    }
    throw new RuntimeException("未知的消息类型" + msgType + ", 请查阅微信公众平台开发者文档https://mp.weixin.qq.com/wiki");
}
 
Example #3
Source File: ChoiceQuestion.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Feedback, solution and hints in case of failure
 * 
 * @param resprocessingXML
 */

private void buildRespconditionKprim_fail(final Element resprocessingXML) {
    final Element respcondition_fail = resprocessingXML.addElement("respcondition");
    respcondition_fail.addAttribute("title", "Fail");
    respcondition_fail.addAttribute("continue", "Yes");
    final Element conditionvar = respcondition_fail.addElement("conditionvar");
    final Element not = conditionvar.addElement("not");
    final Element and = not.addElement("and");

    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final ChoiceResponse choice = (ChoiceResponse) i.next();
        Element varequal;
        varequal = and.addElement("varequal");
        varequal.addAttribute("respident", getIdent());
        varequal.addAttribute("case", "Yes");
        if (choice.isCorrect()) {
            varequal.addText(choice.getIdent() + ":correct");
        } else { // incorrect answers
            varequal.addText(choice.getIdent() + ":wrong");
        }
    }
    QTIEditHelperEBL.addFeedbackFail(respcondition_fail);
    QTIEditHelperEBL.addFeedbackHint(respcondition_fail);
    QTIEditHelperEBL.addFeedbackSolution(respcondition_fail);
}
 
Example #4
Source File: Dom4j.java    From cuba with Apache License 2.0 6 votes vote down vote up
public static void storeMap(Element parentElement, Map<String, String> map) {
    if (map == null) {
        return;
    }

    Element mapElem = parentElement.addElement("map");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        Element entryElem = mapElem.addElement("entry");
        entryElem.addAttribute("key", entry.getKey());
        Element valueElem = entryElem.addElement("value");
        if (entry.getValue() != null) {
            String value = StringEscapeUtils.escapeXml11(entry.getValue());
            valueElem.setText(value);
        }
    }
}
 
Example #5
Source File: CheckboxesTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void spanElementCustomizable() throws Exception {
	this.tag.setPath("stringArray");
	this.tag.setItems(new Object[] {"foo", "bar", "baz"});
	this.tag.setElement("element");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);
	String output = getOutput();

	// wrap the output so it is valid XML
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element spanElement = (Element) document.getRootElement().elements().get(0);
	assertEquals("element", spanElement.getName());
}
 
Example #6
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static ColumnResult buildColumnResult(
			Element columnResultElement,
			XMLContext.Default defaults,
			ClassLoaderAccess classLoaderAccess) {
//		AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
//		copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
//		return AnnotationFactory.create( columnResultDescriptor );

		AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
		copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
		final String columnTypeName = columnResultElement.attributeValue( "class" );
		if ( StringHelper.isNotEmpty( columnTypeName ) ) {
			columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) );
		}
		return AnnotationFactory.create( columnResultDescriptor );
	}
 
Example #7
Source File: XmlHelper.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static void removeStringValue(File file, String key) throws IOException, DocumentException {

        if (!file.exists()) {
            return;
        }

        Document document = XmlHelper.readXml(file);// Read the XML file
        Element root = document.getRootElement();// Get the root node
        List<? extends Node> nodes = root.selectNodes("//string");
        for (Node node : nodes) {
            Element element = (Element)node;
            String name = element.attributeValue("name");
            if (key.equals(name)) {
                element.getParent().remove(element);
                break;
            }
        }
        // sLogger.warn("[resxmlediter] add " + key + " to " + file.getAbsolutePath());
        XmlHelper.saveDocument(document, file);
    }
 
Example #8
Source File: ItemStackFlag.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
static void serializeObject(Object value, Element element) {
	element.addAttribute("type", value.getClass().getName());
	
	if (value instanceof Collection<?>) {
		Collection<?> collection = (Collection<?>) value;
		Iterator<?> iterator = collection.iterator();
		
		while (iterator.hasNext()) {
			Object val = iterator.next();
			
			Element valElement = element.addElement("entry");
			serializeObject(val, valElement);
		}
	} else {
		element.addText(value.toString());
	}
}
 
Example #9
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Copy a string attribute from an XML element to an annotation descriptor. The name of the annotation attribute is
 * explicitely given.
 *
 * @param annotation annotation where to copy to the attribute.
 * @param element XML element from where to copy the attribute.
 * @param annotationAttributeName name of the annotation attribute where to copy.
 * @param attributeName name of the XML attribute to copy.
 * @param mandatory whether the attribute is mandatory.
 */
private static void copyStringAttribute(
		final AnnotationDescriptor annotation, final Element element,
		final String annotationAttributeName, final String attributeName, boolean mandatory) {
	String attribute = element.attributeValue( attributeName );
	if ( attribute != null ) {
		annotation.setValue( annotationAttributeName, attribute );
	}
	else {
		if ( mandatory ) {
			throw new AnnotationException(
					element.getName() + "." + attributeName + " is mandatory in XML overriding. " + SCHEMA_VALIDATION
			);
		}
	}
}
 
Example #10
Source File: ImportPreferences.java    From unitime with Apache License 2.0 6 votes vote down vote up
public DepartmentalInstructor importInstructor(Element element) {
	String deptCode = element.attributeValue("deptCode");
	String puid = element.attributeValue("puid");
	DepartmentalInstructor instructor = (DepartmentalInstructor) hibSession.
		createQuery("select id from DepartmentalInstructor id where id.department.deptCode=:deptCode and id.department.sessionId=:sessionId and id.puid=:puid").
		setString("deptCode", deptCode).
		setLong("sessionId", iSession.getUniqueId().longValue()).
		setString("puid",puid).
		uniqueResult();
	if (instructor==null) {
		sLog.error("Unable to find instructor "+puid+" for department "+deptCode);
		return null;
	}
	sLog.info("Processing instructor "+instructor.getLastName()+" (puid:"+puid+")");
	
	importPreferences(instructor, element);

	hibSession.update(instructor);
	hibSession.flush();
	hibSession.refresh(instructor);
	return instructor;
}
 
Example #11
Source File: SurveyFileResourceValidator.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(final File unzippedDir) {
    // with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed.
    final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
    final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
    // getDocument(..) ensures that InputStream is closed in every case.
    final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
    // if doc is null an error loading the document occured
    if (doc == null) {
        return false;
    }
    final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
    for (final Iterator iter = metas.iterator(); iter.hasNext();) {
        final Element el_metafield = (Element) iter.next();
        final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
        final String label = el_label.getText();
        if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
            final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
            final String entry = el_entry.getText();
            return entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY);
        }
    }

    return false;
}
 
Example #12
Source File: ExamConflictStatisticsInfo.java    From unitime with Apache License 2.0 6 votes vote down vote up
CBSAssignment(CBSConstraint constraint, Element element) {
	iConstraint = constraint;
	iExamId = Long.valueOf(element.attributeValue("exam"));
	iExamName = element.attributeValue("name");
	iExamPref = element.attributeValue("pref");
	iRoomIds = new Vector();
	iRoomNames = new Vector();
	iRoomPrefs = new Vector();
	for (Iterator i=element.elementIterator("room");i.hasNext();) {
		Element r = (Element)i.next();
		iRoomIds.addElement(Integer.valueOf(r.attributeValue("id")));
		iRoomNames.addElement(r.attributeValue("name"));
		iRoomPrefs.addElement(Integer.valueOf(r.attributeValue("pref")));
	}
	iPeriodId = Long.valueOf(element.attributeValue("period"));
	iPeriodName = element.attributeValue("periodName");
	iPeriodPref = Integer.parseInt(element.attributeValue("periodPref"));
	incCounter(Integer.parseInt(element.attributeValue("cnt")));
}
 
Example #13
Source File: CheckboxTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void withMultiValueUnchecked() throws Exception {
	this.tag.setPath("stringArray");
	this.tag.setValue("abc");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();

	// wrap the output so it is valid XML
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element checkboxElement = (Element) document.getRootElement().elements().get(0);
	assertEquals("input", checkboxElement.getName());
	assertEquals("checkbox", checkboxElement.attribute("type").getValue());
	assertEquals("stringArray", checkboxElement.attribute("name").getValue());
	assertNull(checkboxElement.attribute("checked"));
	assertEquals("abc", checkboxElement.attribute("value").getValue());
}
 
Example #14
Source File: InMsgParser.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 消息类型
 * 1:text 文本消息
 * 2:image 图片消息
 * 3:voice 语音消息
 * 4:video 视频消息
 *	shortvideo 小视频消息
 * 5:location 地址位置消息
 * 6:link 链接消息
 * 7:event 事件
 */
private static InMsg doParse(String xml) throws DocumentException {
	Document doc = DocumentHelper.parseText(xml);
	Element root = doc.getRootElement();
	String toUserName = root.elementText("ToUserName");
	String fromUserName = root.elementText("FromUserName");
	Integer createTime = Integer.parseInt(root.elementText("CreateTime"));
	String msgType = root.elementText("MsgType");
	if ("text".equals(msgType))
		return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("image".equals(msgType))
		return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("voice".equals(msgType))
		return parseInVoiceMsgAndInSpeechRecognitionResults(root, toUserName, fromUserName, createTime, msgType);
	if ("video".equals(msgType))
		return parseInVideoMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("shortvideo".equals(msgType))	 //支持小视频
		return parseInShortVideoMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("location".equals(msgType))
		return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("link".equals(msgType))
		return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType);
	if ("event".equals(msgType))
		return parseInEvent(root, toUserName, fromUserName, createTime, msgType);
	throw new RuntimeException("无法识别的消息类型 " + msgType + ",请查阅微信公众平台开发文档");
}
 
Example #15
Source File: XmppControllerImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests adding, removing IQ listeners and handling IQ stanzas.
 */
@Test
public void handlePackets() {
    // IQ packets
    IQ iq = new IQ();
    Element element = new DefaultElement("pubsub", Namespace.get(testNamespace));
    iq.setChildElement(element);
    agent.processUpstreamEvent(jid1, iq);
    assertThat(testXmppIqListener.handledIqs, hasSize(1));
    agent.processUpstreamEvent(jid2, iq);
    assertThat(testXmppIqListener.handledIqs, hasSize(2));
    // Message packets
    Packet message = new Message();
    agent.processUpstreamEvent(jid1, message);
    assertThat(testXmppMessageListener.handledMessages, hasSize(1));
    agent.processUpstreamEvent(jid2, message);
    assertThat(testXmppMessageListener.handledMessages, hasSize(2));
    Packet presence = new Presence();
    agent.processUpstreamEvent(jid1, presence);
    assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(1));
    agent.processUpstreamEvent(jid2, presence);
    assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(2));
}
 
Example #16
Source File: FilterDelegateImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void applyMaxResultsSettings(Element element) {
    Element maxResultsEl = element.element("maxResults");
    if (maxResultsEl != null && !maxResultsEl.getText().equals("") && isMaxResultsLayoutVisible()) {
        try {
            int maxResultsFromSettings = Integer.parseInt(maxResultsEl.getText());
            adapter.setMaxResults(maxResultsFromSettings);
            initMaxResults();

            // set to false cause it's initial value from settings
            maxResultValueChanged = false;
        } catch (NumberFormatException ex) {
            log.error("Error on parsing maxResults setting value", ex);
        }
    }
}
 
Example #17
Source File: MultiUserChatServiceImpl.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Adds an extra Disco identity to the list of identities returned for the conference service.
 * @param category Category for identity.  e.g. conference
 * @param name Descriptive name for identity.  e.g. Public Chatrooms
 * @param type Type for identity.  e.g. text
 */
@Override
public void addExtraIdentity(final String category, final String name, final String type) {
    final Element identity = DocumentHelper.createElement("identity");
    identity.addAttribute("category", category);
    identity.addAttribute("name", name);
    identity.addAttribute("type", type);
    extraDiscoIdentities.add(identity);
}
 
Example #18
Source File: LocalMUCRole.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void updatePresence() {
    if (extendedInformation != null && presence != null) {
        // Remove any previous extendedInformation, then re-add it.
        Element mucUser = presence.getElement().element(QName.get("x", "http://jabber.org/protocol/muc#user"));
        if (mucUser != null) {
            // Remove any previous extendedInformation, then re-add it.
            presence.getElement().remove(mucUser);
        }
        Element exi = extendedInformation.createCopy();
        presence.getElement().add(exi);
    }
}
 
Example #19
Source File: AbstractParser.java    From uflo with Apache License 2.0 5 votes vote down vote up
protected List<UserData> parseUserData(Element element){
	List<UserData> data=new ArrayList<UserData>();
	for(Object object:element.elements()){
		if(!(object instanceof Element))continue;
		Element ele=(Element)object;
		if(!ele.getName().equals("user-data"))continue;
		data.add(new UserData(ele.attributeValue("key"),ele.attributeValue("value")));
	}
	return data;
}
 
Example #20
Source File: PointInTimeDataImport.java    From unitime with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void initializeTeachingResponsibilityData(Element rootElement) throws Exception {
	for (TeachingResponsibility instructorTeachingResponsibility : TeachingResponsibility.getInstructorTeachingResponsibilities()) {
		teachingResponsibilitiesByRef.put(instructorTeachingResponsibility.getReference(), instructorTeachingResponsibility);
	}
	for (TeachingResponsibility coordinatorTeachingResponsibility : TeachingResponsibility.getCoordinatorTeachingResponsibilities()) {
		teachingResponsibilitiesByRef.put(coordinatorTeachingResponsibility.getReference(), coordinatorTeachingResponsibility);
	}
			
	Element responsibilitiesElement = rootElement.element(PointInTimeDataExport.sTeachingResponsibilitiesElementName);
	for(Element responsibilityElement : (List<Element>) responsibilitiesElement.elements()){
		elementTeachingResponsibility(responsibilityElement);
	}
	
}
 
Example #21
Source File: RadioButtonsTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void withMultiValueArray() throws Exception {
	this.tag.setPath("stringArray");
	this.tag.setItems(new Object[] {"foo", "bar", "baz"});
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();

	// wrap the output so it is valid XML
	output = "<doc>" + output + "</doc>";
	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element spanElement1 = (Element) document.getRootElement().elements().get(0);
	Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
	assertEquals("input", radioButtonElement1.getName());
	assertEquals("radio", radioButtonElement1.attribute("type").getValue());
	assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
	assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
	assertEquals("foo", radioButtonElement1.attribute("value").getValue());
	assertEquals("foo", spanElement1.getStringValue());
	Element spanElement2 = (Element) document.getRootElement().elements().get(1);
	Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
	assertEquals("input", radioButtonElement2.getName());
	assertEquals("radio", radioButtonElement2.attribute("type").getValue());
	assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
	assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
	assertEquals("bar", radioButtonElement2.attribute("value").getValue());
	assertEquals("bar", spanElement2.getStringValue());
	Element spanElement3 = (Element) document.getRootElement().elements().get(2);
	Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
	assertEquals("input", radioButtonElement3.getName());
	assertEquals("radio", radioButtonElement3.attribute("type").getValue());
	assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
	assertNull("not checked", radioButtonElement3.attribute("checked"));
	assertEquals("baz", radioButtonElement3.attribute("value").getValue());
	assertEquals("baz", spanElement3.getStringValue());
}
 
Example #22
Source File: ConnectorGenerator.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
private void parseConnector(Element tmp,ZipOutputStream out,String type,String folderName) throws Exception{
	String id = tmp.attributeValue("id");
	String packageName = tmp.attributeValue("package");
	
	String connectorXmlName = "";
	if(type.equals("flowConnector")){
		connectorXmlName = "FlowConnector.xml";
	}else if(type.equals("actorConnector")){
		connectorXmlName = "ActorConnector.xml";
	}else{
		throw new FoxBPMException("不支持的连接器类型:"+type);
	}
	
	String xmlFileName = packageName + "/" + connectorXmlName;
	String pngFileName = packageName + "/" + id + ".png";
	String xmlEntryName = folderName + "/" + id + "/" + connectorXmlName;
	String pngEntryName = folderName + "/" + id + "/" + id + ".png";
	
	InputStream xmlInputStream = ReflectUtil.getResourceAsStream(xmlFileName);
	if(xmlInputStream == null){
		log.error("文件:{}不存在,跳过处理,该连接器可能不可用!" ,xmlFileName);
		return;
	}else{
		generZip(xmlInputStream,xmlEntryName,out);
	}
	
	InputStream pngInputStream = ReflectUtil.getResourceAsStream(pngFileName);
	if(pngInputStream == null){
		pngFileName = packageName + "/" + id + ".jpg";
		pngInputStream = ReflectUtil.getResourceAsStream(pngFileName);
	}
	if(pngInputStream == null){
		log.error("文件:{}不存在,跳过处理,该连接器可能不可用!" ,pngFileName);
	}else{
		generZip(pngInputStream,pngEntryName,out);
	}
	
}
 
Example #23
Source File: PointInTimeDataImport.java    From unitime with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void elementClassEvent(Element classEventElement, PitClass pc) throws Exception {
	PitClassEvent pce = new PitClassEvent();
	pce.setPitClass(pc);
	pc.addTopitClassEvents(pce);
	pce.setEventName(getRequiredStringAttribute(classEventElement, PointInTimeDataExport.sNameAttribute, PointInTimeDataExport.sClassEventElementName));
	pce.setUniqueId((Long) getHibSession().save(pce));
	for(Element classMeetingElement : (List<Element>) classEventElement.elements()){
		elementClassMeeting(classMeetingElement, pce);
	}
}
 
Example #24
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Annotation getMarkerAnnotation(
		Class<? extends Annotation> clazz, Element element, XMLContext.Default defaults
) {
	Element subelement = element == null ? null : element.element( annotationToXml.get( clazz ) );
	if ( subelement != null ) {
		return AnnotationFactory.create( new AnnotationDescriptor( clazz ) );
	}
	else if ( defaults.canUseJavaAnnotations() ) {
		//TODO wonder whether it should be excluded so that user can undone it
		return getPhysicalAnnotation( clazz );
	}
	else {
		return null;
	}
}
 
Example #25
Source File: SelectTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void multipleForCollection() throws Exception {
	this.bean.setSomeList(new ArrayList());

	this.tag.setPath("someList");
	this.tag.setItems(Country.getCountries());
	this.tag.setItemValue("isoCode");
	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);

	String output = getOutput();
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();
	assertEquals(2, rootElement.elements().size());

	Element selectElement = rootElement.element("select");
	assertEquals("select", selectElement.getName());
	assertEquals("someList", selectElement.attribute("name").getValue());
	assertEquals("multiple", selectElement.attribute("multiple").getValue());

	List children = selectElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element inputElement = rootElement.element("input");
	assertNotNull(inputElement);
}
 
Example #26
Source File: ScreensHelper.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String resolveLookupDatasource(Element window) {
    String lookupId = window.attributeValue("lookupComponent");
    Element lookupElement = null;
    if (StringUtils.isNotBlank(lookupId)) {
        lookupElement = elementByID(window, lookupId);
    }

    return lookupElement != null
            ? findLookupElementDataAttributeId(lookupElement, "datasource")
            : null;
}
 
Example #27
Source File: TaskNode.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
Element addXMLElement(final Element parent)
{
  final Element el = parent.addElement("task").addAttribute("id", String.valueOf(this.getId()))
      .addAttribute("name", this.task.getTitle());
  if (this.childs != null) {
    for (final TaskNode node : this.childs) {
      node.addXMLElement(el);
    }
  }
  return el;
}
 
Example #28
Source File: OptionsTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void withCollectionAndDynamicAttributes() throws Exception {
	String dynamicAttribute1 = "attr1";
	String dynamicAttribute2 = "attr2";

	getPageContext().setAttribute(
			SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));

	this.tag.setItems(Country.getCountries());
	this.tag.setItemValue("isoCode");
	this.tag.setItemLabel("name");
	this.tag.setId("myOption");
	this.tag.setCssClass("myClass");
	this.tag.setOnclick("CLICK");
	this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
	this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2);

	int result = this.tag.doStartTag();
	assertEquals(Tag.SKIP_BODY, result);
	String output = getOutput();
	output = "<doc>" + output + "</doc>";

	SAXReader reader = new SAXReader();
	Document document = reader.read(new StringReader(output));
	Element rootElement = document.getRootElement();

	List children = rootElement.elements();
	assertEquals("Incorrect number of children", 4, children.size());

	Element element = (Element) rootElement.selectSingleNode("option[@value = 'UK']");
	assertEquals("UK node not selected", "selected", element.attribute("selected").getValue());
	assertEquals("myOption3", element.attribute("id").getValue());
	assertEquals("myClass", element.attribute("class").getValue());
	assertEquals("CLICK", element.attribute("onclick").getValue());
	assertEquals(dynamicAttribute1, element.attribute(dynamicAttribute1).getValue());
	assertEquals(dynamicAttribute2, element.attribute(dynamicAttribute2).getValue());
}
 
Example #29
Source File: Config2Object.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Object convert(@Comments("xml content") String content,
                             @Comments("xml structure with javabean class") Class<?> cls)
        throws DocumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if (null == cls) return null;
    parseFieldsAttribute(cls);
    //将xml格式的字符串转换成Document对象
    Document doc = DocumentHelper.parseText(content);
    //获取根节点
    Element root = doc.getRootElement();
    return mergerXmlNodeAndField(root, configClasssAttr);
}
 
Example #30
Source File: ScreenSettings.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Save settings of screen.
 *
 * @param screen   screen
 * @param settings settings
 */
public void saveSettings(Screen screen, Settings settings) {
    checkNotNullArgument(screen);
    checkNotNullArgument(settings);

    walkComponents(
            screen.getWindow(),
            (component, name) -> {
                if (component.getId() != null
                        && component instanceof HasSettings) {
                    log.trace("Saving settings for {} : {}", name, component);

                    Element e = settings.get(name);
                    boolean modified = ((HasSettings) component).saveSettings(e);

                    if (component instanceof HasPresentations
                            && ((HasPresentations) component).isUsePresentations()) {
                        Object def = ((HasPresentations) component).getDefaultPresentationId();
                        e.addAttribute("presentation", def != null ? def.toString() : "");
                        Presentations presentations = ((HasPresentations) component).getPresentations();
                        if (presentations != null) {
                            presentations.commit();
                        }
                    }
                    if (modified) {
                        settings.setModified(true);
                    }
                }
            }
    );
    settings.commit();
}