package org.intellimate.izou.sdk.properties;

import org.intellimate.izou.sdk.Context;
import org.intellimate.izou.sdk.util.AddOnModule;
import org.intellimate.izou.system.file.ReloadableFile;
import ro.fortsoft.pf4j.PluginWrapper;

import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.function.Consumer;

/**
 * Manages property files, and is also a {@link ReloadableFile}
 *
 * <p>
 *     Unlike most manager classes in Izou, the PropertiesAssistant is included in every {@code AddOn} instance.
 * </p>
 */
public class PropertiesAssistant extends AddOnModule implements ReloadableFile {
    private String propertiesPath;
    private String defaultPropertiesPath;
    private Properties properties;
    private final EventPropertiesAssistant assistant;
    private File propertiesFile;
    private List<WeakReference<Consumer<PropertiesAssistant>>> listeners =
            Collections.synchronizedList(new ArrayList<>());

    public PropertiesAssistant(Context context, String addOnID) {
        super(context, addOnID + ".PropertiesAssistant");
        this.properties = new Properties();
        this.propertiesPath = null;
        this.defaultPropertiesPath = null;
        this.assistant = new EventPropertiesAssistant(context, addOnID + ".EventPropertiesAssistant");
        PluginWrapper plugin = getContext().getAddOns().getAddOn().getPlugin();
        if (plugin != null) {
            this.defaultPropertiesPath = getContext().getFiles().getLibLocation() +
                    getContext().getAddOns().getAddOn().getPlugin().getPluginPath() + File.separator + "classes"
                    + File.separator + "default_properties.txt";
        } else {
            //if we are debugging
            this.defaultPropertiesPath = getContext().getAddOns().getAddOn().getClass().getClassLoader().
                    getResource("default_properties.txt").getFile();
        }
        initProperties();
        try {
            getContext().getFiles().registerFileDir(propertiesFile.getParentFile().toPath(),
                    propertiesFile.getName(), this);
        } catch (IOException e) {
            error("Error registering reloadablefile with file manager", e);
        }
    }

    /**
     * Gets the EventPropertiesAssistant
     *
     * @return the EventPropertiesAssistant
     */
    public EventPropertiesAssistant getEventPropertiesAssistant() {
        return assistant;
    }

    /**
     * Searches for the property with the specified key in this property list.
     *
     * If the key is not found in this property list, the default property list, and its defaults, recursively, are
     * then checked. The method returns null if the property is not found.
     *
     * @param key the property key.
     * @return the value in this property list with the specified key value.
     */
    public String getProperty(String key) {
        return properties.getProperty(key);
    }

    /**
     * Gets the properties object
     *
     * @return the properties object
     */
    public Properties getProperties() {
        return properties;
    }

    /**
     * Calls the HashTable method put.
     *
     * Provided for parallelism with the getProperty method. Enforces use of strings for
     *     * property keys and values. The value returned is the result of the HashTable call to put.

     * @param key the key to be placed into this property list.
     * @param value the value corresponding to key.
     */
    public void setProperty(String key, String value) {
        properties.setProperty(key, value);
    }

    /**
     * Gets the path to properties file (the real properties file - as opposed to the {@code defaultProperties.txt} file)
     *
     * @return path to properties file
     */
    public String getPropertiesPath() {
        return propertiesPath;
    }

    /**
     * Gets the path to properties file (the real properties file - as opposed to the {@code defaultProperties.txt} file)
     *
     * @return path to properties file
     */
    public File getPropertiesFile() {
        return propertiesFile;
    }

    /**
     * the listener will always be called, when the Properties-file changes.
     *
     * @param listener the listener
     */
    public void registerUpdateListener(Consumer<PropertiesAssistant> listener) {
        if (listener != null)
            listeners.add(new WeakReference<>(listener));
    }

    /**
     * Gets the path to default properties file path (the file which is copied into the real properties on start)
     *
     * @return path to default properties file
     */
    public String getDefaultPropertiesPath() {
        return defaultPropertiesPath;
    }

    /**
     * Initializes properties in the addOn. Creates new properties file using default properties.
     */
    public void initProperties() {
        propertiesPath = getContext().getFiles().getPropertiesLocation() + File.separator
                + getContext().getAddOns().getAddOn().getID() + ".properties";

        this.propertiesFile = new File(propertiesPath);
        if (!this.propertiesFile.exists()) try {
            this.propertiesFile.createNewFile();
        } catch (IOException e) {
            error("Error while trying to create the new Properties file", e);
        }

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(this.propertiesFile),
                    "UTF8"));
            try {
                properties.load(in);
            } catch (IOException e) {
                error("unable to load the InputStream for the PropertiesFile",e);
            }
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            error("Error while trying to read Properties-File", e);
        }

        if (defaultPropertiesPath != null && new File(defaultPropertiesPath).exists()) {
            @SuppressWarnings("unchecked")
            Enumeration<String> keys = (Enumeration<String>)properties.propertyNames();

            if (!keys.hasMoreElements()) {
                try {
                    createDefaultPropertyFile(defaultPropertiesPath);
                } catch (IOException e) {
                    error("Error while trying to copy the Default-Properties File", e);
                }

                if (new File(defaultPropertiesPath).exists() && !writeToPropertiesFile(defaultPropertiesPath)) return;
                reloadProperties();
            }
        }
    }

    /**
     * Writes defaultPropertiesFile.txt to real properties file
     * This is done so that the final user never has to worry about property file initialization
     *
     * @param defaultPropsPath path to defaultPropertyFile.txt (or where it should be created)
     * @return true if operation has succeeded, else false
     */
    private boolean writeToPropertiesFile(String defaultPropsPath) {
        return getContext().getFiles().writeToFile(defaultPropsPath, propertiesPath);
    }

    /**
     * Creates a defaultPropertyFile.txt in case it does not exist yet. In case it is used by an addOn,
     * it copies its content into the real properties file every time the addOn is launched.
     *
     * It is impossible to get the properties file on default, that way the user should not have to worry about
     * the property file's initial content.
     *
     * @param defaultPropsPath path to defaultPropertyFile.txt (or where it should be created)
     * @throws java.io.IOException is thrown by bufferedWriter
     */
    private void createDefaultPropertyFile(String defaultPropsPath) throws IOException {
        getContext().getFiles().createDefaultFile(defaultPropsPath, "# Properties should always be in the "
                + "form of: \"key = value\"");
    }

    /**
     * reloads the propertiesFile into the properties object
     */
    private void reloadProperties() {
        Properties temp = new Properties();
        BufferedReader bufferedReader = null;
        try {
            File properties = new File(propertiesPath);
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(properties), "UTF8"));
            temp.load(bufferedReader);
            this.properties = temp;
            listeners.removeIf(weakReference -> weakReference.get() == null);
            listeners.forEach(weakReference -> {
                Consumer<PropertiesAssistant> consumer = weakReference.get();
                if (consumer != null)
                    consumer.accept(this);
            });
        } catch (IOException e) {
            error("Error while trying to load the Properties-File: "
                    + propertiesPath, e);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    error("Unable to close input stream", e);
                }
            }
        }
    }

    @Override
    public void reloadFile(String eventType) {
        reloadProperties();
    }
}


/**
 *
 * Copyright 2003-2007 Jive Software.
 *
 * All rights reserved. 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.
 */

package org.jivesoftware.smack.util;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.dom4j.Element;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.StreamError;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

/**
 * Utility class that helps to parse packets. Any parsing packets method that
 * must be shared between many clients must be placed in this utility class.
 *
 * @author Gaston Dombiak
 */
public class PacketParserUtils {

    public static String parseContentDepth(XmlPullParser parser, int depth)
            throws XmlPullParserException, IOException {
        StringBuffer content = new StringBuffer();
        while (!(parser.next() == XmlPullParser.END_TAG && parser.getDepth() == depth)) {
            content.append(parser.getText());
        }
        return content.toString();
    }

    /**
     * Parses stream error packets.
     *
     * @param doc
     *            the XML parser.
     * @return an stream error packet.
     * @throws Exception
     *             if an exception occurs while parsing the packet.
     */
    public static StreamError parseStreamError(Element el) throws IOException,
            XmlPullParserException {
        String code = null;
        Element condEl = (Element) el.elements().iterator().next();
        if (condEl.getNamespace().getURI().equals(StreamError.NAMESPACE)) {
            code = condEl.getName();
        }
        String text = condEl.elementText("text");
        return new StreamError(code, text);
    }

