Input: Generates a connection with the server and tries to authenticate . If an error occurs in any of the steps then a ComponentException is thrown . [CODESPLIT] public void connect ( String host , int port , String subdomain ) throws ComponentException { try { // Open a socket to the server this . socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , manager . getConnectTimeout ( ) ) ; if ( manager . getServerName ( ) != null ) { this . domain = subdomain + "." + manager . getServerName ( ) ; } else { this . domain = subdomain ; } this . subdomain = subdomain ; // Keep these variables that will be used in case a reconnection is // required this . host = host ; this . port = port ; try { factory = XmlPullParserFactory . newInstance ( ) ; reader = new XPPPacketReader ( ) ; reader . setXPPFactory ( factory ) ; reader . getXPPParser ( ) . setInput ( new InputStreamReader ( socket . getInputStream ( ) , CHARSET ) ) ; // Get a writer for sending the open stream tag writer = new BufferedWriter ( new OutputStreamWriter ( socket . getOutputStream ( ) , CHARSET ) ) ; // Open the stream. StringBuilder stream = new StringBuilder ( ) ; stream . append ( "<stream:stream" ) ; stream . append ( " xmlns=\"jabber:component:accept\"" ) ; stream . append ( " xmlns:stream=\"http://etherx.jabber.org/streams\"" ) ; if ( manager . isMultipleAllowed ( subdomain ) ) { stream . append ( " allowMultiple=\"true\"" ) ; } stream . append ( " to=\"" ) . append ( domain ) . append ( "\">" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server XmlPullParser xpp = reader . getXPPParser ( ) ; for ( int eventType = xpp . getEventType ( ) ; eventType != XmlPullParser . START_TAG ; ) { eventType = xpp . next ( ) ; } // Set the streamID returned from the server connectionID = xpp . getAttributeValue ( "" , "id" ) ; if ( xpp . getAttributeValue ( "" , "from" ) != null ) { this . domain = xpp . getAttributeValue ( "" , "from" ) ; } xmlSerializer = new XMLWriter ( writer ) ; // Handshake with the server stream = new StringBuilder ( ) ; stream . append ( "<handshake>" ) ; stream . append ( StringUtils . hash ( connectionID + manager . getSecretKey ( subdomain ) ) ) ; stream . append ( "</handshake>" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server try { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( "error" . equals ( doc . getName ( ) ) ) { StreamError error = new StreamError ( doc ) ; // Close the connection socket . close ( ) ; socket = null ; // throw the exception with the wrapped error throw new ComponentException ( error ) ; } // Everything went fine // Start keep alive thread to send every 30 seconds of // inactivity a heart beat keepAliveTask = new KeepAliveTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( keepAliveTask , 15000 , 30000 ) ; timeoutTask = new TimeoutTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( timeoutTask , 2000 , 2000 ) ; } catch ( DocumentException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } } catch ( UnknownHostException uhe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing } throw new ComponentException ( uhe ) ; } catch ( IOException ioe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing } throw new ComponentException ( ioe ) ; } }


Input: Notification message that the connection with the server was lost unexpectedly . We will try to reestablish the connection for ever until the connection has been reestablished or this thread has been stopped . [CODESPLIT] public void connectionLost ( ) { // Ensure that only one thread will try to reconnect. synchronized ( this ) { if ( reconnecting ) { return ; } reconnecting = true ; } readerThread = null ; boolean isConnected = false ; if ( ! shutdown ) { // Notify the component that connection was lost so it needs to // shutdown. The component is // still registered in the local component manager but just not // connected to the server component . shutdown ( ) ; } while ( ! isConnected && ! shutdown ) { try { connect ( host , port , subdomain ) ; isConnected = true ; // It may be possible that while a new connection was being // established the // component was required to shutdown so in this case we need to // close the new // connection if ( shutdown ) { disconnect ( ) ; } else { // Component is back again working so start it up again start ( ) ; } } catch ( ComponentException e ) { manager . getLog ( ) . error ( "Error trying to reconnect with the server" , e ) ; // Wait for 5 seconds until the next retry try { Thread . sleep ( 5000 ) ; } catch ( InterruptedException e1 ) { // Do nothing } } } reconnecting = false ; }


Input: Adds an { @link IQResultListener } that will be invoked when an IQ result is sent to the server itself and is of type result or error . This is a nice way for the server to send IQ packets to other XMPP entities and be waked up when a response is received back . <p > [CODESPLIT] void addIQResultListener ( String id , IQResultListener listener , long timeoutmillis ) { // be generated by the server and simulate like the client sent it. This // will let listeners // react and be removed from the collection resultListeners . put ( id , listener ) ; resultTimeout . put ( id , System . currentTimeMillis ( ) + timeoutmillis ) ; }


Input: Rolls back the changes to the map . [CODESPLIT] public void rollback ( ) { if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; ArrayList < Entry < K , V > > list = new ArrayList < Entry < K , V > > ( allEntrySet ( ) ) ; for ( Iterator < Entry < K , V >> i = list . iterator ( ) ; i . hasNext ( ) ; ) { final Node < K , V > node = ( Node < K , V > ) i . next ( ) ; if ( node . is ( Node . ADDED , id ) ) { doRedBlackDelete ( node ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; )  ( ( TransactionNotifiable ) i2 . next ( ) ) . removedFromMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } if ( node . is ( Node . DELETED , id ) ) { node . setStatus ( Node . NO_CHANGE , null ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; )  ( ( TransactionNotifiable ) i2 . next ( ) ) . addedToMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } } }


Input: Retrieve the current thread id for use by the transaction code . [CODESPLIT] protected String getCurrentThreadId ( ) { String attach_id = ( String ) ThreadSession . getValue ( getThreadSessionKey ( ) ) ; if ( attach_id != null ) return attach_id ; Thread thread = Thread . currentThread ( ) ; return thread . toString ( ) + "(" + thread . hashCode ( ) + ")" ; }


Input: Checks that this node is valid for the current thread [CODESPLIT] private boolean validNode ( final Node < K , V > node , final String thread_id ) { if ( auto_commit || node == null ) return ( node != null ) ; return ! ( ( node . is ( Node . DELETED , thread_id ) ) || ( node . is ( Node . ADDED , null ) && node . is ( Node . NO_CHANGE , thread_id ) ) ) ; }


Input: Returns the key to which this map maps the specified value . Returns null if the map contains no mapping for this value . [CODESPLIT] public K getKeyForValue ( final Object value ) throws ClassCastException , NullPointerException { return ( K ) doGet ( value , VALUE ) ; }


Input: Returns a set view of the mappings contained in this map . Each element in the returned set is a Map . Entry . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableSet < Entry < K , V > > entrySetByValueDescending ( ) { return new AbstractFilterableSet < Entry < K , V > > ( ) { @ Override public Iterator < Entry < K , V > > iterator ( ) { return new TransactionalBidiTreeMapDescendingIterator < Entry < K , V > > ( VALUE ) { @ Override protected Entry < K , V > doGetNext ( ) { return lastReturnedNode ; } } ; } @ Override public boolean contains ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , getCurrentThreadId ( ) ) ; return ( node != null ) && node . getData ( KEY ) . equals ( key ) ; } @ Override public boolean remove ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } String thread_id = getCurrentThreadId ( ) ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , thread_id ) ; if ( ( node != null ) && node . getData ( KEY ) . equals ( key ) ) { if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else node . setStatus ( Node . DELETED , thread_id ) ; return true ; } return false ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; }


Input: Returns a set view of the keys contained in this map . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableSet < K > keySetByValue ( ) { if ( setOfKeysByValue == null ) { setOfKeysByValue = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( VALUE ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldnodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByValue ; }


Input: Returns a collection view of the values contained in this map . The collection is backed by the map so changes to the map are reflected in the collection and vice - versa . If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined . The collection supports element removal which removes the corresponding mapping from the map via the Iterator . remove Collection . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableCollection < V > valuesByValue ( ) { if ( collectionOfValuesByValue == null ) { collectionOfValuesByValue = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( VALUE ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldnodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByValue ; }


Input: common remove logic ( remove by key or remove by value ) [CODESPLIT] private Object doRemove ( final Object o , final int index ) throws ConcurrentModificationException { checkNonNullComparable ( o , index ) ; String thread_id = getCurrentThreadId ( ) ; Node < K , V > node = lookupValid ( o , index , thread_id ) ; Object rval = null ; if ( validNode ( node , thread_id ) ) { if ( node != null && node . is ( Node . DELETED , null ) && ! node . is ( Node . DELETED , thread_id ) ) throw new ConcurrentModificationException ( ) ; rval = node . getData ( oppositeIndex ( index ) ) ; if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else { node . setStatus ( Node . DELETED , thread_id ) ; } } return rval ; }


Input: common get logic used to get by key or get by value [CODESPLIT] private Object doGet ( final Object o , final int index ) { checkNonNullComparable ( o , index ) ; Node < K , V > node = lookupValid ( o , index , getCurrentThreadId ( ) ) ; return ( node == null ) ? null : node . getData ( oppositeIndex ( index ) ) ; }


Input: do the actual lookup of a piece of valid data [CODESPLIT] private Node < K , V > lookupValid ( final Object data , final int index , final String thread_id ) { return nextEqualValid ( getFloorEqualNode ( lookup ( data , index ) , index ) , index , thread_id ) ; }


Input: do the actual lookup of a piece of data [CODESPLIT] private Node < K , V > lookup ( final Object data , final int index ) { Node < K , V > rval = null ; Node < K , V > node = rootNode [ index ] ; while ( node != null ) { int cmp = compare ( Node . NO_CHANGE , data , node . getStatus ( ) , node . getData ( index ) , index ) ; if ( cmp == 0 ) { rval = node ; break ; } else { node = ( cmp < 0 ) ? node . getLeft ( index ) : node . getRight ( index ) ; } } return rval ; }


Input: Compare two objects [CODESPLIT] private int compare ( final int o1_status , final Object o1 , final int o2_status , final Object o2 , final int index ) { if ( comparators [ index ] == null ) { if ( o1 instanceof TransactionalComparable ) return ( ( TransactionalComparable ) o1 ) . compareTo ( o1_status , o2 , o2_status ) ; else return ( ( Comparable ) o1 ) . compareTo ( o2 ) ; } else { return comparators [ index ] . compare ( o1 , o2 ) ; } }


Input: find the least node from a given node . very useful for starting a sorting iterator ... [CODESPLIT] private Node < K , V > leastNode ( final Node < K , V > node , final int index ) { Node < K , V > lval = node ; if ( lval != null ) { while ( lval . getLeft ( index ) != null ) { lval = lval . getLeft ( index ) ; } } return lval ; }


Input: find the most node from a given node . [CODESPLIT] private Node < K , V > mostNode ( final Node < K , V > node , final int index ) { Node < K , V > rval = node ; if ( rval != null ) { while ( rval . getRight ( index ) != null ) { rval = rval . getRight ( index ) ; } } return rval ; }


Input:
get the next larger node from the specified node [CODESPLIT] private Node < K , V > nextGreater ( final Node < K , V > node , final int index ) { Node < K , V > rval ; if ( node == null ) { rval = null ; } else if ( node . getRight ( index ) != null ) { // everything to the node's right is larger. The least of
 // the right node's descendants is the next larger node
 rval = leastNode ( node . getRight ( index ) , index ) ; } else { // traverse up our ancestry until we find an ancestor that
 // is null or one whose left child is our ancestor. If we
 // find a null, then this node IS the largest node in the
 // tree, and there is no greater node. Otherwise, we are
 // the largest node in the subtree on that ancestor's left
 // ... and that ancestor is the next greatest node
 Node < K , V > parent = node . getParent ( index ) ; Node < K , V > child = node ; while ( ( parent != null ) && ( child == parent . getRight ( index ) ) ) { child = parent ; parent = parent . getParent ( index ) ; } rval = parent ; } return rval ; }


Input:
get the next smaller ( previous ) node from the specified node [CODESPLIT] private Node < K , V > nextSmaller ( final Node < K , V > node , final int index ) { Node < K , V > lval ; if ( node == null ) { lval = null ; } else if ( node . getLeft ( index ) != null ) { // everything to the node's left is smaller. The most of
 // the right node's descendants is the next smaller node
 lval = mostNode ( node . getLeft ( index ) , index ) ; } else { // traverse up our ancestry until we find an ancestor that
 // is null or one whose right child is our ancestor. If we
 // find a null, then this node IS the smallest node in the
 // tree, and there is no smaller node. Otherwise, we are
 // the smallest node in the subtree on that ancestor's right
 // ... and that ancestor is the next smallest node
 Node < K , V > parent = node . getParent ( index ) ; Node < K , V > child = node ; while ( ( parent != null ) && ( child == parent . getLeft ( index ) ) ) { child = parent ; parent = parent . getParent ( index ) ; } lval = parent ; } return lval ; }


Input: get the most valid node from the specified node [CODESPLIT] private Node < K , V > mostValidNode ( final Node < K , V > node , final int index , final String thread_id ) { Node < K , V > rval = node ; while ( rval != null && ! validNode ( rval , thread_id ) ) { rval = nextGreater ( rval , index ) ; } return rval ; }


Input: find the least valid node from a given node . very useful for starting a sorting iterator ... [CODESPLIT] private Node < K , V > leastValidNode ( final Node < K , V > node , final int index , final String thread_id ) { Node < K , V > lval = node ; while ( lval != null && ! validNode ( lval , thread_id ) ) { lval = nextSmaller ( lval , index ) ; } return lval ; }


Input:
copy the color from one node to another dealing with the fact that one or both nodes may in fact be null [CODESPLIT] private static < K , V > void copyColor ( final Node < K , V > from , final Node < K , V > to , final int index ) { if ( to != null ) { if ( from == null ) { // by default, make it black
 to . setBlack ( index ) ; } else { to . copyColor ( from , index ) ; } } }


Input: is the specified node red? if the node does not exist no it s black thank you [CODESPLIT] private static < K , V > boolean isRed ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? false : node . isRed ( index ) ) ; }


Input: is the specified black red? if the node does not exist sure it s black thank you [CODESPLIT] private static < K , V > boolean isBlack ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? true : node . isBlack ( index ) ) ; }


Input: force a node ( if it exists ) red [CODESPLIT] private static < K , V > void makeRed ( final Node < K , V > node , final int index ) { if ( node != null ) { node . setRed ( index ) ; } }


Input: force a node ( if it exists ) black [CODESPLIT] private static < K , V > void makeBlack ( final Node < K , V > node , final int index ) { if ( node != null ) { node . setBlack ( index ) ; } }


Input: get a node s grandparent . mind you the node its parent or its grandparent may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getGrandParent ( final Node < K , V > node , final int index ) { return getParent ( getParent ( node , index ) , index ) ; }


Input: get a node s parent . mind you the node or its parent may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getParent ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? null : node . getParent ( index ) ) ; }


