IQPEPHandler.java 25.2 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile: $
 * $Revision: $
 * $Date: $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
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.
19 20 21 22
 */

package org.jivesoftware.openfire.pep;

23 24 25
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
26 27 28
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
29

30 31 32 33 34 35 36 37 38 39 40 41 42
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.disco.ServerIdentitiesProvider;
import org.jivesoftware.openfire.disco.UserIdentitiesProvider;
import org.jivesoftware.openfire.disco.UserItemsProvider;
import org.jivesoftware.openfire.event.UserEventDispatcher;
import org.jivesoftware.openfire.event.UserEventListener;
import org.jivesoftware.openfire.handler.IQHandler;
43 44 45 46 47
import org.jivesoftware.openfire.pubsub.CollectionNode;
import org.jivesoftware.openfire.pubsub.LeafNode;
import org.jivesoftware.openfire.pubsub.Node;
import org.jivesoftware.openfire.pubsub.NodeSubscription;
import org.jivesoftware.openfire.pubsub.PubSubEngine;
48 49 50 51 52
import org.jivesoftware.openfire.pubsub.models.AccessModel;
import org.jivesoftware.openfire.roster.Roster;
import org.jivesoftware.openfire.roster.RosterEventDispatcher;
import org.jivesoftware.openfire.roster.RosterEventListener;
import org.jivesoftware.openfire.roster.RosterItem;
53
import org.jivesoftware.openfire.roster.RosterManager;
54
import org.jivesoftware.openfire.session.ClientSession;
55 56 57 58
import org.jivesoftware.openfire.user.PresenceEventDispatcher;
import org.jivesoftware.openfire.user.PresenceEventListener;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserNotFoundException;
59
import org.jivesoftware.util.JiveGlobals;
60 61
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
62 63 64 65 66 67 68 69 70
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;

/**
 * <p>
71 72
 * An {@link IQHandler} used to implement XEP-0163: "Personal Eventing via Pubsub"
 * Version 1.0
73
 * </p>
Gaston Dombiak's avatar
Gaston Dombiak committed
74
 *
75
 * <p>
76 77
 * For each user on the server there is an associated {@link PEPService} interacting
 * with a single {@link PubSubEngine} for managing the user's PEP nodes.
78
 * </p>
Gaston Dombiak's avatar
Gaston Dombiak committed
79
 *
80 81 82
 * <p>
 * An IQHandler can only handle one namespace in its IQHandlerInfo. However, PEP
 * related packets are seen having a variety of different namespaces. Thus,
83 84
 * classes like {@link IQPEPOwnerHandler} are used to forward packets having these other
 * namespaces to {@link IQPEPHandler#handleIQ(IQ)}.
85
 * <p>
Gaston Dombiak's avatar
Gaston Dombiak committed
86
 *
87 88 89 90 91 92 93
 * <p>
 * This handler is used for the following namespaces:
 * <ul>
 * <li><i>http://jabber.org/protocol/pubsub</i></li>
 * <li><i>http://jabber.org/protocol/pubsub#owner</i></li>
 * </ul>
 * </p>
Gaston Dombiak's avatar
Gaston Dombiak committed
94
 *
95
 * @author Armando Jagucki
96
 * @author Guus der Kinderen, guus.der.kinderen@gmail.com
97 98
 */
public class IQPEPHandler extends IQHandler implements ServerIdentitiesProvider, ServerFeaturesProvider,
99
        UserIdentitiesProvider, UserItemsProvider, PresenceEventListener,
