Node.java 90.6 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile: $
 * $Revision: $
 * $Date: $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
Matt Tucker's avatar
Matt Tucker committed
19 20
 */

21
package org.jivesoftware.openfire.pubsub;
Matt Tucker's avatar
Matt Tucker committed
22

23 24 25 26 27 28 29 30 31
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

Matt Tucker's avatar
Matt Tucker committed
32
import org.dom4j.Element;
33
import org.jivesoftware.openfire.SessionManager;
34
import org.jivesoftware.openfire.cluster.ClusterManager;
35
import org.jivesoftware.openfire.pubsub.cluster.AffiliationTask;
36 37
import org.jivesoftware.openfire.pubsub.cluster.CancelSubscriptionTask;
import org.jivesoftware.openfire.pubsub.cluster.ModifySubscriptionTask;
38
import org.jivesoftware.openfire.pubsub.cluster.NewSubscriptionTask;
39
import org.jivesoftware.openfire.pubsub.cluster.RemoveNodeTask;
40 41
import org.jivesoftware.openfire.pubsub.models.AccessModel;
import org.jivesoftware.openfire.pubsub.models.PublisherModel;
42 43
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.StringUtils;
44
import org.jivesoftware.util.cache.CacheFactory;
Matt Tucker's avatar
Matt Tucker committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58
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;

/**
 * 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 {
59

Matt Tucker's avatar
Matt Tucker committed
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    /**
     * 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
184 185 186 187 188 189 190 191 192
    /**
     * 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
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

    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
222
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
223
     */
Matt Tucker's avatar
Matt Tucker committed
224 225
    public NodeAffiliate addOwner(JID jid) {
        NodeAffiliate nodeAffiliate = addAffiliation(jid, NodeAffiliate.Affiliation.owner);
226 227 228 229
        // Approve any pending subscription
        for (NodeSubscription subscription : getSubscriptions(jid)) {
            if (subscription.isAuthorizationPending()) {
                subscription.approved();
Matt Tucker's avatar
Matt Tucker committed
230
            }
Matt Tucker's avatar
Matt Tucker committed
231
        }
Matt Tucker's avatar
Matt Tucker committed
232
        return nodeAffiliate;
Matt Tucker's avatar
Matt Tucker committed
233 234 235
    }

    /**
236 237 238
     * 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
239 240 241 242
     *
     * @param jid the JID of the user being removed as a node owner.
     */
    public void removeOwner(JID jid) {
243 244 245 246 247 248 249 250 251 252
        // 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
253 254 255 256 257 258 259
    }

    /**
     * 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
260
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
261
     */
Matt Tucker's avatar
Matt Tucker committed
262
    public NodeAffiliate addPublisher(JID jid) {
263
        return addAffiliation(jid, NodeAffiliate.Affiliation.publisher);
Matt Tucker's avatar
Matt Tucker committed
264 265 266
    }

    /**
267 268 269
     * 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
270 271 272 273
     *
     * @param jid the JID of the user being removed as a node publisher.
     */
    public void removePublisher(JID jid) {
274 275 276 277 278 279 280 281 282 283
        // 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
284 285 286 287 288 289 290
    }

    /**
     * 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
291
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
292
     */
