Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

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

License:Apache License

@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
    JID fromJID = iq.getFrom();/*from  w w w.  j  a v a2 s  .  com*/
    String appId = JIDUtil.getAppId(fromJID);
    //read the command
    Element element = iq.getChildElement();
    String payload = element.getText();
    String commandId = element.attributeValue(Constants.MMX_ATTR_COMMAND);

    if (commandId == null || commandId.isEmpty() || commandId.trim().isEmpty()) {
        return IQUtils.createErrorIQ(iq, MessageStatusCode.INVALID_COMMAND.getMessage(),
                MessageStatusCode.INVALID_COMMAND.getCode());
    }

    Constants.MessageCommand command = null;
    try {
        command = Constants.MessageCommand.valueOf(commandId);
    } catch (IllegalArgumentException e) {
        LOGGER.info("Invalid device command string:" + commandId, e);
    }
    if (command == null) {
        return IQUtils.createErrorIQ(iq, MessageStatusCode.INVALID_COMMAND.getMessage(),
                MessageStatusCode.INVALID_COMMAND.getCode());
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Processing command:" + command.toString());
    }

    switch (command) {
    case query:
        return processMessageQuery(iq, appId, payload);
    case getTags:
        return processGetTags(iq, appId, payload);
    case setTags:
        return processSetTags(iq, appId, payload);
    case addTags:
        return processAddTags(iq, appId, payload);
    case removeTags:
        return processRemoveTags(iq, appId, payload);
    case getEvents:
        return processGetEvents(iq, appId, payload);
    case setEvents:
        return processSetEvents(iq, appId, payload);
    case addEvents:
        return processAddEvents(iq, appId, payload);
    case removeEvents:
        return processRemoveEvents(iq, appId, payload);
    default:
        LOGGER.info("Unknown message command");
        return IQUtils.createErrorIQ(iq, MessageStatusCode.INVALID_COMMAND.getMessage(),
                MessageStatusCode.INVALID_COMMAND.getCode());
    }
}

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

License:Apache License

