Example usage for org.dom4j Element attributeValue

List of usage examples for org.dom4j Element attributeValue

Introduction

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

Prototype

String attributeValue(QName qName);

Source Link

Document

This returns the attribute value for the attribute with the given fully qualified name or null if there is no such attribute or the empty string if the attribute value is empty.

Usage

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

private synchronized String searchHotelCacheChange(int cityId, Date fromTimeStamp) {
    //headerAPI?/*from   w w  w.ja va  2  s  .  c  o m*/
    Cache cache = getCache();
    String cacheKey = ConfigData.OTA_HotelCacheChange_Request;
    net.sf.ehcache.Element cacheElement = cache.get(cacheKey);
    if (cacheElement != null) {
        Element headerElement = (Element) cacheElement.getValue();
        int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount"));
        int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1;
        logger.info("AccessCount=" + headerElement.attributeValue("AccessCount") + ", CurrentCount="
                + headerElement.attributeValue("CurrentCount") + ", ResetTime="
                + headerElement.attributeValue("ResetTime"));
        if (currentCount >= accessCount) {
            try {
                logger.info("Sleep for one minute.");
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
                logger.warn(Thread.currentThread().getName() + " is interrupted.");
                return "ER#SearchHotelCacheChange thread.sleep is interrupted.";
            }
        }
    }

    HotelRequestBody request = new HotelRequestBody();
    request.createHotelCacheChangeRequest();

    String cacheFromTimeStamp = DateUtil.formatDate(fromTimeStamp, "yyyy-MM-dd'T'HH:mm:ss");
    request.getHotelCacheChangeRequest().getCacheSearchCriteria().setCacheFromTimestamp(cacheFromTimeStamp);
    request.getHotelCacheChangeRequest().getCacheSearchCriteria().getCacheSearchCriterion()
            .setHotelCityCode(cityId);

    //logger.info("OTA_HotelCacheChange: " + cacheFromTimeStamp + ", " + cityId);

    String xml;

    try {
        xml = createXml4HotelRequestBody(request, ConfigData.OTA_HotelCacheChange_Request);
    } catch (JAXBException e) {
        e.printStackTrace();
        return "<xml>" + e.getMessage() + "</xml>";
    }

    String paraName = "requestXML";
    Date basetime = DateUtil.getCurDateTime();
    String response = execApiRequest(xml, ConfigData.OTA_HotelCacheChange_url, paraName);
    int spantime = DateUtil.getPastTime(basetime);
    logger.info(ConfigData.OTA_HotelCacheChange_Request + ": api elapsed  " + spantime + "ms");

    return response;
}

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

License:Open Source License

/**
 * the file parse to a list //from  w w  w  .j  av a 2  s .  c  o m
 * @return
 */
public List<BookMark> fileToList() {
    List<BookMark> list = new ArrayList<BookMark>();
    List<Element> el = null;
    Element elt = mDocument.getRootElement();
    if (null != elt)
        el = elt.elements("mark");
    if (el != null) {
        Iterator<Element> l = el.iterator();
        while (l.hasNext()) {
            Element Element = (Element) l.next();
            int offset = 0;
            try {
                offset = Integer.parseInt(Element.attributeValue("currentOffset"));
            } catch (Exception e) {
                offset = 0;
            }
            BookMark b = new BookMark(offset, Element.attributeValue("markName"), Constant.BOOK_ID_IN_DATABASE);
            list.add(b);
        }
    }
    System.gc();
    return list;
}

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

License:Open Source License