    /**
     * Parse the available SASL mechanisms reported from the server.
     *
     * @param mechanismsEl
     *            the XML parser, positioned at the start of the mechanisms
     *            stanza.
     * @return a collection of Stings with the mechanisms included in the
     *         mechanisms stanza.
     * @throws Exception
     *             if an exception occurs while parsing the stanza.
     */
    @SuppressWarnings("unchecked")
    public static Collection<String> parseMechanisms(Element mechanismsEl)
            throws Exception {
        List<Element> mechanisms = mechanismsEl.elements("mechanism");
        List<String> mechanismsStr = new LinkedList<String>();
        for (Element mechanismEl : mechanisms) {
            mechanismsStr.add(mechanismEl.getText());
        }
        return mechanismsStr;
    }

    /**
     * Parse the available compression methods reported from the server.
     *
     * @param compressionEl
     *            the XML parser, positioned at the start of the compression
     *            stanza.
     * @return a collection of Stings with the methods included in the
     *         compression stanza.
     * @throws Exception
     *             if an exception occurs while parsing the stanza.
     */
    @SuppressWarnings("unchecked")
    public static Collection<String> parseCompressionMethods(
            Element compressionEl) throws IOException, XmlPullParserException {
        List<Element> methodsEls = compressionEl.elements("method");
        List<String> methodsStr = new LinkedList<String>();
        for (Element methodEl : methodsEls) {
            methodsStr.add(methodEl.getText());
        }
        return methodsStr;
    }

    /**
     * Parses a packet extension sub-packet.
     *
     * @param elementName
     *            the XML element name of the packet extension.
     * @param namespace
     *            the XML namespace of the packet extension.
     * @param parser
     *            the XML parser, positioned at the starting element of the
     *            extension.
     * @return a PacketExtension.
     * @throws Exception
     *             if a parsing error occurs.
     */
    public static PacketExtension parsePacketExtension(String elementName,
            String namespace, XmlPullParser parser) throws Exception {
        DefaultPacketExtension extension = new DefaultPacketExtension(
                elementName, namespace);
        boolean done = false;
        while (!done) {
            int eventType = parser.next();
            if (eventType == XmlPullParser.START_TAG) {
                String name = parser.getName();
                // If an empty element, set the value with the empty string.
                if (parser.isEmptyElementTag()) {
                    extension.setValue(name, "");
                }
                // Otherwise, get the the element text.
                else {
                    eventType = parser.next();
                    if (eventType == XmlPullParser.TEXT) {
                        String value = parser.getText();
                        extension.setValue(name, value);
                    }
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (parser.getName().equals(elementName)) {
                    done = true;
                }
            }
        }
        return extension;
    }

    public static Object parseWithIntrospection(String elementName,
            Class<?> objectClass, XmlPullParser parser) throws Exception {
        boolean done = false;
        Object object = objectClass.newInstance();
        while (!done) {
            int eventType = parser.next();
            if (eventType == XmlPullParser.START_TAG) {
                String name = parser.getName();
                String stringValue = parser.nextText();
                PropertyDescriptor descriptor = new PropertyDescriptor(name,
                        objectClass);
                // Load the class type of the property.
                Class<?> propertyType = descriptor.getPropertyType();
                // Get the value of the property by converting it from a
                // String to the correct object type.
                Object value = decode(propertyType, stringValue);
                // Set the value of the bean.
                descriptor.getWriteMethod().invoke(object, value);
            } else if (eventType == XmlPullParser.END_TAG) {
                if (parser.getName().equals(elementName)) {
                    done = true;
                }
            }
        }
        return object;
    }

    /**
     * Decodes a String into an object of the specified type. If the object type
     * is not supported, null will be returned.
     *
     * @param type
     *            the type of the property.
     * @param value
     *            the encode String value to decode.
     * @return the String value decoded into the specified type.
     * @throws Exception
     *             If decoding failed due to an error.
     */
    private static Object decode(Class<?> type, String value) throws Exception {
        if (type.getName().equals("java.lang.String")) {
            return value;
        }
        if (type.getName().equals("boolean")) {
            return Boolean.valueOf(value);
        }
        if (type.getName().equals("int")) {
            return Integer.valueOf(value);
        }
        if (type.getName().equals("long")) {
            return Long.valueOf(value);
        }
        if (type.getName().equals("float")) {
            return Float.valueOf(value);
        }
        if (type.getName().equals("double")) {
            return Double.valueOf(value);
        }
        if (type.getName().equals("java.lang.Class")) {
            return Class.forName(value);
        }
        return null;
    }

    public static void updateText(Element parentEl, String elName, String text) {
        Element el = parentEl.element(elName);
        if (el == null) {
            el = parentEl.addElement(elName);
        }
        el.setText(text);
    }

}


package org.intellimate.izou.sdk.frameworks.music.events;

import org.intellimate.izou.events.EventModel;
import org.intellimate.izou.identification.Identifiable;
import org.intellimate.izou.identification.Identification;
import org.intellimate.izou.sdk.events.CommonEvents;
import org.intellimate.izou.sdk.events.Event;
import org.intellimate.izou.sdk.frameworks.common.resources.SelectorResource;
import org.intellimate.izou.sdk.frameworks.music.Capabilities;
import org.intellimate.izou.sdk.frameworks.music.player.Playlist;
import org.intellimate.izou.sdk.frameworks.music.player.TrackInfo;
import org.intellimate.izou.sdk.frameworks.music.resources.PlaylistResource;
import org.intellimate.izou.sdk.frameworks.music.resources.TrackInfoResource;
import org.intellimate.izou.system.sound.SoundIDs;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * this events request the start of the music-playing
 * @author LeanderK
 * @version 1.0
 */
public class StartMusicRequest extends Event {
    //TODO in izou
    @SuppressWarnings("SpellCheckingInspection")
    public static final String ID = "izou.music.events.startrequest";

    /**
     * Creates a new Event Object
     *
     * @param source      the source of the Event, most likely a this reference.
     * @param isUsingJava true if the player is using java
     * @throws IllegalArgumentException if one of the Arguments is null or empty
     */
    protected StartMusicRequest(Identification source, boolean isUsingJava) throws IllegalArgumentException {
        super(CommonEvents.Type.RESPONSE_TYPE, source,
                isUsingJava ? Arrays.asList(ID) : Arrays.asList(ID, SoundIDs.StartEvent.isUsingNonJava)
        );
    }

    /**
     * creates a new StartRequest
     * @param source the caller
     * @param target the target who should start playing
     * @return the optional StartMusicRequest
     */
    public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target) {
        return createStartMusicRequest(source, target, (TrackInfo) null);
    }