100 101
        RosterEventListener, UserEventListener {

102 103
	private static final Logger Log = LoggerFactory.getLogger(IQPEPHandler.class);

104
    /**
105
     * Metadata that relates to the IQ processing capabilities of this specific {@link IQHandler}.
106
     */
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    private final IQHandlerInfo info;

    private PEPServiceManager pepServiceManager = null;

	/**
	 * The managed thread pool that will do most of the processing. The amount
	 * of worker threads in this pool should be kept low to avoid resource
	 * contention.
	 */
    // There's room for future improvement here. If anywhere in the future,
	// Openfire allows implementations to use dedicated resource pools, we can
	// significantly increase the number of worker threads in this executor. The
	// bottleneck for this particular executor is the database pool. During
	// startup, PEP queries the database a lot, which causes all of the
	// connections in the generic database pool to be used up by this PEP
	// implementation. This can cause problems in other parts of Openfire that
	// depend on database access (ideally, these should get dedicated resource
	// pools too).
    private ExecutorService executor = null;
126

127 128 129
    /**
     * Constructs a new {@link IQPEPHandler} instance.
     */
130 131 132 133 134
    public IQPEPHandler() {
        super("Personal Eventing Handler");
        info = new IQHandlerInfo("pubsub", "http://jabber.org/protocol/pubsub");
    }

135 136 137 138
    /* 
     * (non-Javadoc)
     * @see org.jivesoftware.openfire.handler.IQHandler#initialize(org.jivesoftware.openfire.XMPPServer)
     */
139 140 141 142
    @Override
    public void initialize(XMPPServer server) {
        super.initialize(server);

143 144 145
        pepServiceManager = new PEPServiceManager();
    }

146 147 148 149 150
	public PEPServiceManager getServiceManager()
	{
		return pepServiceManager;
	}

151 152 153 154 155
    /*
	 * (non-Javadoc)
	 * 
	 * @see org.jivesoftware.openfire.container.BasicModule#destroy()
	 */
156 157
    @Override
	public void destroy() {
158 159 160 161 162 163 164 165
        super.destroy();
    }

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jivesoftware.openfire.container.BasicModule#start()
	 */
166
	@Override
167 168 169 170 171 172 173 174 175
	public void start() {
		super.start();
		
		// start the service manager
		pepServiceManager.start();
		
        // start a new executor service
        startExecutor();
        
176 177 178 179 180 181
        // Listen to presence events to manage PEP auto-subscriptions.
        PresenceEventDispatcher.addListener(this);
        // Listen to roster events for PEP subscription cancelling on contact deletion.
        RosterEventDispatcher.addListener(this);
        // Listen to user events in order to destroy a PEP service when a user is deleted.
        UserEventDispatcher.addListener(this);
182 183 184 185 186 187 188
	}
	
    /*
	 * (non-Javadoc)
	 * 
	 * @see org.jivesoftware.openfire.container.BasicModule#stop()
	 */
189 190
    @Override
	public void stop() {
191
        super.stop();
192
        
193 194 195
        // Remove listeners
        PresenceEventDispatcher.removeListener(this);
        RosterEventDispatcher.removeListener(this);
196 197 198 199 200 201 202
        UserEventDispatcher.removeListener(this);        
        
        // stop the executor service
        stopExecutor();
        
        // stop the pepservicemananger
        pepServiceManager.stop();
203
    }
204 205 206 207 208 209 210 211 212
    
    /**
	 * Starts a new thread pool, unless an existing one is still running.
	 */
	private void startExecutor() {
		if (executor == null || executor.isShutdown()) {
			// keep the amount of workers low! See comment that goes with the
			// field named 'executor'.
			Log.debug("Starting executor service...");
213
			executor = Executors.newScheduledThreadPool(2);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
		}
	}
    
	/**
	 * Shuts down the executor by dropping all tasks from the queue. This method
	 * will allow the executor to finish operations on running tasks for a
	 * period of two seconds. After that, tasks are forcefully stopped.
	 * <p>
	 * The order in which the various shutdown routines of the executor are
	 * called, is:
	 * <ol>
	 * <li>{@link ExecutorService#shutdown()}</li>
	 * <li>{@link ExecutorService#awaitTermination(long, TimeUnit)} (two
	 * seconds)</li>
	 * <li>{@link ExecutorService#shutdownNow()}</li>
	 * </ol>
	 */
	private void stopExecutor() {
		Log.debug("Stopping executor service...");
		/*
		 * This method gets called as part of the Component#shutdown() routine.
		 * If that method gets called, the component has already been removed
		 * from the routing tables. We don't need to worry about new packets to
		 * arrive - there won't be any.
		 */
		executor.shutdown();
		try {
			if (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
				Log.debug("Forcing a shutdown for the executor service (after a two-second timeout has elapsed...");
				executor.shutdownNow();
				// Note that if any IQ request stanzas had been scheduled, they
				// MUST be responded to with an error here. A list of tasks that
				// have never been commenced by the executor is returned by the
				// #shutdownNow() method of the ExecutorService.
			}
		} catch (InterruptedException e) {
			// ignore, as we're shutting down anyway.
		}
	}

    /*
	 * (non-Javadoc)
	 * 
	 * @see org.jivesoftware.openfire.handler.IQHandler#getInfo()
	 */
259 260 261 262 263 264
    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    /**
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
     * Implements ServerIdentitiesProvider and UserIdentitiesProvider, adding
     * the PEP identity to the respective disco#info results.
     */
    public Iterator<Element> getIdentities() {
        ArrayList<Element> identities = new ArrayList<Element>();
        Element identity = DocumentHelper.createElement("identity");
        identity.addAttribute("category", "pubsub");
        identity.addAttribute("type", "pep");
        identities.add(identity);
        return identities.iterator();
    }

    /**
     * Implements ServerFeaturesProvider to include all supported XEP-0060 features
     * in the server's disco#info result (as per section 4 of XEP-0163).
     */
    public Iterator<String> getFeatures() {
        return XMPPServer.getInstance().getPubSubModule().getFeatures(null, null, null);
    }


    /**
     * Returns true if the PEP service is enabled in the server.
Gaston Dombiak's avatar
Gaston Dombiak committed
288
     *
289
     * @return true if the PEP service is enabled in the server.
290
     */
291 292 293
    // TODO: listen for property changes to stop/start this module.
    public boolean isEnabled() {
        return JiveGlobals.getBooleanProperty("xmpp.pep.enabled", true);
294 295
    }

296 297 298 299 300 301 302 303 304 305 306
    // *****************************************************************
    // *** Generic module management ends here. From this point on   ***
    // *** more specific PEP related implementation after this point ***
    // *****************************************************************
    
    /*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.jivesoftware.openfire.handler.IQHandler#handleIQ(org.xmpp.packet.IQ)
	 */
307 308
    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
309 310 311 312 313 314 315 316
        // Do nothing if server is not enabled
        if (!isEnabled()) {
            IQ reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.service_unavailable);
            return reply;
        }