@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
    JID from = iq.getFrom();//from   w w  w  .  j  ava2s  . c o m
    String appId = JIDUtil.getAppId(from);
    Element element = iq.getChildElement();
    String payload = element.getText();
    String commandId = element.attributeValue(Constants.MMX_ATTR_COMMAND);

    if (commandId == null || commandId.isEmpty() || commandId.trim().isEmpty()) {
        return IQUtils.createErrorIQ(iq, StatusCode.INVALID_COMMAND.getMessage() + commandId,
                StatusCode.INVALID_COMMAND.getCode());
    }

    try {
        MMXStatus status;
        Constants.PubSubCommand command = Constants.PubSubCommand.valueOf(commandId);
        if (Log.isDebugEnabled()) {
            Log.debug("Processing command:" + command.toString());
        }
        MMXTopicManager topicMgr = MMXTopicManager.getInstance();
        switch (command) {
        case getlatest:
            status = topicMgr.processSendLastPublishedItems(from, appId,
                    SendLastPublishedItems.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case listtopics:
            TopicAction.ListResponse lstresp = topicMgr.listTopics(from, appId,
                    TopicAction.ListRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(lstresp));
        case createtopic:
            status = topicMgr.createTopic(from, appId, TopicAction.CreateRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case deletetopic:
            status = topicMgr.deleteTopic(from, appId, TopicAction.DeleteRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case getTopic:
            TopicInfo info = topicMgr.getTopic(from, appId, MMXTopicId.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(info));
        //      case publish:
        //        TopicOps.PublishResponse pubresp = publishToTopic(from, appId,
        //            TopicOps.PublishRequest.fromJson(payload)));
        //        return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(pubresp));
        case retract:
            status = topicMgr.retractFromTopic(from, appId, TopicAction.RetractRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case retractall:
            status = topicMgr.retractAllFromTopic(from, appId, TopicAction.RetractAllRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case subscribe:
            TopicAction.SubscribeResponse resp = topicMgr.subscribeTopic(from, appId,
                    TopicAction.SubscribeRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(resp));
        case unsubscribe:
            status = topicMgr.unsubscribeTopic(from, appId, TopicAction.UnsubscribeRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case unsubscribeForDev:
            status = topicMgr.unsubscribeForDev(from, appId,
                    TopicAction.UnsubscribeForDevRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case getSummary:
            TopicAction.SummaryResponse sumresp = topicMgr.getSummary(from, appId,
                    TopicAction.SummaryRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(sumresp));
        case getTags:
            TopicAction.TopicTags tagsresp = topicMgr.getTags(from, appId, MMXTopicId.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(tagsresp));
        case setTags:
            status = topicMgr.setTags(from, appId, TopicAction.TopicTags.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case addTags:
            status = topicMgr.addTags(from, appId, TopicAction.TopicTags.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case removeTags:
            status = topicMgr.removeTags(from, appId, TopicAction.TopicTags.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(status));
        case queryTopic:
            TopicAction.TopicQueryResponse qryresp = topicMgr.queryTopic(from, appId,
                    TopicAction.TopicQueryRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(qryresp));
        case searchTopic:
            TopicAction.TopicQueryResponse srchresp = topicMgr.searchTopic(from, appId,
                    TopicAction.TopicSearchRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(srchresp));
        case fetch:
            TopicAction.FetchResponse fetchresp = topicMgr.fetchItems(from, appId,
                    TopicAction.FetchRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, fetchresp.toJson());
        case searchByTags:
            List<TopicInfo> topiclist = topicMgr.searchByTags(from, appId, TagSearch.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(topiclist));
        case getItems:
            TopicAction.FetchResponse getresp = topicMgr.getItems(from, appId,
                    TopicAction.ItemsByIdsRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, getresp.toJson());
        case getSubscribers:
            TopicAction.SubscribersResponse subresp = topicMgr.getSubscribers(from, appId,
                    TopicAction.SubscribersRequest.fromJson(payload));
            return IQUtils.createResultIQ(iq, GsonData.getGson().toJson(subresp));
        }
    } catch (IllegalArgumentException e) {
        Log.info("Invalid pubsub command string:" + commandId, e);
        return IQUtils.createErrorIQ(iq, e.getMessage(), StatusCode.BAD_REQUEST.getCode());
    } catch (MMXException e) {
        return IQUtils.createErrorIQ(iq, e.getMessage(), e.getCode());
    }
    return IQUtils.createErrorIQ(iq, StatusCode.INVALID_COMMAND.getMessage() + commandId,
            StatusCode.INVALID_COMMAND.getCode());
}

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

License:Apache License

@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
    LOGGER.trace("handleIQ : {}", iq);
    JID fromJID = iq.getFrom();/* w  ww.  j a  v  a2  s  .c om*/
    String appId = JIDUtil.getAppId(fromJID);
    Element element = iq.getChildElement();
    String command = element.attributeValue(Constants.MMX_ATTR_COMMAND);
    String toJID = element.attributeValue(Constants.MMX_ATTR_DST);
    String deviceId = new JID(toJID).getResource();
    LOGGER.trace("handleIQ : toJID={}, deviceId={}", toJID, deviceId);

    MMXPushMessageValidator validator = new IQPushMessageValidator();
    MMXPushValidationResult validationResult = validator.validate(appId,
            JIDUtil.getUserId(new JID(toJID).getNode()), deviceId);

    if (validationResult instanceof MMXPushValidationFailure)
        return getRespIQ(iq, validationResult.getCode());

    String pushMessageId = PushUtil.generateId(appId, deviceId);
    MMXPayload mmxPayload = new MMXPushPayload(command, element.getText());
    PushSender sender = new PushMessageSender();
    PushResult pushResult = sender.push(appId, deviceId, mmxPayload,
            ((MMXPushValidationSuccess) validationResult).getContext());

    if (pushResult.isError())
        return getRespIQ(iq, PushStatusCode.ERROR_SENDING_PUSH);

    storeMessage(pushMessageId, deviceId, appId);
    return getRespIQ(iq, PushStatusCode.SUCCESSFUL);
}

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

License:Apache License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    LOGGER.info("MMXUserHandler.handleIQ called");
    JID from = packet.getFrom();//from w  w  w.j a  va  2s  .  c o  m
    String command = IQUtils.getCommand(packet);
    try {
        UserCommand cmd = UserCommand.valueOf(command);
        LocalClientSession session = (LocalClientSession) sessionManager.getSession(from);
        // Session must be authenticated for delete/query/update, and must not be
        // closed for create/reset.
        if (session == null || session.getStatus() == Session.STATUS_CLOSED
                || (session.getStatus() == Session.STATUS_CONNECTED
                        && (cmd != UserCommand.create && cmd != UserCommand.reset))) {
            IQ reply = IQUtils.createErrorIQ(packet, PacketError.Condition.not_authorized);
            if (session == null || packet.getFrom() != null) {
                return reply;
            } else {
                reply.setTo(session.getAddress());
                reply.setFrom((JID) null);
                session.process(reply);
                return null;
            }
        }

        JID fromJID;
        String appId;
        Element element = packet.getChildElement();
        String payload = element.getText();
        // These two commands have no "from".
        if (cmd != UserCommand.create && cmd != UserCommand.reset) {
            fromJID = packet.getFrom();
            appId = JIDUtil.getAppId(fromJID);
        } else {
            fromJID = null;
            appId = null;
        }

        switch (cmd) {
        case list:
            return handleListUsers(packet, fromJID, appId, payload);
        case get:
            return handleGetUser(packet, fromJID, appId, payload);
        case search:
            return handleSearchUser(packet, fromJID, appId, payload);
        case query:
            return handleQueryUser(packet, fromJID, appId, payload);
        case update:
            return handleUpdateUser(packet, fromJID, appId, payload);
        case delete:
            return handleDeleteUser(packet, fromJID, appId, payload);
        case getTags:
            return handleGetTags(packet, fromJID, appId, payload);
        case setTags:
            return handleSetTags(packet, fromJID, appId, payload);
        case addTags:
            return handleAddTags(packet, fromJID, appId, payload);
        case removeTags:
            return handleRemoveTags(packet, fromJID, appId, payload);
        case searchByTags:
            return handleSearchByTags(packet, fromJID, appId, payload);
        case create:
            IQ reply = handleCreateUser(packet, payload);
            // There was no "from"; send the reply directly to the client session
            reply.setTo(session.getAddress());
            reply.setFrom((JID) null);
            session.process(reply);
            return null;
        //    case reset:
        //      IQ reply = handleResetPassword(packet, payload);
        //      // there was no "from"; send the reply directly to the client session
        //      reply.setTo(session.getAddress());
        //      reply.setFrom((JID) null);
        //      return null;
        }
    } catch (IllegalArgumentException e) {
        LOGGER.info("Invalid user command string:" + command, e);
        return IQUtils.createErrorIQ(packet, e.getMessage(), StatusCode.BAD_REQUEST);
    }
    return IQUtils.createErrorIQ(packet, UserOperationStatusCode.INVALID_COMMAND.getMessage(),
            UserOperationStatusCode.INVALID_COMMAND.getCode());
}

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

License:Apache License

@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {

    LOGGER.debug("handleIQ : {}", iq);

    JID fromJID = iq.getFrom();/*from  w  w  w.  ja v a2 s.  co  m*/
    String appId = JIDUtil.getAppId(fromJID);

    Element element = iq.getChildElement();
    String command = element.attributeValue(Constants.MMX_ATTR_COMMAND);

    if (!isValidCommand(command))
        return getRespIQ(iq, PushStatusCode.BAD_COMMAND_VALUE);

    String toJID = element.attributeValue(Constants.MMX_ATTR_DST);
    String deviceId = new JID(toJID).getResource();
    LOGGER.trace("handleIQ : toJID={}, deviceId={}", toJID, deviceId);

    MMXPushMessageValidator validator = new IQPushMessageValidator();
    MMXPushValidationResult validationResult = validator.validate(appId,
            JIDUtil.getUserId(new JID(toJID).getNode()), deviceId);

    if (validationResult instanceof MMXPushValidationFailure)
        return getRespIQ(iq, validationResult.getCode());

    String pushMessageId = PushUtil.generateId(appId, deviceId);
    PingPong pingpong = new Gson().fromJson(element.getText(), PingPong.class);

    if (command.toLowerCase().equals(Constants.PingPongCommand.ping.name())) {
        LOGGER.trace("handleIQ : command is ping command checking url");
        if (Strings.isNullOrEmpty(pingpong.getUrl())) {
            String callbackUrl = CallbackUrlUtil.buildCallBackURL(pushMessageId);
            pingpong.setUrl(callbackUrl);
            LOGGER.trace("handleIQ : built url={} for messageID={}", callbackUrl, pushMessageId);
        }

    }

    MMXPayload mmxPayload = new MMXWakeupPayload(command, new Gson().toJson(pingpong));
    PushSender sender = new PushMessageSender();
    PushResult pushResult = sender.push(appId, deviceId, mmxPayload,
            ((MMXPushValidationSuccess) validationResult).getContext());
    if (pushResult.isError())
        return getRespIQ(iq, PushStatusCode.ERROR_SENDING_PUSH);

    storeMessage(pushMessageId, deviceId, appId, Constants.PingPongCommand.valueOf(command.toLowerCase()));
    return getRespIQ(iq, PushStatusCode.SUCCESSFUL);
}

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

License:Apache License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    long start = System.nanoTime();
    try {//from w w w  .java 2  s  . c o m
        Element element = packet.getChildElement();
        String payload = element.getText();
        MsgAck acknowledgement = GsonData.getGson().fromJson(payload, MsgAck.class);
        String from = acknowledgement.getFrom();
        String to = acknowledgement.getTo();
        String messageId = acknowledgement.getMsgId();

        MMXOfflineStorageUtil.removeMessage(to, messageId);

        String appId = JIDUtil.getAppId(to);
        String deviceId = JIDUtil.getResource(to);
        MessageDAO messageDAO = getMessageDAO();
        int count = messageDAO.messageDelivered(appId, deviceId, messageId);
        if (count == 0) {
            LOGGER.warn(String.format("No message updated for appId:%s deviceId:%s messageId:%s", appId,
                    deviceId, messageId));
        }
    } catch (Throwable t) {
        LOGGER.warn("Throwable in handleIQ", t);
    }
    /**
     * based on discussion with login2 we are returning 200 even if an exception is encountered when processing
     * these ack. The reason is the client can't deal with an error response.
     */
    MMXStatus response = new MMXStatus();
    response.setCode(MsgAckOperationStatusCode.DELIVERY_ACK_PROCESSED.getCode());
    IQ result = IQUtils.createResultIQ(packet, response.toJson());
    long end = System.nanoTime();
    long delta = end - start;
    String template = "Processed msgack in [%d] milliseconds";
    LOGGER.info(String.format(template, TimeUnit.MILLISECONDS.convert(delta, TimeUnit.NANOSECONDS)));
    return result;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.interceptor.MessageDistributedAnnotator.java

License:Apache License

@Override
public void annotate(Message message) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Annotating a message with id:{}", message.getID());
    }//from w  w  w . ja va 2s.  co  m
    Element mmx = message.getChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);
    Element internalMeta = mmx.element(Constants.MMX_MMXMETA);
    String currentInternalMetaJSON = internalMeta != null ? internalMeta.getText() : null;

    JsonObject jsonObject = null;

    if (currentInternalMetaJSON != null && !currentInternalMetaJSON.isEmpty()) {
        JsonParser parser = new JsonParser();
        try {
            jsonObject = parser.parse(currentInternalMetaJSON).getAsJsonObject();
        } catch (JsonSyntaxException e) {
            LOGGER.warn("Failed to parse mmxmeta string:{} as JSON string", currentInternalMetaJSON, e);
            //assume that the mmxmeta was some invalid JSON.
            jsonObject = new JsonObject();
        }
    } else {
        jsonObject = new JsonObject();
    }
    jsonObject.addProperty(MMXServerConstants.DISTRIBUTED_KEY, true);
    ;
    String updatedInternalMetaJSON = jsonObject.toString();
    if (internalMeta == null) {
        internalMeta = mmx.addElement(Constants.MMX_MMXMETA);
    }
    internalMeta.setText(updatedInternalMetaJSON);
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.interceptor.MessageDistributedAnnotator.java

License:Apache License

@Override
public boolean isAnnotated(Message message) {
    boolean rv = false;
    Element mmx = message.getChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);
    Element internalMeta = mmx.element(Constants.MMX_MMXMETA);
    String currentInternalMetaJSON = internalMeta != null ? internalMeta.getText() : null;
    if (currentInternalMetaJSON != null && !currentInternalMetaJSON.isEmpty()) {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(currentInternalMetaJSON).getAsJsonObject();
        JsonObject jsonObject = jsonElement.isJsonObject() ? jsonElement.getAsJsonObject() : null;
        if (jsonObject != null) {
            rv = jsonObject.has(MMXServerConstants.DISTRIBUTED_KEY);
        }/*from  w  w  w.  ja v a2 s . com*/
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Checking if message :{} result:{}", message, rv);
    }
    return rv;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.interceptor.MMXMessageHandlingRule.java

License:Apache License

private MMXid[] getRecipients(PacketExtension payload) {
    Element mmxElement = payload.getElement();
    if (mmxElement == null) {
        return null;
    }//from  w  w w . j av a 2 s. c om
    Element element = mmxElement.element(Constants.MMX_MMXMETA);
    if (element == null) {
        return null;
    }
    MmxHeaders mmxMeta = GsonData.getGson().fromJson(element.getText(), MmxHeaders.class);
    List<Map<String, String>> list = (List<Map<String, String>>) mmxMeta.getHeader(MmxHeaders.TO, null);
    if (list == null) {
        return null;
    }
    int i = 0;
    MMXid[] recipients = new MMXid[list.size()];
    for (Map<String, String> map : list) {
        recipients[i++] = MMXid.fromMap(map);
    }
    return recipients;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.interceptor.MMXMessageHandlingRule.java

License:Apache License

private Object getMmxMeta(PacketExtension payload, String key, Object defVal) {
    Element mmxElement = payload.getElement();
    if (mmxElement == null) {
        return defVal;
    }//www.j ava  2 s. c  o  m
    Element element = mmxElement.element(Constants.MMX_MMXMETA);
    if (element == null) {
        return defVal;
    }
    MmxHeaders mmxMeta = GsonData.getGson().fromJson(element.getText(), MmxHeaders.class);
    return mmxMeta.getHeader(key, defVal);
}