    /**
     * creates a new StartRequest
     * @param source the caller
     * @param target the target who should start playing
     * @param trackInfo the track to play
     * @return the optional StartMusicRequest
     */
    public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, TrackInfo trackInfo) {
        return createStartMusicRequest(source, target, trackInfo, true);
    }

    /**
     * creates a new StartRequest
     * @param source the caller
     * @param target the target who should start playing
     * @param trackInfo the track to play
     * @param isUsingJava true if the player is using java
     * @return the optional StartMusicRequest
     */
    public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, TrackInfo trackInfo, boolean isUsingJava) {
        if (target.equals(source))
            return Optional.empty();
        try {
            StartMusicRequest request = new StartMusicRequest(source, isUsingJava);
            request.addResource(new SelectorResource(source, target));
            if (trackInfo != null)
                request.addResource(new TrackInfoResource(target, trackInfo, source));
            return Optional.of(request);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

    /**
     * creates a new StartRequest
     * @param source the caller
     * @param target the target who should start playing
     * @param playlist the playlist to play
     * @return the optional StartMusicRequest
     */
    public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, Playlist playlist) {
        return createStartMusicRequest(source, target, playlist, true);
    }

    /**
     * creates a new StartRequest
     * @param source the caller
     * @param target the target who should start playing
     * @param playlist the playlist to play
     * @param isUsingJava true if the player is using java
     * @return the optional StartMusicRequest
     */
    public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, Playlist playlist, boolean isUsingJava) {
        if (target.equals(source))
            return Optional.empty();
        try {
            StartMusicRequest request = new StartMusicRequest(source, isUsingJava);
            request.addResource(new SelectorResource(source, target));
            if (playlist != null)
                request.addResource(new PlaylistResource(target, playlist, source));
            return Optional.of(request);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

    /**
     * verifies that the StartMusicRequest is correct and checks whether the you are meant to react to it
     * @param eventModel the EventModel to check against
     * @param player the identifiable
     * @param capabilities the capabilities
     * @param activators the activators which are able to start the player if it is not able to start from outside commands
     * @return true if verified, false if not
     */
    public static boolean verify(EventModel eventModel, Capabilities capabilities, Identifiable player, List<Identifiable> activators) {
        if (!eventModel.containsDescriptor(StartMusicRequest.ID))
            return false;
        if (!capabilities.handlesPlayRequestFromOutside()) {
            if (activators.stream()
                    .noneMatch(identifiable -> identifiable.isOwner(eventModel.getSource())))
                return false;
        }
        if (!PlaylistResource.getPlaylist(eventModel).map(playlist -> playlist.verify(capabilities)).orElse(true)) {
            return false;
        }
        return SelectorResource.isTarget(eventModel, player)
                .orElse(false);
    }
}


/*
 * Copyright 2010 Workplace Systems PLC (http://www.workplacesystems.com/).
 *
 * 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.
 */

package com.workplacesystems.utilsj.collections.helpers;

import java.util.Comparator;

import com.workplacesystems.utilsj.collections.Filter;

/**
 * Factory to create various comaprison filters to operate on collections
 * that are mutually comparable or given an object that implements the
 * Compartor interface compares the objects in a collection with a base
 * object.
 */
public abstract class ComparisonFilterFactory
{
    /**
     * Creates a filter where valid when an object in a
     * collection is the same as the base object.
     */
    public static <E> Filter<E> createSameAsFilter(final E base)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return (base == obj);
            }
        };
    }

    /**
     * Creates a filter where valid when an object in a
     * collection is the equal to the base object.
     */
    public static <E> Filter<E> createEqualToFilter(final Object base)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return obj.equals(base);
            }
        };
    }

    /**
     * Creates a filter where valid when an Comparable in a
     * collection is considered greater than the base object.
     */
    public static <E extends Comparable<E>> Filter<E> createGreaterThanFilter(final E base)
    {
        return createGreaterThanFilter(base, new Comparator<E>()
        {
            public int compare(E obj1, E obj2)
            {
                return obj1.compareTo(obj2);
            }
        });
    }

    /**
     * Creates a filter where valid when an Object in a
     * collection is considered greater than the base object,
     * based on the given Comparator.
     */
    public static <E> Filter<E> createGreaterThanFilter(final E base, final Comparator<E> comparator)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return comparator.compare(obj, base) > 0;
            }
        };
    }

    /**
     * Creates a filter where valid when an Comparable in a
     * collection is considered greater than or equal to the base object.
     */
    public static <E extends Comparable<E>> Filter<E> createGreaterThanOrEqualToFilter(final E base)
    {
        return createGreaterThanOrEqualToFilter(base, new Comparator<E>()
        {
            public int compare(E obj1, E obj2)
            {
                return obj1.compareTo(obj2);
            }
        });
    }

    /**
     * Creates a filter where valid when an Object in a
     * collection is considered greater than or equal to the base object,
     * based on the given Comparator.
     */
    public static <E> Filter<E> createGreaterThanOrEqualToFilter(final E base, final Comparator<E> comparator)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return comparator.compare(obj, base) >= 0;
            }
        };
    }

    /**
     * Creates a filter where valid when an Comparable in a
     * collection is considered less than the base object.
     */
    public static <E extends Comparable<E>> Filter<E> createLessThanFilter(final E base)
    {
        return createLessThanFilter(base, new Comparator<E>()
        {
            public int compare(E obj1, E obj2)
            {
                return obj1.compareTo(obj2);
            }
        });
    }

    /**
     * Creates a filter where valid when an Object in a
     * collection is considered less than the base object,
     * based on the given Comparator.
     */
    public static <E> Filter<E> createLessThanFilter(final E base, final Comparator<E> comparator)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return comparator.compare(obj, base) < 0;
            }
        };
    }

    /**
     * Creates a filter where valid when an Comparable in a
     * collection is considered less than or equal to the base object.
     */
    public static <E extends Comparable<E>> Filter<E> createLessThanOrEqualToFilter(final E base)
    {
        return createLessThanOrEqualToFilter(base, new Comparator<E>()
        {
            public int compare(E obj1, E obj2)
            {
                return obj1.compareTo(obj2);
            }
        });
    }

    /**
     * Creates a filter where valid when an Object in a
     * collection is considered less than or equal to the base object,
     * based on the given Comparator.
     */
    public static <E> Filter<E> createLessThanOrEqualToFilter(final E base, final Comparator<E> comparator)
    {
        return new Filter<E>() {
            public boolean isValid(E obj)
            {
                return comparator.compare(obj, base) <= 0;
            }
        };
    }
}


package org.intellimate.izou.sdk.frameworks.music.resources;

import org.intellimate.izou.identification.Identification;
import org.intellimate.izou.resource.ResourceModel;
import org.intellimate.izou.sdk.frameworks.music.player.PlaybackState;
import org.intellimate.izou.sdk.resource.Resource;

import java.util.Optional;

/**
 * this class simply holds the playback-state for events,can also be obtained via the resourceManager
 * @author LeanderK
 * @version 1.0
 */
public class PlaybackStateResource extends Resource<String> {
    @SuppressWarnings("SpellCheckingInspection")
    public static final String ID = "izou.music.resource.playbackstate";

    /**
     * creates a new Resource.
     * This method is thread-safe.
     *
     * @param provider   the Provider of the Resource
     */
    public PlaybackStateResource(Identification provider) {
        super(ID, provider);
    }

    /**
     * creates a new Resource.
     * This method is thread-safe.
     *
     * @param provider   the Provider of the Resource
     * @param state      the PlaybackState
     */
    public PlaybackStateResource(Identification provider, PlaybackState state) {
        super(ID, provider, state.name());
    }

    /**
     * creates a new Resource.
     * This method is thread-safe.
     *
     * @param provider   the Provider of the Resource
     * @param consumer   the ID of the Consumer
     */
    public PlaybackStateResource(Identification provider, Identification consumer) {
        super(ID, provider, consumer);
    }

    /**
     * creates a new Resource.
     * This method is thread-safe.
     *
     * @param provider   the Provider of the Resource
     * @param state      the PlaybackState
     * @param consumer   the ID of the Consumer
     */
    public PlaybackStateResource(Identification provider, PlaybackState state, Identification consumer) {
        super(ID, provider, state.name(), consumer);
    }

    /**
     * returns the PlaybackState from the resource
     * @param x the resourceModel
     * @return the optional Playbackstate (empty if illegal resource)
     */
    public static Optional<PlaybackState> getPlaybackStateFromResource(ResourceModel x) {
        if (!x.getResourceID().equals(ID))
            return Optional.empty();
        Object resource = x.getResource();
        if (resource instanceof String) {
            String state = (String) resource;
            try {
                return Optional.of(PlaybackState.valueOf(state));
            } catch (IllegalArgumentException e) {
                return Optional.empty();
            }
        } else {
            return Optional.empty();
        }
    }
}


/**
 * $RCSfile$
 * $Revision: 10099 $
 * $Date: 2008-03-20 16:46:17 -0700 (Thu, 20 Mar 2008) $
 *
 * Copyright 2005 Jive Software.
 *
 * All rights reserved. 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.
 */

package org.jivesoftware.whack;

import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.xmpp.component.Component;
import org.xmpp.component.ComponentException;
import org.xmpp.component.ComponentManager;
import org.xmpp.component.ComponentManagerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;

/**
 * Implementation of the ComponentManager interface for external components.
 * This implementation follows JEP-0014.
 *
 * @author Matt Tucker
 */
public class ExternalComponentManager implements ComponentManager {

    /**
     * Keeps the IP address or hostname of the server. This value will be used
     * only for creating connections.
     */
    private String host;
    /**
     * Port of the server used for establishing new connections.
     */
    private int port;
    /**
     * Keeps the domain of the XMPP server. The domain may or may not match the
     * host. The domain will be used mainly for the XMPP packets while the host
     * is used mainly for creating connections to the server.
     */
    private String domain;
    /**
     * Timeout to use when trying to connect to the server.
     */
    private int connectTimeout = 2000;
    /**
     * This is a global secret key that will be used during the handshake with
     * the server. If a secret key was not defined for the specific component
     * then the global secret key will be used.
     */
    private String defaultSecretKey;
    /**
     * Keeps the secret keys to use for each subdomain. If a key was not found
     * for a specific subdomain then the global secret key will used for the
     * handshake with the server.
     */
    private Map<String, String> secretKeys = new Hashtable<String, String>();
    /**
     * Holds the settings for whether we will tell the XMPP server that a given
     * component can connect to the same JID multiple times. This is a custom
     * Openfire extension and will not work with any other XMPP server. Other
     * servers should ignore this setting.
     */
    private Map<String, Boolean> allowMultiple = new Hashtable<String, Boolean>();

    /**
     * Keeps a map that associates a domain with the external component thas is
     * handling the domain.
     */
    private Map<String, ExternalComponent> componentsByDomain = new Hashtable<String, ExternalComponent>();
    /**
     * Keeps a map that associates a component with the wrapping
     * ExternalComponent.
     */
    private Map<Component, ExternalComponent> components = new Hashtable<Component, ExternalComponent>();

    private static final Logger LOG = Logger.getLogger(ExternalComponent.class);

    private Properties properties = new Properties();