Input: get a node s right child . mind you the node may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getRightChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? null : node . getRight ( index ) ; }


Input: get a node s left child . mind you the node may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getLeftChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? null : node . getLeft ( index ) ; }


Input: is this node its parent s left child? mind you the node or its parent may not exist . no problem . if the node doesn t exist ... it s its non - existent parent s left child . If the node does exist but has no parent ... no we re not the non - existent parent s left child . Otherwise ( both the specified node AND its parent exist ) check . [CODESPLIT] private static < K , V > boolean isLeftChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? true : ( ( node . getParent ( index ) == null ) ? false : ( node == node . getParent ( index ) . getLeft ( index ) ) ) ; }


Input: is this node its parent s right child? mind you the node or its parent may not exist . no problem . if the node doesn t exist ... it s its non - existent parent s right child . If the node does exist but has no parent ... no we re not the non - existent parent s right child . Otherwise ( both the specified node AND its parent exist ) check . [CODESPLIT] private static < K , V > boolean isRightChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? true : ( ( node . getParent ( index ) == null ) ? false : ( node == node . getParent ( index ) . getRight ( index ) ) ) ; }


Input:
do a rotate left . standard fare in the world of balanced trees [CODESPLIT] private void rotateLeft ( final Node < K , V > node , final int index ) { Node < K , V > rightChild = node . getRight ( index ) ; node . setRight ( rightChild . getLeft ( index ) , index ) ; if ( rightChild . getLeft ( index ) != null ) { rightChild . getLeft ( index ) . setParent ( node , index ) ; } rightChild . setParent ( node . getParent ( index ) , index ) ; if ( node . getParent ( index ) == null ) { // node was the root ... now its right child is the root
 rootNode [ index ] = rightChild ; } else if ( node . getParent ( index ) . getLeft ( index ) == node ) { node . getParent ( index ) . setLeft ( rightChild , index ) ; } else { node . getParent ( index ) . setRight ( rightChild , index ) ; } rightChild . setLeft ( node , index ) ; node . setParent ( rightChild , index ) ; }


Input:
do a rotate right . standard fare in the world of balanced trees [CODESPLIT] private void rotateRight ( final Node < K , V > node , final int index ) { Node < K , V > leftChild = node . getLeft ( index ) ; node . setLeft ( leftChild . getRight ( index ) , index ) ; if ( leftChild . getRight ( index ) != null ) { leftChild . getRight ( index ) . setParent ( node , index ) ; } leftChild . setParent ( node . getParent ( index ) , index ) ; if ( node . getParent ( index ) == null ) { // node was the root ... now its left child is the root
 rootNode [ index ] = leftChild ; } else if ( node . getParent ( index ) . getRight ( index ) == node ) { node . getParent ( index ) . setRight ( leftChild , index ) ; } else { node . getParent ( index ) . setLeft ( leftChild , index ) ; } leftChild . setRight ( node , index ) ; node . setParent ( leftChild , index ) ; }


