IQPEPHandler.java 25.7 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
import java.util.ArrayList;
24
import java.util.Collections;
25 26
import java.util.Iterator;
import java.util.Map;
27 28 29
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
30

31 32 33 34 35 36 37 38 39 40 41 42 43
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;
44 45 46 47 48
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;
49 50 51 52 53
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;
54
import org.jivesoftware.openfire.roster.RosterManager;
55
import org.jivesoftware.openfire.session.ClientSession;
56 57 58 59
import org.jivesoftware.openfire.user.PresenceEventDispatcher;
import org.jivesoftware.openfire.user.PresenceEventListener;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserNotFoundException;
60
import org.jivesoftware.util.JiveGlobals;
61 62
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
63 64 65 66 67 68 69 70 71
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>
72 73
 * An {@link IQHandler} used to implement XEP-0163: "Personal Eventing via Pubsub"
 * Version 1.0
74
 * </p>
Gaston Dombiak's avatar
Gaston Dombiak committed
75
 *
76
 * <p>
77 78
 * 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.
79
 * </p>
Gaston Dombiak's avatar
Gaston Dombiak committed
80
 *
81 82 83
 * <p>
 * An IQHandler can only handle one namespace in its IQHandlerInfo. However, PEP
 * related packets are seen having a variety of different namespaces. Thus,
84 85
 * classes like {@link IQPEPOwnerHandler} are used to forward packets having these other
 * namespaces to {@link IQPEPHandler#handleIQ(IQ)}.
86
 * <p>
Gaston Dombiak's avatar
Gaston Dombiak committed
87
 *
88
 * <p>
89
 * This handler is used for the following namespaces:</p>
90 91 92 93
 * <ul>
 * <li><i>http://jabber.org/protocol/pubsub</i></li>
 * <li><i>http://jabber.org/protocol/pubsub#owner</i></li>
 * </ul>
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
     * Implements ServerIdentitiesProvider and UserIdentitiesProvider, adding
     * the PEP identity to the respective disco#info results.
     */
268
    @Override
269 270 271 272
    public Iterator<Element> getIdentities() {
        Element identity = DocumentHelper.createElement("identity");
        identity.addAttribute("category", "pubsub");
        identity.addAttribute("type", "pep");
273
        return Collections.singleton(identity).iterator();
274 275 276 277 278 279
    }

    /**
     * Implements ServerFeaturesProvider to include all supported XEP-0060 features
     * in the server's disco#info result (as per section 4 of XEP-0163).
     */
280
    @Override
281
    public Iterator<String> getFeatures() {
282
        Iterator<String> it = XMPPServer.getInstance().getPubSubModule().getFeatures(null, null, null);
283
        ArrayList<String> features = new ArrayList<>();
284 285 286 287 288 289
        while (it.hasNext()) {
            features.add(it.next());
        }
        // Auto Creation of nodes is supported in PEP
        features.add("http://jabber.org/protocol/pubsub#auto-create");
        return features.iterator();
290 291 292 293 294
    }


    /**
     * Returns true if the PEP service is enabled in the server.
Gaston Dombiak's avatar
Gaston Dombiak committed
295
     *
296
     * @return true if the PEP service is enabled in the server.
297
     */
298 299 300
    // TODO: listen for property changes to stop/start this module.
    public boolean isEnabled() {
        return JiveGlobals.getBooleanProperty("xmpp.pep.enabled", true);
301 302
    }

303 304 305 306 307 308 309 310 311 312 313
    // *****************************************************************
    // *** 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)
	 */
314 315
    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
316 317 318 319 320 321 322 323
        // 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;
        }

324
        final JID senderJID = packet.getFrom();
325
        if (packet.getTo() == null) {
326
        	// packet addressed to service itself (not to a node/user)
327 328 329 330
            final String jidFrom = senderJID.toBareJID();
            packet = packet.createCopy();
            packet.setTo(jidFrom);

331
            if (packet.getType() == IQ.Type.set) {
332
                PEPService pepService = pepServiceManager.getPEPService(jidFrom);
333

334 335
                // If no service exists yet for jidFrom, create one.
                if (pepService == null) {
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
                	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
					}
365
                }
366

367
                // If publishing a node, and the node doesn't exist, create it.
368 369
                final Element childElement = packet.getChildElement();
                final Element publishElement = childElement.element("publish");
370
                if (publishElement != null) {
371
                    final String nodeID = publishElement.attributeValue("node");
372

373 374 375 376 377 378 379 380
                    // 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;
                    }
381

382 383
                    if (pepService.getNode(nodeID) == null) {
                        // Create the node
384 385
                        final JID creator = new JID(jidFrom);
                        final LeafNode newNode = new LeafNode(pepService, pepService.getRootCollectionNode(), nodeID, creator);
386 387 388
                        newNode.addOwner(creator);
                        newNode.saveToDB();
                    }
389
                }
390

391
                // Process with PubSub as usual.
392
                pepServiceManager.process(pepService, packet);
393 394
            } else if (packet.getType() == IQ.Type.get) {
                final PEPService pepService = pepServiceManager.getPEPService(jidFrom);            	
395
                
396
                if (pepService != null) {
397
                	pepServiceManager.process(pepService, packet);
398 399 400 401 402 403
                } 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());