    /**
     * Constructs a new ExternalComponentManager that will make connections to
     * the specified XMPP server on the default port (5222).
     *
     * @param host
     *            the IP address or name of the XMPP server to connect to (e.g.
     *            "example.com").
     */
    public ExternalComponentManager(String host) {
        this(host, 5225);
    }

    /**
     * Constructs a new ExternalComponentManager that will make connections to
     * the specified XMPP server on the given port.
     *
     * @param host
     *            the IP address or name of the XMPP server to connect to (e.g.
     *            "example.com").
     * @param port
     *            the port to connect on.
     */
    public ExternalComponentManager(String host, int port) {
        if (host == null) {
            throw new IllegalArgumentException(
                    "Host of XMPP server cannot be null");
        }
        this.host = host;
        this.port = port;

        // Set this ComponentManager as the current component manager
        ComponentManagerFactory.setComponentManager(this);
    }

    /**
     * Sets a secret key for a sub-domain, for future use by a component
     * connecting to the server. Keys are used as an authentication mechanism
     * when connecting to the server. Some servers may require a different key
     * for each component, while others may use a global secret key.
     *
     * @param subdomain
     *            the sub-domain.
     * @param secretKey
     *            the secret key
     */
    public void setSecretKey(String subdomain, String secretKey) {
        secretKeys.put(subdomain, secretKey);
    }

    /**
     * Returns the secret key for a sub-domain. If no key was found then the
     * default secret key will be returned.
     *
     * @param subdomain
     *            the subdomain to return its secret key.
     * @return the secret key for a sub-domain.
     */
    public String getSecretKey(String subdomain) {
        // Find the proper secret key to connect as the subdomain.
        String secretKey = secretKeys.get(subdomain);
        if (secretKey == null) {
            secretKey = defaultSecretKey;
        }
        return secretKey;
    }

    /**
     * Sets the default secret key, which will be used when connecting if a
     * specific secret key for the component hasn't been sent. Keys are used as
     * an authentication mechanism when connecting to the server. Some servers
     * may require a different key for each component, while others may use a
     * global secret key.
     *
     * @param secretKey
     *            the default secret key.
     */
    public void setDefaultSecretKey(String secretKey) {
        this.defaultSecretKey = secretKey;
    }

    /**
     * Returns if we want components to be able to connect multiple times to the
     * same JID. This is a custom Openfire extension and will not work with any
     * other XMPP server. Other XMPP servers should ignore this extra setting.
     *
     * @param subdomain
     *            the sub-domain.
     * @return True or false if we are allowing multiple connections.
     */
    public boolean isMultipleAllowed(String subdomain) {
        Boolean allowed = allowMultiple.get(subdomain);
        return allowed != null && allowed;
    }

    /**
     * Sets whether we will tell the XMPP server that we want multiple
     * components to be able to connect to the same JID. This is a custom
     * Openfire extension and will not work with any other XMPP server. Other
     * XMPP servers should ignore this extra setting.
     *
     * @param subdomain
     *            the sub-domain.
     * @param allowMultiple
     *            Set to true if we want to allow multiple connections to same
     *            JID.
     */
    public void setMultipleAllowed(String subdomain, boolean allowMultiple) {
        this.allowMultiple.put(subdomain, allowMultiple);
    }

    public void addComponent(String subdomain, Component component)
            throws ComponentException {
        addComponent(subdomain, component, this.port);
    }

    public void addComponent(String subdomain, Component component, Integer port)
            throws ComponentException {
        if (componentsByDomain.containsKey(subdomain)) {
            if (componentsByDomain.get(subdomain).getComponent() == component) {
                // Do nothing since the component has already been registered
                return;
            } else {
                throw new IllegalArgumentException(
                        "Subdomain already in use by another component");
            }
        }
        // Create a wrapping ExternalComponent on the component
        ExternalComponent externalComponent = new ExternalComponent(component,
                this);
        try {
            // Register the new component
            componentsByDomain.put(subdomain, externalComponent);
            components.put(component, externalComponent);
            // Ask the ExternalComponent to connect with the remote server
            externalComponent.connect(host, port, subdomain);
            // Initialize the component
            JID componentJID = new JID(null, externalComponent.getDomain(),
                    null);
            externalComponent.initialize(componentJID, this);
        } catch (ComponentException e) {
            // Unregister the new component
            componentsByDomain.remove(subdomain);
            components.remove(component);
            // Re-throw the exception
            throw e;
        }
        // Ask the external component to start processing incoming packets
        externalComponent.start();
    }

    public void removeComponent(String subdomain) throws ComponentException {
        ExternalComponent externalComponent = componentsByDomain
                .remove(subdomain);
        if (externalComponent != null) {
            components.remove(externalComponent.getComponent());
            externalComponent.shutdown();
        }
    }

    public void sendPacket(Component component, Packet packet) {
        // Get the ExternalComponent that is wrapping the specified component
        // and ask it to
        // send the packet
        components.get(component).send(packet);
    }

    public IQ query(Component component, IQ packet, long timeout)
            throws ComponentException {
        final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
        ExternalComponent externalComponent = components.get(component);
        externalComponent.addIQResultListener(packet.getID(),
                new IQResultListener() {
                    public void receivedAnswer(IQ packet) {
                        answer.offer(packet);
                    }

                    public void answerTimeout(String packetId) {
                        // Do nothing
                    }
                }, timeout);
        sendPacket(component, packet);
        IQ reply = null;
        try {
            reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // Ignore
        }
        return reply;
    }

    public void query(Component component, IQ packet, IQResultListener listener)
            throws ComponentException {
        ExternalComponent externalComponent = components.get(component);
        // Add listenet with a timeout of 5 minutes to prevent memory leaks
        externalComponent.addIQResultListener(packet.getID(), listener, 300000);
        sendPacket(component, packet);
    }

    /**
     * Sets the domain of the XMPP server. The domain may or may not match the
     * host. The domain will be used mainly for the XMPP packets while the host
     * is used mainly for creating connections to the server.
     *
     * @param domain
     *            the domain of the XMPP server.
     */
    public void setServerName(String domain) {
        this.domain = domain;
    }

    /**
     * Returns the domain of the XMPP server where we are connected to or
     * <tt>null</tt> if this value was never configured. When the value is null
     * then the component will register with just its subdomain and we expect
     * the server to accept the component and append its domain to form the JID
     * of the component.
     *
     * @return the domain of the XMPP server or null if never configured.
     */
    public String getServerName() {
        return domain;
    }

    /**
     * Returns the timeout (in milliseconds) to use when trying to connect to
     * the server. The default value is 2 seconds.
     *
     * @return the timeout to use when trying to connect to the server.
     */
    public int getConnectTimeout() {
        return connectTimeout;
    }

    /**
     * Sets the timeout (in milliseconds) to use when trying to connect to the
     * server. The default value is 2 seconds.
     *
     * @param connectTimeout
     *            the timeout, in milliseconds, to use when trying to connect to
     *            the server.
     */
    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public boolean isExternalMode() {
        return true;
    }

    public Logger getLog() {
        return LOG;
    }

    @Override
    public void query(Component component, IQ packet,
            org.xmpp.component.IQResultListener listener)
            throws ComponentException {
        // TODO Auto-generated method stub
    }

    @Override
    public String getProperty(String name) {
        return properties.getProperty(name);
    }

    @Override
    public void setProperty(String name, String value) {
        properties.setProperty(name, value);
    }
}


// Converted, with some major refactors required. Not as memory-efficient as before, could use additional refactoring.
// Perhaps use four different types of HashEntry classes for max efficiency:
//   normal HashEntry for HARD,HARD
//   HardRefEntry for HARD,(SOFT|WEAK)
//   RefHardEntry for (SOFT|WEAK),HARD
//   RefRefEntry for (SOFT|WEAK),(SOFT|WEAK)
/*
 *  Copyright 2002-2004 The Apache Software Foundation
 *
 *  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.
 */
package org.jivesoftware.smack.util.collections;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.*;

