Example usage for org.dom4j Element addElement

List of usage examples for org.dom4j Element addElement

Introduction

In this page you can find the example usage for org.dom4j Element addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper.java

/**
 * ??XML//from   w w  w .  j a  va2  s  .  co  m
 * @param messageResponse
 * @return
 */
public static Document voiceMessageResponseToDocumnet(WechatReceiveReplayVoiceMessageResponse messageResponse) {
    final String toUserName = messageResponse.getToUserName();
    final String fromUserName = messageResponse.getFromUserName();
    final String msgType = messageResponse.getMsgType();

    Document respDoc = initRespDoc(toUserName, fromUserName, msgType);
    Element voiceEle = respDoc.getRootElement().addElement("Voice");
    Element mediaIdEle = voiceEle.addElement("MediaId");
    mediaIdEle.setText(messageResponse.getMediaId());
    return respDoc;
}

From source file:cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper.java

/**
 * ???XML//from  w  ww.j  a v  a2s  . c o m
 *
 * @param messageResponse ?
 * @return XML
 */
public static Document newsMessageResponseToDocument(WechatReceiveReplayNewsMessageResponse messageResponse) {
    final String toUserName = messageResponse.getToUserName();
    final String fromUserName = messageResponse.getFromUserName();
    final String msgType = messageResponse.getMsgType();

    Document respDoc = initRespDoc(toUserName, fromUserName, msgType);
    Element rootEle = respDoc.getRootElement();
    Element articleCountEle = rootEle.addElement("ArticleCount");
    Element articlesEle = rootEle.addElement("Articles");
    messageResponse.getItemList().stream().forEach((item) -> {
        Element itemEle = articlesEle.addElement("item");
        if (!StringUtils.isEmpty(item.getTitle())) {
            Element titleEle = itemEle.addElement("Title");
            titleEle.setText(item.getTitle());
        }
        if (!StringUtils.isEmpty(item.getDescription())) {
            Element descriptionEle = itemEle.addElement("Description");
            descriptionEle.setText(item.getDescription());
        }
        if (!StringUtils.isEmpty(item.getPicUrl())) {
            Element picUrlEle = itemEle.addElement("PicUrl");
            picUrlEle.setText(item.getPicUrl());
        }
        if (!StringUtils.isEmpty(item.getUrl())) {
            Element urlEle = itemEle.addElement("Url");
            urlEle.setText(item.getUrl());
        }
    });
    articleCountEle.setText(String.valueOf(messageResponse.getItemList().size()));

    return respDoc;
}

From source file:cn.com.sunjiesh.wechat.helper.WechatMessageConvertDocumentHelper.java

/**
 * ?XML// w  ww .j  av  a 2 s.  c o m
 *
 * @param toUserName ??OpenID
 * @param fromUserName ??
 * @param msgType ?
 * @return XML
 */
private static Document initRespDoc(final String toUserName, final String fromUserName, final String msgType) {
    Document respDoc = DocumentHelper.createDocument();
    Element rootEle = respDoc.addElement("xml");
    Element toUserNameEle = rootEle.addElement("ToUserName");
    Element fromUserNameEle = rootEle.addElement("FromUserName");
    Element createTimeEle = rootEle.addElement("CreateTime");
    Element msgTypeEle = rootEle.addElement("MsgType");
    toUserNameEle.setText(toUserName);
    fromUserNameEle.setText(fromUserName);
    createTimeEle.setText(String.valueOf(System.currentTimeMillis()));
    msgTypeEle.setText(msgType);
    return respDoc;
}

From source file:cn.com.xdays.xshop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }/* w ww . j  a v  a  2  s . co  m*/
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[SHOP++?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    String webConfigFilePath = new File(
            Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/"
            + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("")
            .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath),
            new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath),
            new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath),
            new File(securityApplicationContextConfigFilePath));

    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("SHOP++?????");
}

From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java

License:Open Source License

