private synchronized void schedulePingServerTask() {
        enableExecutorService();
        stopPingServerTask();

        if (pingInterval > 0) {
            periodicPingTask = periodicPingExecutorService.schedule(
                    new Runnable() {
                        @Override
                        public void run() {
                            Ping ping = new Ping();
                            PacketFilter responseFilter = new PacketIDFilter(
                                    ping.getID());
                            Connection connection = weakRefConnection.get();
                            final PacketCollector response = pingFailedListeners
                                    .isEmpty() ? null : connection
                                    .createPacketCollector(responseFilter);
                            connection.sendPacket(ping);

                            if (response != null) {
                                // Schedule a collector for the ping reply,
                                // notify listeners if none is received.
                                periodicPingExecutorService.schedule(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                Packet result = response
                                                        .nextResult(1);

                                                // Stop queuing results
                                                response.cancel();

                                                // The actual result of the
                                                // reply can be ignored since we
                                                // only care if we actually got
                                                // one.
                                                if (result == null) {
                                                    for (PingFailedListener listener : pingFailedListeners) {
                                                        listener.pingFailed();
                                                    }
                                                }
                                            }
                                        }, SmackConfiguration
                                                .getPacketReplyTimeout(),
                                        TimeUnit.MILLISECONDS);
                            }
                        }
                    }, getPingInterval(), TimeUnit.MILLISECONDS);
        }
    }

Cancels any existing periodic ping task if there is one and schedules a
new ping task if pingInterval is greater then zero.

This is designed so only one executor is used for scheduling all pings on
all connections. This results in only 1 thread used for pinging.

Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater then zero .


public ExecS_CliParser addAllOptions(ApplicationOption<?>[] options){
		if(options!=null){
			for(ApplicationOption<?> option : options){
				this.addOption(option);
			}
		}
		return this;
	}

public ExecS_CliParser addAllOptions ( ApplicationOption < ? > [ ] options ) { if ( options != null ) { for ( ApplicationOption < ? > option : options ) { this . addOption ( option ) ; } } return this ; }

Adds all given option ignoring null elements.
@param options array of options
@return self to allow for chaining

Adds all given option ignoring null elements .


public boolean hasOption(Option option){
		if(option==null){
			return false;
		}
		if(this.usedOptions.contains(option.getOpt())){
			return true;
		}
		if(this.usedOptions.contains(option.getLongOpt())){
			return true;
		}
		return false;
	}

public boolean hasOption ( Option option ) { if ( option == null ) { return false ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { return true ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { return true ; } return false ; }

Tests if an option is already added to the parser.
@param option the option to test for
@return false if option was null or n short and long version of this option is used, true otherwise

Tests if an option is already added to the parser .


public ParseException parse(String[] args){
		ParseException ret = null;
		CommandLineParser parser = new DefaultParser();
		try{
			this.cmdLine = parser.parse(this.options, args);
		}
		catch(ParseException pe){
			ret = pe;
		}
		return ret;
	}

public ParseException parse ( String [ ] args ) { ParseException ret = null ; CommandLineParser parser = new DefaultParser ( ) ; try { this . cmdLine = parser . parse ( this . options , args ) ; } catch ( ParseException pe ) { ret = pe ; } return ret ; }

Parses command line arguments and fills set options.
@param args command line arguments
@return null on success, an exception with message on parsing error

Parses command line arguments and fills set options .


public void usage(String appName){
		HelpFormatter formatter=new HelpFormatter();
		formatter.printHelp(appName, null, this.options, null, false);
	}

public void usage ( String appName ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( appName , null , this . options , null , false ) ; }

Prints a usage screen based on set options.
@param appName name of the application to be used for the usage screen

Prints a usage screen based on set options .


static int doParse(String[] args, ExecS_CliParser cli, String appName){
		Exception err = cli.parse(args);
		if(err!=null){
			System.err.println(appName + ": error parsing command line -> " + err.getMessage());
			return -1;
		}
		return 0;
	}

static
int
doParse
(
String
[
]
args
,
ExecS_CliParser
cli
,
String
appName
)
{
Exception
err
=
cli
.
parse
(
args
)
;
if
(
err
!=
)
{
System
.
err
.
println
(
appName
+
": error parsing command line -> "
+
err
.
getMessage
(
)
)
;
return
1
;
}
return
0
;
}

Parses command line arguments for a given CLI parser.
@param args command line arguments to parse
@param cli CLI object with options to parse for
@param appName application name for error messages
@return 0 on success, -1 on error with error being logged

Parses command line arguments for a given CLI parser .


private void initConnection() throws XMPPException {
        boolean isFirstInitialization = packetReader == null
                || packetWriter == null;
        compressionHandler = null;
        serverAckdCompression = false;

        // Set the reader and writer instance variables
        initReaderAndWriter();

        try {
            if (isFirstInitialization) {
                packetWriter = new PacketWriter(this);
                packetReader = new PacketReader(this);

                // If debugging is enabled, we should start the thread that will
                // listen for
                // all packets and then log them.
                if (config.isDebuggerEnabled()) {
                    addPacketListener(debugger.getReaderListener(), null);
                    if (debugger.getWriterListener() != null) {
                        addPacketSendingListener(debugger.getWriterListener(),
                                null);
                    }
                }
            } else {
                packetWriter.init();
                packetReader.init();
            }

            // Start the packet writer. This will open a XMPP stream to the
            // server
            packetWriter.startup();
            // Start the packet reader. The startup() method will block until we
            // get an opening stream packet back from server.
            packetReader.startup();

            // Make note of the fact that we're now connected.
            connected = true;

            if (isFirstInitialization) {
                // Notify listeners that a new connection has been established
                for (ConnectionCreationListener listener : getConnectionCreationListeners()) {
                    listener.connectionCreated(this);
                }
            }

        } catch (XMPPException ex) {
            // An exception occurred in setting up the connection. Make sure we
            // shut down the
            // readers and writers and close the socket.

            if (packetWriter != null) {
                try {
                    packetWriter.shutdown();
                } catch (Throwable ignore) { /* ignore */
                }
                packetWriter = null;
            }
            if (packetReader != null) {
                try {
                    packetReader.shutdown();
                } catch (Throwable ignore) { /* ignore */
                }
                packetReader = null;
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (Throwable ignore) { /* ignore */
                }
                reader = null;
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable ignore) { /* ignore */
                }
                writer = null;
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) { /* ignore */
                }
                socket = null;
            }
            this.setWasAuthenticated(authenticated);
            authenticated = false;
            connected = false;

            throw ex; // Everything stoppped. Now throw the exception.
        }
    }

Initializes the connection by creating a packet reader and writer and
opening a XMPP stream to the server.

@throws XMPPException
if establishing a connection to the server fails.

Initializes the connection by creating a packet reader and writer and opening a XMPP stream to the server .


void startTLSReceived(boolean required) {
        if (required
                && config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) {
            notifyConnectionError(new IllegalStateException(
                    "TLS required by server but not allowed by connection configuration"));
            return;
        }

        if (config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) {
            // Do not secure the connection using TLS since TLS was disabled
            return;
        }
        try {
            writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
            writer.flush();
        } catch (IOException e) {
            notifyConnectionError(e);
        }
    }

Notification message saying that the server supports TLS so confirm the
server that we want to secure the connection.

@param required
true when the server indicates that TLS is required.

Notification message saying that the server supports TLS so confirm the server that we want to secure the connection .


private XMPPInputOutputStream maybeGetCompressionHandler() {
        if (compressionMethods != null) {
            for (XMPPInputOutputStream handler : compressionHandlers) {
                if (!handler.isSupported())
                    continue;

                String method = handler.getCompressionMethod();
                if (compressionMethods.contains(method))
                    return handler;
            }
        }
        return null;
    }

private XMPPInputOutputStream maybeGetCompressionHandler ( ) { if ( compressionMethods != null ) { for ( XMPPInputOutputStream handler : compressionHandlers ) { if ( ! handler . isSupported ( ) ) continue ; String method = handler . getCompressionMethod ( ) ; if ( compressionMethods . contains ( method ) ) return handler ; } } return null ; }

Returns the compression handler that can be used for one compression
methods offered by the server.

@return a instance of XMPPInputOutputStream or null if no suitable
instance was found

Returns the compression handler that can be used for one compression methods offered by the server .


private void requestStreamCompression(String method) {
        try {
            writer.write("<compress xmlns='http://jabber.org/protocol/compress'>");
            writer.write("<method>" + method + "</method></compress>");
            writer.flush();
        } catch (IOException e) {
            notifyConnectionError(e);
        }
    }

Request the server that we want to start using stream compression. When
using TLS then negotiation of stream compression can only happen after
TLS was negotiated. If TLS compression is being used the stream
compression should not be used.

Request the server that we want to start using stream compression . When using TLS then negotiation of stream compression can only happen after TLS was negotiated . If TLS compression is being used the stream compression should not be used .


void startStreamCompression() throws Exception {
        serverAckdCompression = true;
        // Initialize the reader and writer with the new secured version
        initReaderAndWriter();

        // Set the new writer to use
        packetWriter.setWriter(writer);
        // Send a new opening stream to the server
        packetWriter.openStream();
        // Notify that compression is being used
        synchronized (this) {
            this.notify();
        }
    }

Start using stream compression since the server has acknowledged stream
compression.

@throws Exception
if there is an exception starting stream compression.

Start using stream compression since the server has acknowledged stream compression .


synchronized void notifyConnectionError(Exception e) {
        // Listeners were already notified of the exception, return right here.
        if ((packetReader == null || packetReader.done)
                && (packetWriter == null || packetWriter.done))
            return;

        if (packetReader != null)
            packetReader.done = true;
        if (packetWriter != null)
            packetWriter.done = true;
        // Closes the connection temporary. A reconnection is possible
        shutdown(new Presence(Presence.Type.unavailable));
        // Notify connection listeners of the error.
        for (ConnectionListener listener : getConnectionListeners()) {
            try {
                listener.connectionClosedOnError(e);
            } catch (Exception e2) {
                // Catch and print any exception so we can recover
                // from a faulty listener
                e2.printStackTrace();
            }
        }
    }

Sends out a notification that there was an error with the connection and
closes the connection. Also prints the stack trace of the given exception

@param e
the exception that causes the connection close event.

Sends out a notification that there was an error with the connection and closes the connection . Also prints the stack trace of the given exception


protected void notifyReconnection() {
        // Notify connection listeners of the reconnection.
        for (ConnectionListener listener : getConnectionListeners()) {
            try {
                listener.reconnectionSuccessful();
            } catch (Exception e) {
                // Catch and print any exception so we can recover
                // from a faulty listener
                e.printStackTrace();
            }
        }
    }