/**
 * An abstract implementation of a hash-based map that allows the entries to be
 * removed by the garbage collector.
 *

 * This class implements all the features necessary for a subclass reference
 * hash-based map. Key-value entries are stored in instances of the
 * ReferenceEntry class which can be overridden and replaced. The
 * iterators can similarly be replaced, without the need to replace the KeySet,
 * EntrySet and Values view classes.
 *

 * Overridable methods are provided to change the default hashing behaviour, and
 * to change how entries are added to and removed from the map. Hopefully, all
 * you need for unusual subclasses is here.
 *

 * When you construct an AbstractReferenceMap, you can specify what
 * kind of references are used to store the map's keys and values. If non-hard
 * references are used, then the garbage collector can remove mappings if a key
 * or value becomes unreachable, or if the JVM's memory is running low. For
 * information on how the different reference types behave, see
 * {@link Reference}.
 *

 * Different types of references can be specified for keys and values. The keys
 * can be configured to be weak but the values hard, in which case this class
 * will behave like a
 * WeakHashMap. However, you can also specify hard keys and
 * weak values, or any other combination. The default constructor uses hard keys
 * and soft values, providing a memory-sensitive cache.
 *

 * This {@link Map} implementation does not allow null elements.
 * Attempting to add a null key or value to the map will raise a
 * NullPointerException.
 *

 * All the available iterators can be reset back to the start by casting to
 * ResettableIterator and calling reset().
 *

 * This implementation is not synchronized. You can use
 * {@link java.util.Collections#synchronizedMap} to provide synchronized access
 * to a ReferenceMap.
 *
 * @author Paul Jack
 * @author Matt Hall, John Watkinson, Stephen Colebourne
 * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:32 $
 * @see java.lang.ref.Reference
 * @since Commons Collections 3.1 (extracted from ReferenceMap in 3.0)
 */