404
                    pepServiceManager.process(dummyService, packet);
405
                }
406 407 408
            }
        }
        else if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
409 410 411
        	// packet was addressed to a node.
        	
            final String jidTo = packet.getTo().toBareJID();
412

413
            final PEPService pepService = pepServiceManager.getPEPService(jidTo);
414 415

            if (pepService != null) {
416 417
            	pepServiceManager.process(pepService, packet);
            } else {
418 419
                // 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
420 421
                // already present in the PubSubEngine. This gives the illusion that every user has a
                // PEP service, as required by the specification.
422
                PEPService dummyService = new PEPService(XMPPServer.getInstance(), senderJID.toBareJID());
423
                pepServiceManager.process(dummyService, packet);
424
            }
425
        } else {
426 427 428 429
            // Ignore IQ packets of type 'error' or 'result'.
            return null;
        }

430
        // Other error flows were handled in pubSubEngine.process(...)
431 432 433 434 435
        return null;
    }

    /**
     * Generates and processes an IQ stanza that subscribes to a PEP service.
Gaston Dombiak's avatar
Gaston Dombiak committed
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 487 488 489 490 491 492 493
     * @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");

494
        pepServiceManager.process(pepService, subscriptionPacket);
495 496 497 498
    }

    /**
     * Cancels a subscription to a PEPService's root collection node.
Gaston Dombiak's avatar
Gaston Dombiak committed
499
     *
500 501 502 503 504
     * @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.
505
        PEPService pepService = pepServiceManager.getPEPService(serviceOwner.toBareJID());
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        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.
     */
522
    @Override
523
    public Iterator<Element> getUserItems(String name, JID senderJID) {
524
        ArrayList<Element> items = new ArrayList<>();
525

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

        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();
    }

553
    @Override
554
    public void subscribedToPresence(JID subscriberJID, JID authorizerJID) {
555
        final PEPService pepService = pepServiceManager.getPEPService(authorizerJID.toBareJID());
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
        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);
        }
    }

576
    @Override
577 578 579 580
    public void unsubscribedToPresence(JID unsubscriberJID, JID recipientJID) {
        cancelSubscriptionToPEPService(unsubscriberJID, recipientJID);
    }

581
    @Override
582
    public void availableSession(ClientSession session, Presence presence) {
583 584 585 586
        // Do nothing if server is not enabled
        if (!isEnabled()) {
            return;
        }
587
        JID newlyAvailableJID = presence.getFrom();
Gaston Dombiak's avatar
Gaston Dombiak committed
588

589 590 591
        if (newlyAvailableJID == null) {
            return;
        }
592 593 594
        
        final GetNotificationsOnInitialPresence task = new GetNotificationsOnInitialPresence(newlyAvailableJID);
        executor.submit(task);
595 596
    }

597
    @Override
598 599 600 601 602 603 604
    public void contactDeleted(Roster roster, RosterItem item) {
        JID rosterOwner = XMPPServer.getInstance().createJID(roster.getUsername(), null);
        JID deletedContact = item.getJid();

        cancelSubscriptionToPEPService(deletedContact, rosterOwner);
    }

605
    @Override
606
    public void userDeleting(User user, Map<String, Object> params) {
607 608
        final JID bareJID = XMPPServer.getInstance().createJID(user.getUsername(), null);
        final PEPService pepService = pepServiceManager.getPEPService(bareJID.toString());
609

610 611 612 613 614
        if (pepService == null) {
            return;
        }

        // Remove the user's PEP service, finally.
615
        pepServiceManager.remove(bareJID);
616 617 618 619 620
    }

    /**
     *  The following functions are unimplemented required interface methods.
     */
621
    @Override
622 623 624 625
    public void unavailableSession(ClientSession session, Presence presence) {
        // Do nothing
    }

626
    @Override
627 628 629 630
    public void presenceChanged(ClientSession session, Presence presence) {
        // Do nothing
    }

631
    @Override
632 633 634 635 636
    public boolean addingContact(Roster roster, RosterItem item, boolean persistent) {
        // Do nothing
        return true;
    }

637
    @Override
638 639 640 641
    public void contactAdded(Roster roster, RosterItem item) {
        // Do nothing
    }

642
    @Override
643 644 645 646
    public void contactUpdated(Roster roster, RosterItem item) {
        // Do nothing
    }

647
    @Override
648 649 650 651
    public void rosterLoaded(Roster roster) {
        // Do nothing
    }

652
    @Override
653 654 655 656
    public void userCreated(User user, Map<String, Object> params) {
        // Do nothing
    }

657
    @Override
658 659 660 661
    public void userModified(User user, Map<String, Object> params) {
        // Do nothing
    }

662 663 664 665 666 667 668
    private class GetNotificationsOnInitialPresence implements Runnable {
    	
    	private final JID availableSessionJID;
    	public GetNotificationsOnInitialPresence(final JID availableSessionJID) {
    		this.availableSessionJID = availableSessionJID;
    	}
    	
669
        @Override
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        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
            }
        }    	
    }
690
}