Input: Decodes a base64 String . Unlike Base64 . decode () this method does not try to detect and decompress a gzip - compressed input . [CODESPLIT] public static byte [ ] decodeBase64 ( String data ) { byte [ ] bytes ; try { bytes = data . getBytes ( "UTF-8" ) ; } catch ( java . io . UnsupportedEncodingException uee ) { bytes = data . getBytes ( ) ; } bytes = Base64 . decode ( bytes , 0 , bytes . length , Base64 . NO_OPTIONS ) ; return bytes ; }


Input: Returns a random String of numbers and letters ( lower and upper case ) of the specified length . The method uses the Random class that is built - in to Java which is suitable for low to medium grade security uses . This means that the output is only pseudo random i . e . each number is mathematically generated so is not truly random . <p > [CODESPLIT] public static String randomString ( int length ) { if ( length < 1 ) { return null ; } // Create a char buffer to put random letters and numbers in. char [ ] randBuffer = new char [ length ] ; for ( int i = 0 ; i < randBuffer . length ; i ++ ) { randBuffer [ i ] = numbersAndLetters [ randGen . nextInt ( 71 ) ] ; } return new String ( randBuffer ) ; }


Input:
Overridden to just get the count and nothing else . [CODESPLIT] @ Override public Integer iterate ( final FilterableCollection < ? extends T > c ) { checkUsed ( ) ; // No point doing the iteration. Just return size of collection.
 count = c . size ( ) ; return count ; }


Input: adds the ability for the Play / Pause requests [CODESPLIT] public void setPlayPauseController ( Consumer < String > controller ) { if ( controller == null ) return ; this . playPause = controller ; capabilities . setPlayPauseControl ( true ) ; }


Input: adds the ability to select tracks [CODESPLIT] public void setTrackSelectorController ( Consumer < TrackInfo > controller ) { if ( controller == null ) return ; selectTrack = controller ; capabilities . setAbleToSelectTrack ( true ) ; }


Input: adds the ability to select the next / previous track [CODESPLIT] public void setNextPreviousController ( Consumer < String > controller ) { if ( controller == null ) return ; nextPrevious = controller ; capabilities . setNextPrevious ( true ) ; }


Input: adds the ability to jump to a specified position of the current track [CODESPLIT] public void setJumpProgressController ( Consumer < Progress > controller ) { if ( controller == null ) return ; jumpProgress = controller ; capabilities . setAbleToJump ( true ) ; }


Input: adds the ability to change the playback [CODESPLIT] public void setPlaybackChangeableController ( Consumer < String > controller ) { if ( controller == null ) return ; changePlayback = controller ; capabilities . setPlaybackChangeable ( true ) ; }


Input: adds the ability to change the volume from outside the player [CODESPLIT] public void setVolumeChangeableController ( Consumer < Volume > controller ) { if ( controller == null ) return ; changeVolume = controller ; capabilities . setChangeVolume ( true ) ; }


Input: adds the ability to return the available playlists on request . [CODESPLIT] public void broadcastAvailablePlaylists ( Supplier < List < String > > availablePlaylist , Function < String , Playlist > playlistForNameFunction ) { if ( availablePlaylist == null || playlistForNameFunction == null ) return ; this . availablePlaylist = availablePlaylist ; this . playlistForNameFunction = playlistForNameFunction ; capabilities . setBroadcasting ( true ) ; }


Input: this method gets called when a new Command was found . It automatically fires the update Event or an error [CODESPLIT] public void handleCommandResources ( EventModel eventModel ) { List < ResourceModel < String >> resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( CommandResource . ResourceID ) . stream ( ) . filter ( resourceModel -> resourceModel . getResource ( ) instanceof String ) . map ( resourceModel -> { try { //noinspection unchecked return ( ResourceModel < String > ) resourceModel ; } catch ( ClassCastException e ) { return null ; } } ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; for ( ResourceModel < String > resourceModel : resourceModels ) { if ( ! CommandResource . verifyCommand ( resourceModel . getResource ( ) ) ) continue ; if ( ! CommandResource . verifyCapabilities ( resourceModel . getResource ( ) , capabilities ) ) { musicHelper . playerError ( PlayerError . ERROR_NOT_ABLE + "command: " + resourceModel . getResource ( ) , resourceModel . getProvider ( ) ) ; continue ; } switch ( resourceModel . getResource ( ) ) { case CommandResource . PLAY : if ( ! musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PAUSE : if ( musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . SELECT_TRACK : handleSelectTrack ( eventModel , resourceModel ) ; break ; case CommandResource . NEXT : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PREVIOUS : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . JUMP : handleJump ( eventModel , resourceModel ) ; break ; case CommandResource . CHANGE_PLAYBACK : changePlayback . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . CHANGE_VOLUME : handleVolume ( eventModel , resourceModel ) ; break ; case CommandResource . STOP : stopCallback . run ( ) ; break ; } } }


Input: handles the volume - command [CODESPLIT] private void handleVolume ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < Volume > volumeResource = VolumeResource . getVolume ( eventModel ) ; if ( ! volumeResource . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } changeVolume . accept ( volumeResource . get ( ) ) ; }


Input: handles the jump - command [CODESPLIT] private void handleJump ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; if ( ! progress . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } jumpProgress . accept ( progress . get ( ) ) ; }


Input: handles the select Track command [CODESPLIT] private void handleSelectTrack ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; if ( ! trackInfo . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } selectTrack . accept ( trackInfo . get ( ) ) ; }


Input: { @inheritDoc } [CODESPLIT] public < V > Cache < V > getCache ( String name , CacheScope scope ) { switch ( scope ) { case INSTANCE : return getInstanceCache ( name ) ; case CLUSTERINVALIDATED : return getInstanceCache ( name ) ; case CLUSTERREPLICATED : return getInstanceCache ( name ) ; case REQUEST : return getRequestCache ( name ) ; case THREAD : return getThreadCache ( name ) ; default : return getInstanceCache ( name ) ; } }


Input: Generate a cache bound to the thread . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private < V > Cache < V > getThreadCache ( String name ) { Map < String , Cache < ? > > threadCacheMap = threadCacheMapHolder . get ( ) ; Cache < V > threadCache = ( Cache < V > ) threadCacheMap . get ( name ) ; if ( threadCache == null ) { threadCache = new MapCacheImpl < V > ( ) ; threadCacheMap . put ( name , threadCache ) ; } return threadCache ; }


Input: Generate a cache bound to the request [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private < V > Cache < V > getRequestCache ( String name ) { Map < String , Cache < ? > > requestCacheMap = requestCacheMapHolder . get ( ) ; Cache < V > requestCache = ( Cache < V > ) requestCacheMap . get ( name ) ; if ( requestCache == null ) { requestCache = new MapCacheImpl < V > ( ) ; requestCacheMap . put ( name , requestCache ) ; } return requestCache ; }


Input: { [CODESPLIT] public void onDelete ( String zone , String path , String user , String resourceType , Map < String , Object > beforeEvent , String ... attributes ) { String topic = DEFAULT_DELETE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = deleteTopics . get ( zone ) ; } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ; }


Input: { [CODESPLIT] public void onUpdate ( String zone , String path , String user , String resourceType , boolean isNew , Map < String , Object > beforeEvent , String ... attributes ) { String topic = DEFAULT_UPDATE_TOPIC ; if ( isNew ) { topic = DEFAULT_CREATE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = createTopics . get ( zone ) ; } } else { if ( deleteTopics . containsKey ( zone ) ) { topic = updateTopics . get ( zone ) ; } } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ; }


Input: Get the name of an alternative field for an alternative stream . [CODESPLIT] public static String getAltField ( String field , String streamId ) { if ( streamId == null ) { return field ; } return field + "/" + streamId ; }


Input: TODO : Unit test [CODESPLIT] public static String insecureHash ( String naked ) { try { return insecureHash ( naked . getBytes ( UTF8 ) ) ; } catch ( UnsupportedEncodingException e3 ) { LOGGER . error ( "no UTF-8 Envoding, get a real JVM, nothing will work here. NPE to come" ) ; return null ; } }


Input: Converts to an Immutable map with keys that are in the filter not transfered . Nested maps are also transfered . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < K , V > Map < K , V > getFilterMap ( Map < K , V > source , Map < K , V > modified , Set < K > include , Set < K > exclude , boolean includingRemoveProperties ) { if ( ( modified == null || modified . size ( ) == 0 ) && ( include == null ) && ( exclude == null || exclude . size ( ) == 0 ) ) { if ( source instanceof ImmutableMap ) { return source ; } else { return ImmutableMap . copyOf ( source ) ; } } Builder < K , V > filteredMap = new ImmutableMap . Builder < K , V > ( ) ; for ( Entry < K , V > e : source . entrySet ( ) ) { K k = e . getKey ( ) ; if ( include == null || include . contains ( k ) ) { if ( exclude == null || ! exclude . contains ( k ) ) { if ( modified != null && modified . containsKey ( k ) ) { V o = modified . get ( k ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) o , null , null , exclude , includingRemoveProperties ) ) ; } else if ( includingRemoveProperties ) { filteredMap . put ( k , o ) ; } else if ( ! ( o instanceof RemoveProperty ) ) { filteredMap . put ( k , o ) ; } } else { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) e . getValue ( ) , null , null , exclude , includingRemoveProperties ) ) ; } else { filteredMap . put ( k , e . getValue ( ) ) ; } } } } } if ( modified != null ) { // process additions for ( Entry < K , V > e : modified . entrySet ( ) ) { K k = e . getKey ( ) ; if ( ! source . containsKey ( k ) ) { V v = e . getValue ( ) ; if ( ! ( v instanceof RemoveProperty ) && v != null ) { filteredMap . put ( k , v ) ; } } } } return filteredMap . build ( ) ; }


Input: Converts a map into Map or byte [] values with String keys . No control over depth of nesting . Keys in the filter set are not transfered Resulting map is mutable . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static Map < String , Object > getFilteredAndEcodedMap ( Map < String , Object > source , Set < String > filter ) { Map < String , Object > filteredMap = Maps . newHashMap ( ) ; for ( Entry < String , Object > e : source . entrySet ( ) ) { if ( ! filter . contains ( e . getKey ( ) ) ) { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( e . getKey ( ) , getFilteredAndEcodedMap ( ( Map < String , Object > ) o , filter ) ) ; } else { filteredMap . put ( e . getKey ( ) , o ) ; } } } return filteredMap ; }


