Java Code Examples for org.dom4j.DocumentHelper#createElement()

The following examples show how to use org.dom4j.DocumentHelper#createElement() . 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: AppMsgXmlHandler.java    From SmartIM with Apache License 2.0 6 votes vote down vote up
/**
 * 构造发送文件时的消息内容xml
 * 
 * @param file
 *            文件
 * @param mediaId
 *            通过文件上传返回的mediaId
 * @return 消息xml内容
 */
public String encode(File file, String mediaId) {
    Element root = DocumentHelper.createElement("appmsg");
    root.addAttribute("appid", "wxeb7ec651dd0aefa9");
    root.addAttribute("sdkver", "");
    root.addElement("title").setText(file.getName());
    root.addElement("des");
    root.addElement("action");
    root.addElement("type").setText("6");
    root.addElement("content");
    root.addElement("url");
    root.addElement("rowurl");
    Element appattach = root.addElement("appattach");
    appattach.addElement("totallen").setText(String.valueOf(file.length()));
    appattach.addElement("attachid").setText(mediaId);
    root.addElement("extinfo");
    return root.asXML();
}
 
Example 2
Source File: XmlTest.java    From javautils with Apache License 2.0 6 votes vote down vote up
@Test
    public void test(){
        String filePath = "src/main/resources/xml/test.xml";
        File file = new File(filePath);
        if(!file.exists()){
            long s = System.currentTimeMillis();
            Document doc = DocumentHelper.createDocument();
            Element root = doc.addElement("root");
            for(int i = 0; i <= 10000000; i++){
                Element testElement = DocumentHelper.createElement("eleTest");
                testElement.addAttribute("name", "testEle");
                testElement.addText("this is another text");
                root.add(testElement);
            }
            XmlUtil.writeXml("src/main/resources/xml/test.xml", doc);
            long e = System.currentTimeMillis();
            System.out.println("共耗时:" + (e - s) + "ms");
        }
//        parseXml(filePath);
        XmlUtil.parseHandler(filePath);
    }
 
