Example usage for org.dom4j Element addAttribute

List of usage examples for org.dom4j Element addAttribute

Introduction

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

Prototype

Element addAttribute(QName qName, String value);

Source Link

Document

Adds the attribute value of the given fully qualified name.

Usage

From source file:com.magnet.mmx.server.plugin.mmxmgmt.bot.RPSLSPlayerBotProcessor.java

License:Apache License

/**
 * Build a message by randomly choosing from the possible choices.
 * @param sourceFrom/* ww w  . ja va2  s  .  c  o  m*/
 * @param sourceTo
 * @param gameInfo
 * @return
 */
protected Message buildChoiceMessage(JID sourceFrom, JID sourceTo, RPSLSGameInfo gameInfo) {
    JID fromJID = sourceTo;
    JID toJID = sourceFrom;

    String appId = JIDUtil.getAppId(toJID);

    Message choiceMessage = new Message();

    MessageIdGenerator generator = new MessageIdGeneratorImpl();
    String id = generator.generate(toJID.getNode(), appId, null);
    choiceMessage.setID(id);
    choiceMessage.setType(Message.Type.chat);
    choiceMessage.setTo(toJID);
    choiceMessage.setFrom(fromJID);

    Element mmx = choiceMessage.addChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);
    Element internalMeta = mmx.addElement(Constants.MMX_MMXMETA);
    String userId = JIDUtil.getUserId(toJID);
    String devId = fromJID.getResource();
    //mmx meta
    String mmxMetaJSON = MMXMetaBuilder.build(userId, devId);
    internalMeta.setText(mmxMetaJSON);

    Element meta = mmx.addElement(Constants.MMX_META);
    ChoiceRPSLSGameInfo choice = new ChoiceRPSLSGameInfo();
    choice.setGameId(gameInfo.getGameId());
    choice.setLosses(0);
    choice.setWins(0);
    choice.setTies(0);
    Date current = new Date();
    choice.setTimestamp(current.getTime());
    choice.setType(RPSLSMessageType.CHOICE);
    String myUserId = JIDUtil.getUserId(sourceTo);
    choice.setUsername(myUserId); // user id of the bot user.
    String choiceValue = getRandomChoice();
    choice.setChoice(choiceValue);

    String choiceJSON = choice.toJson();
    meta.setText(choiceJSON);

    Element payloadElement = mmx.addElement(Constants.MMX_PAYLOAD);
    DateFormat fmt = Utils.buildISO8601DateFormat();
    String formattedDateTime = fmt.format(new Date());
    payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, formattedDateTime);
    String text = String.format(CHOICE_TEMPLATE, choiceValue);
    payloadElement.setText(text);
    payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, MessageBuilder.buildChunkAttributeValue(text));

    return choiceMessage;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.context.GeoEventDispatcher.java

License:Apache License

