Node.java 85.6 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11
/**
 * $RCSfile: $
 * $Revision: $
 * $Date: $
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

12
package org.jivesoftware.openfire.pubsub;
Matt Tucker's avatar
Matt Tucker committed
13 14 15 16

import org.dom4j.Element;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.StringUtils;
17 18
import org.jivesoftware.openfire.pubsub.models.AccessModel;
import org.jivesoftware.openfire.pubsub.models.PublisherModel;
Matt Tucker's avatar
Matt Tucker committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A virtual location to which information can be published and from which event
 * notifications and/or payloads can be received (in other pubsub systems, this may
 * be labelled a "topic").
 *
 * @author Matt Tucker
 */
public abstract class Node {

    /**
     * Reference to the publish and subscribe service.
     */
    protected PubSubService service;
    /**
     * Keeps the Node that is containing this node.
     */
    protected CollectionNode parent;
    /**
     * The unique identifier for a node within the context of a pubsub service.
     */
    protected String nodeID;
    /**
     * Flag that indicates whether to deliver payloads with event notifications.
     */
    protected boolean deliverPayloads;
    /**
     * Policy that defines whether owners or publisher should receive replies to items.
     */
    protected ItemReplyPolicy replyPolicy;
    /**
     * Flag that indicates whether to notify subscribers when the node configuration changes.
     */
    protected boolean notifyConfigChanges;
    /**
     * Flag that indicates whether to notify subscribers when the node is deleted.
     */
    protected boolean notifyDelete;
    /**
     * Flag that indicates whether to notify subscribers when items are removed from the node.
     */
    protected boolean notifyRetract;
    /**
     * Flag that indicates whether to deliver notifications to available users only.
     */
    protected boolean presenceBasedDelivery;
    /**
     * Publisher model that specifies who is allowed to publish items to the node.
     */
    protected PublisherModel publisherModel = PublisherModel.open;
    /**
     * Flag that indicates that subscribing and unsubscribing are enabled.
     */
    protected boolean subscriptionEnabled;
    /**
     * Access model that specifies who is allowed to subscribe and retrieve items.
     */
    protected AccessModel accessModel = AccessModel.open;
    /**
     * The roster group(s) allowed to subscribe and retrieve items.
     */
    protected Collection<String> rosterGroupsAllowed = new ArrayList<String>();
    /**
     * List of multi-user chat rooms to specify for replyroom.
     */
    protected Collection<JID> replyRooms = new ArrayList<JID>();
    /**
     * List of JID(s) to specify for replyto.
     */
    protected Collection<JID> replyTo = new ArrayList<JID>();
    /**
     * The type of payload data to be provided at the node. Usually specified by the
     * namespace of the payload (if any).
     */
    protected String payloadType = "";
    /**
     * The URL of an XSL transformation which can be applied to payloads in order
     * to generate an appropriate message body element.
     */
    protected String bodyXSLT = "";
    /**
     * The URL of an XSL transformation which can be applied to the payload format
     * in order to generate a valid Data Forms result that the client could display
     * using a generic Data Forms rendering engine.
     */
    protected String dataformXSLT = "";
    /**
     * Indicates if the node is present in the database.
     */
    private boolean savedToDB = false;
    /**
     * The datetime when the node was created.
     */
    protected Date creationDate;
    /**
     * The last date when the ndoe's configuration was modified.
     */
    private Date modificationDate;
    /**
     * The JID of the node creator.
     */
    protected JID creator;
    /**
     * A description of the node.
     */
    protected String description = "";
    /**
     * The default language of the node.
     */
    protected String language = "";
    /**
     * The JIDs of those to contact with questions.
     */
    protected Collection<JID> contacts = new ArrayList<JID>();
    /**
     * The name of the node.
     */
    protected String name = "";
    /**
     * Flag that indicates whether new subscriptions should be configured to be active.
     */
    protected boolean subscriptionConfigurationRequired = false;
    /**
     * The JIDs of those who have an affiliation with this node. When subscriptionModel is
     * whitelist then this collection acts as the white list (unless user is an outcast)
     */
    protected Collection<NodeAffiliate> affiliates = new CopyOnWriteArrayList<NodeAffiliate>();
    /**
     * Map that contains the current subscriptions to the node. A user may have more than one
     * subscription. Each subscription is uniquely identified by its ID.
     * Key: Subscription ID, Value: the subscription.
     */
    protected Map<String, NodeSubscription> subscriptionsByID =
            new ConcurrentHashMap<String, NodeSubscription>();
Matt Tucker's avatar
Matt Tucker committed
162 163 164 165 166 167 168 169 170
    /**
     * Map that contains the current subscriptions to the node. This map should be used only
     * when node is not configured to allow multiple subscriptions. When multiple subscriptions
     * is not allowed the subscriptions can be searched by the subscriber JID. Otherwise searches
     * should be done using the subscription ID.
     * Key: Subscriber full JID, Value: the subscription.
     */
    protected Map<String, NodeSubscription> subscriptionsByJID =
            new ConcurrentHashMap<String, NodeSubscription>();
Matt Tucker's avatar
Matt Tucker committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

    Node(PubSubService service, CollectionNode parent, String nodeID, JID creator) {
        this.service = service;
        this.parent = parent;
        this.nodeID = nodeID;
        this.creator = creator;
        long startTime = System.currentTimeMillis();
        this.creationDate = new Date(startTime);
        this.modificationDate = new Date(startTime);
        // Configure node with default values (get them from the pubsub service)
        DefaultNodeConfiguration defaultConfiguration =
                service.getDefaultNodeConfiguration(!isCollectionNode());
        this.subscriptionEnabled = defaultConfiguration.isSubscriptionEnabled();
        this.deliverPayloads = defaultConfiguration.isDeliverPayloads();
        this.notifyConfigChanges = defaultConfiguration.isNotifyConfigChanges();
        this.notifyDelete = defaultConfiguration.isNotifyDelete();
        this.notifyRetract = defaultConfiguration.isNotifyRetract();
        this.presenceBasedDelivery = defaultConfiguration.isPresenceBasedDelivery();
        this.accessModel = defaultConfiguration.getAccessModel();
        this.publisherModel = defaultConfiguration.getPublisherModel();
        this.language = defaultConfiguration.getLanguage();
        this.replyPolicy = defaultConfiguration.getReplyPolicy();
    }

    /**
     * Adds a new affiliation or updates an existing affiliation of the specified entity JID
     * to become a node owner.
     *
     * @param jid the JID of the user being added as a node owner.
Matt Tucker's avatar
Matt Tucker committed
200
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
201
     */
Matt Tucker's avatar
Matt Tucker committed
202 203
    public NodeAffiliate addOwner(JID jid) {
        NodeAffiliate nodeAffiliate = addAffiliation(jid, NodeAffiliate.Affiliation.owner);
Matt Tucker's avatar
Matt Tucker committed
204 205 206
        Collection<NodeSubscription> subscriptions = getSubscriptions(jid);
        if (subscriptions.isEmpty()) {
            // User does not have a subscription with the node so create a default one
Matt Tucker's avatar
Matt Tucker committed
207
            createSubscription(null, jid, jid, false, null);
Matt Tucker's avatar
Matt Tucker committed
208 209
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
210 211 212 213 214 215
            // Approve any pending subscription
            for (NodeSubscription subscription : getSubscriptions(jid)) {
                if (subscription.isAuthorizationPending()) {
                    subscription.approved();
                }
            }
Matt Tucker's avatar
Matt Tucker committed
216
        }
Matt Tucker's avatar
Matt Tucker committed
217
        return nodeAffiliate;
Matt Tucker's avatar
Matt Tucker committed
218 219 220
    }

    /**
221 222 223
     * Removes the owner affiliation of the specified entity JID. If the user that is
     * no longer an owner was subscribed to the node then his affiliation will be of
     * type {@link NodeAffiliate.Affiliation#none}.
Matt Tucker's avatar
Matt Tucker committed
224 225 226 227
     *
     * @param jid the JID of the user being removed as a node owner.
     */
    public void removeOwner(JID jid) {
228 229 230 231 232 233 234 235 236 237
        // Get the current affiliation of the specified JID
        NodeAffiliate affiliate = getAffiliate(jid);
        if (affiliate.getSubscriptions().isEmpty()) {
            removeAffiliation(jid, NodeAffiliate.Affiliation.owner);
            removeSubscriptions(jid);
        }
        else {
            // The user has subscriptions so change affiliation to NONE
            addNoneAffiliation(jid);
        }
Matt Tucker's avatar
Matt Tucker committed
238 239 240 241 242 243 244
    }

    /**
     * Adds a new affiliation or updates an existing affiliation of the specified entity JID
     * to become a node publisher.
     *
     * @param jid the JID of the user being added as a node publisher.
Matt Tucker's avatar
Matt Tucker committed
245
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
246
     */
Matt Tucker's avatar
Matt Tucker committed
247 248
    public NodeAffiliate addPublisher(JID jid) {
        NodeAffiliate nodeAffiliate = addAffiliation(jid, NodeAffiliate.Affiliation.publisher);
Matt Tucker's avatar
Matt Tucker committed
249 250 251
        Collection<NodeSubscription> subscriptions = getSubscriptions(jid);
        if (subscriptions.isEmpty()) {
            // User does not have a subscription with the node so create a default one
Matt Tucker's avatar
Matt Tucker committed
252
            createSubscription(null, jid, jid, false, null);
Matt Tucker's avatar
Matt Tucker committed
253 254
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
255 256 257 258 259 260
            // Approve any pending subscription
            for (NodeSubscription subscription : getSubscriptions(jid)) {
                if (subscription.isAuthorizationPending()) {
                    subscription.approved();
                }
            }
Matt Tucker's avatar
Matt Tucker committed
261
        }
Matt Tucker's avatar
Matt Tucker committed
262
        return nodeAffiliate;
Matt Tucker's avatar
Matt Tucker committed
263 264 265
    }

    /**
266 267 268
     * Removes the publisher affiliation of the specified entity JID. If the user that is
     * no longer a publisher was subscribed to the node then his affiliation will be of
     * type {@link NodeAffiliate.Affiliation#none}.
Matt Tucker's avatar
Matt Tucker committed
269 270 271 272
     *
     * @param jid the JID of the user being removed as a node publisher.
     */
    public void removePublisher(JID jid) {
273 274 275 276 277 278 279 280 281 282
        // Get the current affiliation of the specified JID
        NodeAffiliate affiliate = getAffiliate(jid);
        if (affiliate.getSubscriptions().isEmpty()) {
            removeAffiliation(jid, NodeAffiliate.Affiliation.publisher);
            removeSubscriptions(jid);
        }
        else {
            // The user has subscriptions so change affiliation to NONE
            addNoneAffiliation(jid);
        }
Matt Tucker's avatar
Matt Tucker committed
283 284 285 286 287 288 289
    }

