Input: Return an integer for current JSON value parsing string values as required . [CODESPLIT] 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:" ) ; }


Input: Return a double number for current JSON value parsing string values as required . [CODESPLIT] 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:" ) ; }


Input: Return string value for current JSON value [CODESPLIT] 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:" ) ; }


Input: creates a new Resource . [CODESPLIT] 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 ) ; }


Input: verifies that an command is not malformed [CODESPLIT] 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 ) ; }


Input: verifies that the player is capable of handling the command [CODESPLIT] 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 ; }


Input: verifies tha the command is legal and able to be executed [CODESPLIT] public static boolean verify ( String command , Capabilities capabilities ) { return verifyCommand ( command ) && verifyCapabilities ( command , capabilities ) ; }


Input: Create a { @link Cluster } instance . [CODESPLIT] protected Cluster createCluster ( ClusterIdentifier ci ) { return CqlUtils . newCluster ( ci . hostsAndPorts , ci . username , ci . password , getConfiguration ( ) ) ; }


Input: Create a { @link Session } instance . [CODESPLIT] protected Session createSession ( Cluster cluster , String keyspace ) { return CqlUtils . newSession ( cluster , keyspace ) ; }


Input: Obtain a Cassandra cluster instance . [CODESPLIT] synchronized protected Cluster getCluster ( ClusterIdentifier key ) { Cluster cluster ; try { cluster = clusterCache . get ( key ) ; if ( cluster . isClosed ( ) ) { LOGGER . info ( "Cluster [" + cluster + "] was closed, obtaining a new one..." ) ; clusterCache . invalidate ( key ) ; cluster = clusterCache . get ( key ) ; } } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; } return cluster ; }


Input: Obtain a Cassandra cluster instance . [CODESPLIT] public Cluster getCluster ( String hostsAndPorts , String username , String password ) { return getCluster ( ClusterIdentifier . getInstance ( hostsAndPorts , username , password ) ) ; }


Input: Obtain a Cassandra session instance . [CODESPLIT] public Session getSession ( String hostsAndPorts , String username , String password , String keyspace ) { return getSession ( hostsAndPorts , username , password , keyspace , false ) ; }


Input:
Obtain a Cassandra session instance . [CODESPLIT] synchronized protected Session getSession ( SessionIdentifier si , boolean forceNew ) { /*
         * Since 0.2.6: refresh cluster cache before obtaining the session to
         * avoid exception
         * "You may have used a PreparedStatement that was created with another Cluster instance"
         */ Cluster cluster = getCluster ( si ) ; if ( cluster == null ) { return null ; } try { LoadingCache < SessionIdentifier , Session > cacheSessions = sessionCache . get ( si ) ; Session existingSession = cacheSessions . getIfPresent ( si ) ; if ( existingSession != null && existingSession . isClosed ( ) ) { LOGGER . info ( "Session [" + existingSession + "] was closed, obtaining a new one..." ) ; cacheSessions . invalidate ( si ) ; return cacheSessions . get ( si ) ; } if ( forceNew ) { if ( existingSession != null ) { cacheSessions . invalidate ( si ) ; } return cacheSessions . get ( si ) ; } return existingSession != null ? existingSession : cacheSessions . get ( si ) ; } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; } }


Input: Obtain a Cassandra session instance . [CODESPLIT] public Session getSession ( String hostsAndPorts , String username , String password , String keyspace , boolean forceNew ) { return getSession ( SessionIdentifier . getInstance ( hostsAndPorts , username , password , keyspace ) , forceNew ) ; }


Input: Bind values to a { @link PreparedStatement } . [CODESPLIT] public BoundStatement bindValues ( PreparedStatement stm , Object ... values ) { return CqlUtils . bindValues ( stm , values ) ; }


Input: Bind values to a { @link PreparedStatement } . [CODESPLIT] public BoundStatement bindValues ( PreparedStatement stm , Map < String , Object > values ) { return CqlUtils . bindValues ( stm , values ) ; }


Input: Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( String cql , Object ... bindValues ) { return CqlUtils . execute ( getSession ( ) , cql , bindValues ) ; }


Input: Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( PreparedStatement stm , Map < String , Object > bindValues ) { return CqlUtils . execute ( getSession ( ) , stm , bindValues ) ; }


Input: Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( Statement stm , ConsistencyLevel consistencyLevel ) { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) ; }


Input: Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( String cql , ConsistencyLevel consistencyLevel , Map < String , Object > bindValues ) { return CqlUtils . executeOne ( getSession ( ) , cql , consistencyLevel , bindValues ) ; }


Input: Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( PreparedStatement stm , Object ... bindValues ) { return CqlUtils . executeOne ( getSession ( ) , stm , bindValues ) ; }


Input: Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( Statement stm , ConsistencyLevel consistencyLevel ) { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) . one ( ) ; }


Input: / * ---------------------------------------------------------------------- [CODESPLIT] private FutureCallback < ResultSet > wrapCallbackResultSet ( FutureCallback < ResultSet > callback ) { return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ; }


Input: Async - execute a query . [CODESPLIT] public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm ) throws ExceedMaxAsyncJobsException { executeAsync ( callback , stm , null ) ; }


Input: Async - execute a query . [CODESPLIT] public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm , ConsistencyLevel consistencyLevel ) throws ExceedMaxAsyncJobsException { if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } ResultSetFuture rsf = CqlUtils . executeAsync ( getSession ( ) , stm ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } } }


Input: / * ---------------------------------------------------------------------- [CODESPLIT] private FutureCallback < ResultSet > wrapCallbackRow ( FutureCallback < Row > callback ) { return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result . one ( ) ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ; }


Input: Async - execute a query . [CODESPLIT] public void executeOneAsync ( FutureCallback < Row > callback , Statement stm ) throws ExceedMaxAsyncJobsException { executeOneAsync ( callback , stm , null ) ; }


Input: Execute a batch statement . [CODESPLIT] public ResultSet executeBatch ( ConsistencyLevel consistencyLevel , Statement ... statements ) { return CqlUtils . executeBatch ( getSession ( ) , consistencyLevel , statements ) ; }


Input: Execute a batch statement . [CODESPLIT] public ResultSet executeBatch ( BatchStatement . Type batchType , Statement ... statements ) { return CqlUtils . executeBatch ( getSession ( ) , batchType , statements ) ; }


Input: Async - execute a batch statement . [CODESPLIT] 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 ) ; } } }


Input: Sets a jar filter . [CODESPLIT] public CF setJarFilter ( List < String > jarFilter ) { this . locator . setJarFilter ( jarFilter ) ; this . needsReRun = true ; return this ; }


Input: Returns all subclasses found for the given class . [CODESPLIT] 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 ; }


Input: Returns all subclasses found for the given fully qualified class name . [CODESPLIT] 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 ) ; }


Input: Returns all known subclasses for a given class location and package name [CODESPLIT] 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 ( ) ; } }


Input: Returns all known subclasses found in a given directory . [CODESPLIT] 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 ; }


Input: Returns all known subclasses found in a given location [CODESPLIT] 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 ; }


Input: sets the Resource data . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setResource ( T resource ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }


Input: sets who should or has provided the Resource Object . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setProvider ( Identification provider ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }


Input: sets who should or has consumed the Resource Object . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setConsumer ( Identification consumer ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }


Input: creates a list with this Element in it . [CODESPLIT] public List < Resource > toList ( ) { List < Resource > resourceList = new ArrayList <> ( ) ; resourceList . add ( this ) ; return resourceList ; }


Input:
Returns the accumulated size of all the bottom level maps . [CODESPLIT] 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 ; }


Input: this method is called to register for what Events it wants to provide Resources . <p > The Event has to be in the following format : It should contain only one Descriptor and and one Resource with the ID description which contains an description of the Event . < / p > [CODESPLIT] @ Override public List < ? extends EventModel < ? > > announceEvents ( ) { return getTriggeredEvents ( ) . stream ( ) . map ( EventListener :: getEvent ) . collect ( Collectors . toList ( ) ) ; }


Input: this method is called when an object wants to get a Resource . <p > Don t use the Resources provided as arguments they are just the requests . There is a timeout after 1 second . < / p > [CODESPLIT] @ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > list , Optional < EventModel > optional ) { //TODO: check arguments and return type here! Missing ID etc. Fail fast! return new ArrayList <> ( triggered ( list , optional ) ) ; }


Input: Returns the next available packet . The method call will block ( not return ) until a packet is available or the <tt > timeout< / tt > has elapased . If the timeout elapses without a result <tt > null< / tt > will be returned . [CODESPLIT] public Packet nextResult ( long timeout ) { try { return resultQueue . poll ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } }


Input: Processes a packet to see if it meets the criteria for this packet collector . If so the packet is added to the result queue . [CODESPLIT] 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 ( ) ; } } }


