private void insertValue(final Node<K,V> newNode, final String thread_id)
            throws IllegalArgumentException {

        Node<K,V> node = rootNode[VALUE];

        while (true) {
            int cmp = compare(Node.ADDED, newNode.getData(VALUE), node.getStatus(), node.getData(VALUE), VALUE);

            if (cmp == 0)
            {
                if (nextEqualValid(getFloorEqualNode(node, VALUE), VALUE, thread_id) != null)
                {
                    String debug_message = "Cannot store a duplicate value (\"" + newNode.getData(VALUE)
                                 + "\") in this Map. Value already exists for key " + node.getKey();
                    log.debug (debug_message);

                    throw new IllegalArgumentException(debug_message);
                 }

                if (node.is(Node.ADDED, null))
                    throw new ConcurrentModificationException();

                if (node.getRight(VALUE) != null) {
                    node = node.getRight(VALUE);
                } else if (node.getLeft(VALUE) != null) {
                    node = node.getLeft(VALUE);
                } else {
                    node.setRight(newNode, VALUE);
                    newNode.setParent(node, VALUE);
                    doRedBlackInsert(newNode, VALUE);

                    break;
                }
            }
            else if (cmp < 0) {
                if (node.getLeft(VALUE) != null) {
                    node = node.getLeft(VALUE);
                } else {
                    node.setLeft(newNode, VALUE);
                    newNode.setParent(node, VALUE);
                    doRedBlackInsert(newNode, VALUE);

                    break;
                }
            } else {    // cmp > 0
                if (node.getRight(VALUE) != null) {
                    node = node.getRight(VALUE);
                } else {
                    node.setRight(newNode, VALUE);
                    newNode.setParent(node, VALUE);
                    doRedBlackInsert(newNode, VALUE);

                    break;
                }
            }
        }
    }

insert a node by its value

@param newNode the node to be inserted

@throws IllegalArgumentException if the node already exists
in the value mapping


@Override
    public boolean containsKey(final Object key)
            throws ClassCastException, NullPointerException {

        checkKey(key);

        return lookupValid(key, KEY, getCurrentThreadId()) != null;
    }

@ Override public boolean containsKey ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return lookupValid ( key , KEY , getCurrentThreadId ( ) ) != null ; }

Returns true if this map contains a mapping for the specified
key.

@param key key whose presence in this map is to be tested.

@return true if this map contains a mapping for the specified
key.

@throws ClassCastException if the key is of an inappropriate
type for this map.
@throws NullPointerException if the key is null

Returns true if this map contains a mapping for the specified key .


@Override
    public boolean containsValue(final Object value) {

        checkValue(value);

        return lookupValid(value, VALUE, getCurrentThreadId()) != null;
    }

@ Override public boolean containsValue ( final Object value ) { checkValue ( value ) ; return lookupValid ( value , VALUE , getCurrentThreadId ( ) ) != null ; }

Returns true if this map maps one or more keys to the
specified value.

@param value value whose presence in this map is to be tested.

@return true if this map maps one or more keys to the specified
value.

Returns true if this map maps one or more keys to the specified value .


@Override
    public V get(final Object key)
            throws ClassCastException, NullPointerException {

        checkKey(key);

        return (V)doGet(key, KEY);
    }

@ Override public V get ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return ( V ) doGet ( key , KEY ) ; }

Returns the value to which this map maps the specified
key. Returns null if the map contains no mapping for this key.

@param key key whose associated value is to be returned.

@return the value to which this map maps the specified key, or
null if the map contains no mapping for this key.

@throws ClassCastException if the key is of an inappropriate
type for this map.
@throws NullPointerException if the key is null

Returns the value to which this map maps the specified key . Returns null if the map contains no mapping for this key .


@Override
    public V remove(final Object key)
	throws ConcurrentModificationException {

        checkKey(key);

        return (V)doRemove(key, KEY);
    }

@ Override public V remove ( final Object key ) throws ConcurrentModificationException { checkKey ( key ) ; return ( V ) doRemove ( key , KEY ) ; }

Removes the mapping for this key from this map if present

@param key key whose mapping is to be removed from the map.

@return previous value associated with specified key, or null
if there was no mapping for key.


@Override
    public void clear() {

        if (auto_commit)
        {
            modify();

            nodeCount   = 0;
            rootNode[KEY]   = null;
            rootNode[VALUE] = null;
        }
        else
        {
            String thread_id = getCurrentThreadId();
            ArrayList<Entry<K,V>> list = new ArrayList<Entry<K,V>>(entrySet());
            for (Iterator<Entry<K,V>> i = list.iterator(); i.hasNext(); ) {
                Node<K,V> node = (Node<K,V>)i.next();
                if (node.is(Node.ADDED, thread_id))
                    doRedBlackDelete(node);
                else {
                    node.setStatus(Node.DELETED, thread_id);
                }
            }
        }
    }

