Java Code Examples for org.dom4j.Element#setText()

The following examples show how to use org.dom4j.Element#setText() . 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: SASLAuthentication.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public static Element getSASLMechanismsElement( ClientSession session )
{
    final Element result = DocumentHelper.createElement( new QName( "mechanisms", new Namespace( "", SASL_NAMESPACE ) ) );
    for (String mech : getSupportedMechanisms()) {
        if (mech.equals("EXTERNAL")) {
            boolean trustedCert = false;
            if (session.isSecure()) {
                final Connection connection = ( (LocalClientSession) session ).getConnection();
                if ( SKIP_PEER_CERT_REVALIDATION_CLIENT.getValue() ) {
                    // Trust that the peer certificate has been validated when TLS got established.
                    trustedCert = connection.getPeerCertificates() != null && connection.getPeerCertificates().length > 0;
                } else {
                    // Re-evaluate the validity of the peer certificate.
                    final TrustStore trustStore = connection.getConfiguration().getTrustStore();
                    trustedCert = trustStore.isTrusted( connection.getPeerCertificates() );
                }
            }
            if ( !trustedCert ) {
                continue; // Do not offer EXTERNAL.
            }
        }
        final Element mechanism = result.addElement("mechanism");
        mechanism.setText(mech);
    }
    return result;
}
 
Example 2
Source File: Tools.java    From testing_platform with Apache License 2.0 6 votes vote down vote up
public static void updateJmx(String jmxFilePath,String csvFilePath,String csvDataXpath) throws IOException, DocumentException {
    SAXReader reader = new SAXReader();
    Document documentNew =  reader.read(new File(jmxFilePath));
    List<Element> list = documentNew.selectNodes(csvDataXpath);
    if( list.size()>1 ){
        System.out.println("报错");
    }else{
        Element e = list.get(0);
        List<Element> eList = e.elements("stringProp");
        for(Element eStringProp:eList){
            if( "filename".equals( eStringProp.attributeValue("name") ) ){
                System.out.println("==========");
                System.out.println( eStringProp.getText() );
                eStringProp.setText(csvFilePath);
                break;
            }
        }
    }

    XMLWriter writer = new XMLWriter(new FileWriter(new File( jmxFilePath )));
    writer.write(documentNew);
    writer.close();

}
 
Example 3
Source File: Config.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private static void createGenralElement(Element rootElement, Config config) {

        Element nameElement = rootElement.addElement("name");
        nameElement.setText(config.getName());
        
        Element descriptionElement = rootElement.addElement("description");
        descriptionElement.setText(config.getDesc());
        
        Element authorElement = rootElement.addElement("author");
        authorElement.addAttribute("email", config.getAuthorEmail());
        authorElement.addAttribute("href", config.getAuthorHref());
        authorElement.setText(config.getAuthorName());
        
        Element contentElement = rootElement.addElement("content");
        contentElement.addAttribute("src", config.getContentSrc());

	}
 
Example 4
Source File: VersionedXmlDoc.java    From onedev with MIT License 5 votes vote down vote up
private static void unmarshallElement(HierarchicalStreamReader reader, Branch branch) {
	Element element = branch.addElement(reader.getNodeName());
	for (int i=0; i<reader.getAttributeCount(); i++) {
		String attributeName = reader.getAttributeName(i);
		String attributeValue = reader.getAttribute(i);
		element.addAttribute(attributeName, attributeValue);
	}
	if (StringUtils.isNotBlank(reader.getValue()))
		element.setText(reader.getValue().trim());
	while (reader.hasMoreChildren()) {
		reader.moveDown();
		unmarshallElement(reader, element);
		reader.moveUp();
	}
}
 
Example 5
Source File: AddMessages.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add BugCode elements.
 *
 * @param bugCodeSet
 *            all bug codes (abbrevs) referenced in the BugCollection
 */
private void addBugCodes(Set<String> bugCodeSet) {
    Element root = document.getRootElement();
    for (String bugCode : bugCodeSet) {
        Element element = root.addElement("BugCode");
        element.addAttribute("abbrev", bugCode);
        Element description = element.addElement("Description");
        description.setText(I18N.instance().getBugTypeDescription(bugCode));
    }
}
 