public abstract class AbstractReferenceMap<K, V> extends
        AbstractHashedMap<K, V> {

    /**
     * Constant indicating that hard references should be used
     */
    public static final int HARD = 0;

    /**
     * Constant indicating that soft references should be used
     */
    public static final int SOFT = 1;

    /**
     * Constant indicating that weak references should be used
     */
    public static final int WEAK = 2;

    /**
     * The reference type for keys. Must be HARD, SOFT, WEAK.
     *
     * @serial
     */
    protected int keyType;

    /**
     * The reference type for values. Must be HARD, SOFT, WEAK.
     *
     * @serial
     */
    protected int valueType;

    /**
     * Should the value be automatically purged when the associated key has been
     * collected?
     */
    protected boolean purgeValues;

    /**
     * ReferenceQueue used to eliminate stale mappings. See purge.
     */
    private transient ReferenceQueue queue;

    // -----------------------------------------------------------------------
    /**
     * Constructor used during deserialization.
     */
    protected AbstractReferenceMap() {
        super();
    }

    /**
     * Constructs a new empty map with the specified reference types, load
     * factor and initial capacity.
     *
     * @param keyType
     *            the type of reference to use for keys; must be {@link #SOFT}
     *            or {@link #WEAK}
     * @param valueType
     *            the type of reference to use for values; must be {@link #SOFT}
     *            or {@link #WEAK}
     * @param capacity
     *            the initial capacity for the map
     * @param loadFactor
     *            the load factor for the map
     * @param purgeValues
     *            should the value be automatically purged when the key is
     *            garbage collected
     */
    protected AbstractReferenceMap(int keyType, int valueType, int capacity,
            float loadFactor, boolean purgeValues) {
        super(capacity, loadFactor);
        verify("keyType", keyType);
        verify("valueType", valueType);
        this.keyType = keyType;
        this.valueType = valueType;
        this.purgeValues = purgeValues;
    }

    /**
     * Initialise this subclass during construction, cloning or deserialization.
     */
    protected void init() {
        queue = new ReferenceQueue();
    }

    // -----------------------------------------------------------------------
    /**
     * Checks the type int is a valid value.
     *
     * @param name
     *            the name for error messages
     * @param type
     *            the type value to check
     * @throws IllegalArgumentException
     *             if the value if invalid
     */
    private static void verify(String name, int type) {
        if ((type < HARD) || (type > WEAK)) {
            throw new IllegalArgumentException(name
                    + " must be HARD, SOFT, WEAK.");
        }
    }

    // -----------------------------------------------------------------------
    /**
     * Gets the size of the map.
     *
     * @return the size
     */
    public int size() {
        purgeBeforeRead();
        return super.size();
    }

    /**
     * Checks whether the map is currently empty.
     *
     * @return true if the map is currently size zero
     */
    public boolean isEmpty() {
        purgeBeforeRead();
        return super.isEmpty();
    }

    /**
     * Checks whether the map contains the specified key.
     *
     * @param key
     *            the key to search for
     * @return true if the map contains the key
     */
    public boolean containsKey(Object key) {
        purgeBeforeRead();
        Entry entry = getEntry(key);
        if (entry == null) {
            return false;
        }
        return (entry.getValue() != null);
    }

    /**
     * Checks whether the map contains the specified value.
     *
     * @param value
     *            the value to search for
     * @return true if the map contains the value
     */
    public boolean containsValue(Object value) {
        purgeBeforeRead();
        if (value == null) {
            return false;
        }
        return super.containsValue(value);
    }

    /**
     * Gets the value mapped to the key specified.
     *
     * @param key
     *            the key
     * @return the mapped value, null if no match
     */
    public V get(Object key) {
        purgeBeforeRead();
        Entry<K, V> entry = getEntry(key);
        if (entry == null) {
            return null;
        }
        return entry.getValue();
    }

    /**
     * Puts a key-value mapping into this map. Neither the key nor the value may
     * be null.
     *
     * @param key
     *            the key to add, must not be null
     * @param value
     *            the value to add, must not be null
     * @return the value previously mapped to this key, null if none
     * @throws NullPointerException
     *             if either the key or value is null
     */
    public V put(K key, V value) {
        if (key == null) {
            throw new NullPointerException("null keys not allowed");
        }
        if (value == null) {
            throw new NullPointerException("null values not allowed");
        }

        purgeBeforeWrite();
        return super.put(key, value);
    }

    /**
     * Removes the specified mapping from this map.
     *
     * @param key
     *            the mapping to remove
     * @return the value mapped to the removed key, null if key not in map
     */
    public V remove(Object key) {
        if (key == null) {
            return null;
        }
        purgeBeforeWrite();
        return super.remove(key);
    }

    /**
     * Clears this map.
     */
    public void clear() {
        super.clear();
        while (queue.poll() != null) {
        } // drain the queue
    }

    // -----------------------------------------------------------------------
    /**
     * Gets a MapIterator over the reference map. The iterator only returns
     * valid key/value pairs.
     *
     * @return a map iterator
     */
    public MapIterator<K, V> mapIterator() {
        return new ReferenceMapIterator<K, V>(this);
    }

    /**
     * Returns a set view of this map's entries. An iterator returned entry is
     * valid until next() is called again. The
     * setValue() method on the toArray entries has no
     * effect.
     *
     * @return a set view of this map's entries
     */
    public Set<Map.Entry<K, V>> entrySet() {
        if (entrySet == null) {
            entrySet = new ReferenceEntrySet<K, V>(this);
        }
        return entrySet;
    }

    /**
     * Returns a set view of this map's keys.
     *
     * @return a set view of this map's keys
     */
    public Set<K> keySet() {
        if (keySet == null) {
            keySet = new ReferenceKeySet<K, V>(this);
        }
        return keySet;
    }

    /**
     * Returns a collection view of this map's values.
     *
     * @return a set view of this map's values
     */
    public Collection<V> values() {
        if (values == null) {
            values = new ReferenceValues<K, V>(this);
        }
        return values;
    }

    // -----------------------------------------------------------------------
    /**
     * Purges stale mappings from this map before read operations.
     *

     * This implementation calls {@link #purge()} to maintain a consistent
     * state.
     */
    protected void purgeBeforeRead() {
        purge();
    }

    /**
     * Purges stale mappings from this map before write operations.
     *

     * This implementation calls {@link #purge()} to maintain a consistent
     * state.
     */
    protected void purgeBeforeWrite() {
        purge();
    }

    /**
     * Purges stale mappings from this map.
     *

     * Note that this method is not synchronized! Special care must be taken if,
     * for instance, you want stale mappings to be removed on a periodic basis
     * by some background thread.
     */
    protected void purge() {
        Reference ref = queue.poll();
        while (ref != null) {
            purge(ref);
            ref = queue.poll();
        }
    }

    /**
     * Purges the specified reference.
     *
     * @param ref
     *            the reference to purge
     */
    protected void purge(Reference ref) {
        // The hashCode of the reference is the hashCode of the
        // mapping key, even if the reference refers to the
        // mapping value...
        int hash = ref.hashCode();
        int index = hashIndex(hash, data.length);
        HashEntry<K, V> previous = null;
        HashEntry<K, V> entry = data[index];
        while (entry != null) {
            if (((ReferenceEntry<K, V>) entry).purge(ref)) {
                if (previous == null) {
                    data[index] = entry.next;
                } else {
                    previous.next = entry.next;
                }
                this.size--;
                return;
            }
            previous = entry;
            entry = entry.next;
        }

    }

    // -----------------------------------------------------------------------
    /**
     * Gets the entry mapped to the key specified.
     *
     * @param key
     *            the key
     * @return the entry, null if no match
     */
    protected HashEntry<K, V> getEntry(Object key) {
        if (key == null) {
            return null;
        } else {
            return super.getEntry(key);
        }
    }

    /**
     * Gets the hash code for a MapEntry. Subclasses can override this, for
     * example to use the identityHashCode.
     *
     * @param key
     *            the key to get a hash code for, may be null
     * @param value
     *            the value to get a hash code for, may be null
     * @return the hash code, as per the MapEntry specification
     */
    protected int hashEntry(Object key, Object value) {
        return (key == null ? 0 : key.hashCode())
                ^ (value == null ? 0 : value.hashCode());
    }

    /**
     * Compares two keys, in internal converted form, to see if they are equal.
     *

     * This implementation converts the key from the entry to a real reference
     * before comparison.
     *
     * @param key1
     *            the first key to compare passed in from outside
     * @param key2
     *            the second key extracted from the entry via
     *            entry.key
     * @return true if equal
     */
    protected boolean isEqualKey(Object key1, Object key2) {
        // if ((key1 == null) && (key2 != null) || (key1 != null) || (key2 ==
        // null)) {
        // return false;
        // }
        // GenericsNote: Conversion from reference handled by getKey() which
        // replaced all .key references
        // key2 = (keyType > HARD ? ((Reference) key2).get() : key2);
        return (key1 == key2 || key1.equals(key2));
    }

    /**
     * Creates a ReferenceEntry instead of a HashEntry.
     *
     * @param next
     *            the next entry in sequence
     * @param hashCode
     *            the hash code to use
     * @param key
     *            the key to store
     * @param value
     *            the value to store
     * @return the newly created entry
     */
    public HashEntry<K, V> createEntry(HashEntry<K, V> next, int hashCode,
            K key, V value) {
        return new ReferenceEntry<K, V>(this, (ReferenceEntry<K, V>) next,
                hashCode, key, value);
    }

    /**
     * Creates an entry set iterator.
     *
     * @return the entrySet iterator
     */
    protected Iterator<Map.Entry<K, V>> createEntrySetIterator() {
        return new ReferenceEntrySetIterator<K, V>(this);
    }

    /**
     * Creates an key set iterator.
     *
     * @return the keySet iterator
     */
    protected Iterator<K> createKeySetIterator() {
        return new ReferenceKeySetIterator<K, V>(this);
    }

    /**
     * Creates an values iterator.
     *
     * @return the values iterator
     */
    protected Iterator<V> createValuesIterator() {
        return new ReferenceValuesIterator<K, V>(this);
    }

    // -----------------------------------------------------------------------
    /**
     * EntrySet implementation.
     */
    static class ReferenceEntrySet<K, V> extends EntrySet<K, V> {

        protected ReferenceEntrySet(AbstractHashedMap<K, V> parent) {
            super(parent);
        }

        public Object[] toArray() {
            return toArray(new Object[0]);
        }

        public <T> T[] toArray(T[] arr) {
            // special implementation to handle disappearing entries
            ArrayList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>();
            Iterator<Map.Entry<K, V>> iterator = iterator();
            while (iterator.hasNext()) {
                Map.Entry<K, V> e = iterator.next();
                list.add(new DefaultMapEntry<K, V>(e.getKey(), e.getValue()));
            }
            return list.toArray(arr);
        }
    }

    // -----------------------------------------------------------------------
    /**
     * KeySet implementation.
     */
    static class ReferenceKeySet<K, V> extends KeySet<K, V> {

        protected ReferenceKeySet(AbstractHashedMap<K, V> parent) {
            super(parent);
        }

        public Object[] toArray() {
            return toArray(new Object[0]);
        }

        public <T> T[] toArray(T[] arr) {
            // special implementation to handle disappearing keys
            List<K> list = new ArrayList<K>(parent.size());
            for (Iterator<K> it = iterator(); it.hasNext();) {
                list.add(it.next());
            }
            return list.toArray(arr);
        }
    }

    // -----------------------------------------------------------------------
    /**
     * Values implementation.
     */
    static class ReferenceValues<K, V> extends Values<K, V> {

        protected ReferenceValues(AbstractHashedMap<K, V> parent) {
            super(parent);
        }

        public Object[] toArray() {
            return toArray(new Object[0]);
        }

        public <T> T[] toArray(T[] arr) {
            // special implementation to handle disappearing values
            List<V> list = new ArrayList<V>(parent.size());
            for (Iterator<V> it = iterator(); it.hasNext();) {
                list.add(it.next());
            }
            return list.toArray(arr);
        }
    }

    // -----------------------------------------------------------------------
    /**
     * A MapEntry implementation for the map.
     *

     * If getKey() or getValue() returns null, it means the mapping is stale and
     * should be removed.
     *
     * @since Commons Collections 3.1
     */
    protected static class ReferenceEntry<K, V> extends HashEntry<K, V> {
        /**
         * The parent map
         */
        protected final AbstractReferenceMap<K, V> parent;

        protected Reference<K> refKey;
        protected Reference<V> refValue;

        /**
         * Creates a new entry object for the ReferenceMap.
         *
         * @param parent
         *            the parent map
         * @param next
         *            the next entry in the hash bucket
         * @param hashCode
         *            the hash code of the key
         * @param key
         *            the key
         * @param value
         *            the value
         */
        public ReferenceEntry(AbstractReferenceMap<K, V> parent,
                ReferenceEntry<K, V> next, int hashCode, K key, V value) {
            super(next, hashCode, null, null);
            this.parent = parent;
            if (parent.keyType != HARD) {
                refKey = toReference(parent.keyType, key, hashCode);
            } else {
                this.setKey(key);
            }
            if (parent.valueType != HARD) {
                refValue = toReference(parent.valueType, value, hashCode); // the
                                                                           // key
                                                                           // hashCode
                                                                           // is
                                                                           // passed
                                                                           // in
                                                                           // deliberately
            } else {
                this.setValue(value);
            }
        }

        /**
         * Gets the key from the entry. This method dereferences weak and soft
         * keys and thus may return null.
         *
         * @return the key, which may be null if it was garbage collected
         */
        public K getKey() {
            return (parent.keyType > HARD) ? refKey.get() : super.getKey();
        }

        /**
         * Gets the value from the entry. This method dereferences weak and soft
         * value and thus may return null.
         *
         * @return the value, which may be null if it was garbage collected
         */
        public V getValue() {
            return (parent.valueType > HARD) ? refValue.get() : super
                    .getValue();
        }

        /**
         * Sets the value of the entry.
         *
         * @param obj
         *            the object to store
         * @return the previous value
         */
        public V setValue(V obj) {
            V old = getValue();
            if (parent.valueType > HARD) {
                refValue.clear();
                refValue = toReference(parent.valueType, obj, hashCode);
            } else {
                super.setValue(obj);
            }
            return old;
        }

        /**
         * Compares this map entry to another.
         *

         * This implementation uses isEqualKey and
         * isEqualValue on the main map for comparison.
         *
         * @param obj
         *            the other map entry to compare to
         * @return true if equal, false if not
         */
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof Map.Entry == false) {
                return false;
            }

            Map.Entry entry = (Map.Entry) obj;
            Object entryKey = entry.getKey(); // convert to hard reference
            Object entryValue = entry.getValue(); // convert to hard reference
            if ((entryKey == null) || (entryValue == null)) {
                return false;
            }
            // compare using map methods, aiding identity subclass
            // note that key is direct access and value is via method
            return parent.isEqualKey(entryKey, getKey())
                    && parent.isEqualValue(entryValue, getValue());
        }

        /**
         * Gets the hashcode of the entry using temporary hard references.
         *

         * This implementation uses hashEntry on the main map.
         *
         * @return the hashcode of the entry
         */
        public int hashCode() {
            return parent.hashEntry(getKey(), getValue());
        }

        /**
         * Constructs a reference of the given type to the given referent. The
         * reference is registered with the queue for later purging.
         *
         * @param type
         *            HARD, SOFT or WEAK
         * @param referent
         *            the object to refer to
         * @param hash
         *            the hash code of the key of the mapping; this
         *            number might be different from referent.hashCode() if the
         *            referent represents a value and not a key
         */
        protected <T> Reference<T> toReference(int type, T referent, int hash) {
            switch (type) {
            case SOFT:
                return new SoftRef<T>(hash, referent, parent.queue);
            case WEAK:
                return new WeakRef<T>(hash, referent, parent.queue);
            default:
                throw new Error(
                        "Attempt to create hard reference in ReferenceMap!");
            }
        }

        /**
         * Purges the specified reference
         *
         * @param ref
         *            the reference to purge
         * @return true or false
         */
        boolean purge(Reference ref) {
            boolean r = (parent.keyType > HARD) && (refKey == ref);
            r = r || ((parent.valueType > HARD) && (refValue == ref));
            if (r) {
                if (parent.keyType > HARD) {
                    refKey.clear();
                }
                if (parent.valueType > HARD) {
                    refValue.clear();
                } else if (parent.purgeValues) {
                    setValue(null);
                }
            }
            return r;
        }

        /**
         * Gets the next entry in the bucket.
         *
         * @return the next entry in the bucket
         */
        protected ReferenceEntry<K, V> next() {
            return (ReferenceEntry<K, V>) next;
        }
    }

    // -----------------------------------------------------------------------
    /**
     * The EntrySet iterator.
     */
    static class ReferenceIteratorBase<K, V> {
        /**
         * The parent map
         */
        final AbstractReferenceMap<K, V> parent;

        // These fields keep track of where we are in the table.
        int index;
        ReferenceEntry<K, V> entry;
        ReferenceEntry<K, V> previous;

        // These Object fields provide hard references to the
        // current and next entry; this assures that if hasNext()
        // returns true, next() will actually return a valid element.
        K nextKey;
        V nextValue;
        K currentKey;
        V currentValue;

        int expectedModCount;

        public ReferenceIteratorBase(AbstractReferenceMap<K, V> parent) {
            super();
            this.parent = parent;
            index = (parent.size() != 0 ? parent.data.length : 0);
            // have to do this here! size() invocation above
            // may have altered the modCount.
            expectedModCount = parent.modCount;
        }

        public boolean hasNext() {
            checkMod();
            while (nextNull()) {
                ReferenceEntry<K, V> e = entry;
                int i = index;
                while ((e == null) && (i > 0)) {
                    i--;
                    e = (ReferenceEntry<K, V>) parent.data[i];
                }
                entry = e;
                index = i;
                if (e == null) {
                    currentKey = null;
                    currentValue = null;
                    return false;
                }
                nextKey = e.getKey();
                nextValue = e.getValue();
                if (nextNull()) {
                    entry = entry.next();
                }
            }
            return true;
        }

        private void checkMod() {
            if (parent.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }

        private boolean nextNull() {
            return (nextKey == null) || (nextValue == null);
        }

        protected ReferenceEntry<K, V> nextEntry() {
            checkMod();
            if (nextNull() && !hasNext()) {
                throw new NoSuchElementException();
            }
            previous = entry;
            entry = entry.next();
            currentKey = nextKey;
            currentValue = nextValue;
            nextKey = null;
            nextValue = null;
            return previous;
        }

        protected ReferenceEntry<K, V> currentEntry() {
            checkMod();
            return previous;
        }

        public ReferenceEntry<K, V> superNext() {
            return nextEntry();
        }

        public void remove() {
            checkMod();
            if (previous == null) {
                throw new IllegalStateException();
            }
            parent.remove(currentKey);
            previous = null;
            currentKey = null;
            currentValue = null;
            expectedModCount = parent.modCount;
        }
    }

    /**
     * The EntrySet iterator.
     */
    static class ReferenceEntrySetIterator<K, V> extends
            ReferenceIteratorBase<K, V> implements Iterator<Map.Entry<K, V>> {

        public ReferenceEntrySetIterator(
                AbstractReferenceMap<K, V> abstractReferenceMap) {
            super(abstractReferenceMap);
        }

        public ReferenceEntry<K, V> next() {
            return superNext();
        }

    }

    /**
     * The keySet iterator.
     */
    static class ReferenceKeySetIterator<K, V> extends
            ReferenceIteratorBase<K, V> implements Iterator<K> {

        ReferenceKeySetIterator(AbstractReferenceMap<K, V> parent) {
            super(parent);
        }

        public K next() {
            return nextEntry().getKey();
        }
    }

    /**
     * The values iterator.
     */
    static class ReferenceValuesIterator<K, V> extends
            ReferenceIteratorBase<K, V> implements Iterator<V> {

        ReferenceValuesIterator(AbstractReferenceMap<K, V> parent) {
            super(parent);
        }

        public V next() {
            return nextEntry().getValue();
        }
    }

    /**
     * The MapIterator implementation.
     */
    static class ReferenceMapIterator<K, V> extends ReferenceIteratorBase<K, V>
            implements MapIterator<K, V> {

        protected ReferenceMapIterator(AbstractReferenceMap<K, V> parent) {
            super(parent);
        }

        public K next() {
            return nextEntry().getKey();
        }

        public K getKey() {
            HashEntry<K, V> current = currentEntry();
            if (current == null) {
                throw new IllegalStateException(
                        AbstractHashedMap.GETKEY_INVALID);
            }
            return current.getKey();
        }

        public V getValue() {
            HashEntry<K, V> current = currentEntry();
            if (current == null) {
                throw new IllegalStateException(
                        AbstractHashedMap.GETVALUE_INVALID);
            }
            return current.getValue();
        }

        public V setValue(V value) {
            HashEntry<K, V> current = currentEntry();
            if (current == null) {
                throw new IllegalStateException(
                        AbstractHashedMap.SETVALUE_INVALID);
            }
            return current.setValue(value);
        }
    }

    // -----------------------------------------------------------------------
    // These two classes store the hashCode of the key of
    // of the mapping, so that after they're dequeued a quick
    // lookup of the bucket in the table can occur.

    /**
     * A soft reference holder.
     */
    static class SoftRef<T> extends SoftReference<T> {
        /**
         * the hashCode of the key (even if the reference points to a value)
         */
        private int hash;

        public SoftRef(int hash, T r, ReferenceQueue q) {
            super(r, q);
            this.hash = hash;
        }

        public int hashCode() {
            return hash;
        }
    }

    /**
     * A weak reference holder.
     */
    static class WeakRef<T> extends WeakReference<T> {
        /**
         * the hashCode of the key (even if the reference points to a value)
         */
        private int hash;

        public WeakRef(int hash, T r, ReferenceQueue q) {
            super(r, q);
            this.hash = hash;
        }

        public int hashCode() {
            return hash;
        }
    }

    // -----------------------------------------------------------------------
    /**
     * Replaces the superclass method to store the state of this class.
     *

     * Serialization is not one of the JDK's nicest topics. Normal serialization
     * will initialise the superclass before the subclass. Sometimes however,
     * this isn't what you want, as in this case the put() method
     * on read can be affected by subclass state.
     *

     * The solution adopted here is to serialize the state data of this class in
     * this protected method. This method must be called by the
     * writeObject() of the first serializable subclass.
     *

     * Subclasses may override if they have a specific field that must be
     * present on read before this implementation will work. Generally, the read
     * determines what must be serialized here, if anything.
     *
     * @param out
     *            the output stream
     */
    protected void doWriteObject(ObjectOutputStream out) throws IOException {
        out.writeInt(keyType);
        out.writeInt(valueType);
        out.writeBoolean(purgeValues);
        out.writeFloat(loadFactor);
        out.writeInt(data.length);
        for (MapIterator it = mapIterator(); it.hasNext();) {
            out.writeObject(it.next());
            out.writeObject(it.getValue());
        }
        out.writeObject(null); // null terminate map
        // do not call super.doWriteObject() as code there doesn't work for
        // reference map
    }

    /**
     * Replaces the superclassm method to read the state of this class.
     *

     * Serialization is not one of the JDK's nicest topics. Normal serialization
     * will initialise the superclass before the subclass. Sometimes however,
     * this isn't what you want, as in this case the put() method
     * on read can be affected by subclass state.
     *

     * The solution adopted here is to deserialize the state data of this class
     * in this protected method. This method must be called by the
     * readObject() of the first serializable subclass.
     *

     * Subclasses may override if the subclass has a specific field that must be
     * present before put() or calculateThreshold()
     * will work correctly.
     *
     * @param in
     *            the input stream
     */
    protected void doReadObject(ObjectInputStream in) throws IOException,
            ClassNotFoundException {
        this.keyType = in.readInt();
        this.valueType = in.readInt();
        this.purgeValues = in.readBoolean();
        this.loadFactor = in.readFloat();
        int capacity = in.readInt();
        init();
        data = new HashEntry[capacity];
        while (true) {
            K key = (K) in.readObject();
            if (key == null) {
                break;
            }
            V value = (V) in.readObject();
            put(key, value);
        }
        threshold = calculateThreshold(data.length, loadFactor);
        // do not call super.doReadObject() as code there doesn't work for
        // reference map
    }

}