Sends a notification indicating that the connection was reconnected
successfully.

Sends a notification indicating that the connection was reconnected successfully .


public static void registerSASLMechanism(String name,
            Class<? extends SASLMechanism> mClass) {
        implementedMechanisms.put(name, mClass);
    }

public static void registerSASLMechanism ( String name , Class < ? extends SASLMechanism > mClass ) { implementedMechanisms . put ( name , mClass ) ; }

Registers a new SASL mechanism

@param name
common name of the SASL mechanism. E.g.: PLAIN, DIGEST-MD5 or
KERBEROS_V4.
@param mClass
a SASLMechanism subclass.


public static List<Class<? extends SASLMechanism>> getRegisterSASLMechanisms() {
        List<Class<? extends SASLMechanism>> answer = new ArrayList<Class<? extends SASLMechanism>>();
        for (String mechanismsPreference : mechanismsPreferences) {
            answer.add(implementedMechanisms.get(mechanismsPreference));
        }
        return answer;
    }

public static List < Class < ? extends SASLMechanism > > getRegisterSASLMechanisms ( ) { List < Class < ? extends SASLMechanism > > answer = new ArrayList < Class < ? extends SASLMechanism > > ( ) ; for ( String mechanismsPreference : mechanismsPreferences ) { answer . add ( implementedMechanisms . get ( mechanismsPreference ) ) ; } return answer ; }

Returns the registerd SASLMechanism classes sorted by the level of
preference.

@return the registerd SASLMechanism classes sorted by the level of
preference.

Returns the registerd SASLMechanism classes sorted by the level of preference .


@Override
    public HashMap<Integer, List<Identification>> getOutputPluginBehaviour(List<Identification> identifications) {
        if(outputPluginBehaviour == null) return new HashMap<>();
        return outputPluginBehaviour.apply(identifications);
    }

@ Override public HashMap < Integer , List < Identification > > getOutputPluginBehaviour ( List < Identification > identifications ) { if ( outputPluginBehaviour == null ) return new HashMap <> ( ) ; return outputPluginBehaviour . apply ( identifications ) ; }

generates the data to control the Event
@param identifications the Identifications of the OutputPlugins
@return a HashMap, where the keys represent the associated Behaviour and the values the Identification;


static void info(String message, Throwable t) {
		log(System.out, "*INFO*", message, t);
	}

static void info ( String message , Throwable t ) { log ( System . out , "*INFO*" , message , t ) ; }

emit an informational message to standard out


static void error(String message, Throwable t) {
		log(System.err, "*ERROR*", message, t);
	}

static void error ( String message , Throwable t ) { log ( System . err , "*ERROR*" , message , t ) ; }


private static void log(PrintStream out, String prefix, String message,
			Throwable t) {

		final StringBuilder linePrefixBuilder = new StringBuilder();
		synchronized (fmt) {
			linePrefixBuilder.append(fmt.format(new Date()));
		}
		linePrefixBuilder.append(prefix);
		linePrefixBuilder.append(" [");
		linePrefixBuilder.append(Thread.currentThread().getName());
		linePrefixBuilder.append("] ");
		final String linePrefix = linePrefixBuilder.toString();

		out.print(linePrefix);
		out.println(message);
		if (t != null) {
			t.printStackTrace(new PrintStream(out) {
				@Override
				public void println(String x) {
					synchronized (this) {
						print(linePrefix);
						super.println(x);
						flush();
					}
				}
			});
		}
	}

private
static
void
log
(
PrintStream
out
,
String
prefix
,
String
message
,
Throwable
t
)
{
final
StringBuilder
linePrefixBuilder
=
new
StringBuilder
(
)
;
synchronized
(
fmt
)
{
linePrefixBuilder
.
append
(
fmt
.
format
(
new
Date
(
)
)
)
;
}
linePrefixBuilder
.
append
(
prefix
)
;
linePrefixBuilder
.
append
(
" ["
)
;
linePrefixBuilder
.
append
(
Thread
.
currentThread
(
)
.
getName
(
)
)
;
linePrefixBuilder
.
append
(
"] "
)
;
final
String
linePrefix
=
linePrefixBuilder
.
toString
(
)
;
out
.
print
(
linePrefix
)
;
out
.
println
(
message
)
;
if
(
t
!=
)
{
t
.
printStackTrace
(
new
PrintStream
(
out
)
{
@
Override
public
void
println
(
String
x
)
{
synchronized
(
this
)
{
print
(
linePrefix
)
;
super
.
println
(
x
)
;
flush
(
)
;
}
}
}
)
;
}
}

the throwable if not-null is also prefixed line by line with the prefix

the throwable if not - null is also prefixed line by line with the prefix