Example 3
Source File: ResultSet.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
    if (returnedResults == null) {
        throw new IllegalArgumentException(
                "Argument 'returnedResults' cannot be null.");
    }
    final Element setElement = DocumentHelper.createElement(QName.get(
            "set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
    // the size element contains the size of this entire result set.
    setElement.addElement("count").setText(String.valueOf(size()));

    // if the query wasn't a 'count only' query, add two more elements
    if (returnedResults.size() > 0) {
        final Element firstElement = setElement.addElement("first");
        firstElement.addText(returnedResults.get(0).getUID());
        firstElement.addAttribute("index", String
                .valueOf(indexOf(returnedResults.get(0))));

        setElement.addElement("last").addText(
                returnedResults.get(returnedResults.size() - 1).getUID());
    }

    return setElement;
}
 
Example 4
Source File: PubSubEngine.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void getDefaultNodeConfiguration(PubSubService service, IQ iq,
                                         Element childElement, Element defaultElement) {
    String type = defaultElement.attributeValue("type");
    type = type == null ? "leaf" : type;

    boolean isLeafType = "leaf".equals(type);
    DefaultNodeConfiguration config = service.getDefaultNodeConfiguration(isLeafType);
    if (config == null) {
        // Service does not support the requested node type so return an error
        Element pubsubError = DocumentHelper.createElement(
                QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", isLeafType ? "leaf" : "collections");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;
    }

    // Return data form containing default node configuration
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("default").add(config.getConfigurationForm().getElement());
    router.route(reply);
}
 
Example 5
Source File: HttpSession.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the stream features which are available for this session.
 *
 * @return the stream features which are available for this session.
 */
public Collection<Element> getAvailableStreamFeaturesElements() {
    List<Element> elements = new ArrayList<>();

    if (getAuthToken() == null) {
        Element sasl = SASLAuthentication.getSASLMechanismsElement(this);
        if (sasl != null) {
            elements.add(sasl);
        }
    }

    if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) {
        elements.add(DocumentHelper.createElement(new QName("register",
                new Namespace("", "http://jabber.org/features/iq-register"))));
    }
    Element bind = DocumentHelper.createElement(new QName("bind",
            new Namespace("", "urn:ietf:params:xml:ns:xmpp-bind")));
    elements.add(bind);

    Element session = DocumentHelper.createElement(new QName("session",
            new Namespace("", "urn:ietf:params:xml:ns:xmpp-session")));
    session.addElement("optional");
    elements.add(session);
    return elements;
}
 
Example 6
Source File: UserSetHelper.java    From cuba with Apache License 2.0 6 votes vote down vote up
public static String generateSetFilter(Set ids, String entityClass, String componentId, String entityAlias) {
    Document document = DocumentHelper.createDocument();
    Element root = DocumentHelper.createElement("filter");
    Element or = root.addElement("and");

    Element condition = or.addElement("c");
    condition.addAttribute("name", "set");
    condition.addAttribute("inExpr", "true");
    condition.addAttribute("hidden", "true");
    condition.addAttribute("locCaption", "Set filter");
    condition.addAttribute("entityAlias", entityAlias);
    condition.addAttribute("class", entityClass);
    condition.addAttribute("type", ConditionType.CUSTOM.name());

    String listOfId = createIdsString(ids);
    String randomName = RandomStringUtils.randomAlphabetic(10);
    condition.addText(entityAlias + ".id in :component$" + componentId + "." + randomName);

    Element param = condition.addElement("param");
    param.addAttribute("name", "component$" + componentId + "." + randomName);
    param.addAttribute("isFoldersFilterEntitiesSet", "true");
    param.addText(listOfId);

    document.add(root);
    return Dom4j.writeDocument(document, true);
}
 
Example 7
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 8
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
    JID recipientJID = XMPPServer.getInstance().createJID(name, null, true).asBareJID();
    PEPService pepService = pepServiceManager.getPEPService(recipientJID);

    if (node != null && pepService != null) {
        Node pubNode = pepService.getNode(node);
        if (pubNode == null) return null;
        // Answer the identity of a given node
        Element identity = DocumentHelper.createElement("identity");
        identity.addAttribute("category", "pubsub");
        identity.addAttribute("type", pubNode.isCollectionNode() ? "collection" : "leaf");

        List<Element> identities = new LinkedList<>();
        identities.add(identity);
        return identities.iterator();
    } else if (node != null) {
        return null;
    } else {
        PubSubModule pubsub = XMPPServer.getInstance().getPubSubModule();
        return pubsub.getIdentities(null, null, senderJID);
    }
}
 
Example 9
Source File: IQEntityTimeHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) {
    IQ response = IQ.createResultIQ(packet);
    Element timeElement = DocumentHelper.createElement(QName.get(info.getName(), info.getNamespace()));
    timeElement.addElement("tzo").setText(formatsTimeZone(TimeZone.getDefault()));
    timeElement.addElement("utc").setText(getUtcDate(new Date()));
    response.setChildElement(timeElement);
    return response;
}
 
Example 10
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Implements ServerIdentitiesProvider and UserIdentitiesProvider, adding
 * the PEP identity to the respective disco#info results.
 */
@Override
public Iterator<Element> getIdentities() {
    Element identity = DocumentHelper.createElement("identity");
    identity.addAttribute("category", "pubsub");
    identity.addAttribute("type", "pep");
    return Collections.singleton(identity).iterator();
}
 
Example 11
Source File: WxXmlUtil.java    From WeixinMultiPlatform with Apache License 2.0 5 votes vote down vote up
private static Element respEntityFactory(WxBaseRespEntity entity) {
	Element ele = DocumentHelper.createElement("xml");
	ele.addElement("ToUserName").addCDATA(entity.getToUserName());
	ele.addElement("FromUserName").addCDATA(entity.getFromUserName());
	String createTime = String.valueOf(entity.getCreateTime());
	if (StringUtils.isBlank(createTime)) {
		Long currentTime = WxUtil.currentTimeInSec();
		entity.setCreateTime(currentTime);
		createTime = String.valueOf(currentTime);
	}
	ele.addElement("CreateTime").setText(createTime);
	ele.addElement("MsgType").addCDATA(entity.getMsgType());
	ele.addElement("FuncFlag").setText(String.valueOf(entity.getFuncFlag()));
	return ele;
}
 