package org.intellimate.izou.sdk.frameworks.presence.provider.template;

import org.intellimate.izou.events.EventModel;
import org.intellimate.izou.sdk.Context;
import org.intellimate.izou.sdk.events.EventsController;
import org.intellimate.izou.sdk.frameworks.presence.provider.Presence;
import org.intellimate.izou.sdk.frameworks.presence.provider.PresenceHelper;
import org.intellimate.izou.sdk.frameworks.presence.provider.PresenceIndicatorLevel;
import org.intellimate.izou.sdk.frameworks.presence.provider.PresenceResourceProvider;
import org.intellimate.izou.sdk.frameworks.presence.resources.PresenceResource;

import java.util.ArrayList;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * the base template class for addons able to conclude about constant presence.
 * <p>
 * If the addon is based on encounters with the user and not able to conclude constant presence from the information,
 * it should pass not extend this class, if not (for example if it monitors wifi) it can. They can just fire the
 * Presence-Event on encountering.
 * It is expected that addons extending this class are pretty sure that the user is around and not a random person.
 * </p>
 * @author LeanderK
 * @version 1.0
 */
public abstract class PresenceConstant extends EventsController implements PresenceHelper, PresenceResourceProvider {
    private boolean present = false;
    private  boolean globalPresent = false;
    private boolean globalStrictPresent = false;
    private final boolean strict;
    private final PresenceIndicatorLevel level;
    /**
     * if the PresenceIndicatorLevel is under Weak, it will control events if it is still (one of) the most Vague
     */
    private AtomicBoolean mostVague = new AtomicBoolean(true);