Example 6
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the specified subscriber. The event notification may
 * include information about the affected subscriptions.
 *
 * @param subscriberJID the subscriber JID that will get the notification.
 * @param notification the message to send to the subscriber.
 * @param subIDs the list of affected subscription IDs or null when node does not
 *        allow multiple subscriptions.
 */
protected void sendEventNotification(JID subscriberJID, Message notification,
        Collection<String> subIDs) {
    Element headers = null;
    if (subIDs != null) {
        // Notate the event notification with the ID of the affected subscriptions
        headers = notification.addChildElement("headers", "http://jabber.org/protocol/shim");
        for (String subID : subIDs) {
            Element header = headers.addElement("header");
            header.addAttribute("name", "SubID");
            header.setText(subID);
        }
    }
    
    // Verify that the subscriber JID is currently available to receive notification
    // messages. This is required because the message router will deliver packets via 
    // the bare JID if a session for the full JID is not available. The "isActiveRoute"
    // condition below will prevent inadvertent delivery of multiple copies of each
    // event notification to the user, possibly multiple times (e.g. route.all-resources). 
    // (Refer to http://issues.igniterealtime.org/browse/OF-14 for more info.)
    //
    // This approach is informed by the following XEP-0060 implementation guidelines:
    //   12.2 "Intended Recipients for Notifications" - only deliver to subscriber JID
    //   12.4 "Not Routing Events to Offline Storage" - no offline storage for notifications
    //
    // Note however that this may be somewhat in conflict with the following:
    //   12.3 "Presence-Based Delivery of Events" - automatically detect user's presence
    //
    if (subscriberJID.getResource() == null ||
        SessionManager.getInstance().getSession(subscriberJID) != null) {
        getService().sendNotification(this, notification, subscriberJID);
    }

    if (headers != null) {
        // Remove the added child element that includes subscription IDs information
        notification.getElement().remove(headers);
    }
}
 
Example 7
Source File: ScriptTaskXMLConverter.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
@Override
public void convertModelToXML(Element element, BaseElement baseElement) {
	
	ScriptTask scriptTask = (ScriptTask) baseElement;
	if (null != scriptTask.getScript()) {
		element.addAttribute(BpmnXMLConstants.FOXBPM_PREFIX + ':' + BpmnXMLConstants.ATTRIBUTE_SCRIPTNAME, BpmnXMLUtil.interceptStr(scriptTask.getScript()));
		Element childElem = element.addElement(BpmnXMLConstants.BPMN2_PREFIX + ':'
		        + BpmnXMLConstants.ELEMENT_SCRIPT);
		childElem.setText(scriptTask.getScript());
	}
	if (null != scriptTask.getScriptFormat()) {
		element.addAttribute(BpmnXMLConstants.ATTRIBUTE_SCRIPTFORMAT, scriptTask.getScriptFormat());
	}
	super.convertModelToXML(element, baseElement);
}
 
Example 8
Source File: StudentSectioningXMLSaver.java    From cpsolver with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save free time request
 * @param requestEl request element to be populated
 * @param request free time request to be saved 
 */
protected void saveFreeTimeRequest(Element requestEl, FreeTimeRequest request) {
    requestEl.addAttribute("id", getId("request", request.getId()));
    requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
    if (request.isAlternative())
        requestEl.addAttribute("alternative", "true");
    if (request.getWeight() != 1.0)
        requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
    TimeLocation tl = request.getTime();
    if (tl != null) {
        requestEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl
                .getDayCode()))));
        requestEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
        requestEl.addAttribute("length", String.valueOf(tl.getLength()));
        if (iShowNames && tl.getDatePatternId() != null)
            requestEl.addAttribute("datePattern", tl.getDatePatternId().toString());
        requestEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
        if (iShowNames)
            requestEl.setText(tl.getLongName(true));
    }
    if (iSaveInitial && request.getInitialAssignment() != null) {
        requestEl.addElement("initial");
    }
    if (iSaveCurrent && getAssignment().getValue(request) != null) {
        requestEl.addElement("current");
    }
    if (iSaveBest && request.getBestAssignment() != null) {
        requestEl.addElement("best");
    }
}
 