Input: For instance the SparsePrincipal uses it . [CODESPLIT] public static String shardPath ( String id ) { String hash = insecureHash ( id ) ; return hash . substring ( 0 , 2 ) + "/" + hash . substring ( 2 , 4 ) + "/" + hash . substring ( 4 , 6 ) + "/" + id ; }


Input: TODO : Unit test [CODESPLIT] public static String arrayEscape ( String string ) { string = string . replaceAll ( "%" , "%1" ) ; string = string . replaceAll ( "," , "%2" ) ; return string ; }


Input: TODO : Unit test [CODESPLIT] public static String arrayUnEscape ( String string ) { string = string . replaceAll ( "%2" , "," ) ; string = string . replaceAll ( "%1" , "%" ) ; return string ; }


Input: Adapt an object to a session . I haven t used typing here becuase I don t want to bind to the Jars in question and create dependencies . [CODESPLIT] public static Session adaptToSession ( Object source ) { if ( source instanceof SessionAdaptable ) { return ( ( SessionAdaptable ) source ) . getSession ( ) ; } else { // assume this is a JCR session of someform, in which case there // should be a SparseUserManager Object userManager = safeMethod ( source , "getUserManager" , new Object [ 0 ] , new Class [ 0 ] ) ; if ( userManager != null ) { return ( Session ) safeMethod ( userManager , "getSession" , new Object [ 0 ] , new Class [ 0 ] ) ; } return null ; } }


Input: Make the method on the target object accessible and then invoke it . [CODESPLIT] private static Object safeMethod ( Object target , String methodName , Object [ ] args , @ SuppressWarnings ( "rawtypes" ) Class [ ] argsTypes ) { if ( target != null ) { try { Method m = target . getClass ( ) . getMethod ( methodName , argsTypes ) ; if ( ! m . isAccessible ( ) ) { m . setAccessible ( true ) ; } return m . invoke ( target , args ) ; } catch ( Throwable e ) { LOGGER . info ( "Failed to invoke method " + methodName + " " + target , e ) ; } } return null ; }


Input: Delete an entire tree starting from the deepest part of the tree and working back up . Will stop the moment a permission denied is encountered either for read or for delete . [CODESPLIT] public static void deleteTree ( ContentManager contentManager , String path ) throws AccessDeniedException , StorageClientException { Content content = contentManager . get ( path ) ; if ( content != null ) { for ( String childPath : content . listChildPaths ( ) ) { deleteTree ( contentManager , childPath ) ; } } contentManager . delete ( path ) ; }


Input:
Method to get existing [ key1 key2 key3 key4 ] value or create new one if it s absent . Needs implementation of create ( key1 key2 key3 key4 ) in order to work [CODESPLIT] public V getOrCreate ( K1 key1 , K2 key2 , K3 key3 , K4 key4 ) { // already got it?
 MultiKey multi_key = new MultiKey ( key1 , key2 , key3 , key4 ) ; if ( containsKey ( multi_key ) ) return get ( multi_key ) ; // if not, create and add it
 V result = create ( key1 , key2 , key3 , key4 ) ; put ( multi_key , result ) ; return result ; }


Input:
Only update specified properties of the Object [CODESPLIT] @ Override public void updateOne ( E object , String ... properties ) { if ( object . getId ( ) == null ) { throw new RuntimeException ( "Not a Persisted entity" ) ; } if ( properties == null || properties . length == 0 ) { entityManager . merge ( object ) ; return ; } // for performance reason its better to mix getting fields, their values
 // and making query all in one loop
 // in one iteration
 StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Update " + clazz . getName ( ) + " SET " ) ; // cache of fieldName --> value
 Map < String , Object > cache = new HashMap < String , Object > ( ) ; for ( String prop : properties ) { try { Field field = object . getClass ( ) . getDeclaredField ( prop ) ; field . setAccessible ( true ) ; Object value = field . get ( object ) ; if ( value instanceof Collection ) { // value = new LinkedList<>((Collection< ? extends Object>) value);
 throw new RuntimeException ( "Collection property is not suppotred." ) ; } cache . put ( prop , value ) ; // ignore first comma
 if ( cache . size ( ) > 1 ) { sb . append ( " ," ) ; } sb . append ( prop ) ; sb . append ( " = :" ) ; sb . append ( prop ) ; } catch ( Exception e ) { // TODO: use fine grain exceptions
 // FIX: NEXT RELEASE I hope :)
 throw new RuntimeException ( e ) ; } } // this means nothing will be updated so hitting db is unnecessary
 if ( cache . size ( ) == 0 ) return ; sb . append ( " WHERE id = " + object . getId ( ) ) ; Query query = entityManager . createQuery ( sb . toString ( ) ) ; for ( Entry < String , Object > entry : cache . entrySet ( ) ) { query . setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } query . executeUpdate ( ) ; }


Input: Retrieves a { @link KeepAliveManager } for the specified { @link Connection } creating one if it doesn t already exist . [CODESPLIT] public synchronized static KeepAliveManager getInstanceFor ( Connection connection ) { KeepAliveManager pingManager = instances . get ( connection ) ; if ( pingManager == null ) { pingManager = new KeepAliveManager ( connection ) ; instances . put ( connection , pingManager ) ; } return pingManager ; }


Input: / * Start the executor service if it hasn t been started yet . [CODESPLIT] private synchronized static void enableExecutorService ( ) { if ( periodicPingExecutorService == null ) { periodicPingExecutorService = new ScheduledThreadPoolExecutor ( 1 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread pingThread = new Thread ( runnable , "Smack Keepalive" ) ; pingThread . setDaemon ( true ) ; return pingThread ; } } ) ; } }


Input: / * Stop the executor service if all monitored connections are disconnected . [CODESPLIT] private synchronized static void handleDisconnect ( Connection con ) { if ( periodicPingExecutorService != null ) { instances . remove ( con ) ; if ( instances . isEmpty ( ) ) { periodicPingExecutorService . shutdownNow ( ) ; periodicPingExecutorService = null ; } } }