317
        final JID senderJID = packet.getFrom();
318
        if (packet.getTo() == null) {
319
        	// packet addressed to service itself (not to a node/user)
320 321 322 323
            final String jidFrom = senderJID.toBareJID();
            packet = packet.createCopy();
            packet.setTo(jidFrom);

324
            if (packet.getType() == IQ.Type.set) {
325
                PEPService pepService = pepServiceManager.getPEPService(jidFrom);
326

327 328
                // If no service exists yet for jidFrom, create one.
                if (pepService == null) {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
                	try {
                		pepService = pepServiceManager.create(senderJID);                		
                	} catch (IllegalArgumentException ex) {
            			final IQ reply = IQ.createResultIQ(packet);
            			reply.setChildElement(packet.getChildElement().createCopy());
            			reply.setError(PacketError.Condition.not_allowed);
            			return reply;
                	}

            		// Probe presences
            		pepServiceManager.start(pepService);

            		// Those who already have presence subscriptions to jidFrom
					// will now automatically be subscribed to this new
					// PEPService.
					try {
						final RosterManager rm = XMPPServer.getInstance()
								.getRosterManager();
						final Roster roster = rm.getRoster(senderJID.getNode());
						for (final RosterItem item : roster.getRosterItems()) {
							if (item.getSubStatus() == RosterItem.SUB_BOTH
									|| item.getSubStatus() == RosterItem.SUB_FROM) {
								createSubscriptionToPEPService(pepService, item
										.getJid(), senderJID);
							}
						}
					} catch (UserNotFoundException e) {
						// Do nothing
					}
358
                }
359

360
                // If publishing a node, and the node doesn't exist, create it.
361 362
                final Element childElement = packet.getChildElement();
                final Element publishElement = childElement.element("publish");
363
                if (publishElement != null) {
364
                    final String nodeID = publishElement.attributeValue("node");
365

366 367 368 369 370 371 372 373
                    // Do not allow User Avatar nodes to be created.
                    // TODO: Implement XEP-0084
                    if (nodeID.startsWith("http://www.xmpp.org/extensions/xep-0084.html")) {
                        IQ reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.feature_not_implemented);
                        return reply;
                    }
374

375 376
                    if (pepService.getNode(nodeID) == null) {
                        // Create the node
377 378
                        final JID creator = new JID(jidFrom);
                        final LeafNode newNode = new LeafNode(pepService, pepService.getRootCollectionNode(), nodeID, creator);
379 380 381
                        newNode.addOwner(creator);
                        newNode.saveToDB();
                    }
382
                }
383

384
                // Process with PubSub as usual.
385
                pepServiceManager.process(pepService, packet);
386 387
            } else if (packet.getType() == IQ.Type.get) {
                final PEPService pepService = pepServiceManager.getPEPService(jidFrom);            	
388
                
389
                if (pepService != null) {
390
                	pepServiceManager.process(pepService, packet);
391 392 393 394 395 396
                } else {
                    // Process with PubSub using a dummyService. In the case where an IQ packet is sent to
                    // a user who does not have a PEP service, we wish to utilize the error reporting flow
                    // already present in the PubSubEngine. This gives the illusion that every user has a
                    // PEP service, as required by the specification.
                    PEPService dummyService = new PEPService(XMPPServer.getInstance(), senderJID.toBareJID());
397
                    pepServiceManager.process(dummyService, packet);
398
                }
399 400 401
            }
        }
        else if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