Example 9
Source File: GroupCreated.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Get the group name
    String groupname;
    try {
        groupname = get(data, "groupName", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Group name required parameter.");
        return;
    }

    // Sends the event
    Group group;
    try {
        group = GroupManager.getInstance().getGroup(groupname, true);

        // Fire event.
        Map<String, Object> params = Collections.emptyMap();
        GroupEventDispatcher.dispatchEvent(group, GroupEventDispatcher.EventType.group_created, params);

    } catch (GroupNotFoundException e) {
        note.addAttribute("type", "error");
        note.setText("Group not found.");
    }

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example 10
Source File: FIBQuestion.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Build mastery respcondition for FIB in all-banks-must-be-correct mode. Adds one respcondition in which all blanks must be answered correctly. This respcondition
 * uses the mastery feedback.
 * 
 * @param resprocessingXML
 */
private void buildRespconditionFIBSingle(final Element resprocessingXML) {
    final Element correct = resprocessingXML.addElement("respcondition");
    correct.addAttribute("title", "Mastery");
    correct.addAttribute("continue", "Yes");

    final Element conditionvar = correct.addElement("conditionvar");
    final Element and = conditionvar.addElement("and");
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse fib = (FIBResponse) i.next();
        if (fib.getType().equals(FIBResponse.TYPE_BLANK)) {
            final String[] correctFIBs = fib.getCorrectBlank().split(";");
            final Element or = and.addElement("or");
            for (int j = 0; j < correctFIBs.length; j++) {
                final Element varequal = or.addElement("varequal");
                varequal.addAttribute("respident", fib.getIdent());
                varequal.addAttribute("case", fib.getCaseSensitive());
                if (correctFIBs[j].length() > 0) {
                    varequal.addCDATA(correctFIBs[j]);
                }
            }
        }
    }

    final Element setvar = correct.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Set");
    setvar.setText("" + getSingleCorrectScore());

    // Use mastery feedback
    QTIEditHelperEBL.addFeedbackMastery(correct);

    // remove whole respcondition if empty
    if (and.element("or") == null) {
        resprocessingXML.remove(correct);
    }
}
 
Example 11
Source File: Dom4jAccessor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void set(Object target, Object value, SessionFactoryImplementor factory) 
throws HibernateException {
	Element owner = ( Element ) target;
	if ( !super.propertyType.isXMLElement() ) { //kinda ugly, but needed for collections with a "." node mapping
		if (value==null) {
			owner.setText(null); //is this ok?
		}
		else {
			super.propertyType.setToXMLNode(owner, value, factory);
		}
	}
}
 