static Message buildGeoMessageFromPubSubIQ(final IQ geoIQ) {
    Message geoMessage = null;/*w  w  w  . j av  a2s  .c om*/
    if (IQ.Type.set == geoIQ.getType() && geoIQ.getTo().toString().startsWith("pubsub")) {
        // find 'geoloc'
        Element element = geoIQ.getChildElement();
        Element action = element.element("publish");
        if (action != null) {
            String nodeID = action.attributeValue("node");
            if (nodeID != null && nodeID.endsWith(TopicHelper.TOPIC_GEOLOC)) {
                // Entity publishes an item
                geoMessage = new Message();
                geoMessage.setType(Message.Type.chat);
                Map<String, String> geoValues = new HashMap<String, String>();
                JID from = geoIQ.getFrom();
                String appId = JIDUtil.getAppId(from);
                geoValues.put(APP_ID, appId);

                String userId = JIDUtil.getUserId(from);
                geoValues.put(USER_ID, userId);

                String deviceId = JIDUtil.getResource(from.toString());
                geoValues.put(DEVICE_ID, deviceId);

                Iterator<Element> items = action.elementIterator("item");
                if (items != null) {
                    while (items.hasNext()) {
                        Element item = (Element) items.next();
                        Element mmx = item.element(Constants.MMX_ELEMENT);
                        if (mmx == null)
                            continue;
                        Element payload = mmx.element(Constants.MMX_PAYLOAD);
                        if (payload == null)
                            return null; // not a valid MMX payload, ignore it
                        Attribute timestamp = payload.attribute(Constants.MMX_ATTR_STAMP);
                        if (timestamp != null) {
                            geoValues.put(Constants.MMX_ATTR_STAMP, timestamp.getValue());
                        }
                        String geoData = payload.getTextTrim();
                        GeoLoc geoLoc = GsonData.getGson().fromJson(geoData, GeoLoc.class);
                        if (geoLoc.getAccuracy() != null) {
                            geoValues.put(ACCURACY, geoLoc.getAccuracy().toString());
                        }
                        if (geoLoc.getLng() != null && geoLoc.getLat() != null) {
                            geoValues.put(LONG, geoLoc.getLng().toString());
                            geoValues.put(LAT, geoLoc.getLat().toString());
                            // calculate geohash
                            GeoPoint point = new GeoPointDefaultImpl(geoLoc.getLat(), geoLoc.getLng());
                            geoValues.put(GEOHASH, localGeoEndocoder.get().encodePoint(point));
                        }
                        if (geoLoc.getAlt() != null) {
                            geoValues.put(ALTITUDE, Integer.toString((int) geoLoc.getAlt().floatValue()));
                        }
                        Element geoElement = geoMessage.addChildElement(Constants.MMX_ELEMENT,
                                Constants.MMX_NS_CONTEXT);
                        geoElement.addAttribute(Constants.MMX_ATTR_MTYPE, Constants.MMX_MTYPE_GEOLOC);
                        JSONObject geoJson = new JSONObject(geoValues);
                        geoElement.setText(geoJson.toString());
                        geoMessage.setBody(geoJson.toString());

                        return geoMessage;

                    }
                }
            }
        }
    }
    return null;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.handler.MMXChannelManager.java

License:Apache License

private boolean sendLastPublishedItem(PublishedItem publishedItem, NodeSubscription subNode, JID to) {
    if (!subNode.canSendPublicationEvent(publishedItem.getNode(), publishedItem)) {
        return false;
    }//from  w w w  .j  a  v a  2 s  .  c  o  m
    Node node = subNode.getNode();
    Message notification = new Message();
    Element event = notification.getElement().addElement("event", "http://jabber.org/protocol/pubsub#event");
    Element items = event.addElement("items");
    items.addAttribute("node", node.getNodeID());
    Element item = items.addElement("item");
    if (publishedItem.getNode().isItemRequired()) {
        item.addAttribute("id", publishedItem.getID());
    }
    if (node.isPayloadDelivered() && publishedItem.getPayload() != null) {
        item.add(publishedItem.getPayload().createCopy());
    }
    // Add a message body (if required)
    if (subNode.isIncludingBody()) {
        notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body"));
    }
    // Include date when published item was created
    notification.getElement().addElement("delay", "urn:xmpp:delay").addAttribute("stamp",
            XMPPDateTimeFormat.format(publishedItem.getCreationDate()));
    // Send the event notification to the subscriber
    node.getService().sendNotification(node, notification, to);
    //    node.getService().sendNotification(node, notification, subNode.getJID());
    return true;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.handler.MMXChannelManager.java

License:Apache License

private boolean sendLastPublishedItems(List<PublishedItem> publishedItems, NodeSubscription subNode, JID to) {
    PublishedItem pubItem = publishedItems.get(0);
    if (!subNode.canSendPublicationEvent(pubItem.getNode(), pubItem)) {
        return false;
    }/*from   w w  w .jav a 2  s .c om*/
    Node node = subNode.getNode();
    Message notification = new Message();
    Element event = notification.getElement().addElement("event", "http://jabber.org/protocol/pubsub#event");
    Element items = event.addElement("items");
    items.addAttribute("node", node.getNodeID());
    for (PublishedItem publishedItem : publishedItems) {
        Element item = items.addElement("item");
        if (publishedItem.getNode().isItemRequired()) {
            item.addAttribute("id", publishedItem.getID());
        }
        if (node.isPayloadDelivered() && publishedItem.getPayload() != null) {
            item.add(publishedItem.getPayload().createCopy());
        }
    }
    // Add a message body (if required)
    if (subNode.isIncludingBody()) {
        notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body"));
    }
    // Include date when published item was created
    notification.getElement().addElement("delay", "urn:xmpp:delay").addAttribute("stamp",
            XMPPDateTimeFormat.format(pubItem.getCreationDate()));
    // Send the event notification to the subscriber
    node.getService().sendNotification(node, notification, to);
    // node.getService().sendNotification(node, notification, subNode.getJID());
    return true;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.message.MessageBuilder.java

License:Apache License

public Message build() {
    Message message = new Message();
    String id = idGenerator.generate(userId, appEntity.getAppId(),
            deviceEntity != null ? deviceEntity.getDeviceId() : null);
    message.setID(id);//from w  w w  .j  a v  a2 s  . co m
    Element mmxElement = message.addChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);

    if (replyTo != null) {
        if (metadata == null) {
            metadata = new HashMap<String, String>();
        }
        metadata.put(MMXServerConstants.REPLY_TO, formatReplyTo(replyTo));
    }

    if (metadata == null) {
        metadata = new HashMap<String, String>();
    }
    //as per the latest changes we need to add the content to the metadata using key "textContent"
    metadata.put(MMXServerConstants.TEXT_CONTENT_KEY, messageContent);

    Map<String, String> meta = metadata;
    String metaJSON = GsonData.getGson().toJson(meta);
    Element metaElement = mmxElement.addElement(Constants.MMX_META);
    metaElement.setText(metaJSON);

    Element payloadElement = mmxElement.addElement(Constants.MMX_PAYLOAD);

    DateFormat fmt = Utils.buildISO8601DateFormat();
    String formattedDateTime = fmt.format(new Date(utcTime));
    payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, formattedDateTime);
    String text = messageContent;
    payloadElement.setText(text);
    payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, buildChunkAttributeValue(text));

    message.setType(Message.Type.chat);
    message.setFrom(buildFromJID());
    message.setTo(buildToJID());
    if (receipt) {
        //add the element for requesting read receipt
        message.addChildElement(Constants.XMPP_REQUEST, Constants.XMPP_NS_RECEIPTS);
    }
    //https://magneteng.atlassian.net/browse/MOB-2035
    //add a body
    message.setBody(MMXServerConstants.MESSAGE_BODY_DOT);
    return message;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.message.MMXPacketExtension.java

License:Apache License

private void fillElement() {
    // It seems that DOM4J does XML escape too, so don't escape again!
    final boolean xmlEsc = false;
    Date sentTime = new Date();
    mPayload.setSentTime(sentTime);// ww w  . ja va 2 s .  c o  m

    if (mHeaders != null) {
        Element metaElement = this.element.addElement(Constants.MMX_META);
        // No need to do XML escape for the headers because GSON is XML safe.
        metaElement.setText(GsonData.getGson().toJson(mHeaders));
    }
    if (mPayload.getData() != null || mPayload.getFile() != null) {
        Element payloadElement = this.element.addElement(Constants.MMX_PAYLOAD);
        if (mPayload.getMsgType() != null) {
            payloadElement.addAttribute(Constants.MMX_ATTR_MTYPE, mPayload.getMsgType());
        }
        if (mPayload.getCid() != null) {
            payloadElement.addAttribute(Constants.MMX_ATTR_CID, mPayload.getCid());
        }
        payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, mPayload.formatChunk());
        payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, TimeUtil.toString(sentTime));
        CharSequence csq = null;
        if (mPayload.getData() != null) {
            if (!xmlEsc) {
                csq = mPayload.getData();
            } else {
                if (mPayload.getDataSize() >= Constants.PAYLOAD_THRESHOLD) {
                    csq = FileUtil.encodeForXml(mPayload.getData());
                } else {
                    csq = Utils.escapeForXML(mPayload.getData());
                }
            }
        } else if (mPayload.getFile() != null) {
            csq = FileUtil.encodeFile(mPayload.getFile(), xmlEsc);
            mPayload.getFile().finish();
        }
        if (csq != null) {
            payloadElement.setText(csq.toString());
        }
        LOGGER.warn("fillElement : payload={}", csq.toString());
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.message.ServerAckMessageBuilder.java

License:Apache License

/**
 * Build the ServerAckMessage//from w  w  w  . ja v a  2  s .  c o m
 * @return Message
 */
public Message build() {

    JID sender = originalMessage.getFrom();
    String senderUserId = JIDUtil.getUserId(sender);
    String senderDeviceId = sender.getResource();

    JID receiver = originalMessage.getTo();
    String receiverUserId = JIDUtil.getUserId(receiver);
    String receiverDeviceId = receiver.getResource();

    Message ackMessage = new Message();
    ackMessage.setType(Message.Type.chat);
    ackMessage.setFrom(appId + "%" + appId + "@" + XMPPServer.getInstance().getServerInfo().getXMPPDomain());
    ackMessage.setTo(sender);
    ackMessage.setID(new MessageIdGeneratorImpl().generate(sender.toString(), appId, senderDeviceId));
    Element mmxElement = ackMessage.addChildElement(Constants.MMX, Constants.MMX_NS_MSG_SIGNAL);
    Element mmxMetaElement = mmxElement.addElement(Constants.MMX_MMXMETA);
    Map<String, ServerAckMmxMeta> mmxMetaMap = new HashMap<String, ServerAckMmxMeta>();
    ServerAckMmxMeta meta = new ServerAckMmxMeta();
    meta.setAckForMsgId(originalMessage.getID());
    meta.setReceiver(receiverUserId, receiverDeviceId);
    meta.setSender(senderUserId, senderDeviceId);
    mmxMetaMap.put(MMXServerConstants.SERVER_ACK_KEY, meta);

    String mmxMetaJSON = GsonData.getGson().toJson(mmxMetaMap);
    mmxMetaElement.setText(mmxMetaJSON);

    Element payloadElement = mmxElement.addElement(Constants.MMX_PAYLOAD);

    DateFormat fmt = Utils.buildISO8601DateFormat();
    String formattedDateTime = fmt.format(new Date());
    payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, formattedDateTime);
    String text = ".";
    payloadElement.setText(text);
    payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, MessageBuilder.buildChunkAttributeValue(text));
    ackMessage.setBody(MMXServerConstants.MESSAGE_BODY_DOT);
    return ackMessage;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.message.TopicMessageBuilder.java