public IQ handleDiscoInfoIQ(IQ packet) {
    /*//from  w  w  w . j  a  v a2s  .  c om
     * 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.xep0030.DiscoItem.java

License:Open Source License

public DiscoItem(Element element) {
    this.element = element;
    jid = new JID(element.attributeValue("jid"));
    action = element.attributeValue("action");
    name = element.attributeValue("name");
    node = element.attributeValue("node");
}

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

License:Open Source License

public IQ handleDiscoItemsIQ(IQ packet) {
    /*//from w w  w .ja  va 2  s .  co m
     * 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, there may be more than one.
     *  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 regarding a particular node, as a node
     *  may host multiple identities.  For instance, a JID+Node may support PubSub as well
     *  as ping and time. Every node supports info and item.
     *  
     *  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(); //   Assumption: it's a 'query' object...
    final String node = queryElement.attributeValue("node");

    final JID targetJID = (null != node) ? JIDUtils.setNodeIDAsResource(packet.getTo(), node) : packet.getTo();
    final JID senderJID = packet.getFrom();
    /*
      * 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<DiscoItemsProvider> itemProviders = getProviders(targetJID.toBareJID());
    if (!itemProviders.isEmpty()) {
        /*
         *    Begin looping through the providers, checking with each to provide them with the
         * opportunity to add information on their behalf if they have any to add.
         */
        Iterator<DiscoItemsProvider> providerItor = itemProviders.iterator();
        while (providerItor.hasNext()) {
            //   Add the items that this provider says it has...
            DiscoItemsProvider provider = providerItor.next();

            if (true == provider.hasItems(targetJID, senderJID)) {
                Iterator<DiscoItem> itemItor = provider.getItems(targetJID, senderJID);
                while (itemItor.hasNext()) {
                    queryElement.add(itemItor.next().getElement().createCopy());
                }
            }
        }
    } else {
        // If we didn't find a DiscoItemsProvider then answer a not found error
        reply.setError(PacketError.Condition.item_not_found);
    }
    return reply;
}

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

License:Open Source License

/**
 * Publishes the list of items to the node. Event notifications will be sent to subscribers
 * for the new published event. The published event may or may not include an item. When the
 * node is not persistent and does not require payloads then an item is not going to be created
 * nore included in the event notification.<p>
 *
 * When an affiliate has many subscriptions to the node, the affiliate will get a
 * notification for each set of items that affected the same list of subscriptions.<p>
 *
 * When an item is included in the published event then a new {@link PublishedItem} is
 * going to be created and added to the list of published item. Each published item will
 * have a unique ID in the node scope. The new published item will be added to the end
 * of the published list to keep the cronological order. When the max number of published
 * items is exceeded then the oldest published items will be removed.<p>
 *
 * For performance reasons the newly added published items and the deleted items (if any)
 * are saved to the database using a background thread. Sending event notifications to
 * node subscribers may also use another thread to ensure good performance.<p>
 *
 * @param publisher the full JID of the user that sent the new published event.
 * @param itemElements list of dom4j elements that contain info about the published items.
 *//*  w  ww. ja v  a  2 s .  c o  m*/
public void publishItems(JID publisher, List<Element> itemElements) {
    List<PublishedItem> newPublishedItems = new ArrayList<PublishedItem>();
    if (isItemRequired()) {
        String itemID;
        Element payload;
        PublishedItem newItem;
        for (Element item : itemElements) {
            itemID = item.attributeValue("id");
            List entries = item.elements();
            payload = entries.isEmpty() ? null : (Element) entries.get(0);

            // Make sure that the published item has a unique ID if NOT assigned by publisher
            if (itemID == null) {
                itemID = genIdSeed + sequenceCounter.getAndIncrement();
            }

            // Create a new published item
            newItem = new PublishedItem(this, publisher, itemID, new Date(mService.mContext.getContextTime()));
            newItem.setPayload(payload);
            // Add the new item to the list of published items
            newPublishedItems.add(newItem);
            setLastPublishedItem(newItem);
        }
    }

    // Build event notification packet to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");

    // Broadcast event notification to subscribers and parent node subscribers
    Set<NodeAffiliate> affiliatesToNotify = new HashSet<NodeAffiliate>(affiliates);

    // Get affiliates that are subscribed to a parent in the hierarchy of parent nodes
    for (CollectionNode parentNode : getParents()) {
        for (NodeSubscription subscription : parentNode.getSubscriptions()) {
            affiliatesToNotify.add(subscription.getAffiliate());
        }
    }
    mService.submitTask(
            new NotifyAffiliatesCallable(affiliatesToNotify, message, event, this, newPublishedItems));
}

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