402 403 404
        	// packet was addressed to a node.
        	
            final String jidTo = packet.getTo().toBareJID();
405

406
            final PEPService pepService = pepServiceManager.getPEPService(jidTo);
407 408

            if (pepService != null) {
409 410
            	pepServiceManager.process(pepService, packet);
            } else {
411 412
                // Process with PubSub using a dummyService. In the case where an IQ packet is sent to
                // a user who does not have a PEP service, we wish to utilize the error reporting flow
413 414
                // already present in the PubSubEngine. This gives the illusion that every user has a
                // PEP service, as required by the specification.
415
                PEPService dummyService = new PEPService(XMPPServer.getInstance(), senderJID.toBareJID());
416
                pepServiceManager.process(dummyService, packet);
417
            }
418
        } else {
419 420 421 422
            // Ignore IQ packets of type 'error' or 'result'.
            return null;
        }

423
        // Other error flows were handled in pubSubEngine.process(...)
424 425 426 427 428
        return null;
    }

    /**
     * Generates and processes an IQ stanza that subscribes to a PEP service.
Gaston Dombiak's avatar
Gaston Dombiak committed
429
     *
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
     * @param pepService the PEP service of the owner.
     * @param subscriber the JID of the entity that is subscribing to the PEP service.
     * @param owner      the JID of the owner of the PEP service.
     */
    private void createSubscriptionToPEPService(PEPService pepService, JID subscriber, JID owner) {
        // If `owner` has a PEP service, generate and process a pubsub subscription packet
        // that is equivalent to: (where 'from' field is JID of subscriber and 'to' field is JID of owner)
        //
        //        <iq type='set'
        //            from='nurse@capulet.com/chamber'
        //            to='juliet@capulet.com
        //            id='collsub'>
        //          <pubsub xmlns='http://jabber.org/protocol/pubsub'>
        //            <subscribe jid='nurse@capulet.com'/>
        //            <options>
        //              <x xmlns='jabber:x:data'>
        //                <field var='FORM_TYPE' type='hidden'>
        //                  <value>http://jabber.org/protocol/pubsub#subscribe_options</value>
        //                </field>
        //                <field var='pubsub#subscription_type'>
        //                  <value>items</value>
        //                </field>
        //                <field var='pubsub#subscription_depth'>
        //                  <value>all</value>
        //                </field>
        //              </x>
        //           </options>
        //         </pubsub>
        //        </iq>

        IQ subscriptionPacket = new IQ(IQ.Type.set);
        subscriptionPacket.setFrom(subscriber);
        subscriptionPacket.setTo(owner.toBareJID());

        Element pubsubElement = subscriptionPacket.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");

        Element subscribeElement = pubsubElement.addElement("subscribe");
        subscribeElement.addAttribute("jid", subscriber.toBareJID());

        Element optionsElement = pubsubElement.addElement("options");
        Element xElement = optionsElement.addElement(QName.get("x", "jabber:x:data"));

        DataForm dataForm = new DataForm(xElement);

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

        formField = dataForm.addField();
        formField.setVariable("pubsub#subscription_type");
        formField.addValue("items");

        formField = dataForm.addField();
        formField.setVariable("pubsub#subscription_depth");
        formField.addValue("all");

487
        pepServiceManager.process(pepService, subscriptionPacket);
488 489 490 491
    }

    /**
     * Cancels a subscription to a PEPService's root collection node.
Gaston Dombiak's avatar
Gaston Dombiak committed
492
     *
493 494 495 496 497
     * @param unsubscriber the JID of the subscriber whose subscription is being canceled.
     * @param serviceOwner the JID of the owner of the PEP service for which the subscription is being canceled.
     */
    private void cancelSubscriptionToPEPService(JID unsubscriber, JID serviceOwner) {
        // Retrieve recipientJID's PEP service, if it exists.
498
        PEPService pepService = pepServiceManager.getPEPService(serviceOwner.toBareJID());
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        if (pepService == null) {
            return;
        }

        // Cancel unsubscriberJID's subscription to recipientJID's PEP service, if it exists.
        CollectionNode rootNode = pepService.getRootCollectionNode();
        NodeSubscription nodeSubscription = rootNode.getSubscription(unsubscriber);
        if (nodeSubscription != null) {
            rootNode.cancelSubscription(nodeSubscription);
        }
    }

    /**
     * Implements UserItemsProvider, adding PEP related items to a disco#items
     * result.
     */
    public Iterator<Element> getUserItems(String name, JID senderJID) {
        ArrayList<Element> items = new ArrayList<Element>();

518
        String recipientJID = XMPPServer.getInstance().createJID(name, null, true).toBareJID();
519
        PEPService pepService = pepServiceManager.getPEPService(recipientJID);
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

        if (pepService != null) {
            CollectionNode rootNode = pepService.getRootCollectionNode();

            Element defaultItem = DocumentHelper.createElement("item");
            defaultItem.addAttribute("jid", recipientJID);

            for (Node node : pepService.getNodes()) {
                // Do not include the root node as an item element.
                if (node == rootNode) {
                    continue;
                }

                AccessModel accessModel = node.getAccessModel();
                if (accessModel.canAccessItems(node, senderJID, new JID(recipientJID))) {
                    Element item = defaultItem.createCopy();
                    item.addAttribute("node", node.getNodeID());
                    items.add(item);
                }
            }
        }

        return items.iterator();
    }

    public void subscribedToPresence(JID subscriberJID, JID authorizerJID) {
546
        final PEPService pepService = pepServiceManager.getPEPService(authorizerJID.toBareJID());
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
        if (pepService != null) {
            createSubscriptionToPEPService(pepService, subscriberJID, authorizerJID);

            // Delete any leaf node subscriptions the subscriber may have already
            // had (since a subscription to the PEP service, and thus its leaf PEP
            // nodes, would be duplicating publish notifications from previous leaf
            // node subscriptions).
            CollectionNode rootNode = pepService.getRootCollectionNode();
            for (Node node : pepService.getNodes()) {
                if (rootNode.isChildNode(node)) {
                    for (NodeSubscription subscription : node.getSubscriptions(subscriberJID)) {
                        node.cancelSubscription(subscription);
                    }
                }
            }

            pepService.sendLastPublishedItems(subscriberJID);
        }
    }

    public void unsubscribedToPresence(JID unsubscriberJID, JID recipientJID) {
        cancelSubscriptionToPEPService(unsubscriberJID, recipientJID);
    }

    public void availableSession(ClientSession session, Presence presence) {
572 573 574 575
        // Do nothing if server is not enabled
        if (!isEnabled()) {
            return;
        }
576
        JID newlyAvailableJID = presence.getFrom();
Gaston Dombiak's avatar
Gaston Dombiak committed
577

578 579 580
        if (newlyAvailableJID == null) {
            return;
        }
581 582 583
        
        final GetNotificationsOnInitialPresence task = new GetNotificationsOnInitialPresence(newlyAvailableJID);
        executor.submit(task);
584 585 586 587 588 589 590 591 592 593
    }

    public void contactDeleted(Roster roster, RosterItem item) {
        JID rosterOwner = XMPPServer.getInstance().createJID(roster.getUsername(), null);
        JID deletedContact = item.getJid();

        cancelSubscriptionToPEPService(deletedContact, rosterOwner);
    }

    public void userDeleting(User user, Map<String, Object> params) {
594 595
        final JID bareJID = XMPPServer.getInstance().createJID(user.getUsername(), null);
        final PEPService pepService = pepServiceManager.getPEPService(bareJID.toString());
596

597 598 599 600 601
        if (pepService == null) {
            return;
        }

        // Remove the user's PEP service, finally.
602
        pepServiceManager.remove(bareJID);
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    }

    /**
     *  The following functions are unimplemented required interface methods.
     */
    public void unavailableSession(ClientSession session, Presence presence) {
        // Do nothing
    }

    public void presenceChanged(ClientSession session, Presence presence) {
        // Do nothing
    }

    public boolean addingContact(Roster roster, RosterItem item, boolean persistent) {
        // Do nothing
        return true;
    }

    public void contactAdded(Roster roster, RosterItem item) {
        // Do nothing
    }

    public void contactUpdated(Roster roster, RosterItem item) {
        // Do nothing
    }

    public void rosterLoaded(Roster roster) {
        // Do nothing
    }

    public void userCreated(User user, Map<String, Object> params) {
        // Do nothing
    }

    public void userModified(User user, Map<String, Object> params) {
        // Do nothing
    }

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    private class GetNotificationsOnInitialPresence implements Runnable {
    	
    	private final JID availableSessionJID;
    	public GetNotificationsOnInitialPresence(final JID availableSessionJID) {
    		this.availableSessionJID = availableSessionJID;
    	}
    	
        public void run() {
            // Send the last published items for the contacts on availableSessionJID's roster.
            try {
                final XMPPServer server = XMPPServer.getInstance();
                final Roster roster = server.getRosterManager().getRoster(availableSessionJID.getNode());
                for (final RosterItem item : roster.getRosterItems()) {
                    if (server.isLocal(item.getJid()) && (item.getSubStatus() == RosterItem.SUB_BOTH ||
                            item.getSubStatus() == RosterItem.SUB_TO)) {
                        PEPService pepService = pepServiceManager.getPEPService(item.getJid().toBareJID());
                        if (pepService != null) {
                            pepService.sendLastPublishedItems(availableSessionJID);
                        }
                    }
                }
            }
            catch (UserNotFoundException e) {
                // Do nothing
            }
        }    	
    }
668
}