public static void appendXMLByDOM4J(HashMap target, String source, String destination) throws IOException {

    SAXReader reader = new SAXReader();
    try {//from   ww  w  . j  av  a 2 s . co  m

        Document document = reader.read(new File(source));
        Element configStore = document.getRootElement();
        Iterator iter = target.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            Element property = configStore.addElement("property");
            Element name = property.addElement("name");
            name.setText(key);
            Element value = property.addElement("value");
            value.setText(val);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream(destination), format);
        writer.write(document);
        writer.close();

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

From source file:cn.itcreator.android.reader.util.XMLUtil.java

License:Open Source License

/**
 * save the list to a xml file/*from ww  w.j  a v a  2 s .c  o m*/
 * @param list the list u wanna save
 * @return
 */
public boolean saveToFile(List<BookMark> list) {
    boolean result = true;
    Element root = null;
    root = mDocument.getRootElement();
    if (null == root) {
        root = mDocument.addElement("bookmark");
    }
    for (BookMark bookMark : list) {
        Element mark = root.addElement("mark");
        mark.addAttribute("markName", bookMark.getMarkName());
        mark.addAttribute("currentOffset", "" + bookMark.getCurrentOffset());
    }
    OutputFormat format = OutputFormat.createPrettyPrint();
    /** Give the xml file encode */
    format.setEncoding(Constant.UTF8);
    try {
        XMLWriter writer = new XMLWriter(new FileOutputStream(mFilePath), format);
        writer.write(mDocument);
        writer.close();
    } catch (IOException e) {
        result = false;
    }
    return result;
}

From source file:com.adspore.splat.xep0030.DiscoInfoHandler.java

License:Open Source License

public IQ handleDiscoInfoIQ(IQ packet) {
    /*/*from w ww. j  a v a2  s .  co m*/
     * Create a copy of the sent pack that will be used as the reply we need to add
     * the requested info (query) to the reply as well as the 'error' element as described
     * in the XEP-30 Service Discovery docs, section 3.1 / example 1,2.
     * 
     * We'll stuff the 'query' element into the reply, then add identity and feature elements
     * to that if they exist.  
     */
    Element queryElement = packet.getChildElement().createCopy();
    IQ reply = IQ.createResultIQ(packet);
    reply.setChildElement(queryElement);

    /*
     *  Look for a DiscoInfoProvider associated with the requested entity.
     *  We consider the host of the recipient JID of the packet as the entity. It's the
     *  DiscoInfoProvider responsibility to provide information about the JID's name together
     *  with any possible requested node.
     *  
     *  As part of the refactoring, I moved this to a MultiMap implementation because there
     *  may be multiple DiscoInfoProviders that can speak to a particular node, as a node
     *  may host both PubSub entries as well as other services.
     *  
     *  One of the things that makes this so problematic, is the confusion between the JID's
     *  concept of 'Node' and the Entity's concept of 'Node'.  When referring to PubSub, the
     *  node is really placed in a JID's 'resource', and the JID uses the 'Node' to identify
     *  the User's name.  See example:
     *  
     *   nodeId@domainFoo.domainBar/resource
     *
     *   When using the JID+Node approach, this goes very wrong....
     *  
     */

    final Element iq = packet.getChildElement();
    final String node = queryElement.attributeValue("node");

    final JID targetJID = (null != node) ? JIDUtils.setNodeIDAsResource(packet.getTo(), node) : packet.getTo();
    final JID senderJID = packet.getFrom();

    /*
     * Flags controlling the addition of 'standard' features/identities applicable to the
     * entire result set.  Added if ANY of the infoProviders say they do.
     */
    boolean hasDiscoInfoFeature = false;
    boolean hasDiscoItemsFeature = false;
    boolean hasResultSetManagementFeature = false;

    /*
     * Lookup all possible DiscoInfoProviders that service the target.  Base this on the
     * 'domain' field of the JID, patch up with username later if required.
     */
    Collection<DiscoInfoProvider> infoProviders = getProviders(targetJID.toBareJID());
    if (!infoProviders.isEmpty()) {

        /*
         *    Begin looping through the providers, checking with each to provide them with the
         * opportunity to add information if they have any to add.
         */
        Iterator<DiscoInfoProvider> itor = infoProviders.iterator();
        while (itor.hasNext()) {
            DiscoInfoProvider possibleProvider = itor.next();

            if (possibleProvider.hasInfo(targetJID, senderJID)) {
                //   Add the info that this provider says it has...
                Iterator<Element> identities = possibleProvider.getIdentities(targetJID, senderJID);
                while (identities.hasNext()) {
                    queryElement.add(identities.next().createCopy());
                }

                // Add to the reply all the features provided by the DiscoInfoProvider
                Iterator<String> features = possibleProvider.getFeatures(targetJID, senderJID);
                while (features.hasNext()) {
                    //   Loop through all of the features that this provider has....
                    final String feature = features.next();

                    queryElement.addElement("feature").addAttribute("var", feature);
                    if (feature.equals(AbstractComponent.NAMESPACE_DISCO_INFO)) {
                        hasDiscoInfoFeature = true;
                    } else if (feature.equals(AbstractComponent.NAMESPACE_DISCO_ITEMS)) {
                        hasDiscoItemsFeature = true;
                    } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
                        hasResultSetManagementFeature = true;
                    }
                }
            }

            if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
                // IQDiscoItemsHandler provides result set management
                // support.
                queryElement.addElement("feature").addAttribute("var",
                        ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
            }

            // Add to the reply the extended info (XDataForm) provided by the DiscoInfoProvider
            DataForm dataForm = possibleProvider.getExtendedInfo(targetJID, packet.getFrom());
            if (dataForm != null) {
                queryElement.add(dataForm.getElement());
            }
        }
    }

    else {
        // If we didn't find a DiscoInfoProvider then answer a not found error
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:com.adspore.splat.xep0060.CollectionNode.java

License:Open Source License

/**
 * Notification that a new node was created and added to this node. Trigger notifications
 * to node subscribers whose subscription type is {@link NodeSubscription.Type#nodes} and
 * have the proper depth.//from w ww .j a v a  2 s  .  c  o m
 *
 * @param child the newly created node that was added to this node.
 */
void childNodeAdded(Node child) {
    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    Element item = event.addElement("items").addElement("item");
    item.addAttribute("id", child.getNodeID());
    if (mDeliverPayloads) {
        item.add(child.getMetadataForm().getElement());
    }
    // Broadcast event notification to subscribers
    broadcastCollectionNodeEvent(child, message);
}

From source file:com.adspore.splat.xep0060.CollectionNode.java

License:Open Source License

/**
 * Notification that a child node was deleted from this node. Trigger notifications
 * to node subscribers whose subscription type is {@link NodeSubscription.Type#nodes} and
 * have the proper depth.//from ww w  . j a  v a 2  s .c om
 *
 * @param child the deleted node that was removed from this node.
 */
void childNodeDeleted(Node child) {
    // Build packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
    event.addElement("delete").addAttribute("node", child.getNodeID());
    // Broadcast event notification to subscribers
    broadcastCollectionNodeEvent(child, message);
}

From source file:com.adspore.splat.xep0060.LeafNode.java

License:Open Source License

/**
 * Sends an IQ result with the list of items published to the node. Item ID and payload
 * may be included in the result based on the node configuration.
 *
 * @param originalRequest the IQ packet sent by a subscriber (or anyone) to get the node items.
 * @param publishedItems the list of published items to send to the subscriber.
 * @param forceToIncludePayload true if the item payload should be include if one exists. When
 *        false the decision is up to the node.
 *///from   w  w  w  .j  a va 2  s.  c o m
void sendPublishedItems(IQ originalRequest, List<PublishedItem> publishedItems, boolean forceToIncludePayload) {
    IQ result = IQ.createResultIQ(originalRequest);
    Element pubsubElem = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
    Element items = pubsubElem.addElement("items");
    items.addAttribute("node", getNodeID());

    for (PublishedItem publishedItem : publishedItems) {
        Element item = items.addElement("item");
        if (isItemRequired()) {
            item.addAttribute("id", publishedItem.getID());
        }
        if ((forceToIncludePayload || isPayloadDelivered()) && publishedItem.getPayload() != null) {
            item.add(publishedItem.getPayload().createCopy());
        }
    }
    // Send the result
    mService.send(result);
}