Input:
complicated red - black insert stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more [CODESPLIT] private void doRedBlackInsert ( final Node < K , V > insertedNode , final int index ) { Node < K , V > currentNode = insertedNode ; makeRed ( currentNode , index ) ; while ( ( currentNode != null ) && ( currentNode != rootNode [ index ] ) && ( isRed ( currentNode . getParent ( index ) , index ) ) ) { if ( isLeftChild ( getParent ( currentNode , index ) , index ) ) { Node < K , V > y = getRightChild ( getGrandParent ( currentNode , index ) , index ) ; if ( isRed ( y , index ) ) { makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( y , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; currentNode = getGrandParent ( currentNode , index ) ; } else { if ( isRightChild ( currentNode , index ) ) { currentNode = getParent ( currentNode , index ) ; rotateLeft ( currentNode , index ) ; } makeBlack ( getParent ( currentNode , index ) , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; if ( getGrandParent ( currentNode , index ) != null ) { rotateRight ( getGrandParent ( currentNode , index ) , index ) ; } } } else { // just like clause above, except swap left for right
 Node < K , V > y = getLeftChild ( getGrandParent ( currentNode , index ) , index ) ; if ( isRed ( y , index ) ) { makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( y , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; currentNode = getGrandParent ( currentNode , index ) ; } else { if ( isLeftChild ( currentNode , index ) ) { currentNode = getParent ( currentNode , index ) ; rotateRight ( currentNode , index ) ; } makeBlack ( getParent ( currentNode , index ) , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; if ( getGrandParent ( currentNode , index ) != null ) { rotateLeft ( getGrandParent ( currentNode , index ) , index ) ; } } } } makeBlack ( rootNode [ index ] , index ) ; }


Input:
complicated red - black delete stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more [CODESPLIT] private void doRedBlackDelete ( final Node < K , V > deletedNode ) { for ( int index = FIRST_INDEX ; index < NUMBER_OF_INDICES ; index ++ ) { // if deleted node has both left and children, swap with
 // the next greater node
 if ( ( deletedNode . getLeft ( index ) != null ) && ( deletedNode . getRight ( index ) != null ) ) { swapPosition ( nextGreater ( deletedNode , index ) , deletedNode , index ) ; } Node < K , V > replacement = ( ( deletedNode . getLeft ( index ) != null ) ? deletedNode . getLeft ( index ) : deletedNode . getRight ( index ) ) ; if ( replacement != null ) { replacement . setParent ( deletedNode . getParent ( index ) , index ) ; if ( deletedNode . getParent ( index ) == null ) { rootNode [ index ] = replacement ; } else if ( deletedNode == deletedNode . getParent ( index ) . getLeft ( index ) ) { deletedNode . getParent ( index ) . setLeft ( replacement , index ) ; } else { deletedNode . getParent ( index ) . setRight ( replacement , index ) ; } deletedNode . setLeft ( null , index ) ; deletedNode . setRight ( null , index ) ; deletedNode . setParent ( null , index ) ; if ( isBlack ( deletedNode , index ) ) { doRedBlackDeleteFixup ( replacement , index ) ; } } else { // replacement is null
 if ( deletedNode . getParent ( index ) == null ) { // empty tree
 rootNode [ index ] = null ; } else { // deleted node had no children
 if ( isBlack ( deletedNode , index ) ) { doRedBlackDeleteFixup ( deletedNode , index ) ; } if ( deletedNode . getParent ( index ) != null ) { if ( deletedNode == deletedNode . getParent ( index ) . getLeft ( index ) ) { deletedNode . getParent ( index ) . setLeft ( null , index ) ; } else { deletedNode . getParent ( index ) . setRight ( null , index ) ; } deletedNode . setParent ( null , index ) ; } } } } shrink ( ) ; }


Input: complicated red - black delete stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more . This rebalances the tree ( somewhat as red - black trees are not perfectly balanced -- perfect balancing takes longer ) [CODESPLIT] private void doRedBlackDeleteFixup ( final Node < K , V > replacementNode , final int index ) { Node < K , V > currentNode = replacementNode ; while ( ( currentNode != rootNode [ index ] ) && ( isBlack ( currentNode , index ) ) ) { if ( isLeftChild ( currentNode , index ) ) { Node < K , V > siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; if ( isRed ( siblingNode , index ) ) { makeBlack ( siblingNode , index ) ; makeRed ( getParent ( currentNode , index ) , index ) ; rotateLeft ( getParent ( currentNode , index ) , index ) ; siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; } if ( isBlack ( getLeftChild ( siblingNode , index ) , index ) && isBlack ( getRightChild ( siblingNode , index ) , index ) ) { makeRed ( siblingNode , index ) ; currentNode = getParent ( currentNode , index ) ; } else { if ( isBlack ( getRightChild ( siblingNode , index ) , index ) ) { makeBlack ( getLeftChild ( siblingNode , index ) , index ) ; makeRed ( siblingNode , index ) ; rotateRight ( siblingNode , index ) ; siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; } copyColor ( getParent ( currentNode , index ) , siblingNode , index ) ; makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( getRightChild ( siblingNode , index ) , index ) ; rotateLeft ( getParent ( currentNode , index ) , index ) ; currentNode = rootNode [ index ] ; } } else { Node < K , V > siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; if ( isRed ( siblingNode , index ) ) { makeBlack ( siblingNode , index ) ; makeRed ( getParent ( currentNode , index ) , index ) ; rotateRight ( getParent ( currentNode , index ) , index ) ; siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; } if ( isBlack ( getRightChild ( siblingNode , index ) , index ) && isBlack ( getLeftChild ( siblingNode , index ) , index ) ) { makeRed ( siblingNode , index ) ; currentNode = getParent ( currentNode , index ) ; } else { if ( isBlack ( getLeftChild ( siblingNode , index ) , index ) ) { makeBlack ( getRightChild ( siblingNode , index ) , index ) ; makeRed ( siblingNode , index ) ; rotateLeft ( siblingNode , index ) ; siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; } copyColor ( getParent ( currentNode , index ) , siblingNode , index ) ; makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( getLeftChild ( siblingNode , index ) , index ) ; rotateRight ( getParent ( currentNode , index ) , index ) ; currentNode = rootNode [ index ] ; } } } makeBlack ( currentNode , index ) ; }


Input:
swap two nodes ( except for their content ) taking care of special cases where one is the other s parent ... hey it happens . [CODESPLIT] private void swapPosition ( final Node < K , V > x , final Node < K , V > y , final int index ) { // Save initial values.
 Node < K , V > xFormerParent = x . getParent ( index ) ; Node < K , V > xFormerLeftChild = x . getLeft ( index ) ; Node < K , V > xFormerRightChild = x . getRight ( index ) ; Node < K , V > yFormerParent = y . getParent ( index ) ; Node < K , V > yFormerLeftChild = y . getLeft ( index ) ; Node < K , V > yFormerRightChild = y . getRight ( index ) ; boolean xWasLeftChild = ( x . getParent ( index ) != null ) && ( x == x . getParent ( index ) . getLeft ( index ) ) ; boolean yWasLeftChild = ( y . getParent ( index ) != null ) && ( y == y . getParent ( index ) . getLeft ( index ) ) ; // Swap, handling special cases of one being the other's parent.
 if ( x == yFormerParent ) { // x was y's parent
 x . setParent ( y , index ) ; if ( yWasLeftChild ) { y . setLeft ( x , index ) ; y . setRight ( xFormerRightChild , index ) ; } else { y . setRight ( x , index ) ; y . setLeft ( xFormerLeftChild , index ) ; } } else { x . setParent ( yFormerParent , index ) ; if ( yFormerParent != null ) { if ( yWasLeftChild ) { yFormerParent . setLeft ( x , index ) ; } else { yFormerParent . setRight ( x , index ) ; } } y . setLeft ( xFormerLeftChild , index ) ; y . setRight ( xFormerRightChild , index ) ; } if ( y == xFormerParent ) { // y was x's parent
 y . setParent ( x , index ) ; if ( xWasLeftChild ) { x . setLeft ( y , index ) ; x . setRight ( yFormerRightChild , index ) ; } else { x . setRight ( y , index ) ; x . setLeft ( yFormerLeftChild , index ) ; } } else { y . setParent ( xFormerParent , index ) ; if ( xFormerParent != null ) { if ( xWasLeftChild ) { xFormerParent . setLeft ( y , index ) ; } else { xFormerParent . setRight ( y , index ) ; } } x . setLeft ( yFormerLeftChild , index ) ; x . setRight ( yFormerRightChild , index ) ; } // Fix children's parent pointers
 if ( x . getLeft ( index ) != null ) { x . getLeft ( index ) . setParent ( x , index ) ; } if ( x . getRight ( index ) != null ) { x . getRight ( index ) . setParent ( x , index ) ; } if ( y . getLeft ( index ) != null ) { y . getLeft ( index ) . setParent ( y , index ) ; } if ( y . getRight ( index ) != null ) { y . getRight ( index ) . setParent ( y , index ) ; } x . swapColors ( y , index ) ; // Check if root changed
 if ( rootNode [ index ] == x ) { rootNode [ index ] = y ; } else if ( rootNode [ index ] == y ) { rootNode [ index ] = x ; } }


Input: check if an object is fit to be proper input ... has to be Comparable if the comparator has not been set and non - null [CODESPLIT] private void checkNonNullComparable ( final Object o , final int index ) { if ( o == null ) { throw new NullPointerException ( dataName [ index ] + " cannot be null" ) ; } if ( comparators [ index ] == null && ! ( o instanceof Comparable ) ) { throw new ClassCastException ( dataName [ index ] + " must be Comparable" ) ; } }


Input:
insert a node by its value [CODESPLIT] private void insertValue ( final Node < K , V > newNode , final String thread_id ) throws IllegalArgumentException { Node < K , V > node = rootNode [ VALUE ] ; while ( true ) { int cmp = compare ( Node . ADDED , newNode . getData ( VALUE ) , node . getStatus ( ) , node . getData ( VALUE ) , VALUE ) ; if ( cmp == 0 ) { if ( nextEqualValid ( getFloorEqualNode ( node , VALUE ) , VALUE , thread_id ) != null ) { String debug_message = "Cannot store a duplicate value (\"" + newNode . getData ( VALUE ) + "\") in this Map. Value already exists for key " + node . getKey ( ) ; log . debug ( debug_message ) ; throw new IllegalArgumentException ( debug_message ) ; } if ( node . is ( Node . ADDED , null ) ) throw new ConcurrentModificationException ( ) ; if ( node . getRight ( VALUE ) != null ) { node = node . getRight ( VALUE ) ; } else if ( node . getLeft ( VALUE ) != null ) { node = node . getLeft ( VALUE ) ; } else { node . setRight ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } else if ( cmp < 0 ) { if ( node . getLeft ( VALUE ) != null ) { node = node . getLeft ( VALUE ) ; } else { node . setLeft ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } else { // cmp > 0
 if ( node . getRight ( VALUE ) != null ) { node = node . getRight ( VALUE ) ; } else { node . setRight ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } } }


Input: Returns true if this map contains a mapping for the specified key . [CODESPLIT] @ Override public boolean containsKey ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return lookupValid ( key , KEY , getCurrentThreadId ( ) ) != null ; }


Input: Returns true if this map maps one or more keys to the specified value . [CODESPLIT] @ Override public boolean containsValue ( final Object value ) { checkValue ( value ) ; return lookupValid ( value , VALUE , getCurrentThreadId ( ) ) != null ; }


Input: Returns the value to which this map maps the specified key . Returns null if the map contains no mapping for this key . [CODESPLIT] @ Override public V get ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return ( V ) doGet ( key , KEY ) ; }


Input:
Associates the specified value with the specified key in this map . [CODESPLIT] @ Override public V put ( final K key , final V value ) throws ClassCastException , NullPointerException , IllegalArgumentException , ConcurrentModificationException { checkKeyAndValue ( key , value ) ; Node < K , V > node = rootNode [ KEY ] ; String thread_id = getCurrentThreadId ( ) ; if ( node == null ) { Node < K , V > root = new Node < K , V > ( key , value ) ; rootNode [ KEY ] = root ; rootNode [ VALUE ] = root ; if ( ! auto_commit ) root . setStatus ( Node . ADDED , thread_id ) ; grow ( ) ; } else { while ( true ) { int cmp = compare ( Node . ADDED , key , node . getStatus ( ) , node . getData ( KEY ) , KEY ) ; if ( cmp == 0 ) { if ( nextEqualValid ( getFloorEqualNode ( node , KEY ) , KEY , thread_id ) != null ) { String debug_message = "Cannot store a duplicate key (\"" + key + "\") in this Map" ; log . debug ( debug_message ) ; throw new IllegalArgumentException ( debug_message ) ; } if ( node . is ( Node . ADDED , null ) ) throw new ConcurrentModificationException ( ) ; if ( node . getRight ( KEY ) != null ) { node = node . getRight ( KEY ) ; } else if ( node . getLeft ( KEY ) != null ) { node = node . getLeft ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setRight ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } else if ( cmp < 0 ) { if ( node . getLeft ( KEY ) != null ) { node = node . getLeft ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setLeft ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } else { // cmp > 0
 if ( node . getRight ( KEY ) != null ) { node = node . getRight ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setRight ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } } } return null ; }


Input: Removes the mapping for this key from this map if present [CODESPLIT] @ Override public V remove ( final Object key ) throws ConcurrentModificationException { checkKey ( key ) ; return ( V ) doRemove ( key , KEY ) ; }


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


Input: Returns a set view of the keys contained in this map . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . [CODESPLIT] @ Override public Set < K > keySet ( ) { if ( setOfKeysByKey == null ) { setOfKeysByKey = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( KEY ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldNodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByKey ; }


Input: Returns a collection view of the values contained in this map . The collection is backed by the map so changes to the map are reflected in the collection and vice - versa . If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined . The collection supports element removal which removes the corresponding mapping from the map via the Iterator . remove Collection . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . [CODESPLIT] @ Override public Collection < V > values ( ) { if ( collectionOfValuesByKey == null ) { collectionOfValuesByKey = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( KEY ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldNodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByKey ; }


Input:
It is very rare that this method would be required . You probably want to use entrySet instead . This method returns all Entry s in this Map no matter what its transactional status . [CODESPLIT] public FilterableSet < Entry < K , V > > allEntrySet ( ) { if ( setOfAllEntries == null ) { setOfAllEntries = new AbstractFilterableSet < Entry < K , V > > ( ) { @ Override public Iterator < Entry < K , V > > iterator ( ) { return new TransactionalBidiTreeMapIterator < Entry < K , V > > ( KEY ) { @ Override protected Entry < K , V > doGetNext ( ) { return lastReturnedNode ; } @ Override protected Node < K , V > getNextValidNode ( Node < K , V > node , String thread_id ) { return node ; } } ; } //cannot have contains or remove methods
 //as we have ALL the nodes and so may have duplicates
 //which are in the provess of being deleted
 @ Override public boolean contains ( Object o ) { throw new UtilsjException ( "method not supported" ) ; } @ Override public boolean remove ( Object o ) { throw new UtilsjException ( "method not supported" ) ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( true ) ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfAllEntries ; }


Input:
Copy all entries including transaction statuses from this map into the supplied map . Do not use this method unless you know exactly what you are doing . The auto commit flag of the supplied map may be changed as a result of calling this method check that this is valid first . [CODESPLIT] public final void copyEntries ( TransactionalBidiTreeMap < K , V > new_map ) { K key ; V val ; int transaction_status ; String transaction_id ; new_map . setAutoCommit ( isAutoCommit ( ) ) ; if ( ! isAutoCommit ( ) ) { // Do committed and deleted first
 for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; transaction_status = entry . getStatus ( ) ; transaction_id = entry . getTransactionId ( ) ; if ( transaction_status != TransactionalBidiTreeMap . Node . ADDED ) { try { // Put the value against the key
 new_map . put ( key , val ) ; // As the transaction status is deleted or no change then we need to commit the entry now.
 new_map . commit ( ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value
 try { // If transaction status is deleted we need to now attach to the transaction id and remove.
 if ( transaction_status == TransactionalBidiTreeMap . Node . DELETED ) { new_map . attach ( transaction_id ) ; new_map . remove ( key ) ; } } catch ( Exception e ) { } // The entry may have already been deleted
 // Finally detach
 new_map . detach ( ) ; } } // Then do added
 for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; transaction_status = entry . getStatus ( ) ; transaction_id = entry . getTransactionId ( ) ; if ( transaction_status == TransactionalBidiTreeMap . Node . ADDED ) { // As the transaction status is added then attach to the transaction id before putting.
 new_map . attach ( transaction_id ) ; try { // Put the value against the key
 new_map . put ( key , val ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value
 // Finally detach
 new_map . detach ( ) ; } } } else { for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; try { new_map . put ( key , val ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value
 } } }


Input: Gets the entry corresponding to the specified key ; if no such entry exists returns the entry for the least key greater than the specified key ; if no such entry exists ( i . e . the greatest key in the Tree is less than the specified key ) returns <tt > null< / tt > . [CODESPLIT] private Node < K , V > getCeilNode ( Object lookup , int type ) { Node < K , V > p = TransactionalBidiTreeMap . this . rootNode [ type ] ; Object compareval ; if ( p == null ) return null ; while ( true ) { compareval = type == KEY ? p . getKey ( ) : p . getValue ( ) ; int cmp = TransactionalBidiTreeMap . this . compare ( Node . NO_CHANGE , lookup , p . getStatus ( ) , compareval , type ) ; if ( cmp == 0 ) { return p ; } else if ( cmp < 0 ) { if ( p . getLeft ( type ) != null ) p = p . getLeft ( type ) ; else return p ; } else { if ( p . getRight ( type ) != null ) { p = p . getRight ( type ) ; } else { Node < K , V > parent = p . getParent ( type ) ; Node < K , V > ch = p ; while ( parent != null && ch == parent . getRight ( type ) ) { ch = parent ; parent = parent . getParent ( type ) ; } return parent ; } } } }


Input: / * Remove operation with a flag so we can tell coherence if the remove was caused by cache internal processing such as eviction or loading [CODESPLIT] public synchronized V remove ( Object key , boolean internal ) { // noinspection SuspiciousMethodCalls CacheObject < V > cacheObject = map . remove ( key ) ; // If the object is not in cache, stop trying to remove it. if ( cacheObject == null ) { return null ; } // Remove from the cache order list cacheObject . lastAccessedListNode . remove ( ) ; cacheObject . ageListNode . remove ( ) ; // Remove references to linked list nodes cacheObject . ageListNode = null ; cacheObject . lastAccessedListNode = null ; return cacheObject . object ; }


Input: Clears all entries out of cache where the entries are older than the maximum defined age . [CODESPLIT] protected synchronized void deleteExpiredEntries ( ) { // Check if expiration is turned on. if ( maxLifetime <= 0 ) { return ; } // Remove all old entries. To do this, we remove objects from the end // of the linked list until they are no longer too old. We get to avoid // any hash lookups or looking at any more objects than is strictly // neccessary. LinkedListNode node = ageList . getLast ( ) ; // If there are no entries in the age list, return. if ( node == null ) { return ; } // Determine the expireTime, which is the moment in time that elements // should expire from cache. Then, we can do an easy check to see // if the expire time is greater than the expire time. long expireTime = System . currentTimeMillis ( ) - maxLifetime ; while ( expireTime > node . timestamp ) { if ( remove ( node . object , true ) == null ) { log . warn ( "Error attempting to remove(" + node . object . toString ( ) + ") - cacheObject not found in cache!" ) ; // remove from the ageList node . remove ( ) ; } // Get the next node. node = ageList . getLast ( ) ; // If there are no more entries in the age list, return. if ( node == null ) { return ; } } }


Input: Removes the least recently used elements if the cache size is greater than or equal to the maximum allowed size until the cache is at least 10% empty . [CODESPLIT] protected synchronized void cullCache ( ) { // Check if a max cache size is defined. if ( maxCacheSize < 0 ) { return ; } // See if the cache is too big. If so, clean out cache until it's 10% // free. if ( map . size ( ) > maxCacheSize ) { // First, delete any old entries to see how much memory that frees. deleteExpiredEntries ( ) ; // Next, delete the least recently used elements until 10% of the // cache // has been freed. int desiredSize = ( int ) ( maxCacheSize * .90 ) ; for ( int i = map . size ( ) ; i > desiredSize ; i -- ) { // Get the key and invoke the remove method on it. if ( remove ( lastAccessedList . getLast ( ) . object , true ) == null ) { log . warn ( "Error attempting to cullCache with remove(" + lastAccessedList . getLast ( ) . object . toString ( ) + ") - cacheObject not found in cache!" ) ; lastAccessedList . getLast ( ) . remove ( ) ; } } } }


Input: When the bundle gets activated we retrieve the OSGi properties . [CODESPLIT] protected void activate ( Map < String , Object > props ) { // Get the properties from the console. sharedSecret = toString ( props . get ( "sharedSecret" ) , "e2KS54H35j6vS5Z38nK40" ) ; hostname = toString ( props . get ( "hostname" ) , "localhost" ) ; LOGGER . info ( " Trusted hostname: " + hostname ) ; port = toInteger ( props . get ( "port" ) , 80 ) ; LOGGER . info ( "Trusted port: " + port ) ; }


Input: { [CODESPLIT] @ Override public Map < String , Object > getPropertiesForUpdate ( ) { if ( ! readOnly && membersModified ) { modifiedMap . put ( MEMBERS_FIELD , StringUtils . join ( members , ' ' ) ) ; } Map < String , Object > propertiesForUpdate = super . getPropertiesForUpdate ( ) ; return propertiesForUpdate ; }


Input: { [CODESPLIT] @ Override // TODO: Unit test public Map < String , Object > getSafeProperties ( ) { if ( ! readOnly && membersModified ) { modifiedMap . put ( MEMBERS_FIELD , StringUtils . join ( members , ' ' ) ) ; } return super . getSafeProperties ( ) ; }


Input: { [CODESPLIT] public void process ( Map < String , Object > config , Map < String , Object > templateParams , HttpServletResponse response , ProxyResponse proxyResponse ) throws IOException { for ( Entry < String , String [ ] > h : proxyResponse . getResponseHeaders ( ) . entrySet ( ) ) { for ( String v : h . getValue ( ) ) { response . setHeader ( h . getKey ( ) , v ) ; } } int code = proxyResponse . getResultCode ( ) ; response . setStatus ( code ) ; IOUtils . copy ( proxyResponse . getResponseBodyAsInputStream ( ) , response . getOutputStream ( ) ) ; }


Input: asks the Player for more information about the playlist . <p > This method may block for 1 second . [CODESPLIT] public Optional < Playlist > getPlaylist ( String playlistName ) { try { return context . getResources ( ) . generateResource ( BroadcasterPlaylist . createPlaylistRequest ( player , playlistName ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( Playlist :: importResource ) ) . get ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { context . getLogger ( ) . error ( "unable to get Playlist" ) ; return Optional . empty ( ) ; } }


Input: asks the player for more information about the specified playlist and creates a PlayerRequest with the answer . [CODESPLIT] public Optional < PlayerRequest > getPlayerRequest ( String playlistName , boolean permanent ) { return getPlaylist ( playlistName ) . map ( playlist -> PlayerRequest . createPlayerRequest ( playlist , permanent , player , capabilities , context , identifiable ) ) ; }


Input: creates a new PlaylistSelector . <p > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist< / li > <li > the players - capabilities signal its broadcasting playlists< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( "unused" ) public static Optional < PlaylistSelector > getPlaylistsFromPlayer ( Identification player , AddOnModule addOnModule ) { if ( player == null || addOnModule == null ) return Optional . empty ( ) ; Function < Capabilities , CompletableFuture < Optional < PlaylistSelector > > > getPlaylistSelector = capabilities -> addOnModule . getContext ( ) . getResources ( ) . generateResource ( new BroadcasterAvailablePlaylists ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( BroadcasterAvailablePlaylists :: getPlaylists ) . map ( playlists -> new PlaylistSelector ( player , capabilities , playlists , addOnModule . getContext ( ) , addOnModule ) ) ) ; Function < List < ResourceModel > , Optional < Capabilities > > getCapabilities = resourceModels -> resourceModels . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( resource -> Capabilities . importFromResource ( resource , addOnModule . getContext ( ) ) ) . filter ( capabilities -> { if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( "player does not handle play-request from outside" ) ; return false ; } if ( ! capabilities . hasPlayRequestDetailed ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( "player does not handle trackInfo-request from outside" ) ; return false ; } if ( ! capabilities . isBroadcasting ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( "player is not broadcasting playlists" ) ; return false ; } return true ; } ) ; try { return addOnModule . getContext ( ) . getResources ( ) . generateResource ( new CapabilitiesResource ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( getCapabilities :: apply ) . thenCompose ( capabilities -> capabilities . map ( getPlaylistSelector :: apply ) . orElseGet ( ( ) -> CompletableFuture . completedFuture ( Optional . < PlaylistSelector > empty ( ) ) ) ) . get ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { addOnModule . getContext ( ) . getLogger ( ) . error ( "unable to get PlaylistSelector" ) ; return Optional . empty ( ) ; } }


Input: Creates a new roster store on disk [CODESPLIT] public static DefaultRosterStore init ( final File baseDir ) { DefaultRosterStore store = new DefaultRosterStore ( baseDir ) ; if ( store . setRosterVersion ( "" ) ) { return store ; } else { return null ; } }


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


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


Input: Return list of InetAddress for localhost that are not loopback addresses ( e . g . 127 . 0 . 0 . 1 ) [CODESPLIT] public static List < InetAddress > localhostNetworkAddresses ( ) throws UnknownHostException , SocketException { List < InetAddress > result = new ArrayList < InetAddress > ( ) ; InetAddress localhost = null ; try { //    localhost = InetAddress.getLocalHost(); throw new UnknownHostException ( ) ; } catch ( UnknownHostException ex ) { logger . debug ( "localhostNetworkAddresses InetAddress.getLocalHost() failed" ) ; } if ( localhost == null || localhost . getHostAddress ( ) . startsWith ( "127" ) ) { Enumeration < NetworkInterface > n = NetworkInterface . getNetworkInterfaces ( ) ; while ( n . hasMoreElements ( ) ) { NetworkInterface e = n . nextElement ( ) ; Enumeration < InetAddress > a = e . getInetAddresses ( ) ; while ( a . hasMoreElements ( ) ) { localhost = a . nextElement ( ) ; if ( localhost . isLoopbackAddress ( ) ) { // ignore } else { result . add ( localhost ) ; } } } } if ( result . size ( ) == 0 ) { result . add ( localhost ) ; } return result ; }


Input: Scan a range of InetAddresses starting with the given address [CODESPLIT] public static Collection < InetAddress > scanRange ( InetAddress addr , int count , int msTimeout ) { Collection < InetAddress > addresses = new ArrayList < InetAddress > ( ) ; Collection < InetAddress > result = new ArrayList < InetAddress > ( ) ; if ( addr == null ) { try { addresses . addAll ( localhostNetworkAddresses ( ) ) ; } catch ( Exception e ) { throw new FireRESTException ( e ) ; // Should not happen } } else { addresses . add ( addr ) ; } for ( InetAddress a : addresses ) { if ( a instanceof Inet4Address ) { InetAddress start = subnetAddress0 ( a , 24 ) ; result . addAll ( scanRangeCore ( start , count , msTimeout ) ) ; } } return result ; }


Input: Return first address on subnet containing given address [CODESPLIT] public static InetAddress subnetAddress0 ( InetAddress addr , int subnetBits ) { if ( subnetBits < 1 || 32 <= subnetBits ) { throw new FireRESTException ( "Expected subnetBits 1..31" ) ; } long mask = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { mask <<= 1 ; mask |= i < subnetBits ? 1 : 0 ; } long host0 = asLongAddress ( addr ) & mask ; try { return asInetAddress ( host0 ) ; } catch ( UnknownHostException e ) { throw new FireRESTException ( e ) ; } }


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


Input: ----------------------------------------------------------------------- [CODESPLIT] public Set < Map . Entry < K , V > > entrySet ( ) { return SyncUtils . synchronizeRead ( lock , new Callback < Set < Map . Entry < K , V > > > ( ) { @ Override protected void doAction ( ) { FilterableSet < Map . Entry < K , V > > _set = ( FilterableSet < Map . Entry < K , V > > ) map . entrySet ( ) ; _return ( new SynchronizedFilterableSet < Map . Entry < K , V > > ( _set , lock ) ) ; } } ) ; }


Input: { [CODESPLIT] @ Override public void onFailure ( Throwable t ) { if ( t instanceof ExceedMaxAsyncJobsException ) { try { if ( stm != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , stm , consistencyLevel ) ; } else if ( pstm != null ) { if ( bindValuesArr != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , pstm , consistencyLevel , bindValuesArr ) ; } else { sessionManager . executeAsync ( this , permitTimeoutMs , pstm , consistencyLevel , bindValuesMap ) ; } } else if ( ! StringUtils . isBlank ( cql ) ) { if ( bindValuesArr != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , cql , consistencyLevel , bindValuesArr ) ; } else { sessionManager . executeAsync ( this , permitTimeoutMs , cql , consistencyLevel , bindValuesMap ) ; } } else { onError ( new Exception ( "No query is defined to retry!" ) ) ; } } catch ( Throwable _t ) { onError ( _t ) ; } } else { onError ( t ) ; } }


Input: <p > Reads a Document from the given <code > File< / code > < / p > [CODESPLIT] public Document read ( File file ) throws DocumentException , IOException , XmlPullParserException { String systemID = file . getAbsolutePath ( ) ; return read ( new BufferedReader ( new FileReader ( file ) ) , systemID ) ; }


Input: <p > Reads a Document from the given <code > URL< / code > < / p > [CODESPLIT] public Document read ( URL url ) throws DocumentException , IOException , XmlPullParserException { String systemID = url . toExternalForm ( ) ; return read ( createReader ( url . openStream ( ) ) , systemID ) ; }


Input: <p > Reads a Document from the given URL or filename . < / p > <p / > <p / > If the systemID contains a <code > : < / code > character then it is assumed to be a URL otherwise its assumed to be a file name . If you want finer grained control over this mechansim then please explicitly pass in either a { @link URL } or a { @link File } instance instead of a { @link String } to denote the source of the document . < / p > [CODESPLIT] public Document read ( String systemID ) throws DocumentException , IOException , XmlPullParserException { if ( systemID . indexOf ( ' ' ) >= 0 ) { // lets assume its a URL return read ( new URL ( systemID ) ) ; } else { // lets assume that we are given a file name return read ( new File ( systemID ) ) ; } }


Input: <p > Reads a Document from the given <code > Reader< / code > < / p > [CODESPLIT] public Document read ( Reader reader ) throws DocumentException , IOException , XmlPullParserException { getXPPParser ( ) . setInput ( reader ) ; return parseDocument ( ) ; }


Input: <p > Reads a Document from the given array of characters < / p > [CODESPLIT] public Document read ( char [ ] text ) throws DocumentException , IOException , XmlPullParserException { getXPPParser ( ) . setInput ( new CharArrayReader ( text ) ) ; return parseDocument ( ) ; }


Input: <p > Reads a Document from the given stream < / p > [CODESPLIT] public Document read ( InputStream in , String systemID ) throws DocumentException , IOException , XmlPullParserException { return read ( createReader ( in ) , systemID ) ; }


Input: <p > Reads a Document from the given <code > Reader< / code > < / p > [CODESPLIT] public Document read ( Reader reader , String systemID ) throws DocumentException , IOException , XmlPullParserException { Document document = read ( reader ) ; document . setName ( systemID ) ; return document ; }


Input: ------------------------------------------------------------------------- [CODESPLIT] public Document parseDocument ( ) throws DocumentException , IOException , XmlPullParserException { DocumentFactory df = getDocumentFactory ( ) ; Document document = df . createDocument ( ) ; Element parent = null ; XmlPullParser pp = getXPPParser ( ) ; int count = 0 ; while ( true ) { int type = - 1 ; type = pp . nextToken ( ) ; switch ( type ) { case XmlPullParser . PROCESSING_INSTRUCTION : { String text = pp . getText ( ) ; int loc = text . indexOf ( " " ) ; if ( loc >= 0 ) { document . addProcessingInstruction ( text . substring ( 0 , loc ) , text . substring ( loc + 1 ) ) ; } else document . addProcessingInstruction ( text , "" ) ; break ; } case XmlPullParser . COMMENT : { if ( parent != null ) parent . addComment ( pp . getText ( ) ) ; else document . addComment ( pp . getText ( ) ) ; break ; } case XmlPullParser . CDSECT : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addCDATA ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( "Cannot have text content outside of the root document" ) ; } } break ; } case XmlPullParser . ENTITY_REF : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addText ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( "Cannot have an entityref outside of the root document" ) ; } } break ; } case XmlPullParser . END_DOCUMENT : { return document ; } case XmlPullParser . START_TAG : { QName qname = ( pp . getPrefix ( ) == null ) ? df . createQName ( pp . getName ( ) , pp . getNamespace ( ) ) : df . createQName ( pp . getName ( ) , pp . getPrefix ( ) , pp . getNamespace ( ) ) ; Element newElement = null ; // Do not include the namespace if this is the start tag of a // new packet // This avoids including "jabber:client", "jabber:server" or // "jabber:component:accept" if ( "jabber:client" . equals ( qname . getNamespaceURI ( ) ) || "jabber:server" . equals ( qname . getNamespaceURI ( ) ) || "jabber:component:accept" . equals ( qname . getNamespaceURI ( ) ) || "http://jabber.org/protocol/httpbind" . equals ( qname . getNamespaceURI ( ) ) ) { newElement = df . createElement ( pp . getName ( ) ) ; } else { newElement = df . createElement ( qname ) ; } int nsStart = pp . getNamespaceCount ( pp . getDepth ( ) - 1 ) ; int nsEnd = pp . getNamespaceCount ( pp . getDepth ( ) ) ; for ( int i = nsStart ; i < nsEnd ; i ++ ) if ( pp . getNamespacePrefix ( i ) != null ) newElement . addNamespace ( pp . getNamespacePrefix ( i ) , pp . getNamespaceUri ( i ) ) ; for ( int i = 0 ; i < pp . getAttributeCount ( ) ; i ++ ) { QName qa = ( pp . getAttributePrefix ( i ) == null ) ? df . createQName ( pp . getAttributeName ( i ) ) : df . createQName ( pp . getAttributeName ( i ) , pp . getAttributePrefix ( i ) , pp . getAttributeNamespace ( i ) ) ; newElement . addAttribute ( qa , pp . getAttributeValue ( i ) ) ; } if ( parent != null ) { parent . add ( newElement ) ; } else { document . add ( newElement ) ; } parent = newElement ; count ++ ; break ; } case XmlPullParser . END_TAG : { if ( parent != null ) { parent = parent . getParent ( ) ; } count -- ; if ( count < 1 ) { return document ; } break ; } case XmlPullParser . TEXT : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addText ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( "Cannot have text content outside of the root document" ) ; } } break ; } default : { ; } } } }


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


Input: ----------------------------------------------------------------------- [CODESPLIT] public FilterableMap < K , V > filteredMap ( final Filter < ? super K > filter ) { return SyncUtils . synchronizeRead ( lock , new Callback < FilterableMap < K , V > > ( ) { @ Override protected void doAction ( ) { FilterableMap < K , V > _map = getFilterableBidiMap ( ) . filteredMap ( filter ) ; _return ( new SynchronizedFilterableMap < K , V > ( _map , lock ) ) ; } } ) ; }


Input: retruns true if any of these arguments is already existing and would be overwritten otherwise retruns false . The method also returns true if everything is null except the albumCover - Format ( maybe known in advance ) . [CODESPLIT] public boolean isNew ( TrackInfo trackInfo ) { return isNew ( trackInfo . name , trackInfo . artist , trackInfo . album , trackInfo . albumCover , trackInfo . albumCoverFormat , trackInfo . data , trackInfo . year , trackInfo . genre , trackInfo . bmp , trackInfo . duration ) ; }


Input: retruns true if any of these arguments is already existing and would be overwritten otherwise retruns false . The method also returns true if everything is null except the albumCover - Format ( maybe known in advance ) . [CODESPLIT] public boolean isNew ( String name , String artist , String album , byte [ ] albumCover , String albumCoverFormat , String id , String year , String genre , String bmp , long duration ) { if ( name == null && artist == null && album == null && albumCover == null && id == null ) return true ; BiPredicate < String , String > compareStrings = ( newString , oldString ) -> oldString != null && newString != null && ! oldString . equals ( newString ) ; if ( compareStrings . test ( name , this . name ) ) { return true ; } if ( compareStrings . test ( artist , this . artist ) ) { return true ; } if ( compareStrings . test ( album , this . album ) ) { return true ; } if ( compareStrings . test ( id , this . data ) ) { return true ; } if ( compareStrings . test ( albumCoverFormat , this . albumCoverFormat ) ) { return true ; } if ( compareStrings . test ( year , this . year ) ) { return true ; } if ( compareStrings . test ( genre , this . genre ) ) { return true ; } if ( this . duration > 0 && duration > 0 && this . duration == duration ) { return true ; } if ( compareStrings . test ( bmp , this . bmp ) ) { return true ; } if ( albumCover != null ) { if ( this . albumCover == null || ! Arrays . equals ( albumCover , this . albumCover ) ) return true ; } return false ; }


Input: returns a trackinfo if some information was added and not overwritten ( see isNew ) AND a change occurred . [CODESPLIT] public Optional < TrackInfo > update ( String name , String artist , String album , byte [ ] albumCover , String coverFormat , String data , String year , String genre , String bmp , long duration ) { if ( isNew ( name , artist , album , albumCover , albumCoverFormat , data , year , genre , bmp , duration ) ) return Optional . empty ( ) ; boolean change = false ; if ( name != null && ! name . equals ( this . name ) ) { change = true ; } if ( artist != null && ! artist . equals ( this . artist ) ) { change = true ; } if ( album != null && ! album . equals ( this . album ) ) { change = true ; } if ( name != null && ! name . equals ( this . name ) ) { change = true ; } if ( albumCoverFormat != null && ! albumCoverFormat . equals ( this . albumCoverFormat ) ) { change = true ; } if ( data != null && ! data . equals ( this . data ) ) { change = true ; } if ( year != null && ! year . equals ( this . year ) ) { change = true ; } if ( genre != null && ! genre . equals ( this . genre ) ) { change = true ; } if ( duration > 0 && duration != this . duration ) { change = true ; } if ( bmp != null && ! bmp . equals ( this . bmp ) ) { change = true ; } if ( ! change ) return Optional . empty ( ) ; return Optional . of ( new TrackInfo ( this . name == null ? name : this . name , this . artist == null ? artist : this . artist , this . album == null ? album : this . album , this . albumCover == null ? albumCover : this . albumCover , this . albumCoverFormat == null ? albumCoverFormat : this . albumCoverFormat , this . data == null ? data : this . data , this . year == null ? year : this . year , this . genre == null ? genre : this . genre , this . bmp == null ? bmp : this . bmp , this . duration < 0 ? duration : this . duration ) ) ; }


Input: exports the TrackInfo to a Hashmap [CODESPLIT] public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( nameDescriptor , name ) ; data . put ( artistDescriptor , artist ) ; data . put ( albumDescriptor , albumDescriptor ) ; data . put ( albumCoverDescriptor , albumCover ) ; data . put ( albumCoverFormatDescriptor , albumCoverFormatDescriptor ) ; data . put ( dataDescriptor , this . data ) ; data . put ( yearDescriptor , this . year ) ; data . put ( genreDescriptor , this . genre ) ; data . put ( durationDescriptor , this . duration ) ; data . put ( bmpDescriptor , this . bmp ) ; return data ; }


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


Input: creates a TrackInfo from the resourceModel [CODESPLIT] public static Optional < TrackInfo > importFromResource ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { @ SuppressWarnings ( "unchecked" ) HashMap < String , Object > hashMap = ( HashMap < String , Object > ) resource ; return importFromHashMap ( hashMap ) ; } catch ( ClassCastException e ) { return Optional . empty ( ) ; } }


Input: a new map with just [ key -- &gt ; value ] maplet [CODESPLIT] public static < K , V > Map < K , V > map ( K key , V value ) { return new MapBuilder ( ) . put ( key , value ) . toMap ( ) ; }


Input: Sets the jar filter for the executor . This filter can contain any name of a jar file that should be considered during search . If not set no filter is applied . If the argument is null no filter is used . Otherwise all strings in the argument are used as jar files and only those jar files will be used in a search . Using filters can speed up the search process . Filters can be set any time a new filter will overwrite an existing one ( using null will disable filtering ) . [CODESPLIT] protected final void setJarFilter ( String [ ] filter ) { this . jarFilter = ( filter == null ) ? null : Collections . unmodifiableList ( Arrays . asList ( filter ) ) ; }


Input: Adds a new application at runtime with name ( shortcut to start ) and related class . [CODESPLIT] protected final void addApplication ( String name , Class < ? extends ExecS_Application > clazz ) { this . classmap . put ( name , clazz ) ; }


Input: Adds a set of application at runtime as in all found applications that can be executed [CODESPLIT] protected final void addAllApplications ( Set < Class < ? > > set ) { for ( Class < ? > cls : set ) { if ( ! cls . isInterface ( ) && ! Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( ! this . classmap . containsValue ( cls ) ) { this . classNames . add ( cls . getName ( ) ) ; } } } }


Input: Main method [CODESPLIT] public final int execute ( String [ ] args ) { String arguments = StringUtils . join ( args , ' ' ) ; StrTokenizer tokens = new StrTokenizer ( arguments ) ; String arg = tokens . nextToken ( ) ; int ret = 0 ; if ( arg == null || "-?" . equals ( arg ) || "-h" . equals ( arg ) || "--help" . equals ( arg ) ) { //First help: no arguments or -? or --help -> print usage and exit(0) this . printUsage ( ) ; return 0 ; } else if ( "-v" . equals ( arg ) || "--version" . equals ( arg ) ) { System . out . println ( this . appName + " - " + ExecS . APP_VERSION ) ; System . out . println ( ) ; } else if ( "-l" . equals ( arg ) || "--list" . equals ( arg ) ) { //Second list: if -l or --list -> trigger search and exit(0) CF cf = new CF ( ) . setJarFilter ( ( ArrayUtils . contains ( args , "-j" ) ) ? this . jarFilter : null ) . setPkgFilter ( ( ArrayUtils . contains ( args , "-p" ) ) ? this . packageFilter : null ) ; this . addAllApplications ( cf . getSubclasses ( ExecS_Application . class ) ) ; this . printList ( ) ; return 0 ; } else { Object svc = null ; if ( this . classmap . containsKey ( arg ) ) { try { svc = this . classmap . get ( arg ) . newInstance ( ) ; } catch ( IllegalAccessException | InstantiationException iex ) { System . err . println ( this . appName + ": tried to execute <" + args [ 0 ] + "> by registered name -> exception: " + iex . getMessage ( ) ) ; //					iex.printStackTrace(); ret = - 99 ; } } else { try { Class < ? > c = Class . forName ( arg ) ; svc = c . newInstance ( ) ; } catch ( ClassNotFoundException | IllegalAccessException | InstantiationException ex ) { System . err . println ( this . appName + ": tried to execute <" + args [ 0 ] + "> as class name -> exception: " + ex . getMessage ( ) ) ; //					ex.printStackTrace(); ret = - 99 ; } } ret = this . executeApplication ( svc , args , arg ) ; } if ( ret == - 99 ) { //now we are in trouble, nothing we could do worked, so print that and quit System . err . println ( this . appName + ": no application could be started and nothing else could be done, try '-?' or '--help' for help" ) ; System . err . println ( ) ; } return ret ; }


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


Input: Prints a list of pre - registered and found applications . [CODESPLIT] protected final void printList ( ) { ST list = this . stg . getInstanceOf ( "list" ) ; list . add ( "appName" , this . appName ) ; if ( this . classmap . size ( ) > 0 ) { List < Map < String , String > > l = new ArrayList <> ( ) ; for ( String key : this . classmap . keySet ( ) ) { Map < String , String > m = new HashMap <> ( ) ; m . put ( "key" , key ) ; m . put ( "val" , this . classmap . get ( key ) . getName ( ) ) ; l . add ( m ) ; } list . add ( "classMap" , l ) ; } list . add ( "className" , this . classNames ) ; System . out . println ( list . render ( ) ) ; }


Input: Prints usage information to standard out . [CODESPLIT] protected final void printUsage ( ) { ST usage = this . stg . getInstanceOf ( "usage" ) ; usage . add ( "appName" , this . appName ) ; usage . add ( "packageFilter" , this . packageFilter ) ; usage . add ( "jarFilter" , this . jarFilter ) ; usage . add ( "excludedNames" , new TreeSet <> ( Arrays . asList ( new CF ( ) . excludedNames ) ) ) ; System . out . println ( usage . render ( ) ) ; }


Input: Public main to start the application executor . [CODESPLIT] public static void main ( String [ ] args ) { ExecS run = new ExecS ( ) ; int ret = run . execute ( args ) ; System . exit ( ret ) ; }


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


Input: creates a new MuteEvent will mute everything [CODESPLIT] public static Optional < MuteEvent > createMuteEvent ( Identification source ) { if ( source == null ) return Optional . empty ( ) ; try { MuteEvent muteRequest = new MuteEvent ( source ) ; return Optional . of ( muteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Invalidate and refresh the cache <p / > This is blocking and returns when the cache has been updated [CODESPLIT] public void refreshSchemataCache ( ) { try { final List < GoodwillSchema > schemata = delegate . getSchemata ( ) . get ( ) ; // If Goodwill is down - keep the old cache around if ( schemata == null ) { return ; } final Map < String , GoodwillSchema > newSchemataCache = new ConcurrentHashMap < String , GoodwillSchema > ( ) ; for ( final GoodwillSchema schema : schemata ) { newSchemataCache . put ( schema . getName ( ) , schema ) ; } synchronized ( cacheMonitor ) { knownSchemata . clear ( ) ; knownSchemata . putAll ( newSchemataCache ) ; } } catch ( InterruptedException e ) { log . warn ( "Interrupted while refreshing the cache" ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( ExecutionException e ) { log . warn ( "Unable to refresh schemata cache: {}" , e . getLocalizedMessage ( ) ) ; } }


Input: Given a schema name get the associated GoodwillSchema . This method tries hard to find it i . e . it will refresh the cache if the schema is not in the cache . [CODESPLIT] public GoodwillSchema getSchema ( final String schemaName ) { GoodwillSchema schema = knownSchemata . get ( schemaName ) ; if ( schema == null ) { refreshSchemataCache ( ) ; schema = knownSchemata . get ( schemaName ) ; } return schema ; }


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


Input: Tests if the class is run from an executable JAR . [CODESPLIT] protected boolean inExecJar ( ) { Class < Gen_ExecJarScripts > clazz = Gen_ExecJarScripts . class ; String className = clazz . getSimpleName ( ) + ".class" ; String classPath = clazz . getResource ( className ) . toString ( ) ; if ( ! classPath . startsWith ( "jar" ) ) { System . err . println ( this . getAppName ( ) + ": not started in a jar, cannot proceed" ) ; return false ; } String manifestPath = classPath . substring ( 0 , classPath . lastIndexOf ( "!" ) + 1 ) + "/META-INF/MANIFEST.MF" ; Manifest manifest ; try { manifest = new Manifest ( new URL ( manifestPath ) . openStream ( ) ) ; } catch ( IOException ex ) { System . err . println ( this . getAppName ( ) + ": exception while retrieving manifest: " + ex . getMessage ( ) ) ; return false ; } Attributes attr = manifest . getMainAttributes ( ) ; if ( StringUtils . isBlank ( attr . getValue ( "Main-Class" ) ) ) { System . err . println ( this . getAppName ( ) + ": no main class in manifest, probably not an executable JAR, cannot continue" ) ; return false ; } return true ; }


Input: Adds a new option to CLI parser and option list . [CODESPLIT] protected void addOption ( ApplicationOption < ? > option ) { if ( option != null ) { this . getCli ( ) . addOption ( option ) ; this . options . add ( option ) ; } }


Input: Get the schema as a collection of fields . We guarantee the ordering by field id . [CODESPLIT] public ArrayList < GoodwillSchemaField > getSchema ( ) { final ArrayList < GoodwillSchemaField > items = new ArrayList < GoodwillSchemaField > ( thriftItems . values ( ) ) ; Collections . sort ( items , new Comparator < GoodwillSchemaField > ( ) { @ Override public int compare ( final GoodwillSchemaField left , final GoodwillSchemaField right ) { return Short . valueOf ( left . getId ( ) ) . compareTo ( right . getId ( ) ) ; } } ) ; return items ; }


Input: Given a name return the field matching the name . [CODESPLIT] public GoodwillSchemaField getFieldByName ( final String name ) { for ( final GoodwillSchemaField field : thriftItems . values ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return field ; } } return null ; }


Input: Returns the package name for a jar entry . [CODESPLIT] public final static String getPkgName ( JarEntry entry ) { if ( entry == null ) { return "" ; } String s = entry . getName ( ) ; if ( s == null ) { return "" ; } if ( s . length ( ) == 0 ) { return s ; } if ( s . startsWith ( "/" ) ) { s = s . substring ( 1 , s . length ( ) ) ; } if ( s . endsWith ( "/" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) ; } return s . replace ( ' ' , ' ' ) ; }


Input: { @inheritDoc } [CODESPLIT] public InputStream getResponseBodyAsInputStream ( ) throws IOException { InputStream in = response . getEntity ( ) . getContent ( ) ; leakedInputStreams . add ( in ) ; return in ; }


Input: { @inheritDoc } [CODESPLIT] public String getResponseBodyAsString ( ) throws IOException { HttpEntity entity = response . getEntity ( ) ; if ( entity == null ) { return null ; } String contentEncoding = getContentEncoding ( entity ) ; InputStream in = entity . getContent ( ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( in , contentEncoding ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { String l = r . readLine ( ) ; if ( l == null ) { break ; } sb . append ( l ) . append ( "\n" ) ; } r . close ( ) ; in . close ( ) ; return sb . toString ( ) ; }


Input: { @inheritDoc } [CODESPLIT] public void close ( ) { for ( InputStream in : leakedInputStreams ) { try { in . close ( ) ; } catch ( IOException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } } }


Input: Maps the content of the base map to its values . [CODESPLIT] private ImmutableMap < C , V > mapContentToValues ( final ImmutableMap < K , V > base ) { final ImmutableMap . Builder < C , V > builder = ImmutableMap . builder ( ) ; for ( final Entry < K , V > entry : base . entrySet ( ) ) { builder . put ( this . key ( entry . getKey ( ) ) , entry . getValue ( ) ) ; } return builder . build ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public StorageClient getClient ( ) throws ClientPoolException { try { StorageClient client = ( StorageClient ) pool . borrowObject ( ) ; LOGGER . debug ( "Borrowed storage client pool client:" + client ) ; return client ; } catch ( Exception e ) { LOGGER . warn ( "Failed To Borrow connection from pool {} " , e . getMessage ( ) ) ; throw new ClientPoolException ( "Failed To Borrow connection from pool " , e ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public void releaseClient ( StorageClient client ) { try { if ( client != null ) { pool . returnObject ( client ) ; LOGGER . debug ( "Released storage client pool client:" + client ) ; } } catch ( Exception e ) { LOGGER . warn ( "Failed to close connection " + e . getMessage ( ) , e ) ; } }


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


Input: Sets the supplied state for this IterativeCallback . [CODESPLIT] public IterativeState < T , R > setState ( IterativeState < T , R > new_state ) { IterativeState < T , R > old_state = this . state ; this . state = new_state ; return old_state ; }


Input:
public wrapper for the iteration [CODESPLIT] public R iterate ( final FilterableCollection < ? extends T > c ) { initState ( ) ; checkUsed ( ) ; // If collection is decorated with a syncronized wrapper then synchronize the iteration
 if ( c instanceof SynchronizedFilterableCollection ) { return SyncUtils . synchronizeRead ( c , new Callback < R > ( ) { @ Override protected void doAction ( ) { _return ( doIteration ( c . iterator ( ) ) ) ; } } ) ; } return doIteration ( c . iterator ( ) ) ; }


Input:
do the actual iteration [CODESPLIT] private R doIteration ( Iterator < ? extends T > it ) { // save the iterator into member variable
 state . i = it ; state . iterations = 0 ; if ( state . do_break == true ) return state . return_object ; // do the iteration calling nextobject on each
 while ( state . i . hasNext ( ) ) { T o = state . i . next ( ) ; if ( delegate != null ) delegate . delegate ( o ) ; else iterateObject ( o ) ; if ( state . do_break == true ) return state . return_object ; } return state . amended_object ; }


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


Input: exports the progress [CODESPLIT] public HashMap < String , Long > export ( ) { HashMap < String , Long > data = new HashMap <> ( ) ; data . put ( lengthDescriptor , length ) ; data . put ( knownPositionDescriptor , knownPosition ) ; data . put ( knownMillisTimeStampDescriptor , knownMillisTimeStamp ) ; return data ; }


Input: creates a Progress - object from the resourceModel [CODESPLIT] public static Optional < Progress > importResource ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { //noinspection unchecked HashMap < String , Long > data = ( HashMap < String , Long > ) resource ; long length = data . get ( lengthDescriptor ) ; long knownPosition = data . get ( knownPositionDescriptor ) ; long knownTimestamp = data . get ( knownMillisTimeStampDescriptor ) ; return Optional . of ( new Progress ( length , knownPosition , knownTimestamp ) ) ; } catch ( Exception e ) { return Optional . empty ( ) ; } }


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


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


Input: Load json from given file resource . This is a convenient equivalent to getJSON () with a file URL . [CODESPLIT] public JSONResult getJSON ( File file ) { try { String json = new Scanner ( file ) . useDelimiter ( "\\Z" ) . next ( ) ; return new JSONResult ( json ) ; } catch ( Throwable e ) { throw new FireRESTException ( file . toString ( ) , e ) ; } }


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


Input: Property principals are stored with keys of the form _pp_<principal > [CODESPLIT] public PropertyAcl getPropertyAcl ( String objectType , String objectPath ) throws AccessDeniedException , StorageClientException { long t = System . currentTimeMillis ( ) ; checkOpen ( ) ; compilingPermissions . inc ( ) ; try { String key = this . getAclKey ( objectType , objectPath ) ; Map < String , Object > objectAcl = getCached ( keySpace , aclColumnFamily , key ) ; Set < String > orderedPrincipals = Sets . newLinkedHashSet ( ) ; { String principal = user . getId ( ) ; if ( principal . startsWith ( "_" ) ) { throw new StorageClientException ( "Princials may not start with _ " ) ; } orderedPrincipals . add ( principal ) ; } for ( String principal : getPrincipals ( user ) ) { if ( principal . startsWith ( "_" ) ) { throw new StorageClientException ( "Princials may not start with _ " ) ; } orderedPrincipals . add ( principal ) ; } // Everyone must be the last principal to be applied if ( ! User . ANON_USER . equals ( user . getId ( ) ) ) { orderedPrincipals . add ( Group . EVERYONE ) ; } // go through each principal Map < String , Integer > grants = Maps . newHashMap ( ) ; Map < String , Integer > denies = Maps . newHashMap ( ) ; for ( String principal : orderedPrincipals ) { // got through each property String ppk = PROPERTY_PRINCIPAL_STEM + principal ; for ( Entry < String , Object > e : objectAcl . entrySet ( ) ) { String k = e . getKey ( ) ; if ( k . startsWith ( ppk ) ) { String [ ] parts = StringUtils . split ( k . substring ( PROPERTY_PRINCIPAL_STEM . length ( ) ) , "@" ) ; String propertyName = parts [ 1 ] ; if ( AclModification . isDeny ( k ) ) { int td = toInt ( e . getValue ( ) ) ; denies . put ( propertyName , toInt ( denies . get ( propertyName ) ) | td ) ; } else if ( AclModification . isGrant ( k ) ) { int tg = toInt ( e . getValue ( ) ) ; grants . put ( propertyName , toInt ( grants . get ( propertyName ) ) | tg ) ; } } } } // if the property has been granted, then that should remove the // deny for ( Entry < String , Integer > g : grants . entrySet ( ) ) { String k = g . getKey ( ) ; if ( denies . containsKey ( k ) ) { denies . put ( k , toInt ( denies . get ( k ) ) & ~ g . getValue ( ) ) ; } } return new PropertyAcl ( denies ) ; } finally { compilingPermissions . dec ( ) ; statsService . apiCall ( AccessControlManagerImpl . class . getName ( ) , "getPropertyAcl" , System . currentTimeMillis ( ) - t ) ; } }


Input: Content Tokens activate ACEs for a user that holds the content token . The token is signed by the secret key associated with the target Object / acl and the token is token content item is then returned for the caller to save . [CODESPLIT] public void signContentToken ( Content token , String securityZone , String objectPath ) throws StorageClientException , AccessDeniedException { long t = System . currentTimeMillis ( ) ; try { checkOpen ( ) ; check ( Security . ZONE_CONTENT , objectPath , Permissions . CAN_WRITE_ACL ) ; check ( Security . ZONE_CONTENT , objectPath , Permissions . CAN_READ_ACL ) ; String key = this . getAclKey ( securityZone , objectPath ) ; Map < String , Object > currentAcl = getCached ( keySpace , aclColumnFamily , key ) ; String secretKey = ( String ) currentAcl . get ( _SECRET_KEY ) ; principalTokenValidator . signToken ( token , secretKey ) ; // the caller must save the target. } finally { statsService . apiCall ( AccessControlManagerImpl . class . getName ( ) , "signContentToken" , System . currentTimeMillis ( ) - t ) ; } }


Input: Take key and value pairs from source and create map from value to key in target . [CODESPLIT] public static < K , V > void reverse ( Map < K , V > source , Map < V , K > target ) { Iterator < K > i = source . keySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { K key = i . next ( ) ; V value = source . get ( key ) ; target . put ( value , key ) ; } }