    /**
     * Adds a new affiliation or updates an existing affiliation of the specified entity JID
     * to become a none affiliate. Affiliates of type none are allowed to subscribe to the node.
     *
     * @param jid the JID of the user with affiliation "none".
Matt Tucker's avatar
Matt Tucker committed
290
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
291
     */
Matt Tucker's avatar
Matt Tucker committed
292 293
    public NodeAffiliate addNoneAffiliation(JID jid) {
        return addAffiliation(jid, NodeAffiliate.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
294 295 296 297 298 299 300
    }

    /**
     * Sets that the specified entity is an outcast of the node. Outcast entities are not
     * able to publish or subscribe to the node. Existing subscriptions will be deleted.
     *
     * @param jid the JID of the user that is no longer able to publish or subscribe to the node.
Matt Tucker's avatar
Matt Tucker committed
301
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
302
     */
Matt Tucker's avatar
Matt Tucker committed
303 304
    public NodeAffiliate addOutcast(JID jid) {
        NodeAffiliate nodeAffiliate = addAffiliation(jid, NodeAffiliate.Affiliation.outcast);
Matt Tucker's avatar
Matt Tucker committed
305 306
        // Delete existing subscriptions
        removeSubscriptions(jid);
Matt Tucker's avatar
Matt Tucker committed
307
        return nodeAffiliate;
Matt Tucker's avatar
Matt Tucker committed
308 309 310 311 312 313 314 315 316 317 318
    }

    /**
     * Removes the banning to subscribe to the node for the specified entity.
     *
     * @param jid the JID of the user that is no longer an outcast.
     */
    public void removeOutcast(JID jid) {
        removeAffiliation(jid, NodeAffiliate.Affiliation.outcast);
    }

Matt Tucker's avatar
Matt Tucker committed
319
    private NodeAffiliate addAffiliation(JID jid, NodeAffiliate.Affiliation affiliation) {
Matt Tucker's avatar
Matt Tucker committed
320 321 322 323 324 325
        boolean created = false;
        // Get the current affiliation of the specified JID
        NodeAffiliate affiliate = getAffiliate(jid);
        // Check if the user already has the same affiliation
        if (affiliate != null && affiliation == affiliate.getAffiliation()) {
            // Do nothing since the user already has the expected affiliation
Matt Tucker's avatar
Matt Tucker committed
326
            return affiliate;
Matt Tucker's avatar
Matt Tucker committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        }
        else if (affiliate != null) {
            // Update existing affiliation with new affiliation type
            affiliate.setAffiliation(affiliation);
        }
        else {
            // User did not have any affiliation with the node so create a new one
            affiliate = new NodeAffiliate(this, jid);
            affiliate.setAffiliation(affiliation);
            addAffiliate(affiliate);
            created = true;
        }

        if (savedToDB) {
            // Add or update the affiliate in the database
            PubSubPersistenceManager.saveAffiliation(service, this, affiliate, created);
        }
Matt Tucker's avatar
Matt Tucker committed
344
        return affiliate;
Matt Tucker's avatar
Matt Tucker committed
345 346 347 348 349
    }

    private void removeAffiliation(JID jid, NodeAffiliate.Affiliation affiliation) {
        // Get the current affiliation of the specified JID
        NodeAffiliate affiliate = getAffiliate(jid);
350
        // Check if the current affiliatin of the user is the one to remove
Matt Tucker's avatar
Matt Tucker committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364
        if (affiliate != null && affiliation == affiliate.getAffiliation()) {
            removeAffiliation(affiliate);
        }
    }

    private void removeAffiliation(NodeAffiliate affiliate) {
        // Remove the existing affiliate from the list in memory
        affiliates.remove(affiliate);
        if (savedToDB) {
            // Remove the affiliate from the database
            PubSubPersistenceManager.removeAffiliation(service, this, affiliate);
        }
    }

Matt Tucker's avatar
Matt Tucker committed
365 366 367 368 369
    /**
     * Removes all subscriptions owned by the specified entity.
     *
     * @param owner the owner of the subscriptions to be cancelled.
     */
Matt Tucker's avatar
Matt Tucker committed
370 371
    private void removeSubscriptions(JID owner) {
        for (NodeSubscription subscription : getSubscriptions(owner)) {
Matt Tucker's avatar
Matt Tucker committed
372
            cancelSubscription(subscription);
Matt Tucker's avatar
Matt Tucker committed
373 374 375 376 377 378 379 380 381 382
        }
    }

    /**
     * Returns the list of subscriptions owned by the specified user. The subscription owner
     * may have more than one subscription based on {@link #isMultipleSubscriptionsEnabled()}.
     * Each subscription may have a different subscription JID if the owner wants to receive
     * notifications in different resources (or even JIDs).
     *
     * @param owner the owner of the subscriptions.
Matt Tucker's avatar
Matt Tucker committed
383
     * @return the list of subscriptions owned by the specified user.
Matt Tucker's avatar
Matt Tucker committed
384
     */
Matt Tucker's avatar
Matt Tucker committed
385
    public Collection<NodeSubscription> getSubscriptions(JID owner) {
Matt Tucker's avatar
Matt Tucker committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        Collection<NodeSubscription> subscriptions = new ArrayList<NodeSubscription>();
        for (NodeSubscription subscription : subscriptionsByID.values()) {
            if (owner.equals(subscription.getOwner())) {
                subscriptions.add(subscription);
            }
        }
        return subscriptions;
    }

    /**
     * Returns all subscriptions to the node.
     *
     * @return all subscriptions to the node.
     */
    Collection<NodeSubscription> getSubscriptions() {
        return subscriptionsByID.values();
    }

    /**
     * Returns the {@link NodeAffiliate} of the specified {@link JID} or <tt>null</tt>
     * if none was found. Users that have a subscription with the node will ALWAYS
     * have an affiliation even if the affiliation is of type <tt>none</tt>.
     *
     * @param jid the JID of the user to look his affiliation with this node.
     * @return the NodeAffiliate of the specified JID or <tt>null</tt> if none was found.
     */
    public NodeAffiliate getAffiliate(JID jid) {
        for (NodeAffiliate affiliate : affiliates) {
            if (jid.equals(affiliate.getJID())) {
                return affiliate;
            }
        }
        return null;
    }

Matt Tucker's avatar
Matt Tucker committed
421 422 423 424 425 426 427 428
    /**
     * Returns a collection with the JID of the node owners. Entities that are node owners have
     * an affiliation of {@link NodeAffiliate.Affiliation#owner}. Owners are allowed to purge
     * and delete the node. Moreover, owners may also get The collection can be modified
     * since it represents a snapshot.
     *
     * @return a collection with the JID of the node owners.
     */
Matt Tucker's avatar
Matt Tucker committed
429 430 431 432 433 434 435 436 437 438
    public Collection<JID> getOwners() {
        Collection<JID> jids = new ArrayList<JID>();
        for (NodeAffiliate affiliate : affiliates) {
            if (NodeAffiliate.Affiliation.owner == affiliate.getAffiliation()) {
                jids.add(affiliate.getJID());
            }
        }
        return jids;
    }

Matt Tucker's avatar
Matt Tucker committed
439 440 441
    /**
     * Returns a collection with the JID of the enitities with an affiliation of
     * {@link NodeAffiliate.Affiliation#publisher}. When using the publisher model
442
     * {@link org.jivesoftware.openfire.pubsub.models.OpenPublisher} anyone may publish
Matt Tucker's avatar
Matt Tucker committed
443 444 445 446 447
     * to the node so this collection may be empty or may not contain the complete list
     * of publishers. The returned collection can be modified since it represents a snapshot.
     *
     * @return a collection with the JID of the enitities with an affiliation of publishers.
     */
Matt Tucker's avatar
Matt Tucker committed
448 449 450 451 452 453 454 455 456 457
    public Collection<JID> getPublishers() {
        Collection<JID> jids = new ArrayList<JID>();
        for (NodeAffiliate affiliate : affiliates) {
            if (NodeAffiliate.Affiliation.publisher == affiliate.getAffiliation()) {
                jids.add(affiliate.getJID());
            }
        }
        return jids;
    }

Matt Tucker's avatar
Matt Tucker committed
458 459 460 461 462 463 464 465 466
    /**
     * Changes the node configuration based on the completed data form. Only owners or
     * sysadmins are allowed to change the node configuration. The completed data form
     * cannot remove all node owners. An exception is going to be thrown if the new form
     * tries to leave the node without owners.
     *
     * @param completedForm the completed data form.
     * @throws NotAcceptableException if completed data form tries to leave the node without owners.
     */
Matt Tucker's avatar
Matt Tucker committed
467
    public void configure(DataForm completedForm) throws NotAcceptableException {
468 469
        boolean wasPresenceBased = isPresenceBasedDelivery();

Matt Tucker's avatar
Matt Tucker committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        if (DataForm.Type.cancel.equals(completedForm.getType())) {
            // Existing node configuration is applied (i.e. nothing is changed)
        }
        else if (DataForm.Type.submit.equals(completedForm.getType())) {
            List<String> values;
            String booleanValue;

            // Get the new list of owners
            FormField ownerField = completedForm.getField("pubsub#owner");
            boolean ownersSent = ownerField != null;
            List<JID> owners = new ArrayList<JID>();
            if (ownersSent) {
                for (String value : ownerField.getValues()) {
                    try {
                        owners.add(new JID(value));
                    }
486 487 488
                    catch (Exception e) {
                        // Do nothing
                    }
Matt Tucker's avatar
Matt Tucker committed
489 490 491 492 493 494 495 496 497 498
                }
            }

            // Answer a not-acceptable error if all the current owners will be removed
            if (ownersSent && owners.isEmpty()) {
                throw new NotAcceptableException();
            }

            for (FormField field : completedForm.getFields()) {
                if ("FORM_TYPE".equals(field.getVariable())) {
Matt Tucker's avatar
Matt Tucker committed
499
                    // Do nothing
Matt Tucker's avatar
Matt Tucker committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                }
                else if ("pubsub#deliver_payloads".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    deliverPayloads = "1".equals(booleanValue);
                }
                else if ("pubsub#notify_config".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    notifyConfigChanges = "1".equals(booleanValue);
                }
                else if ("pubsub#notify_delete".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    notifyDelete = "1".equals(booleanValue);
                }
                else if ("pubsub#notify_retract".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    notifyRetract = "1".equals(booleanValue);
                }
                else if ("pubsub#presence_based_delivery".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    presenceBasedDelivery = "1".equals(booleanValue);
                }
                else if ("pubsub#subscribe".equals(field.getVariable())) {
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    subscriptionEnabled = "1".equals(booleanValue);
                }
                else if ("pubsub#subscription_required".equals(field.getVariable())) {
                    // TODO Replace this variable for the one defined in the JEP (once one is defined)
                    values = field.getValues();
                    booleanValue = (values.size() > 0 ? values.get(0) : "1");
                    subscriptionConfigurationRequired = "1".equals(booleanValue);
                }
                else if ("pubsub#type".equals(field.getVariable())) {
                    values = field.getValues();
                    payloadType = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#body_xslt".equals(field.getVariable())) {
                    values = field.getValues();
                    bodyXSLT = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#dataform_xslt".equals(field.getVariable())) {
                    values = field.getValues();
                    dataformXSLT = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#access_model".equals(field.getVariable())) {
                    values = field.getValues();
                    if (values.size() > 0)  {
                        accessModel = AccessModel.valueOf(values.get(0));
                    }
                }
                else if ("pubsub#publish_model".equals(field.getVariable())) {
                    values = field.getValues();
                    if (values.size() > 0)  {
                        publisherModel = PublisherModel.valueOf(values.get(0));
                    }
                }
                else if ("pubsub#roster_groups_allowed".equals(field.getVariable())) {
                    // Get the new list of roster group(s) allowed to subscribe and retrieve items
                    rosterGroupsAllowed = new ArrayList<String>();
                    for (String value : field.getValues()) {
565
                        addAllowedRosterGroup(value);
Matt Tucker's avatar
Matt Tucker committed
566 567 568 569 570 571 572
                    }
                }
                else if ("pubsub#contact".equals(field.getVariable())) {
                    // Get the new list of users that may be contacted with questions
                    contacts = new ArrayList<JID>();
                    for (String value : field.getValues()) {
                        try {
573
                            addContact(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
574
                        }
575 576 577
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
                    }
                }
                else if ("pubsub#description".equals(field.getVariable())) {
                    values = field.getValues();
                    description = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#language".equals(field.getVariable())) {
                    values = field.getValues();
                    language = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#title".equals(field.getVariable())) {
                    values = field.getValues();
                    name = values.size() > 0 ? values.get(0) : " ";
                }
                else if ("pubsub#itemreply".equals(field.getVariable())) {
                    values = field.getValues();
                    if (values.size() > 0)  {
                        replyPolicy = ItemReplyPolicy.valueOf(values.get(0));
                    }
                }
                else if ("pubsub#replyroom".equals(field.getVariable())) {
                    // Get the new list of multi-user chat rooms to specify for replyroom
                    replyRooms = new ArrayList<JID>();
                    for (String value : field.getValues()) {
                        try {
603
                            addReplyRoom(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
604
                        }
605 606 607
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
608 609 610 611 612 613 614
                    }
                }
                else if ("pubsub#replyto".equals(field.getVariable())) {
                    // Get the new list of JID(s) to specify for replyto
                    replyTo = new ArrayList<JID>();
                    for (String value : field.getValues()) {
                        try {
615
                            addReplyTo(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
616
                        }
617 618 619
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
620 621 622 623 624 625 626 627 628 629 630 631
                    }
                }
                else {
                    // Let subclasses be configured by specified fields
                    configure(field);
                }
            }

            // Set new list of owners of the node
            if (ownersSent) {
                // Calculate owners to remove and remove them from the DB
                Collection<JID> oldOwners = getOwners();
Matt Tucker's avatar
Matt Tucker committed
632
                oldOwners.removeAll(owners);
Matt Tucker's avatar
Matt Tucker committed
633 634 635 636 637
                for (JID jid : oldOwners) {
                    removeOwner(jid);
                }

                // Calculate new owners and add them to the DB
Matt Tucker's avatar
Matt Tucker committed
638
                owners.removeAll(getOwners());
Matt Tucker's avatar
Matt Tucker committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652
                for (JID jid : owners) {
                    addOwner(jid);
                }
            }
            // TODO Before removing owner or admin check if user was changed from admin to owner or vice versa. This way his susbcriptions are not going to be deleted.
            // Set the new list of publishers
            FormField publisherField = completedForm.getField("pubsub#publisher");
            if (publisherField != null) {
                // New list of publishers was sent to update publishers of the node
                List<JID> publishers = new ArrayList<JID>();
                for (String value : publisherField.getValues()) {
                    try {
                        publishers.add(new JID(value));
                    }
653 654 655
                    catch (Exception e) {
                        // Do nothing
                    }
Matt Tucker's avatar
Matt Tucker committed
656 657 658
                }
                // Calculate publishers to remove and remove them from the DB
                Collection<JID> oldPublishers = getPublishers();
Matt Tucker's avatar
Matt Tucker committed
659
                oldPublishers.removeAll(publishers);
Matt Tucker's avatar
Matt Tucker committed
660 661 662 663 664
                for (JID jid : oldPublishers) {
                    removePublisher(jid);
                }

                // Calculate new publishers and add them to the DB
Matt Tucker's avatar
Matt Tucker committed
665
                publishers.removeAll(getPublishers());
Matt Tucker's avatar
Matt Tucker committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
                for (JID jid : publishers) {
                    addPublisher(jid);
                }
            }
            // Let subclasses have a chance to finish node configuration based on
            // the completed form
            postConfigure(completedForm);

            // Update the modification date to reflect the last time when the node's configuration
            // was modified
            modificationDate = new Date();

            // Notify subscribers that the node configuration has changed
            nodeConfigurationChanged();
        }
        // Store the new or updated node in the backend store
        saveToDB();
683 684 685 686 687 688 689 690 691 692

        // Check if we need to subscribe or unsubscribe from affiliate presences
        if (wasPresenceBased != isPresenceBasedDelivery()) {
            if (isPresenceBasedDelivery()) {
                addPresenceSubscriptions();
            }
            else {
                cancelPresenceSubscriptions();
            }
        }
Matt Tucker's avatar
Matt Tucker committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    }

    /**
     * Configures the node with the completed form field. Fields that are common to leaf
     * and collection nodes are handled in {@link #configure(org.xmpp.forms.DataForm)}.
     * Subclasses should implement this method in order to configure the node with form
     * fields specific to the node type.
     *
     * @param field the form field specific to the node type.
     */
    abstract void configure(FormField field);

    /**
     * Node configuration was changed based on the completed form. Subclasses may implement
     * this method to finsh node configuration based on the completed form.
     *
     * @param completedForm the form completed by the node owner.
     */
    abstract void postConfigure(DataForm completedForm);

Matt Tucker's avatar
Matt Tucker committed
713 714 715 716 717
    /**
     * The node configuration has changed. If this is the first time the node is configured
     * after it was created (i.e. is not yet persistent) then do nothing. Otherwise, send
     * a notification to the node subscribers informing that the configuration has changed.
     */
Matt Tucker's avatar
Matt Tucker committed
718
    private void nodeConfigurationChanged() {
Matt Tucker's avatar
Matt Tucker committed
719
        if (!isNotifiedOfConfigChanges() || !savedToDB) {
Matt Tucker's avatar
Matt Tucker committed
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
            // Do nothing if node was just created and configure or if notification
            // of config changes is disabled
            return;
        }

        // Build packet to broadcast to subscribers
        Message message = new Message();
        Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
        Element items = event.addElement("items");
        items.addAttribute("node", nodeID);
        Element item = items.addElement("item");
        item.addAttribute("id", "configuration");
        if (deliverPayloads) {
            item.add(getConfigurationChangeForm().getElement());
        }
        // Send notification that the node configuration has changed
Matt Tucker's avatar
Matt Tucker committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        broadcastNodeEvent(message, false);
    }

    /**
     * Returns the data form to be included in the authorization request to be sent to
     * node owners when a new subscription needs to be approved.
     *
     * @param subscription the new subscription that needs to be approved.
     * @return the data form to be included in the authorization request.
     */
    DataForm getAuthRequestForm(NodeSubscription subscription) {
        DataForm form = new DataForm(DataForm.Type.form);
        form.setTitle(LocaleUtils.getLocalizedString("pubsub.form.authorization.title"));
        form.addInstruction(
                LocaleUtils.getLocalizedString("pubsub.form.authorization.instruction"));

        FormField formField = form.addField();
        formField.setVariable("FORM_TYPE");
        formField.setType(FormField.Type.hidden);
        formField.addValue("http://jabber.org/protocol/pubsub#subscribe_authorization");

        formField = form.addField();
        formField.setVariable("pubsub#subid");
        formField.setType(FormField.Type.hidden);
        formField.addValue(subscription.getID());

        formField = form.addField();
        formField.setVariable("pubsub#node");
        formField.setType(FormField.Type.text_single);
        formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.authorization.node"));
        formField.addValue(getNodeID());

        formField = form.addField();
        formField.setVariable("pusub#subscriber_jid");
        formField.setType(FormField.Type.jid_single);
        formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.authorization.subscriber"));
        formField.addValue(subscription.getJID().toString());

        formField = form.addField();
        formField.setVariable("pubsub#allow");
        formField.setType(FormField.Type.boolean_type);
        formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.authorization.allow"));
        formField.addValue(Boolean.FALSE);

        return form;
Matt Tucker's avatar
Matt Tucker committed
781 782
    }

Matt Tucker's avatar
Matt Tucker committed
783

Matt Tucker's avatar
Matt Tucker committed
784 785 786 787 788 789 790 791 792 793 794
    /**
     * Returns a data form used by the owner to edit the node configuration.
     *
     * @return data form used by the owner to edit the node configuration.
     */
    public DataForm getConfigurationForm() {
        DataForm form = new DataForm(DataForm.Type.form);
        form.setTitle(LocaleUtils.getLocalizedString("pubsub.form.conf.title"));
        List<String> params = new ArrayList<String>();
        params.add(getNodeID());
        form.addInstruction(LocaleUtils.getLocalizedString("pubsub.form.conf.instruction", params));
Matt Tucker's avatar
Matt Tucker committed
795 796 797 798 799 800

        FormField formField = form.addField();
        formField.setVariable("FORM_TYPE");
        formField.setType(FormField.Type.hidden);
        formField.addValue("http://jabber.org/protocol/pubsub#node_config");

Matt Tucker's avatar
Matt Tucker committed
801 802 803 804 805
        // Add the form fields and configure them for edition
        addFormFields(form, true);
        return form;
    }

Matt Tucker's avatar
Matt Tucker committed
806 807 808 809 810 811 812 813 814
    /**
     * Adds the required form fields to the specified form. When editing is true the field type
     * and a label is included in each fields. The form being completed will contain the current
     * node configuration. This information can be used for editing the node or for notifing that
     * the node configuration has changed.
     *
     * @param form the form containing the node configuration.
     * @param isEditing true when the form will be used to edit the node configuration.
     */
Matt Tucker's avatar
Matt Tucker committed
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    protected void addFormFields(DataForm form, boolean isEditing) {
        FormField formField = form.addField();
        formField.setVariable("pubsub#title");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.short_name"));
        }
        formField.addValue(name);

        formField = form.addField();
        formField.setVariable("pubsub#description");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.description"));
        }
        formField.addValue(description);

        formField = form.addField();
        formField.setVariable("pubsub#subscribe");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.subscribe"));
        }
        formField.addValue(subscriptionEnabled);

        formField = form.addField();
        formField.setVariable("pubsub#subscription_required");
        // TODO Replace this variable for the one defined in the JEP (once one is defined)
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.subscription_required"));
        }
        formField.addValue(subscriptionConfigurationRequired);

        formField = form.addField();
        formField.setVariable("pubsub#deliver_payloads");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.deliver_payloads"));
        }
        formField.addValue(deliverPayloads);