Example 12
Source File: BpmnXMLUtil.java    From FoxBPM with Apache License 2.0 4 votes vote down vote up
/*******************************************************************************************/
public static void createConectorElement(Element parentElement, String connrctorType, List<Connector> connectors) {
	if (null != connectors) {
		Connector connector = null;
		Element connectorInstanceElements = null;
		Element connectorInstanceElem = null;
		Element childElem = null;
		Element expressionElem = null;
		connectorInstanceElements = parentElement.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
		        + BpmnXMLConstants.ELEMENT_CONNECTORINSTANCEELEMENTS, BpmnXMLConstants.FOXBPM_NAMESPACE);
		connectorInstanceElements.addAttribute(BpmnXMLConstants.ATTRIBUTE_CONNRCTORTYPE, connrctorType);
		
		for (Iterator<Connector> iterator = connectors.iterator(); iterator.hasNext();) {
			connector = iterator.next();
			// 处理基本属性
			connectorInstanceElem = connectorInstanceElements.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
			        + BpmnXMLConstants.ELEMENT_CONNECTORINSTANCE);
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_PACKAGENAME, connector.getPackageName());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_ISTIMEEXECUTE, connector.getIsTimeExecute());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_CONNECTORID, connector.getId());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_CLASSNAME, connector.getClassName());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_CONNECTORINSTANCE_ID, connector.getConnectorInstanceId());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_CONNECTORINSTANCE_NAME, connector.getConnectorInstanceName());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_EVENTTYPE, connector.getEventType());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_ERRORHANDLING, connector.getErrorHandling());
			connectorInstanceElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_ERRORCODE, connector.getErrorCode());
			// 结束
			BpmnXMLUtil.addElemAttribute(connectorInstanceElem, BpmnXMLConstants.ATTRIBUTE_TYPE, connector.getType());
			// 处理输入参数
			createInputsParam(connectorInstanceElem, connector.getInputsParam());
			// 处理输出参数
			createOutputsParam(connectorInstanceElem, connector.getOutputsParam());
			// 处理输出参数
			createOutputsParamDef(connectorInstanceElem, connector.getOutputsParamDef());
			// 处理其他
			// 处理foxbpm:skipComment
			if (null != connector.getSkipComment()) {
				childElem = connectorInstanceElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_SKIPCOMMENT);
				childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.FOXBPM_PREFIX
				        + ':' + BpmnXMLConstants.TYPE_SKIPCOMMENT);
				expressionElem = childElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_EXPRESSION);
				createExpressionElement(expressionElem, connector.getSkipComment());
			}
			// 处理foxbpm:timeExpression
			if (null != connector.getTimerEventDefinition()) {
				childElem = connectorInstanceElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_TIMEEXPRESSION);
				childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.FOXBPM_PREFIX
				        + ':' + BpmnXMLConstants.ELEMENT_TIMEEXPRESSION);
				if (null != connector.getTimerEventDefinition().getTimeDate()) {
					expressionElem = childElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
					        + BpmnXMLConstants.ELEMENT_EXPRESSION);
					createExpressionElement(expressionElem, connector.getTimerEventDefinition().getTimeDate());
				}
				
			}
			// foxbpm:timeSkipExpression
			if (null != connector.getSkipExpression()) {
				childElem = connectorInstanceElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_TIMESKIPEXPRESSION);
				childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.FOXBPM_PREFIX
				        + ':' + BpmnXMLConstants.ELEMENT_TIMESKIPEXPRESSION);
				expressionElem = childElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_EXPRESSION);
				createExpressionElement(expressionElem, connector.getSkipExpression());
			}
			// 描述
			if (null != connector.getDocumentation()) {
				childElem = connectorInstanceElem.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
				        + BpmnXMLConstants.ELEMENT_DOCUMENTATION);
				childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.FOXBPM_PREFIX
				        + ':' + BpmnXMLConstants.TYPE_DOCUMENTATION);
				childElem.setText(connector.getDocumentation());
			}
		}
	}
}
 
Example 13
Source File: FlagWinCommandProbability.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void marshalValue(Element element, Integer value) {
    element.setText(String.valueOf(value.intValue()));
}
 
Example 14
Source File: FIBQuestion.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Render XML
 */