    /**
     * @param context the context
     * @param ID      the ID
     * @param strict  whether it is strict (very high probability that the user is around)
     * @param level   the level
     *
     */
    public PresenceConstant(Context context, String ID, boolean strict, PresenceIndicatorLevel level) {
        super(context, ID);
        this.strict = strict;
        this.level = level;
    }

    /**
     * Controls whether the fired Event should be dispatched to all the listeners. This method should execute quickly
     *
     * @param eventModel the Event
     * @return true if it should dispatch, false if not
     */
    @Override
    public boolean controlEvents(EventModel eventModel) {
        if (level.compareTo(PresenceIndicatorLevel.WEAK) >= 0) {
            return present;
        } else //noinspection SimplifiableIfStatement
            if (level.compareTo(PresenceIndicatorLevel.WEAK) < 0 && mostVague.get()) {
            return present;
        } else {
            return true;
        }
    }

    /**
     * true if the addon can guarantee that the user is around, false if not
     *
     * @return true if it can guarantee it, false if not
     */
    @Override
    public boolean isStrict() {
        return strict;
    }

    /**
     * whether it is known that the user caused the presence
     *
     * @return true if known, false if not
     */
    @Override
    public boolean isKnown() {
        return true;
    }

    /**
     * gets the PresenceIndicatorLevel of the addon (mainly used for communication between presence-providing addons)
     *
     * @return the Level
     */
    @Override
    public PresenceIndicatorLevel getLevel() {
        return level;
    }

    /**
     * returns true if the user might be/is present
     *
     * @return true if present
     */
    @Override
    public boolean isPresent() {
        return present;
    }

    /**
     * when this method is called the present-status was changed
     *
     * @param present true if present, false if not
     */
    @Override
    public void setGlobalPresent(boolean present) {
        globalPresent = present;
    }

    /**
     * returns true if the user is first encountered in the current mode
     */
    @Override
    public boolean isFirstEncountering() {
        if (strict && !globalStrictPresent) {
            return true;
        } else if (!globalPresent) {
            return true;
        }
        return false;
    }

    /**
     * when this method is called, the strict-present status was changed
     *
     * @param present true if present, false if not
     */
    @Override
    public void setGlobalStrictPresent(boolean present) {
        globalStrictPresent = present;
    }

    /**
     * sets the presence
     * @param present true for presence, false if not
     */
    public void setPresence(boolean present) {
        if (this.present == present)
            return;
        this.present = present;
        updateVague();
        if (present) {
            firePresence(true);
        } else {
            fireLeaving();
        }
    }

    /**
     * updates the boolean whether it is the mode vague
     */
    private void updateVague() {
        generateResource(PresenceResource.ID)
            .orElse(CompletableFuture.completedFuture(new ArrayList<>()))
            .thenAccept(list -> mostVague.set(list.stream()
                            .map(Presence::importPresence)
                            .filter(Optional::isPresent)
                            .map(Optional::get)
                            .map(Presence::getLevel)
                            .noneMatch(level -> level.compareTo(getLevel()) > 0))
            );
    }
}


/**
 *
 * Copyright 2003-2007 Jive Software.
 *
 * All rights reserved. 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.
 */

package org.jivesoftware.smack;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.xmpp.packet.Message;
import org.xmpp.packet.Message.Type;

/**
 * A chat is a series of messages sent between two users. Each chat has a unique
 * thread ID, which is used to track which messages are part of a particular
 * conversation. Some messages are sent without a thread ID, and some clients
 * don't send thread IDs at all. Therefore, if a message without a thread ID
 * arrives it is routed to the most recently created Chat with the message
 * sender.
 *
 * @author Matt Tucker
 */
public class Chat {

    private ChatManager chatManager;
    private String threadID;
    private String participant;
    private final Set<MessageListener> listeners = new CopyOnWriteArraySet<MessageListener>();

    /**
     * Creates a new chat with the specified user and thread ID.
     *
     * @param chatManager
     *            the chatManager the chat will use.
     * @param participant
     *            the user to chat with.
     * @param threadID
     *            the thread ID to use.
     */
    Chat(ChatManager chatManager, String participant, String threadID) {
        this.chatManager = chatManager;
        this.participant = participant;
        this.threadID = threadID;
    }

    /**
     * Returns the thread id associated with this chat, which corresponds to the
     * <tt>thread</tt> field of XMPP messages. This method may return
     * <tt>null</tt> if there is no thread ID is associated with this Chat.
     *
     * @return the thread ID of this chat.
     */
    public String getThreadID() {
        return threadID;
    }

    /**
     * Returns the name of the user the chat is with.
     *
     * @return the name of the user the chat is occuring with.
     */
    public String getParticipant() {
        return participant;
    }

    /**
     * Sends the specified text as a message to the other chat participant. This
     * is a convenience method for:
     *
     * <pre>
     * Message message = chat.createMessage();
     * message.setBody(messageText);
     * chat.sendMessage(message);
     * </pre>
     *
     * @param text
     *            the text to send.
     * @throws XMPPException
     *             if sending the message fails.
     */
    public void sendMessage(String text) throws XMPPException {
        Message message = new Message();
        message.setTo(participant);
        message.setType(Type.chat);
        message.setThread(threadID);
        message.setBody(text);
        chatManager.sendMessage(this, message);
    }

    /**
     * Sends a message to the other chat participant. The thread ID, recipient,
     * and message type of the message will automatically set to those of this
     * chat.
     *
     * @param message
     *            the message to send.
     * @throws XMPPException
     *             if an error occurs sending the message.
     */
    public void sendMessage(Message message) throws XMPPException {
        // Force the recipient, message type, and thread ID since the user
        // elected
        // to send the message through this chat object.
        message.setTo(participant);
        message.setType(Message.Type.chat);
        message.setThread(threadID);
        chatManager.sendMessage(this, message);
    }

    /**
     * Adds a packet listener that will be notified of any new messages in the
     * chat.
     *
     * @param listener
     *            a packet listener.
     */
    public void addMessageListener(MessageListener listener) {
        if (listener == null) {
            return;
        }
        // TODO these references should be weak.
        listeners.add(listener);
    }

    public void removeMessageListener(MessageListener listener) {
        listeners.remove(listener);
    }

    /**
     * Returns an unmodifiable collection of all of the listeners registered
     * with this chat.
     *
     * @return an unmodifiable collection of all of the listeners registered
     *         with this chat.
     */
    public Collection<MessageListener> getListeners() {
        return Collections.unmodifiableCollection(listeners);
    }

    /**
     * Creates a {@link org.jivesoftware.smack.PacketCollector} which will
     * accumulate the Messages for this chat. Always cancel PacketCollectors
     * when finished with them as they will accumulate messages indefinitely.
     *
     * @return the PacketCollector which returns Messages for this chat.
     */
    public PacketCollector createCollector() {
        return chatManager.createPacketCollector(this);
    }

    /**
     * Delivers a message directly to this chat, which will add the message to
     * the collector and deliver it to all listeners registered with the Chat.
     * This is used by the Connection class to deliver messages without a thread
     * ID.
     *
     * @param message
     *            the message.
     */
    void deliver(Message message) {
        // Because the collector and listeners are expecting a thread ID with
        // a specific value, set the thread ID on the message even though it
        // probably never had one.
        message.setThread(threadID);

        for (MessageListener listener : listeners) {
            listener.processMessage(this, message);
        }
    }

    @Override
    public String toString() {
        return "Chat [(participant=" + participant + "), (thread=" + threadID
                + ")]";
    }

    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 31 + threadID.hashCode();
        hash = hash * 31 + participant.hashCode();
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Chat
                && threadID.equals(((Chat) obj).getThreadID())
                && participant.equals(((Chat) obj).getParticipant());
    }
}