Example 12
Source File: IQVersionHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public IQVersionHandler() {
    super("XMPP Server Version Handler");
    info = new IQHandlerInfo("query", "jabber:iq:version");
    if (bodyElement == null) {
        bodyElement = DocumentHelper.createElement(QName.get("query", "jabber:iq:version"));
        bodyElement.addElement("name").setText(AdminConsole.getAppName());
        bodyElement.addElement("version").setText(AdminConsole.getVersionString());
    }
}
 
Example 13
Source File: PictureDom4jDbTemplate.java    From egdownloader with GNU General Public License v2.0 5 votes vote down vote up
public static Element picture2Element(Picture t){
		Element ele = DocumentHelper.createElement("picture");
		ele.addAttribute("id", t.getId());
		ele.addAttribute("tid", t.getTid());
		ele.addAttribute("num", t.getNum());
		ele.addAttribute("name", t.getName());
		ele.addAttribute("url", t.getUrl());
//		ele.addAttribute("realUrl", t.getRealUrl());
		ele.addAttribute("size", t.getSize() + "");
		ele.addAttribute("time", t.getTime());
		ele.addAttribute("saveAsName", t.isSaveAsName() + "");
		ele.addAttribute("isCompleted", t.isCompleted() + "");
//		ele.addAttribute("isRunning", t.isRunning() + "");
		return ele;
	}
 
Example 14
Source File: IQMuclumbusSearchHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
static Element generateResultElement( final List<MUCRoom> rooms )
{
    Log.debug( "Generating result element." );
    final Element res = DocumentHelper.createElement( QName.get( RESPONSE_ELEMENT_NAME, NAMESPACE ) );
    for ( final MUCRoom room : rooms )
    {
        final Element item = res.addElement( "item" );
        item.addAttribute( "address", room.getJID().toString() );
        if ( room.getNaturalLanguageName() != null && !room.getNaturalLanguageName().isEmpty() )
        {
            item.addElement( "name" ).setText( room.getNaturalLanguageName() );
        }
        if ( room.getDescription() != null && !room.getDescription().isEmpty() )
        {
            item.addElement( "description" ).setText( room.getDescription() );
        }
        // Openfire does not support 'language'
        if ( !room.isLocked() && !room.isMembersOnly() && !room.isPasswordProtected() )
        {
            item.addElement( "is-open" );
        }

        final Element anonymityMode = item.addElement( "anonymity-mode" );
        if ( room.canAnyoneDiscoverJID() )
        {
            anonymityMode.setText( "none" );
        }
        else
        {
            anonymityMode.setText( "semi" );
        }

        item.addElement( "nusers" ).setText( Integer.toString( room.getOccupantsCount() ) );
    }
    return res;
}
 