License:Apache License

/**
 * <iq>//from  ww w . j  a  v a2 s .c  om
 * <pubsub>
 * <publish>
 * <item>
 * <mmx>
 * <p/>
 * </mmx>
 * </item>
 * </publish>
 * </pubsub>
 * </iq>
 *
 * @return
 */

public IQ build() {

    if (topicId == null) {
        throw new IllegalArgumentException("topicId needs to be specified");
    }

    IQ message = new IQ();

    String id = idGenerator.generateTopicMessageId(appId, topicId);
    String toAddress = "pubsub." + domain;
    JID from = buildFromJID(appEntity, domain);

    message.setType(IQ.Type.set);
    message.setID(id);
    message.setTo(toAddress);
    message.setFrom(from);

    Element pubsubElement = message.setChildElement(PUBSUB_NAME, PUBSUB_NS);
    Element publishElement = pubsubElement.addElement(PUBLISH_NAME);
    publishElement.addAttribute(ATTRIBUTE_NODE, topicId);
    Element itemElement = publishElement.addElement(ITEM_NAME);
    //we need to have an id attribute for the item element
    itemElement.addAttribute(Constants.XMPP_ATTR_ID, idGenerator.generateItemIdentifier(topicId));
    Element mmxElement = itemElement.addElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);

    Element payloadElement = mmxElement.addElement(Constants.MMX_PAYLOAD);
    payloadElement.addAttribute(Constants.MMX_ATTR_CTYPE, request.getContentType());
    payloadElement.addAttribute(Constants.MMX_ATTR_MTYPE, request.getMessageType());

    String formattedDateTime = TimeUtil.toString(new Date(utcTime));
    payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, formattedDateTime);
    String text = request.getContent();
    payloadElement.setText(text);
    payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, MessageBuilder.buildChunkAttributeValue(text));

    return message;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.IQUtils.java