Input: Factory method to create a synchronized map . [CODESPLIT] public static < E > FilterableSet < E > decorate ( FilterableSet < E > set ) { return new SynchronizedFilterableSet < E > ( set ) ; }


Input: gets the first Volume if found in the EventModel [CODESPLIT] 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 ( ) ; } }


Input: Logs the error and returns an IQ error response [CODESPLIT] public static IQ error ( IQ iq , String errorMessage , Logger logger ) { logger . error ( errorMessage ) ; return error ( iq , errorMessage ) ; }


Input: Logs the error and returns an IQ error response [CODESPLIT] public static IQ error ( IQ iq , String errorMessage ) { return XMPPUtils . createErrorResponse ( iq , errorMessage , Condition . bad_request , Type . modify ) ; }


Input: Logs the RSM page not found error and returns an IQ error response [CODESPLIT] 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 ) ; }


Input: Creates an error response for a given IQ request . [CODESPLIT] 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 ; }


Input: returns true if the identifiable is the target of the EventModel [CODESPLIT] public static Optional < Boolean > isTarget ( EventModel eventModel , Identifiable identifiable ) { if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( SelectorResource . RESOURCE_ID ) ) ) { return Optional . of ( eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( resource -> resource instanceof Identification ) . map ( object -> ( Identification ) object ) . anyMatch ( identifiable :: isOwner ) ) ; } else { return Optional . empty ( ) ; } }


Input: Factory method to create a synchronized map . [CODESPLIT] public static < K , V > SortedMap < K , V > decorate ( SortedMap < K , V > map ) { return new SynchronizedSortedMap < K , V > ( map ) ; }


Input: ----------------------------------------------------------------------- [CODESPLIT] public Comparator < ? super K > comparator ( ) { return SyncUtils . synchronizeRead ( lock , new Callback < Comparator < ? super K > > ( ) { @ Override protected void doAction ( ) { _return ( getSortedMap ( ) . comparator ( ) ) ; } } ) ; }


Input: TODO : Unit test [CODESPLIT] public boolean allowImpersonate ( Subject impersSubject ) { String impersonators = ( String ) getProperty ( IMPERSONATORS_FIELD ) ; if ( impersonators == null ) { return false ; } Set < String > impersonatorSet = ImmutableSet . copyOf ( StringUtils . split ( impersonators , ' ' ) ) ; for ( Principal p : impersSubject . getPrincipals ( ) ) { if ( ADMIN_USER . equals ( p . getName ( ) ) || SYSTEM_USER . equals ( p . getName ( ) ) || impersonatorSet . contains ( p . getName ( ) ) ) { return true ; } } return false ; }