License:Open Source License

/**
 * Publishes an item or retracts an item based on the caller provided criteria. Provides a means
 * of controlling PublishedItem visibility on a user by user basis outside of the subscription
 * scheme.//from   w  w  w.ja  v a  2s  .c o m
 * @param publisher JID of the entity responsible for the publishing/retracting/ignoring operation
 * @param publishCriteria Caller supplied test that will be applied to each subscriber
 * @param itemElements List of 'item' elements which are to be published.
 */
public void publishOrRetractByCriteria(JID publisher, IPublishCriteria publishCriteria,
        List<Element> itemElements) {
    List<PublishedItem> newPublishedItems = new ArrayList<PublishedItem>();

    if (isItemRequired()) {
        String itemID;
        Element payload;
        PublishedItem newItem;
        for (Element item : itemElements) {
            itemID = item.attributeValue("id");
            List entries = item.elements();
            payload = entries.isEmpty() ? null : (Element) entries.get(0);

            // Make sure that the published item has a unique ID if NOT assigned by publisher
            if (itemID == null) {
                itemID = genIdSeed + sequenceCounter.getAndIncrement();
            }

            // Create a new published item
            newItem = new PublishedItem(this, publisher, itemID, new Date(mService.mContext.getContextTime()));
            newItem.setPayload(payload);
            // Add the new item to the list of published items
            newPublishedItems.add(newItem);
            setLastPublishedItem(newItem);
        }
    }

    // Build both event notification packets to broadcast to subscribers
    Message message = new Message();
    Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");

    Set<NodeAffiliate> affiliatesToNotify = new HashSet<NodeAffiliate>(affiliates);
    for (CollectionNode parentNode : getParents()) {
        for (NodeSubscription subscription : parentNode.getSubscriptions()) {
            affiliatesToNotify.add(subscription.getAffiliate());
        }
    }

    for (NodeAffiliate affiliate : affiliatesToNotify) {
        ItemPublishOperation operation = publishCriteria.getOperationForAffiliate(this, affiliate,
                newPublishedItems);
        switch (operation) {
        case publish:
            if (isPayloadDelivered()) {
                affiliate.sendPublishedNotifications(message, event, this, newPublishedItems);
            } else {
                affiliate.sendPublishedNotifications(message, event, this, Collections.EMPTY_LIST);
            }
            break;

        case retract:
            if (isNotifiedOfRetract()) {
                affiliate.sendDeletionNotifications(message, event, this, newPublishedItems);
            }
            break;

        case none:
            //   Do nothing, don't send message but don't retract either..'no-op'
            break;
        }
    }
}

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

License:Open Source License

/**
 * Handles IQ packets sent to the pubsub service. Requests of disco#info and disco#items
 * are not being handled by the engine. Instead the service itself should handle disco packets.
 *
 * @param service the PubSub service this action is to be performed for.
 * @param iq the IQ packet sent to the pubsub service.
 * @return true if the IQ packet was handled by the engine.
 *///from   www  .  j a v a  2  s .c o m