Input: / * Call after every connection to add the packet listener . [CODESPLIT] private void handleConnect ( ) { Connection connection = weakRefConnection . get ( ) ; // Listen for all incoming packets and reset the scheduled ping whenever // one arrives. connection . addPacketListener ( new PacketListener ( ) { @ Override public void processPacket ( Packet packet ) { // reschedule the ping based on this last server contact lastSuccessfulContact = System . currentTimeMillis ( ) ; schedulePingServerTask ( ) ; } } , null ) ; }


Input: Sets the ping interval . [CODESPLIT] public void setPingInterval ( long newPingInterval ) { if ( pingInterval == newPingInterval ) return ; // Enable the executor service if ( newPingInterval > 0 ) enableExecutorService ( ) ; pingInterval = newPingInterval ; if ( pingInterval < 0 ) { stopPinging ( ) ; } else { schedulePingServerTask ( ) ; } }


Input: Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater then zero . [CODESPLIT] private synchronized void schedulePingServerTask ( ) { enableExecutorService ( ) ; stopPingServerTask ( ) ; if ( pingInterval > 0 ) { periodicPingTask = periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Ping ping = new Ping ( ) ; PacketFilter responseFilter = new PacketIDFilter ( ping . getID ( ) ) ; Connection connection = weakRefConnection . get ( ) ; final PacketCollector response = pingFailedListeners . isEmpty ( ) ? null : connection . createPacketCollector ( responseFilter ) ; connection . sendPacket ( ping ) ; if ( response != null ) { // Schedule a collector for the ping reply, // notify listeners if none is received. periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Packet result = response . nextResult ( 1 ) ; // Stop queuing results response . cancel ( ) ; // The actual result of the // reply can be ignored since we // only care if we actually got // one. if ( result == null ) { for ( PingFailedListener listener : pingFailedListeners ) { listener . pingFailed ( ) ; } } } } , SmackConfiguration . getPacketReplyTimeout ( ) , TimeUnit . MILLISECONDS ) ; } } } , getPingInterval ( ) , TimeUnit . MILLISECONDS ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public final Object makeObject ( ) { log . debug ( " makeObject..." ) ; WorkerThread thread = new WorkerThread ( ) ; initialiseThread ( thread ) ; thread . start ( ) ; return thread ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public final void destroyObject ( Object obj ) { log . debug ( " !!! destroyObject... !!!" + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; rt . setStopped ( ) ; } }


Input:
/ * ( non - Javadoc ) [CODESPLIT] public final boolean validateObject ( Object obj ) { log . debug ( " validateObject..." + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; if ( ! rt . isDone ( ) ) { //if the thread is running the previous task, get another one.
 return false ; } if ( rt . isRunning ( ) ) { if ( rt . getThreadGroup ( ) == null ) { return false ; } return true ; } } return true ; }


Input: { [CODESPLIT] public void remove ( String key ) { V o = super . remove ( key ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; } }


Input: { [CODESPLIT] @ Override public void clear ( ) { for ( String k : super . keySet ( ) ) { Object o = get ( k ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; } } super . clear ( ) ; }


Input: { [CODESPLIT] public void removeChildren ( String key ) { super . remove ( key ) ; if ( ! key . endsWith ( "/" ) ) { key = key + "/" ; } Set < String > keys = super . keySet ( ) ; for ( String k : keys ) { if ( ( k ) . startsWith ( key ) ) { super . remove ( k ) ; } } }


Input: Adds a CLI option to the parser . [CODESPLIT] public ExecS_CliParser addOption ( ApplicationOption < ? > option ) { if ( option != null && option . getCliOption ( ) != null ) { this . _addOption ( option . getCliOption ( ) ) ; } return this ; }


Input: Adds all given option ignoring null elements . [CODESPLIT] public ExecS_CliParser addAllOptions ( ApplicationOption < ? > [ ] options ) { if ( options != null ) { for ( ApplicationOption < ? > option : options ) { this . addOption ( option ) ; } } return this ; }


Input: Adds a CLI option to the parser . [CODESPLIT] protected void _addOption ( Option option ) { if ( option == null ) { return ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { throw new IllegalArgumentException ( "ExecS Cli: short option <" + option . getOpt ( ) + "> already in use" ) ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { throw new IllegalArgumentException ( "ExecS Cli: long option <" + option . getLongOpt ( ) + "> already in use" ) ; } this . options . addOption ( option ) ; if ( option . getOpt ( ) != null ) { this . usedOptions . add ( option . getOpt ( ) ) ; } if ( option . getLongOpt ( ) != null ) { this . usedOptions . add ( option . getLongOpt ( ) ) ; } }


Input: Tests if an option is already added to the parser . [CODESPLIT] public boolean hasOption ( Option option ) { if ( option == null ) { return false ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { return true ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { return true ; } return false ; }


Input: Parses command line arguments and fills set options . [CODESPLIT] public ParseException parse ( String [ ] args ) { ParseException ret = null ; CommandLineParser parser = new DefaultParser ( ) ; try { this . cmdLine = parser . parse ( this . options , args ) ; } catch ( ParseException pe ) { ret = pe ; } return ret ; }


Input: Prints a usage screen based on set options . [CODESPLIT] public void usage ( String appName ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( appName , null , this . options , null , false ) ; }


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


Input: Closes the connection by setting presence to unavailable then closing the stream to the XMPP server . The shutdown logic will be used during a planned disconnection or when dealing with an unexpected disconnection . Unlike { @link #disconnect () } the connection s packet reader packet writer and { @link UserRoster } will not be removed ; thus connection s state is kept . [CODESPLIT] protected void shutdown ( Presence unavailablePresence ) { // Set presence to offline. if ( packetWriter != null ) { packetWriter . sendPacket ( unavailablePresence ) ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; if ( packetReader != null ) { packetReader . shutdown ( ) ; } if ( packetWriter != null ) { packetWriter . shutdown ( ) ; } // Wait 150 ms for processes to clean-up, then shutdown. try { Thread . sleep ( 150 ) ; } catch ( Exception e ) { // Ignore. } // Set socketClosed to true. This will cause the PacketReader // and PacketWriter to ignore any Exceptions that are thrown // because of a read/write from/to a closed stream. // It is *important* that this is done before socket.close()! socketClosed = true ; try { socket . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } for ( Plugin plugin : plugins ) { plugin . shutdown ( ) ; } // In most cases the close() should be successful, so set // connected to false here. connected = false ; reader = null ; writer = null ; saslAuthentication . init ( ) ; }


Input: Initializes the connection by creating a packet reader and writer and opening a XMPP stream to the server . [CODESPLIT] private void initConnection ( ) throws XMPPException { boolean isFirstInitialization = packetReader == null || packetWriter == null ; compressionHandler = null ; serverAckdCompression = false ; // Set the reader and writer instance variables initReaderAndWriter ( ) ; try { if ( isFirstInitialization ) { packetWriter = new PacketWriter ( this ) ; packetReader = new PacketReader ( this ) ; // If debugging is enabled, we should start the thread that will // listen for // all packets and then log them. if ( config . isDebuggerEnabled ( ) ) { addPacketListener ( debugger . getReaderListener ( ) , null ) ; if ( debugger . getWriterListener ( ) != null ) { addPacketSendingListener ( debugger . getWriterListener ( ) , null ) ; } } } else { packetWriter . init ( ) ; packetReader . init ( ) ; } // Start the packet writer. This will open a XMPP stream to the // server packetWriter . startup ( ) ; // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader . startup ( ) ; // Make note of the fact that we're now connected. connected = true ; if ( isFirstInitialization ) { // Notify listeners that a new connection has been established for ( ConnectionCreationListener listener : getConnectionCreationListeners ( ) ) { listener . connectionCreated ( this ) ; } } } catch ( XMPPException ex ) { // An exception occurred in setting up the connection. Make sure we // shut down the // readers and writers and close the socket. if ( packetWriter != null ) { try { packetWriter . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */ } packetWriter = null ; } if ( packetReader != null ) { try { packetReader . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */ } packetReader = null ; } if ( reader != null ) { try { reader . close ( ) ; } catch ( Throwable ignore ) { /* ignore */ } reader = null ; } if ( writer != null ) { try { writer . close ( ) ; } catch ( Throwable ignore ) { /* ignore */ } writer = null ; } if ( socket != null ) { try { socket . close ( ) ; } catch ( Exception e ) { /* ignore */ } socket = null ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; connected = false ; throw ex ; // Everything stoppped. Now throw the exception. } }


Input: Notification message saying that the server supports TLS so confirm the server that we want to secure the connection . [CODESPLIT] void startTLSReceived ( boolean required ) { if ( required && config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { notifyConnectionError ( new IllegalStateException ( "TLS required by server but not allowed by connection configuration" ) ) ; return ; } if ( config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { // Do not secure the connection using TLS since TLS was disabled return ; } try { writer . write ( "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; } }


Input: The server has indicated that TLS negotiation can start . We now need to secure the existing plain connection and perform a handshake . This method won t return until the connection has finished the handshake or an error occured while securing the connection . [CODESPLIT] void proceedTLSReceived ( ) throws Exception { SSLContext context = this . config . getCustomSSLContext ( ) ; KeyStore ks = null ; KeyManager [ ] kms = null ; PasswordCallback pcb = null ; if ( config . getCallbackHandler ( ) == null ) { ks = null ; } else if ( context == null ) { if ( config . getKeystoreType ( ) . equals ( "NONE" ) ) { ks = null ; pcb = null ; } else if ( config . getKeystoreType ( ) . equals ( "PKCS11" ) ) { try { Constructor < ? > c = Class . forName ( "sun.security.pkcs11.SunPKCS11" ) . getConstructor ( InputStream . class ) ; String pkcs11Config = "name = SmartCard\nlibrary = " + config . getPKCS11Library ( ) ; ByteArrayInputStream config = new ByteArrayInputStream ( pkcs11Config . getBytes ( ) ) ; Provider p = ( Provider ) c . newInstance ( config ) ; Security . addProvider ( p ) ; ks = KeyStore . getInstance ( "PKCS11" , p ) ; pcb = new PasswordCallback ( "PKCS11 Password: " , false ) ; this . config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( null , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } else if ( config . getKeystoreType ( ) . equals ( "Apple" ) ) { ks = KeyStore . getInstance ( "KeychainStore" , "Apple" ) ; ks . load ( null , null ) ; // pcb = new PasswordCallback("Apple Keychain",false); // pcb.setPassword(null); } else { ks = KeyStore . getInstance ( config . getKeystoreType ( ) ) ; try { pcb = new PasswordCallback ( "Keystore Password: " , false ) ; config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( new FileInputStream ( config . getKeystorePath ( ) ) , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } KeyManagerFactory kmf = KeyManagerFactory . getInstance ( "SunX509" ) ; try { if ( pcb == null ) { kmf . init ( ks , null ) ; } else { kmf . init ( ks , pcb . getPassword ( ) ) ; pcb . clearPassword ( ) ; } kms = kmf . getKeyManagers ( ) ; } catch ( NullPointerException npe ) { kms = null ; } } // Verify certificate presented by the server if ( context == null ) { context = SSLContext . getInstance ( "TLS" ) ; context . init ( kms , null , new java . security . SecureRandom ( ) ) ; } Socket plain = socket ; // Secure the plain connection socket = context . getSocketFactory ( ) . createSocket ( plain , plain . getInetAddress ( ) . getHostAddress ( ) , plain . getPort ( ) , true ) ; socket . setSoTimeout ( 0 ) ; socket . setKeepAlive ( true ) ; // Initialize the reader and writer with the new secured version initReaderAndWriter ( ) ; // Proceed to do the handshake ( ( SSLSocket ) socket ) . startHandshake ( ) ; // if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println("Connection wants client auth"); // } // else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println("Connection needs client auth"); // } // else { // System.err.println("Connection does not require client auth"); // } // Set that TLS was successful usingTLS = true ; // Set the new writer to use packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server packetWriter . openStream ( ) ; }


Input: Returns the compression handler that can be used for one compression methods offered by the server . [CODESPLIT] private XMPPInputOutputStream maybeGetCompressionHandler ( ) { if ( compressionMethods != null ) { for ( XMPPInputOutputStream handler : compressionHandlers ) { if ( ! handler . isSupported ( ) ) continue ; String method = handler . getCompressionMethod ( ) ; if ( compressionMethods . contains ( method ) ) return handler ; } } return null ; }


Input: Starts using stream compression that will compress network traffic . Traffic can be reduced up to 90% . Therefore stream compression is ideal when using a slow speed network connection . However the server and the client will need to use more CPU time in order to un / compress network data so under high load the server performance might be affected . <p > <p / > Stream compression has to have been previously offered by the server . Currently only the zlib method is supported by the client . Stream compression negotiation has to be done before authentication took place . <p > <p / > Note : to use stream compression the smackx . jar file has to be present in the classpath . [CODESPLIT] private boolean useCompression ( ) { // If stream compression was offered by the server and we want to use // compression then send compression request to the server if ( authenticated ) { throw new IllegalStateException ( "Compression should be negotiated before authentication." ) ; } if ( ( compressionHandler = maybeGetCompressionHandler ( ) ) != null ) { requestStreamCompression ( compressionHandler . getCompressionMethod ( ) ) ; // Wait until compression is being used or a timeout happened synchronized ( this ) { try { this . wait ( SmackConfiguration . getPacketReplyTimeout ( ) * 5 ) ; } catch ( InterruptedException e ) { // Ignore. } } return isUsingCompression ( ) ; } return false ; }


Input: Request the server that we want to start using stream compression . When using TLS then negotiation of stream compression can only happen after TLS was negotiated . If TLS compression is being used the stream compression should not be used . [CODESPLIT] private void requestStreamCompression ( String method ) { try { writer . write ( "<compress xmlns='http://jabber.org/protocol/compress'>" ) ; writer . write ( "<method>" + method + "</method></compress>" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; } }


Input: Start using stream compression since the server has acknowledged stream compression . [CODESPLIT] void startStreamCompression ( ) throws Exception { serverAckdCompression = true ; // Initialize the reader and writer with the new secured version initReaderAndWriter ( ) ; // Set the new writer to use packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server packetWriter . openStream ( ) ; // Notify that compression is being used synchronized ( this ) { this . notify ( ) ; } }


Input: Establishes a connection to the XMPP server and performs an automatic login only if the previous connection state was logged ( authenticated ) . It basically creates and maintains a socket connection to the server . <p > <p / > Listeners will be preserved from a previous connection if the reconnection occurs after an abrupt termination . [CODESPLIT] public void connect ( ) throws XMPPException { // Establishes the connection, readers and writers connectUsingConfiguration ( config ) ; // Automatically makes the login if the user was previously connected // successfully // to the server and the connection was terminated abruptly if ( connected && wasAuthenticated ) { // Make the login if ( isAnonymous ( ) ) { // Make the anonymous login loginAnonymously ( ) ; } else { login ( config . getUsername ( ) , config . getPassword ( ) , config . getResource ( ) ) ; } notifyReconnection ( ) ; } }


Input: Sends out a notification that there was an error with the connection and closes the connection . Also prints the stack trace of the given exception [CODESPLIT] synchronized void notifyConnectionError ( Exception e ) { // Listeners were already notified of the exception, return right here. if ( ( packetReader == null || packetReader . done ) && ( packetWriter == null || packetWriter . done ) ) return ; if ( packetReader != null ) packetReader . done = true ; if ( packetWriter != null ) packetWriter . done = true ; // Closes the connection temporary. A reconnection is possible shutdown ( new Presence ( Presence . Type . unavailable ) ) ; // Notify connection listeners of the error. for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . connectionClosedOnError ( e ) ; } catch ( Exception e2 ) { // Catch and print any exception so we can recover // from a faulty listener e2 . printStackTrace ( ) ; } } }


Input: Sends a notification indicating that the connection was reconnected successfully . [CODESPLIT] protected void notifyReconnection ( ) { // Notify connection listeners of the reconnection. for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . reconnectionSuccessful ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover // from a faulty listener e . printStackTrace ( ) ; } } }


Input: Registers a new SASL mechanism [CODESPLIT] public static void registerSASLMechanism ( String name , Class < ? extends SASLMechanism > mClass ) { implementedMechanisms . put ( name , mClass ) ; }


Input: Returns the registerd SASLMechanism classes sorted by the level of preference . [CODESPLIT] public static List < Class < ? extends SASLMechanism > > getRegisterSASLMechanisms ( ) { List < Class < ? extends SASLMechanism > > answer = new ArrayList < Class < ? extends SASLMechanism > > ( ) ; for ( String mechanismsPreference : mechanismsPreferences ) { answer . add ( implementedMechanisms . get ( mechanismsPreference ) ) ; } return answer ; }


Input: Performs SASL authentication of the specified user . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticate ( String username , String resource , CallbackHandler cbh ) throws XMPPException { // Locate the SASLMechanism to use String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found. Authenticate using the selected // mechanism and then // proceed to bind a resource try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism. We // use // connection.getHost() since GSAPI requires the FQDN of the // server, which // may not match the XMPP domain. currentMechanism . authenticate ( username , connection . getHost ( ) , cbh ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed // the connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication " + selectedMechanism + " failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed using mechanism " + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed } } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { throw new XMPPException ( "SASL Authentication failed. No known authentication mechanisims." ) ; } throw new XMPPException ( "SASL authentication failed" ) ; }


Input: Performs SASL authentication of the specified user . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticate ( String username , String password , String resource ) throws XMPPException { // Locate the SASLMechanism to use String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found. Authenticate using the selected // mechanism and then // proceed to bind a resource try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism. We // use // connection.getHost() since GSAPI requires the FQDN of the // server, which // may not match the XMPP domain. // The serviceName is basically the value that XMPP server sends // to the client as being the location // of the XMPP service we are trying to connect to. This should // have the format: host [ "/" serv-name ] // as per RFC-2831 guidelines String serviceName = connection . getServiceName ( ) ; currentMechanism . authenticate ( username , connection . getHost ( ) , serviceName , password ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed // the connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication " + selectedMechanism + " failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed using mechanism " + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed so try a Non-SASL // authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; // SASL authentication failed so try a Non-SASL authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } else { // No SASL method was found so try a Non-SASL authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } }


Input: Performs ANONYMOUS SASL authentication . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticateAnonymously ( ) throws XMPPException { try { currentMechanism = new SASLAnonymous ( this ) ; currentMechanism . authenticate ( null , null , null , "" ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 5000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed the // connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed" ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( null ) ; } else { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; } } catch ( IOException e ) { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; } }


Input: ========= PROPFIND PROPPATCH Support =============================== [CODESPLIT] public Object getProperty ( QName name ) { String n = getFullName ( name ) ; Object o = content . getProperty ( n ) ; LOGGER . debug ( "-------------- GETTING {} as {} --------------" , n , o ) ; return o ; }


Input: ========= LOCK Support =============================== [CODESPLIT] public LockToken createAndLock ( String name , LockTimeout timeout , LockInfo lockInfo ) throws NotAuthorizedException { LOGGER . debug ( "Create And Lock {} {} " , timeout , lockInfo ) ; try { String newPath = StorageClientUtils . newPath ( path , name ) ; LockHolder lockHolder = new LockHolder ( lockInfo , timeout ) ; String token = session . getLockManager ( ) . lock ( newPath , lockHolder . getTimeoutInSeconds ( ) , lockHolder . toString ( ) ) ; return new LockToken ( token , lockInfo , timeout ) ; } catch ( StorageClientException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; } catch ( AlreadyLockedException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; } }


Input: this method sets the controls for the Output - Plugin Behaviour . <p > Supply a Function which controls the OutputPlugin - Behaviour . You can set Priorities . The output - plugin with the highest POSITIVE priority ( in int ) will be processed first . Negative priorities are processed last ( so outputPlugins with no priorities will be processed in between positive and negative priorities ) [CODESPLIT] public void controlOutputPluginBehaviour ( Function < List < Identification > , HashMap < Integer , List < Identification > > > outputPluginBehaviour ) { this . outputPluginBehaviour = outputPluginBehaviour ; }


Input: generates the data to control the Event [CODESPLIT] @ Override public HashMap < Integer , List < Identification > > getOutputPluginBehaviour ( List < Identification > identifications ) { if ( outputPluginBehaviour == null ) return new HashMap <> ( ) ; return outputPluginBehaviour . apply ( identifications ) ; }


Input: Define the sling . home parameter implementing the algorithme defined on the wiki page to find the setting according to this algorithm : <ol > <li > Command line option <code > - c< / code > < / li > <li > System property <code > sling . home< / code > < / li > <li > Environment variable <code > SLING_HOME< / code > < / li > <li > Default value <code > sling< / code > < / li > < / ol > [CODESPLIT] private static String getSlingHome ( Map < String , String > commandLine ) { String source = null ; String slingHome = commandLine . get ( "c" ) ; if ( slingHome != null ) { source = "command line" ; } else { slingHome = System . getProperty ( SharedConstants . SLING_HOME ) ; if ( slingHome != null ) { source = "system property sling.home" ; } else { slingHome = System . getenv ( ENV_SLING_HOME ) ; if ( slingHome != null ) { source = "environment variable SLING_HOME" ; } else { source = "default" ; slingHome = SharedConstants . SLING_HOME_DEFAULT ; } } } System . setProperty ( SharedConstants . SLING_HOME , slingHome ) ; info ( "Setting sling.home=" + slingHome + " (" + source + ")" , null ) ; return slingHome ; }


Input: Parses the command line arguments into a map of strings indexed by strings . This method suppports single character option names only at the moment . Each pair of an option name and its value is stored into the map . If a single dash - character is encountered the rest of the command line are interpreted as option names and are stored in the map unmodified as entries with the same key and value . <table > <tr > <th > Command Line< / th > <th > Mapping< / th > < / tr > <tr > <td > x< / td > <td > x - > x< / td > < / tr > <tr > <td > - y z< / td > <td > y - > z< / td > < / tr > <tr > <td > - yz< / td > <td > y - > z< / td > < / tr > <tr > <td > - y - z< / td > <td > y - > y z - > z< / td > < / tr > <tr > <td > - y x - - z a< / td > <td > y - > x - z - > - z a - > a< / td > < / tr > < / table > [CODESPLIT] static Map < String , String > parseCommandLine ( String [ ] args ) { Map < String , String > commandLine = new HashMap < String , String > ( ) ; boolean readUnparsed = false ; for ( int argc = 0 ; args != null && argc < args . length ; argc ++ ) { String arg = args [ argc ] ; if ( readUnparsed ) { commandLine . put ( arg , arg ) ; } else if ( arg . startsWith ( "-" ) ) { if ( arg . length ( ) == 1 ) { readUnparsed = true ; } else { String key = String . valueOf ( arg . charAt ( 1 ) ) ; if ( arg . length ( ) > 2 ) { commandLine . put ( key , arg . substring ( 2 ) ) ; } else { argc ++ ; if ( argc < args . length && ( args [ argc ] . equals ( "-" ) || ! args [ argc ] . startsWith ( "-" ) ) ) { commandLine . put ( key , args [ argc ] ) ; } else { commandLine . put ( key , key ) ; argc -- ; } } } } else { commandLine . put ( arg , arg ) ; } } return commandLine ; }


Input: emit an informational message to standard out [CODESPLIT] static void info ( String message , Throwable t ) { log ( System . out , "*INFO*" , message , t ) ; }


Input: emit an error message to standard err [CODESPLIT] static void error ( String message , Throwable t ) { log ( System . err , "*ERROR*" , message , t ) ; }


Input: the throwable if not - null is also prefixed line by line with the prefix [CODESPLIT] private static void log ( PrintStream out , String prefix , String message , Throwable t ) { final StringBuilder linePrefixBuilder = new StringBuilder ( ) ; synchronized ( fmt ) { linePrefixBuilder . append ( fmt . format ( new Date ( ) ) ) ; } linePrefixBuilder . append ( prefix ) ; linePrefixBuilder . append ( " [" ) ; linePrefixBuilder . append ( Thread . currentThread ( ) . getName ( ) ) ; linePrefixBuilder . append ( "] " ) ; final String linePrefix = linePrefixBuilder . toString ( ) ; out . print ( linePrefix ) ; out . println ( message ) ; if ( t != null ) { t . printStackTrace ( new PrintStream ( out ) { @ Override public void println ( String x ) { synchronized ( this ) { print ( linePrefix ) ; super . println ( x ) ; flush ( ) ; } } } ) ; } }


Input: creates a new StartEvent . Assumes the Output is using the java - sound output . [CODESPLIT] public static Optional < StartEvent > createStartEvent ( Identification source ) { try { StartEvent startRequest = new StartEvent ( source ) ; return Optional . of ( startRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


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


Input: Notify that a new string has been written . [CODESPLIT] private void notifyListeners ( String str ) { WriterListener [ ] writerListeners = null ; synchronized ( listeners ) { writerListeners = new WriterListener [ listeners . size ( ) ] ; listeners . toArray ( writerListeners ) ; } for ( int i = 0 ; i < writerListeners . length ; i ++ ) { writerListeners [ i ] . write ( str ) ; } }


Input: checks whether it can provide the resource [CODESPLIT] @ Override public boolean providesResource ( ResourceModel resource ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourceS -> resourceS . equals ( resource . getResourceID ( ) ) ) ; }


Input: checks whether there are any resources registered from the source [CODESPLIT] @ Override public boolean containsResourcesFromSource ( String sourceID ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( source -> source . equals ( sourceID ) ) ; }


Input: checks whether the ResourceContainer can provide at least ONE resource [CODESPLIT] @ Override public boolean providesResource ( List < String > resourcesIDs ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourcesIDs :: contains ) ; }


Input: returns all EXISTING resources for the ID . If there are no resources for the ID the ID will get skipped [CODESPLIT] @ Override public List < ResourceModel > provideResource ( String [ ] resourceIDs ) { return resources . stream ( ) . filter ( resource -> Arrays . stream ( resourceIDs ) . anyMatch ( resourceID -> resourceID . equals ( resource . getResourceID ( ) ) ) ) . collect ( Collectors . toList ( ) ) ; }


Input: returns the resource ( if existing ) from the source [CODESPLIT] @ Override public List < ResourceModel > provideResourceFromSource ( String sourceID ) { return resources . stream ( ) . filter ( resource -> resource . getProvider ( ) . getID ( ) . equals ( sourceID ) ) . collect ( Collectors . toList ( ) ) ; }


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


Input: Try to retrieve an object from the cache . Has the side - effect of loading an uncached object into cache the first time . [CODESPLIT] protected Map < String , Object > getCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { Map < String , Object > m = null ; String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; CacheHolder cacheHolder = getFromCacheInternal ( cacheKey ) ; if ( cacheHolder != null ) { m = cacheHolder . get ( ) ; if ( m != null ) { LOGGER . debug ( "Cache Hit {} {} {} " , new Object [ ] { cacheKey , cacheHolder , m } ) ; } } if ( m == null ) { m = client . get ( keySpace , columnFamily , key ) ; if ( m != null ) { LOGGER . debug ( "Cache Miss, Found Map {} {}" , cacheKey , m ) ; } putToCacheInternal ( cacheKey , new CacheHolder ( m ) , true ) ; } return m ; }


Input: Combine the parameters into a key suitable for storage and lookup in the cache . [CODESPLIT] private String getCacheKey ( String keySpace , String columnFamily , String key ) throws StorageClientException { if ( client instanceof RowHasher ) { return ( ( RowHasher ) client ) . rowHash ( keySpace , columnFamily , key ) ; } return keySpace + ":" + columnFamily + ":" + key ; }


Input: Remove this object from the cache . Note StorageClient uses the word remove to mean delete . This method should do the same . [CODESPLIT] protected void removeCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { if ( sharedCache != null ) { // insert a replacement. This should cause an invalidation message // to propagate in the cluster. final String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; putToCacheInternal ( cacheKey , new CacheHolder ( null , managerId ) , false ) ; LOGGER . debug ( "Marked as deleted in Cache {} " , cacheKey ) ; if ( client instanceof Disposer ) { // we might want to change this to register the action as a // commit handler rather than a disposable. // it depends on if we think the delete is a transactional thing // or a operational cache thing. // at the moment, I am leaning towards an operational cache // thing, since regardless of if // the session commits or not, we want this to dispose when the // session is closed, or commits. ( ( Disposer ) client ) . registerDisposable ( new Disposable ( ) { @ Override public void setDisposer ( Disposer disposer ) { } @ Override public void close ( ) { CacheHolder ch = sharedCache . get ( cacheKey ) ; if ( ch != null && ch . wasLockedTo ( managerId ) ) { sharedCache . remove ( cacheKey ) ; LOGGER . debug ( "Removed deleted marker from Cache {} " , cacheKey ) ; } } } ) ; } } client . remove ( keySpace , columnFamily , key ) ; }


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


Input: Sets a jar filter . [CODESPLIT] public CF_Locator setJarFilter ( List < String > jarFilter ) { this . jarFilter . clear ( ) ; if ( jarFilter != null ) { this . jarFilter . addAll ( jarFilter ) ; } this . needsReRun = true ; return this ; }


Input: Runs the locator and collects all locations using the filters if set . The method can be called multiple times and will only result in a new map if any of the filters have been changed . If no filter has been changed the current map will be returned . [CODESPLIT] public Map < URI , String > getCfLocations ( ) { if ( this . needsReRun == true ) { this . locationMap . clear ( ) ; String pathSep = System . getProperty ( "path.separator" ) ; String classpath = System . getProperty ( "java.class.path" ) ; StringTokenizer st = new StringTokenizer ( classpath , pathSep ) ; File file = null ; while ( st . hasMoreTokens ( ) ) { String path = st . nextToken ( ) ; file = new File ( path ) ; this . include ( file ) ; } } this . needsReRun = false ; return this . locationMap ; }


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


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


Input: Add a SASL mechanism to the list to be used . [CODESPLIT] public static void addSaslMech ( String mech ) { initialize ( ) ; if ( ! defaultMechs . contains ( mech ) ) { defaultMechs . add ( mech ) ; } }


Input: Add a Collection of SASL mechanisms to the list to be used . [CODESPLIT] public static void addSaslMechs ( Collection < String > mechs ) { initialize ( ) ; for ( String mech : mechs ) { addSaslMech ( mech ) ; } }


Input: Creates the listeners that will print in the console when new activity is detected . [CODESPLIT] private void createDebug ( ) { // Create a special Reader that wraps the main Reader and logs data to // the GUI. ObservableReader debugReader = new ObservableReader ( reader ) ; readerListener = new ReaderListener ( ) { public void read ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " RCV  (" + connection . hashCode ( ) + "): " + str ) ; } } ; debugReader . addReaderListener ( readerListener ) ; // Create a special Writer that wraps the main Writer and logs data to // the GUI. ObservableWriter debugWriter = new ObservableWriter ( writer ) ; writerListener = new WriterListener ( ) { public void write ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " SENT (" + connection . hashCode ( ) + "): " + str ) ; } } ; debugWriter . addWriterListener ( writerListener ) ; // Assign the reader/writer objects to use the debug versions. The // packet reader // and writer will use the debug versions when they are created. reader = debugReader ; writer = debugWriter ; // Create a thread that will listen for all incoming packets and write // them to // the GUI. This is what we call "interpreted" packet data, since it's // the packet // data as Smack sees it and not as it's coming in as raw XML. listener = new PacketListener ( ) { public void processPacket ( Packet packet ) { if ( printInterpreted ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " RCV PKT (" + connection . hashCode ( ) + "): " + packet . toXML ( ) ) ; } } } ; connListener = new ConnectionListener ( ) { public void connectionClosed ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection closed (" + connection . hashCode ( ) + ")" ) ; } public void connectionClosedOnError ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection closed due to an exception (" + connection . hashCode ( ) + ")" ) ; e . printStackTrace ( ) ; } public void reconnectionFailed ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Reconnection failed due to an exception (" + connection . hashCode ( ) + ")" ) ; e . printStackTrace ( ) ; } public void reconnectionSuccessful ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection reconnected (" + connection . hashCode ( ) + ")" ) ; } public void reconnectingIn ( int seconds ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection (" + connection . hashCode ( ) + ") will reconnect in " + seconds ) ; } } ; }


Input: Create resources used by this component . [CODESPLIT] protected void activate ( Map < String , Object > properties ) throws Exception { configProperties = properties ; String [ ] safePostProcessorNames = ( String [ ] ) configProperties . get ( SAFE_POSTPROCESSORS ) ; if ( safePostProcessorNames == null ) { safeOpenProcessors . add ( "rss" ) ; safeOpenProcessors . add ( "trustedLoginTokenProxyPostProcessor" ) ; } else { for ( String pp : safePostProcessorNames ) { safeOpenProcessors . add ( pp ) ; } } // allow communications via a proxy server if command line // java parameters http.proxyHost,http.proxyPort,http.proxyUser, // http.proxyPassword have been provided. String proxyHost = System . getProperty ( "http.proxyHost" , "" ) ; if ( ! proxyHost . equals ( "" ) ) { useJreProxy = true ; } }


Input: Executes a HTTP call using a path in the JCR to point to a template and a map of properties to populate that template with . An example might be a SOAP call . [CODESPLIT] public ProxyResponse executeCall ( Map < String , Object > config , Map < String , Object > headers , Map < String , Object > input , InputStream requestInputStream , long requestContentLength , String requestContentType ) throws ProxyClientException { try { LOGGER . info ( "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] " + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] " , new Object [ ] { config , headers , input , requestInputStream , requestContentLength , requestContentType } ) ; bindConfig ( config ) ; if ( config != null && config . containsKey ( CONFIG_REQUEST_PROXY_ENDPOINT ) ) { // setup the post request String endpointURL = ( String ) config . get ( CONFIG_REQUEST_PROXY_ENDPOINT ) ; if ( isUnsafeProxyDefinition ( config ) ) { try { URL u = new URL ( endpointURL ) ; String host = u . getHost ( ) ; if ( host . indexOf ( ' ' ) >= 0 ) { throw new ProxyClientException ( "Invalid Endpoint template, relies on request to resolve valid URL " + u ) ; } } catch ( MalformedURLException e ) { throw new ProxyClientException ( "Invalid Endpoint template, relies on request to resolve valid URL" , e ) ; } } LOGGER . info ( "Valied Endpoint Def" ) ; Map < String , Object > context = Maps . newHashMap ( input ) ; // add in the config properties from the bundle overwriting // everything else. context . put ( "config" , configProperties ) ; endpointURL = processUrlTemplate ( endpointURL , context ) ; LOGGER . info ( "Calling URL {} " , endpointURL ) ; ProxyMethod proxyMethod = ProxyMethod . GET ; if ( config . containsKey ( CONFIG_REQUEST_PROXY_METHOD ) ) { try { proxyMethod = ProxyMethod . valueOf ( ( String ) config . get ( CONFIG_REQUEST_PROXY_METHOD ) ) ; } catch ( Exception e ) { } } HttpClient client = getHttpClient ( ) ; HttpUriRequest method = null ; switch ( proxyMethod ) { case GET : if ( config . containsKey ( CONFIG_LIMIT_GET_SIZE ) ) { long maxSize = ( Long ) config . get ( CONFIG_LIMIT_GET_SIZE ) ; HttpHead h = new HttpHead ( endpointURL ) ; HttpParams params = h . getParams ( ) ; // make certain we reject the body of a head params . setBooleanParameter ( "http.protocol.reject-head-body" , true ) ; h . setParams ( params ) ; populateMessage ( method , config , headers ) ; HttpResponse response = client . execute ( h ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { // Check if the content-length is smaller than the // maximum (if any). Header contentLengthHeader = response . getLastHeader ( "Content-Length" ) ; if ( contentLengthHeader != null ) { long length = Long . parseLong ( contentLengthHeader . getValue ( ) ) ; if ( length > maxSize ) { return new ProxyResponseImpl ( HttpServletResponse . SC_PRECONDITION_FAILED , "Response too large" , response ) ; } } } else { return new ProxyResponseImpl ( response ) ; } } method = new HttpGet ( endpointURL ) ; break ; case HEAD : method = new HttpHead ( endpointURL ) ; break ; case OPTIONS : method = new HttpOptions ( endpointURL ) ; break ; case POST : method = new HttpPost ( endpointURL ) ; break ; case PUT : method = new HttpPut ( endpointURL ) ; break ; default : method = new HttpGet ( endpointURL ) ; } populateMessage ( method , config , headers ) ; if ( requestInputStream == null && ! config . containsKey ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) { if ( method instanceof HttpPost ) { HttpPost postMethod = ( HttpPost ) method ; MultipartEntity multipart = new MultipartEntity ( ) ; for ( Entry < String , Object > param : input . entrySet ( ) ) { String key = param . getKey ( ) ; Object value = param . getValue ( ) ; if ( value instanceof Object [ ] ) { for ( Object val : ( Object [ ] ) value ) { addPart ( multipart , key , val ) ; } } else { addPart ( multipart , key , value ) ; } postMethod . setEntity ( multipart ) ; } } } else { if ( method instanceof HttpEntityEnclosingRequestBase ) { String contentType = requestContentType ; if ( contentType == null && config . containsKey ( CONFIG_REQUEST_CONTENT_TYPE ) ) { contentType = ( String ) config . get ( CONFIG_REQUEST_CONTENT_TYPE ) ; } if ( contentType == null ) { contentType = APPLICATION_OCTET_STREAM ; } HttpEntityEnclosingRequestBase eemethod = ( HttpEntityEnclosingRequestBase ) method ; if ( requestInputStream != null ) { eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( requestInputStream , requestContentLength ) ) ; } else { // build the request StringWriter body = new StringWriter ( ) ; templateService . evaluate ( context , body , ( String ) config . get ( "path" ) , ( String ) config . get ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) ; byte [ ] soapBodyContent = body . toString ( ) . getBytes ( "UTF-8" ) ; eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( new ByteArrayInputStream ( soapBodyContent ) , soapBodyContent . length ) ) ; } } } HttpResponse response = client . execute ( method ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 302 && method instanceof HttpEntityEnclosingRequestBase ) { // handle redirects on post and put String url = response . getFirstHeader ( "Location" ) . getValue ( ) ; method = new HttpGet ( url ) ; response = client . execute ( method ) ; } return new ProxyResponseImpl ( response ) ; } } catch ( ProxyClientException e ) { throw e ; } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new ProxyClientException ( "The Proxy request specified by  " + config + " failed, cause follows:" , e ) ; } finally { unbindConfig ( ) ; } throw new ProxyClientException ( "The Proxy request specified by " + config + " does not contain a valid endpoint specification " ) ; }


Input: registers the standard - events [CODESPLIT] private void registerStandardEvents ( ) { CommonEvents . Descriptors . stopListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . leavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . presenceListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . fullResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . majorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . minorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . notificationListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . responseListener ( this ) . ifPresent ( this :: registerEventListener ) ; }


Input: Registers or adds an event to the local_events . properties file with the informations found in the EventListener [CODESPLIT] public void registerEventListener ( EventListener eventListener ) { registerEventID ( eventListener . getDescription ( ) , eventListener . getDescriptorID ( ) , eventListener . getDescriptor ( ) ) ; }


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


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


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


Input: Checks if the outputExtension can execute with the current event [CODESPLIT] @ Override public boolean canRun ( EventModel event ) { //noinspection SimplifiableIfStatement if ( event != null ) { return event . getListResourceContainer ( ) . providesResource ( getResourceIdWishList ( ) ) ; } return false ; }


Input: Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source ) { try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Volume volume ) { if ( volume == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new VolumeResource ( source , volume ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Playlist playlist ) { if ( playlist == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new PlaylistResource ( source , playlist ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , TrackInfo trackInfo ) { if ( trackInfo == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new TrackInfoResource ( source , trackInfo ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Helper method to get an instance of { @link ClusterIdentifier } . [CODESPLIT] public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password ) { return getInstance ( hostsAndPorts , username , password , null ) ; }


Input: Helper method to get an instance of { @link ClusterIdentifier } . [CODESPLIT] public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password , String authorizationId ) { String [ ] key = { hostsAndPorts , username , password , authorizationId } ; try { return cache . get ( key ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } }


Input: Build a new DSE cluster instance . [CODESPLIT] public static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser ) { return newDseCluster ( hostsAndPorts , username , password , proxiedUser , null ) ; }


Input: Build a new DSE cluster instance . [CODESPLIT] public static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser , Configuration configuration ) { DseCluster . Builder builder = DseCluster . builder ( ) ; if ( ! StringUtils . isBlank ( username ) ) { AuthProvider authProvider ; if ( StringUtils . isBlank ( proxiedUser ) ) { authProvider = new DsePlainTextAuthProvider ( username , password ) ; } else { authProvider = new DsePlainTextAuthProvider ( username , password , proxiedUser ) ; } builder = builder . withAuthProvider ( authProvider ) ; } Collection < InetSocketAddress > contactPointsWithPorts = new HashSet < InetSocketAddress > ( ) ; String [ ] hostAndPortArr = StringUtils . split ( hostsAndPorts , ";, " ) ; for ( String hostAndPort : hostAndPortArr ) { String [ ] tokens = StringUtils . split ( hostAndPort , ' ' ) ; String host = tokens [ 0 ] ; int port = tokens . length > 1 ? Integer . parseInt ( tokens [ 1 ] ) : DEFAULT_CASSANDRA_PORT ; contactPointsWithPorts . add ( new InetSocketAddress ( host , port ) ) ; } builder = builder . addContactPointsWithPorts ( contactPointsWithPorts ) ; buildPolicies ( configuration , builder ) ; buildOptions ( configuration , builder ) ; DseCluster cluster = builder . build ( ) ; return cluster ; }


Input: Create a new session for a DSE cluster initializes it and sets the keyspace to the provided one . [CODESPLIT] public static DseSession newDseSession ( DseCluster cluster , String keyspace ) { return cluster . connect ( StringUtils . isBlank ( keyspace ) ? null : keyspace ) ; }


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


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


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


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


Input: creates the Playlist - Request [CODESPLIT] public static BroadcasterPlaylist createPlaylistRequest ( Identification provider , String playlistName ) { HashMap < String , Object > hashMap = new HashMap <> ( ) ; hashMap . put ( RESOURCE_ID , playlistName ) ; return new BroadcasterPlaylist ( provider , hashMap ) ; }


Input: creates the Playlist - Answer [CODESPLIT] public static BroadcasterPlaylist createPlaylistAnswer ( Identification provider , Playlist playlist ) { return new BroadcasterPlaylist ( provider , playlist . export ( ) ) ; }


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


Input: { @inheritDoc } [CODESPLIT] public void log ( int level , String msg ) { if ( inDebugMode ) { logger . info ( msg ) ; } switch ( level ) { case LogChute . DEBUG_ID : logger . debug ( msg ) ; break ; case LogChute . ERROR_ID : logger . error ( msg ) ; break ; case LogChute . INFO_ID : logger . info ( msg ) ; break ; case LogChute . TRACE_ID : logger . trace ( msg ) ; break ; case LogChute . WARN_ID : logger . warn ( msg ) ; break ; } }


Input: Appends one or more postfixes and separates them by slashes . [CODESPLIT] public UrlBuilder append ( boolean encode , String ... postFix ) { for ( String part : postFix ) { if ( StringUtils . isNotBlank ( part ) ) { if ( url . charAt ( url . length ( ) - 1 ) != ' ' && ! part . startsWith ( "/" ) ) { url . append ( ' ' ) ; } if ( encode ) { try { url . append ( URLEncoder . encode ( part , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } else { url . append ( part ) ; } } } return this ; }


Input: Create a query parameter with a boolean value . [CODESPLIT] public UrlBuilder queryParam ( String name , Boolean value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }


Input: Create a query parameter with a number value . [CODESPLIT] public UrlBuilder queryParam ( String name , Number value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }


Input: Create a query parameter with a String value . The value will be urlencoded . [CODESPLIT] public UrlBuilder queryParam ( String name , String value ) { return queryParam ( name , value , true ) ; }


Input: Create a query parameter with a String value . [CODESPLIT] public UrlBuilder queryParam ( String name , String value , boolean encode ) { if ( StringUtils . isNotEmpty ( value ) ) { if ( encode ) { try { value = URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } params . add ( new EntryImpl ( name , value ) ) ; } return this ; }


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


Input: This method is called from within the constructor to initialize the form . <p > Note : This code was generated by Netbeans . [CODESPLIT] private void initComponents ( ) { launchButton = new javax . swing . JButton ( ) ; statusLabel = new javax . swing . JLabel ( ) ; exitButton = new javax . swing . JButton ( ) ; headingLabel = new javax . swing . JLabel ( ) ; disclaimerLabel = new javax . swing . JLabel ( ) ; browserButton = new javax . swing . JButton ( ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . EXIT_ON_CLOSE ) ; setTitle ( "Launch Nakamura" ) ; setName ( "mainFrame" ) ; // NOI18N setResizable ( false ) ; launchButton . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N launchButton . setText ( "Launch" ) ; launchButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { launchButtonActionPerformed ( evt ) ; } } ) ; statusLabel . setFont ( new java . awt . Font ( "Arial" , 0 , 12 ) ) ; // NOI18N statusLabel . setText ( "Nakamura is not running." ) ; exitButton . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N exitButton . setText ( "Exit" ) ; exitButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { exitButtonActionPerformed ( evt ) ; } } ) ; headingLabel . setText ( "SakaiOAE icon" ) ; headingLabel . setBorder ( javax . swing . BorderFactory . createEtchedBorder ( ) ) ; disclaimerLabel . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N disclaimerLabel . setText ( "jLabel1" ) ; disclaimerLabel . setVerticalAlignment ( javax . swing . SwingConstants . TOP ) ; disclaimerLabel . setAutoscrolls ( true ) ; disclaimerLabel . setBorder ( javax . swing . BorderFactory . createTitledBorder ( "Disclaimer" ) ) ; browserButton . setText ( "Open Sakai OAE" ) ; browserButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { browserButtonActionPerformed ( evt ) ; } } ) ; javax . swing . GroupLayout layout = new javax . swing . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 27 , 27 , 27 ) . addComponent ( launchButton ) . addGap ( 18 , 18 , 18 ) . addComponent ( statusLabel ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , 162 , Short . MAX_VALUE ) . addComponent ( browserButton ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( exitButton ) ) . addGroup ( javax . swing . GroupLayout . Alignment . CENTER , layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 149 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addGap ( 18 , 18 , 18 ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 493 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( ) ) ) ; layout . linkSize ( javax . swing . SwingConstants . HORIZONTAL , new java . awt . Component [ ] { exitButton , launchButton } ) ; layout . setVerticalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 215 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 116 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addGap ( 58 , 58 , 58 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . CENTER ) . addComponent ( browserButton ) . addComponent ( exitButton ) ) . addContainerGap ( ) ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 259 , 259 , 259 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( launchButton , javax . swing . GroupLayout . PREFERRED_SIZE , 50 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( statusLabel ) ) . addContainerGap ( javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; pack ( ) ; }


Input: This is the launch button action method . This method launches the Apache Sling bootloader and informs the user to wait before accessing it in a browser . [CODESPLIT] private void launchButtonActionPerformed ( java . awt . event . ActionEvent evt ) { // Launch Nakamura if ( runStatus == APP_NOT_RUNNING ) { System . setSecurityManager ( null ) ; try { NakamuraMain . main ( savedArgs ) ; // Update label statusLabel . setText ( "Nakamura is starting..." ) ; // Notify the user JOptionPane . showMessageDialog ( this , "Nakamura has been started.\nPlease allow 30-60 seconds for it to be ready." , "Information" , JOptionPane . INFORMATION_MESSAGE ) ; runStatus = APP_RUNNING ; isStartupFinished ( ) ; } catch ( IOException e ) { statusLabel . setText ( "Nakamura is startup failed " + e . getMessage ( ) ) ; } } else { // Can't start it again... // custom title, warning icon JOptionPane . showMessageDialog ( this , "Nakamura is already running." , "Warning" , JOptionPane . WARNING_MESSAGE ) ; } }


Input: Pings the Apache Sling server URL every 5 seconds to see if it has finished booting . Once it receives an OK status it enables the button to launch the browser and disables the launch Nakamura button . [CODESPLIT] private void isStartupFinished ( ) { boolean started = false ; try { while ( ! started ) { if ( exists ( localhostURL ) ) started = true ; Thread . sleep ( 5 * 1000 ) ; } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( started ) { statusLabel . setText ( "Nakamura is running." ) ; statusLabel . setForeground ( Color . green ) ; launchButton . setEnabled ( false ) ; browserButton . setEnabled ( true ) ; } }


Input: Pings the Apache Sling server URL looking for an OK status . Returns true once that OK status is received . [CODESPLIT] public static boolean exists ( String URLName ) { try { HttpURLConnection . setFollowRedirects ( false ) ; // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = ( HttpURLConnection ) new URL ( URLName ) . openConnection ( ) ; con . setRequestMethod ( "HEAD" ) ; return ( con . getResponseCode ( ) == HttpURLConnection . HTTP_OK ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; } }


Input: Performs the action when the browser button is pressed which is launch a web browser and browse to the server URL . [CODESPLIT] private void browserButtonActionPerformed ( java . awt . event . ActionEvent evt ) { try { Desktop . getDesktop ( ) . browse ( new URL ( localhostURL ) . toURI ( ) ) ; } catch ( IOException e ) { System . err . println ( "IO Exception: " + e . getMessage ( ) ) ; } catch ( URISyntaxException e ) { System . err . println ( "URISyntaxException: " + e . getMessage ( ) ) ; } }


Input: Returns an ImageIcon or null if the path was invalid . [CODESPLIT] protected ImageIcon createImageIcon ( String path , String description ) { java . net . URL imgURL = getClass ( ) . getResource ( path ) ; if ( imgURL != null ) { return new ImageIcon ( imgURL , description ) ; } else { System . err . println ( "Couldn't find file: " + path ) ; return null ; } }


Input: Returns the full contents of a ( assumed ) text file for use in a label . [CODESPLIT] protected String getLabelText ( String path ) throws IOException { InputStream is = this . getClass ( ) . getResourceAsStream ( path ) ; if ( is != null ) { Writer writer = new StringWriter ( ) ; char [ ] buffer = new char [ 1024 ] ; try { Reader reader = new BufferedReader ( new InputStreamReader ( is , "UTF-8" ) ) ; int n ; while ( ( n = reader . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , n ) ; } } finally { is . close ( ) ; } return writer . toString ( ) ; } else { System . err . println ( "Couldn't find file: " + path ) ; return null ; } }


Input: The Main method which executes the program . [CODESPLIT] public static void main ( String args [ ] ) { savedArgs = args ; java . awt . EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { new LaunchNakamura ( ) . setVisible ( true ) ; } } ) ; }


Input: Replace contents with given values [CODESPLIT] public IntArray with ( int ... values ) { if ( values . length != this . length ) throw new IllegalArgumentException ( "Array size mismatch" ) ; value = values . clone ( ) ; return this ; }


Input: exports the Presence to a HashMap [CODESPLIT] public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( LEVEL_DESCRIPTOR , level . name ( ) ) ; data . put ( PRESENT_DESCRIPTOR , present ) ; data . put ( STRICT_DESCRIPTOR , strict ) ; data . put ( KNOWN_DESCRIPTOR , known ) ; return data ; }


Input: imports ( if no errors occurred ) the Presence from the ResourceModel [CODESPLIT] public static Optional < Presence > importPresence ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { //noinspection unchecked HashMap < String , Object > data = ( HashMap < String , Object > ) resource ; PresenceIndicatorLevel level ; try { level = PresenceIndicatorLevel . valueOf ( ( String ) data . get ( LEVEL_DESCRIPTOR ) ) ; } catch ( IllegalArgumentException e ) { level = PresenceIndicatorLevel . VERY_WEAK ; } boolean present = ( boolean ) data . get ( PRESENT_DESCRIPTOR ) ; boolean strict = ( boolean ) data . get ( STRICT_DESCRIPTOR ) ; boolean known = ( boolean ) data . get ( KNOWN_DESCRIPTOR ) ; return Optional . of ( new Presence ( level , present , strict , known ) ) ; } catch ( Exception e ) { return Optional . empty ( ) ; } }


Input: Advance current JSON value to specified element in JSON array . Set current JSON value to null otherwise . [CODESPLIT] public JSONResult get ( int index ) { if ( value instanceof JSONArray ) { JSONArray array = ( JSONArray ) value ; Object result = array . get ( index ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONObject ) { return get ( String . valueOf ( index ) ) ; } return new JSONResult ( null ) ; }


Input: Advance current JSON value to specified value of current JSON object . Set current JSON value to null otherwise . [CODESPLIT] public JSONResult get ( String key ) { if ( value instanceof JSONObject ) { JSONObject obj = ( JSONObject ) value ; Object result = obj . get ( key ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONArray ) { try { int index = Integer . parseInt ( key ) ; return get ( index ) ; } catch ( NumberFormatException e ) { throw createException ( "Excpected JSONObject " + key + ":" ) ; } } return new JSONResult ( null ) ; }