001/**
002 *
003 * Copyright 2018 Florian Schmaus
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.smack.compression;
018
019import java.util.ArrayList;
020import java.util.Collections;
021import java.util.Iterator;
022import java.util.List;
023
024import org.jivesoftware.smack.compress.packet.Compress;
025
026public class XmppCompressionManager {
027
028    private static final List<XmppCompressionFactory> xmppCompressionFactories = new ArrayList<>(4);
029
030    public static XmppCompressionFactory registerXmppCompressionFactory(XmppCompressionFactory xmppCompressionFactory) {
031        final String method = xmppCompressionFactory.getCompressionMethod();
032        XmppCompressionFactory previousFactory = null;
033
034        synchronized (xmppCompressionFactories) {
035            for (Iterator<XmppCompressionFactory> it = xmppCompressionFactories.iterator(); it.hasNext(); ) {
036                XmppCompressionFactory factory = it.next();
037                if (factory.getCompressionMethod().equals(method)) {
038                    it.remove();
039                    previousFactory = factory;
040                    break;
041                }
042            }
043
044            xmppCompressionFactories.add(xmppCompressionFactory);
045
046            Collections.sort(xmppCompressionFactories);
047        }
048
049        return previousFactory;
050    }
051
052    public static XmppCompressionFactory getBestFactory(Compress.Feature compressFeature) {
053        List<String> announcedMethods = compressFeature.getMethods();
054
055        synchronized (xmppCompressionFactories) {
056            for (XmppCompressionFactory factory : xmppCompressionFactories) {
057                if (announcedMethods.contains(factory.getCompressionMethod())) {
058                    return factory;
059                }
060            }
061        }
062
063        return null;
064    }
065}