public static IQ process(PubSubService service, IQ iq) {
    // Ignore IQs of type ERROR or RESULT
    if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) {
        return createErrorPacket(iq, Condition.bad_request, null);
    }

    Element childElement = iq.getChildElement();
    String namespace = null;

    if (childElement != null) {
        namespace = childElement.getNamespaceURI();
    }

    //   PUBSUB
    if ("http://jabber.org/protocol/pubsub".equals(namespace)) {

        //   PUBLISH
        Element action = childElement.element("publish");
        if (action != null) {
            // Entity publishes an item
            return publishItemsToNode(service, iq, action);
        }

        //   SUBSCRIBE
        action = childElement.element("subscribe");
        if (action != null) {
            // Entity subscribes to a node
            return subscribeNode(service, iq, childElement, action);
        }

        //   OPTIONS
        action = childElement.element("options");
        if (action != null) {
            if (IQ.Type.get == iq.getType()) {
                // Subscriber requests subscription options form
                return getSubscriptionConfiguration(service, iq, childElement, action);
            } else {
                // Subscriber submits completed options form
                return configureSubscription(service, iq, action);
            }
        }

        //   CREATE
        action = childElement.element("create");
        if (action != null) {
            // Entity is requesting to create a new node
            return createNode(service, iq, childElement, action);
        }

        //   UNSUBSCRIBE
        action = childElement.element("unsubscribe");
        if (action != null) {
            // Entity unsubscribes from a node
            return unsubscribeNode(service, iq, action);
        }

        //   GET SUBSCRIPTIONS
        action = childElement.element("subscriptions");
        if (action != null) {
            // Entity requests all current subscriptions
            return getSubscriptions(service, iq, childElement);
        }

        //   GET AFFILIATIONS
        action = childElement.element("affiliations");
        if (action != null) {
            // Entity requests all current affiliations
            return getAffiliations(service, iq, childElement);
        }

        //   GET ITEMS
        action = childElement.element("items");
        if (action != null) {
            // Subscriber requests all active items
            return getPublishedItems(service, iq, action);
        }

        //   RETRACT
        action = childElement.element("retract");
        if (action != null) {
            // Entity deletes an item
            return deleteItems(service, iq, action);
        }

        // Unknown action requested
        //   TODO:  Add error packet
        return createErrorPacket(iq, PacketError.Condition.bad_request, null);
    }

    else if ("http://jabber.org/protocol/pubsub#owner".equals(namespace)) {
        //   CONFIGURE
        Element action = childElement.element("configure");
        if (action != null) {
            String nodeID = action.attributeValue("node");
            if (nodeID == null) {
                // if user is not sysadmin then return nodeid-required error
                if (!service.isServiceAdmin(iq.getFrom()) || !service.isCollectionNodesSupported()) {
                    // Configure elements must have a node attribute so answer an error
                    Element pubsubError = DocumentHelper.createElement(
                            QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
                    return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
                } else {
                    // Sysadmin is trying to configure root collection node
                    nodeID = service.getRootCollectionNode().getNodeID();
                }
            }
            if (IQ.Type.get == iq.getType()) {
                // Owner requests configuration form of a node
                return getNodeConfiguration(service, iq, childElement, nodeID);
            } else {
                // Owner submits or cancels node configuration form
                configureNode(service, iq, action, nodeID);
            }
        }

        //   DEFAULT
        action = childElement.element("default");
        if (action != null) {
            // Owner requests default configuration options for
            // leaf or collection nodes
            return getDefaultNodeConfiguration(service, iq, childElement, action);
        }

        //   DELETE
        action = childElement.element("delete");
        if (action != null) {
            // Owner deletes a node
            return deleteNode(service, iq, action);
        }

        //   SUBSCRIPTIONS
        action = childElement.element("subscriptions");
        if (action != null) {
            if (IQ.Type.get == iq.getType()) {
                // Owner requests all affiliated entities
                return getNodeSubscriptions(service, iq, action);
            } else {
                return modifyNodeSubscriptions(service, iq, action);
            }
        }

        //   AFFILIATIONS
        action = childElement.element("affiliations");
        if (action != null) {
            if (IQ.Type.get == iq.getType()) {
                // Owner requests all affiliated entities
                return getNodeAffiliations(service, iq, action);
            } else {
                return modifyNodeAffiliations(service, iq, action);
            }
        }

        //   PURGE
        action = childElement.element("purge");
        if (action != null) {
            // Owner purges items from a node
            return purgeNode(service, iq, action);

        }
    }

    //   TODO:  Temporarily blocking commands; this should be handled by the command service, not pubsub
    //        //   GET COMMANDS
    //        else if (SplatNamespaces.NAMESPACE_COMMANDS.equals(namespace)) {
    //            // Process ad-hoc command
    //            IQ reply = service.getManager().process(iq);
    //            router.route(reply);
    //            return true;
    //        }
    return createErrorPacket(iq, PacketError.Condition.bad_request, null);
}

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