@ Override public void clear ( ) { if ( auto_commit ) { modify ( ) ; nodeCount = 0 ; rootNode [ KEY ] = null ; rootNode [ VALUE ] = null ; } else { String thread_id = getCurrentThreadId ( ) ; ArrayList < Entry < K , V > > list = new ArrayList < Entry < K , V > > ( entrySet ( ) ) ; for ( Iterator < Entry < K , V > > i = list . iterator ( ) ; i . hasNext ( ) ; ) { Node < K , V > node = ( Node < K , V > ) i . next ( ) ; if ( node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else { node . setStatus ( Node . DELETED , thread_id ) ; } } } }


@Override
    public Set<K> keySet() {

        if (setOfKeysByKey == null) {
            setOfKeysByKey = new AbstractFilterableSet<K>() {

                @Override
                public Iterator<K> iterator() {

                    return new TransactionalBidiTreeMapIterator<K>(KEY) {

                        @Override
                        protected K doGetNext() {
                            return (K)lastReturnedNode.getData(KEY);
                        }
                    };
                }

                @Override
                public int size() {
                    return TransactionalBidiTreeMap.this.size();
                }

                @Override
                public boolean contains(Object o) {
                    return containsKey(o);
                }

                @Override
                public boolean remove(Object o) {

                    int oldNodeCount = nodeCount;

                    TransactionalBidiTreeMap.this.remove(o);

                    return nodeCount != oldNodeCount;
                }

                @Override
                public void clear() {
                    TransactionalBidiTreeMap.this.clear();
                }
            };
        }

        return setOfKeysByKey;
    }

@ Override public Set < K > keySet ( ) { if ( setOfKeysByKey == null ) { setOfKeysByKey = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( KEY ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldNodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByKey ; }

Returns a set view of the keys contained in this map.  The set
is backed by the map, so changes to the map are reflected in
the set, and vice-versa. If the map is modified while an
iteration over the set is in progress, the results of the
iteration are undefined. The set supports element removal,
which removes the corresponding mapping from the map, via the
Iterator.remove, Set.remove, removeAll, retainAll, and clear
operations.  It does not support the add or addAll operations.

@return a set view of the keys contained in this map.

Returns a set view of the keys contained in this map . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations .


@Override
    public Collection<V> values() {

        if (collectionOfValuesByKey == null) {
            collectionOfValuesByKey = new AbstractFilterableCollection<V>() {

                @Override
                public Iterator<V> iterator() {

                    return new TransactionalBidiTreeMapIterator<V>(KEY) {

                        @Override
                        protected V doGetNext() {
                            return (V)lastReturnedNode.getData(VALUE);
                        }
                    };
                }

                @Override
                public int size() {
                    return TransactionalBidiTreeMap.this.size();
                }

                @Override
                public boolean contains(Object o) {
                    return containsValue(o);
                }

                @Override
                public boolean remove(Object o) {

                    int oldNodeCount = nodeCount;

                    removeValue(o);

                    return nodeCount != oldNodeCount;
                }

                @Override
                public boolean removeAll(Collection<?> c) {

                    boolean  modified = false;
                    Iterator<?> iter     = c.iterator();

                    while (iter.hasNext()) {
                        if (removeValue(iter.next()) != null) {
                            modified = true;
                        }
                    }

                    return modified;
                }

                @Override
                public void clear() {
                    TransactionalBidiTreeMap.this.clear();
                }
            };
        }

        return collectionOfValuesByKey;
    }

@ Override public Collection < V > values ( ) { if ( collectionOfValuesByKey == null ) { collectionOfValuesByKey = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( KEY ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldNodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByKey ; }

Returns a collection view of the values contained in this
map. The collection is backed by the map, so changes to the map
are reflected in the collection, and vice-versa. If the map is
modified while an iteration over the collection is in progress,
the results of the iteration are undefined. The collection
supports element removal, which removes the corresponding
mapping from the map, via the Iterator.remove,
Collection.remove, removeAll, retainAll and clear operations.
It does not support the add or addAll operations.

@return a collection view of the values contained in this map.

Returns a collection view of the values contained in this map . The collection is backed by the map so changes to the map are reflected in the collection and vice - versa . If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined . The collection supports element removal which removes the corresponding mapping from the map via the Iterator . remove Collection . remove removeAll retainAll and clear operations . It does not support the add or addAll operations .


public FilterableSet<Entry<K,V>> allEntrySet() {

        if (setOfAllEntries == null) {
            setOfAllEntries = new AbstractFilterableSet<Entry<K,V>>() {

                @Override
                public Iterator<Entry<K,V>> iterator() {

                    return new TransactionalBidiTreeMapIterator<Entry<K,V>>(KEY) {

                        @Override
                        protected Entry<K,V> doGetNext() {
                            return lastReturnedNode;
                        }
                        @Override
                        protected Node<K,V> getNextValidNode(Node<K,V> node, String thread_id) {
                            return node;
                        }
                    };
                }

                //cannot have contains or remove methods
                //as we have ALL the nodes and so may have duplicates
                //which are in the provess of being deleted
                @Override
                public boolean contains(Object o) {
                    throw new UtilsjException("method not supported");
                }

                @Override
                public boolean remove(Object o) {
                    throw new UtilsjException("method not supported");
                }

                @Override
                public int size() {
                    return TransactionalBidiTreeMap.this.size(true);
                }

                @Override
                public void clear() {
                    TransactionalBidiTreeMap.this.clear();
                }
            };
        }

        return setOfAllEntries;
    }

It is very rare that this method would be required. You probably
want to use entrySet instead. This method returns all Entry's
in this Map no matter what its transactional status.

Returns a set view of the mappings contained in this map. Each
element in the returned set is a Map.Entry. The set is backed
by the map, so changes to the map are reflected in the set, and
vice-versa.  If the map is modified while an iteration over the
set is in progress, the results of the iteration are
undefined. The set supports element removal, which removes the
corresponding mapping from the map, via the Iterator.remove,
Set.remove, removeAll, retainAll and clear operations.  It does
not support the add or addAll operations.

@return a set view of the mappings contained in this map.

It is very rare that this method would be required . You probably want to use entrySet instead . This method returns all Entry s in this Map no matter what its transactional status .


public final void copyEntries(TransactionalBidiTreeMap<K,V> new_map)
    {
        K key;
        V val;
        int transaction_status;
        String transaction_id;

        new_map.setAutoCommit(isAutoCommit());

        if (!isAutoCommit())
        {
            // Do committed and deleted first
            for(Iterator<Entry<K,V>> i = allEntrySet().iterator(); i.hasNext(); ) {
                TransactionalBidiTreeMap.Node<K,V> entry = (TransactionalBidiTreeMap.Node<K,V>)i.next();
                key=entry.getKey();
                val=entry.getValue();
                transaction_status=entry.getStatus();
                transaction_id=entry.getTransactionId();

                if (transaction_status != TransactionalBidiTreeMap.Node.ADDED)
                {
                    try
                    {
                        // Put the value against the key
                        new_map.put(key, val);

                        // As the transaction status is deleted or no change then we need to commit the entry now.
                        new_map.commit();
                    }
                    catch (Exception e) {} // Duplicate keys can be ignored, this means we already have the value

                    try
                    {
                        // If transaction status is deleted we need to now attach to the transaction id and remove.
                        if (transaction_status == TransactionalBidiTreeMap.Node.DELETED)
                        {
                            new_map.attach(transaction_id);
                            new_map.remove(key);
                        }
                    }
                    catch (Exception e) {} // The entry may have already been deleted

                    // Finally detach
                    new_map.detach();
                }
            }

            // Then do added
            for(Iterator<Entry<K,V>> i = allEntrySet().iterator(); i.hasNext(); ) {
                TransactionalBidiTreeMap.Node<K,V> entry = (TransactionalBidiTreeMap.Node<K,V>)i.next();
                key=entry.getKey();
                val=entry.getValue();
                transaction_status=entry.getStatus();
                transaction_id=entry.getTransactionId();

                if (transaction_status == TransactionalBidiTreeMap.Node.ADDED)
                {
                    // As the transaction status is added then attach to the transaction id before putting.
                    new_map.attach(transaction_id);

                    try
                    {
                        // Put the value against the key
                        new_map.put(key, val);
                    }
                    catch (Exception e) {} // Duplicate keys can be ignored, this means we already have the value

                    // Finally detach
                    new_map.detach();
                }
            }
        }
        else
        {
            for(Iterator<Entry<K,V>> i = allEntrySet().iterator(); i.hasNext(); ) {
                TransactionalBidiTreeMap.Node<K,V> entry = (TransactionalBidiTreeMap.Node<K,V>)i.next();
                key=entry.getKey();
                val=entry.getValue();

                try
                {
                    new_map.put(key, val);
                }
                catch (Exception e) {} // Duplicate keys can be ignored, this means we already have the value
            }
        }
    }

Copy all entries including transaction statuses from this map into the supplied map.
Do not use this method unless you know exactly what you are doing. The auto commit flag
of the supplied map may be changed as a result of calling this method, check that this is
valid first.

Copy all entries including transaction statuses from this map into the supplied map . Do not use this method unless you know exactly what you are doing . The auto commit flag of the supplied map may be changed as a result of calling this method check that this is valid first .


protected synchronized void deleteExpiredEntries() {
        // Check if expiration is turned on.
        if (maxLifetime <= 0) {
            return;
        }

        // Remove all old entries. To do this, we remove objects from the end
        // of the linked list until they are no longer too old. We get to avoid
        // any hash lookups or looking at any more objects than is strictly
        // neccessary.
        LinkedListNode node = ageList.getLast();
        // If there are no entries in the age list, return.
        if (node == null) {
            return;
        }

        // Determine the expireTime, which is the moment in time that elements
        // should expire from cache. Then, we can do an easy check to see
        // if the expire time is greater than the expire time.
        long expireTime = System.currentTimeMillis() - maxLifetime;

        while (expireTime > node.timestamp) {
            if (remove(node.object, true) == null) {
                log.warn("Error attempting to remove(" + node.object.toString()
                        + ") - cacheObject not found in cache!");
                // remove from the ageList
                node.remove();
            }

            // Get the next node.
            node = ageList.getLast();
            // If there are no more entries in the age list, return.
            if (node == null) {
                return;
            }
        }
    }

Clears all entries out of cache where the entries are older than the
maximum defined age.

Clears all entries out of cache where the entries are older than the maximum defined age .


protected synchronized void cullCache() {
        // Check if a max cache size is defined.
        if (maxCacheSize < 0) {
            return;
        }

        // See if the cache is too big. If so, clean out cache until it's 10%
        // free.
        if (map.size() > maxCacheSize) {
            // First, delete any old entries to see how much memory that frees.
            deleteExpiredEntries();
            // Next, delete the least recently used elements until 10% of the
            // cache
            // has been freed.
            int desiredSize = (int) (maxCacheSize * .90);
            for (int i = map.size(); i > desiredSize; i--) {
                // Get the key and invoke the remove method on it.
                if (remove(lastAccessedList.getLast().object, true) == null) {
                    log.warn("Error attempting to cullCache with remove("
                            + lastAccessedList.getLast().object.toString()
                            + ") - cacheObject not found in cache!");
                    lastAccessedList.getLast().remove();
                }
            }
        }
    }

Removes the least recently used elements if the cache size is greater
than or equal to the maximum allowed size until the cache is at least 10%
empty.

Removes the least recently used elements if the cache size is greater than or equal to the maximum allowed size until the cache is at least 10% empty .


protected void activate(Map<String, Object> props) {
		// Get the properties from the console.
		sharedSecret = toString(props.get("sharedSecret"),
				"e2KS54H35j6vS5Z38nK40");
		hostname = toString(props.get("hostname"), "localhost");
		LOGGER.info(" Trusted hostname: " + hostname);
		port = toInteger(props.get("port"), 80);
		LOGGER.info("Trusted port: " + port);
	}

protected
void
activate
(
Map
<
String
,
Object
>
props
)
{
// Get the properties from the console.
sharedSecret
=
toString
(
props
.
get
(
"sharedSecret"
)
,
"e2KS54H35j6vS5Z38nK40"
)
;
hostname
=
toString
(
props
.
get
(
"hostname"
)
,
"localhost"
)
;
LOGGER
.
info
(
" Trusted hostname: "
+
hostname
)
;
port
=
toInteger
(
props
.
get
(
"port"
)
,
80
)
;
LOGGER
.
info
(
"Trusted port: "
+
port
)
;
}

When the bundle gets activated we retrieve the OSGi properties.

@param context

When the bundle gets activated we retrieve the OSGi properties .


public Optional<PlayerRequest> getPlayerRequest(String playlistName, boolean permanent) {
        return getPlaylist(playlistName)
                .map(playlist -> PlayerRequest.createPlayerRequest(playlist, permanent, player, capabilities, context, identifiable));
    }

public Optional < PlayerRequest > getPlayerRequest ( String playlistName , boolean permanent ) { return getPlaylist ( playlistName ) . map ( playlist -> PlayerRequest . createPlayerRequest ( playlist , permanent , player , capabilities , context , identifiable ) ) ; }

asks the player for more information about the specified playlist and creates a PlayerRequest with the answer.
@param playlistName the name of the Playlist
@param permanent true means the player can play indefinitely, but only if no one is currently using audio as
permanent. It will also not block. false is limited to 10 minutes playback, but will block.
@return the optional PlayerRequest

asks the player for more information about the specified playlist and creates a PlayerRequest with the answer .


public static DefaultRosterStore init(final File baseDir) {
        DefaultRosterStore store = new DefaultRosterStore(baseDir);
        if (store.setRosterVersion("")) {
            return store;
        } else {
            return null;
        }
    }

public static DefaultRosterStore init ( final File baseDir ) { DefaultRosterStore store = new DefaultRosterStore ( baseDir ) ; if ( store . setRosterVersion ( "" ) ) { return store ; } else { return null ; } }

Creates a new roster store on disk

@param baseDir
The directory to create the store in. The directory should be
empty
@return A {@link DefaultRosterStore} instance if successful,
null else.


public static DefaultRosterStore open(final File baseDir) {
        DefaultRosterStore store = new DefaultRosterStore(baseDir);
        String s = store.readFile(store.getVersionFile());
        if (s != null && s.startsWith(STORE_ID + "\n")) {
            return store;
        } else {
            return null;
        }
    }

public static DefaultRosterStore open ( final File baseDir ) { DefaultRosterStore store = new DefaultRosterStore ( baseDir ) ; String s = store . readFile ( store . getVersionFile ( ) ) ; if ( s != null && s . startsWith ( STORE_ID + "\n" ) ) { return store ; } else { return null ; } }

Opens a roster store

@param baseDir
The directory containing the roster store.
@return A {@link DefaultRosterStore} instance if successful,
null else.


public static Collection<InetAddress> scanRange(InetAddress addr, int count, int msTimeout) {
    Collection<InetAddress> addresses = new ArrayList<InetAddress>();
    Collection<InetAddress> result = new ArrayList<InetAddress>();
    if (addr == null) {
      try {
	addresses.addAll(localhostNetworkAddresses());
      } catch (Exception e) {
	throw new FireRESTException(e); // Should not happen
      }
    } else {
      addresses.add(addr);
    }

    for (InetAddress a: addresses) {
      if (a instanceof Inet4Address) {
	InetAddress start = subnetAddress0(a, 24);
	result.addAll(scanRangeCore(start, count, msTimeout));
      }
    }

    return result;
  }

public
static
Collection
<
InetAddress
>
scanRange
(
InetAddress
addr
,
int
count
,
int
msTimeout
)
{
Collection
<
InetAddress
>
addresses
=
new
ArrayList
<
InetAddress
>
(
)
;
Collection
<
InetAddress
>
result
=
new
ArrayList
<
InetAddress
>
(
)
;
if
(
addr
==
)
{
try
{
addresses
.
addAll
(
localhostNetworkAddresses
(
)
)
;
}
catch
(
Exception
e
)
{
throw
new
FireRESTException
(
e
)
;
// Should not happen
}
}
else
{
addresses
.
add
(
addr
)
;
}
for
(
InetAddress
a
:
addresses
)
{
if
(
a
instanceof
Inet4Address
)
{
InetAddress
start
=
subnetAddress0
(
a
,
24
)
;
result
.
addAll
(
scanRangeCore
(
start
,
count
,
msTimeout
)
)
;
}
}
return
result
;
}

Scan a range of InetAddresses starting with the given address

@param start starting address of search; null implies subnetAddress0(null,24)
@param count number of addresses in range
@param msTimeout maximum time to wait for each host


public static InetAddress subnetAddress0(InetAddress addr, int subnetBits) {
    if (subnetBits < 1 || 32 <= subnetBits) {
      throw new FireRESTException("Expected subnetBits 1..31");
    }
    long mask = 1;
    for (int i = 0; i < 32; i++) {
      mask <<= 1;
      mask |= i < subnetBits ? 1 : 0;
    }
    long host0 = asLongAddress(addr) & mask;
    try {
      return asInetAddress(host0);
    } catch (UnknownHostException e) {
      throw new FireRESTException(e);
    }
  }

public
static
InetAddress
subnetAddress0
(
InetAddress
addr
,
int
subnetBits
)
{
if
(
subnetBits
<
1
||
32
<=
subnetBits
)
{
throw
new
FireRESTException
(
"Expected subnetBits 1..31"
)
;
}
long
mask
=
1
;
for
(
int
i
=
0
;
i
<
32
;
i
++
)
{
mask
<<=
1
;
mask
|=
i
<
subnetBits
1
:
0
;
}
long
host0
=
asLongAddress
(
addr
)
&
mask
;
try
{
return
asInetAddress
(
host0
)
;
}
catch
(
UnknownHostException
e
)
{
throw
new
FireRESTException
(
e
)
;
}
}

Return first address on subnet containing given address

@param addr any machine in subnet
@param subnetBits the number of bits in subnet mask. Many small networks use 24.
@return first address on subnet. E.g., subnetAddress(10.0.1.88, 25) -> 10.0.1.0


public HashMap<String, Object> export() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(nameDescriptor, name);
        data.put(artistDescriptor, artist);
        data.put(albumDescriptor, albumDescriptor);
        data.put(albumCoverDescriptor, albumCover);
        data.put(albumCoverFormatDescriptor, albumCoverFormatDescriptor);
        data.put(dataDescriptor, this.data);
        data.put(yearDescriptor, this.year);
        data.put(genreDescriptor, this.genre);
        data.put(durationDescriptor, this.duration);
        data.put(bmpDescriptor, this.bmp);
        return data;
    }

public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( nameDescriptor , name ) ; data . put ( artistDescriptor , artist ) ; data . put ( albumDescriptor , albumDescriptor ) ; data . put ( albumCoverDescriptor , albumCover ) ; data . put ( albumCoverFormatDescriptor , albumCoverFormatDescriptor ) ; data . put ( dataDescriptor , this . data ) ; data . put ( yearDescriptor , this . year ) ; data . put ( genreDescriptor , this . genre ) ; data . put ( durationDescriptor , this . duration ) ; data . put ( bmpDescriptor , this . bmp ) ; return data ; }

exports the TrackInfo to a Hashmap
@return a HashMap


public static Optional<TrackInfo> importFromHashMap(HashMap<String, Object> hashMap) {
        try {
            String name = (String) hashMap.get(nameDescriptor);
            String album = (String) hashMap.get(albumDescriptor);
            String artist = (String) hashMap.get(artistDescriptor);
            byte[] albumCover = (byte[]) hashMap.get(albumCoverDescriptor);
            String albumCoverFormat = (String) hashMap.get(albumCoverFormatDescriptor);
            String data = (String) hashMap.get(dataDescriptor);
            String year = (String) hashMap.get(yearDescriptor);
            String genre = (String) hashMap.get(genreDescriptor);
            long duration = (Long) hashMap.get(durationDescriptor);
            String bmp = (String) hashMap.get(bmpDescriptor);
            return Optional.of(new TrackInfo(name, artist, album, albumCover, albumCoverFormat, data, year, genre, bmp, duration));
        } catch (ClassCastException e) {
            return Optional.empty();
        }
    }

public static Optional < TrackInfo > importFromHashMap ( HashMap < String , Object > hashMap ) { try { String name = ( String ) hashMap . get ( nameDescriptor ) ; String album = ( String ) hashMap . get ( albumDescriptor ) ; String artist = ( String ) hashMap . get ( artistDescriptor ) ; byte [ ] albumCover = ( byte [ ] ) hashMap . get ( albumCoverDescriptor ) ; String albumCoverFormat = ( String ) hashMap . get ( albumCoverFormatDescriptor ) ; String data = ( String ) hashMap . get ( dataDescriptor ) ; String year = ( String ) hashMap . get ( yearDescriptor ) ; String genre = ( String ) hashMap . get ( genreDescriptor ) ; long duration = ( Long ) hashMap . get ( durationDescriptor ) ; String bmp = ( String ) hashMap . get ( bmpDescriptor ) ; return Optional . of ( new TrackInfo ( name , artist , album , albumCover , albumCoverFormat , data , year , genre , bmp , duration ) ) ; } catch ( ClassCastException e ) { return Optional . empty ( ) ; } }

returns the optional TrackInfo if the HashMap contains no malformed data
@param hashMap the data to import from
@return an optional


protected final void addAllApplications(Set<Class<?>> set){
		for(Class<?> cls:set){
			if(!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers())){
				if(!this.classmap.containsValue(cls)){
					this.classNames.add(cls.getName());
				}
			}
		}
	}

protected final void addAllApplications ( Set < Class < ? > > set ) { for ( Class < ? > cls : set ) { if ( ! cls . isInterface ( ) && ! Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( ! this . classmap . containsValue ( cls ) ) { this . classNames . add ( cls . getName ( ) ) ; } } } }

Adds a set of application at runtime, as in all found applications that can be executed
@param set a set of applications

Adds a set of application at runtime as in all found applications that can be executed


protected int executeApplication(Object svc, String[] args, String orig){
		if(svc!=null && (svc instanceof ExecS_Application)){
			if(svc instanceof Gen_RunScripts){
				//hook for GenRunScripts to get current class map - registered applications
				((Gen_RunScripts)svc).setClassMap(this.classmap);
			}
			if(svc instanceof Gen_ExecJarScripts){
				//hook for Gen_ExecJarScripts to get current class map - registered applications
				((Gen_ExecJarScripts)svc).setClassMap(this.classmap);
			}
			return ((ExecS_Application)svc).executeApplication(ArrayUtils.remove(args, 0));
		}
		else if(svc==null){
			System.err.println("could not create object for class or application name <" + orig + ">");
			return -1;
		}
		else if(!(svc instanceof ExecS_Application)){
			System.err.println("given class or application name <" + orig + "> is not instance of " + ExecS_Application.class.getName());
			return -2;
		}
		else{
			System.err.println("unexpected error processing for class or application name <" + orig + ">");
			return -3;
		}
	}

Executes an application.
@param svc the application, must not be null
@param args original command line arguments
@param orig the original name or class for the application for error messages
@return 0 on success, other than zero on failure (including failure of the executed application)


protected final void printList(){
		ST list = this.stg.getInstanceOf("list");
		list.add("appName", this.appName);
		if(this.classmap.size()>0){
			List<Map<String, String>> l = new ArrayList<>();
			for(String key : this.classmap.keySet()){
				Map<String, String> m = new HashMap<>();
				m.put("key", key);
				m.put("val", this.classmap.get(key).getName());
				l.add(m);
			}
			list.add("classMap", l);
		}
		list.add("className", this.classNames);
		System.out.println(list.render());
	}

protected final void printList ( ) { ST list = this . stg . getInstanceOf ( "list" ) ; list . add ( "appName" , this . appName ) ; if ( this . classmap . size ( ) > 0 ) { List < Map < String , String > > l = new ArrayList <> ( ) ; for ( String key : this . classmap . keySet ( ) ) { Map < String , String > m = new HashMap <> ( ) ; m . put ( "key" , key ) ; m . put ( "val" , this . classmap . get ( key ) . getName ( ) ) ; l . add ( m ) ; } list . add ( "classMap" , l ) ; } list . add ( "className" , this . classNames ) ; System . out . println ( list . render ( ) ) ; }

Prints a list of pre-registered and found applications.

Prints a list of pre - registered and found applications .


protected final void printUsage(){
		ST usage = this.stg.getInstanceOf("usage");
		usage.add("appName", this.appName);
		usage.add("packageFilter", this.packageFilter);
		usage.add("jarFilter", this.jarFilter);
		usage.add("excludedNames", new TreeSet<>(Arrays.asList(new CF().excludedNames)));
		System.out.println(usage.render());
	}

protected final void printUsage ( ) { ST usage = this . stg . getInstanceOf ( "usage" ) ; usage . add ( "appName" , this . appName ) ; usage . add ( "packageFilter" , this . packageFilter ) ; usage . add ( "jarFilter" , this . jarFilter ) ; usage . add ( "excludedNames" , new TreeSet <> ( Arrays . asList ( new CF ( ) . excludedNames ) ) ) ; System . out . println ( usage . render ( ) ) ; }

Prints usage information to standard out.

Prints usage information to standard out .


public static void main(String[] args) {
		ExecS run = new ExecS();
		int ret = run.execute(args);
		System.exit(ret);
	}

public static void main ( String [ ] args ) { ExecS run = new ExecS ( ) ; int ret = run . execute ( args ) ; System . exit ( ret ) ; }

Public main to start the application executor.
@param args command line arguments

Public main to start the application executor .


public static Optional<MuteEvent> createMuteEvent(Identification source, Identification target) {
        if (target == null || target.equals(source))
            return Optional.empty();
        try {
            MuteEvent muteRequest = new MuteEvent(source);
            muteRequest.addResource(new SelectorResource(source, target));
            return Optional.of(muteRequest);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < MuteEvent > createMuteEvent ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { MuteEvent muteRequest = new MuteEvent ( source ) ; muteRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( muteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new MuteEvent
@param source the caller
@param target the target who should start playing
@return the optional StartMusicRequest


public static Optional<MuteEvent> createMuteEvent(Identification source) {
        if (source == null)
            return Optional.empty();
        try {
            MuteEvent muteRequest = new MuteEvent(source);
            return Optional.of(muteRequest);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < MuteEvent > createMuteEvent ( Identification source ) { if ( source == null ) return Optional . empty ( ) ; try { MuteEvent muteRequest = new MuteEvent ( source ) ; return Optional . of ( muteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new MuteEvent, will mute everything
@param source the caller
@return the optional StartMusicRequest

creates a new MuteEvent will mute everything


public GoodwillSchema getSchema(final String schemaName)
    {
        GoodwillSchema schema = knownSchemata.get(schemaName);
        if (schema == null) {
            refreshSchemataCache();
            schema = knownSchemata.get(schemaName);
        }

        return schema;
    }

public GoodwillSchema getSchema ( final String schemaName ) { GoodwillSchema schema = knownSchemata . get ( schemaName ) ; if ( schema == null ) { refreshSchemataCache ( ) ; schema = knownSchemata . get ( schemaName ) ; } return schema ; }

Given a schema name, get the associated GoodwillSchema. This method tries hard to find it, i.e. it will refresh the
cache if the schema is not in the cache.

@param schemaName name of the schema to find
@return GoodwillSchema describing the schema

Given a schema name get the associated GoodwillSchema . This method tries hard to find it i . e . it will refresh the cache if the schema is not in the cache .


public boolean writeFile(File file, List<String> lines){
		if(file.exists()){
			file.delete();
		}
		try {
			FileWriter out = new FileWriter(file);
			for(String s : lines){
				out.write(s);
				out.write(System.getProperty("line.separator"));
			}
			out.close();
			file.setExecutable(true);
		}
		catch (IOException ex) {
			System.err.println(this.getAppName() + ": IO exception while writing to file - " + file + " with message: " + ex.getMessage());
			return false;
		}
		return true;
	}

Writes the given lines to the given file, if possible.
@param file file to write to
@param lines lines to write to the file
@return true if lines where written to the file, false otherwise with errors printed

Writes the given lines to the given file if possible .


protected boolean inExecJar(){
		Class<Gen_ExecJarScripts> clazz = Gen_ExecJarScripts.class;
		String className = clazz.getSimpleName() + ".class";
		String classPath = clazz.getResource(className).toString();
		if (!classPath.startsWith("jar")) {
			System.err.println(this.getAppName() + ": not started in a jar, cannot proceed");
			return false;
		}

		String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
		Manifest manifest;
		try {
			manifest = new Manifest(new URL(manifestPath).openStream());
		}
		catch (IOException ex) {
			System.err.println(this.getAppName() + ": exception while retrieving manifest: " + ex.getMessage());
			return false;
		}
		Attributes attr = manifest.getMainAttributes();
		if(StringUtils.isBlank(attr.getValue("Main-Class"))){
			System.err.println(this.getAppName() + ": no main class in manifest, probably not an executable JAR, cannot continue");
			return false;
		}
		return true;
	}

Tests if the class is run from an executable JAR.
@return true if run from an executable JAR (JAR with Main-Class in manifest), false otherwise with errors printed

Tests if the class is run from an executable JAR .


protected void addOption(ApplicationOption<?> option){
		if(option!=null){
			this.getCli().addOption(option);
			this.options.add(option);
		}
	}

protected void addOption ( ApplicationOption < ? > option ) { if ( option != null ) { this . getCli ( ) . addOption ( option ) ; this . options . add ( option ) ; } }

Adds a new option to CLI parser and option list.
@param option new option, ignored if null

Adds a new option to CLI parser and option list .


public ArrayList<GoodwillSchemaField> getSchema()
    {
        final ArrayList<GoodwillSchemaField> items = new ArrayList<GoodwillSchemaField>(thriftItems.values());

        Collections.sort(items, new Comparator<GoodwillSchemaField>()
        {
            @Override
            public int compare(final GoodwillSchemaField left, final GoodwillSchemaField right)
            {
                return Short.valueOf(left.getId()).compareTo(right.getId());
            }
        });

        return items;
    }

public ArrayList < GoodwillSchemaField > getSchema ( ) { final ArrayList < GoodwillSchemaField > items = new ArrayList < GoodwillSchemaField > ( thriftItems . values ( ) ) ; Collections . sort ( items , new Comparator < GoodwillSchemaField > ( ) { @ Override public int compare ( final GoodwillSchemaField left , final GoodwillSchemaField right ) { return Short . valueOf ( left . getId ( ) ) . compareTo ( right . getId ( ) ) ; } } ) ; return items ; }

Get the schema as a collection of fields.
We guarantee the ordering by field id.

@return the sorted collection of fields

Get the schema as a collection of fields . We guarantee the ordering by field id .


public GoodwillSchemaField getFieldByName(final String name)
    {
        for (final GoodwillSchemaField field : thriftItems.values()) {
            if (field.getName().equals(name)) {
                return field;
            }
        }

        return null;
    }

public GoodwillSchemaField getFieldByName ( final String name ) { for ( final GoodwillSchemaField field : thriftItems . values ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return field ; } } return null ; }

Given a name, return the field matching the name.

@param name GoodwillSchemaField name
@return the GoodwillSchemaField object

Given a name return the field matching the name .


public final static String getPkgName(JarEntry entry){
		if(entry==null){
			return "";
		}
		String s = entry.getName();
		if(s==null){
			return "";
		}
		if(s.length()==0){
			return s;
		}
		if(s.startsWith("/")){
			s = s.substring(1, s.length());
		}
		if(s.endsWith("/")){
			s = s.substring(0, s.length()-1);
		}
		return s.replace('/', '.');
	}

public final static String getPkgName ( JarEntry entry ) { if ( entry == null ) { return "" ; } String s = entry . getName ( ) ; if ( s == null ) { return "" ; } if ( s . length ( ) == 0 ) { return s ; } if ( s . startsWith ( "/" ) ) { s = s . substring ( 1 , s . length ( ) ) ; } if ( s . endsWith ( "/" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) ; } return s . replace ( ' ' , ' ' ) ; }

Returns the package name for a jar entry.
@param entry jar entry to extract package name from
@return empty string on error (entry being null, or no name), package name otherwise

Returns the package name for a jar entry .


private ImmutableMap<C, V> mapContentToValues(
        final ImmutableMap<K, V> base
    ) {
        final ImmutableMap.Builder<C, V> builder = ImmutableMap.builder();
        for (final Entry<K, V> entry : base.entrySet()) {
            builder.put(
                this.key(entry.getKey()),
                entry.getValue()
            );
        }
        return builder.build();
    }

private ImmutableMap < C , V > mapContentToValues ( final ImmutableMap < K , V > base ) { final ImmutableMap . Builder < C , V > builder = ImmutableMap . builder ( ) ; for ( final Entry < K , V > entry : base . entrySet ( ) ) { builder . put ( this . key ( entry . getKey ( ) ) , entry . getValue ( ) ) ; } return builder . build ( ) ; }

Maps the content of the base map to its values.
@param base Base map
@return Map from content of the base map to its values.

Maps the content of the base map to its values .


public static Optional<EventListener> createEventListener(String descriptor, String description,
                                                       String descriptorID, Identifiable identifiable)
                                                                                throws IllegalArgumentException{

        if (!descriptorID.matches("[\\w\\-_]+"))
            throw new IllegalArgumentException("descriptorID: " + descriptorID + " contains illegal characters");
        return
                IdentificationManagerM.getInstance().getIdentification(identifiable)
                .flatMap(id -> Event.createEvent(CommonEvents.Type.NOTIFICATION_TYPE, id, Collections.singletonList(descriptor)))
                .map(event -> new EventListener(event, descriptor, description, descriptorID));
    }

public
static
Optional
<
EventListener
>
createEventListener
(
String
descriptor
,
String
description
,
String
descriptorID
,
Identifiable
identifiable
)
throws
IllegalArgumentException
{
if
(
!
descriptorID
.
matches
(
"[\\w\\-_]+"
)
)
throw
new
IllegalArgumentException
(
"descriptorID: "
+
descriptorID
+
" contains illegal characters"
)
;
return
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
identifiable
)
.
flatMap
(
id
->
Event
.
createEvent
(
CommonEvents
.
Type
.
NOTIFICATION_TYPE
,
id
,
Collections
.
singletonList
(
descriptor
)
)
)
.
map
(
event
->
new
EventListener
(
event
,
descriptor
,
description
,
descriptorID
)
)
;
}

Create the EventListener.

@param descriptor the descriptor of the Event you want to listen to
@param description the description of the descriptor
@param descriptorID an ID for the descriptor (Should contain no special characters, spaces etc.). Only String
which match the regex (\w-_)+ are allowed.
@param identifiable the identifiable which wants to create the EventListener
@return if one of the parameter is null, or unable to to obtain ID
@throws java.lang.IllegalArgumentException if the descriptorID contains illegal characters


public IterativeState<T,R> setState(IterativeState<T,R> new_state)
    {
        IterativeState<T,R> old_state = this.state;
        this.state = new_state;
        return old_state;
    }

public IterativeState < T , R > setState ( IterativeState < T , R > new_state ) { IterativeState < T , R > old_state = this . state ; this . state = new_state ; return old_state ; }

Sets the supplied state for this IterativeCallback.

@return previous state

Sets the supplied state for this IterativeCallback .


public R iterate(final FilterableCollection<? extends T> c)
    {
        initState();

        checkUsed();

        // If collection is decorated with a syncronized wrapper then synchronize the iteration
        if (c instanceof SynchronizedFilterableCollection)
        {
            return SyncUtils.synchronizeRead(c, new Callback<R>() {
                @Override
                protected void doAction()
                {
                    _return(doIteration(c.iterator()));
                }
            });
        }
        return doIteration(c.iterator());
    }


private R doIteration(Iterator<? extends T> it)
    {
        // save the iterator into member variable
        state.i = it;
        state.iterations = 0;

        if (state.do_break == true)
            return state.return_object;

        // do the iteration calling nextobject on each
        while (state.i.hasNext())
        {
            T o = state.i.next();

            if (delegate != null)
                delegate.delegate(o);
            else
                iterateObject(o);

            if (state.do_break == true)
                return state.return_object;
        }
        return state.amended_object;
    }


public static Optional<TrackInfo> getTrackInfo(EventModel eventModel) {
        if (eventModel.getListResourceContainer().containsResourcesFromSource(RESOURCE_ID)) {
            return eventModel
                    .getListResourceContainer()
                    .provideResource(RESOURCE_ID)
                    .stream()
                    .findAny()
                    .flatMap(TrackInfo::importFromResource);
        } else {
            return Optional.empty();
        }
    }

public static Optional < TrackInfo > getTrackInfo ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( RESOURCE_ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( RESOURCE_ID ) . stream ( ) . findAny ( ) . flatMap ( TrackInfo :: importFromResource ) ; } else { return Optional . empty ( ) ; } }

gets the first TrackInfo if found in the EventModel
@param eventModel the EventModel
@return return the optional TrackInfo


public HashMap<String, Long> export() {
        HashMap<String, Long> data = new HashMap<>();
        data.put(lengthDescriptor, length);
        data.put(knownPositionDescriptor, knownPosition);
        data.put(knownMillisTimeStampDescriptor, knownMillisTimeStamp);
        return data;
    }

public HashMap < String , Long > export ( ) { HashMap < String , Long > data = new HashMap <> ( ) ; data . put ( lengthDescriptor , length ) ; data . put ( knownPositionDescriptor , knownPosition ) ; data . put ( knownMillisTimeStampDescriptor , knownMillisTimeStamp ) ; return data ; }

exports the progress
@return a new HashMap


public static Optional<Progress> importResource(ResourceModel resourceModel) {
        Object resource = resourceModel.getResource();
        try {
            //noinspection unchecked
            HashMap<String, Long> data = (HashMap<String, Long>) resource;
            long length = data.get(lengthDescriptor);
            long knownPosition = data.get(knownPositionDescriptor);
            long knownTimestamp = data.get(knownMillisTimeStampDescriptor);
            return Optional.of(new Progress(length, knownPosition, knownTimestamp));
        } catch (Exception e) {
            return Optional.empty();
        }
    }

public
static
Optional
<
Progress
>
importResource
(
ResourceModel
resourceModel
)
{
Object
resource
=
resourceModel
.
getResource
(
)
;
try
{
//noinspection unchecked
HashMap
<
String
,
Long
>
data
=
(
HashMap
<
String
,
Long
>
)
resource
;
long
length
=
data
.
get
(
lengthDescriptor
)
;
long
knownPosition
=
data
.
get
(
knownPositionDescriptor
)
;
long
knownTimestamp
=
data
.
get
(
knownMillisTimeStampDescriptor
)
;
return
Optional
.
of
(
new
Progress
(
length
,
knownPosition
,
knownTimestamp
)
)
;
}
catch
(
Exception
e
)
{
return
Optional
.
empty
(
)
;
}
}

creates a Progress-object from the resourceModel
@param resourceModel the ResourceModel
@return the optional Progress

creates a Progress - object from the resourceModel


public BufferedImage errorImage(String... lines) {
    if (imageBuffer == null || imageBuffer.getWidth() != imageWidth || imageBuffer.getHeight() != imageHeight) {
      imageBuffer = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    }
    Graphics2D g = (Graphics2D) imageBuffer.getGraphics();
    g.setBackground(new Color(64, 32, 32));
    g.setColor(new Color(255, 64, 64));
    g.clearRect(0, 0, imageWidth, imageHeight);
    int maxLen = 0;
    for (String line : lines) {
      if (line != null) {
        for (String innerLine : line.split("\n")) {
          maxLen = Math.max(innerLine.length(), maxLen);
        }
      }
    }
    int padding = 20;
    float sizeForWidth = 1.8f * (imageWidth - padding - padding) / maxLen; // should use TextLayout
    float sizeForHeight = (imageHeight - padding - padding) / lines.length;
    float lineHeight = Math.min(80, Math.max(12, Math.min(sizeForWidth, sizeForHeight)));
    float fontSize = 0.8f * lineHeight;
    Font font = g.getFont().deriveFont(fontSize);
    g.setFont(font);
    float y = fontSize + padding;
    for (String line : lines) {
      if (line != null) {
        g.drawString(line, padding, y);
        y += lineHeight;
      }
    }
    return imageBuffer;
  }

public
BufferedImage
errorImage
(
String
...
lines
)
{
if
(
imageBuffer
==
||
imageBuffer
.
getWidth
(
)
!=
imageWidth
||
imageBuffer
.
getHeight
(
)
!=
imageHeight
)
{
imageBuffer
=
new
BufferedImage
(
imageWidth
,
imageHeight
,
BufferedImage
.
TYPE_INT_RGB
)
;
}
Graphics2D
g
=
(
Graphics2D
)
imageBuffer
.
getGraphics
(
)
;
g
.
setBackground
(
new
Color
(
64
,
32
,
32
)
)
;
g
.
setColor
(
new
Color
(
255
,
64
,
64
)
)
;
g
.
clearRect
(
0
,
0
,
imageWidth
,
imageHeight
)
;
int
maxLen
=
0
;
for
(
String
line
:
lines
)
{
if
(
line
!=
)
{
for
(
String
innerLine
:
line
.
split
(
"\n"
)
)
{
maxLen
=
Math
.
max
(
innerLine
.
length
(
)
,
maxLen
)
;
}
}
}
int
padding
=
20
;
float
sizeForWidth
=
1.8f
*
(
imageWidth
padding
padding
)
/
maxLen
;
// should use TextLayout
float
sizeForHeight
=
(
imageHeight
padding
padding
)
/
lines
.
length
;
float
lineHeight
=
Math
.
min
(
80
,
Math
.
max
(
12
,
Math
.
min
(
sizeForWidth
,
sizeForHeight
)
)
)
;
float
fontSize
=
0.8f
*
lineHeight
;
Font
font
=
g
.
getFont
(
)
.
deriveFont
(
fontSize
)
;
g
.
setFont
(
font
)
;
float
y
=
fontSize
+
padding
;
for
(
String
line
:
lines
)
{
if
(
line
!=
)
{
g
.
drawString
(
line
,
padding
,
y
)
;
y
+=
lineHeight
;
}
}
return
imageBuffer
;
}

Return an red image with the given text auto-sized to fit the current imageWidthximageHeight

@param lines one or more lines of text
@return image

Return an red image with the given text auto - sized to fit the current imageWidthximageHeight


public BufferedImage getImage(URL url) {
    String now = new Date().toString();
    if (url == null) {
      return errorImage(now, "(No image url)");
    }
    try {
      HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
      urlconn.setReadTimeout(msTimeout);
      urlconn.setConnectTimeout(msTimeout);
      urlconn.setRequestMethod("GET");
      urlconn.connect();
      BufferedImage image = ImageIO.read(urlconn.getInputStream());
      if (image == null) {
        return errorImage(now, "(Null image read)");
      }
      imageWidth = image.getWidth();
      imageHeight = image.getHeight();
      return image;
    } catch (SocketTimeoutException e) {
      logger.warn("getImage({}) => {} {}", url, e.getClass().getCanonicalName(), e.getMessage());
      return errorImage(now, msTimeout+"ms TIMEOUT");
    }  catch (Exception e) {
      logger.warn("getImage({}) => {} {}", url, e.getClass().getCanonicalName(), e.getMessage());
      return errorImage(now, "(No image)", url.toString(), e.getMessage());
    }
  }

public
BufferedImage
getImage
(
URL
url
)
{
String
now
=
new
Date
(
)
.
toString
(
)
;
if
(
url
==
)
{
return
errorImage
(
now
,
"(No image url)"
)
;
}
try
{
HttpURLConnection
urlconn
=
(
HttpURLConnection
)
url
.
openConnection
(
)
;
urlconn
.
setReadTimeout
(
msTimeout
)
;
urlconn
.
setConnectTimeout
(
msTimeout
)
;
urlconn
.
setRequestMethod
(
"GET"
)
;
urlconn
.
connect
(
)
;
BufferedImage
image
=
ImageIO
.
read
(
urlconn
.
getInputStream
(
)
)
;
if
(
image
==
)
{
return
errorImage
(
now
,
"(Null image read)"
)
;
}
imageWidth
=
image
.
getWidth
(
)
;
imageHeight
=
image
.
getHeight
(
)
;
return
image
;
}
catch
(
SocketTimeoutException
e
)
{
logger
.
warn
(
"getImage({}) => {} {}"
,
url
,
e
.
getClass
(
)
.
getCanonicalName
(
)
,
e
.
getMessage
(
)
)
;
return
errorImage
(
now
,
msTimeout
+
"ms TIMEOUT"
)
;
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getImage({}) => {} {}"
,
url
,
e
.
getClass
(
)
.
getCanonicalName
(
)
,
e
.
getMessage
(
)
)
;
return
errorImage
(
now
,
"(No image)"
,
url
.
toString
(
)
,
e
.
getMessage
(
)
)
;
}
}

Return image from given URL.

@return image from url or image with error text


public JSONResult getJSON(URL url) {
    try {
      logger.debug("Requesting {}", url);
      StringBuilder text = new StringBuilder();
      String line;

      HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
      urlconn.setReadTimeout(msTimeout);
      urlconn.setConnectTimeout(msTimeout);
      urlconn.setRequestMethod("GET");
      urlconn.connect();
      BufferedReader br = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
      while ((line = br.readLine()) != null) {
        text.append(line);
      }
      return new JSONResult(text.toString());
    }
    catch (Throwable e) {
      throw new FireRESTException(url.toString(), e);
    }
  }

public
JSONResult
getJSON
(
URL
url
)
{
try
{
logger
.
debug
(
"Requesting {}"
,
url
)
;
StringBuilder
text
=
new
StringBuilder
(
)
;
String
line
;
HttpURLConnection
urlconn
=
(
HttpURLConnection
)
url
.
openConnection
(
)
;
urlconn
.
setReadTimeout
(
msTimeout
)
;
urlconn
.
setConnectTimeout
(
msTimeout
)
;
urlconn
.
setRequestMethod
(
"GET"
)
;
urlconn
.
connect
(
)
;
BufferedReader
br
=
new
BufferedReader
(
new
InputStreamReader
(
urlconn
.
getInputStream
(
)
)
)
;
while
(
(
line
=
br
.
readLine
(
)
)
!=
)
{
text
.
append
(
line
)
;
}
return
new
JSONResult
(
text
.
toString
(
)
)
;
}
catch
(
Throwable
e
)
{
throw
new
FireRESTException
(
url
.
toString
(
)
,
e
)
;
}
}

HTTP GET json from given URL resource.

@return JSONResult


public static <K,V> void reverse(Map<K,V> source, Map<V,K> target)
    {
        Iterator<K> i = source.keySet().iterator();
        while (i.hasNext())
        {
            K key = i.next();
            V value = source.get(key);
            target.put(value, key);
        }
    }

public static < K , V > void reverse ( Map < K , V > source , Map < V , K > target ) { Iterator < K > i = source . keySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { K key = i . next ( ) ; V value = source . get ( key ) ; target . put ( value , key ) ; } }

Take key and value pairs from source and create map from value to key in target.

Take key and value pairs from source and create map from value to key in target .


private Set<R> multiplication() {
        final Set<R> answer = new LinkedHashSet<>(
            this.one.size() * this.two.size()
        );
        for (final A left : this.one) {
            for (final B right : this.two) {
                final R element = this.function.apply(left, right);
                if (answer.contains(element)) {
                    throw new IllegalStateException(
                        String.format(
                            "Cartesian product result contains duplicated element %s",
                            element
                        )
                    );
                }
                answer.add(element);
            }
        }
        return ImmutableSet.copyOf(answer);
    }

Creates Cartesian product of two lists .


@Override
public synchronized void start() {
      if (!running && !used) {
         this.running = true;
         this.used = true;
         this.setDaemon(true);
         super.start();
      }
   }

@ Override public synchronized void start ( ) { if ( ! running && ! used ) { this . running = true ; this . used = true ; this . setDaemon ( true ) ; super . start ( ) ; } }


private void returnToPool() {
      if(pool != null) {
         try {
            pool.returnObject(this);
         } catch (Exception e1) {
            log.error("Exception :", e1);
         }
         this.pool = null;
      }
   }

private
void
returnToPool
(
)
{
if
(
pool
!=
)
{
try
{
pool
.
returnObject
(
this
)
;
}
catch
(
Exception
e1
)
{
log
.
error
(
"Exception :"
,
e1
)
;
}
this
.
pool
=
;
}
}


public static Optional<EndedEvent> createEndedEvent(Identification source) {
        try {
            EndedEvent stopRequest = new EndedEvent(source);
            return Optional.of(stopRequest);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < EndedEvent > createEndedEvent ( Identification source ) { try { EndedEvent stopRequest = new EndedEvent ( source ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new EndedEvent
@param source the caller
@return the optional StartMusicRequest


public TrackInfo getCurrent() {
        TrackInfo trackInfo = null;
        try {
            trackInfo = queue.get(position);
        } catch (IndexOutOfBoundsException e) {
            trackInfo = null;
        }
        return trackInfo;
    }

public TrackInfo getCurrent ( ) { TrackInfo trackInfo = null ; try { trackInfo = queue . get ( position ) ; } catch ( IndexOutOfBoundsException e ) { trackInfo = null ; } return trackInfo ; }

returns the current played track or null
@return an instance of TrackInfo


public Playlist update(TrackInfo old, TrackInfo newTrackInfo) {
        List<TrackInfo> list = new ArrayList<>(queue);
        list.set(list.indexOf(old), newTrackInfo);
        return new Playlist(queue, name, playbackModes, position);
    }

public Playlist update ( TrackInfo old , TrackInfo newTrackInfo ) { List < TrackInfo > list = new ArrayList <> ( queue ) ; list . set ( list . indexOf ( old ) , newTrackInfo ) ; return new Playlist ( queue , name , playbackModes , position ) ; }

updates the TrackInfo-Object
@param old the old TrackInfo
@param newTrackInfo the new TrackInfo
@return the resulting new Playlist


public Playlist shuffle() {
        int position = getPosition();
        long seed = System.nanoTime();

        if (position >= 0 && position < queue.size()) {
            List<TrackInfo> trackInfos = queue.subList(0, position);
            List<TrackInfo> notPlayed = queue.subList(position, queue.size());

            List<TrackInfo> shuffledNotPlayed = new ArrayList<>(notPlayed);
            Collections.shuffle(shuffledNotPlayed, new Random(seed));
            trackInfos.addAll(shuffledNotPlayed);
            return new Playlist(trackInfos);
        } else {
            List<TrackInfo> trackInfos = new ArrayList<>(queue);
            Collections.shuffle(trackInfos, new Random(seed));
            return new Playlist(trackInfos);
        }
    }

public Playlist shuffle ( ) { int position = getPosition ( ) ; long seed = System . nanoTime ( ) ; if ( position >= 0 && position < queue . size ( ) ) { List < TrackInfo > trackInfos = queue . subList ( 0 , position ) ; List < TrackInfo > notPlayed = queue . subList ( position , queue . size ( ) ) ; List < TrackInfo > shuffledNotPlayed = new ArrayList <> ( notPlayed ) ; Collections . shuffle ( shuffledNotPlayed , new Random ( seed ) ) ; trackInfos . addAll ( shuffledNotPlayed ) ; return new Playlist ( trackInfos ) ; } else { List < TrackInfo > trackInfos = new ArrayList <> ( queue ) ; Collections . shuffle ( trackInfos , new Random ( seed ) ) ; return new Playlist ( trackInfos ) ; } }

Shuffles the playlist and returns the shuffled playlist, so the original stays intact.
Only the part of the playlist after the current position is shuffled.

@return a shuffled copy of this playlist

Shuffles the playlist and returns the shuffled playlist so the original stays intact . Only the part of the playlist after the current position is shuffled .


public boolean verify(Capabilities capabilities) {
        for (PlaybackMode playbackMode : playbackModes) {
            switch (playbackMode) {
                case REPEAT:
                    if (!capabilities.canRepeatPlayback()) {
                        return false;
                    } else {
                        break;
                    }
                case REPEAT_SONG:
                    if (!capabilities.canRepeatPlaybackOfSong()) {
                        return false;
                    } else {
                        break;
                    }
                case SHUFFLE:
                    if (!capabilities.canShufflePlayback()) {
                        return false;
                    } else {
                        break;
                    }
            }
        }
        return true;
    }

public boolean verify ( Capabilities capabilities ) { for ( PlaybackMode playbackMode : playbackModes ) { switch ( playbackMode ) { case REPEAT : if ( ! capabilities . canRepeatPlayback ( ) ) { return false ; } else { break ; } case REPEAT_SONG : if ( ! capabilities . canRepeatPlaybackOfSong ( ) ) { return false ; } else { break ; } case SHUFFLE : if ( ! capabilities . canShufflePlayback ( ) ) { return false ; } else { break ; } } } return true ; }

returns true if all the active playbackModes are supported
@param capabilities the Capabilities to match against
@return true if the player is capable, false if not


public HashMap<String, Object> export() {
        HashMap<String, Object> data = new HashMap<>();
        for (int i = 0; i < queue.size(); i++) {
            data.put(QUEUE_DESCRIPTOR+i, queue.get(i).export());
        }
        for (int i = 0; i < playbackModes.size(); i++) {
            data.put(PLAYBACK_MODE_DESCRIPTOR+i, playbackModes.get(i).name());
        }
        data.put(NAME_DESCRIPTOR, name);
        data.put(POSITION_DESCRIPTOR, position);
        data.put(DATA_DESCRIPTOR, this.data);
        return data;
    }

public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; for ( int i = 0 ; i < queue . size ( ) ; i ++ ) { data . put ( QUEUE_DESCRIPTOR + i , queue . get ( i ) . export ( ) ) ; } for ( int i = 0 ; i < playbackModes . size ( ) ; i ++ ) { data . put ( PLAYBACK_MODE_DESCRIPTOR + i , playbackModes . get ( i ) . name ( ) ) ; } data . put ( NAME_DESCRIPTOR , name ) ; data . put ( POSITION_DESCRIPTOR , position ) ; data . put ( DATA_DESCRIPTOR , this . data ) ; return data ; }

exports the Playlist to a HashMap
@return a HashMap


public static final String escapeForXML(String string) {
        if (string == null) {
            return null;
        }
        char ch;
        int i = 0;
        int last = 0;
        char[] input = string.toCharArray();
        int len = input.length;
        StringBuffer out = new StringBuffer((int) (len * 1.3));
        for (; i < len; i++) {
            ch = input[i];
            if (ch > '>') {
                continue;
            } else if (ch == '<') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(LT_ENCODE);
            } else if (ch == '>') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(GT_ENCODE);
            }

            else if (ch == '&') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                // Do nothing if the string is of the form ë (unicode
                // value)
                if (!(len > i + 5 && input[i + 1] == '#'
                        && Character.isDigit(input[i + 2])
                        && Character.isDigit(input[i + 3])
                        && Character.isDigit(input[i + 4]) && input[i + 5] == ';')) {
                    last = i + 1;
                    out.append(AMP_ENCODE);
                }
            } else if (ch == '"') {
                if (i > last) {
                    out.append(input, last, i - last);
                }
                last = i + 1;
                out.append(QUOTE_ENCODE);
            }
        }
        if (last == 0) {
            return string;
        }
        if (i > last) {
            out.append(input, last, i - last);
        }
        return out.toString();
    }

Escapes all necessary characters in the String so that it can be used in
an XML doc.

@param string
the string to escape.
@return the string with appropriate characters escaped.

Escapes all necessary characters in the String so that it can be used in an XML doc .


public void challengeReceived(String challenge) throws IOException {
        byte response[];
        if (challenge != null) {
            response = sc
                    .evaluateChallenge(StringUtils.decodeBase64(challenge));
        } else {
            response = sc.evaluateChallenge(new byte[0]);
        }

        Packet responseStanza;
        if (response == null) {
            responseStanza = new Response();
        } else {
            responseStanza = new Response(StringUtils.encodeBase64(response,
                    false));
        }

        // Send the authentication to the server
        getSASLAuthentication().send(responseStanza);
    }

The server is challenging the SASL mechanism for the stanza he just sent.
Send a response to the server's challenge.

@param challenge
a base64 encoded string representing the challenge.
@throws IOException
if an exception sending the response occurs.

The server is challenging the SASL mechanism for the stanza he just sent . Send a response to the server s challenge .


public ByteArrayOutputStream toJSON() throws IOException
    {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        mapper.writeValue(out, this);
        return out;
    }

public ByteArrayOutputStream toJSON ( ) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; mapper . writeValue ( out , this ) ; return out ; }

Create a JSON representation of the GoodwillSchemaField. It will always contain
the name, type and position. Description and SQL attributes are however
optional.

@return JSONObject containing all fields
@throws IOException             if a serialization exception occurs
@throws JsonGenerationException if a serialization exception occurs

Create a JSON representation of the GoodwillSchemaField . It will always contain the name type and position . Description and SQL attributes are however optional .


@Override
    public void run() {
        while (!stop) {
            EventModel event;
            try {
                event = blockingQueueHandling();  //gets the new Event if one was added to the blockingQueue
            } catch (InterruptedException e) {
                getContext().getLogger().warn(e);
                continue;
            }

            List<CompletableFuture<X>> outputExtensions = getContext().getOutput()
                    .generateAllOutputExtensions(this, getArgument(), event);

            try {
                outputExtensions = timeOut(outputExtensions, getTimeoutLimit());
            } catch (InterruptedException e) {
                getContext().getLogger().warn(e);
            }

            handleFutures(outputExtensions, event);

            //notifies output-manager when done processing
            isDone(event);
        }
    }

main method for outputPlugin, runs the data-conversion and output-renderer

it will instruct the outputManager to let the outputExtensions generate the data. Wait for the time specified
in getTimeoutLimit() (standard is 1000 milliseconds) abd the call renderFinalOutput() with the resulting data.

main method for outputPlugin runs the data - conversion and output - renderer


public void handleEvent(Event event) {
		String topic = event.getTopic();
		LOGGER.debug("Got Event {} {} ", event, handlers);
		Collection<IndexingHandler> contentIndexHandler = handlers.get(topic);
		if (contentIndexHandler != null && contentIndexHandler.size() > 0) {
			try {
				int ttl = Utils.toInt(event.getProperty(TopicIndexer.TTL),
						Integer.MAX_VALUE);
				for ( IndexingHandler indexingHandler : contentIndexHandler ) {
					if ( indexingHandler instanceof QoSIndexHandler ) {
						ttl = Math.min(ttl, Utils.defaultMax(((QoSIndexHandler)indexingHandler).getTtl(event)));
					}
				}
				QueueManager q = null;
				// queues is ordered by ascending ttl, so the fastest queue is queues[0],
				// if the ttl is less that that, we can't satisfy it, so we will put it
				// in the fastest queue
				if ( ttl < queues[0].batchDelay ) {
					LOGGER.warn("Unable to satisfy TTL of {} on event {}, posting to the highest priority queue. " +
							"If this message is logged a lot please adjust the queues or change the event ttl to something that can be satisfied. " +
							"Filling the highest priority queue is counter productive. ",
							ttl, event);
					queues[0].saveEvent(event);
				} else {
					for (QueueManager qm : queues) {
						if (ttl < qm.batchDelay) {
							q.saveEvent(event);
							q = null;
							break;
						}
						q = qm;
					}
					if (q != null) {
						q.saveEvent(event);
					}
				}
			} catch (IOException e) {
				LOGGER.warn(e.getMessage(), e);
			}
		}
	}

Handles an event from OSGi and places it in the appropriate queue.
@see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event)

Handles an event from OSGi and places it in the appropriate queue .


protected void joinAll() throws InterruptedException {
		if (queues != null) {
			for (QueueManager q : queues) {
				q.getQueueDispatcher().join();
			}
		}
	}

protected void joinAll ( ) throws InterruptedException { if ( queues != null ) { for ( QueueManager q : queues ) { q . getQueueDispatcher ( ) . join ( ) ; } } }


public void setProperty(String name, Object value) {
        if (!readOnly && !FILTER_PROPERTIES.contains(name)) {
            Object cv = authorizableMap.get(name);
            if ( value == null  ) {
                if ( cv != null && !(cv instanceof RemoveProperty)) {
                    modifiedMap.put(name, new RemoveProperty());
                }
            } else if (!value.equals(cv)) {
                modifiedMap.put(name, value);
            } else if (modifiedMap.containsKey(name) && !value.equals(modifiedMap.get(name))) {
                modifiedMap.put(name, value);
            }

        }
    }

public void setProperty ( String name , Object value ) { if ( ! readOnly && ! FILTER_PROPERTIES . contains ( name ) ) { Object cv = authorizableMap . get ( name ) ; if ( value == null ) { if ( cv != null && ! ( cv instanceof RemoveProperty ) ) { modifiedMap . put ( name , new RemoveProperty ( ) ) ; } } else if ( ! value . equals ( cv ) ) { modifiedMap . put ( name , value ) ; } else if ( modifiedMap . containsKey ( name ) && ! value . equals ( modifiedMap . get ( name ) ) ) { modifiedMap . put ( name , value ) ; } } }

Set a property. The property will only be set if writable. If the property or this athorizable is read only, nothing will happen.
@param name the name of the property
@param value the value of the property.

Set a property . The property will only be set if writable . If the property or this athorizable is read only nothing will happen .


public void removeProperty(String key) {
        if (!readOnly && (authorizableMap.containsKey(key) || modifiedMap.containsKey(key))) {
            modifiedMap.put(key, new RemoveProperty());
        }
    }

public void removeProperty ( String key ) { if ( ! readOnly && ( authorizableMap . containsKey ( key ) || modifiedMap . containsKey ( key ) ) ) { modifiedMap . put ( key , new RemoveProperty ( ) ) ; } }


public void addPrincipal(String principal) {
        if (!readOnly && !principals.contains(principal)) {
            principals.add(principal);
            principalsModified = true;
        }
    }

public void addPrincipal ( String principal ) { if ( ! readOnly && ! principals . contains ( principal ) ) { principals . add ( principal ) ; principalsModified = true ; } }

add a principal to this authorizable.
@param principal


public void removePrincipal(String principal) {
        if (!readOnly && principals.contains(principal)) {
            principals.remove(principal);
            principalsModified = true;
        }
    }

public void removePrincipal ( String principal ) { if ( ! readOnly && principals . contains ( principal ) ) { principals . remove ( principal ) ; principalsModified = true ; } }

remove a principal from this authorizable.
@param principal

remove a principal from this authorizable .


public void rootWindowClosing(WindowEvent evt) {
        connection.removePacketListener(listener);
        ((ObservableReader) reader).removeReaderListener(readerListener);
        ((ObservableWriter) writer).removeWriterListener(writerListener);
    }

public void rootWindowClosing ( WindowEvent evt ) { connection . removePacketListener ( listener ) ; ( ( ObservableReader ) reader ) . removeReaderListener ( readerListener ) ; ( ( ObservableWriter ) writer ) . removeWriterListener ( writerListener ) ; }

Notification that the root window is closing. Stop listening for received
and transmitted packets.

@param evt
the event that indicates that the root window is closing

Notification that the root window is closing . Stop listening for received and transmitted packets .


@SuppressWarnings("unused")
    public void userEncountered() {
        List<String> descriptors = new ArrayList<>();
        /*
        if (strict && ((!present && !fireUnknownIfNotPresent)|| !strictPresent) && addResponseDescriptors) {
            if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdNotPresent()) {
                descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR);
            } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) {
                descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR);
            }
        } else if (present && strict && addResponseDescriptors) {
            if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdPresent()) {
                descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR);
            } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) {
                descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR);
            }
        }*/
        descriptors.add(CommonEvents.Descriptors.NOT_INTERRUPT);
        boolean known = !fireUnknownIfNotPresent || present;
        boolean firstPresent = (!strict && !present) || (strict && !strictPresent);
        long lastSeen = this.lastSeen.until(LocalDateTime.now(), ChronoUnit.SECONDS);
        Optional<Event> presenceEvent = IdentificationManagerM.getInstance()
                .getIdentification(this)
                .flatMap(id -> PresenceEvent.createPresenceEvent(id, strict, known, firstPresent, descriptors, lastSeen))
                .map(event -> event.addEventLifeCycleListener(EventLifeCycle.APPROVED, lifeCycle -> {
                    if (known) {
                        this.lastSeen = LocalDateTime.now();
                        if (strict)
                            this.strictPresent = true;
                        present = true;
                    }
                }));
        if (!presenceEvent.isPresent()) {
            error("unable to create PresenceEvent");
        } else {
            fire(presenceEvent.get(), 5);
        }
    }

call this method when you have encountered the user


@Override
    public void eventFired(EventModel event) {
        if (event.containsDescriptor(LeavingEvent.ID) || event.containsDescriptor(PresenceEvent.ID)) {
            if (event.containsDescriptor(LeavingEvent.ID)) {
                if (event.containsDescriptor(LeavingEvent.GENERAL_DESCRIPTOR)) {
                    present = false;
                    strictPresent = false;
                } else if (event.containsDescriptor(LeavingEvent.STRICT_DESCRIPTOR)) {
                    nonStrictAvailable().thenAccept(available -> {
                        if (!available)
                            present = false;
                        strictPresent = false;
                    });
                }
            } else {
                present = true;
                if (event.containsDescriptor(PresenceEvent.STRICT_DESCRIPTOR))
                    strictPresent = true;
            }
            if (event.containsDescriptor(PresenceEvent.STRICT_DESCRIPTOR))
                lastSeen = LocalDateTime.now();
        }
    }

@ Override public void eventFired ( EventModel event ) { if ( event . containsDescriptor ( LeavingEvent . ID ) || event . containsDescriptor ( PresenceEvent . ID ) ) { if ( event . containsDescriptor ( LeavingEvent . ID ) ) { if ( event . containsDescriptor ( LeavingEvent . GENERAL_DESCRIPTOR ) ) { present = false ; strictPresent = false ; } else if ( event . containsDescriptor ( LeavingEvent . STRICT_DESCRIPTOR ) ) { nonStrictAvailable ( ) . thenAccept ( available -> { if ( ! available ) present = false ; strictPresent = false ; } ) ; } } else { present = true ; if ( event . containsDescriptor ( PresenceEvent . STRICT_DESCRIPTOR ) ) strictPresent = true ; } if ( event . containsDescriptor ( PresenceEvent . STRICT_DESCRIPTOR ) ) lastSeen = LocalDateTime . now ( ) ; } }

Invoked when an activator-event occurs.

@param event an instance of Event

Invoked when an activator - event occurs .


public static boolean isPermanent(ResourceModel resourceModel) {
        Object resource = resourceModel.getResource();
        try {
            return (Boolean) resource;
        } catch (ClassCastException e) {
            return false;
        }
    }

public static boolean isPermanent ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { return ( Boolean ) resource ; } catch ( ClassCastException e ) { return false ; } }

returns true if the resource is true, otherwise returns false
@param resourceModel the resourceModel
@return true if permanent

returns true if the resource is true otherwise returns false


public void setName(String name) {
        synchronized (entries) {
            for (RosterEntry entry : entries) {
                Roster packet = new Roster();
                packet.setType(IQ.Type.set);
                List<String> groupNames = new LinkedList<String>(
                        entry.getGroupNames());
                groupNames.remove(this.name);
                groupNames.add(name);
                packet.addItem(new JID(entry.getUser()), entry.getName(),
                        entry.getAsk(), entry.getSubscription(), groupNames);
                connection.sendPacket(packet);
            }
        }
    }

public void setName ( String name ) { synchronized ( entries ) { for ( RosterEntry entry : entries ) { Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; List < String > groupNames = new LinkedList < String > ( entry . getGroupNames ( ) ) ; groupNames . remove ( this . name ) ; groupNames . add ( name ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , entry . getSubscription ( ) , groupNames ) ; connection . sendPacket ( packet ) ; } } }

Sets the name of the group. Changing the group's name is like moving all
the group entries of the group to a new group specified by the new name.
Since this group won't have entries it will be removed from the roster.
This means that all the references to this object will be invalid and
will need to be updated to the new group specified by the new name.

@param name
the name of the group.

Sets the name of the group . Changing the group s name is like moving all the group entries of the group to a new group specified by the new name . Since this group won t have entries it will be removed from the roster . This means that all the references to this object will be invalid and will need to be updated to the new group specified by the new name .


public boolean containsKey(Object key) {
        int hashCode = hash((key == null) ? NULL : key);
        HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local
                                                                  // for hash
                                                                  // index
        while (entry != null) {
            if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) {
                return true;
            }
            entry = entry.next;
        }
        return false;
    }

public
boolean
containsKey
(
Object
key
)
{
int
hashCode
=
hash
(
(
key
==
)
:
key
)
;
HashEntry
entry
=
data
[
hashIndex
(
hashCode
,
data
.
length
)
]
;
// no local
// for hash
// index
while
(
entry
!=
)
{
if
(
entry
.
hashCode
==
hashCode
&&
isEqualKey
(
key
,
entry
.
getKey
(
)
)
)
{
return
true
;
}
entry
=
entry
.
next
;
}
return
false
;
}

Checks whether the map contains the specified key.

@param key
the key to search for
@return true if the map contains the key

Checks whether the map contains the specified key .


public boolean containsValue(Object value) {
        if (value == null) {
            for (int i = 0, isize = data.length; i < isize; i++) {
                HashEntry entry = data[i];
                while (entry != null) {
                    if (entry.getValue() == null) {
                        return true;
                    }
                    entry = entry.next;
                }
            }
        } else {
            for (int i = 0, isize = data.length; i < isize; i++) {
                HashEntry entry = data[i];
                while (entry != null) {
                    if (isEqualValue(value, entry.getValue())) {
                        return true;
                    }
                    entry = entry.next;
                }
            }
        }
        return false;
    }

public boolean containsValue ( Object value ) { if ( value == null ) { for ( int i = 0 , isize = data . length ; i < isize ; i ++ ) { HashEntry entry = data [ i ] ; while ( entry != null ) { if ( entry . getValue ( ) == null ) { return true ; } entry = entry . next ; } } } else { for ( int i = 0 , isize = data . length ; i < isize ; i ++ ) { HashEntry entry = data [ i ] ; while ( entry != null ) { if ( isEqualValue ( value , entry . getValue ( ) ) ) { return true ; } entry = entry . next ; } } } return false ; }

Checks whether the map contains the specified value.

@param value
the value to search for
@return true if the map contains the value

Checks whether the map contains the specified value .


public V put(K key, V value) {
        int hashCode = hash((key == null) ? NULL : key);
        int index = hashIndex(hashCode, data.length);
        HashEntry<K, V> entry = data[index];
        while (entry != null) {
            if (entry.hashCode == hashCode && isEqualKey(key, entry.getKey())) {
                V oldValue = entry.getValue();
                updateEntry(entry, value);
                return oldValue;
            }
            entry = entry.next;
        }
        addMapping(index, hashCode, key, value);
        return null;
    }

public V put ( K key , V value ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; int index = hashIndex ( hashCode , data . length ) ; HashEntry < K , V > entry = data [ index ] ; while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . getKey ( ) ) ) { V oldValue = entry . getValue ( ) ; updateEntry ( entry , value ) ; return oldValue ; } entry = entry . next ; } addMapping ( index , hashCode , key , value ) ; return null ; }

Puts a key-value mapping into this map.

@param key
the key to add
@param value
the value to add
@return the value previously mapped to this key, null if none

Puts a key - value mapping into this map .


public void clear() {
        modCount++;
        HashEntry[] data = this.data;
        for (int i = data.length - 1; i >= 0; i--) {
            data[i] = null;
        }
        size = 0;
    }

public void clear ( ) { modCount ++ ; HashEntry [ ] data = this . data ; for ( int i = data . length - 1 ; i >= 0 ; i -- ) { data [ i ] = null ; } size = 0 ; }

Clears the map, resetting the size to zero and nullifying references to
avoid garbage collection issues.

Clears the map resetting the size to zero and nullifying references to avoid garbage collection issues .


protected int hash(Object key) {
        // same as JDK 1.4
        int h = key.hashCode();
        h += ~(h << 9);
        h ^= (h >>> 14);
        h += (h << 4);
        h ^= (h >>> 10);
        return h;
    }

protected
int
hash
(
Object
key
)
{
// same as JDK 1.4
int
h
=
key
.
hashCode
(
)
;
h
+=
~
(
h
<<
9
)
;
h
^=
(
h
>>>
14
)
;
h
+=
(
h
<<
4
)
;
h
^=
(
h
>>>
10
)
;
return
h
;
}

Gets the hash code for the key specified. This implementation uses the
additional hashing routine from JDK1.4. Subclasses can override this to
return alternate hash codes.

@param key
the key to get a hash code for
@return the hash code

Gets the hash code for the key specified . This implementation uses the additional hashing routine from JDK1 . 4 . Subclasses can override this to return alternate hash codes .


protected boolean isEqualKey(Object key1, Object key2) {
        return (key1 == key2 || ((key1 != null) && key1.equals(key2)));
    }

protected boolean isEqualKey ( Object key1 , Object key2 ) { return ( key1 == key2 || ( ( key1 != null ) && key1 . equals ( key2 ) ) ) ; }

Compares two keys, in internal converted form, to see if they are equal.
This implementation uses the equals method. Subclasses can override this
to match differently.

@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

Compares two keys in internal converted form to see if they are equal . This implementation uses the equals method . Subclasses can override this to match differently .


protected boolean isEqualValue(Object value1, Object value2) {
        return (value1 == value2 || value1.equals(value2));
    }

protected boolean isEqualValue ( Object value1 , Object value2 ) { return ( value1 == value2 || value1 . equals ( value2 ) ) ; }

Compares two values, in external form, to see if they are equal. This
implementation uses the equals method and assumes neither value is null.
Subclasses can override this to match differently.

@param value1
the first value to compare passed in from outside
@param value2
the second value extracted from the entry via
getValue()
@return true if equal

Compares two values in external form to see if they are equal . This implementation uses the equals method and assumes neither value is null . Subclasses can override this to match differently .


protected void ensureCapacity(int newCapacity) {
        int oldCapacity = data.length;
        if (newCapacity <= oldCapacity) {
            return;
        }
        if (size == 0) {
            threshold = calculateThreshold(newCapacity, loadFactor);
            data = new HashEntry[newCapacity];
        } else {
            HashEntry<K, V> oldEntries[] = data;
            HashEntry<K, V> newEntries[] = new HashEntry[newCapacity];

            modCount++;
            for (int i = oldCapacity - 1; i >= 0; i--) {
                HashEntry<K, V> entry = oldEntries[i];
                if (entry != null) {
                    oldEntries[i] = null; // gc
                    do {
                        HashEntry<K, V> next = entry.next;
                        int index = hashIndex(entry.hashCode, newCapacity);
                        entry.next = newEntries[index];
                        newEntries[index] = entry;
                        entry = next;
                    } while (entry != null);
                }
            }
            threshold = calculateThreshold(newCapacity, loadFactor);
            data = newEntries;
        }
    }

protected
void
ensureCapacity
(
int
newCapacity
)
{
int
oldCapacity
=
data
.
length
;
if
(
newCapacity
<=
oldCapacity
)
{
return
;
}
if
(
size
==
0
)
{
threshold
=
calculateThreshold
(
newCapacity
,
loadFactor
)
;
data
=
new
HashEntry
[
newCapacity
]
;
}
else
{
HashEntry
<
K
,
V
>
oldEntries
[
]
=
data
;
HashEntry
<
K
,
V
>
newEntries
[
]
=
new
HashEntry
[
newCapacity
]
;
modCount
++
;
for
(
int
i
=
oldCapacity
1
;
i
>=
0
;
i
)
{
HashEntry
<
K
,
V
>
entry
=
oldEntries
[
i
]
;
if
(
entry
!=
)
{
oldEntries
[
i
]
=
;
// gc
do
{
HashEntry
<
K
,
V
>
next
=
entry
.
next
;
int
index
=
hashIndex
(
entry
.
hashCode
,
newCapacity
)
;
entry
.
next
=
newEntries
[
index
]
;
newEntries
[
index
]
=
entry
;
entry
=
next
;
}
while
(
entry
!=
)
;
}
}
threshold
=
calculateThreshold
(
newCapacity
,
loadFactor
)
;
data
=
newEntries
;
}
}

Changes the size of the data structure to the capacity proposed.

@param newCapacity
the new capacity of the array (a power of two, less or equal
to max)

Changes the size of the data structure to the capacity proposed .


protected int calculateNewCapacity(int proposedCapacity) {
        int newCapacity = 1;
        if (proposedCapacity > MAXIMUM_CAPACITY) {
            newCapacity = MAXIMUM_CAPACITY;
        } else {
            while (newCapacity < proposedCapacity) {
                newCapacity <<= 1; // multiply by two
            }
            if (newCapacity > MAXIMUM_CAPACITY) {
                newCapacity = MAXIMUM_CAPACITY;
            }
        }
        return newCapacity;
    }

protected
int
calculateNewCapacity
(
int
proposedCapacity
)
{
int
newCapacity
=
1
;
if
(
proposedCapacity
>
MAXIMUM_CAPACITY
)
{
newCapacity
=
MAXIMUM_CAPACITY
;
}
else
{
while
(
newCapacity
<
proposedCapacity
)
{
newCapacity
<<=
1
;
// multiply by two
}
if
(
newCapacity
>
MAXIMUM_CAPACITY
)
{
newCapacity
=
MAXIMUM_CAPACITY
;
}
}
return
newCapacity
;
}

Calculates the new capacity of the map. This implementation normalizes
the capacity to a power of two.

@param proposedCapacity
the proposed capacity
@return the normalized new capacity

Calculates the new capacity of the map . This implementation normalizes the capacity to a power of two .


protected Iterator<Map.Entry<K, V>> createEntrySetIterator() {
        if (size() == 0) {
            return EmptyIterator.INSTANCE;
        }
        return new EntrySetIterator<K, V>(this);
    }

protected Iterator < Map . Entry < K , V > > createEntrySetIterator ( ) { if ( size ( ) == 0 ) { return EmptyIterator . INSTANCE ; } return new EntrySetIterator < K , V > ( this ) ; }

Creates an entry set iterator. Subclasses can override this to return
iterators with different properties.

@return the entrySet iterator

Creates an entry set iterator . Subclasses can override this to return iterators with different properties .


public static void loadFromStream(String key, Map<String, Object> output, InputStream binaryStream, String type)
            throws IOException {
        DataInputStream dis = new DataInputStream(binaryStream);
        String ckey = dis.readUTF();
        if (!key.equals(ckey)) {
            throw new IOException("Body Key does not match row key, unable to read");
        }
        readMapFromStream(output, dis);
        String cftype = null;
        try {
            cftype = dis.readUTF();
        } catch (IOException e) {
            LOGGER.debug("No type specified");
        }
        if (cftype != null && !cftype.equals(type)) {
            throw new IOException(
                    "Object is not of expected column family, unable to read expected [" + type
                            + "] was [" + cftype + "]");
        }
        LOGGER.debug("Finished Reading");
        dis.close();
        binaryStream.close();
    }

Load a Map from binary stream

@param output
@param binaryStream
@throws IOException