Example 15
Source File: IQRegisterHandler.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(XMPPServer server) {
    super.initialize(server);
    userManager = server.getUserManager();
    rosterManager = server.getRosterManager();

    if (probeResult == null) {
        // Create the basic element of the probeResult which contains the basic registration
        // information (e.g. username, passoword and email)
        probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:register"));
        probeResult.addElement("username");
        probeResult.addElement("password");
        probeResult.addElement("email");
        probeResult.addElement("name");

        // Create the registration form to include in the probeResult. The form will include
        // the basic information plus name and visibility of name and email.
        // TODO Future versions could allow plugin modules to add new fields to the form 
        final DataForm registrationForm = new DataForm(DataForm.Type.form);
        registrationForm.setTitle("XMPP Client Registration");
        registrationForm.addInstruction("Please provide the following information");

        final FormField fieldForm = registrationForm.addField();
        fieldForm.setVariable("FORM_TYPE");
        fieldForm.setType(FormField.Type.hidden);
        fieldForm.addValue("jabber:iq:register");

        final FormField fieldUser = registrationForm.addField();
        fieldUser.setVariable("username");
        fieldUser.setType(FormField.Type.text_single);
        fieldUser.setLabel("Username");
        fieldUser.setRequired(true);

        final FormField fieldName = registrationForm.addField(); 
        fieldName.setVariable("name");
        fieldName.setType(FormField.Type.text_single);
        fieldName.setLabel("Full name");
        if (UserManager.getUserProvider().isNameRequired()) {
            fieldName.setRequired(true);
        }

        final FormField fieldMail = registrationForm.addField();
        fieldMail.setVariable("email");
        fieldMail.setType(FormField.Type.text_single);
        fieldMail.setLabel("Email");
        if (UserManager.getUserProvider().isEmailRequired()) {
            fieldMail.setRequired(true);
        }

        final FormField fieldPwd = registrationForm.addField();
        fieldPwd.setVariable("password");
        fieldPwd.setType(FormField.Type.text_private);
        fieldPwd.setLabel("Password");
        fieldPwd.setRequired(true);

        // Add the registration form to the probe result.
        probeResult.add(registrationForm.getElement());
    }
    
    JiveGlobals.migrateProperty("register.inband");
    JiveGlobals.migrateProperty("register.password");
    
    // See if in-band registration should be enabled (default is true).
    registrationEnabled = JiveGlobals.getBooleanProperty("register.inband", true);
    // See if users can change their passwords (default is true).
    canChangePassword = JiveGlobals.getBooleanProperty("register.password", true);
}
 
Example 16
Source File: Simplicity.java    From MesquiteCore with GNU Lesser General Public License v3.0 4 votes vote down vote up
public  void renameSettingsFile(int i, String newName){
	if (!MesquiteInteger.isCombinable(i) || i<0 || i>= InterfaceManager.settingsFiles.size())
		return;
	StringArray s = (StringArray)InterfaceManager.settingsFiles.elementAt(i);
	String path = s.getValue(PATH);
	String settingsXML = s.getValue(XML);
	Element root = XMLUtil.getRootXMLElementFromString("mesquite",settingsXML);
	if (root==null)
		return;
	Element element = root.element("simplicitySettings");
	if (element != null) {
		Element versionElement = element.element("version");
		if (versionElement == null)
			return ;
		else {
			int version = MesquiteInteger.fromString(element.elementText("version"));
			boolean acceptableVersion = version==1;
			if (acceptableVersion) {
				Element name = element.element("name");

				Element settingsFile = DocumentHelper.createElement("mesquite");
				Document doc = DocumentHelper.createDocument(settingsFile);
				Element hidden = DocumentHelper.createElement("simplicitySettings");
				settingsFile.add(hidden);
				XMLUtil.addFilledElement(hidden, "version","1");
				XMLUtil.addFilledElement(hidden, "name",newName);
				Element hp = element.element("hiddenPackages");
				element.remove(hp);
				hidden.add(hp);
				hp = element.element("hiddenMenuItems");
				element.remove(hp);
				hidden.add(hp);
				hp = element.element("hiddenTools");
				element.remove(hp);
				hidden.add(hp);
				s.setName(newName);
				MesquiteFile.putFileContents(path, XMLUtil.getDocumentAsXMLString(doc), false);
			}
		} 
	}
}
 
Example 17
Source File: IQMUCSearchHandler.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method that returns a 'jabber:iq:search' child element filled
 * with a blank dataform.
 * 
 * @return Element, named 'query', escaped by the 'jabber:iq:search'
 *         namespace, filled with a blank dataform.
 */