License:Open Source License

private static IQ publishItemsToNode(PubSubService service, IQ iq, Element publishElement) {
    String nodeID = publishElement.attributeValue("node");

    if (nodeID == null) {
        // No node was specified. Return bad_request error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }//from  ww w .j  av  a2s.  co m

    // Look for the specified node
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }

    JID from = iq.getFrom();
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = new JID(from.getNode(), from.getDomain(), null, true);
    if (!node.getPublisherModel().canPublish(node, owner) && !service.isServiceAdmin(owner)) {
        // Entity does not have sufficient privileges to publish to node
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    if (node.isCollectionNode()) {
        // Node is a collection node. Return feature-not-implemented error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "publish");
        return createErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
    }

    LeafNode leafNode = (LeafNode) node;
    Iterator itemElements = publishElement.elementIterator("item");

    // Check that an item was included if node persist items or includes payload
    if (!itemElements.hasNext() && leafNode.isItemRequired()) {
        Element pubsubError = DocumentHelper
                .createElement(QName.get("item-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }

    // Check that no item was included if node doesn't persist items and doesn't
    // includes payload
    if (itemElements.hasNext() && !leafNode.isItemRequired()) {
        Element pubsubError = DocumentHelper
                .createElement(QName.get("item-forbidden", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }

    List<Element> items = new ArrayList<Element>();
    List entries;
    Element payload;
    while (itemElements.hasNext()) {
        Element item = (Element) itemElements.next();
        entries = item.elements();
        payload = entries.isEmpty() ? null : (Element) entries.get(0);
        // Check that a payload was included if node is configured to include payload
        // in notifications
        if (payload == null && leafNode.isPayloadDelivered()) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("payload-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        }

        // Check that the payload (if any) contains only one child element
        if (entries.size() > 1) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("invalid-payload", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);

        }
        items.add(item);
    }

    // Publish item and send event notifications to subscribers
    leafNode.publishItems(from, items);
    // Return success operation
    return createSuccessPacket(iq);
}

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

License:Open Source License

private static IQ deleteItems(PubSubService service, IQ iq, Element retractElement) {
    String nodeID = retractElement.attributeValue("node");

    if (nodeID == null) {
        // No node was specified. Return bad_request error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }//from   ww  w.  j  a v a  2s  .co m

    Node node;
    // Look for the specified node
    node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }

    // Get the items to delete
    Iterator itemElements = retractElement.elementIterator("item");
    if (!itemElements.hasNext()) {
        Element pubsubError = DocumentHelper
                .createElement(QName.get("item-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }

    if (node.isCollectionNode()) {
        // Cannot delete items from a collection node. Return an error.
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "persistent-items");
        return createErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
    }
    LeafNode leafNode = (LeafNode) node;

    if (!leafNode.isItemRequired()) {
        // Cannot delete items from a leaf node that doesn't handle itemIDs. Return an error.
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "persistent-items");
        return createErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
    }

    List<PublishedItem> items = new ArrayList<PublishedItem>();
    while (itemElements.hasNext()) {
        Element itemElement = (Element) itemElements.next();
        String itemID = itemElement.attributeValue("id");
        if (itemID != null) {
            PublishedItem item = node.getPublishedItem(itemID);
            if (item == null) {
                // ItemID does not exist. Return item-not-found error
                return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
            } else {
                if (item.canDelete(iq.getFrom())) {
                    items.add(item);
                } else {
                    // Publisher does not have sufficient privileges to delete this item
                    createErrorPacket(iq, PacketError.Condition.forbidden, null);
                }
            }
        } else {
            // No item ID was specified so return a bad_request error
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("item-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        }
    }
    // Send reply with success
    //router.route(IQ.createResultIQ(iq));
    // Delete items and send subscribers a notification
    leafNode.deleteItems(items);
    return createSuccessPacket(iq);
}