public void addToElement(final Element root) {
    final Element presentationXML = root.addElement("presentation");
    presentationXML.addAttribute("label", "notset");
    // presentation
    final Element flowXML = presentationXML.addElement("flow");
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse fibcontent = (FIBResponse) i.next();
        if (fibcontent.getType().equals(FIBResponse.TYPE_CONTENT)) {
            final Material mat = fibcontent.getContent();
            if (mat.getElements().isEmpty()) {
                // the flow cannot be empty -> add dummy material element
                flowXML.addElement("material").addElement("mattext").addCDATA("");
            } else {
                mat.addToElement(flowXML);
            }
        } else if (fibcontent.getType().equals(FIBResponse.TYPE_BLANK)) {
            final Element response_str = flowXML.addElement("response_str");
            response_str.addAttribute("ident", fibcontent.getIdent());
            response_str.addAttribute("rcardinality", "Single");

            final Element render_fib = response_str.addElement("render_fib");
            render_fib.addAttribute("columns", String.valueOf(fibcontent.getSize()));
            render_fib.addAttribute("maxchars", String.valueOf(fibcontent.getMaxLength()));

            final Element flow_label = render_fib.addElement("flow_label");
            flow_label.addAttribute("class", "Block");
            final Element response_lable = flow_label.addElement("response_label");
            response_lable.addAttribute("ident", fibcontent.getIdent());
            response_lable.addAttribute("rshuffle", "Yes");
        }
    }

    // resprocessing
    final Element resprocessingXML = root.addElement("resprocessing");

    // outcomes
    final Element decvar = resprocessingXML.addElement("outcomes").addElement("decvar");
    decvar.addAttribute("varname", "SCORE");
    decvar.addAttribute("vartype", "Decimal");
    decvar.addAttribute("defaultval", "0");
    decvar.addAttribute("minvalue", "" + getMinValue());
    float maxScore = QTIEditHelperEBL.calculateMaxScore(this);
    maxScore = maxScore > getMaxValue() ? getMaxValue() : maxScore;
    decvar.addAttribute("maxvalue", "" + maxScore);
    decvar.addAttribute("cutvalue", "" + maxScore);

    // respcondition
    // correct

    if (isSingleCorrect()) {
        buildRespconditionFIBSingle(resprocessingXML);
        buildRespcondition_fail(resprocessingXML, true);
    } else {
        buildRespconditionFIBMulti(resprocessingXML);
        buildRespcondition_fail(resprocessingXML, false);
    }

    // hint
    if (getHintText() != null) {
        QTIEditHelperEBL.addHintElement(root, getHintText());
    }

    // solution
    if (getSolutionText() != null) {
        QTIEditHelperEBL.addSolutionElement(root, getSolutionText());
    }

    // Feedback for all other cases eg. none has been answered at all
    final Element incorrect = resprocessingXML.addElement("respcondition");
    incorrect.addAttribute("title", "Fail");
    incorrect.addAttribute("continue", "Yes");
    incorrect.addElement("conditionvar").addElement("other");
    final Element setvar = incorrect.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Set");
    setvar.setText("0");
    QTIEditHelperEBL.addFeedbackFail(incorrect);
    QTIEditHelperEBL.addFeedbackHint(incorrect);
    QTIEditHelperEBL.addFeedbackSolution(incorrect);
}
 
Example 15
Source File: ResultsBuilder.java    From olat with Apache License 2.0 4 votes vote down vote up
private void addElementText(final Element parent, final String child, final String text) {
    final Element el = parent.addElement(child);
    el.setText(text);
}
 
Example 16
Source File: MainLayoutController.java    From javafx-TKMapEditor with GNU General Public License v3.0 4 votes vote down vote up
private Document createSaveDocument() {
	Document document = DocumentHelper.createDocument();
	Element map = document.addElement(XMLElements.ELEMENT_MAP);

	Element mapSetting = map.addElement(XMLElements.ELEMENT_MAP_SETTING);

	Element mapWidth = mapSetting.addElement(XMLElements.ELEMENT_MAP_WIDTH);
	mapWidth.setText(TiledMap.getInstance().getMapWidth() + "");

	Element mapHeight = mapSetting.addElement(XMLElements.ELEMENT_MAP_HEIGHT);
	mapHeight.setText(TiledMap.getInstance().getMapHeight() + "");

	Element tileWidth = mapSetting.addElement(XMLElements.ELEMENT_TILE_WIDTH);
	tileWidth.setText(TiledMap.getInstance().getTileWidth() + "");

	Element tileHeight = mapSetting.addElement(XMLElements.ELEMENT_TILE_HEIGHT);
	tileHeight.setText(TiledMap.getInstance().getTileHeight() + "");

	// 写入资源列表
	Element mapResource = map.addElement(XMLElements.ELEMENT_MAP_RESOURCE);
	List<AltasResource> resources = AltasResourceManager.getInstance().getResources();
	for (int i = 0; i < resources.size(); i++) {
		AltasResource altasResource = resources.get(i);
		Element resource = mapResource.addElement(XMLElements.ELEMENT_RESOURCE);
		Element resourceId = resource.addElement(XMLElements.ELEMENT_ALTAS_ID);
		resourceId.setText(altasResource.getAltasId());
		Element resourcePath = resource.addElement(XMLElements.ELEMENT_ALTAS_PATH);
		resourcePath.setText(altasResource.getPathStr());
	}

	Element mapData = map.addElement(XMLElements.ELEMENT_MAP_DATA);
	for (int i = 0; i < tiledMapLayerList.size(); i++) {
		TiledMapLayer mapLayer = tiledMapLayerList.get(i);
		Element layer = mapData.addElement(XMLElements.ELEMENT_MAP_LAYER);
		layer.addAttribute(XMLElements.ATTRIBUTE_NAME, mapLayer.getLayerName());
		layer.addAttribute(XMLElements.ATTRIBUTE_VISIBLE, String.valueOf(mapLayer.isVisible()));
		layer.addAttribute(XMLElements.ATTRIBUTE_ALPHA, mapLayer.getAlpha() + "");
		layer.addAttribute(XMLElements.ATTRIBUTE_COLLIDER, String.valueOf(mapLayer.isCollider()));
		layer.setText(mapLayer.toString());
	}

	Element tilePropertyElement = map.addElement(XMLElements.ELEMENT_MAP_PROPERTY);
	ArrayList<TileProperty> tileProperties = TiledMap.getInstance().getPropertyList();
	for (TileProperty tileProperty : tileProperties) {
		Element data = tilePropertyElement.addElement(XMLElements.ELEMENT_PROPERTY_DATA);
		data.addAttribute(XMLElements.ATTRIBUTE_COL, String.valueOf(tileProperty.getCol()));
		data.addAttribute(XMLElements.ATTRIBUTE_ROW, String.valueOf(tileProperty.getRow()));

		HashMap<String, String> valuesMap = tileProperty.getValueMap();
		Iterator<String> keys = valuesMap.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			String value = valuesMap.get(key);
			Element propertyElement = data.addElement(XMLElements.ELEMENT_PROPERTY);
			propertyElement.addAttribute(XMLElements.ATTRIBUTE_KEY, key);
			propertyElement.addAttribute(XMLElements.ATTRIBUTE_VALUE, value);
		}
	}

	return document;
}
 