Input: Sets the login enabled time [CODESPLIT] public void setLoginEnabled ( long from , long to , boolean day , TimeZone timeZone ) { String enabledSetting = EnabledPeriod . getEnableValue ( from , to , day , timeZone ) ; if ( enabledSetting == null ) { removeProperty ( LOGIN_ENABLED_PERIOD_FIELD ) ; } else { setProperty ( LOGIN_ENABLED_PERIOD_FIELD , enabledSetting ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public boolean accept ( Packet packet ) { return ( packet instanceof IQ && ( ( IQ ) packet ) . getType ( ) . equals ( type ) ) ; }


Input: Factory method to create a synchronized set . [CODESPLIT] public static < E > Set < E > decorate ( Set < E > set ) { return new SynchronizedSet < E > ( set ) ; }


Input: Sets the name associated with this entry . [CODESPLIT] public void setName ( String name ) { // Do nothing if the name hasn't changed. if ( name != null && name . equals ( this . name ) ) { return ; } this . name = name ; Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( user ) , name , ask , subscription , getGroupNames ( ) ) ; connection . sendPacket ( packet ) ; }


Input: Updates the state of the entry with the new values . [CODESPLIT] void updateState ( String name , Subscription type , Ask status ) { this . name = name ; this . subscription = type ; this . ask = status ; }


Input: Returns an unmodifiable collection of the roster groups that this entry belongs to . [CODESPLIT] public Collection < RosterGroup > getGroups ( ) { List < RosterGroup > results = new ArrayList < RosterGroup > ( ) ; // Loop through all roster groups and find the ones that contain this // entry. This algorithm should be fine for ( RosterGroup group : roster . getGroups ( ) ) { if ( group . contains ( this ) ) { results . add ( group ) ; } } return Collections . unmodifiableCollection ( results ) ; }


Input: Indicates whether some other object is equal to this by comparing all members . <p > The { @link #equals ( Object ) } method returns <code > true< / code > if the user JIDs are equal . [CODESPLIT] public boolean equalsDeep ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; RosterEntry other = ( RosterEntry ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( ask == null ) { if ( other . ask != null ) return false ; } else if ( ! ask . equals ( other . ask ) ) return false ; if ( subscription == null ) { if ( other . subscription != null ) return false ; } else if ( ! subscription . equals ( other . subscription ) ) return false ; if ( user == null ) { if ( other . user != null ) return false ; } else if ( ! user . equals ( other . user ) ) return false ; return true ; }


Input: { @inheritDoc } [CODESPLIT] public V get ( String key ) { Element e = cache . get ( key ) ; if ( e == null ) { return stats ( null ) ; } return stats ( e . getObjectValue ( ) ) ; }


Input: { @inherit - doc } [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public V put ( String key , V payload ) { V previous = null ; if ( cache . isKeyInCache ( key ) ) { Element e = cache . get ( key ) ; if ( e != null ) { previous = ( V ) e . getObjectValue ( ) ; } } cache . put ( new Element ( key , payload ) ) ; return previous ; }


Input: { @inheritDoc } [CODESPLIT] public void removeChildren ( String key ) { cache . remove ( key ) ; if ( ! key . endsWith ( "/" ) ) { key = key + "/" ; } List < ? > keys = cache . getKeys ( ) ; for ( Object k : keys ) { if ( ( ( String ) k ) . startsWith ( key ) ) { cache . remove ( k ) ; } } }


Input: { @inheritDoc } [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public List < V > list ( ) { List < String > keys = cache . getKeys ( ) ; List < V > values = new ArrayList < V > ( ) ; for ( String k : keys ) { Element e = cache . get ( k ) ; if ( e != null ) { values . add ( ( V ) e . getObjectValue ( ) ) ; } } return values ; }


Input: Appends RSM info to query response . [CODESPLIT] public static void appendRSMElement ( Element queryElement , RSM rsm ) { Element setElement = queryElement . addElement ( "set" , RSM . NAMESPACE ) ; if ( rsm . getFirst ( ) != null ) { Element firstElement = setElement . addElement ( "first" ) ; firstElement . addAttribute ( "index" , rsm . getIndex ( ) . toString ( ) ) ; firstElement . setText ( rsm . getFirst ( ) ) ; } if ( rsm . getLast ( ) != null ) { Element lastElement = setElement . addElement ( "last" ) ; lastElement . setText ( rsm . getLast ( ) ) ; } setElement . addElement ( "count" ) . setText ( String . valueOf ( rsm . getCount ( ) ) ) ; }


Input: Parses an RSM from a query XML element [CODESPLIT] public static RSM parseRSM ( Element queryElement ) { RSM rsm = new RSM ( ) ; Element setElement = queryElement . element ( "set" ) ; if ( setElement == null ) { return rsm ; } Element after = setElement . element ( "after" ) ; if ( after != null ) { rsm . setAfter ( after . getText ( ) ) ; } Element before = setElement . element ( "before" ) ; if ( before != null ) { String beforeText = before . getText ( ) ; rsm . setBefore ( beforeText == null ? "" : beforeText ) ; } Element index = setElement . element ( "index" ) ; if ( index != null ) { rsm . setIndex ( Integer . parseInt ( index . getText ( ) ) ) ; } Element max = setElement . element ( "max" ) ; if ( max != null ) { rsm . setMax ( Integer . parseInt ( max . getText ( ) ) ) ; } return rsm ; }


Input: Filters response objects based on the RSM parameters . Updates the RSM object with item count first and last jid [CODESPLIT] public static List < Identifiable > filterRSMResponse ( List < Identifiable > objects , RSM rsm ) throws IllegalArgumentException { String after = rsm . getAfter ( ) ; String before = rsm . getBefore ( ) ; int initialIndex = rsm . getIndex ( ) ; int lastIndex = objects . size ( ) ; if ( after != null || ( before != null && ! before . isEmpty ( ) ) ) { boolean afterItemFound = false ; boolean beforeItemFound = false ; int i = 0 ; for ( Identifiable object : objects ) { if ( after != null && after . equals ( object . getId ( ) ) ) { initialIndex = i + 1 ; afterItemFound = true ; } if ( before != null && before . equals ( object . getId ( ) ) ) { lastIndex = i ; beforeItemFound = true ; } i ++ ; } if ( after != null && ! afterItemFound ) { throw new IllegalArgumentException ( ) ; } if ( before != null && ! before . isEmpty ( ) && ! beforeItemFound ) { throw new IllegalArgumentException ( ) ; } } if ( rsm . getMax ( ) != null ) { if ( before != null ) { initialIndex = lastIndex - rsm . getMax ( ) ; } else { lastIndex = initialIndex + rsm . getMax ( ) ; } } boolean outOfRange = initialIndex > lastIndex || initialIndex < 0 || lastIndex > objects . size ( ) ; List < Identifiable > filteredList = outOfRange ? new LinkedList < Identifiable > ( ) : objects . subList ( initialIndex , lastIndex ) ; rsm . setCount ( objects . size ( ) ) ; rsm . setIndex ( initialIndex ) ; if ( ! filteredList . isEmpty ( ) ) { rsm . setFirst ( filteredList . get ( 0 ) . getId ( ) ) ; rsm . setLast ( filteredList . get ( filteredList . size ( ) - 1 ) . getId ( ) ) ; } return filteredList ; }


Input: Handles an event from OSGi and indexes it . The indexing operation should only index metadata and not bodies . Indexing of bodies is performed by a seperate thread . [CODESPLIT] public void handleEvent ( Event event ) { String topic = event . getTopic ( ) ; Session session = ( Session ) event . getProperty ( Session . class . getName ( ) ) ; RepositorySession repositoryRession = null ; Thread thisThread = Thread . currentThread ( ) ; ClassLoader classloader = thisThread . getContextClassLoader ( ) ; // ES might load classes so we had better set the context classloader. try { thisThread . setContextClassLoader ( this . getClass ( ) . getClassLoader ( ) ) ; try { repositoryRession = new RepositorySessionImpl ( session , repository ) ; } catch ( ClientPoolException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( StorageClientException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( AccessDeniedException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } LOGGER . debug ( "Got Event {} {} " , event , handlers ) ; Collection < IndexingHandler > contentIndexHandler = handlers . get ( topic ) ; if ( contentIndexHandler != null && contentIndexHandler . size ( ) > 0 ) { BulkRequestBuilder bulk = client . prepareBulk ( ) ; int added = 0 ; for ( IndexingHandler indexingHandler : contentIndexHandler ) { Collection < InputDocument > documents = indexingHandler . getDocuments ( repositoryRession , event ) ; for ( InputDocument in : documents ) { LOGGER . info ( "Indexing {} " , in ) ; if ( in . isDelete ( ) ) { bulk . add ( client . prepareDelete ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ) ; added ++ ; } else { try { IndexRequestBuilder r = client . prepareIndex ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ; XContentBuilder d = XContentFactory . jsonBuilder ( ) ; d = d . startObject ( ) ; for ( Entry < String , Object > e : in . getKeyData ( ) ) { d = d . field ( e . getKey ( ) , e . getValue ( ) ) ; } r . setSource ( d . endObject ( ) ) ; bulk . add ( r ) ; added ++ ; } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } } } if ( added > 0 ) { BulkResponse resp = bulk . execute ( ) . actionGet ( ) ; if ( resp . hasFailures ( ) ) { for ( BulkItemResponse br : Iterables . adaptTo ( resp . iterator ( ) ) ) { if ( br . failed ( ) ) { LOGGER . error ( "Failed {} {} " , br . getId ( ) , br . getFailureMessage ( ) ) ; // not going to retry at the moment, just log. } } } } } } finally { if ( repositoryRession != null ) { repositoryRession . logout ( ) ; } thisThread . setContextClassLoader ( classloader ) ; } }


Input: creates a new LeavingEvent [CODESPLIT] public static Optional < LeavingEvent > createLeavingEvent ( Identification source , boolean strict , List < String > descriptors ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } descriptors . add ( ID ) ; descriptors . add ( CommonEvents . Descriptors . NOT_INTERRUPT ) ; LeavingEvent stopRequest = new LeavingEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Reloads the entire roster from the server . This is an asynchronous operation which means the method will return immediately and the roster will be reloaded at a later point when the server responds to the reload request . [CODESPLIT] public void reload ( ) { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } Roster packet = new Roster ( ) ; if ( rosterStore != null && connection . isRosterVersioningSupported ( ) ) { packet . getElement ( ) . element ( "query" ) . addAttribute ( "ver" , rosterStore . getRosterVersion ( ) ) ; PacketFilter filter = new PacketIDFilter ( packet . getID ( ) ) ; connection . addPacketListener ( new RosterResultListener ( ) , filter ) ; } connection . sendPacket ( packet ) ; }


Input: Creates a new group . <p > <p / > Note : you must add at least one entry to the group for the group to be kept after a logout / login . This is due to the way that XMPP stores group information . [CODESPLIT] public RosterGroup createGroup ( String name ) { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } if ( groups . containsKey ( name ) ) { throw new IllegalArgumentException ( "Group with name " + name + " alread exists." ) ; } RosterGroup group = new RosterGroup ( name , connection ) ; groups . put ( name , group ) ; return group ; }


Input: Creates a new roster entry and presence subscription . The server will asynchronously update the roster with the subscription status . [CODESPLIT] public void createEntry ( String user , String name , String [ ] groups ) throws XMPPException { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } // Create and send roster entry creation packet. Roster rosterPacket = new Roster ( ) ; rosterPacket . setType ( IQ . Type . set ) ; rosterPacket . addItem ( new JID ( user ) , name , null , null , Arrays . asList ( groups ) ) ; // Wait up to a certain number of seconds for a reply from the server. PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( rosterPacket . getID ( ) ) ) ; connection . sendPacket ( rosterPacket ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( "No response from the server." ) ; } // If the server replied with an error, throw an exception. else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } // Create a presence subscription packet and send. Presence presencePacket = new Presence ( Presence . Type . subscribe ) ; presencePacket . setTo ( user ) ; connection . sendPacket ( presencePacket ) ; }


Input: Removes a roster entry from the roster . The roster entry will also be removed from the unfiled entries or from any roster group where it could belong and will no longer be part of the roster . Note that this is an asynchronous call -- Smack must wait for the server to send an updated subscription status . [CODESPLIT] public void removeEntry ( RosterEntry entry ) throws XMPPException { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } // Only remove the entry if it's in the entry list. // The actual removal logic takes place in // RosterPacketListenerprocess>>Packet(Packet) if ( ! entries . containsKey ( entry . getUser ( ) ) ) { return ; } Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , Subscription . remove , entry . getGroupNames ( ) ) ; PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( packet . getID ( ) ) ) ; connection . sendPacket ( packet ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( "No response from the server." ) ; } // If the server replied with an error, throw an exception. else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } }


Input: Returns an unmodifiable collection of all entries in the roster including entries that don t belong to any groups . [CODESPLIT] public Collection < RosterEntry > getEntries ( ) { Set < RosterEntry > allEntries = new HashSet < RosterEntry > ( ) ; // Loop through all roster groups and add their entries to the answer for ( RosterGroup rosterGroup : getGroups ( ) ) { allEntries . addAll ( rosterGroup . getEntries ( ) ) ; } // Add the roster unfiled entries to the answer allEntries . addAll ( unfiledEntries ) ; return Collections . unmodifiableCollection ( allEntries ) ; }


Input: Returns the roster entry associated with the given XMPP address or <tt > null< / tt > if the user is not an entry in the roster . [CODESPLIT] public RosterEntry getEntry ( String user ) { if ( user == null ) { return null ; } return entries . get ( user . toLowerCase ( ) ) ; }


Input: Returns the presence info for a particular user . If the user is offline or if no presence data is available ( such as when you are not subscribed to the user s presence updates ) unavailable presence will be returned . <p > <p / > If the user has several presences ( one for each resource ) then the presence with highest priority will be returned . If multiple presences have the same priority the one with the most available presence mode will be returned . In order that s { @link org . jivesoftware . smack . packet . Presence . Mode#chat free to chat } { @link org . jivesoftware . smack . packet . Presence . Mode#available available } { @link org . jivesoftware . smack . packet . Presence . Mode#away away } { @link org . jivesoftware . smack . packet . Presence . Mode#xa extended away } and { @link org . jivesoftware . smack . packet . Presence . Mode#dnd do not disturb } . <p > <p / > Note that presence information is received asynchronously . So just after logging in to the server presence values for users in the roster may be unavailable even if they are actually online . In other words the value returned by this method should only be treated as a snapshot in time and may not accurately reflect other user s presence instant by instant . If you need to track presence over time such as when showing a visual representation of the roster consider using a { @link RosterListener } . [CODESPLIT] public Presence getPresence ( String user ) { String key = getPresenceMapKey ( StringUtils . parseBareAddress ( user ) ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { // Find the resource with the highest priority // Might be changed to use the resource with the highest // availability instead. Presence presence = null ; for ( String resource : userPresences . keySet ( ) ) { Presence p = userPresences . get ( resource ) ; if ( ! p . isAvailable ( ) ) { continue ; } // Chose presence with highest priority first. if ( presence == null || p . getPriority ( ) > presence . getPriority ( ) ) { presence = p ; } // If equal priority, choose "most available" by the mode value. else if ( p . getPriority ( ) == presence . getPriority ( ) ) { Presence . Show pMode = p . getShow ( ) ; // Default to presence mode of available. if ( pMode == null ) { pMode = Presence . Show . chat ; } Presence . Show presenceMode = presence . getShow ( ) ; // Default to presence mode of available. if ( presenceMode == null ) { presenceMode = Presence . Show . chat ; } if ( pMode . compareTo ( presenceMode ) < 0 ) { presence = p ; } } } if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { return presence ; } } }


Input: Returns the presence info for a particular user s resource or unavailable presence if the user is offline or if no presence information is available such as when you are not subscribed to the user s presence updates . [CODESPLIT] public Presence getPresenceResource ( String userWithResource ) { String key = getPresenceMapKey ( userWithResource ) ; String resource = StringUtils . parseResource ( userWithResource ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { Presence presence = userPresences . get ( resource ) ; if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { return presence ; } } }


Input: Returns an iterator ( of Presence objects ) for all of a user s current presences or an unavailable presence if the user is unavailable ( offline ) or if no presence information is available such as when you are not subscribed to the user s presence updates . [CODESPLIT] public Iterator < Presence > getPresences ( String user ) { String key = getPresenceMapKey ( user ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } else { Collection < Presence > answer = new ArrayList < Presence > ( ) ; for ( Presence presence : userPresences . values ( ) ) { if ( presence . isAvailable ( ) ) { answer . add ( presence ) ; } } if ( ! answer . isEmpty ( ) ) { return answer . iterator ( ) ; } else { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } } }


Input: Returns the key to use in the presenceMap for a fully qualified XMPP ID . The roster can contain any valid address format such us domain / resource user@domain or user@domain / resource . If the roster contains an entry associated with the fully qualified XMPP ID then use the fully qualified XMPP ID as the key in presenceMap otherwise use the bare address . Note : When the key in presenceMap is a fully qualified XMPP ID the userPresences is useless since it will always contain one entry for the user . [CODESPLIT] private String getPresenceMapKey ( String user ) { if ( user == null ) { return null ; } String key = user ; if ( ! contains ( user ) ) { key = StringUtils . parseBareAddress ( user ) ; } return key . toLowerCase ( ) ; }


Input: Changes the presence of available contacts offline by simulating an unavailable presence sent from the server . After a disconnection every Presence is set to offline . [CODESPLIT] private void setOfflinePresences ( ) { Presence packetUnavailable ; for ( String user : presenceMap . keySet ( ) ) { Map < String , Presence > resources = presenceMap . get ( user ) ; if ( resources != null ) { for ( String resource : resources . keySet ( ) ) { packetUnavailable = new Presence ( Presence . Type . unavailable ) ; packetUnavailable . setFrom ( user + "/" + resource ) ; presencePacketListener . processPacket ( packetUnavailable ) ; } } } }


Input: Fires roster changed event to roster listeners indicating that the specified collections of contacts have been added updated or deleted from the roster . [CODESPLIT] private void fireRosterChangedEvent ( Collection < String > addedEntries , Collection < String > updatedEntries , Collection < String > deletedEntries ) { for ( RosterListener listener : rosterListeners ) { if ( ! addedEntries . isEmpty ( ) ) { listener . entriesAdded ( addedEntries ) ; } if ( ! updatedEntries . isEmpty ( ) ) { listener . entriesUpdated ( updatedEntries ) ; } if ( ! deletedEntries . isEmpty ( ) ) { listener . entriesDeleted ( deletedEntries ) ; } } }


Input: Sets the digest value using a connection ID and password . Password digests offer a more secure alternative for authentication compared to plain text . The digest is the hex - encoded SHA - 1 hash of the connection ID plus the user s password . If the digest and password are set digest authentication will be used . If only one value is set the respective authentication mode will be used . [CODESPLIT] public void setDigest ( String connectionID , String password ) { setDigest ( StringUtils . hash ( connectionID + password ) ) ; }


Input: generates the resources [CODESPLIT] @ Override public Optional < ? extends ResourceModel > generateResource ( ResourceModel resourceModel , Optional < EventModel > event ) { switch ( resourceModel . getResourceID ( ) ) { case BroadcasterAvailablePlaylists . RESOURCE_ID : return createBroadcasterAvailablePlaylists ( ) ; case BroadcasterPlaylist . RESOURCE_ID : return createBroadcasterPlaylist ( resourceModel ) ; default : return MusicResourceGenerator . super . generateResource ( resourceModel , event ) ; } }


Input: Sets the value stored in this Map Entry . <p / > This Map Entry is not connected to a Map so only the local data is changed . [CODESPLIT] public V setValue ( V value ) { V answer = this . value ; this . value = value ; return answer ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public Object borrowObject ( ) throws Exception { log . debug ( " borrowing object.." ) ; WorkerThread thread = ( WorkerThread ) super . borrowObject ( ) ; thread . setPool ( this ) ; return thread ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void returnObject ( Object obj ) throws Exception { log . debug ( " returning object.." + obj ) ; super . returnObject ( obj ) ; }


Input: creates a new PresenceEvent [CODESPLIT] public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent stopRequest = new PresenceEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: creates a new PresenceEvent [CODESPLIT] public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors , Long timePassed ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent presenceEvent = new PresenceEvent ( source , descriptors ) ; presenceEvent . addResource ( new LastEncountered ( source , timePassed ) ) ; return Optional . of ( presenceEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Factory method to create a synchronized map . [CODESPLIT] public static < K , V > Map < K , V > decorate ( Map < K , V > map ) { return new SynchronizedMap < K , V > ( map ) ; }


Input: ----------------------------------------------------------------------- [CODESPLIT] public void clear ( ) { SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { map . clear ( ) ; } } ) ; }


Input: tries to set the Volume of the PlayerRequest . <p > if the Player supports the Change of the Volume it will create a new PlayerRequest and return it if not it returns this . < / p > [CODESPLIT] public PlayerRequest trySetVolume ( Volume volume ) { if ( capabilities . canChangeVolume ( ) ) { return new PlayerRequest ( trackInfo , playlist , permanent , player , capabilities , context , identifiable , volume ) ; } return this ; }


Input: returns a List of Resources that can be added to an already existing event . <p > This causes the Addon to block the Event in the OutputPlugin lifecycle of the Event . [CODESPLIT] @ SuppressWarnings ( "unused" ) public List < ResourceModel > resourcesForExisting ( ) { List < ResourceModel > resourceModels = new ArrayList <> ( ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new MusicUsageResource ( id , true ) ) . ifPresent ( resourceModels :: add ) ; if ( volume != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new VolumeResource ( id , volume ) ) . ifPresent ( resourceModels :: add ) ; } if ( playlist != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new PlaylistResource ( id , playlist ) ) . ifPresent ( resourceModels :: add ) ; } if ( trackInfo != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new TrackInfoResource ( id , trackInfo ) ) . ifPresent ( resourceModels :: add ) ; } return resourceModels ; }


Input: helper method for PlaylistSelector [CODESPLIT] static PlayerRequest createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , Capabilities capabilities , Context context , Identifiable identifiable ) { return new PlayerRequest ( null , playlist , permanent , player , capabilities , context , identifiable ) ; }


Input:
creates a new PlayerRequest .
 the resulting PlayerRequest is not permanent which means that it will mute all other sound but is limited to 10 minutes .
 For this method to return a non - empty Optional the following criteria must be met :

 the player must exist and be support the standard defined through the sdk

 the players - capabilities must allow requests from outside

 the players - capabilities must allow a requests with specified a specified playlist / trackInfo

 [CODESPLIT] @ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( TrackInfo trackInfo , Identification player , AddOnModule source ) { return createPlayerRequest ( trackInfo , false , player , source ) ; }


Input:
creates a new PlayerRequest .
 the resulting PlayerRequest is not permanent which means that it will mute all other sound but is limited to 10 minutes .
 For this method to return a non - empty Optional the following criteria must be met :

 the player must exist and be support the standard defined through the sdk

 the players - capabilities must allow requests from outside

 the players - capabilities must allow a requests with specified a specified playlist / trackInfo

 [CODESPLIT] @ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , Identification player , AddOnModule source ) { return createPlayerRequest ( playlist , false , player , source ) ; }


Input: creates a new PlayerRequest . <p > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist and be support the standard defined through the sdk< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , AddOnModule source ) { if ( playlist == null || player == null || source == null ) return Optional . empty ( ) ; try { return source . getContext ( ) . getResources ( ) . generateResource ( new CapabilitiesResource ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( resource -> Capabilities . importFromResource ( resource , source . getContext ( ) ) ) ) . get ( 1 , TimeUnit . SECONDS ) . filter ( capabilities -> { if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { source . getContext ( ) . getLogger ( ) . error ( "player does not handle play-request from outside" ) ; return false ; } if ( ! capabilities . hasPlayRequestDetailed ( ) ) { source . getContext ( ) . getLogger ( ) . error ( "player does not handle playlist-request from outside" ) ; return false ; } if ( ! playlist . verify ( capabilities ) ) { source . getContext ( ) . getLogger ( ) . error ( "player can not handle the playlist, probably illegal PlaybackModes" ) ; return false ; } return true ; } ) . map ( capabilities -> new PlayerRequest ( null , playlist , permanent , player , capabilities , source . getContext ( ) , source ) ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { source . getContext ( ) . getLogger ( ) . debug ( "unable to obtain capabilities" ) ; return Optional . empty ( ) ; } }


Input: returns the time passed if available [CODESPLIT] @ SuppressWarnings ( "unused" ) public static Optional < Long > getTimePassed ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Long ) . map ( ob -> ( Long ) ob ) . findAny ( ) ; } else { return Optional . empty ( ) ; } }


Input: the listener will always be called when the Properties - file changes . [CODESPLIT] public void registerUpdateListener ( Consumer < PropertiesAssistant > listener ) { if ( listener != null ) listeners . add ( new WeakReference <> ( listener ) ) ; }


Input: Initializes properties in the addOn . Creates new properties file using default properties . [CODESPLIT] public void initProperties ( ) { propertiesPath = getContext ( ) . getFiles ( ) . getPropertiesLocation ( ) + File . separator + getContext ( ) . getAddOns ( ) . getAddOn ( ) . getID ( ) + ".properties" ; this . propertiesFile = new File ( propertiesPath ) ; if ( ! this . propertiesFile . exists ( ) ) try { this . propertiesFile . createNewFile ( ) ; } catch ( IOException e ) { error ( "Error while trying to create the new Properties file" , e ) ; } try { BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( this . propertiesFile ) , "UTF8" ) ) ; try { properties . load ( in ) ; } catch ( IOException e ) { error ( "unable to load the InputStream for the PropertiesFile" , e ) ; } } catch ( FileNotFoundException | UnsupportedEncodingException e ) { error ( "Error while trying to read Properties-File" , e ) ; } if ( defaultPropertiesPath != null && new File ( defaultPropertiesPath ) . exists ( ) ) { @ SuppressWarnings ( "unchecked" ) Enumeration < String > keys = ( Enumeration < String > ) properties . propertyNames ( ) ; if ( ! keys . hasMoreElements ( ) ) { try { createDefaultPropertyFile ( defaultPropertiesPath ) ; } catch ( IOException e ) { error ( "Error while trying to copy the Default-Properties File" , e ) ; } if ( new File ( defaultPropertiesPath ) . exists ( ) && ! writeToPropertiesFile ( defaultPropertiesPath ) ) return ; reloadProperties ( ) ; } } }


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


Input: Parses stream error packets . [CODESPLIT] public static StreamError parseStreamError ( Element el ) throws IOException , XmlPullParserException { String code = null ; Element condEl = ( Element ) el . elements ( ) . iterator ( ) . next ( ) ; if ( condEl . getNamespace ( ) . getURI ( ) . equals ( StreamError . NAMESPACE ) ) { code = condEl . getName ( ) ; } String text = condEl . elementText ( "text" ) ; return new StreamError ( code , text ) ; }


Input: Parse the available SASL mechanisms reported from the server . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static Collection < String > parseMechanisms ( Element mechanismsEl ) throws Exception { List < Element > mechanisms = mechanismsEl . elements ( "mechanism" ) ; List < String > mechanismsStr = new LinkedList < String > ( ) ; for ( Element mechanismEl : mechanisms ) { mechanismsStr . add ( mechanismEl . getText ( ) ) ; } return mechanismsStr ; }


Input: Parse the available compression methods reported from the server . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static Collection < String > parseCompressionMethods ( Element compressionEl ) throws IOException , XmlPullParserException { List < Element > methodsEls = compressionEl . elements ( "method" ) ; List < String > methodsStr = new LinkedList < String > ( ) ; for ( Element methodEl : methodsEls ) { methodsStr . add ( methodEl . getText ( ) ) ; } return methodsStr ; }


Input: Parses a packet extension sub - packet . [CODESPLIT] public static PacketExtension parsePacketExtension ( String elementName , String namespace , XmlPullParser parser ) throws Exception { DefaultPacketExtension extension = new DefaultPacketExtension ( elementName , namespace ) ; boolean done = false ; while ( ! done ) { int eventType = parser . next ( ) ; if ( eventType == XmlPullParser . START_TAG ) { String name = parser . getName ( ) ; // If an empty element, set the value with the empty string. if ( parser . isEmptyElementTag ( ) ) { extension . setValue ( name , "" ) ; } // Otherwise, get the the element text. else { eventType = parser . next ( ) ; if ( eventType == XmlPullParser . TEXT ) { String value = parser . getText ( ) ; extension . setValue ( name , value ) ; } } } else if ( eventType == XmlPullParser . END_TAG ) { if ( parser . getName ( ) . equals ( elementName ) ) { done = true ; } } } return extension ; }


Input: Decodes a String into an object of the specified type . If the object type is not supported null will be returned . [CODESPLIT] private static Object decode ( Class < ? > type , String value ) throws Exception { if ( type . getName ( ) . equals ( "java.lang.String" ) ) { return value ; } if ( type . getName ( ) . equals ( "boolean" ) ) { return Boolean . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "int" ) ) { return Integer . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "long" ) ) { return Long . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "float" ) ) { return Float . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "double" ) ) { return Double . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "java.lang.Class" ) ) { return Class . forName ( value ) ; } return null ; }