public static Optional<StartEvent> createStartEvent(Identification source) {
        try {
            StartEvent startRequest = new StartEvent(source);
            return Optional.of(startRequest);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < StartEvent > createStartEvent ( Identification source ) { try { StartEvent startRequest = new StartEvent ( source ) ; return Optional . of ( startRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new StartEvent.
Assumes the Output is using the java-sound output.
@param source the caller
@return the optional StartMusicRequest

creates a new StartEvent . Assumes the Output is using the java - sound output .


public static Optional<StartEvent> createStartEvent(Identification source, boolean isUsingJava) {
        try {
            StartEvent startEvent;
            if (isUsingJava) {
                startEvent  = new StartEvent(source);
            } else {
                startEvent =  new StartEvent(source, IS_USING_NON_JAVA_OUTPUT);
            }
            return Optional.of(startEvent);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < StartEvent > createStartEvent ( Identification source , boolean isUsingJava ) { try { StartEvent startEvent ; if ( isUsingJava ) { startEvent = new StartEvent ( source ) ; } else { startEvent = new StartEvent ( source , IS_USING_NON_JAVA_OUTPUT ) ; } return Optional . of ( startEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new StartEvent
@param source the caller
@param isUsingJava true if using java, false if not (and for example a C-library)
@return the optional StartMusicRequest


private void notifyListeners(String str) {
        WriterListener[] writerListeners = null;
        synchronized (listeners) {
            writerListeners = new WriterListener[listeners.size()];
            listeners.toArray(writerListeners);
        }
        for (int i = 0; i < writerListeners.length; i++) {
            writerListeners[i].write(str);
        }
    }

private void notifyListeners ( String str ) { WriterListener [ ] writerListeners = null ; synchronized ( listeners ) { writerListeners = new WriterListener [ listeners . size ( ) ] ; listeners . toArray ( writerListeners ) ; } for ( int i = 0 ; i < writerListeners . length ; i ++ ) { writerListeners [ i ] . write ( str ) ; } }

Notify that a new string has been written.

@param str
the written String to notify

Notify that a new string has been written .


@Override
    public boolean providesResource(ResourceModel resource) {
        return resources.stream()
                .map(ResourceModel::getResourceID)
                .anyMatch(resourceS -> resourceS.equals(resource.getResourceID()));
    }

@ Override public boolean providesResource ( ResourceModel resource ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourceS -> resourceS . equals ( resource . getResourceID ( ) ) ) ; }

checks whether it can provide the resource

@param resource the resource to provide
@return true if the container can provide the resource


@Override
    public boolean containsResourcesFromSource(String sourceID) {
        return resources.stream()
                .map(ResourceModel::getResourceID)
                .anyMatch(source -> source.equals(sourceID));
    }

@ Override public boolean containsResourcesFromSource ( String sourceID ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( source -> source . equals ( sourceID ) ) ; }

checks whether there are any resources registered from the source

@param sourceID the ID of the source
@return true if the container has resources from the source


@Override
    public boolean providesResource(List<String> resourcesIDs) {
        return resources.stream()
                .map(ResourceModel::getResourceID)
                .anyMatch(resourcesIDs::contains);
    }

@ Override public boolean providesResource ( List < String > resourcesIDs ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourcesIDs :: contains ) ; }

checks whether the ResourceContainer can provide at least ONE resource

@param resourcesIDs a list containing sources
@return true if the ResourceContainer can provide at least one resource


@Override
    public List<ResourceModel> provideResource(String[] resourceIDs) {
        return resources.stream()
                .filter(resource -> Arrays.stream(resourceIDs)
                        .anyMatch(resourceID -> resourceID.equals(resource.getResourceID())))
                .collect(Collectors.toList());
    }

@ Override public List < ResourceModel > provideResource ( String [ ] resourceIDs ) { return resources . stream ( ) . filter ( resource -> Arrays . stream ( resourceIDs ) . anyMatch ( resourceID -> resourceID . equals ( resource . getResourceID ( ) ) ) ) . collect ( Collectors . toList ( ) ) ; }

returns all EXISTING resources for the ID.
If there are no resources for the ID the ID will get skipped

@param resourceIDs an Array containing the resources
@return a list of resources found

returns all EXISTING resources for the ID . If there are no resources for the ID the ID will get skipped


protected Map<String, Object> getCached(String keySpace, String columnFamily, String key) throws StorageClientException {
        Map<String, Object> m = null;
        String cacheKey = getCacheKey(keySpace, columnFamily, key);

        CacheHolder cacheHolder = getFromCacheInternal(cacheKey);
        if (cacheHolder != null) {
            m = cacheHolder.get();
            if (m != null) {
                LOGGER.debug("Cache Hit {} {} {} ", new Object[] { cacheKey, cacheHolder, m });
            }
        }
        if (m == null) {
            m = client.get(keySpace, columnFamily, key);
            if (m != null) {
                LOGGER.debug("Cache Miss, Found Map {} {}", cacheKey, m);
            }
            putToCacheInternal(cacheKey, new CacheHolder(m), true);
        }
        return m;
    }

protected
Map
<
String
,
Object
>
getCached
(
String
keySpace
,
String
columnFamily
,
String
key
)
throws
StorageClientException
{
Map
<
String
,
Object
>
m
=
;
String
cacheKey
=
getCacheKey
(
keySpace
,
columnFamily
,
key
)
;
CacheHolder
cacheHolder
=
getFromCacheInternal
(
cacheKey
)
;
if
(
cacheHolder
!=
)
{
m
=
cacheHolder
.
get
(
)
;
if
(
m
!=
)
{
LOGGER
.
debug
(
"Cache Hit {} {} {} "
,
new
Object
[
]
{
cacheKey
,
cacheHolder
,
m
}
)
;
}
}
if
(
m
==
)
{
m
=
client
.
get
(
keySpace
,
columnFamily
,
key
)
;
if
(
m
!=
)
{
LOGGER
.
debug
(
"Cache Miss, Found Map {} {}"
,
cacheKey
,
m
)
;
}
putToCacheInternal
(
cacheKey
,
new
CacheHolder
(
m
)
,
true
)
;
}
return
m
;
}

Try to retrieve an object from the cache. Has the side-effect of loading
an uncached object into cache the first time.

@param keySpace
the key space we're operating in.
@param columnFamily
the column family for the object
@param key
the object key
@return the object or null if not cached and not found
@throws StorageClientException

Try to retrieve an object from the cache . Has the side - effect of loading an uncached object into cache the first time .


private String getCacheKey(String keySpace, String columnFamily, String key) throws StorageClientException {
        if (client instanceof RowHasher) {
            return ((RowHasher) client).rowHash(keySpace, columnFamily, key);
        }
        return keySpace + ":" + columnFamily + ":" + key;
    }

private String getCacheKey ( String keySpace , String columnFamily , String key ) throws StorageClientException { if ( client instanceof RowHasher ) { return ( ( RowHasher ) client ) . rowHash ( keySpace , columnFamily , key ) ; } return keySpace + ":" + columnFamily + ":" + key ; }

Combine the parameters into a key suitable for storage and lookup in the
cache.

@param keySpace
@param columnFamily
@param key
@return the cache key
@throws StorageClientException

Combine the parameters into a key suitable for storage and lookup in the cache .


protected void removeCached(String keySpace, String columnFamily, String key) throws StorageClientException {
        if (sharedCache != null) {
            // insert a replacement. This should cause an invalidation message
            // to propagate in the cluster.
            final String cacheKey = getCacheKey(keySpace, columnFamily, key);
            putToCacheInternal(cacheKey, new CacheHolder(null, managerId), false);
            LOGGER.debug("Marked as deleted in Cache {} ", cacheKey);
            if (client instanceof Disposer) {
                // we might want to change this to register the action as a
                // commit handler rather than a disposable.
                // it depends on if we think the delete is a transactional thing
                // or a operational cache thing.
                // at the moment, I am leaning towards an operational cache
                // thing, since regardless of if
                // the session commits or not, we want this to dispose when the
                // session is closed, or commits.
                ((Disposer) client).registerDisposable(new Disposable() {

                    @Override
                    public void setDisposer(Disposer disposer) {
                    }

                    @Override
                    public void close() {
                        CacheHolder ch = sharedCache.get(cacheKey);
                        if (ch != null && ch.wasLockedTo(managerId)) {
                            sharedCache.remove(cacheKey);
                            LOGGER.debug("Removed deleted marker from Cache {} ", cacheKey);
                        }
                    }
                });
            }
        }
        client.remove(keySpace, columnFamily, key);

    }

Remove this object from the cache. Note, StorageClient uses the word
remove to mean delete. This method should do the same.

@param keySpace
@param columnFamily
@param key
@throws StorageClientException

Remove this object from the cache . Note StorageClient uses the word remove to mean delete . This method should do the same .


protected void putCached(String keySpace, String columnFamily, String key, Map<String, Object> encodedProperties,
            boolean probablyNew) throws StorageClientException {
        String cacheKey = null;
        if (sharedCache != null) {
            cacheKey = getCacheKey(keySpace, columnFamily, key);
        }
        if (sharedCache != null && !probablyNew) {
            CacheHolder ch = getFromCacheInternal(cacheKey);
            if (ch != null && ch.isLocked(this.managerId)) {
                LOGGER.debug("Is Locked {} ", ch);
                return; // catch the case where another method creates while
                // something is in the cache.
                // this is a big assumption since if the item is not in the
                // cache it will get updated
                // there is no difference in sparsemap between create and
                // update, they are all insert operations
                // what we are really saying here is that inorder to update the
                // item you have to have just got it
                // and if you failed to get it, your update must have been a
                // create operation. As long as the dwell time
                // in the cache is longer than the lifetime of an active session
                // then this will be true.
                // if the lifetime of an active session is longer (like with a
                // long running background operation)
                // then you should expect to see race conditions at this point
                // since the marker in the cache will have
                // gone, and the marker in the database has gone, so the put
                // operation, must be a create operation.
                // To change this behavior we would need to differentiate more
                // strongly between new and update and change
                // probablyNew into certainlyNew, but that would probably break
                // the BASIC assumption of the whole system.
                // Update 2011-12-06 related to issue 136
                // I am not certain this code is correct. What happens if the
                // session wants to remove and then add items.
                // the session will never get past this point, since sitting in
                // the cache is a null CacheHolder preventing the session
                // removing then adding.
                // also, how long should the null cache holder be placed in
                // there for ?
                // I think the solution is to bind the null Cache holder to the
                // instance of the caching manager that created it,
                // let the null Cache holder last for 10s, and during that time
                // only the CachingManagerImpl that created it can remove it.
            }
        }
        LOGGER.debug("Saving {} {} {} {} ", new Object[] { keySpace, columnFamily, key, encodedProperties });
        client.insert(keySpace, columnFamily, key, encodedProperties, probablyNew);
        if (sharedCache != null) {
            // if we just added a value in, remove the key so that any stale
            // state (including a previously deleted object is removed)
            sharedCache.remove(cacheKey);
        }
    }

Put an object in the cache

@param keySpace
@param columnFamily
@param key
@param encodedProperties
the object to be stored
@param probablyNew
whether or not this object is new.
@throws StorageClientException


public Map<URI, String> getCfLocations(){
		if(this.needsReRun==true){
			this.locationMap.clear();
			String pathSep = System.getProperty("path.separator");
			String classpath = System.getProperty("java.class.path");
			StringTokenizer st = new StringTokenizer(classpath, pathSep);

			File file = null;
			while(st.hasMoreTokens()){
				String path = st.nextToken();
				file = new File(path);
				this.include(file);
			}
		}

		this.needsReRun = false;
		return this.locationMap;
	}

public Map < URI , String > getCfLocations ( ) { if ( this . needsReRun == true ) { this . locationMap . clear ( ) ; String pathSep = System . getProperty ( "path.separator" ) ; String classpath = System . getProperty ( "java.class.path" ) ; StringTokenizer st = new StringTokenizer ( classpath , pathSep ) ; File file = null ; while ( st . hasMoreTokens ( ) ) { String path = st . nextToken ( ) ; file = new File ( path ) ; this . include ( file ) ; } } this . needsReRun = false ; return this . locationMap ; }

Runs the locator and collects all locations using the filters if set.
The method can be called multiple times and will only result in a new map if any of the filters have been changed.
If no filter has been changed, the current map will be returned.
@return returns a map with all found locations, empty if none found

Runs the locator and collects all locations using the filters if set . The method can be called multiple times and will only result in a new map if any of the filters have been changed . If no filter has been changed the current map will be returned .


protected final void include(String name, File file){
		if(!file.exists()){
			return;
		}
		if(!file.isDirectory()){
			if(this.jarFilter.size()>0){
				boolean ok = false;
				for(String s : this.jarFilter){
					if(file.getName().startsWith(s)){
						ok = true;
					}
				}
				if(ok==false){
					return;
				}
			}
			this.includeJar(file);
			return;
		}

		if(name==null){
			name = "";
		}
		else{
			name += ".";
		}

		File[] dirs = file.listFiles(CF_Utils.DIRECTORIES_ONLY);
		for(int i=0; i<dirs.length; i++){
			try{
				this.locationMap.put(new URI("file://" + dirs[i].getCanonicalPath()), name + dirs[i].getName());
			}
			catch(IOException ignore){return;}
			catch(URISyntaxException ignore){return;}

			this.include(name + dirs[i].getName(), dirs[i]);
		}
	}

protected final void include ( String name , File file ) { if ( ! file . exists ( ) ) { return ; } if ( ! file . isDirectory ( ) ) { if ( this . jarFilter . size ( ) > 0 ) { boolean ok = false ; for ( String s : this . jarFilter ) { if ( file . getName ( ) . startsWith ( s ) ) { ok = true ; } } if ( ok == false ) { return ; } } this . includeJar ( file ) ; return ; } if ( name == null ) { name = "" ; } else { name += "." ; } File [ ] dirs = file . listFiles ( CF_Utils . DIRECTORIES_ONLY ) ; for ( int i = 0 ; i < dirs . length ; i ++ ) { try { this . locationMap . put ( new URI ( "file://" + dirs [ i ] . getCanonicalPath ( ) ) , name + dirs [ i ] . getName ( ) ) ; } catch ( IOException ignore ) { return ; } catch ( URISyntaxException ignore ) { return ; } this . include ( name + dirs [ i ] . getName ( ) , dirs [ i ] ) ; } }

Include a name and file
@param name name to be included, if null will be set to empty
@param file file to be included


private void includeJar(File file){
		if(file.isDirectory()){
			return;
		}

		URL jarURL = null;
		JarFile jar = null;
		try{
			jarURL = new URL("jar:" + new URL("file:/" + file.getCanonicalPath()).toExternalForm() + "!/");
			JarURLConnection conn = (JarURLConnection)jarURL.openConnection();
			jar = conn.getJarFile();
		}
		catch(MalformedURLException ignore){return;}
		catch(IOException ignore){return;}

		if(jar==null){
			return;
		}

		try{
			this.locationMap.put(jarURL.toURI(), "");
		}
		catch(URISyntaxException ignore){}

		for(Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();){
			JarEntry entry = e.nextElement();
			if(this.pkgFilter!=null && entry.getName().startsWith(this.pkgFilter)){
				continue;
			}
			if(entry.isDirectory()){
				if(entry.getName().toUpperCase(Locale.ENGLISH).equals("META-INF/")){
					continue;
				}
				try{
					this.locationMap.put(new URI(jarURL.toExternalForm() + entry.getName()), CF_Utils.getPkgName(entry));
				}
				catch(URISyntaxException ignore){continue;}
			}
		}
	}

private void includeJar ( File file ) { if ( file . isDirectory ( ) ) { return ; } URL jarURL = null ; JarFile jar = null ; try { jarURL = new URL ( "jar:" + new URL ( "file:/" + file . getCanonicalPath ( ) ) . toExternalForm ( ) + "!/" ) ; JarURLConnection conn = ( JarURLConnection ) jarURL . openConnection ( ) ; jar = conn . getJarFile ( ) ; } catch ( MalformedURLException ignore ) { return ; } catch ( IOException ignore ) { return ; } if ( jar == null ) { return ; } try { this . locationMap . put ( jarURL . toURI ( ) , "" ) ; } catch ( URISyntaxException ignore ) { } for ( Enumeration < JarEntry > e = jar . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; if ( this . pkgFilter != null && entry . getName ( ) . startsWith ( this . pkgFilter ) ) { continue ; } if ( entry . isDirectory ( ) ) { if ( entry . getName ( ) . toUpperCase ( Locale . ENGLISH ) . equals ( "META-INF/" ) ) { continue ; } try { this . locationMap . put ( new URI ( jarURL . toExternalForm ( ) + entry . getName ( ) ) , CF_Utils . getPkgName ( entry ) ) ; } catch ( URISyntaxException ignore ) { continue ; } } } }

Include from a jar file
@param file jar file


public static void addSaslMech(String mech) {
        initialize();

        if (!defaultMechs.contains(mech)) {
            defaultMechs.add(mech);
        }
    }

public static void addSaslMech ( String mech ) { initialize ( ) ; if ( ! defaultMechs . contains ( mech ) ) { defaultMechs . add ( mech ) ; } }

Add a SASL mechanism to the list to be used.

@param mech
the SASL mechanism to be added

Add a SASL mechanism to the list to be used .


public static void addSaslMechs(Collection<String> mechs) {
        initialize();

        for (String mech : mechs) {
            addSaslMech(mech);
        }
    }

public static void addSaslMechs ( Collection < String > mechs ) { initialize ( ) ; for ( String mech : mechs ) { addSaslMech ( mech ) ; } }

Add a Collection of SASL mechanisms to the list to be used.

@param mechs
the Collection of SASL mechanisms to be added

Add a Collection of SASL mechanisms to the list to be used .


private void createDebug() {
        // Create a special Reader that wraps the main Reader and logs data to
        // the GUI.
        ObservableReader debugReader = new ObservableReader(reader);
        readerListener = new ReaderListener() {
            public void read(String str) {
                System.out.println(dateFormatter.format(new Date()) + " RCV  ("
                        + connection.hashCode() + "): " + str);
            }
        };
        debugReader.addReaderListener(readerListener);

        // Create a special Writer that wraps the main Writer and logs data to
        // the GUI.
        ObservableWriter debugWriter = new ObservableWriter(writer);
        writerListener = new WriterListener() {
            public void write(String str) {
                System.out.println(dateFormatter.format(new Date()) + " SENT ("
                        + connection.hashCode() + "): " + str);
            }
        };
        debugWriter.addWriterListener(writerListener);

        // Assign the reader/writer objects to use the debug versions. The
        // packet reader
        // and writer will use the debug versions when they are created.
        reader = debugReader;
        writer = debugWriter;

        // Create a thread that will listen for all incoming packets and write
        // them to
        // the GUI. This is what we call "interpreted" packet data, since it's
        // the packet
        // data as Smack sees it and not as it's coming in as raw XML.
        listener = new PacketListener() {
            public void processPacket(Packet packet) {
                if (printInterpreted) {
                    System.out.println(dateFormatter.format(new Date())
                            + " RCV PKT (" + connection.hashCode() + "): "
                            + packet.toXML());
                }
            }
        };

        connListener = new ConnectionListener() {
            public void connectionClosed() {
                System.out.println(dateFormatter.format(new Date())
                        + " Connection closed (" + connection.hashCode() + ")");
            }

            public void connectionClosedOnError(Exception e) {
                System.out.println(dateFormatter.format(new Date())
                        + " Connection closed due to an exception ("
                        + connection.hashCode() + ")");
                e.printStackTrace();
            }

            public void reconnectionFailed(Exception e) {
                System.out.println(dateFormatter.format(new Date())
                        + " Reconnection failed due to an exception ("
                        + connection.hashCode() + ")");
                e.printStackTrace();
            }

            public void reconnectionSuccessful() {
                System.out.println(dateFormatter.format(new Date())
                        + " Connection reconnected (" + connection.hashCode()
                        + ")");
            }

            public void reconnectingIn(int seconds) {
                System.out.println(dateFormatter.format(new Date())
                        + " Connection (" + connection.hashCode()
                        + ") will reconnect in " + seconds);
            }
        };
    }

Creates the listeners that will print in the console when new activity is
detected.

Creates the listeners that will print in the console when new activity is detected .


protected void activate(Map<String, Object> properties) throws Exception {
		configProperties = properties;
		String[] safePostProcessorNames = (String[]) configProperties
				.get(SAFE_POSTPROCESSORS);
		if (safePostProcessorNames == null) {
			safeOpenProcessors.add("rss");
			safeOpenProcessors.add("trustedLoginTokenProxyPostProcessor");
		} else {
			for (String pp : safePostProcessorNames) {
				safeOpenProcessors.add(pp);
			}
		}

		// allow communications via a proxy server if command line
		// java parameters http.proxyHost,http.proxyPort,http.proxyUser,
		// http.proxyPassword have been provided.
		String proxyHost = System.getProperty("http.proxyHost", "");
		if (!proxyHost.equals("")) {
			useJreProxy = true;
		}
	}

Create resources used by this component.

@param ctx
@throws Exception

Create resources used by this component .


private void registerStandardEvents() {
        CommonEvents.Descriptors.stopListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.generalLeavingListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.generalListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.leavingListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.presenceListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.strictLeavingListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Presence.strictListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Response.fullResponseListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Response.majorResponseListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Response.minorResponseListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Type.notificationListener(this).ifPresent(this::registerEventListener);
        CommonEvents.Type.responseListener(this).ifPresent(this::registerEventListener);
    }

private void registerStandardEvents ( ) { CommonEvents . Descriptors . stopListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . leavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . presenceListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . fullResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . majorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . minorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . notificationListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . responseListener ( this ) . ifPresent ( this :: registerEventListener ) ; }


public void registerEventListener(EventListener eventListener) {
        registerEventID(eventListener.getDescription(),
                eventListener.getDescriptorID(), eventListener.getDescriptor());
    }

public void registerEventListener ( EventListener eventListener ) { registerEventID ( eventListener . getDescription ( ) , eventListener . getDescriptorID ( ) , eventListener . getDescriptor ( ) ) ; }

Registers or adds an event to the local_events.properties file with the informations found in the EventListener

@param eventListener the eventListener to add

Registers or adds an event to the local_events . properties file with the informations found in the EventListener


public void registerEventID(String description, String key, String value) {
        BufferedWriter bufferedWriter;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(eventPropertiesPath, true);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(out));
            doWithLock(out.getChannel(), lock -> {
                unlockedReloadFile();
                if (getEventID(key) != null) {
                    return;
                }
                try {
                    bufferedWriter.write("\n\n" + key + "_DESCRIPTION = " + description + "\n" + key + " = " + value);
                    bufferedWriter.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (FileNotFoundException e) {
            error("Unable find file", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                error("Unable to close lock", e);
            }
        }
    }

public
void
registerEventID
(
String
description
,
String
key
,
String
value
)
{
BufferedWriter
bufferedWriter
;
FileOutputStream
out
=
;
try
{
out
=
new
FileOutputStream
(
eventPropertiesPath
,
true
)
;
bufferedWriter
=
new
BufferedWriter
(
new
OutputStreamWriter
(
out
)
)
;
doWithLock
(
out
.
getChannel
(
)
,
lock
->
{
unlockedReloadFile
(
)
;
if
(
getEventID
(
key
)
!=
)
{
return
;
}
try
{
bufferedWriter
.
write
(
"\n\n"
+
key
+
"_DESCRIPTION = "
+
description
+
"\n"
+
key
+
" = "
+
value
)
;
bufferedWriter
.
flush
(
)
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
)
;
}
}
)
;
}
catch
(
FileNotFoundException
e
)
{
error
(
"Unable find file"
,
e
)
;
}
finally
{
try
{
if
(
out
!=
)
{
out
.
close
(
)
;
}
}
catch
(
IOException
e
)
{
error
(
"Unable to close lock"
,
e
)
;
}
}
}

Registers or adds an event to the local_events.properties file

@param description a simple description of the Event
@param key the key with which to store the event ID
@param value the complete event ID

Registers or adds an event to the local_events . properties file


private void doWithLock(FileChannel channel, Consumer<FileLock> consumer) {
        FileLock lock = null;
        try {
            while (lock == null) {
                try {
                    lock = channel.tryLock();
                } catch (OverlappingFileLockException e) {
                    Thread.sleep(500);
                }
            }
            consumer.accept(lock);
        } catch (IOException | InterruptedException e) {
            error("Unable to write", e);
        } finally {
            try {
                if (lock != null) {
                    lock.release();
                }
            } catch (IOException e) {
                error("Unable to close lock", e);
            }
        }
    }

private
void
doWithLock
(
FileChannel
channel
,
Consumer
<
FileLock
>
consumer
)
{
FileLock
lock
=
;
try
{
while
(
lock
==
)
{
try
{
lock
=
channel
.
tryLock
(
)
;
}
catch
(
OverlappingFileLockException
e
)
{
Thread
.
sleep
(
500
)
;
}
}
consumer
.
accept
(
lock
)
;
}
catch
(
IOException
|
InterruptedException
e
)
{
error
(
"Unable to write"
,
e
)
;
}
finally
{
try
{
if
(
lock
!=
)
{
lock
.
release
(
)
;
}
}
catch
(
IOException
e
)
{
error
(
"Unable to close lock"
,
e
)
;
}
}
}

executes with a lock
@param channel the channel where the lock is acquired from
@param consumer the consumer to execute


public void unregisterEventID(String eventKey) {
        properties.remove(eventKey + "_DESCRIPTION");
        properties.remove(eventKey);

        FileOutputStream out = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;

        try {
            out = new FileOutputStream(eventPropertiesPath, true);

            final File tempFile = new File(eventPropertiesPath + "temp.properties");
            final BufferedReader readerFinal = new BufferedReader(new FileReader(eventPropertiesPath));
            final BufferedWriter writerFinal = new BufferedWriter(new FileWriter(tempFile));

            doWithLock(out.getChannel(), lock -> {
                unlockedReloadFile();
                if (getEventID(eventKey) != null) {
                    return;
                }

                try {
                    String currentLine = readerFinal.readLine();
                    while(currentLine != null) {
                        String trimmedLine = currentLine.trim();
                        if(trimmedLine.equals(eventKey + "_DESCRIPTION") || trimmedLine.equals(eventKey)) continue;
                        writerFinal.write(currentLine + System.getProperty("line.separator"));
                        currentLine = readerFinal.readLine();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            reader = readerFinal;
            writer = writerFinal;
            tempFile.renameTo(new File(eventPropertiesPath));
        } catch (IOException e) {
            error("Unable find file", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                error("Unable to close lock", e);
            }
        }
    }

public
void
unregisterEventID
(
String
eventKey
)
{
properties
.
remove
(
eventKey
+
"_DESCRIPTION"
)
;
properties
.
remove
(
eventKey
)
;
FileOutputStream
out
=
;
BufferedReader
reader
=
;
BufferedWriter
writer
=
;
try
{
out
=
new
FileOutputStream
(
eventPropertiesPath
,
true
)
;
final
File
tempFile
=
new
File
(
eventPropertiesPath
+
"temp.properties"
)
;
final
BufferedReader
readerFinal
=
new
BufferedReader
(
new
FileReader
(
eventPropertiesPath
)
)
;
final
BufferedWriter
writerFinal
=
new
BufferedWriter
(
new
FileWriter
(
tempFile
)
)
;
doWithLock
(
out
.
getChannel
(
)
,
lock
->
{
unlockedReloadFile
(
)
;
if
(
getEventID
(
eventKey
)
!=
)
{
return
;
}
try
{
String
currentLine
=
readerFinal
.
readLine
(
)
;
while
(
currentLine
!=
)
{
String
trimmedLine
=
currentLine
.
trim
(
)
;
if
(
trimmedLine
.
equals
(
eventKey
+
"_DESCRIPTION"
)
||
trimmedLine
.
equals
(
eventKey
)
)
continue
;
writerFinal
.
write
(
currentLine
+
System
.
getProperty
(
"line.separator"
)
)
;
currentLine
=
readerFinal
.
readLine
(
)
;
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
)
;
}
}
)
;
reader
=
readerFinal
;
writer
=
writerFinal
;
tempFile
.
renameTo
(
new
File
(
eventPropertiesPath
)
)
;
}
catch
(
IOException
e
)
{
error
(
"Unable find file"
,
e
)
;
}
finally
{
try
{
if
(
out
!=
)
{
out
.
close
(
)
;
}
if
(
writer
!=
)
{
writer
.
close
(
)
;
}
if
(
reader
!=
)
{
reader
.
close
(
)
;
}
}
catch
(
IOException
e
)
{
error
(
"Unable to close lock"
,
e
)
;
}
}
}

Unregisters or deletes an event from the local_events.properties file

@param eventKey the key under which the complete event ID is stored in the properties file

Unregisters or deletes an event from the local_events . properties file


@Override
    public boolean canRun(EventModel event) {
        //noinspection SimplifiableIfStatement
        if (event != null) {
            return event.getListResourceContainer().providesResource(getResourceIdWishList());
        }
        return false;
    }

@
Override
public
boolean
canRun
(
EventModel
event
)
{
//noinspection SimplifiableIfStatement
if
(
event
!=
)
{
return
event
.
getListResourceContainer
(
)
.
providesResource
(
getResourceIdWishList
(
)
)
;
}
return
false
;
}

Checks if the outputExtension can execute with the current event

@param event the event to check against
@return the state of whether the outputExtension can execute with the current event


public static DseSession newDseSession(DseCluster cluster, String keyspace) {
        return cluster.connect(StringUtils.isBlank(keyspace) ? null : keyspace);
    }

public static DseSession newDseSession ( DseCluster cluster , String keyspace ) { return cluster . connect ( StringUtils . isBlank ( keyspace ) ? null : keyspace ) ; }

Create a new session for a DSE cluster, initializes it and sets the keyspace
to the provided one.

@param cluster
@param keyspace
@return
@throws NoHostAvailableException
@throws AuthenticationException
@throws IllegalStateException

Create a new session for a DSE cluster initializes it and sets the keyspace to the provided one .


public static Optional<PlayerError> createMusicPlayerError(Identification source, String error) {
        if (error == null || error.isEmpty())
            return Optional.empty();
        try {
            PlayerError playerError = new PlayerError(source);
            playerError.addResource(new MusicErrorResource(source, error));
            return Optional.of(playerError);
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }

public static Optional < PlayerError > createMusicPlayerError ( Identification source , String error ) { if ( error == null || error . isEmpty ( ) ) return Optional . empty ( ) ; try { PlayerError playerError = new PlayerError ( source ) ; playerError . addResource ( new MusicErrorResource ( source , error ) ) ; return Optional . of ( playerError ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }

creates a new MusicPlayerError
@param source the source
@param error the error (not null and not empty)
@return the optional event


public void startPlaying(TrackInfo trackInfo) {
        Optional<Identification> ownIdentification = IdentificationManagerM.getInstance()
                .getIdentification(this);
        Optional<Identification> playerIdentification = IdentificationManagerM.getInstance()
                .getIdentification(player);
        if (!ownIdentification.isPresent() || !playerIdentification.isPresent()) {
            error("unable to obtain identification");
            return;
        }
        StartMusicRequest.createStartMusicRequest(ownIdentification.get(), playerIdentification.get(), trackInfo, player.isUsingJava)
                .ifPresent(event -> fire(event, 5));

    }

public
void
startPlaying
(
TrackInfo
trackInfo
)
{
Optional
<
Identification
>
ownIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
this
)
;
Optional
<
Identification
>
playerIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
player
)
;
if
(
!
ownIdentification
.
isPresent
(
)
||
!
playerIdentification
.
isPresent
(
)
)
{
error
(
"unable to obtain identification"
)
;
return
;
}
StartMusicRequest
.
createStartMusicRequest
(
ownIdentification
.
get
(
)
,
playerIdentification
.
get
(
)
,
trackInfo
,
player
.
isUsingJava
)
.
ifPresent
(
event
->
fire
(
event
,
5
)
)
;
}

starts the playing command
@param trackInfo the track to play


public void stopPlaying() {
        Optional<Identification> ownIdentification = IdentificationManagerM.getInstance()
                .getIdentification(this);
        Optional<Identification> playerIdentification = IdentificationManagerM.getInstance()
                .getIdentification(player);
        if (!ownIdentification.isPresent()|| !playerIdentification.isPresent()) {
            error("unable to obtain id");
            return;
        }
        StopMusic.createStopMusic(ownIdentification.get(), playerIdentification.get())
                .ifPresent(event -> fire(event, 5));
    }

public
void
stopPlaying
(
)
{
Optional
<
Identification
>
ownIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
this
)
;
Optional
<
Identification
>
playerIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
player
)
;
if
(
!
ownIdentification
.
isPresent
(
)
||
!
playerIdentification
.
isPresent
(
)
)
{
error
(
"unable to obtain id"
)
;
return
;
}
StopMusic
.
createStopMusic
(
ownIdentification
.
get
(
)
,
playerIdentification
.
get
(
)
)
.
ifPresent
(
event
->
fire
(
event
,
5
)
)
;
}


public void command(String command, Playlist playlist, Progress progress, TrackInfo trackInfo, Volume volume) {
        Optional<Identification> ownIdentification = IdentificationManagerM.getInstance()
                .getIdentification(this);
        Optional<Identification> playerIdentification = IdentificationManagerM.getInstance()
                .getIdentification(player);
        if (!ownIdentification.isPresent()|| !playerIdentification.isPresent()) {
            error("unable to obtain id");
            return;
        }
        Optional<PlayerCommand> playerCommand = PlayerCommand.createPlayerCommand(ownIdentification.get(),
                playerIdentification.get(), command, player.getCapabilities(), getContext());
        if (playlist != null) {
            playerCommand.get().addResource(new PlaylistResource(ownIdentification.get(), playlist));
        }
        if (progress != null) {
            playerCommand.get().addResource(new ProgressResource(ownIdentification.get(), progress));
        }
        if (trackInfo != null) {
            playerCommand.get().addResource(new TrackInfoResource(ownIdentification.get(), trackInfo));
        }
        if (volume != null) {
            playerCommand.get().addResource(new VolumeResource(ownIdentification.get(), volume));
        }
        fire(playerCommand.get(), 5);
    }

public
void
command
(
String
command
,
Playlist
playlist
,
Progress
progress
,
TrackInfo
trackInfo
,
Volume
volume
)
{
Optional
<
Identification
>
ownIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
this
)
;
Optional
<
Identification
>
playerIdentification
=
IdentificationManagerM
.
getInstance
(
)
.
getIdentification
(
player
)
;
if
(
!
ownIdentification
.
isPresent
(
)
||
!
playerIdentification
.
isPresent
(
)
)
{
error
(
"unable to obtain id"
)
;
return
;
}
Optional
<
PlayerCommand
>
playerCommand
=
PlayerCommand
.
createPlayerCommand
(
ownIdentification
.
get
(
)
,
playerIdentification
.
get
(
)
,
command
,
player
.
getCapabilities
(
)
,
getContext
(
)
)
;
if
(
playlist
!=
)
{
playerCommand
.
get
(
)
.
addResource
(
new
PlaylistResource
(
ownIdentification
.
get
(
)
,
playlist
)
)
;
}
if
(
progress
!=
)
{
playerCommand
.
get
(
)
.
addResource
(
new
ProgressResource
(
ownIdentification
.
get
(
)
,
progress
)
)
;
}
if
(
trackInfo
!=
)
{
playerCommand
.
get
(
)
.
addResource
(
new
TrackInfoResource
(
ownIdentification
.
get
(
)
,
trackInfo
)
)
;
}
if
(
volume
!=
)
{
playerCommand
.
get
(
)
.
addResource
(
new
VolumeResource
(
ownIdentification
.
get
(
)
,
volume
)
)
;
}
fire
(
playerCommand
.
get
(
)
,
5
)
;
}

commands the player to fulfill the command
@param command the command
@param playlist the playlist, or null if not needed
@param progress the progress, or null if not needed
@param trackInfo the trackInfo, or null if not needed
@param volume the volume, or null if not needed


public static BroadcasterPlaylist createPlaylistRequest(Identification provider, String playlistName) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(RESOURCE_ID, playlistName);
        return new BroadcasterPlaylist(provider, hashMap);
    }

public static BroadcasterPlaylist createPlaylistRequest ( Identification provider , String playlistName ) { HashMap < String , Object > hashMap = new HashMap <> ( ) ; hashMap . put ( RESOURCE_ID , playlistName ) ; return new BroadcasterPlaylist ( provider , hashMap ) ; }

creates the Playlist-Request
@param provider the provider of the playlist
@param playlistName the name of the playlist
@return the resource


public static BroadcasterPlaylist createPlaylistAnswer(Identification provider, Playlist playlist) {
        return new BroadcasterPlaylist(provider, playlist.export());
    }

public static BroadcasterPlaylist createPlaylistAnswer ( Identification provider , Playlist playlist ) { return new BroadcasterPlaylist ( provider , playlist . export ( ) ) ; }

creates the Playlist-Answer
@param provider the provider
@param playlist the playlist
@return the resource


public UrlBuilder append(boolean encode,String... postFix) {
        for (String part : postFix) {
            if(StringUtils.isNotBlank(part)) {
                if (url.charAt(url.length() - 1) != '/' && !part.startsWith("/")) {
                    url.append('/');
                }
                if(encode) {
                    try {
                        url.append(URLEncoder.encode(part, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new IllegalStateException(e);
                    }
                } else {
                    url.append(part);
                }
            }
        }
        return this;
    }

public UrlBuilder append ( boolean encode , String ... postFix ) { for ( String part : postFix ) { if ( StringUtils . isNotBlank ( part ) ) { if ( url . charAt ( url . length ( ) - 1 ) != ' ' && ! part . startsWith ( "/" ) ) { url . append ( ' ' ) ; } if ( encode ) { try { url . append ( URLEncoder . encode ( part , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } else { url . append ( part ) ; } } } return this ; }

Appends one or more postfixes and separates them by slashes.
@param encode if true, the postFixes are url encoded.
@param postFix one or more String values
@return the builder

Appends one or more postfixes and separates them by slashes .


public UrlBuilder queryParam(String name, Boolean value) {
        if(value != null) {
            return queryParam(name, value.toString());
        } else {
            return null;
        }
    }

public UrlBuilder queryParam ( String name , Boolean value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }

Create a query parameter with a boolean value.
@param name parameter name
@param value value
@return the builder

Create a query parameter with a boolean value .


public UrlBuilder queryParam(String name, Number value) {
        if(value != null) {
            return queryParam(name, value.toString());
        } else {
            return null;
        }
    }

public UrlBuilder queryParam ( String name , Number value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }

Create a query parameter with a number value.
@param name parameter name
@param value value
@return the builder

Create a query parameter with a number value .


public UrlBuilder queryParam(String name, String value) {
        return queryParam(name, value, true);
    }

public UrlBuilder queryParam ( String name , String value ) { return queryParam ( name , value , true ) ; }

Create a query parameter with a String value. The value will be urlencoded.
@param name name
@param value value
@return the builder

Create a query parameter with a String value . The value will be urlencoded .


public UrlBuilder queryParam(String name, String value, boolean encode) {
        if (StringUtils.isNotEmpty(value)) {
            if (encode) {
                try {
                    value = URLEncoder.encode(value, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new IllegalStateException(e);
                }
            }
            params.add(new EntryImpl(name, value));
        }
        return this;
    }

public UrlBuilder queryParam ( String name , String value , boolean encode ) { if ( StringUtils . isNotEmpty ( value ) ) { if ( encode ) { try { value = URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } params . add ( new EntryImpl ( name , value ) ) ; } return this ; }

Create a query parameter with a String value.
@param name name
@param value value
@param encode if true, the value is urlencoded.
@return the builder

Create a query parameter with a String value .


public static Optional<Playlist> getPlaylist(EventModel eventModel) {
        if (eventModel.getListResourceContainer().containsResourcesFromSource(ID)) {
            return eventModel
                    .getListResourceContainer()
                    .provideResource(ID)
                    .stream()
                    .findAny()
                    .flatMap(Playlist::importResource);
        } else {
            return Optional.empty();
        }
    }

public static Optional < Playlist > getPlaylist ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . findAny ( ) . flatMap ( Playlist :: importResource ) ; } else { return Optional . empty ( ) ; } }

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


private void launchButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // Launch Nakamura
    if (runStatus == APP_NOT_RUNNING) {
      System.setSecurityManager(null);
      try {
        NakamuraMain.main(savedArgs);

        // Update label
        statusLabel.setText("Nakamura is starting...");

        // Notify the user
        JOptionPane.showMessageDialog(this,
            "Nakamura has been started.\nPlease allow 30-60 seconds for it to be ready.",
            "Information", JOptionPane.INFORMATION_MESSAGE);

        runStatus = APP_RUNNING;
        isStartupFinished();
      } catch (IOException e) {
        statusLabel.setText("Nakamura is startup failed " + e.getMessage());
      }
    } else {
      // Can't start it again...
      // custom title, warning icon
      JOptionPane.showMessageDialog(this, "Nakamura is already running.", "Warning",
          JOptionPane.WARNING_MESSAGE);
    }
  }

This is the launch button action method. This method launches the Apache Sling
bootloader and informs the user to wait before accessing it in a browser.

@param evt
The details of the Action event.
@throws IOException

This is the launch button action method . This method launches the Apache Sling bootloader and informs the user to wait before accessing it in a browser .


private void isStartupFinished() {
    boolean started = false;
    try {
      while (!started) {
        if (exists(localhostURL))
          started = true;
        Thread.sleep(5 * 1000);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    if (started) {
      statusLabel.setText("Nakamura is running.");
      statusLabel.setForeground(Color.green);
      launchButton.setEnabled(false);
      browserButton.setEnabled(true);
    }
  }

private
void
isStartupFinished
(
)
{
boolean
started
=
false
;
try
{
while
(
!
started
)
{
if
(
exists
(
localhostURL
)
)
started
=
true
;
Thread
.
sleep
(
5
*
1000
)
;
}
}
catch
(
InterruptedException
e
)
{
e
.
printStackTrace
(
)
;
}
if
(
started
)
{
statusLabel
.
setText
(
"Nakamura is running."
)
;
statusLabel
.
setForeground
(
Color
.
green
)
;
launchButton
.
setEnabled
(
false
)
;
browserButton
.
setEnabled
(
true
)
;
}
}

Pings the Apache Sling server URL every 5 seconds to see if it has finished booting.
Once it receives an OK status, it enables the button to launch the browser and
disables the launch Nakamura button.

Pings the Apache Sling server URL every 5 seconds to see if it has finished booting . Once it receives an OK status it enables the button to launch the browser and disables the launch Nakamura button .


public static boolean exists(String URLName) {
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      // HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

Pings the Apache Sling server URL, looking for an OK status. Returns true once that
OK status is received.

@param URLName
The URL to ping.
@return true if OK status is received back. False if not OK.

Pings the Apache Sling server URL looking for an OK status . Returns true once that OK status is received .


private void browserButtonActionPerformed(java.awt.event.ActionEvent evt) {
    try {
      Desktop.getDesktop().browse(new URL(localhostURL).toURI());
    } catch (IOException e) {
      System.err.println("IO Exception: " + e.getMessage());
    } catch (URISyntaxException e) {
      System.err.println("URISyntaxException: " + e.getMessage());
    }
  }

private
void
browserButtonActionPerformed
(
java
.
awt
.
event
.
ActionEvent
evt
)
{
try
{
Desktop
.
getDesktop
(
)
.
browse
(
new
URL
(
localhostURL
)
.
toURI
(
)
)
;
}
catch
(
IOException
e
)
{
System
.
err
.
println
(
"IO Exception: "
+
e
.
getMessage
(
)
)
;
}
catch
(
URISyntaxException
e
)
{
System
.
err
.
println
(
"URISyntaxException: "
+
e
.
getMessage
(
)
)
;
}
}

Performs the action when the browser button is pressed, which is launch a web browser
and browse to the server URL.

@param evt
The details of the event.

Performs the action when the browser button is pressed which is launch a web browser and browse to the server URL .


protected ImageIcon createImageIcon(String path, String description) {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL, description);
    } else {
      System.err.println("Couldn't find file: " + path);
      return null;
    }
  }

protected
ImageIcon
createImageIcon
(
String
path
,
String
description
)
{
java
.
net
.
URL
imgURL
=
getClass
(
)
.
getResource
(
path
)
;
if
(
imgURL
!=
)
{
return
new
ImageIcon
(
imgURL
,
description
)
;
}
else
{
System
.
err
.
println
(
"Couldn't find file: "
+
path
)
;
return
;
}
}

Returns an ImageIcon, or null if the path was invalid.

@param path
The path to the icon.
@param description
The description of the icon.
@return the newly created ImageIcon or null.

Returns an ImageIcon or null if the path was invalid .


public static void main(String args[]) {
    savedArgs = args;
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        new LaunchNakamura().setVisible(true);
      }
    });
  }

public static void main ( String args [ ] ) { savedArgs = args ; java . awt . EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { new LaunchNakamura ( ) . setVisible ( true ) ; } } ) ; }

The Main method which executes the program.

@param args
the command line arguments

The Main method which executes the program .


public IntArray with(int... values)
    {
        if (values.length != this.length)
            throw new IllegalArgumentException("Array size mismatch");
        value = values.clone();
        return this;
    }

public
IntArray
with
(
int
...
values
)
{
if
(
values
.
length
!=
this
.
length
)
throw
new
IllegalArgumentException
(
"Array size mismatch"
)
;
value
=
values
.
clone
(
)
;
return
this
;
}


public HashMap<String, Object> export() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(LEVEL_DESCRIPTOR, level.name());
        data.put(PRESENT_DESCRIPTOR, present);
        data.put(STRICT_DESCRIPTOR, strict);
        data.put(KNOWN_DESCRIPTOR, known);
        return data;
    }

public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( LEVEL_DESCRIPTOR , level . name ( ) ) ; data . put ( PRESENT_DESCRIPTOR , present ) ; data . put ( STRICT_DESCRIPTOR , strict ) ; data . put ( KNOWN_DESCRIPTOR , known ) ; return data ; }

exports the Presence to a HashMap
@return the resulting HashMap


public JSONResult get(int index) {
    if (value instanceof JSONArray) {
      JSONArray array = (JSONArray) value;
      Object result = array.get(index);
      return new JSONResult(result);
    } else if (value instanceof JSONObject) {
      return get(String.valueOf(index));
    }
    return new JSONResult(null);
  }

public JSONResult get ( int index ) { if ( value instanceof JSONArray ) { JSONArray array = ( JSONArray ) value ; Object result = array . get ( index ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONObject ) { return get ( String . valueOf ( index ) ) ; } return new JSONResult ( null ) ; }

Advance current JSON value to specified element in JSON array.
Set current JSON value to null otherwise.

@param index zero-based JSON array index
@return JSONResult for fluent method chaining

Advance current JSON value to specified element in JSON array . Set current JSON value to null otherwise .


public JSONResult get(String key) {
    if (value instanceof JSONObject) {
      JSONObject obj = (JSONObject) value;
      Object result = obj.get(key);
      return new JSONResult(result);
    } else if (value instanceof JSONArray) {
      try {
	int index = Integer.parseInt(key);
	return get(index);
      } catch(NumberFormatException e) {
        throw createException("Excpected JSONObject " + key + ":");
      }
    }
    return new JSONResult(null);
  }

public
JSONResult
get
(
String
key
)
{
if
(
value
instanceof
JSONObject
)
{
JSONObject
obj
=
(
JSONObject
)
value
;
Object
result
=
obj
.
get
(
key
)
;
return
new
JSONResult
(
result
)
;
}
else
if
(
value
instanceof
JSONArray
)
{
try
{
int
index
=
Integer
.
parseInt
(
key
)
;
return
get
(
index
)
;
}
catch
(
NumberFormatException
e
)
{
throw
createException
(
"Excpected JSONObject "
+
key
+
":"
)
;
}
}
return
new
JSONResult
(
)
;
}

Advance current JSON value to specified value of current JSON object.
Set current JSON value to null otherwise.

@param key element key
@return JSONResult for fluent method chaining

Advance current JSON value to specified value of current JSON object . Set current JSON value to null otherwise .


public Integer getInt(Integer defaultValue) {
    if (value instanceof Number) {
      return ((Number) value).intValue();
    }
    if (value instanceof String) {
      String s = (String) value;
      return Integer.parseInt(s);
    }
    if (value == null) {
      return defaultValue;
    }
    throw createException("Expected integer:");
  }

public
Integer
getInt
(
Integer
defaultValue
)
{
if
(
value
instanceof
Number
)
{
return
(
(
Number
)
value
)
.
intValue
(
)
;
}
if
(
value
instanceof
String
)
{
String
s
=
(
String
)
value
;
return
Integer
.
parseInt
(
s
)
;
}
if
(
value
==
)
{
return
defaultValue
;
}
throw
createException
(
"Expected integer:"
)
;
}

Return an integer for current JSON value, parsing string values as required.

Return an integer for current JSON value parsing string values as required .


public Double getDouble(Double defaultValue) {
    if (value instanceof Number) {
      return ((Number) value).doubleValue();
    }
    if (value instanceof String) {
      String s = (String) value;
      return Double.parseDouble(s);
    }
    if (value == null) {
      return defaultValue;
    }
    throw createException("Expected number:");
  }

public
Double
getDouble
(
Double
defaultValue
)
{
if
(
value
instanceof
Number
)
{
return
(
(
Number
)
value
)
.
doubleValue
(
)
;
}
if
(
value
instanceof
String
)
{
String
s
=
(
String
)
value
;
return
Double
.
parseDouble
(
s
)
;
}
if
(
value
==
)
{
return
defaultValue
;
}
throw
createException
(
"Expected number:"
)
;
}

Return a double number for current JSON value, parsing string values as required.

Return a double number for current JSON value parsing string values as required .


public String getString(String defaultValue) {
    if (value instanceof String || value instanceof Number) {
      return value.toString();
    }
    if (value == null) {
      return null;
    }
    if (value instanceof JSONArray) {
      return ((JSONArray) value).toJSONString();
    }
    if (value instanceof JSONObject) {
      return ((JSONObject) value).toJSONString();
    }
    if (value == null) {
      return defaultValue;
    }
    throw createException("Expected string:");
  }

public
String
getString
(
String
defaultValue
)
{
if
(
value
instanceof
String
||
value
instanceof
Number
)
{
return
value
.
toString
(
)
;
}
if
(
value
==
)
{
return
;
}
if
(
value
instanceof
JSONArray
)
{
return
(
(
JSONArray
)
value
)
.
toJSONString
(
)
;
}
if
(
value
instanceof
JSONObject
)
{
return
(
(
JSONObject
)
value
)
.
toJSONString
(
)
;
}
if
(
value
==
)
{
return
defaultValue
;
}
throw
createException
(
"Expected string:"
)
;
}

Return string value for current JSON value


public static Optional<CommandResource> createCommandResource(Identification provider, String command, Capabilities capabilities, Context context) {
        CommandResource commandResource = new CommandResource(provider, command, capabilities);
        if (!verifyCommand(command)) {
            context.getLogger().error("IllegalCommand!");
            return Optional.empty();
        }
        if (!verifyCapabilities(command, capabilities)) {
            context.getLogger().error("Player is not able to handle Command!");
            return Optional.empty();
        }
        return Optional.of(commandResource);
    }

public
static
Optional
<
CommandResource
>
createCommandResource
(
Identification
provider
,
String
command
,
Capabilities
capabilities
,
Context
context
)
{
CommandResource
commandResource
=
new
CommandResource
(
provider
,
command
,
capabilities
)
;
if
(
!
verifyCommand
(
command
)
)
{
context
.
getLogger
(
)
.
error
(
"IllegalCommand!"
)
;
return
Optional
.
empty
(
)
;
}
if
(
!
verifyCapabilities
(
command
,
capabilities
)
)
{
context
.
getLogger
(
)
.
error
(
"Player is not able to handle Command!"
)
;
return
Optional
.
empty
(
)
;
}
return
Optional
.
of
(
commandResource
)
;
}

creates a new Resource.

@param provider   the Provider of the Resource
@param command          the resource
@param capabilities the capabilities of the player
@param context used for logging
@return the commandResource if nothing illegal was passed


public static boolean verifyCommand(String command) {
        return command.equals(PLAY) ||
                command.equals(PAUSE) ||
                command.equals(STOP) ||
                command.equals(SELECT_TRACK) ||
                command.equals(NEXT) ||
                command.equals(PREVIOUS) ||
                command.equals(CHANGE_PLAYBACK) ||
                command.equals(CHANGE_VOLUME);
    }

public static boolean verifyCommand ( String command ) { return command . equals ( PLAY ) || command . equals ( PAUSE ) || command . equals ( STOP ) || command . equals ( SELECT_TRACK ) || command . equals ( NEXT ) || command . equals ( PREVIOUS ) || command . equals ( CHANGE_PLAYBACK ) || command . equals ( CHANGE_VOLUME ) ; }

verifies that an command is not malformed
@param command the Command
@return false if malformed


public static boolean verifyCapabilities(String command, Capabilities capabilities) {
        switch (command) {
            case PLAY: return capabilities.hasPlayPauseControl();
            case PAUSE: return capabilities.hasPlayPauseControl();
            case SELECT_TRACK: return capabilities.isAbleToSelectTrack();
            case NEXT: return capabilities.hasNextPrevious();
            case PREVIOUS: return capabilities.hasNextPrevious();
            case JUMP: return capabilities.isAbleToJump();
            case CHANGE_PLAYBACK: return capabilities.isPlaybackChangeable();
            case CHANGE_VOLUME: return capabilities.canChangeVolume();
            case STOP: return true;
        }
        return false;
    }

public static boolean verifyCapabilities ( String command , Capabilities capabilities ) { switch ( command ) { case PLAY : return capabilities . hasPlayPauseControl ( ) ; case PAUSE : return capabilities . hasPlayPauseControl ( ) ; case SELECT_TRACK : return capabilities . isAbleToSelectTrack ( ) ; case NEXT : return capabilities . hasNextPrevious ( ) ; case PREVIOUS : return capabilities . hasNextPrevious ( ) ; case JUMP : return capabilities . isAbleToJump ( ) ; case CHANGE_PLAYBACK : return capabilities . isPlaybackChangeable ( ) ; case CHANGE_VOLUME : return capabilities . canChangeVolume ( ) ; case STOP : return true ; } return false ; }

verifies that the player is capable of handling the command
@param command the command
@param capabilities the capabilities
@return true if capable, false if not


public static boolean verify(String command, Capabilities capabilities) {
        return verifyCommand(command) && verifyCapabilities(command, capabilities);
    }

public static boolean verify ( String command , Capabilities capabilities ) { return verifyCommand ( command ) && verifyCapabilities ( command , capabilities ) ; }

verifies tha the command is legal and able to be executed
@param command the command
@param capabilities the capabilities
@return true if able, false if not


public void executeBatchAsync(FutureCallback<ResultSet> callback, Statement... statements)
            throws ExceedMaxAsyncJobsException {
        if (!asyncSemaphore.tryAcquire()) {
            if (callback == null) {
                throw new ExceedMaxAsyncJobsException(maxSyncJobs);
            } else {
                callback.onFailure(new ExceedMaxAsyncJobsException(maxSyncJobs));
            }
        } else {
            try {
                ResultSetFuture rsf = CqlUtils.executeBatchAsync(getSession(), statements);
                if (callback != null) {
                    Futures.addCallback(rsf, wrapCallbackResultSet(callback), asyncExecutor);
                }
            } catch (Exception e) {
                asyncSemaphore.release();
                LOGGER.error(e.getMessage(), e);
            }
        }
    }

public void executeBatchAsync ( FutureCallback < ResultSet > callback , Statement ... statements ) throws ExceedMaxAsyncJobsException { if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { ResultSetFuture rsf = CqlUtils . executeBatchAsync ( getSession ( ) , statements ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } } }

Async-execute a batch statement.

The default session (obtained via {@link #getSession()} is used to execute the query.

@param callback
{@link ExceedMaxAsyncJobsException} will be passed to
{@link FutureCallback#onFailure(Throwable)} if number of async-jobs exceeds
{@link #getMaxAsyncJobs()}.
@param statements
@throws ExceedMaxAsyncJobsException
If number of running jobs exceeds a threshold and {@code callback} is
{@code null}.
@since 0.4.0


public Set<Class<?>> getSubclasses(Class<?> clazz){
		Set<Class<?>> ret = new HashSet<Class<?>>();
		Set<Class<?>> w = null;

		if(clazz!=null){
			this.clear();
			Map<URI, String> locations = this.locator.getCfLocations();
			for(Entry<URI, String> entry : locations.entrySet()){
				try{
					w = search(clazz, entry.getKey(), locations.get(entry.getKey()));
					if(w!=null && (w.size()>0)){
						ret.addAll(w);
					}
				}
				catch(MalformedURLException ex){}
			}
		}

		return ret;
	}

public Set < Class < ? > > getSubclasses ( Class < ? > clazz ) { Set < Class < ? > > ret = new HashSet < Class < ? > > ( ) ; Set < Class < ? > > w = null ; if ( clazz != null ) { this . clear ( ) ; Map < URI , String > locations = this . locator . getCfLocations ( ) ; for ( Entry < URI , String > entry : locations . entrySet ( ) ) { try { w = search ( clazz , entry . getKey ( ) , locations . get ( entry . getKey ( ) ) ) ; if ( w != null && ( w . size ( ) > 0 ) ) { ret . addAll ( w ) ; } } catch ( MalformedURLException ex ) { } } } return ret ; }

Returns all subclasses found for the given class.
@param clazz class to search for
@return all found subclasses

Returns all subclasses found for the given class .


public Set<Class<?>> getSubclasses(String fqcn){
		if(fqcn==null){
			return new HashSet<Class<?>>();
		}
		else if(StringUtils.startsWith(fqcn, ".") || StringUtils.endsWith(fqcn, ".")){
			return new HashSet<Class<?>>();
		}

		Class<?> clazz = null;
		try{
			clazz = Class.forName(fqcn);
		}
		catch(ClassNotFoundException ex){
			this.clear();
			this.errors.add(ex);
			return new HashSet<Class<?>>();
		}
		return getSubclasses(clazz);
	}

public Set < Class < ? > > getSubclasses ( String fqcn ) { if ( fqcn == null ) { return new HashSet < Class < ? > > ( ) ; } else if ( StringUtils . startsWith ( fqcn , "." ) || StringUtils . endsWith ( fqcn , "." ) ) { return new HashSet < Class < ? > > ( ) ; } Class < ? > clazz = null ; try { clazz = Class . forName ( fqcn ) ; } catch ( ClassNotFoundException ex ) { this . clear ( ) ; this . errors . add ( ex ) ; return new HashSet < Class < ? > > ( ) ; } return getSubclasses ( clazz ) ; }

Returns all subclasses found for the given fully qualified class name.
@param fqcn fully qualified class name, e.g. package and class name
@return all found subclasses

Returns all subclasses found for the given fully qualified class name .


private final Set<Class<?>> search(Class<?> clazz, URI location, String packageName) throws MalformedURLException{
		if(clazz==null || location==null){
			return new HashSet<Class<?>>();
		}

		File directory = new File(location.toURL().getFile());
		if(directory.exists()){
			return this.searchDirectory(clazz, directory, location, packageName).keySet();
		}
		else{
			return this.searchJar(clazz, location).keySet();
		}
	}

private final Set < Class < ? > > search ( Class < ? > clazz , URI location , String packageName ) throws MalformedURLException { if ( clazz == null || location == null ) { return new HashSet < Class < ? > > ( ) ; } File directory = new File ( location . toURL ( ) . getFile ( ) ) ; if ( directory . exists ( ) ) { return this . searchDirectory ( clazz , directory , location , packageName ) . keySet ( ) ; } else { return this . searchJar ( clazz , location ) . keySet ( ) ; } }

Returns all known subclasses for a given class, location and package name
@param clazz class to search for
@param location a URL to look into
@param packageName a package name
@return all found subclasses in location, empty set of none found
@throws MalformedURLException

Returns all known subclasses for a given class location and package name


protected final Map<Class<?>, URI> searchDirectory(Class<?> clazz, File directory, URI location, String packageName){
		Map<Class<?>, URI> ret = new HashMap<>();

		String[] files = directory.list();
		for(int i=0; i<files.length; i++){
			if(files[i].endsWith(".class")){
				String classname = files[i].substring(0, files[i].length()-6);
				try{
					Class<?> c = Class.forName(packageName + "." + classname);
					if(clazz.isAssignableFrom(c) && !clazz.getName().equals(packageName + "." + classname)){
						ret.put(c, location);
					}
				}
				catch(Exception ex){
					errors.add(ex);
				}
			}
		}
		return ret;
	}

protected final Map < Class < ? > , URI > searchDirectory ( Class < ? > clazz , File directory , URI location , String packageName ) { Map < Class < ? > , URI > ret = new HashMap <> ( ) ; String [ ] files = directory . list ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . endsWith ( ".class" ) ) { String classname = files [ i ] . substring ( 0 , files [ i ] . length ( ) - 6 ) ; try { Class < ? > c = Class . forName ( packageName + "." + classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( packageName + "." + classname ) ) { ret . put ( c , location ) ; } } catch ( Exception ex ) { errors . add ( ex ) ; } } } return ret ; }

Returns all known subclasses found in a given directory.
@param clazz class name to look for
@param directory search directory
@param location a URI location for return map
@param packageName a package name to test against class name
@return a map with found classes, empty if none found

Returns all known subclasses found in a given directory .


protected final Map<Class<?>, URI> searchJar(Class<?> clazz, URI location){
		Map<Class<?>, URI> ret = new HashMap<>();

		try{
			JarURLConnection conn = (JarURLConnection)location.toURL().openConnection();
			JarFile jarFile = conn.getJarFile();

			for(Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();){
				JarEntry entry = e.nextElement();
				String entryname = entry.getName();
				if(this.processed.contains(entryname)){
					continue;
				}
				this.processed.add(entryname);

				if(!entry.isDirectory() && entryname.endsWith(".class")){
					String classname = entryname.substring(0, entryname.length()-6);
					if(classname.startsWith("/")){
						classname = classname.substring(1);
					}
					classname = classname.replace('/','.');
					if(!StringUtils.startsWithAny(classname, this.excludedNames)){
						try{
							Class<?> c = Class.forName(classname);
							if(clazz.isAssignableFrom(c) && !clazz.getName().equals(classname)){
								ret.put(c, location);
							}
						}
						catch(Exception exception){
							errors.add(exception);
						}
						catch(Error error){
							errors.add(error);
						}
					}
				}
			}
		}
		catch(IOException ignore){
			errors.add(ignore);
		}

		return ret;
	}

protected final Map < Class < ? > , URI > searchJar ( Class < ? > clazz , URI location ) { Map < Class < ? > , URI > ret = new HashMap <> ( ) ; try { JarURLConnection conn = ( JarURLConnection ) location . toURL ( ) . openConnection ( ) ; JarFile jarFile = conn . getJarFile ( ) ; for ( Enumeration < JarEntry > e = jarFile . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; String entryname = entry . getName ( ) ; if ( this . processed . contains ( entryname ) ) { continue ; } this . processed . add ( entryname ) ; if ( ! entry . isDirectory ( ) && entryname . endsWith ( ".class" ) ) { String classname = entryname . substring ( 0 , entryname . length ( ) - 6 ) ; if ( classname . startsWith ( "/" ) ) { classname = classname . substring ( 1 ) ; } classname = classname . replace ( ' ' , ' ' ) ; if ( ! StringUtils . startsWithAny ( classname , this . excludedNames ) ) { try { Class < ? > c = Class . forName ( classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( classname ) ) { ret . put ( c , location ) ; } } catch ( Exception exception ) { errors . add ( exception ) ; } catch ( Error error ) { errors . add ( error ) ; } } } } } catch ( IOException ignore ) { errors . add ( ignore ) ; } return ret ; }

Returns all known subclasses found in a given location
@param clazz class name to look for
@param location a URI location for return map
@return a map with found classes, empty if none found


public List<Resource> toList() {
        List<Resource> resourceList = new ArrayList<>();
        resourceList.add(this);
        return resourceList;
    }

public List < Resource > toList ( ) { List < Resource > resourceList = new ArrayList <> ( ) ; resourceList . add ( this ) ; return resourceList ; }

creates a list with this Element in it.
@return a list

creates a list with this Element in it .


public int size()
    {
        int result = 0;
        // sum over all inner maps
        for ( Iterator<K1> keys1 = maps.keySet().iterator(); keys1.hasNext(); )
        {
            Map2<K2,K3,V> inner_map = maps.get(keys1.next());
            result += inner_map.size();
        }
        return result;
    }

public
int
size
(
)
{
int
result
=
0
;
// sum over all inner maps
for
(
Iterator
<
K1
>
keys1
=
maps
.
keySet
(
)
.
iterator
(
)
;
keys1
.
hasNext
(
)
;
)
{
Map2
<
K2
,
K3
,
V
>
inner_map
=
maps
.
get
(
keys1
.
next
(
)
)
;
result
+=
inner_map
.
size
(
)
;
}
return
result
;
}

Returns the accumulated size of all the bottom level maps.

Returns the accumulated size of all the bottom level maps .


protected void processPacket(Packet packet) {
        if (packet == null) {
            return;
        }

        if (packetFilter == null || packetFilter.accept(packet)) {
            while (!resultQueue.offer(packet)) {
                // Since we know the queue is full, this poll should never
                // actually block.
                resultQueue.poll();
            }
        }
    }

Processes a packet to see if it meets the criteria for this packet
collector. If so, the packet is added to the result queue.

@param packet
the packet to process.

Processes a packet to see if it meets the criteria for this packet collector . If so the packet is added to the result queue .


public static Optional<Volume> getVolume(EventModel eventModel) {
        if (eventModel.getListResourceContainer().containsResourcesFromSource(ID)) {
            return eventModel
                    .getListResourceContainer()
                    .provideResource(ID)
                    .stream()
                    .map(ResourceModel::getResource)
                    .filter(ob -> ob instanceof Integer)
                    .map(ob -> (Integer) ob)
                    .findAny()
                    .flatMap(Volume::createVolume);

        } else {
            return Optional.empty();
        }
    }

public static Optional < Volume > getVolume ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Integer ) . map ( ob -> ( Integer ) ob ) . findAny ( ) . flatMap ( Volume :: createVolume ) ; } else { return Optional . empty ( ) ; } }

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


public static IQ errorRSM(IQ iq, Logger logger) {
        String rsmMessage = "RSM: Page Not Found";
        logger.error(rsmMessage + " " + iq);
        return XMPPUtils.createErrorResponse(iq, rsmMessage,
                Condition.item_not_found, Type.cancel);
    }

public
static
IQ
errorRSM
(
IQ
iq
,
Logger
logger
)
{
String
rsmMessage
=
"RSM: Page Not Found"
;
logger
.
error
(
rsmMessage
+
" "
+
iq
)
;
return
XMPPUtils
.
createErrorResponse
(
iq
,
rsmMessage
,
Condition
.
item_not_found
,
Type
.
cancel
)
;
}

Logs the RSM page not found error and returns an IQ error response

@param iq
@param errorMessage
@param logger
@return


public static IQ createErrorResponse(final IQ request,
            final String message, Condition condition, Type type) {
        final IQ result = request.createCopy();
        result.setID(request.getID());
        result.setFrom(request.getTo());
        result.setTo(request.getFrom());

        PacketError e = new PacketError(condition, type);
        if (message != null) {
            e.setText(message);
        }
        result.setError(e);

        return result;
    }

public static IQ createErrorResponse ( final IQ request , final String message , Condition condition , Type type ) { final IQ result = request . createCopy ( ) ; result . setID ( request . getID ( ) ) ; result . setFrom ( request . getTo ( ) ) ; result . setTo ( request . getFrom ( ) ) ; PacketError e = new PacketError ( condition , type ) ; if ( message != null ) { e . setText ( message ) ; } result . setError ( e ) ; return result ; }

Creates an error response for a given IQ request.

@param request
@param message
@param condition
@param type
@return

Creates an error response for a given IQ request .