Example 17
Source File: ResultsBuilder.java    From olat with Apache License 2.0 4 votes vote down vote up
private void addElementText(final Element parent, final String child, final String text) {
    final Element el = parent.addElement(child);
    el.setText(text);
}
 
Example 18
Source File: MUCRoomHistory.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new message and adds it to the history. The new message will be created based on
 * the provided information. This information will likely come from the database when loading
 * the room history from the database.
 *
 * @param senderJID the sender's JID of the message to add to the history.
 * @param nickname the sender's nickname of the message to add to the history.
 * @param sentDate the date when the message was sent to the room.
 * @param subject the subject included in the message.
 * @param body the body of the message.
 * @param stanza the stanza to add
 */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject,
        String body, String stanza)
{
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>)element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>)child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>)child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    }
    else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }

    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    }
    else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}
 
Example 19
Source File: XMLUtil.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 修改XML文件
 * @param fileName
 * @param newFileName
 * @return
 */
private static Document testModifyXMLFile(String fileName) {
    SAXReader reader = new SAXReader();
    Document document = null;
    try {
        document = reader.read(new File(fileName));
        // 用xpath查找对象
        List<?> list = document.selectNodes("/catalog/journal/@title");
        Iterator<?> itr = list.iterator();
        while (itr.hasNext()) {
            Attribute attribute = (Attribute) itr.next();
            if (attribute.getValue().equals("XML Zone")) {
                attribute.setText("Modi XML");
            }
        }
        // 在journal元素中增加date元素
        list = document.selectNodes("/catalog/journal");
        itr = list.iterator();
        if (itr.hasNext()) {
            Element journalElement = (Element) itr.next();
            Element dateElement = journalElement.addElement("date");
            dateElement.setText("2006-07-10");
            dateElement.addAttribute("type", "Gregorian calendar");
        }
        // 删除title接点
        list = document.selectNodes("/catalog/journal/article");
        itr = list.iterator();
        while (itr.hasNext()) {
            Element articleElement = (Element) itr.next();
            Iterator<Element> iter = articleElement.elementIterator("title");
            while (iter.hasNext()) {
                Element titleElement = (Element) iter.next();
                if (titleElement.getText().equals("Dom4j Create XML Schema")) {
                    articleElement.remove(titleElement);
                }
            }
        }

    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return document;

}
 
Example 20
Source File: FlagReward.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void marshalListItem(Element element, Double item) {
	element.setText(String.valueOf(item));
}