Matt Tucker's avatar
Matt Tucker committed
293 294
    public NodeAffiliate addNoneAffiliation(JID jid) {
        return addAffiliation(jid, NodeAffiliate.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
295 296 297 298 299 300 301
    }

    /**
     * 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
302
     * @return the newly created or modified affiliation to the node.
Matt Tucker's avatar
Matt Tucker committed
303
     */
Matt Tucker's avatar
Matt Tucker committed
304 305
    public NodeAffiliate addOutcast(JID jid) {
        NodeAffiliate nodeAffiliate = addAffiliation(jid, NodeAffiliate.Affiliation.outcast);
Matt Tucker's avatar
Matt Tucker committed
306 307
        // Delete existing subscriptions
        removeSubscriptions(jid);
Matt Tucker's avatar
Matt Tucker committed
308
        return nodeAffiliate;
Matt Tucker's avatar
Matt Tucker committed
309 310 311 312 313 314 315 316 317 318 319
    }

    /**
     * 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
320
    private NodeAffiliate addAffiliation(JID jid, NodeAffiliate.Affiliation affiliation) {
Matt Tucker's avatar
Matt Tucker committed
321 322 323 324 325 326
        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
327
            return affiliate;
Matt Tucker's avatar
Matt Tucker committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        }
        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
343
            PubSubPersistenceManager.saveAffiliation(this, affiliate, created);
Matt Tucker's avatar
Matt Tucker committed
344
        }
345 346 347 348
        
        // Update the other members with the new affiliation
        CacheFactory.doClusterTask(new AffiliationTask(this, jid, affiliation));

Matt Tucker's avatar
Matt Tucker committed
349
        return affiliate;
Matt Tucker's avatar
Matt Tucker committed
350 351 352 353 354
    }

    private void removeAffiliation(JID jid, NodeAffiliate.Affiliation affiliation) {
        // Get the current affiliation of the specified JID
        NodeAffiliate affiliate = getAffiliate(jid);
355
        // Check if the current affiliatin of the user is the one to remove
Matt Tucker's avatar
Matt Tucker committed
356 357 358 359 360 361 362 363 364 365
        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
366
            PubSubPersistenceManager.removeAffiliation(this, affiliate);
Matt Tucker's avatar
Matt Tucker committed
367 368 369
        }
    }

Matt Tucker's avatar
Matt Tucker committed
370 371 372 373 374
    /**
     * 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
375 376
    private void removeSubscriptions(JID owner) {
        for (NodeSubscription subscription : getSubscriptions(owner)) {
Matt Tucker's avatar
Matt Tucker committed
377
            cancelSubscription(subscription);
Matt Tucker's avatar
Matt Tucker committed
378 379 380 381 382 383 384 385 386 387
        }
    }

    /**
     * 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
388
     * @return the list of subscriptions owned by the specified user.
Matt Tucker's avatar
Matt Tucker committed
389
     */
Matt Tucker's avatar
Matt Tucker committed
390
    public Collection<NodeSubscription> getSubscriptions(JID owner) {
Matt Tucker's avatar
Matt Tucker committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        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();
    }

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    /**
     * Returns all subscriptions to the node. If multiple subscriptions are enabled,
     * this method returns the subscriptions by <tt>subId</tt>, otherwise it returns
     * the subscriptions by {@link JID}.
     *
     * @return All subscriptions to the node.
     */
    public Collection<NodeSubscription> getAllSubscriptions() {
        if (isMultipleSubscriptionsEnabled()) {
            return subscriptionsByID.values();
        } else {
            return subscriptionsByJID.values();
        }
    }

Matt Tucker's avatar
Matt Tucker committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    /**
     * 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
441 442 443 444 445 446 447 448
    /**
     * 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
449 450 451 452 453 454 455 456 457 458
    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
459 460 461
    /**
     * Returns a collection with the JID of the enitities with an affiliation of
     * {@link NodeAffiliate.Affiliation#publisher}. When using the publisher model
462
     * {@link org.jivesoftware.openfire.pubsub.models.OpenPublisher} anyone may publish
Matt Tucker's avatar
Matt Tucker committed
463 464 465 466 467
     * 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
468 469 470 471 472 473 474 475 476 477
    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
478 479 480 481 482 483 484 485 486
    /**
     * 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
487
    public void configure(DataForm completedForm) throws NotAcceptableException {
488 489
        boolean wasPresenceBased = isPresenceBasedDelivery();

Matt Tucker's avatar
Matt Tucker committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        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));
                    }
506 507 508
                    catch (Exception e) {
                        // Do nothing
                    }
Matt Tucker's avatar
Matt Tucker committed
509 510 511 512 513 514 515 516 517 518
                }
            }

            // 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
519
                    // Do nothing
Matt Tucker's avatar
Matt Tucker committed
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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
                }
                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()) {
585
                        addAllowedRosterGroup(value);
Matt Tucker's avatar
Matt Tucker committed
586 587 588 589 590 591 592
                    }
                }
                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 {
593
                            addContact(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
594
                        }
595 596 597
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
                    }
                }
                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 {
623
                            addReplyRoom(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
624
                        }
625 626 627
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
628 629 630 631 632 633 634
                    }
                }
                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 {
635
                            addReplyTo(new JID(value));
Matt Tucker's avatar
Matt Tucker committed
636
                        }
637 638 639
                        catch (Exception e) {
                            // Do nothing
                        }
Matt Tucker's avatar
Matt Tucker committed
640 641
                    }
                }
642 643 644 645 646 647 648 649 650 651 652 653
                else if ("pubsub#collection".equals(field.getVariable())) {
                    // Set the parent collection node
                    values = field.getValues();
                    String newParent = values.size() > 0 ? values.get(0) : " ";
                    Node newParentNode = service.getNode(newParent);

                    if (!(newParentNode instanceof CollectionNode))
                    {
                    	throw new NotAcceptableException("Specified node in field pubsub#collection [" + newParent + "] " + ((newParentNode == null) ? "does not exist" : "is not a collection node"));
                    }
                    changeParent((CollectionNode) newParentNode);
                }
Matt Tucker's avatar
Matt Tucker committed
654 655 656 657 658 659 660 661 662 663
                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
664
                oldOwners.removeAll(owners);
Matt Tucker's avatar
Matt Tucker committed
665 666 667 668 669
                for (JID jid : oldOwners) {
                    removeOwner(jid);
                }

                // Calculate new owners and add them to the DB
Matt Tucker's avatar
Matt Tucker committed
670
                owners.removeAll(getOwners());
Matt Tucker's avatar
Matt Tucker committed
671 672 673 674
                for (JID jid : owners) {
                    addOwner(jid);
                }
            }
675
            // TODO Before removing owner or admin check if user was changed from admin to owner or vice versa. This way his subscriptions are not going to be deleted.
Matt Tucker's avatar
Matt Tucker committed
676 677 678 679 680 681 682 683 684
            // 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));
                    }
685 686 687
                    catch (Exception e) {
                        // Do nothing
                    }
Matt Tucker's avatar
Matt Tucker committed
688 689 690
                }
                // Calculate publishers to remove and remove them from the DB
                Collection<JID> oldPublishers = getPublishers();
Matt Tucker's avatar
Matt Tucker committed
691
                oldPublishers.removeAll(publishers);
Matt Tucker's avatar
Matt Tucker committed
692 693 694 695 696
                for (JID jid : oldPublishers) {
                    removePublisher(jid);
                }

                // Calculate new publishers and add them to the DB
Matt Tucker's avatar
Matt Tucker committed
697
                publishers.removeAll(getPublishers());
Matt Tucker's avatar
Matt Tucker committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
                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();
715 716 717 718 719 720 721 722 723 724

        // 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
725 726 727 728 729 730 731 732 733
    }

    /**
     * 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.
734
     * @throws NotAcceptableException if field cannot be configured because of invalid data.
Matt Tucker's avatar
Matt Tucker committed
735
     */
736
    protected abstract void configure(FormField field) throws NotAcceptableException;
Matt Tucker's avatar
Matt Tucker committed
737 738 739 740 741 742 743 744 745

    /**
     * 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
746 747 748 749 750
    /**
     * 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
751
    private void nodeConfigurationChanged() {
Matt Tucker's avatar
Matt Tucker committed
752
        if (!isNotifiedOfConfigChanges() || !savedToDB) {
Matt Tucker's avatar
Matt Tucker committed
753 754 755 756 757 758 759 760
            // 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");
761 762 763
        Element config = event.addElement("configuration");
        config.addAttribute("node", nodeID);

Matt Tucker's avatar
Matt Tucker committed
764
        if (deliverPayloads) {
765
            config.add(getConfigurationChangeForm().getElement());
Matt Tucker's avatar
Matt Tucker committed
766 767
        }
        // Send notification that the node configuration has changed
Matt Tucker's avatar
Matt Tucker committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        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();
801
        formField.setVariable("pubsub#subscriber_jid");
Matt Tucker's avatar
Matt Tucker committed
802 803 804 805 806 807 808 809 810 811 812
        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
813 814
    }

Matt Tucker's avatar
Matt Tucker committed
815

Matt Tucker's avatar
Matt Tucker committed
816 817 818 819 820 821 822 823 824 825 826
    /**
     * 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
827 828 829 830 831 832

        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
833 834 835 836 837
        // Add the form fields and configure them for edition
        addFormFields(form, true);
        return form;
    }

Matt Tucker's avatar
Matt Tucker committed
838 839 840 841 842 843 844 845 846
    /**
     * 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
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    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);

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
        formField = form.addField();
        formField.setVariable("pubsub#node_type");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.node_type"));
        }
        
        formField = form.addField();
        formField.setVariable("pubsub#collection");
        if (isEditing) {
            formField.setType(FormField.Type.text_single);
            formField.setLabel(LocaleUtils.getLocalizedString("pubsub.form.conf.collection"));
        }

        if (!parent.isRootCollectionNode()) {
        	formField.addValue(parent.getNodeID());
        }

Matt Tucker's avatar
Matt Tucker committed
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 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
        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
1076 1077 1078 1079
        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
1080 1081 1082 1083 1084 1085
        // 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
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    /**
     * 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
1103 1104 1105 1106 1107
    /**
     * 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
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    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() {
1121
        return service.isMultipleSubscriptionsEnabled();
Matt Tucker's avatar
Matt Tucker committed
1122 1123
    }

Matt Tucker's avatar
Matt Tucker committed
1124 1125 1126 1127 1128 1129
    /**
     * 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
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    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) {
1172
            user = user.asBareJID();
Matt Tucker's avatar
Matt Tucker committed
1173 1174 1175 1176 1177
            return isAdmin(user);
        }
        return false;
    }

1178 1179 1180 1181 1182 1183 1184 1185 1186
    /**
     * Returns the {@link PubSubService} to which this node belongs.
     *
     * @return the pubsub service.
     */
    public PubSubService getService() {
        return service;
    }

Matt Tucker's avatar
Matt Tucker committed
1187 1188 1189 1190 1191
    /**
     * 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
1192 1193 1194 1195
    public String getNodeID() {
        return nodeID;
    }

Matt Tucker's avatar
Matt Tucker committed
1196 1197 1198 1199 1200 1201
    /**
     * 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
1202 1203 1204 1205
    public String getName() {
        return name;
    }

Matt Tucker's avatar
Matt Tucker committed
1206 1207 1208 1209 1210 1211 1212 1213 1214
    /**
     * 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
1215 1216 1217 1218 1219 1220 1221
        return deliverPayloads;
    }

    public ItemReplyPolicy getReplyPolicy() {
        return replyPolicy;
    }

Matt Tucker's avatar
Matt Tucker committed
1222 1223 1224 1225 1226 1227
    /**
     * 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
1228 1229 1230
        return notifyConfigChanges;
    }

Matt Tucker's avatar
Matt Tucker committed
1231 1232 1233 1234 1235 1236
    /**
     * 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
1237 1238 1239
        return notifyDelete;
    }

Matt Tucker's avatar
Matt Tucker committed
1240 1241 1242 1243 1244 1245
    /**
     * 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
1246 1247 1248
        return notifyRetract;
    }

Matt Tucker's avatar
Matt Tucker committed
1249 1250 1251 1252 1253
    /**
     * 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
1254 1255 1256 1257
    public boolean isPresenceBasedDelivery() {
        return presenceBasedDelivery;
    }

Matt Tucker's avatar
Matt Tucker committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    /**
     * 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
1319 1320 1321 1322 1323
    /**
     * 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
1324
    public boolean isSendItemSubscribe() {
Matt Tucker's avatar
Matt Tucker committed
1325
        return false;
Matt Tucker's avatar
Matt Tucker committed
1326 1327
    }

Matt Tucker's avatar
Matt Tucker committed
1328 1329 1330 1331 1332
    /**
     * 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
1333 1334 1335 1336
    public PublisherModel getPublisherModel() {
        return publisherModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1337 1338 1339 1340 1341
    /**
     * 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
1342 1343 1344 1345
    public boolean isSubscriptionEnabled() {
        return subscriptionEnabled;
    }

Matt Tucker's avatar
Matt Tucker committed
1346 1347 1348 1349 1350 1351 1352
    /**
     * 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
1353 1354 1355 1356
    public boolean isSubscriptionConfigurationRequired() {
        return subscriptionConfigurationRequired;
    }

Matt Tucker's avatar
Matt Tucker committed
1357 1358 1359 1360 1361
    /**
     * 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
1362 1363 1364 1365
    public AccessModel getAccessModel() {
        return accessModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1366 1367 1368
    /**
     * Returns the roster group(s) allowed to subscribe and retrieve items. This information
     * is going to be used only when using the
1369
     * {@link org.jivesoftware.openfire.pubsub.models.RosterAccess} access model.
Matt Tucker's avatar
Matt Tucker committed
1370 1371 1372
     *
     * @return the roster group(s) allowed to subscribe and retrieve items.
     */
Matt Tucker's avatar
Matt Tucker committed
1373
    public Collection<String> getRosterGroupsAllowed() {
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        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
1386 1387 1388
    }

    public Collection<JID> getReplyRooms() {
1389 1390 1391 1392 1393
        return Collections.unmodifiableCollection(replyRooms);
    }

    void addReplyRoom(JID roomJID) {
        replyRooms.add(roomJID);
Matt Tucker's avatar
Matt Tucker committed
1394 1395 1396
    }

    public Collection<JID> getReplyTo() {
1397 1398 1399 1400 1401
        return Collections.unmodifiableCollection(replyTo);
    }

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

Matt Tucker's avatar
Matt Tucker committed
1404 1405 1406 1407 1408 1409
    /**
     * 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
1410 1411 1412 1413
    public String getPayloadType() {
        return payloadType;
    }

Matt Tucker's avatar
Matt Tucker committed
1414 1415 1416 1417 1418 1419
    /**
     * 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
1420 1421 1422 1423
    public String getBodyXSLT() {
        return bodyXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1424 1425 1426 1427 1428 1429 1430
    /**
     * 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
1431 1432 1433 1434
    public String getDataformXSLT() {
        return dataformXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1435 1436 1437 1438 1439
    /**
     * Returns the datetime when the node was created.
     *
     * @return the datetime when the node was created.
     */
Matt Tucker's avatar
Matt Tucker committed
1440 1441 1442 1443
    public Date getCreationDate() {
        return creationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1444 1445 1446 1447 1448
    /**
     * 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
1449 1450 1451 1452
    public Date getModificationDate() {
        return modificationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1453 1454 1455 1456 1457 1458
    /**
     * 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
1459 1460 1461 1462
    public JID getCreator() {
        return creator;
    }

Matt Tucker's avatar
Matt Tucker committed
1463 1464 1465 1466 1467 1468
    /**
     * 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
1469 1470 1471 1472
    public String getDescription() {
        return description;
    }

Matt Tucker's avatar
Matt Tucker committed
1473 1474 1475 1476 1477 1478
    /**
     * 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
1479 1480 1481 1482
    public String getLanguage() {
        return language;
    }

Matt Tucker's avatar
Matt Tucker committed
1483 1484 1485 1486 1487 1488 1489
    /**
     * 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
1490
    public Collection<JID> getContacts() {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
        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
1501 1502
    }

Matt Tucker's avatar
Matt Tucker committed
1503 1504 1505 1506 1507 1508
    /**
     * 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
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    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
1538 1539 1540 1541 1542 1543 1544 1545 1546
    /**
     * 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
1547 1548 1549 1550 1551 1552 1553
        this.deliverPayloads = deliverPayloads;
    }

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

Matt Tucker's avatar
Matt Tucker committed
1554 1555 1556 1557 1558 1559 1560
    /**
     * 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
1561 1562 1563
        this.notifyConfigChanges = notifyConfigChanges;
    }

Matt Tucker's avatar
Matt Tucker committed
1564 1565 1566 1567 1568 1569
    /**
     * 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
1570 1571 1572
        this.notifyDelete = notifyDelete;
    }

Matt Tucker's avatar
Matt Tucker committed
1573 1574 1575 1576 1577 1578 1579
    /**
     * 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
1580 1581 1582 1583 1584 1585 1586
        this.notifyRetract = notifyRetract;
    }

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

Matt Tucker's avatar
Matt Tucker committed
1587 1588 1589 1590 1591 1592
    /**
     * 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
1593 1594 1595 1596
    void setPublisherModel(PublisherModel publisherModel) {
        this.publisherModel = publisherModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1597 1598 1599 1600 1601
    /**
     * 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
1602 1603 1604 1605
    void setSubscriptionEnabled(boolean subscriptionEnabled) {
        this.subscriptionEnabled = subscriptionEnabled;
    }

Matt Tucker's avatar
Matt Tucker committed
1606 1607 1608 1609 1610 1611 1612 1613
    /**
     * 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
1614 1615 1616 1617
    void setSubscriptionConfigurationRequired(boolean subscriptionConfigurationRequired) {
        this.subscriptionConfigurationRequired = subscriptionConfigurationRequired;
    }

Matt Tucker's avatar
Matt Tucker committed
1618 1619 1620 1621 1622 1623
    /**
     * 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
1624 1625 1626 1627
    void setAccessModel(AccessModel accessModel) {
        this.accessModel = accessModel;
    }

Matt Tucker's avatar
Matt Tucker committed
1628 1629 1630
    /**
     * Sets the roster group(s) allowed to subscribe and retrieve items. This information
     * is going to be used only when using the
1631
     * {@link org.jivesoftware.openfire.pubsub.models.RosterAccess} access model.
Matt Tucker's avatar
Matt Tucker committed
1632 1633 1634 1635 1636 1637 1638
     *
     * @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
1639 1640 1641 1642 1643 1644 1645 1646
    void setReplyRooms(Collection<JID> replyRooms) {
        this.replyRooms = replyRooms;
    }

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

Matt Tucker's avatar
Matt Tucker committed
1647 1648 1649 1650 1651 1652
    /**
     * 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
1653 1654 1655 1656
    void setPayloadType(String payloadType) {
        this.payloadType = payloadType;
    }

Matt Tucker's avatar
Matt Tucker committed
1657 1658 1659 1660 1661 1662
    /**
     * 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
1663 1664 1665 1666
    void setBodyXSLT(String bodyXSLT) {
        this.bodyXSLT = bodyXSLT;
    }

Matt Tucker's avatar
Matt Tucker committed
1667 1668 1669 1670 1671 1672 1673 1674
    /**
     * 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
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
    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
1687 1688 1689 1690 1691
    /**
     * Sets the datetime when the node was created.
     *
     * @param creationDate the datetime when the node was created.
     */
Matt Tucker's avatar
Matt Tucker committed
1692 1693 1694 1695
    void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1696 1697 1698 1699 1700
    /**
     * 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
1701 1702 1703 1704
    void setModificationDate(Date modificationDate) {
        this.modificationDate = modificationDate;
    }

Matt Tucker's avatar
Matt Tucker committed
1705 1706 1707 1708 1709 1710
    /**
     * 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
1711 1712 1713 1714
    void setDescription(String description) {
        this.description = description;
    }

Matt Tucker's avatar
Matt Tucker committed
1715 1716 1717 1718 1719 1720
    /**
     * 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
1721 1722 1723 1724
    void setLanguage(String language) {
        this.language = language;
    }

Matt Tucker's avatar
Matt Tucker committed
1725 1726 1727 1728 1729 1730
    /**
     * 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
1731 1732 1733 1734
    void setName(String name) {
        this.name = name;
    }

Matt Tucker's avatar
Matt Tucker committed
1735 1736 1737 1738 1739 1740 1741
    /**
     * 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
1742 1743 1744 1745
    void setContacts(Collection<JID> contacts) {
        this.contacts = contacts;
    }

Matt Tucker's avatar
Matt Tucker committed
1746 1747 1748
    /**
     * Saves the node configuration to the backend store.
     */
Matt Tucker's avatar
Matt Tucker committed
1749 1750 1751
    public void saveToDB() {
        // Make the room persistent
        if (!savedToDB) {
1752
            PubSubPersistenceManager.createNode(this);
1753
            // Set that the node is now in the DB
Matt Tucker's avatar
Matt Tucker committed
1754 1755 1756
            setSavedToDB(true);
            // Save the existing node affiliates to the DB
            for (NodeAffiliate affialiate : affiliates) {
1757
                PubSubPersistenceManager.saveAffiliation(this, affialiate, true);
Matt Tucker's avatar
Matt Tucker committed
1758 1759 1760
            }
            // Add new subscriptions to the database
            for (NodeSubscription subscription : subscriptionsByID.values()) {
1761
                PubSubPersistenceManager.saveSubscription(this, subscription, true);
Matt Tucker's avatar
Matt Tucker committed
1762
            }
Matt Tucker's avatar
Matt Tucker committed
1763 1764
            // Add the new node to the list of available nodes
            service.addNode(this);
1765 1766 1767 1768
            // 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
1769 1770
        }
        else {
1771
            PubSubPersistenceManager.updateNode(this);
Matt Tucker's avatar
Matt Tucker committed
1772 1773 1774
        }
    }

1775
    public void addAffiliate(NodeAffiliate affiliate) {
Matt Tucker's avatar
Matt Tucker committed
1776 1777 1778
        affiliates.add(affiliate);
    }

1779 1780
    public void addSubscription(NodeSubscription subscription)
    {
Matt Tucker's avatar
Matt Tucker committed
1781
        subscriptionsByID.put(subscription.getID(), subscription);
Matt Tucker's avatar
Matt Tucker committed
1782
        subscriptionsByJID.put(subscription.getJID().toString(), subscription);
Matt Tucker's avatar
Matt Tucker committed
1783 1784 1785 1786 1787 1788 1789 1790 1791
    }

    /**
     * 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
1792
     * @param subscriberJID the JID of the entity that receives event notifications.
Matt Tucker's avatar
Matt Tucker committed
1793 1794 1795 1796 1797
     * @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.
     */
1798
    public NodeSubscription getSubscription(JID subscriberJID) {
Matt Tucker's avatar
Matt Tucker committed
1799
        // Check that node does not support multiple subscriptions
1800
        if (isMultipleSubscriptionsEnabled() && (getSubscriptions(subscriberJID).size() > 1)) {
Matt Tucker's avatar
Matt Tucker committed
1801 1802
            throw new IllegalStateException("Multiple subscriptions is enabled so subscriptions " +
                    "should be retrieved using subID.");
Matt Tucker's avatar
Matt Tucker committed
1803
        }
Matt Tucker's avatar
Matt Tucker committed
1804
        return subscriptionsByJID.get(subscriberJID.toString());
Matt Tucker's avatar
Matt Tucker committed
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
    }

    /**
     * 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
1831
        if (PubSubPersistenceManager.removeNode(this)) {
Matt Tucker's avatar
Matt Tucker committed
1832 1833 1834 1835
            // Remove this node from the parent node (if any)
            if (parent != null) {
                parent.removeChildNode(this);
            }
Matt Tucker's avatar
Matt Tucker committed
1836
            deletingNode();
Matt Tucker's avatar
Matt Tucker committed
1837
            // Broadcast delete notification to subscribers (if enabled)
Matt Tucker's avatar
Matt Tucker committed
1838
            if (isNotifiedOfDelete()) {
Matt Tucker's avatar
Matt Tucker committed
1839 1840 1841 1842 1843 1844
                // 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
1845
                broadcastNodeEvent(message, true);
Matt Tucker's avatar
Matt Tucker committed
1846
            }
1847 1848 1849 1850 1851 1852
            // 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
1853 1854
            // Remove the node from memory
            service.removeNode(getNodeID());
1855
            CacheFactory.doClusterTask(new RemoveNodeTask(this));
Matt Tucker's avatar
Matt Tucker committed
1856 1857 1858
            // Clear collections in memory (clear them after broadcast was sent)
            affiliates.clear();
            subscriptionsByID.clear();
Matt Tucker's avatar
Matt Tucker committed
1859
            subscriptionsByJID.clear();
Matt Tucker's avatar
Matt Tucker committed
1860 1861 1862 1863 1864
            return true;
        }
        return false;
    }

Matt Tucker's avatar
Matt Tucker committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    /**
     * 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) {
1882 1883 1884 1885
    	if (parent == newParent) {
    		return;
    	}
    	
Matt Tucker's avatar
Matt Tucker committed
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
        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) {
1897
            PubSubPersistenceManager.updateNode(this);
Matt Tucker's avatar
Matt Tucker committed
1898 1899 1900
        }
    }

1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    /**
     * 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
1928
    /**
1929
     * Sends the list of affiliations with the node to the owner that sent the IQ
Matt Tucker's avatar
Matt Tucker committed
1930 1931 1932 1933
     * request.
     *
     * @param iqRequest IQ request sent by an owner of the node.
     */
1934
    void sendAffiliations(IQ iqRequest) {
Matt Tucker's avatar
Matt Tucker committed
1935 1936 1937
        IQ reply = IQ.createResultIQ(iqRequest);
        Element childElement = iqRequest.getChildElement().createCopy();
        reply.setChildElement(childElement);
1938
        Element affiliations = childElement.element("affiliations");
Matt Tucker's avatar
Matt Tucker committed
1939

Matt Tucker's avatar
Matt Tucker committed
1940
        for (NodeAffiliate affiliate : affiliates) {
1941 1942
            if (affiliate.getAffiliation() == NodeAffiliate.Affiliation.none) {
                continue;
Matt Tucker's avatar
Matt Tucker committed
1943
            }
1944
            Element entity = affiliations.addElement("affiliation");
1945 1946 1947
            entity.addAttribute("jid", affiliate.getJID().toString());
            entity.addAttribute("affiliation", affiliate.getAffiliation().name());
        }
1948 1949
        // Send reply
        service.send(reply);
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    }

    /**
     * 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);
1962
        Element subscriptions = childElement.element("subscriptions");
1963 1964 1965 1966 1967 1968

        for (NodeAffiliate affiliate : affiliates) {
            for (NodeSubscription subscription : affiliate.getSubscriptions()) {
                if (subscription.isAuthorizationPending()) {
                    continue;
                }
1969
                Element entity = subscriptions.addElement("subscription");
1970 1971 1972 1973 1974
                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
1975 1976
                }
            }
Matt Tucker's avatar
Matt Tucker committed
1977
        }
1978 1979
        // Send reply
        service.send(reply);
Matt Tucker's avatar
Matt Tucker committed
1980 1981
    }

Matt Tucker's avatar
Matt Tucker committed
1982 1983 1984 1985 1986 1987 1988 1989
    /**
     * 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
1990 1991
        Collection<JID> jids = new ArrayList<JID>();
        for (NodeSubscription subscription : subscriptionsByID.values()) {
Matt Tucker's avatar
Matt Tucker committed
1992
            if (includeAll || subscription.canSendNodeEvents()) {
Matt Tucker's avatar
Matt Tucker committed
1993 1994 1995 1996 1997 1998 1999
                jids.add(subscription.getJID());
            }
        }
        // Broadcast packet to subscribers
        service.broadcast(this, message, jids);
    }

Matt Tucker's avatar
Matt Tucker committed
2000 2001 2002 2003 2004 2005 2006 2007 2008
    /**
     * 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
2009 2010 2011 2012 2013 2014 2015 2016
    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");
2017
                header.addAttribute("name", "SubID");
Matt Tucker's avatar
Matt Tucker committed
2018 2019 2020
                header.setText(subID);
            }
        }
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
        
		// Verify that the subscriber JID is currently available to receive notification 
        // messages. This is required because the message router will deliver packets via 
        // the bare JID if a session for the full JID is not available. The "isActiveRoute"
        // condition below will prevent inadvertent delivery of multiple copies of each
        // event notification to the user, possibly multiple times (e.g. route.all-resources). 
        // (Refer to http://issues.igniterealtime.org/browse/OF-14 for more info.)
        //
        // This approach is informed by the following XEP-0060 implementation guidelines:
        //   12.2 "Intended Recipients for Notifications" - only deliver to subscriber JID
        //   12.4 "Not Routing Events to Offline Storage" - no offline storage for notifications
        //
        // Note however that this may be somewhat in conflict with the following:
        //   12.3 "Presence-Based Delivery of Events" - automatically detect user's presence
        //
2036 2037
		if (subscriberJID.getResource() == null ||
			SessionManager.getInstance().getSession(subscriberJID) != null) {
2038
			service.sendNotification(this, notification, subscriberJID);
2039
		}
Matt Tucker's avatar
Matt Tucker committed
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050

        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
2051 2052 2053 2054 2055
     * 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
2056
     *
Matt Tucker's avatar
Matt Tucker committed
2057 2058
     * @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
2059 2060 2061 2062 2063 2064 2065
     * @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
2066 2067
    public void createSubscription(IQ originalIQ, JID owner, JID subscriber,
            boolean authorizationRequired, DataForm options) {
Matt Tucker's avatar
Matt Tucker committed
2068 2069 2070 2071 2072 2073
        // Create a new affiliation if required
        if (getAffiliate(owner) == null) {
            addNoneAffiliation(owner);
        }
        // Figure out subscription status
        NodeSubscription.State subState = NodeSubscription.State.subscribed;
2074
        if (isSubscriptionConfigurationRequired()) {
Matt Tucker's avatar
Matt Tucker committed
2075 2076 2077
            // User has to configure the subscription to make it active
            subState = NodeSubscription.State.unconfigured;
        }
2078 2079 2080 2081
        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
2082 2083
        // 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
2084
        // Create new subscription
2085
        NodeSubscription subscription = new NodeSubscription(this, owner, subscriber, subState, id);
Matt Tucker's avatar
Matt Tucker committed
2086 2087 2088 2089 2090 2091 2092 2093
        // 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
2094
            PubSubPersistenceManager.saveSubscription(this, subscription, true);
Matt Tucker's avatar
Matt Tucker committed
2095
        }
Matt Tucker's avatar
Matt Tucker committed
2096

Matt Tucker's avatar
Matt Tucker committed
2097 2098 2099 2100 2101
        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
2102

Matt Tucker's avatar
Matt Tucker committed
2103 2104 2105 2106 2107
        // If subscription is pending then send notification to node owners asking to approve
        // new subscription
        if (subscription.isAuthorizationPending()) {
            subscription.sendAuthorizationRequest();
        }
2108

2109 2110
        // Update the other members with the new subscription
        CacheFactory.doClusterTask(new NewSubscriptionTask(subscription));
Matt Tucker's avatar
Matt Tucker committed
2111

Matt Tucker's avatar
Matt Tucker committed
2112
        // Send last published item (if node is leaf node and subscription status is ok)
Matt Tucker's avatar
Matt Tucker committed
2113
        if (isSendItemSubscribe() && subscription.isActive()) {
Matt Tucker's avatar
Matt Tucker committed
2114 2115 2116 2117 2118
            PublishedItem lastItem = getLastPublishedItem();
            if (lastItem != null) {
                subscription.sendLastPublishedItem(lastItem);
            }
        }
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128

        // 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
2129 2130 2131 2132 2133 2134 2135 2136
    }

    /**
     * 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.
2137
     * @param sendToCluster True to forward cancel order to cluster peers
Matt Tucker's avatar
Matt Tucker committed
2138
     */
2139
    public void cancelSubscription(NodeSubscription subscription, boolean sendToCluster) {
Matt Tucker's avatar
Matt Tucker committed
2140 2141
        // Remove subscription from memory
        subscriptionsByID.remove(subscription.getID());
Matt Tucker's avatar
Matt Tucker committed
2142
        subscriptionsByJID.remove(subscription.getJID().toString());
Matt Tucker's avatar
Matt Tucker committed
2143 2144 2145 2146 2147 2148 2149 2150 2151
        // 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
2152
            PubSubPersistenceManager.removeSubscription(subscription);
Matt Tucker's avatar
Matt Tucker committed
2153
        }
2154 2155 2156
        if (sendToCluster) {
            CacheFactory.doClusterTask(new CancelSubscriptionTask(subscription));
        }
2157

2158 2159 2160 2161
        // 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
2162 2163
    }

2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    /**
     * 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.
     */
    public void cancelSubscription(NodeSubscription subscription) {
        cancelSubscription(subscription, ClusterManager.isClusteringEnabled());
    }

Matt Tucker's avatar
Matt Tucker committed
2175 2176 2177 2178 2179 2180 2181
    /**
     * 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
2182
     * @param itemID the ID of the item to retrieve.
Matt Tucker's avatar
Matt Tucker committed
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
     * @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
2205
     * @param recentItems number of recent items to retrieve.
Matt Tucker's avatar
Matt Tucker committed
2206 2207 2208 2209 2210 2211 2212
     * @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
2213 2214 2215
    /**
     * 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
2216
     * {@link org.jivesoftware.openfire.pubsub.models.AuthorizeAccess} then the result will
Matt Tucker's avatar
Matt Tucker committed
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
     * 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();
    }

2235
    @Override
2236
    public String toString() {
Matt Tucker's avatar
Matt Tucker committed
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
        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
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
    /**
     * 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();
2269
            CacheFactory.doClusterTask(new ModifySubscriptionTask(subscription));
Matt Tucker's avatar
Matt Tucker committed
2270 2271 2272 2273 2274 2275 2276
        }
        else  {
            // Cancel the subscription to the node
            cancelSubscription(subscription);
        }
    }

2277 2278
    @Override
    public int hashCode() {
2279 2280 2281 2282 2283 2284 2285
		final int prime = 31;
		int result = 1;
		result = prime * result + nodeID.hashCode();
		result = prime * result + service.getServiceID().hashCode();
		return result;
	}

2286
    @Override
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
	public boolean equals(Object obj) {
    	if (obj == this)
    		return true;
    	
    	if (getClass() != obj.getClass())
    		return false;
    	
    	Node compareNode = (Node) obj;
    	
		return (service.getServiceID().equals(compareNode.service.getServiceID()) && nodeID.equals(compareNode.nodeID));
	}
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

    /**
     * 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.
         */
        publisher
    };
Matt Tucker's avatar
Matt Tucker committed
2313
}