private static Element getDataElement()
{
    final DataForm searchForm = new DataForm(DataForm.Type.form);
    searchForm.setTitle("Chat Rooms Search");
    searchForm.addInstruction("Instructions");

    final FormField typeFF = searchForm.addField();
    typeFF.setVariable("FORM_TYPE");
    typeFF.setType(FormField.Type.hidden);
    typeFF.addValue(JABBER_IQ_SEARCH);

    final FormField nameFF = searchForm.addField();
    nameFF.setVariable("name");
    nameFF.setType(FormField.Type.text_single);
    nameFF.setLabel("Name");
    nameFF.setRequired(false);

    final FormField matchFF = searchForm.addField();
    matchFF.setVariable("name_is_exact_match");
    matchFF.setType(FormField.Type.boolean_type);
    matchFF.setLabel("Name must match exactly");
    matchFF.setRequired(false);

    final FormField subjectFF = searchForm.addField();
    subjectFF.setVariable(SUBJECT);
    subjectFF.setType(FormField.Type.text_single);
    subjectFF.setLabel("Subject");
    subjectFF.setRequired(false);

    final FormField userAmountFF = searchForm.addField();
    userAmountFF.setVariable(NUM_USERS);
    userAmountFF.setType(FormField.Type.text_single);
    userAmountFF.setLabel("Number of users");
    userAmountFF.setRequired(false);

    final FormField maxUsersFF = searchForm.addField();
    maxUsersFF.setVariable(NUM_MAX_USERS);
    maxUsersFF.setType(FormField.Type.text_single);
    maxUsersFF.setLabel("Max number allowed of users");
    maxUsersFF.setRequired(false);

    final FormField includePasswordProtectedFF = searchForm.addField();
    includePasswordProtectedFF.setVariable("include_password_protected");
    includePasswordProtectedFF.setType(FormField.Type.boolean_type);
    includePasswordProtectedFF.setLabel("Include password protected rooms");
    includePasswordProtectedFF.setRequired(false);

    final Element probeResult = DocumentHelper.createElement(QName.get(
        "query", JABBER_IQ_SEARCH));
    probeResult.add(searchForm.getElement());
    return probeResult;
}
 
Example 18
Source File: WhitelistAccess.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public Element getSubsriptionErrorDetail() {
    return DocumentHelper.createElement(
            QName.get("closed-node", "http://jabber.org/protocol/pubsub#errors"));
}
 
Example 19
Source File: PrivateStorage.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Stores private data. If the name and namespace of the element matches another
 * stored private data XML document, then replace it with the new one.
 *
 * @param data the data to store (XML element)
 * @param username the username of the account where private data is being stored
 */
public void add(String username, Element data) {
    if (!enabled)
    {
        return;
    }

    final JID owner = XMPPServer.getInstance().createJID( username, null );
    final PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
    PEPService pepService = serviceMgr.getPEPService( owner );
    if ( pepService == null )
    {
        pepService = serviceMgr.create( owner );
    }

    Node node = pepService.getNode( data.getNamespaceURI() );
    if ( node == null )
    {
        PubSubEngine.CreateNodeResponse response = PubSubEngine.createNodeHelper( pepService, owner, pepService.getDefaultNodeConfiguration( true ).getConfigurationForm().getElement(), data.getNamespaceURI(), PRIVATE_DATA_PUBLISHING_OPTIONS );
        node = response.newNode;

        if ( node == null )
        {
            Log.error( "Unable to create new PEP node, to be used to store private data. Error condition: {}", response.creationStatus.toXMPP() );
            return;
        }
    }

    if (!(node instanceof LeafNode))
    {
        Log.error( "Unable to store private data into a PEP node. The node that is available is not a leaf node." );
        return;
    }

    data.detach();
    final Element item = DocumentHelper.createElement( "item" );
    item.addAttribute( "id", "current" );
    item.add( data );

    ((LeafNode) node).publishItems( owner, Collections.singletonList( item ) );
}
 
Example 20
Source File: XmlText.java    From ats-framework with Apache License 2.0 3 votes vote down vote up
private XmlText( Element root ) throws XMLException {
    this.root = DocumentHelper.createElement("root");

    DocumentHelper.createDocument(this.root);

    this.root = root.createCopy();

    DocumentHelper.createDocument(this.root);
}