Input: creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target ) { return createStartMusicRequest ( source , target , ( TrackInfo ) null ) ; }


Input: creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo ) { return createStartMusicRequest ( source , target , trackInfo , true ) ; }


Input: creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo , boolean isUsingJava ) { if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( trackInfo != null ) request . addResource ( new TrackInfoResource ( target , trackInfo , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist ) { return createStartMusicRequest ( source , target , playlist , true ) ; }


Input: creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist , boolean isUsingJava ) { if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( playlist != null ) request . addResource ( new PlaylistResource ( target , playlist , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: verifies that the StartMusicRequest is correct and checks whether the you are meant to react to it [CODESPLIT] public static boolean verify ( EventModel eventModel , Capabilities capabilities , Identifiable player , List < Identifiable > activators ) { if ( ! eventModel . containsDescriptor ( StartMusicRequest . ID ) ) return false ; if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { if ( activators . stream ( ) . noneMatch ( identifiable -> identifiable . isOwner ( eventModel . getSource ( ) ) ) ) return false ; } if ( ! PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> playlist . verify ( capabilities ) ) . orElse ( true ) ) { return false ; } return SelectorResource . isTarget ( eventModel , player ) . orElse ( false ) ; }


Input: Creates a filter where valid when an object in a collection is the <strong > same as< / strong > the base object . [CODESPLIT] public static < E > Filter < E > createSameAsFilter ( final E base ) { return new Filter < E > ( ) { public boolean isValid ( E obj ) { return ( base == obj ) ; } } ; }


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


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


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


Input: returns the PlaybackState from the resource [CODESPLIT] public static Optional < PlaybackState > getPlaybackStateFromResource ( ResourceModel x ) { if ( ! x . getResourceID ( ) . equals ( ID ) ) return Optional . empty ( ) ; Object resource = x . getResource ( ) ; if ( resource instanceof String ) { String state = ( String ) resource ; try { return Optional . of ( PlaybackState . valueOf ( state ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; } }


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


Input: Returns if we want components to be able to connect multiple times to the same JID . This is a custom Openfire extension and will not work with any other XMPP server . Other XMPP servers should ignore this extra setting . [CODESPLIT] public boolean isMultipleAllowed ( String subdomain ) { Boolean allowed = allowMultiple . get ( subdomain ) ; return allowed != null && allowed ; }


Input: Gets the value mapped to the key specified . [CODESPLIT] public V get ( Object key ) { purgeBeforeRead ( ) ; Entry < K , V > entry = getEntry ( key ) ; if ( entry == null ) { return null ; } return entry . getValue ( ) ; }


Input: Puts a key - value mapping into this map . Neither the key nor the value may be null . [CODESPLIT] public V put ( K key , V value ) { if ( key == null ) { throw new NullPointerException ( "null keys not allowed" ) ; } if ( value == null ) { throw new NullPointerException ( "null values not allowed" ) ; } purgeBeforeWrite ( ) ; return super . put ( key , value ) ; }


Input: Removes the specified mapping from this map . [CODESPLIT] public V remove ( Object key ) { if ( key == null ) { return null ; } purgeBeforeWrite ( ) ; return super . remove ( key ) ; }


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


Input: Returns a set view of this map s keys . [CODESPLIT] public Set < K > keySet ( ) { if ( keySet == null ) { keySet = new ReferenceKeySet < K , V > ( this ) ; } return keySet ; }


Input: Returns a collection view of this map s values . [CODESPLIT] public Collection < V > values ( ) { if ( values == null ) { values = new ReferenceValues < K , V > ( this ) ; } return values ; }


Input: Purges stale mappings from this map . <p / > Note that this method is not synchronized! Special care must be taken if for instance you want stale mappings to be removed on a periodic basis by some background thread . [CODESPLIT] protected void purge ( ) { Reference ref = queue . poll ( ) ; while ( ref != null ) { purge ( ref ) ; ref = queue . poll ( ) ; } }


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


Input: Gets the entry mapped to the key specified . [CODESPLIT] protected HashEntry < K , V > getEntry ( Object key ) { if ( key == null ) { return null ; } else { return super . getEntry ( key ) ; } }


Input: Gets the hash code for a MapEntry . Subclasses can override this for example to use the identityHashCode . [CODESPLIT] protected int hashEntry ( Object key , Object value ) { return ( key == null ? 0 : key . hashCode ( ) ) ^ ( value == null ? 0 : value . hashCode ( ) ) ; }


Input: Creates a ReferenceEntry instead of a HashEntry . [CODESPLIT] public HashEntry < K , V > createEntry ( HashEntry < K , V > next , int hashCode , K key , V value ) { return new ReferenceEntry < K , V > ( this , ( ReferenceEntry < K , V > ) next , hashCode , key , value ) ; }


Input: Replaces the superclass method to store the state of this class . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to serialize the state data of this class in this protected method . This method must be called by the <code > writeObject () < / code > of the first serializable subclass . <p / > Subclasses may override if they have a specific field that must be present on read before this implementation will work . Generally the read determines what must be serialized here if anything . [CODESPLIT] protected void doWriteObject ( ObjectOutputStream out ) throws IOException { out . writeInt ( keyType ) ; out . writeInt ( valueType ) ; out . writeBoolean ( purgeValues ) ; out . writeFloat ( loadFactor ) ; out . writeInt ( data . length ) ; for ( MapIterator it = mapIterator ( ) ; it . hasNext ( ) ; ) { out . writeObject ( it . next ( ) ) ; out . writeObject ( it . getValue ( ) ) ; } out . writeObject ( null ) ; // null terminate map // do not call super.doWriteObject() as code there doesn't work for // reference map }


Input: Replaces the superclassm method to read the state of this class . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to deserialize the state data of this class in this protected method . This method must be called by the <code > readObject () < / code > of the first serializable subclass . <p / > Subclasses may override if the subclass has a specific field that must be present before <code > put () < / code > or <code > calculateThreshold () < / code > will work correctly . [CODESPLIT] protected void doReadObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { this . keyType = in . readInt ( ) ; this . valueType = in . readInt ( ) ; this . purgeValues = in . readBoolean ( ) ; this . loadFactor = in . readFloat ( ) ; int capacity = in . readInt ( ) ; init ( ) ; data = new HashEntry [ capacity ] ; while ( true ) { K key = ( K ) in . readObject ( ) ; if ( key == null ) { break ; } V value = ( V ) in . readObject ( ) ; put ( key , value ) ; } threshold = calculateThreshold ( data . length , loadFactor ) ; // do not call super.doReadObject() as code there doesn't work for // reference map }


Input: Controls whether the fired Event should be dispatched to all the listeners . This method should execute quickly [CODESPLIT] @ Override public boolean controlEvents ( EventModel eventModel ) { if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) >= 0 ) { return present ; } else //noinspection SimplifiableIfStatement if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) < 0 && mostVague . get ( ) ) { return present ; } else { return true ; } }


Input: sets the presence [CODESPLIT] public void setPresence ( boolean present ) { if ( this . present == present ) return ; this . present = present ; updateVague ( ) ; if ( present ) { firePresence ( true ) ; } else { fireLeaving ( ) ; } }


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


Input: Sends the specified text as a message to the other chat participant . This is a convenience method for : [CODESPLIT] public void sendMessage ( String text ) throws XMPPException { Message message = new Message ( ) ; message . setTo ( participant ) ; message . setType ( Type . chat ) ; message . setThread ( threadID ) ; message . setBody ( text ) ; chatManager . sendMessage ( this , message ) ; }


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


Input: Generates a script . [CODESPLIT] protected final ST generateScript ( String clazz , HashMap < String , Boolean > targetMap ) { ST ret = this . stg . getInstanceOf ( "generateExec" ) ; ret . add ( "target" , targetMap ) ; ret . add ( "applicationHome" , this . applicationDir ) ; ret . add ( "runName" , this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; ret . add ( "class" , clazz ) ; return ret ; }


Input: Loads and tests the configuration from configuration properties file . The default configuration file name is de / vandermeer / execs / configuration . properties . The file name can be overwritten using the -- property - file CLI option . The method will also test for some configuration keys to exist and fail if they are not defined . [CODESPLIT] protected final int initConfiguration ( ) { String propFile = this . optionPropFile . getValue ( ) ; this . configuration = this . loadProperties ( propFile ) ; if ( this . configuration == null ) { System . err . println ( this . getAppName ( ) + ": could not load configuration properties from file <" + propFile + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_SCRIPT_NAME ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_RUN_SCRIPT_NAME + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_CLASS ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_RUN_CLASS + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_JAVA_CP ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_JAVA_CP + ">, exiting" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": using configuration: " ) ; System . out . println ( "  - run script name: " + this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; System . out . println ( "  - run class      : " + this . configuration . get ( PROP_RUN_CLASS ) ) ; System . out . println ( "  - java cp        : " + this . configuration . get ( PROP_JAVA_CP ) ) ; System . out . println ( "  - auto-gen reg   : " + this . configuration . get ( PROP_EXECS_AUTOGEN_REGISTERED ) ) ; for ( Object key : this . configuration . keySet ( ) ) { if ( StringUtils . startsWith ( key . toString ( ) , PROP_JAVAPROP_START ) ) { System . out . println ( "  - java property  : " + key + " = " + this . configuration . getProperty ( key . toString ( ) ) ) ; } } System . out . println ( ) ; return 0 ; }


Input: Sets target for generation and initializes an STG object from an stg template file . The default template file name is de / vandermeer / execs / executable - script . stg . This default can be overwritten using the property stg . file in the configuration properties file . The default and the property file name can be overwritten using the -- stg - file CLI option . The set target ( CLI option -- target ) must be supported by the template file otherwise this method will fail . [CODESPLIT] protected final int initTargetAndStg ( ) { this . target = this . optionTarget . getValue ( ) ; if ( this . target == null ) { System . err . println ( this . getAppName ( ) + ": no target set" ) ; return - 1 ; } String fileName = this . optionStgFile . getValue ( ) ; try { this . stg = new STGroupFile ( fileName ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": cannot load stg file <" + fileName + ">, general exception\n--> " + e ) ; return - 1 ; } String [ ] availableTargets = null ; try { availableTargets = StringUtils . split ( this . stg . getInstanceOf ( "supportedTargets" ) . render ( ) , " , " ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": stg file <" + fileName + "> does not contain <supportedTargets> function" ) ; return - 1 ; } if ( availableTargets . length == 0 ) { System . err . println ( this . getAppName ( ) + ": stg file <" + fileName + "> does not have a list of targets in <supportedTargets> function" ) ; return - 1 ; } if ( ! ArrayUtils . contains ( availableTargets , this . target ) ) { System . err . println ( this . getAppName ( ) + ": target " + this . target + " not supported in stg file <" + fileName + ">" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": generating scripts for target: " + this . target ) ; System . out . println ( ) ; return 0 ; }


Input: Initializes the application directory for the generator . There is no default set and no configuration property can be used . The application directory has to be set using the CLI option -- application - directory . Otherwise this method will fail . [CODESPLIT] protected final int initApplicationDir ( ) { this . applicationDir = this . optionAppHome . getValue ( ) ; if ( this . applicationDir == null ) { System . err . println ( this . getAppName ( ) + ": no application directory set" ) ; return - 1 ; } return 0 ; }


Input: Loads a classmap from a property file . A classmap maps class names to script names . A class name must be an implementation of the executable application interface { [CODESPLIT] protected final int initClassmap ( ) { this . optionClassMapFile . setPropertyValue ( this . configuration ) ; String fileName = this . optionClassMapFile . getValue ( ) ; if ( fileName == null ) { System . err . println ( this . getAppName ( ) + ": no classmap file name given" ) ; return - 2 ; } this . classMap = this . loadProperties ( fileName ) ; if ( this . classMap == null ) { System . err . println ( this . getAppName ( ) + ": could not load classmap, exiting" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": generating scripts for:" ) ; for ( Object key : this . classMap . keySet ( ) ) { System . out . println ( "  - " + key + " --> " + this . classMap . getProperty ( key . toString ( ) ) ) ; } System . out . println ( ) ; return 0 ; }


Input: Tests and if necessary creates an output directory . The root path is the current directory as given by the system property user . dir . The created output directory has the name of the specified target for the generator . The method fails if the output directory cannot be created or if it exists and is write protected . [CODESPLIT] protected final int initOutputDir ( ) { String parent = System . getProperty ( "user.dir" ) ; String target = parent + File . separator + this . target ; File targetDir = new File ( target ) ; File parentDir = targetDir . getParentFile ( ) ; if ( targetDir . exists ( ) ) { //target dir exists, let's see if it is what we want it to be if ( ! targetDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir <" + target + "> exists but is not a directory, exiting" ) ; return - 1 ; } if ( ! targetDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir <" + target + "> exists but but cannot write into it, exiting" ) ; return - 1 ; } } else { //target dir does not exist, let's see if we can create it the way we need if ( ! parentDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir parent <" + parent + "> exists but is not a directory, exiting" ) ; return - 1 ; } if ( ! parentDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir parent <" + parent + "> exists but but cannot write into it, exiting" ) ; return - 1 ; } if ( ! targetDir . mkdir ( ) ) { System . err . println ( this . getAppName ( ) + ": could not create target dir <" + target + ">, exiting" ) ; return - 1 ; } } this . outputDir = target ; return 0 ; }


Input: Loads properties from a file . [CODESPLIT] protected final Properties loadProperties ( String filename ) { Properties ret = new Properties ( ) ; URL url = null ; File f = new File ( filename . toString ( ) ) ; if ( f . exists ( ) ) { try { url = f . toURI ( ) . toURL ( ) ; } catch ( Exception ignore ) { } } else { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; url = loader . getResource ( filename ) ; if ( url == null ) { loader = Gen_RunScripts . class . getClassLoader ( ) ; url = loader . getResource ( filename ) ; } } try { ret . load ( url . openStream ( ) ) ; } catch ( IOException e ) { System . err . println ( this . getAppName ( ) + ": cannot load property file <" + filename + ">, IO exception\n--><" + e + ">" ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": cannot load property file <" + filename + ">, general exception\n--><" + e + ">" ) ; } return ret ; }


Input: Writes an ST object to a file . [CODESPLIT] protected final int writeFile ( String fn , ST st ) { try { FileWriter fs = new FileWriter ( fn ) ; BufferedWriter bw = new BufferedWriter ( fs ) ; bw . write ( st . render ( ) ) ; bw . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return - 1 ; } return 0 ; }


Input: gets the first Progress if found in the EventModel [CODESPLIT] public static Optional < Progress > getProgress ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . findAny ( ) . flatMap ( Progress :: importResource ) ; } else { return Optional . empty ( ) ; } }


Input: Factory method to create a synchronized collection . [CODESPLIT] public static < E > Collection < E > decorate ( Collection < E > coll ) { return new SynchronizedCollection < E > ( coll ) ; }


Input: ----------------------------------------------------------------------- [CODESPLIT] public boolean add ( final E object ) { Boolean ret = SyncUtils . synchronizeWrite ( lock , new Callback < Boolean > ( ) { @ Override protected void doAction ( ) { _return ( collection . add ( object ) ? Boolean . TRUE : Boolean . FALSE ) ; } } ) ; return ret . booleanValue ( ) ; }


Input: Discover FireREST services located in a range of IPv4 InetAddresses . E . g . The range of 256 addresses that starts with 10 . 0 . 1 . 128 ends with 10 . 0 . 2 . 127 . [CODESPLIT] public static Collection < ServiceResolver > discover ( InetAddress start , int count , int msTimeout ) { Collection < ServiceResolver > result = new ArrayList < ServiceResolver > ( ) ; Collection < InetAddress > hosts = IPv4Scanner . scanRange ( start , count , msTimeout ) ; for ( InetAddress host : hosts ) { ServiceResolver resolver = new ServiceResolver ( host ) ; logger . info ( "resolving {} {}" , host . getHostAddress ( ) , host . getCanonicalHostName ( ) ) ; JSONResult config = resolver . getConfig ( ) ; if ( config != null ) { result . add ( resolver ) ; } } return result ; }


Input: ( Re - ) discover the service configuration [CODESPLIT] public void resolve ( ) { attempts ++ ; config = null ; Exception caughtException = null ; String host = address == null ? "null" : address . getCanonicalHostName ( ) ; if ( url == null ) { URL attemptUrl = null ; int [ ] ports = { 8080 , 80 } ; for ( int i = 0 ; i < ports . length ; i ++ ) { try { attemptUrl = new URL ( "http" , host , ports [ i ] , "/firerest/config.json" ) ; break ; } catch ( Exception e ) { attemptUrl = null ; caughtException = e ; } } if ( attemptUrl == null ) { throw new FireRESTException ( "Could not resolve service at " + host , caughtException ) ; } url = attemptUrl ; } if ( config == null ) { logger . info ( "Resolving {}" , url ) ; config = new FireREST ( ) . withTimeout ( msTimeout ) . getJSON ( url ) ; } }


Input: Return the cached service configuration resolving the service if required . [CODESPLIT] public JSONResult getConfig ( ) { if ( attempts == 0 ) { try { resolve ( ) ; } catch ( Exception e ) { // discard exception } } if ( config == null ) { logger . info ( "{} => no response" , url ) ; return null ; } logger . info ( "{} => {}" , url , config . get ( "FireREST" ) . getString ( ) ) ; return config ; }


Input: ----------------------------------------------------------------------------------- [CODESPLIT] @ Override public void invalidate ( String keySpace , String columnFamily , Map < String , Object > queryProperties ) { Map < String , CacheHolder > queryCache = client . getQueryCache ( ) ; if ( queryCache == null ) { return ; } String cacheKey = getCacheKey ( keySpace , columnFamily , queryProperties ) ; if ( cacheKey != null ) { LOGGER . debug ( "Removing Cached Query {} " , cacheKey ) ; queryCache . remove ( cacheKey ) ; } }


Input: Returns the map of String key / value pairs of account attributes . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public Map < String , String > getAttributes ( ) { Map < String , String > attributes = null ; List < Element > elements = queryEl . elements ( ) ; for ( Element element : elements ) { if ( ! element . getName ( ) . equals ( "instructions" ) ) { if ( attributes == null ) { attributes = new HashMap < String , String > ( ) ; } attributes . put ( element . getName ( ) , element . getText ( ) ) ; } } return attributes ; }


Input: Sets the account attributes . The map must only contain String key / value pairs . [CODESPLIT] public void setAttributes ( Map < String , String > attributes ) { for ( Entry < String , String > attribute : attributes . entrySet ( ) ) { PacketParserUtils . updateText ( queryEl , attribute . getKey ( ) , attribute . getValue ( ) ) ; } }


Input: returns the API used to manage the ThreadPool [CODESPLIT] @ Override public org . intellimate . izou . sdk . specification . context . ThreadPool getThreadPool ( ) { return threadPool ; }


Input: creates a new StopRequest [CODESPLIT] public static Optional < StopMusic > createStopMusic ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { StopMusic stopRequest = new StopMusic ( source ) ; stopRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: verifies that the StopMusicRequest is correct and checks whether the you are meant to react to it [CODESPLIT] public static boolean verify ( EventModel eventModel , Identifiable player ) { if ( ! eventModel . containsDescriptor ( StopMusic . ID ) ) return false ; return SelectorResource . isTarget ( eventModel , player ) . orElse ( true ) ; }


Input: { [CODESPLIT] @ Override protected DseCluster createCluster ( ClusterIdentifier ci ) { return DseUtils . newDseCluster ( ci . hostsAndPorts , ci . username , ci . password , ci . authorizationId , getConfiguration ( ) ) ; }


Input: { [CODESPLIT] @ Override protected DseSession createSession ( Cluster cluster , String keyspace ) { return DseUtils . newDseSession ( ( DseCluster ) cluster , keyspace ) ; }


Input: { [CODESPLIT] @ Override public DseCluster getCluster ( String hostsAndPorts , String username , String password ) { return getCluster ( hostsAndPorts , username , password , null ) ; }


Input: Obtain a DSE cluster instance . [CODESPLIT] public DseCluster getCluster ( String hostsAndPorts , String username , String password , String authorizationId ) { return getCluster ( ClusterIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId ) ) ; }


Input: { [CODESPLIT] @ Override synchronized protected DseSession getSession ( SessionIdentifier si , boolean forceNew ) { return ( DseSession ) super . getSession ( si , forceNew ) ; }


Input: { [CODESPLIT] @ Override public DseSession getSession ( String hostsAndPorts , String username , String password , String keyspace ) { return getSession ( hostsAndPorts , username , password , null , keyspace , false ) ; }


Input: Obtain a DSE session instance . [CODESPLIT] public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace ) { return getSession ( hostsAndPorts , username , password , authorizationId , keyspace , false ) ; }


Input: Obtain a DSE session instance . [CODESPLIT] public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace , boolean forceNew ) { return getSession ( SessionIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId , keyspace ) , forceNew ) ; }


Input: { [CODESPLIT] public DseSession getSession ( boolean forceNew ) { return getSession ( getDefaultHostsAndPorts ( ) , getDefaultUsername ( ) , getDefaultPassword ( ) , defaultAuthorizationId , getDefaultKeyspace ( ) , forceNew ) ; }


Input: Adds a connection listener to this connection that will be notified when the connection closes or fails . [CODESPLIT] public void addConnectionListener ( ConnectionListener connectionListener ) { if ( connectionListener == null ) { return ; } if ( ! connectionListeners . contains ( connectionListener ) ) { connectionListeners . add ( connectionListener ) ; } }


Input: Creates a new packet collector for this connection . A packet filter determines which packets will be accumulated by the collector . A PacketCollector is more suitable to use than a { @link PacketListener } when you need to wait for a specific result . [CODESPLIT] public PacketCollector createPacketCollector ( PacketFilter packetFilter ) { PacketCollector collector = new PacketCollector ( this , packetFilter ) ; // Add the collector to the list of active collectors. collectors . add ( collector ) ; return collector ; }


Input: Registers a packet listener with this connection . A packet listener will be invoked only when an incoming packet is received . A packet filter determines which packets will be delivered to the listener . If the same packet listener is added again with a different filter only the new filter will be used . [CODESPLIT] public void addPacketListener ( PacketListener packetListener , PacketFilter packetFilter ) { if ( packetListener == null ) { throw new NullPointerException ( "Packet listener is null." ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; recvListeners . put ( packetListener , wrapper ) ; }


Input: Registers a packet listener with this connection . The listener will be notified of every packet that this connection sends . A packet filter determines which packets will be delivered to the listener . Note that the thread that writes packets will be used to invoke the listeners . Therefore each packet listener should complete all operations quickly or use a different thread for processing . [CODESPLIT] public void addPacketSendingListener ( PacketListener packetListener , PacketFilter packetFilter ) { if ( packetListener == null ) { throw new NullPointerException ( "Packet listener is null." ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; sendListeners . put ( packetListener , wrapper ) ; }


Input: Process all packet listeners for sending packets . [CODESPLIT] protected void firePacketSendingListeners ( Packet packet ) { // Notify the listeners of the new sent packet for ( ListenerWrapper listenerWrapper : sendListeners . values ( ) ) { listenerWrapper . notifyListener ( packet ) ; } }


Input: Registers a packet interceptor with this connection . The interceptor will be invoked every time a packet is about to be sent by this connection . Interceptors may modify the packet to be sent . A packet filter determines which packets will be delivered to the interceptor . [CODESPLIT] public void addPacketInterceptor ( PacketInterceptor packetInterceptor , PacketFilter packetFilter ) { if ( packetInterceptor == null ) { throw new NullPointerException ( "Packet interceptor is null." ) ; } interceptors . put ( packetInterceptor , new InterceptorWrapper ( packetInterceptor , packetFilter ) ) ; }


Input: Process interceptors . Interceptors may modify the packet that is about to be sent . Since the thread that requested to send the packet will invoke all interceptors it is important that interceptors perform their work as soon as possible so that the thread does not remain blocked for a long period . [CODESPLIT] protected void firePacketInterceptors ( Packet packet ) { if ( packet != null ) { for ( InterceptorWrapper interceptorWrapper : interceptors . values ( ) ) { interceptorWrapper . notifyListener ( packet ) ; } } }


Input: Initialize the { @link #debugger } . You can specify a customized { @link SmackDebugger } by setup the system property <code > smack . debuggerClass< / code > to the implementation . [CODESPLIT] protected void initDebugger ( ) { if ( reader == null || writer == null ) { throw new NullPointerException ( "Reader or writer isn't initialized." ) ; } // If debugging is enabled, we open a window and write out all network // traffic. if ( config . isDebuggerEnabled ( ) ) { if ( debugger == null ) { // Detect the debugger class to use. String className = null ; // Use try block since we may not have permission to get a // system // property (for example, when an applet). try { className = System . getProperty ( "smack.debuggerClass" ) ; } catch ( Throwable t ) { // Ignore. } Class < ? > debuggerClass = null ; if ( className != null ) { try { debuggerClass = Class . forName ( className ) ; } catch ( Exception e ) { log . warn ( "Unabled to instantiate debugger class " + className ) ; } } if ( debuggerClass == null ) { try { debuggerClass = Class . forName ( "org.jivesoftware.smackx.debugger.EnhancedDebugger" ) ; } catch ( Exception ex ) { try { debuggerClass = Class . forName ( "org.jivesoftware.smack.debugger.LiteDebugger" ) ; } catch ( Exception ex2 ) { log . warn ( "Unabled to instantiate either Smack debugger class" ) ; } } } // Create a new debugger instance. If an exception occurs then // disable the debugging // option try { Constructor < ? > constructor = debuggerClass . getConstructor ( Connection . class , Writer . class , Reader . class ) ; debugger = ( SmackDebugger ) constructor . newInstance ( this , writer , reader ) ; reader = debugger . getReader ( ) ; writer = debugger . getWriter ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Can't initialize the configured debugger!" , e ) ; } } else { // Obtain new reader and writer from the existing debugger reader = debugger . newConnectionReader ( reader ) ; writer = debugger . newConnectionWriter ( writer ) ; } } }


Input: Creates the most suitable type . [CODESPLIT] public static Object toValue ( String name , Object value ) { String [ ] parts = StringUtils . split ( name , "@" , 2 ) ; String fieldName = null ; String fieldType = "String" ; if ( parts . length == 2 ) { fieldType = parts [ 1 ] ; fieldName = parts [ 0 ] ; } else if ( parts . length == 1 ) { fieldName = parts [ 0 ] ; } else { throw new IllegalArgumentException ( "Invalid property name" ) ; } try { int l = Array . getLength ( value ) ; RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } if ( ! fieldName . endsWith ( "[]" ) && l == 1 ) { return rpt . newInstance ( Array . get ( value , 0 ) ) ; } Class < ? > componentType = rpt . getComponentType ( ) ; Object [ ] a = ( Object [ ] ) Array . newInstance ( componentType , l ) ; for ( int i = 0 ; i < l ; i ++ ) { a [ i ] = rpt . newInstance ( Array . get ( value , i ) ) ; } return a ; } catch ( IllegalArgumentException e ) { RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } return rpt . newInstance ( value ) ; } }