001/**
002 *
003 * Copyright 2018 Paul Schaub
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.reference;
018
019import java.util.Map;
020import java.util.WeakHashMap;
021
022import org.jivesoftware.smack.ConnectionCreationListener;
023import org.jivesoftware.smack.Manager;
024import org.jivesoftware.smack.XMPPConnection;
025import org.jivesoftware.smack.XMPPConnectionRegistry;
026
027import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
028
029public final class ReferenceManager extends Manager {
030
031    public static final String NAMESPACE = "urn:xmpp:reference:0";
032
033    private static final Map<XMPPConnection, ReferenceManager> INSTANCES = new WeakHashMap<>();
034
035    static {
036        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
037            @Override
038            public void connectionCreated(XMPPConnection connection) {
039                getInstanceFor(connection);
040            }
041        });
042    }
043
044    private ReferenceManager(XMPPConnection connection) {
045        super(connection);
046        ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE);
047    }
048
049    /**
050     * Return a new instance of the ReferenceManager for the given connection.
051     *
052     * @param connection xmpp connection
053     * @return reference manager instance
054     */
055    public static synchronized ReferenceManager getInstanceFor(XMPPConnection connection) {
056        ReferenceManager manager = INSTANCES.get(connection);
057        if (manager == null) {
058            manager = new ReferenceManager(connection);
059            INSTANCES.put(connection, manager);
060        }
061        return manager;
062    }
063}