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;
026import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
027
028public final class ReferenceManager extends Manager {
029
030    public static final String NAMESPACE = "urn:xmpp:reference:0";
031
032    private static final Map<XMPPConnection, ReferenceManager> INSTANCES = new WeakHashMap<>();
033
034    static {
035        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
036            @Override
037            public void connectionCreated(XMPPConnection connection) {
038                getInstanceFor(connection);
039            }
040        });
041    }
042
043    private ReferenceManager(XMPPConnection connection) {
044        super(connection);
045        ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE);
046    }
047
048    /**
049     * Return a new instance of the ReferenceManager for the given connection.
050     *
051     * @param connection xmpp connection
052     * @return reference manager instance
053     */
054    public static synchronized ReferenceManager getInstanceFor(XMPPConnection connection) {
055        ReferenceManager manager = INSTANCES.get(connection);
056        if (manager == null) {
057            manager = new ReferenceManager(connection);
058            INSTANCES.put(connection, manager);
059        }
060        return manager;
061    }
062}