        formField = form.addField();
        formField.setVariable("pubsub#notify_config");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.notify_config"));
        }
        formField.addValue(notifyConfigChanges);

        formField = form.addField();
        formField.setVariable("pubsub#notify_delete");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.notify_delete"));
        }
        formField.addValue(notifyDelete);

        formField = form.addField();
        formField.setVariable("pubsub#notify_retract");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.notify_retract"));
        }
        formField.addValue(notifyRetract);

        formField = form.addField();
        formField.setVariable("pubsub#presence_based_delivery");
        if (isEditing) {
            formField.setType(FormField.Type.boolean_type);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.presence_based"));
        }
        formField.addValue(presenceBasedDelivery);

        formField = form.addField();
        formField.setVariable("pubsub#type");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.type"));
        }
        formField.addValue(payloadType);

        formField = form.addField();
        formField.setVariable("pubsub#body_xslt");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.body_xslt"));
        }
        formField.addValue(bodyXSLT);

        formField = form.addField();
        formField.setVariable("pubsub#dataform_xslt");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.dataform_xslt"));
        }
        formField.addValue(dataformXSLT);

        formField = form.addField();
        formField.setVariable("pubsub#access_model");
        if (isEditing) {
            formField.setType(FormField.Type.list_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.access_model"));
            formField.addOption(null, AccessModel.authorize.getName());
            formField.addOption(null, AccessModel.open.getName());
            formField.addOption(null, AccessModel.presence.getName());
            formField.addOption(null, AccessModel.roster.getName());
            formField.addOption(null, AccessModel.whitelist.getName());
        }
        formField.addValue(accessModel.getName());

        formField = form.addField();
        formField.setVariable("pubsub#publish_model");
        if (isEditing) {
            formField.setType(FormField.Type.list_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.publish_model"));
            formField.addOption(null, PublisherModel.publishers.getName());
            formField.addOption(null, PublisherModel.subscribers.getName());
            formField.addOption(null, PublisherModel.open.getName());
        }
        formField.addValue(publisherModel.getName());

        formField = form.addField();
        formField.setVariable("pubsub#roster_groups_allowed");
        if (isEditing) {
            formField.setType(FormField.Type.list_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.roster_allowed"));
        }
        for (String group : rosterGroupsAllowed) {
            formField.addValue(group);
        }

        formField = form.addField();
        formField.setVariable("pubsub#contact");
        if (isEditing) {
            formField.setType(FormField.Type.jid_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.contact"));
        }
        for (JID contact : contacts) {
            formField.addValue(contact.toString());
        }

        formField = form.addField();
        formField.setVariable("pubsub#language");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.language"));
        }
        formField.addValue(language);

        formField = form.addField();
        formField.setVariable("pubsub#owner");
        if (isEditing) {
            formField.setType(FormField.Type.jid_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.owner"));
        }
        for (JID owner : getOwners()) {
            formField.addValue(owner.toString());
        }

        formField = form.addField();
        formField.setVariable("pubsub#publisher");
        if (isEditing) {
            formField.setType(FormField.Type.jid_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.publisher"));
        }
        for (JID owner : getPublishers()) {
            formField.addValue(owner.toString());
        }

        formField = form.addField();
        formField.setVariable("pubsub#itemreply");
        if (isEditing) {
            formField.setType(FormField.Type.list_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.itemreply"));
        }
        if (replyPolicy != null) {
            formField.addValue(replyPolicy.name());
        }

        formField = form.addField();
        formField.setVariable("pubsub#replyroom");
        if (isEditing) {
            formField.setType(FormField.Type.jid_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.replyroom"));
        }
        for (JID owner : getReplyRooms()) {
            formField.addValue(owner.toString());
        }

        formField = form.addField();
        formField.setVariable("pubsub#replyto");
        if (isEditing) {
            formField.setType(FormField.Type.jid_multi);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.replyto"));
        }
        for (JID owner : getReplyTo()) {
            formField.addValue(owner.toString());
        }
    }

    /**
     * Returns a data form with the node configuration. The returned data form is used for
     * notifying node subscribers that the node configuration has changed. The data form is
     * ony going to be included if node is configure to include payloads in event
     * notifications.
     *
     * @return a data form with the node configuration.
     */
    private DataForm getConfigurationChangeForm() {
        DataForm form = new DataForm(DataForm.Type.result);
Matt Tucker's avatar
Matt Tucker committed
1026 1027 1028 1029
        FormField formField = form.addField();
        formField.setVariable("FORM_TYPE");
        formField.setType(FormField.Type.hidden);
        formField.addValue("http://jabber.org/protocol/pubsub#node_config");
Matt Tucker's avatar
Matt Tucker committed
1030 1031 1032 1033 1034 1035
        // Add the form fields and configure them for notification
        // (i.e. no label or options are included)
        addFormFields(form, false);
        return form;
    }

Matt Tucker's avatar
Matt Tucker committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    /**
     * Returns a data form containing the node configuration that is going to be used for
     * service discovery.
     *
     * @return a data form with the node configuration.
     */
    public DataForm getMetadataForm() {
        DataForm form = new DataForm(DataForm.Type.result);
        FormField formField = form.addField();
        formField.setVariable("FORM_TYPE");
        formField.setType(FormField.Type.hidden);
        formField.addValue("http://jabber.org/protocol/pubsub#meta-data");
        // Add the form fields
        addFormFields(form, true);
        return form;
    }

Matt Tucker's avatar
Matt Tucker committed
1053 1054 1055 1056 1057
    /**
     * Returns true if this node is the root node of the pubsub service.
     *
     * @return true if this node is the root node of the pubsub service.
     */
Matt Tucker's avatar
Matt Tucker committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    public boolean isRootCollectionNode() {
        return service.getRootCollectionNode() == this;
    }

    /**
     * Returns true if a user may have more than one subscription with the node. When
     * multiple subscriptions is enabled each subscription request, event notification and
     * unsubscription request should include a <tt>subid</tt> attribute. By default multiple
     * subscriptions is enabled.
     *
     * @return true if a user may have more than one subscription with the node.
     */
    public boolean isMultipleSubscriptionsEnabled() {
1071
        return service.isMultipleSubscriptionsEnabled();
Matt Tucker's avatar
Matt Tucker committed
1072 1073
    }

Matt Tucker's avatar
Matt Tucker committed
1074 1075 1076 1077 1078 1079
    /**
     * Returns true if this node is a node container. Node containers may only contain nodes
     * but are not allowed to get items published.
     *
     * @return true if this node is a node container.
     */
Matt Tucker's avatar
Matt Tucker committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    public boolean isCollectionNode() {
        return false;
    }

    /**
     * Returns true if the specified node is a first-level children of this node.
     *
     * @param child the node to check if it is a direct child of this node.
     * @return true if the specified node is a first-level children of this collection
     *         node.
     */
    public boolean isChildNode(Node child) {
        return false;
    }

    /**
     * Returns true if the specified node is a direct child node of this node or
     * a descendant of the children nodes.
     *
     * @param child the node to check if it is a descendant of this node.
     * @return true if the specified node is a direct child node of this node or
     *         a descendant of the children nodes.
     */
    public boolean isDescendantNode(Node child) {
        return false;
    }

    /**
     * Returns true if the specified user is allowed to administer the node. Node
     * administrator are allowed to retrieve the node configuration, change the node
     * configuration, purge the node, delete the node and get the node affiliations and
     * subscriptions.
     *
     * @param user the user to check if he is an admin.
     * @return true if the specified user is allowed to administer the node.
     */
    public boolean isAdmin(JID user) {
        if (getOwners().contains(user) || service.isServiceAdmin(user)) {
            return true;
        }
        // Check if we should try again but using the bare JID
        if (user.getResource() != null) {
            user = new JID(user.toBareJID());
            return isAdmin(user);
        }
        return false;
    }

Matt Tucker's avatar
Matt Tucker committed
1128 1129 1130 1131 1132
    /**
     * Returns the unique identifier for a node within the context of a pubsub service.
     *
     * @return the unique identifier for a node within the context of a pubsub service.
     */
Matt Tucker's avatar
Matt Tucker committed
1133 1134 1135 1136
    public String getNodeID() {
        return nodeID;
    }

Matt Tucker's avatar
Matt Tucker committed
1137 1138 1139 1140 1141 1142
    /**
     * Returns the name of the node. The node may not have a configured name. The node's
     * name can be changed by submiting a completed data form.
     *
     * @return the name of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1143 1144 1145 1146
    public String getName() {
        return name;
    }

Matt Tucker's avatar
Matt Tucker committed
1147 1148 1149 1150 1151 1152 1153 1154 1155
    /**
     * Returns true if event notifications will include payloads. Payloads are included when
     * publishing new items. However, new items may not always include a payload depending
     * on the node configuration. Nodes can be configured to not deliver payloads for performance
     * reasons.
     *
     * @return true if event notifications will include payloads.
     */
    public boolean isPayloadDelivered() {
Matt Tucker's avatar
Matt Tucker committed
1156 1157 1158 1159 1160 1161 1162
        return deliverPayloads;
    }

    public ItemReplyPolicy getReplyPolicy() {
        return replyPolicy;
    }

Matt Tucker's avatar
Matt Tucker committed
1163 1164 1165 1166 1167 1168
    /**
     * Returns true if subscribers will be notified when the node configuration changes.
     *
     * @return true if subscribers will be notified when the node configuration changes.
     */
    public boolean isNotifiedOfConfigChanges() {
Matt Tucker's avatar
Matt Tucker committed
1169 1170 1171
        return notifyConfigChanges;
    }

Matt Tucker's avatar
Matt Tucker committed
1172 1173 1174 1175 1176 1177
    /**
     * Returns true if subscribers will be notified when the node is deleted.
     *
     * @return true if subscribers will be notified when the node is deleted.
     */
    public boolean isNotifiedOfDelete() {
Matt Tucker's avatar
Matt Tucker committed
1178 1179 1180
        return notifyDelete;
    }

Matt Tucker's avatar
Matt Tucker committed
1181 1182 1183 1184 1185 1186
    /**
     * Returns true if subscribers will be notified when items are removed from the node.
     *
     * @return true if subscribers will be notified when items are removed from the node.
     */
    public boolean isNotifiedOfRetract() {
Matt Tucker's avatar
Matt Tucker committed
1187 1188 1189
        return notifyRetract;
    }

Matt Tucker's avatar
Matt Tucker committed
1190 1191 1192 1193 1194
    /**
     * Returns true if notifications are going to be delivered to available users only.
     *
     * @return true if notifications are going to be delivered to available users only.
     */
Matt Tucker's avatar
Matt Tucker committed
1195 1196 1197 1198
    public boolean isPresenceBasedDelivery() {
        return presenceBasedDelivery;
    }

Matt Tucker's avatar
Matt Tucker committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    /**
     * Returns true if notifications to the specified user will be delivered when the
     * user is online.
     *
     * @param user the JID of the affiliate that has to be subscribed to the node.
     * @return true if notifications are going to be delivered when the user is online.
     */
    public boolean isPresenceBasedDelivery(JID user) {
        Collection<NodeSubscription> subscriptions = getSubscriptions(user);
        if (!subscriptions.isEmpty()) {
            if (presenceBasedDelivery) {
                // Node sends notifications only to only users so return true
                return true;
            }
            else {
                // Check if there is a subscription configured to only send notifications
                // based on the user presence
                for (NodeSubscription subscription : subscriptions) {
                    if (!subscription.getPresenceStates().isEmpty()) {
                        return true;
                    }
                }
            }
        }
        // User is not subscribed to the node so presence subscription is not required
        return false;
    }

    /**
     * Returns the JID of the affiliates that are receiving notifications based on their
     * presence status.
     *
     * @return the JID of the affiliates that are receiving notifications based on their
     *         presence status.
     */
    Collection<JID> getPresenceBasedSubscribers() {
        Collection<JID> affiliatesJID = new ArrayList<JID>();
        if (presenceBasedDelivery) {
            // Add JID of all affiliates that are susbcribed to the node
            for (NodeAffiliate affiliate : affiliates) {
                if (!affiliate.getSubscriptions().isEmpty()) {
                    affiliatesJID.add(affiliate.getJID());
                }
            }
        }
        else {
            // Add JID of those affiliates that have a subscription that only wants to be
            // notified based on the subscriber presence
            for (NodeAffiliate affiliate : affiliates) {
                Collection<NodeSubscription> subscriptions = affiliate.getSubscriptions();
                for (NodeSubscription subscription : subscriptions) {
                    if (!subscription.getPresenceStates().isEmpty()) {
                        affiliatesJID.add(affiliate.getJID());
                        break;
                    }
                }
            }
        }
        return affiliatesJID;
    }

Matt Tucker's avatar
Matt Tucker committed
1260 1261 1262 1263 1264
    /**
     * Returns true if the last published item is going to be sent to new subscribers.
     *
     * @return true if the last published item is going to be sent to new subscribers.
     */
Matt Tucker's avatar
Matt Tucker committed
1265
    public boolean isSendItemSubscribe() {
Matt Tucker's avatar
Matt Tucker committed
1266
        return false;
Matt Tucker's avatar
Matt Tucker committed
1267 1268
    }

Matt Tucker's avatar
Matt Tucker committed
1269 1270 1271 1272 1273
    /**
     * Returns the publisher model that specifies who is allowed to publish items to the node.
     *
     * @return the publisher model that specifies who is allowed to publish items to the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1274 1275 1276 1277
    public PublisherModel getPublisherModel() {
        return publisherModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1278 1279 1280 1281 1282
    /**
     * Returns true if users are allowed to subscribe and unsubscribe.
     *
     * @return true if users are allowed to subscribe and unsubscribe.
     */
Matt Tucker's avatar
Matt Tucker committed
1283 1284 1285 1286
    public boolean isSubscriptionEnabled() {
        return subscriptionEnabled;
    }

Matt Tucker's avatar
Matt Tucker committed
1287 1288 1289 1290 1291 1292 1293
    /**
     * Returns true if new subscriptions should be configured to be active. Inactive
     * subscriptions will not get event notifications. However, subscribers will be
     * notified when a node is deleted no matter the subscription status.
     *
     * @return true if new subscriptions should be configured to be active.
     */
Matt Tucker's avatar
Matt Tucker committed
1294 1295 1296 1297
    public boolean isSubscriptionConfigurationRequired() {
        return subscriptionConfigurationRequired;
    }

Matt Tucker's avatar
Matt Tucker committed
1298 1299 1300 1301 1302
    /**
     * Returns the access model that specifies who is allowed to subscribe and retrieve items.
     *
     * @return the access model that specifies who is allowed to subscribe and retrieve items.
     */
Matt Tucker's avatar
Matt Tucker committed
1303 1304 1305 1306
    public AccessModel getAccessModel() {
        return accessModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1307 1308 1309
    /**
     * Returns the roster group(s) allowed to subscribe and retrieve items. This information
     * is going to be used only when using the
1310
     * {@link org.jivesoftware.openfire.pubsub.models.RosterAccess} access model.
Matt Tucker's avatar
Matt Tucker committed
1311 1312 1313
     *
     * @return the roster group(s) allowed to subscribe and retrieve items.
     */
Matt Tucker's avatar
Matt Tucker committed
1314
    public Collection<String> getRosterGroupsAllowed() {
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
        return Collections.unmodifiableCollection(rosterGroupsAllowed);
    }

    /**
     * Adds a new roster group that is allowed to subscribe and retrieve items.
     * The new roster group is not going to be added to the database. Instead it is just
     * kept in memory.
     *
     * @param groupName the new roster group that is allowed to subscribe and retrieve items.
     */
    void addAllowedRosterGroup(String groupName) {
        rosterGroupsAllowed.add(groupName);
Matt Tucker's avatar
Matt Tucker committed
1327 1328 1329
    }

    public Collection<JID> getReplyRooms() {
1330 1331 1332 1333 1334
        return Collections.unmodifiableCollection(replyRooms);
    }

    void addReplyRoom(JID roomJID) {
        replyRooms.add(roomJID);
Matt Tucker's avatar
Matt Tucker committed
1335 1336 1337
    }

    public Collection<JID> getReplyTo() {
1338 1339 1340 1341 1342
        return Collections.unmodifiableCollection(replyTo);
    }

    void addReplyTo(JID entity) {
        replyTo.add(entity);
Matt Tucker's avatar
Matt Tucker committed
1343 1344
    }

Matt Tucker's avatar
Matt Tucker committed
1345 1346 1347 1348 1349 1350
    /**
     * Returns the type of payload data to be provided at the node. Usually specified by the
     * namespace of the payload (if any).
     *
     * @return the type of payload data to be provided at the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1351 1352 1353 1354
    public String getPayloadType() {
        return payloadType;
    }

Matt Tucker's avatar
Matt Tucker committed
1355 1356 1357 1358 1359 1360
    /**
     * Returns the URL of an XSL transformation which can be applied to payloads in order
     * to generate an appropriate message body element.
     *
     * @return the URL of an XSL transformation which can be applied to payloads.
     */
Matt Tucker's avatar
Matt Tucker committed
1361 1362 1363 1364
    public String getBodyXSLT() {
        return bodyXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1365 1366 1367 1368 1369 1370 1371
    /**
     * Returns the URL of an XSL transformation which can be applied to the payload format
     * in order to generate a valid Data Forms result that the client could display
     * using a generic Data Forms rendering engine.
     *
     * @return the URL of an XSL transformation which can be applied to the payload format.
     */
Matt Tucker's avatar
Matt Tucker committed
1372 1373 1374 1375
    public String getDataformXSLT() {
        return dataformXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1376 1377 1378 1379 1380
    /**
     * Returns the datetime when the node was created.
     *
     * @return the datetime when the node was created.
     */
Matt Tucker's avatar
Matt Tucker committed
1381 1382 1383 1384
    public Date getCreationDate() {
        return creationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1385 1386 1387 1388 1389
    /**
     * Returns the last date when the ndoe's configuration was modified.
     *
     * @return the last date when the ndoe's configuration was modified.
     */
Matt Tucker's avatar
Matt Tucker committed
1390 1391 1392 1393
    public Date getModificationDate() {
        return modificationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1394 1395 1396 1397 1398 1399
    /**
     * Returns the JID of the node creator. This is usually the sender's full JID of the
     * IQ packet used for creating the node.
     *
     * @return the JID of the node creator.
     */
Matt Tucker's avatar
Matt Tucker committed
1400 1401 1402 1403
    public JID getCreator() {
        return creator;
    }

Matt Tucker's avatar
Matt Tucker committed
1404 1405 1406 1407 1408 1409
    /**
     * Returns the description of the node. This information is really optional and can be
     * modified by submiting a completed data form with the new node configuration.
     *
     * @return the description of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1410 1411 1412 1413
    public String getDescription() {
        return description;
    }

Matt Tucker's avatar
Matt Tucker committed
1414 1415 1416 1417 1418 1419
    /**
     * Returns the default language of the node. This information is really optional and can be
     * modified by submiting a completed data form with the new node configuration.
     *
     * @return the default language of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1420 1421 1422 1423
    public String getLanguage() {
        return language;
    }

Matt Tucker's avatar
Matt Tucker committed
1424 1425 1426 1427 1428 1429 1430
    /**
     * Returns the JIDs of those to contact with questions. This information is not used by
     * the pubsub service. It is meant to be "discovered" by users and redirect any question
     * to the returned people to contact.
     *
     * @return the JIDs of those to contact with questions.
     */
Matt Tucker's avatar
Matt Tucker committed
1431
    public Collection<JID> getContacts() {
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        return Collections.unmodifiableCollection(contacts);
    }

    /**
     * Adds a new user as a candidate to answer questions about the node.
     *
     * @param user the JID of the new user.
     */
    void addContact(JID user) {
        contacts.add(user);
Matt Tucker's avatar
Matt Tucker committed
1442 1443
    }

Matt Tucker's avatar
Matt Tucker committed
1444 1445 1446 1447 1448 1449
    /**
     * Returns the list of nodes contained by this node. Only {@link CollectionNode} may
     * contain other nodes.
     *
     * @return the list of nodes contained by this node.
     */
Matt Tucker's avatar
Matt Tucker committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    public Collection<Node> getNodes() {
        return Collections.emptyList();
    }

    /**
     * Returns the collection node that is containing this node. The only node that
     * does not have a parent node is the root collection node.
     *
     * @return the collection node that is containing this node.
     */
    public CollectionNode getParent() {
        return parent;
    }

    /**
     * Returns the complete hierarchy of parents of this node.
     *
     * @return the complete hierarchy of parents of this node.
     */
    public Collection<CollectionNode> getParents() {
        Collection<CollectionNode> parents = new ArrayList<CollectionNode>();
        CollectionNode myParent = parent;
        while (myParent != null) {
            parents.add(myParent);
            myParent = myParent.getParent();
        }
        return parents;
    }

Matt Tucker's avatar
Matt Tucker committed
1479 1480 1481 1482 1483 1484 1485 1486 1487
    /**
     * Sets whether event notifications will include payloads. Payloads are included when
     * publishing new items. However, new items may not always include a payload depending
     * on the node configuration. Nodes can be configured to not deliver payloads for performance
     * reasons.
     *
     * @param deliverPayloads true if event notifications will include payloads.
     */
    void setPayloadDelivered(boolean deliverPayloads) {
Matt Tucker's avatar
Matt Tucker committed
1488 1489 1490 1491 1492 1493 1494
        this.deliverPayloads = deliverPayloads;
    }

    void setReplyPolicy(ItemReplyPolicy replyPolicy) {
        this.replyPolicy = replyPolicy;
    }

Matt Tucker's avatar
Matt Tucker committed
1495 1496 1497 1498 1499 1500 1501
    /**
     * Sets whether subscribers will be notified when the node configuration changes.
     *
     * @param notifyConfigChanges true if subscribers will be notified when the node
     *        configuration changes.
     */
    void setNotifiedOfConfigChanges(boolean notifyConfigChanges) {
Matt Tucker's avatar
Matt Tucker committed
1502 1503 1504
        this.notifyConfigChanges = notifyConfigChanges;
    }

Matt Tucker's avatar
Matt Tucker committed
1505 1506 1507 1508 1509 1510
    /**
     * Sets whether subscribers will be notified when the node is deleted.
     *
     * @param notifyDelete true if subscribers will be notified when the node is deleted.
     */
    void setNotifiedOfDelete(boolean notifyDelete) {
Matt Tucker's avatar
Matt Tucker committed
1511 1512 1513
        this.notifyDelete = notifyDelete;
    }

Matt Tucker's avatar
Matt Tucker committed
1514 1515 1516 1517 1518 1519 1520
    /**
     * Sets whether subscribers will be notified when items are removed from the node.
     *
     * @param notifyRetract true if subscribers will be notified when items are removed from
     *        the node.
     */
    void setNotifiedOfRetract(boolean notifyRetract) {
Matt Tucker's avatar
Matt Tucker committed
1521 1522 1523 1524 1525 1526 1527
        this.notifyRetract = notifyRetract;
    }

    void setPresenceBasedDelivery(boolean presenceBasedDelivery) {
        this.presenceBasedDelivery = presenceBasedDelivery;
    }

Matt Tucker's avatar
Matt Tucker committed
1528 1529 1530 1531 1532 1533
    /**
     * Sets the publisher model that specifies who is allowed to publish items to the node.
     *
     * @param publisherModel the publisher model that specifies who is allowed to publish items
     *        to the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1534 1535 1536 1537
    void setPublisherModel(PublisherModel publisherModel) {
        this.publisherModel = publisherModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1538 1539 1540 1541 1542
    /**
     * Sets whether users are allowed to subscribe and unsubscribe.
     *
     * @param subscriptionEnabled true if users are allowed to subscribe and unsubscribe.
     */
Matt Tucker's avatar
Matt Tucker committed
1543 1544 1545 1546
    void setSubscriptionEnabled(boolean subscriptionEnabled) {
        this.subscriptionEnabled = subscriptionEnabled;
    }

Matt Tucker's avatar
Matt Tucker committed
1547 1548 1549 1550 1551 1552 1553 1554
    /**
     * Sets whether new subscriptions should be configured to be active. Inactive
     * subscriptions will not get event notifications. However, subscribers will be
     * notified when a node is deleted no matter the subscription status.
     *
     * @param subscriptionConfigurationRequired true if new subscriptions should be
     *        configured to be active.
     */
Matt Tucker's avatar
Matt Tucker committed
1555 1556 1557 1558
    void setSubscriptionConfigurationRequired(boolean subscriptionConfigurationRequired) {
        this.subscriptionConfigurationRequired = subscriptionConfigurationRequired;
    }

Matt Tucker's avatar
Matt Tucker committed
1559 1560 1561 1562 1563 1564
    /**
     * Sets the access model that specifies who is allowed to subscribe and retrieve items.
     *
     * @param accessModel the access model that specifies who is allowed to subscribe and
     *        retrieve items.
     */
Matt Tucker's avatar
Matt Tucker committed
1565 1566 1567 1568
    void setAccessModel(AccessModel accessModel) {
        this.accessModel = accessModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1569 1570 1571
    /**
     * Sets the roster group(s) allowed to subscribe and retrieve items. This information
     * is going to be used only when using the
1572
     * {@link org.jivesoftware.openfire.pubsub.models.RosterAccess} access model.
Matt Tucker's avatar
Matt Tucker committed
1573 1574 1575 1576 1577 1578 1579
     *
     * @param rosterGroupsAllowed the roster group(s) allowed to subscribe and retrieve items.
     */
    void setRosterGroupsAllowed(Collection<String> rosterGroupsAllowed) {
        this.rosterGroupsAllowed = rosterGroupsAllowed;
    }

Matt Tucker's avatar
Matt Tucker committed
1580 1581 1582 1583 1584 1585 1586 1587
    void setReplyRooms(Collection<JID> replyRooms) {
        this.replyRooms = replyRooms;
    }

    void setReplyTo(Collection<JID> replyTo) {
        this.replyTo = replyTo;
    }

Matt Tucker's avatar
Matt Tucker committed
1588 1589 1590 1591 1592 1593
    /**
     * Sets the type of payload data to be provided at the node. Usually specified by the
     * namespace of the payload (if any).
     *
     * @param payloadType the type of payload data to be provided at the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1594 1595 1596 1597
    void setPayloadType(String payloadType) {
        this.payloadType = payloadType;
    }

Matt Tucker's avatar
Matt Tucker committed
1598 1599 1600 1601 1602 1603
    /**
     * Sets the URL of an XSL transformation which can be applied to payloads in order
     * to generate an appropriate message body element.
     *
     * @param bodyXSLT the URL of an XSL transformation which can be applied to payloads.
     */
Matt Tucker's avatar
Matt Tucker committed
1604 1605 1606 1607
    void setBodyXSLT(String bodyXSLT) {
        this.bodyXSLT = bodyXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1608 1609 1610 1611 1612 1613 1614 1615
    /**
     * Sets the URL of an XSL transformation which can be applied to the payload format
     * in order to generate a valid Data Forms result that the client could display
     * using a generic Data Forms rendering engine.
     *
     * @param dataformXSLT the URL of an XSL transformation which can be applied to the
     *        payload format.
     */
Matt Tucker's avatar
Matt Tucker committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
    void setDataformXSLT(String dataformXSLT) {
        this.dataformXSLT = dataformXSLT;
    }

    void setSavedToDB(boolean savedToDB) {
        this.savedToDB = savedToDB;
        if (savedToDB && parent != null) {
            // Notify the parent that he has a new child :)
            parent.addChildNode(this);
        }
    }

Matt Tucker's avatar
Matt Tucker committed
1628 1629 1630 1631 1632
    /**
     * Sets the datetime when the node was created.
     *
     * @param creationDate the datetime when the node was created.
     */
Matt Tucker's avatar
Matt Tucker committed
1633 1634 1635 1636
    void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1637 1638 1639 1640 1641
    /**
     * Sets the last date when the ndoe's configuration was modified.
     *
     * @param modificationDate the last date when the ndoe's configuration was modified.
     */
Matt Tucker's avatar
Matt Tucker committed
1642 1643 1644 1645
    void setModificationDate(Date modificationDate) {
        this.modificationDate = modificationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1646 1647 1648 1649 1650 1651
    /**
     * Sets the description of the node. This information is really optional and can be
     * modified by submiting a completed data form with the new node configuration.
     *
     * @param description the description of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1652 1653 1654 1655
    void setDescription(String description) {
        this.description = description;
    }

Matt Tucker's avatar
Matt Tucker committed
1656 1657 1658 1659 1660 1661
    /**
     * Sets the default language of the node. This information is really optional and can be
     * modified by submiting a completed data form with the new node configuration.
     *
     * @param language the default language of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1662 1663 1664 1665
    void setLanguage(String language) {
        this.language = language;
    }

Matt Tucker's avatar
Matt Tucker committed
1666 1667 1668 1669 1670 1671
    /**
     * Sets the name of the node. The node may not have a configured name. The node's
     * name can be changed by submiting a completed data form.
     *
     * @param name the name of the node.
     */
Matt Tucker's avatar
Matt Tucker committed
1672 1673 1674 1675
    void setName(String name) {
        this.name = name;
    }

Matt Tucker's avatar
Matt Tucker committed
1676 1677 1678 1679 1680 1681 1682
    /**
     * Sets the JIDs of those to contact with questions. This information is not used by
     * the pubsub service. It is meant to be "discovered" by users and redirect any question
     * to the returned people to contact.
     *
     * @param contacts the JIDs of those to contact with questions.
     */
Matt Tucker's avatar
Matt Tucker committed
1683 1684 1685 1686
    void setContacts(Collection<JID> contacts) {
        this.contacts = contacts;
    }

Matt Tucker's avatar
Matt Tucker committed
1687 1688 1689
    /**
     * Saves the node configuration to the backend store.
     */
Matt Tucker's avatar
Matt Tucker committed
1690 1691 1692 1693
    public void saveToDB() {
        // Make the room persistent
        if (!savedToDB) {
            PubSubPersistenceManager.createNode(service, this);
1694
            // Set that the node is now in the DB
Matt Tucker's avatar
Matt Tucker committed
1695 1696 1697 1698 1699 1700 1701 1702 1703
            setSavedToDB(true);
            // Save the existing node affiliates to the DB
            for (NodeAffiliate affialiate : affiliates) {
                PubSubPersistenceManager.saveAffiliation(service, this, affialiate, true);
            }
            // Add new subscriptions to the database
            for (NodeSubscription subscription : subscriptionsByID.values()) {
                PubSubPersistenceManager.saveSubscription(service, this, subscription, true);
            }
Matt Tucker's avatar
Matt Tucker committed
1704 1705
            // Add the new node to the list of available nodes
            service.addNode(this);
1706 1707 1708 1709
            // Notify the parent (if any) that a new node has been added
            if (parent != null) {
                parent.childNodeAdded(this);
            }
Matt Tucker's avatar
Matt Tucker committed
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        }
        else {
            PubSubPersistenceManager.updateNode(service, this);
        }
    }

    void addAffiliate(NodeAffiliate affiliate) {
        affiliates.add(affiliate);
    }

    void addSubscription(NodeSubscription subscription) {
        subscriptionsByID.put(subscription.getID(), subscription);
Matt Tucker's avatar
Matt Tucker committed
1722
        subscriptionsByJID.put(subscription.getJID().toString(), subscription);
Matt Tucker's avatar
Matt Tucker committed
1723 1724 1725 1726 1727 1728 1729 1730 1731
    }

    /**
     * Returns the subscription whose subscription JID matches the specified JID or <tt>null</tt>
     * if none was found. Accessing subscriptions by subscription JID and not by subscription ID
     * is only possible when the node does not allow multiple subscriptions from the same entity.
     * If the node allows multiple subscriptions and this message is sent then an
     * IllegalStateException exception is going to be thrown.
     *
Matt Tucker's avatar
Matt Tucker committed
1732
     * @param subscriberJID the JID of the entity that receives event notifications.
Matt Tucker's avatar
Matt Tucker committed
1733 1734 1735 1736 1737
     * @return the subscription whose subscription JID matches the specified JID or <tt>null</tt>
     *         if none was found.
     * @throws IllegalStateException If this message was used when the node supports multiple
     *         subscriptions.
     */
Matt Tucker's avatar
Matt Tucker committed
1738
    NodeSubscription getSubscription(JID subscriberJID) {
Matt Tucker's avatar
Matt Tucker committed
1739 1740
        // Check that node does not support multiple subscriptions
        if (isMultipleSubscriptionsEnabled()) {
Matt Tucker's avatar
Matt Tucker committed
1741 1742
            throw new IllegalStateException("Multiple subscriptions is enabled so subscriptions " +
                    "should be retrieved using subID.");
Matt Tucker's avatar
Matt Tucker committed
1743
        }
Matt Tucker's avatar
Matt Tucker committed
1744
        return subscriptionsByJID.get(subscriberJID.toString());
Matt Tucker's avatar
Matt Tucker committed
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    }

    /**
     * Returns the subscription whose subscription ID matches the specified ID or <tt>null</tt>
     * if none was found. Accessing subscriptions by subscription ID is always possible no matter
     * if the node allows one or multiple subscriptions for the same entity. Even when users can
     * only subscribe once to the node a subscription ID is going to be internally created though
     * never returned to the user.
     *
     * @param subscriptionID the ID of the subscription.
     * @return the subscription whose subscription ID matches the specified ID or <tt>null</tt>
     *         if none was found.
     */
    NodeSubscription getSubscription(String subscriptionID) {
        return subscriptionsByID.get(subscriptionID);
    }


    /**
     * Deletes this node from memory and the database. Subscribers are going to be notified
     * that the node has been deleted after the node was successfully deleted.
     *
     * @return true if the node was successfully deleted.
     */
    public boolean delete() {
        // Delete node from the database
        if (PubSubPersistenceManager.removeNode(service, this)) {
            // Remove this node from the parent node (if any)
            if (parent != null) {
                parent.removeChildNode(this);
            }
Matt Tucker's avatar
Matt Tucker committed
1776
            deletingNode();
Matt Tucker's avatar
Matt Tucker committed
1777
            // Broadcast delete notification to subscribers (if enabled)
Matt Tucker's avatar
Matt Tucker committed
1778
            if (isNotifiedOfDelete()) {
Matt Tucker's avatar
Matt Tucker committed
1779 1780 1781 1782 1783 1784
                // Build packet to broadcast to subscribers
                Message message = new Message();
                Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event");
                Element items = event.addElement("delete");
                items.addAttribute("node", nodeID);
                // Send notification that the node was deleted
Matt Tucker's avatar
Matt Tucker committed
1785
                broadcastNodeEvent(message, true);
Matt Tucker's avatar
Matt Tucker committed
1786
            }
1787 1788 1789 1790 1791 1792
            // Notify the parent (if any) that the node has been removed from the parent node
            if (parent != null) {
                parent.childNodeDeleted(this);
            }
            // Remove presence subscription when node was deleted.
            cancelPresenceSubscriptions();
Matt Tucker's avatar
Matt Tucker committed
1793 1794
            // Remove the node from memory
            service.removeNode(getNodeID());
Matt Tucker's avatar
Matt Tucker committed
1795 1796 1797
            // Clear collections in memory (clear them after broadcast was sent)
            affiliates.clear();
            subscriptionsByID.clear();
Matt Tucker's avatar
Matt Tucker committed
1798
            subscriptionsByJID.clear();
Matt Tucker's avatar
Matt Tucker committed
1799 1800 1801 1802 1803
            return true;
        }
        return false;
    }

Matt Tucker's avatar
Matt Tucker committed
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
    /**
     * Notification message indicating that the node is being deleted. Subclasses should
     * implement this method to delete any subclass specific information.
     */
    protected abstract void deletingNode();

    /**
     * Changes the parent node of this node. The node ID of the node will not be modified
     * based on the new parent so pubsub implementations where node ID has a semantic
     * meaning will end up affecting the meaning of the node hierarchy and possibly messing
     * up the meaning of the hierarchy.<p>
     *
     * No notifications are sent due to the new parent adoption process.
     *
     * @param newParent the new parent node of this node.
     */
    protected void changeParent(CollectionNode newParent) {
        if (parent != null) {
            // Remove this node from the current parent node
            parent.removeChildNode(this);
        }
        // Set the new parent of this node
        parent = newParent;
        if (parent != null) {
            // Add this node to the new parent node
            parent.addChildNode(this);
        }
        if (savedToDB) {
            PubSubPersistenceManager.updateNode(service, this);
        }
    }

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    /**
     * Unsubscribe from affiliates presences if node is only sending notifications to
     * only users or only unsubscribe from those subscribers that configured their
     * subscription to send notifications based on their presence show value.
     */
    private void addPresenceSubscriptions() {
        for (NodeAffiliate affiliate : affiliates) {
            if (affiliate.getAffiliation() != NodeAffiliate.Affiliation.outcast &&
                    (isPresenceBasedDelivery() || (!affiliate.getSubscriptions().isEmpty()))) {
                service.presenceSubscriptionRequired(this, affiliate.getJID());
            }
        }
    }

    /**
     * Unsubscribe from affiliates presences if node is only sending notifications to
     * only users or only unsubscribe from those subscribers that configured their
     * subscription to send notifications based on their presence show value.
     */
    private void cancelPresenceSubscriptions() {
        for (NodeSubscription subscription : getSubscriptions()) {
            if (isPresenceBasedDelivery() || !subscription.getPresenceStates().isEmpty()) {
                service.presenceSubscriptionNotRequired(this, subscription.getOwner());
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
1863
    /**
1864
     * Sends the list of affiliations with the node to the owner that sent the IQ
Matt Tucker's avatar
Matt Tucker committed
1865 1866 1867 1868
     * request.
     *
     * @param iqRequest IQ request sent by an owner of the node.
     */
1869
    void sendAffiliations(IQ iqRequest) {
Matt Tucker's avatar
Matt Tucker committed
1870 1871 1872
        IQ reply = IQ.createResultIQ(iqRequest);
        Element childElement = iqRequest.getChildElement().createCopy();
        reply.setChildElement(childElement);
1873
        Element affiliations = childElement.element("affiliations");
Matt Tucker's avatar
Matt Tucker committed
1874

Matt Tucker's avatar
Matt Tucker committed
1875
        for (NodeAffiliate affiliate : affiliates) {
1876 1877
            if (affiliate.getAffiliation() == NodeAffiliate.Affiliation.none) {
                continue;
Matt Tucker's avatar
Matt Tucker committed
1878
            }
1879
            Element entity = affiliations.addElement("affiliation");
1880 1881 1882
            entity.addAttribute("jid", affiliate.getJID().toString());
            entity.addAttribute("affiliation", affiliate.getAffiliation().name());
        }
1883 1884
        // Send reply
        service.send(reply);
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    }

    /**
     * Sends the list of subscriptions with the node to the owner that sent the IQ
     * request.
     *
     * @param iqRequest IQ request sent by an owner of the node.
     */
    void sendSubscriptions(IQ iqRequest) {
        IQ reply = IQ.createResultIQ(iqRequest);
        Element childElement = iqRequest.getChildElement().createCopy();
        reply.setChildElement(childElement);
1897
        Element subscriptions = childElement.element("subscriptions");
1898 1899 1900 1901 1902 1903

        for (NodeAffiliate affiliate : affiliates) {
            for (NodeSubscription subscription : affiliate.getSubscriptions()) {
                if (subscription.isAuthorizationPending()) {
                    continue;
                }
1904
                Element entity = subscriptions.addElement("subscription");
1905 1906 1907 1908 1909
                entity.addAttribute("jid", subscription.getJID().toString());
                //entity.addAttribute("affiliation", affiliate.getAffiliation().name());
                entity.addAttribute("subscription", subscription.getState().name());
                if (isMultipleSubscriptionsEnabled()) {
                    entity.addAttribute("subid", subscription.getID());
Matt Tucker's avatar
Matt Tucker committed
1910 1911
                }
            }
Matt Tucker's avatar
Matt Tucker committed
1912
        }
1913 1914
        // Send reply
        service.send(reply);
Matt Tucker's avatar
Matt Tucker committed
1915 1916
    }

Matt Tucker's avatar
Matt Tucker committed
1917 1918 1919 1920 1921 1922 1923 1924
    /**
     * Broadcasts a node event to subscribers of the node.
     *
     * @param message the message containing the node event.
     * @param includeAll true if all subscribers will be notified no matter their
     *        subscriptions status or configuration.
     */
    protected void broadcastNodeEvent(Message message, boolean includeAll) {
Matt Tucker's avatar
Matt Tucker committed
1925 1926
        Collection<JID> jids = new ArrayList<JID>();
        for (NodeSubscription subscription : subscriptionsByID.values()) {
Matt Tucker's avatar
Matt Tucker committed
1927
            if (includeAll || subscription.canSendNodeEvents()) {
Matt Tucker's avatar
Matt Tucker committed
1928 1929 1930 1931 1932 1933 1934
                jids.add(subscription.getJID());
            }
        }
        // Broadcast packet to subscribers
        service.broadcast(this, message, jids);
    }

Matt Tucker's avatar
Matt Tucker committed
1935 1936 1937 1938 1939 1940 1941 1942 1943
    /**
     * Sends an event notification to the specified subscriber. The event notification may
     * include information about the affected subscriptions.
     *
     * @param subscriberJID the subscriber JID that will get the notification.
     * @param notification the message to send to the subscriber.
     * @param subIDs the list of affected subscription IDs or null when node does not
     *        allow multiple subscriptions.
     */
Matt Tucker's avatar
Matt Tucker committed
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    protected void sendEventNotification(JID subscriberJID, Message notification,
            Collection<String> subIDs) {
        Element headers = null;
        if (subIDs != null) {
            // Notate the event notification with the ID of the affected subscriptions
            headers = notification.addChildElement("headers", "http://jabber.org/protocol/shim");
            for (String subID : subIDs) {
                Element header = headers.addElement("header");
                header.addAttribute("name", "pubsub#subid");
                header.setText(subID);
            }
        }

Matt Tucker's avatar
Matt Tucker committed
1957
        service.sendNotification(this, notification, subscriberJID);
Matt Tucker's avatar
Matt Tucker committed
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968

        if (headers != null) {
            // Remove the added child element that includes subscription IDs information
            notification.getElement().remove(headers);
        }
    }

    /**
     * Creates a new subscription and possibly a new affiliate if the owner of the subscription
     * does not have any existing affiliation with the node. The new subscription might require
     * to be authorized by a node owner to be active. If new subscriptions are required to be
Matt Tucker's avatar
Matt Tucker committed
1969 1970 1971 1972 1973
     * configured before being active then the subscription state would be "unconfigured".<p>
     *
     * The originalIQ parameter may be <tt>null</tt> when using this API internally. When no
     * IQ packet was sent then no IQ result will be sent to the sender. The rest of the
     * functionality is the same.
Matt Tucker's avatar
Matt Tucker committed
1974
     *
Matt Tucker's avatar
Matt Tucker committed
1975 1976
     * @param originalIQ the IQ packet sent by the entity to subscribe to the node or
     *        null when using this API internally.
Matt Tucker's avatar
Matt Tucker committed
1977 1978 1979 1980 1981 1982 1983
     * @param owner the JID of the affiliate.
     * @param subscriber the JID where event notifications are going to be sent.
     * @param authorizationRequired true if the new subscriptions needs to be authorized by
     *        a node owner.
     * @param options the data form with the subscription configuration or null if subscriber
     *        didn't provide a configuration.
     */
Matt Tucker's avatar
Matt Tucker committed
1984 1985
    public void createSubscription(IQ originalIQ, JID owner, JID subscriber,
            boolean authorizationRequired, DataForm options) {
Matt Tucker's avatar
Matt Tucker committed
1986 1987 1988 1989 1990 1991
        // Create a new affiliation if required
        if (getAffiliate(owner) == null) {
            addNoneAffiliation(owner);
        }
        // Figure out subscription status
        NodeSubscription.State subState = NodeSubscription.State.subscribed;
1992
        if (isSubscriptionConfigurationRequired()) {
Matt Tucker's avatar
Matt Tucker committed
1993 1994 1995
            // User has to configure the subscription to make it active
            subState = NodeSubscription.State.unconfigured;
        }
1996 1997 1998 1999
        else if (authorizationRequired && !isAdmin(owner)) {
            // Node owner needs to authorize subscription request so status is pending
            subState = NodeSubscription.State.pending;
        }
Matt Tucker's avatar
Matt Tucker committed
2000 2001
        // Generate a subscription ID (override even if one was sent by the client)
        String id = StringUtils.randomString(40);
Matt Tucker's avatar
Matt Tucker committed
2002
        // Create new subscription
Matt Tucker's avatar
Matt Tucker committed
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
        NodeSubscription subscription =
                new NodeSubscription(service, this, owner, subscriber, subState, id);
        // Configure the subscription with the specified configuration (if any)
        if (options != null) {
            subscription.configure(options);
        }
        addSubscription(subscription);

        if (savedToDB) {
            // Add the new subscription to the database
            PubSubPersistenceManager.saveSubscription(service, this, subscription, true);
        }
Matt Tucker's avatar
Matt Tucker committed
2015

Matt Tucker's avatar
Matt Tucker committed
2016 2017 2018 2019 2020
        if (originalIQ != null) {
            // Reply with subscription and affiliation status indicating if subscription
            // must be configured (only when subscription was made through an IQ packet)
            subscription.sendSubscriptionState(originalIQ);
        }
Matt Tucker's avatar
Matt Tucker committed
2021

Matt Tucker's avatar
Matt Tucker committed
2022 2023 2024 2025 2026 2027
        // If subscription is pending then send notification to node owners asking to approve
        // new subscription
        if (subscription.isAuthorizationPending()) {
            subscription.sendAuthorizationRequest();
        }

Matt Tucker's avatar
Matt Tucker committed
2028
        // Send last published item (if node is leaf node and subscription status is ok)
Matt Tucker's avatar
Matt Tucker committed
2029
        if (isSendItemSubscribe() && subscription.isActive()) {
Matt Tucker's avatar
Matt Tucker committed
2030 2031 2032 2033 2034
            PublishedItem lastItem = getLastPublishedItem();
            if (lastItem != null) {
                subscription.sendLastPublishedItem(lastItem);
            }
        }
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044

        // Check if we need to subscribe to the presence of the owner
        if (isPresenceBasedDelivery() && getSubscriptions(subscription.getOwner()).size() == 1) {
            if (subscription.getPresenceStates().isEmpty()) {
                // Subscribe to the owner's presence since the node is only sending events to
                // online subscribers and this is the first subscription of the user and the
                // subscription is not filtering notifications based on presence show values.
                service.presenceSubscriptionRequired(this, owner);
            }
        }
Matt Tucker's avatar
Matt Tucker committed
2045 2046 2047 2048 2049 2050 2051 2052 2053
    }

    /**
     * Cancels an existing subscription to the node. If the subscriber does not have any
     * other subscription to the node and his affiliation was of type <tt>none</tt> then
     * remove the existing affiliation too.
     *
     * @param subscription the subscription to cancel.
     */
Matt Tucker's avatar
Matt Tucker committed
2054
    public void cancelSubscription(NodeSubscription subscription) {
Matt Tucker's avatar
Matt Tucker committed
2055 2056
        // Remove subscription from memory
        subscriptionsByID.remove(subscription.getID());
Matt Tucker's avatar
Matt Tucker committed
2057
        subscriptionsByJID.remove(subscription.getJID().toString());
Matt Tucker's avatar
Matt Tucker committed
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
        // Check if user has affiliation of type "none" and there are no more subscriptions
        NodeAffiliate affiliate = subscription.getAffiliate();
        if (affiliate != null && affiliate.getAffiliation() == NodeAffiliate.Affiliation.none &&
                getSubscriptions(subscription.getOwner()).isEmpty()) {
            // Remove affiliation of type "none"
            removeAffiliation(affiliate);
        }
        if (savedToDB) {
            // Remove the subscription from the database
            PubSubPersistenceManager.removeSubscription(service, this, subscription);
        }
2069 2070 2071 2072
        // Check if we need to unsubscribe from the presence of the owner
        if (isPresenceBasedDelivery() && getSubscriptions(subscription.getOwner()).isEmpty()) {
            service.presenceSubscriptionNotRequired(this, subscription.getOwner());
        }
Matt Tucker's avatar
Matt Tucker committed
2073 2074 2075 2076 2077 2078 2079 2080 2081
    }

    /**
     * Returns the {@link PublishedItem} whose ID matches the specified item ID or <tt>null</tt>
     * if none was found. Item ID may or may not exist and it depends on the node's configuration.
     * When the node is configured to not include payloads in event notifications and
     * published items are not persistent then item ID is not used. In this case a <tt>null</tt>
     * value will always be returned.
     *
Matt Tucker's avatar
Matt Tucker committed
2082
     * @param itemID the ID of the item to retrieve.
Matt Tucker's avatar
Matt Tucker committed
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
     * @return the PublishedItem whose ID matches the specified item ID or null if none was found.
     */
    public PublishedItem getPublishedItem(String itemID) {
        return null;
    }

    /**
     * Returns the list of {@link PublishedItem} that were published to the node. The
     * returned collection cannot be modified. Collection nodes does not support publishing
     * of items so an empty list will be returned in that case.
     *
     * @return the list of PublishedItem that were published to the node.
     */
    public List<PublishedItem> getPublishedItems() {
        return Collections.emptyList();
    }

    /**
     * Returns a list of {@link PublishedItem} with the most recent N items published to
     * the node. The returned collection cannot be modified. Collection nodes does not
     * support publishing of items so an empty list will be returned in that case.
     *
Matt Tucker's avatar
Matt Tucker committed
2105
     * @param recentItems number of recent items to retrieve.
Matt Tucker's avatar
Matt Tucker committed
2106 2107 2108 2109 2110 2111 2112
     * @return a list of PublishedItem with the most recent N items published to
     *         the node.
     */
    public List<PublishedItem> getPublishedItems(int recentItems) {
        return Collections.emptyList();
    }

Matt Tucker's avatar
Matt Tucker committed
2113 2114 2115
    /**
     * Returns a list with the subscriptions to the node that are pending to be approved by
     * a node owner. If the node is not using the access model
2116
     * {@link org.jivesoftware.openfire.pubsub.models.AuthorizeAccess} then the result will
Matt Tucker's avatar
Matt Tucker committed
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
     * be an empty collection.
     *
     * @return a list with the subscriptions to the node that are pending to be approved by
     *         a node owner.
     */
    public Collection<NodeSubscription> getPendingSubscriptions() {
        if (accessModel.isAuthorizationRequired()) {
            List<NodeSubscription> pendingSubscriptions = new ArrayList<NodeSubscription>();
            for (NodeSubscription subscription : subscriptionsByID.values()) {
                if (subscription.isAuthorizationPending()) {
                    pendingSubscriptions.add(subscription);
                }
            }
            return pendingSubscriptions;
        }
        return Collections.emptyList();
    }

Matt Tucker's avatar
Matt Tucker committed
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
    public String toString() {
        return super.toString() + " - ID: " + getNodeID();
    }

    /**
     * Returns the last {@link PublishedItem} that was published to the node or <tt>null</tt> if
     * the node does not have published items. Collection nodes does not support publishing
     * of items so a <tt>null</tt> will be returned in that case.
     *
     * @return the PublishedItem that was published to the node or <tt>null</tt> if
     *         the node does not have published items.
     */
    public PublishedItem getLastPublishedItem() {
        return null;
    }

Matt Tucker's avatar
Matt Tucker committed
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    /**
     * Approves or cancels a subscriptions that was pending to be approved by a node owner.
     * Subscriptions that were not approved will be deleted. Approved subscriptions will be
     * activated (i.e. will be able to receive event notifications) as long as the subscriber
     * is not required to configure the subscription.
     *
     * @param subscription the subscriptions that was approved or rejected.
     * @param approved true when susbcription was approved. Otherwise the subscription was rejected.
     */
    public void approveSubscription(NodeSubscription subscription, boolean approved) {
        if (!subscription.isAuthorizationPending()) {
            // Do nothing if the subscription is no longer pending
            return;
        }
        if (approved) {
            // Mark that the subscription to the node has been approved
            subscription.approved();
        }
        else  {
            // Cancel the subscription to the node
            cancelSubscription(subscription);
        }
    }

Matt Tucker's avatar
Matt Tucker committed
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
    /**
     * Policy that defines whether owners or publisher should receive replies to items.
     */
    public static enum ItemReplyPolicy {

        /**
         * Statically specify a replyto of the node owner(s).
         */
        owner,
        /**
         * Dynamically specify a replyto of the item publisher.
         */
2187
        publisher
Matt Tucker's avatar
Matt Tucker committed
2188 2189
    }
}