License:Apache License

/**
 * Create an IQ MMX result from the request.  The element, namespace and
 * command are cloned.  The payload content type is set to JSON.
 * @param iq The request IQ./*from  www .ja  v  a 2  s .c o  m*/
 * @param payload The JSON payload.
 * @return An IQ MMX result.
 */
public static IQ createResultIQ(IQ iq, String payload) {
    IQ result = IQ.createResultIQ(iq);
    Element rqtElt = iq.getChildElement();
    Element rstElt = result.setChildElement(rqtElt.getName(), rqtElt.getNamespace().getText());
    rstElt.addAttribute(Constants.MMX_ATTR_COMMAND, rqtElt.attributeValue(Constants.MMX_ATTR_COMMAND));
    rstElt.addAttribute(Constants.MMX_ATTR_CTYPE, GsonData.CONTENT_TYPE_JSON);
    rstElt.setText(payload);
    return result;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.IQUtils.java

License:Apache License

/**
 * Create an error IQ from the request.  The element, namespace and command
 * are cloned.  The content type is set to JSON.
 * @param iq The request IQ.//  ww w .  j  a va2s .  co m
 * @param msg  Optional message.
 * @param code
 * @return An IQ MMX error.
 */
public static IQ createErrorIQ(IQ iq, String msg, int code) {
    IQ error = IQ.createResultIQ(iq);
    error.setType(IQ.Type.error);
    Element rqtElt = iq.getChildElement();
    Element errElt = error.setChildElement(rqtElt.getName(), rqtElt.getNamespace().getText());
    errElt.addAttribute(Constants.MMX_ATTR_COMMAND, rqtElt.attributeValue(Constants.MMX_ATTR_COMMAND));
    errElt.addAttribute(Constants.MMX_ATTR_CTYPE, GsonData.CONTENT_TYPE_JSON);
    MMXStatus status = new MMXStatus();
    status.setCode(code);
    status.setMessage(msg);
    errElt.setText(status.toJson());
    return error;
}