idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
137,600
@ SuppressWarnings ( "rawtypes" ) public List < Interval > getIntervals ( ) { List < Interval > lstIntervals = new ArrayList < Interval > ( ) ; for ( AbstractEdge < T > e : this . edges ) { lstIntervals . addAll ( e . getIntervals ( ) ) ; } return lstIntervals ; }
Collect all intervals of all outgoing edges
83
7
137,601
public AbstractEdge < T > match ( T value ) throws UnmatchedException , MIDDException { for ( AbstractEdge < T > e : this . edges ) { if ( e . match ( value ) ) { return e ; } } throw new UnmatchedException ( "No matching edge found for value " + value ) ; }
Return an edge to match with input value
68
8
137,602
public AbstractNode createFromConjunctionClauses ( Map < String , AttributeInfo > intervals ) throws MIDDParsingException , MIDDException { if ( intervals == null || intervals . size ( ) == 0 ) { return ExternalNode . newInstance ( ) ; // return true-value external node } // Create edges from intervals Map < Integer , AbstractEdge < ? > > edges = new HashMap < Integer , AbstractEdge < ? > > ( ) ; for ( String attrId : intervals . keySet ( ) ) { int varId = attrMapper . getVariableId ( attrId ) ; Interval < ? > interval = intervals . get ( attrId ) . getInterval ( ) ; Class < ? > type = interval . getType ( ) ; AbstractEdge < ? > e = EdgeUtils . createEdge ( interval ) ; edges . put ( varId , e ) ; } List < Integer > lstVarIds = new ArrayList < Integer > ( edges . keySet ( ) ) ; Collections . sort ( lstVarIds ) ; // create a MIDD path from list of edges, start from lowest var-id InternalNode < ? > root = null ; InternalNode < ? > currentNode = null ; AbstractEdge < ? > currentEdge = null ; Iterator < Integer > lstIt = lstVarIds . iterator ( ) ; while ( lstIt . hasNext ( ) ) { Integer varId = lstIt . next ( ) ; AbstractEdge < ? > e = edges . get ( varId ) ; // default is NotApplicable, unless the "MustBePresent" is set to "true" String attrId = attrMapper . getAttributeId ( varId ) ; boolean isAttrMustBePresent = intervals . get ( attrId ) . isMustBePresent ; InternalNodeState nodeState = new InternalNodeState ( isAttrMustBePresent ? DecisionType . Indeterminate : DecisionType . NotApplicable ) ; InternalNode < ? > node = NodeUtils . createInternalNode ( varId , nodeState , e . getType ( ) ) ; if ( root == null ) { root = node ; // root points to the start of the MIDD path currentNode = node ; currentEdge = e ; } else { currentNode . addChild ( currentEdge , node ) ; currentNode = node ; currentEdge = e ; } } // the tail points to the true clause currentNode . addChild ( currentEdge , ExternalNode . newInstance ( ) ) ; // add a true-value external node return root ; }
Create a MIDD from conjunctions of intervals
551
9
137,603
private final static byte [ ] getAlphabet ( final int options ) { if ( ( options & Base64 . URL_SAFE ) == Base64 . URL_SAFE ) { return Base64 . _URL_SAFE_ALPHABET ; } else if ( ( options & Base64 . ORDERED ) == Base64 . ORDERED ) { return Base64 . _ORDERED_ALPHABET ; } else { return Base64 . _STANDARD_ALPHABET ; } }
Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified . It s possible though silly to specify ORDERED and URLSAFE in which case one of them will be picked though there is no guarantee as to which one will be picked .
107
57
137,604
private final static void usage ( final String msg ) { System . err . println ( msg ) ; System . err . println ( "Usage: java Base64 -e|-d inputfile outputfile" ) ; }
Prints command line usage .
45
6
137,605
public String toHeader ( ) { StringBuilder header = new StringBuilder ( ) ; header . append ( name ) . append ( ' ' ) . append ( value ) ; if ( domain != null ) { header . append ( "; " ) . append ( "Domain=" ) . append ( domain ) ; } if ( path != null ) { header . append ( "; " ) . append ( "Path=" ) . append ( path ) ; } if ( expireTime > - 1 ) { header . append ( "; " ) . append ( "Expires=" ) . append ( RFC_DATEFORMAT . format ( new Date ( expireTime ) ) ) ; } if ( secure ) { header . append ( "; " ) . append ( "Secure" ) ; } return header . toString ( ) ; }
Transforms this cookie into a Set - Cookie header field
171
11
137,606
public static String generateRandomString ( int nbytes ) { byte [ ] salt = new byte [ nbytes ] ; Random r = new SecureRandom ( ) ; r . nextBytes ( salt ) ; return bytesToHex ( salt ) ; }
Generate a random string with a certain entropy .
51
10
137,607
public static boolean fixedTimeEqual ( String lhs , String rhs ) { boolean equal = ( lhs . length ( ) == rhs . length ( ) ? true : false ) ; // If not equal, work on a single operand to have same length. if ( ! equal ) { rhs = lhs ; } int len = lhs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( lhs . charAt ( i ) == rhs . charAt ( i ) ) { equal = equal && true ; } else { equal = equal && false ; } } return equal ; }
Fixed time comparison of two strings .
136
7
137,608
private void initialize ( InputStream input ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( input ) ) ; String line ; Matcher m ; while ( ( line = reader . readLine ( ) ) != null ) { m = TYPE_PATTERN . matcher ( line ) ; if ( m . find ( ) ) { String type = m . group ( 1 ) ; String [ ] extensions = m . group ( 2 ) . split ( " " ) ; for ( String extension : extensions ) { contentTypes . put ( extension , type ) ; } } } } catch ( IOException e ) { // Unable to load } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } }
Read and parse the type file .
180
7
137,609
private static final String getExtension ( String fileName ) { return fileName . indexOf ( ' ' ) == - 1 ? null : fileName . substring ( fileName . lastIndexOf ( ' ' ) + 1 ) ; }
Get the extension of a file .
50
7
137,610
public boolean containsInterval ( Interval < T > i ) { for ( Interval < T > item : intervals ) { if ( item . contains ( i ) ) { return true ; } } return false ; }
Return true if the argument interval is a subset of an interval of the partition
45
15
137,611
public void addHeader ( String key , Object value ) { List < Object > values = headers . get ( key ) ; if ( values == null ) { headers . put ( key , values = new ArrayList < Object > ( ) ) ; } values . add ( value ) ; }
Add a header to the response
59
6
137,612
public void setResponse ( String response ) { this . response = response ; try { this . responseLength = response . getBytes ( "UTF-8" ) . length ; } catch ( UnsupportedEncodingException e ) { this . responseLength = response . length ( ) ; } }
Set the response string
60
4
137,613
public void setResponse ( InputStream response ) { this . response = response ; try { this . responseLength = response . available ( ) ; } catch ( IOException e ) { // This shouldn't happen. } }
Set the response Input Stream
45
5
137,614
public void start ( ) { if ( socket == null ) { throw new RuntimeException ( "Cannot bind a server that has not been initialized!" ) ; } running = true ; Thread t = new Thread ( this ) ; t . setName ( "HttpServer" ) ; t . start ( ) ; }
Start the server in a new thread
64
7
137,615
@ Override public void run ( ) { while ( running ) { try { // Read the request service . execute ( new HttpSession ( this , socket . accept ( ) ) ) ; } catch ( IOException e ) { // Ignore mostly. } } }
Run and process requests .
54
5
137,616
public void dispatchRequest ( HttpRequest httpRequest ) throws IOException { for ( HttpRequestHandler handler : handlers ) { HttpResponse resp = handler . handleRequest ( httpRequest ) ; if ( resp != null ) { httpRequest . getSession ( ) . sendResponse ( resp ) ; return ; } } if ( ! hasCapability ( HttpCapability . THREADEDRESPONSE ) ) { // If it's still here nothing handled it. httpRequest . getSession ( ) . sendResponse ( new HttpResponse ( HttpStatus . NOT_FOUND , HttpStatus . NOT_FOUND . toString ( ) ) ) ; } }
Dispatch a request to all handlers
140
6
137,617
public WwwAuthenticateHeader createWwwAuthenticateHeader ( ) throws HawkException { WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader . wwwAuthenticate ( ) ; if ( hasTs ( ) ) { if ( ! hasTsm ( ) ) { String hmac = this . generateHmac ( ) ; headerBuilder . ts ( getTs ( ) ) . tsm ( hmac ) ; } else { headerBuilder . ts ( getTs ( ) ) . tsm ( getTsm ( ) ) ; } if ( hasError ( ) ) { throw new IllegalStateException ( "Context cannot contain error and ts at the same time." ) ; } } if ( hasError ( ) ) { headerBuilder . error ( this . error ) ; } return headerBuilder . build ( ) ; }
Create a WWW - Authenticate header from this HawkWwwAuthenticateContext .
169
17
137,618
public boolean isValidTimestampMac ( String hmac ) throws HawkException { String this_hmac = this . generateHmac ( ) ; return Util . fixedTimeEqual ( this_hmac , hmac ) ; }
Check whether a given HMAC value matches the HMAC for the timestamp in this HawkWwwAuthenticateContext .
49
23
137,619
private String getBaseString ( ) { if ( ! hasTs ( ) ) { throw new IllegalStateException ( "This HawkWwwAuthenticateContext has no timestamp" ) ; } return new StringBuilder ( HAWK_TS_PREFIX ) . append ( SLF ) . append ( getTs ( ) ) . append ( SLF ) . toString ( ) ; }
Generate base string for timestamp HMAC generation .
80
10
137,620
private String generateHmac ( ) throws HawkException { String baseString = getBaseString ( ) ; Mac mac ; try { mac = Mac . getInstance ( getAlgorithm ( ) . getMacName ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new HawkException ( "Unknown algorithm " + getAlgorithm ( ) . getMacName ( ) , e ) ; } SecretKeySpec secret_key = new SecretKeySpec ( getKey ( ) . getBytes ( Charsets . UTF_8 ) , getAlgorithm ( ) . getMacName ( ) ) ; try { mac . init ( secret_key ) ; } catch ( InvalidKeyException e ) { throw new HawkException ( "Key is invalid " , e ) ; } return new String ( Base64 . encodeBase64 ( mac . doFinal ( baseString . getBytes ( Charsets . UTF_8 ) ) ) , Charsets . UTF_8 ) ; }
Generate an HMAC from the context ts parameter .
203
11
137,621
public static HawkWwwAuthenticateContextBuilder_A tsAndTsm ( long l , String tsm ) { return new HawkWwwAuthenticateContextBuilder ( ) . ts ( l ) . tsm ( tsm ) ; }
Create a new HawkWwwAuthenticateContextBuilder_A initialized with timestamp and timestamp hmac .
49
20
137,622
public int addAttribute ( String attrId ) { if ( attributeMapper . containsKey ( attrId ) ) { return attributeMapper . get ( attrId ) ; // attribute-id has existed } attributeMapper . put ( attrId , varIdCounter ) ; varIdCounter ++ ; return attributeMapper . get ( attrId ) ; }
Add a new attribute - id to the map return the variable id . If the attribute existed throws exception
78
20
137,623
public String getAttributeId ( int variableId ) throws MIDDParsingException { if ( ! attributeMapper . containsValue ( variableId ) ) { throw new MIDDParsingException ( "Variable identifier '" + variableId + "' not found" ) ; } for ( String attrId : attributeMapper . keySet ( ) ) { if ( attributeMapper . get ( attrId ) == variableId ) { return attrId ; } } throw new MIDDParsingException ( "Variable identifier '" + variableId + "' not found" ) ; }
Return the attribute identifier from the variable - id
121
9
137,624
public void write ( MessageBodyWriterContext context ) throws IOException , WebApplicationException { Object encoding = context . getHeaders ( ) . getFirst ( HttpHeaders . CONTENT_ENCODING ) ; if ( encoding != null && encoding . toString ( ) . equalsIgnoreCase ( "lzf" ) ) { OutputStream old = context . getOutputStream ( ) ; // constructor writes to underlying OS causing headers to be written. CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream ( old , null ) ; // Any content length set will be obsolete context . getHeaders ( ) . remove ( "Content-Length" ) ; context . setOutputStream ( lzfOutputStream ) ; try { context . proceed ( ) ; } finally { if ( lzfOutputStream . getLzf ( ) != null ) lzfOutputStream . getLzf ( ) . flush ( ) ; context . setOutputStream ( old ) ; } return ; } else { context . proceed ( ) ; } }
Grab the outgoing message if encoding is set to LZF then wrap the OutputStream in an LZF OutputStream before sending it on its merry way compressing all the time .
230
37
137,625
public AuthorizationHeader createAuthorizationHeader ( ) throws HawkException { String hmac = this . generateHmac ( ) ; AuthorizationBuilder headerBuilder = AuthorizationHeader . authorization ( ) . ts ( ts ) . nonce ( nonce ) . id ( getId ( ) ) . mac ( hmac ) ; if ( hasExt ( ) ) { headerBuilder . ext ( getExt ( ) ) ; } if ( hasApp ( ) ) { headerBuilder . app ( getApp ( ) ) ; if ( hasDlg ( ) ) { headerBuilder . dlg ( getDlg ( ) ) ; } } if ( hasHash ( ) ) { headerBuilder . hash ( getHash ( ) ) ; } return headerBuilder . build ( ) ; }
Create an Authorization header from this HawkContext .
158
9
137,626
public boolean verifyServerAuthorizationMatches ( AuthorizationHeader header ) { if ( ! Util . fixedTimeEqual ( header . getId ( ) , this . getId ( ) ) ) { return false ; } if ( header . getTs ( ) != this . getTs ( ) ) { return false ; } if ( ! Util . fixedTimeEqual ( header . getNonce ( ) , this . getNonce ( ) ) ) { return false ; } return true ; }
Verify that a given header matches a HawkContext .
103
11
137,627
public boolean isValidMac ( String hmac ) throws HawkException { String this_hmac = this . generateHmac ( ) ; return Util . fixedTimeEqual ( this_hmac , hmac ) ; }
Check whether a given HMAC value matches the HMAC for this HawkContext .
47
16
137,628
protected String getBaseString ( ) { StringBuilder sb = new StringBuilder ( HAWK_HEADER_PREFIX ) . append ( SLF ) ; sb . append ( getTs ( ) ) . append ( SLF ) ; sb . append ( getNonce ( ) ) . append ( SLF ) ; sb . append ( getMethod ( ) ) . append ( SLF ) ; sb . append ( getPath ( ) ) . append ( SLF ) ; sb . append ( getHost ( ) ) . append ( SLF ) ; sb . append ( getPort ( ) ) . append ( SLF ) ; sb . append ( hasHash ( ) ? getHash ( ) : "" ) . append ( SLF ) ; sb . append ( hasExt ( ) ? getExt ( ) : "" ) . append ( SLF ) ; // FIXME: escaping of stuff in ext to a single line. // See https://github.com/algermissen/hawkj/issues/1 if ( hasApp ( ) ) { sb . append ( getApp ( ) ) . append ( SLF ) ; sb . append ( hasDlg ( ) ? getDlg ( ) : "" ) . append ( SLF ) ; } return sb . toString ( ) ; // FIXME - code for ext quote escaping // https://github.com/algermissen/hawkj/issues/1 // if (options.ext) { // normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); // } // // normalized += '\n'; // // // escapeHeaderAttribute: function (attribute) { // // return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // }, }
Generate base string for HMAC generation .
391
9
137,629
public static HawkContextBuilder_B request ( String method , String path , String host , int port ) { return new HawkContextBuilder ( ) . method ( method ) . path ( path ) . host ( host ) . port ( port ) ; }
Create a new RequestBuilder_A initialized with request data .
51
12
137,630
@ Override public byte [ ] decompress ( InputStream strm ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; LZFInputStream in = new LZFInputStream ( strm ) ; byte [ ] buffer = new byte [ 8192 ] ; int len = 0 ; //Decode and copy to output while ( ( len = in . read ( buffer ) ) != - 1 ) { baos . write ( buffer , 0 , len ) ; } return baos . toByteArray ( ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "IOException reading input stream" , ioe ) ; } }
Attempts to decompress an LZF stream
143
9
137,631
public static GregorianCalendar getRandomDate ( long seed ) { GregorianCalendar gc = new GregorianCalendar ( ) ; Random rand = new Random ( seed ) ; gc . set ( GregorianCalendar . YEAR , 1900 + rand . nextInt ( 120 ) ) ; //Between 1900 & 2020 gc . set ( GregorianCalendar . DAY_OF_YEAR , rand . nextInt ( 364 ) + 1 ) ; //Day of year return gc ; }
Gets a random date in the last 100 years
103
10
137,632
public void setCookies ( List < HttpCookie > cookies ) { Map < String , HttpCookie > map = new HashMap < String , HttpCookie > ( ) ; for ( HttpCookie cookie : cookies ) { map . put ( cookie . getName ( ) , cookie ) ; } this . cookies = map ; }
Set the request s cookies
74
5
137,633
private static < T extends Comparable < T > > List < Interval < T > > combine ( Partition < T > p1 , Partition < T > p2 ) throws MIDDException { Set < EndPoint < T >> boundSet = new HashSet < EndPoint < T > > ( ) ; //collect all bounds and remove duplicated items for ( Interval < T > interval : p1 . getIntervals ( ) ) { boundSet . add ( interval . getLowerBound ( ) ) ; boundSet . add ( interval . getUpperBound ( ) ) ; } for ( Interval < T > interval : p2 . getIntervals ( ) ) { boundSet . add ( interval . getLowerBound ( ) ) ; boundSet . add ( interval . getUpperBound ( ) ) ; } //sorting the bounds List < EndPoint < T > > sortedBounds = new ArrayList < EndPoint < T > > ( boundSet ) ; Collections . sort ( sortedBounds ) ; List < Interval < T > > tempPartition = new ArrayList < Interval < T > > ( ) ; // Generate new intervals for ( int i = 0 ; i < sortedBounds . size ( ) - 1 ; i ++ ) { EndPoint < T > lowBound = sortedBounds . get ( i ) ; EndPoint < T > upBound = sortedBounds . get ( i + 1 ) ; tempPartition . add ( new Interval < T > ( lowBound ) ) ; tempPartition . add ( new Interval < T > ( lowBound , upBound ) ) ; } // add the last end-point if ( sortedBounds . size ( ) > 0 ) { EndPoint < T > lastBound = sortedBounds . get ( sortedBounds . size ( ) - 1 ) ; tempPartition . add ( new Interval < T > ( lastBound ) ) ; } else { log . warn ( "empty sortedBound" ) ; } return tempPartition ; }
Create a list of intervals from two partitions
426
8
137,634
public List < Interval < T > > complement ( final Interval < T > op ) throws MIDDException { final boolean disJoined = ( this . lowerBound . compareTo ( op . upperBound ) >= 0 ) || ( this . upperBound . compareTo ( op . lowerBound ) <= 0 ) ; if ( disJoined ) { Interval < T > newInterval = new Interval <> ( this . lowerBound , this . upperBound ) ; final boolean isLowerClosed ; if ( this . lowerBound . compareTo ( op . upperBound ) == 0 ) { isLowerClosed = this . lowerBoundClosed && ! op . upperBoundClosed ; } else { isLowerClosed = this . lowerBoundClosed ; } newInterval . closeLeft ( isLowerClosed ) ; final boolean isUpperClosed ; if ( this . upperBound . compareTo ( op . lowerBound ) == 0 ) { isUpperClosed = this . upperBoundClosed && ! op . upperBoundClosed ; } else { isUpperClosed = this . upperBoundClosed ; } newInterval . closeRight ( isUpperClosed ) ; // return empty if new interval is invalid if ( ! newInterval . validate ( ) ) { return ImmutableList . of ( ) ; } return ImmutableList . of ( newInterval ) ; } else { final Interval < T > interval1 = new Interval <> ( this . lowerBound , op . lowerBound ) ; final Interval < T > interval2 = new Interval <> ( op . upperBound , this . upperBound ) ; interval1 . closeLeft ( ! interval1 . isLowerInfinite ( ) && this . lowerBoundClosed ) ; interval1 . closeRight ( ! interval1 . isUpperInfinite ( ) && ! op . lowerBoundClosed ) ; interval2 . closeLeft ( ! interval2 . isLowerInfinite ( ) && ! op . upperBoundClosed ) ; interval2 . closeRight ( ! interval2 . isUpperInfinite ( ) && this . upperBoundClosed ) ; final List < Interval < T > > result = new ArrayList <> ( ) ; if ( interval1 . validate ( ) ) { result . add ( interval1 ) ; } if ( interval2 . validate ( ) ) { result . add ( interval2 ) ; } return ImmutableList . copyOf ( result ) ; } }
Return the complement section of the interval .
522
8
137,635
public boolean contains ( final Interval < T > i ) { int compareLow , compareUp ; compareLow = this . lowerBound . compareTo ( i . lowerBound ) ; compareUp = this . upperBound . compareTo ( i . upperBound ) ; if ( compareLow < 0 ) { // check the upper bound if ( compareUp > 0 ) { return true ; } else if ( ( compareUp == 0 ) && ( this . upperBoundClosed || ! i . upperBoundClosed ) ) { return true ; } } else if ( compareLow == 0 ) { if ( this . lowerBoundClosed || ! i . lowerBoundClosed ) { // lowerbound satisfied { // check upperbound if ( compareUp > 0 ) { return true ; } else if ( ( compareUp == 0 ) && ( this . upperBoundClosed || ! i . upperBoundClosed ) ) { return true ; } } } } return false ; }
Return true if interval in the argument is the subset of the current interval .
199
15
137,636
public boolean hasValue ( final T value ) throws MIDDException { //special processing when missing attribute if ( value == null ) { return this . isLowerInfinite ( ) || this . isUpperInfinite ( ) ; } EndPoint < T > epValue = new EndPoint <> ( value ) ; int compareLow = this . lowerBound . compareTo ( epValue ) ; int compareUp = this . upperBound . compareTo ( epValue ) ; if ( ( compareLow < 0 || ( compareLow == 0 && this . lowerBoundClosed ) ) && ( compareUp > 0 || ( compareUp == 0 && this . upperBoundClosed ) ) ) { return true ; } return false ; }
Check if the value is presenting in the interval .
150
10
137,637
public static < T extends Comparable < T > > Interval < T > of ( final T v ) throws MIDDException { return new Interval ( v ) ; }
Create an interval with a single endpoint
36
7
137,638
public void logLocalCommands ( final List < Command > commands ) { if ( singleValue == null ) { return ; } for ( final Command command : commands ) { if ( command instanceof SetPropertyValue ) { singleValue . logLocalCommand ( ( SetPropertyValue ) command ) ; } else if ( command instanceof ListCommand ) { lists . logLocalCommand ( ( ListCommand ) command ) ; } } }
Logs a list of locally generated commands that is sent to the server .
87
15
137,639
public void setModel ( SoundCloudTrack track ) { mModel = track ; if ( mModel != null ) { Picasso . with ( getContext ( ) ) . load ( SoundCloudArtworkHelper . getArtworkUrl ( mModel , SoundCloudArtworkHelper . XLARGE ) ) . placeholder ( R . color . grey_light ) . fit ( ) . centerInside ( ) . into ( mArtwork ) ; mArtist . setText ( mModel . getArtist ( ) ) ; mTitle . setText ( mModel . getTitle ( ) ) ; long min = mModel . getDurationInMilli ( ) / 60000 ; long sec = ( mModel . getDurationInMilli ( ) % 60000 ) / 1000 ; mDuration . setText ( String . format ( getResources ( ) . getString ( R . string . duration ) , min , sec ) ) ; } }
Set the track which must be displayed .
191
8
137,640
private void setTrack ( SoundCloudTrack track ) { if ( track == null ) { mTitle . setText ( "" ) ; mArtwork . setImageDrawable ( null ) ; mPlayPause . setImageResource ( R . drawable . ic_play_white ) ; mSeekBar . setProgress ( 0 ) ; String none = String . format ( getResources ( ) . getString ( R . string . playback_view_time ) , 0 , 0 ) ; mCurrentTime . setText ( none ) ; mDuration . setText ( none ) ; } else { Picasso . with ( getContext ( ) ) . load ( SoundCloudArtworkHelper . getArtworkUrl ( track , SoundCloudArtworkHelper . XLARGE ) ) . fit ( ) . centerCrop ( ) . placeholder ( R . color . grey ) . into ( mArtwork ) ; mTitle . setText ( Html . fromHtml ( String . format ( getResources ( ) . getString ( R . string . playback_view_title ) , track . getArtist ( ) , track . getTitle ( ) ) ) ) ; mPlayPause . setImageResource ( R . drawable . ic_pause_white ) ; if ( getTranslationY ( ) != 0 ) { this . animate ( ) . translationY ( 0 ) ; } mSeekBar . setMax ( ( ( int ) track . getDurationInMilli ( ) ) ) ; String none = String . format ( getResources ( ) . getString ( R . string . playback_view_time ) , 0 , 0 ) ; int [ ] secondMinute = getSecondMinutes ( track . getDurationInMilli ( ) ) ; String duration = String . format ( getResources ( ) . getString ( R . string . playback_view_time ) , secondMinute [ 0 ] , secondMinute [ 1 ] ) ; mCurrentTime . setText ( none ) ; mDuration . setText ( duration ) ; } }
Set the current played track .
424
6
137,641
public String getFinalReason ( Path path ) { StringBuilder sb = new StringBuilder ( path + " cannot be modified; " ) ; StringBuilder finalPath = new StringBuilder ( "/" ) ; // Step through the nodes based on the given path. If any intermediate // nodes are marked as final, we can just return true. Node currentNode = root ; for ( Term t : path . getTerms ( ) ) { finalPath . append ( t . toString ( ) ) ; Node nextNode = currentNode . getChild ( t ) ; if ( nextNode == null ) { return null ; } else if ( nextNode . isFinal ( ) ) { sb . append ( finalPath . toString ( ) + " is marked as final" ) ; return sb . toString ( ) ; } finalPath . append ( "/" ) ; currentNode = nextNode ; } // Strip off the last slash. It is not needed. finalPath . deleteCharAt ( finalPath . length ( ) - 1 ) ; // Either the path itself is final or a descendant. if ( currentNode . isFinal ( ) ) { sb . append ( finalPath . toString ( ) + " is marked as final" ) ; } else if ( currentNode . hasChild ( ) ) { sb . append ( finalPath . toString ( ) + currentNode . getFinalDescendantPath ( ) + " is marked as final" ) ; return sb . toString ( ) ; } else { return null ; } return null ; }
Return a String with a message indicating why the given path is final .
323
14
137,642
public void setFinal ( Path path ) { // Step through the nodes creating any nodes which don't exist. Node currentNode = root ; for ( Term t : path . getTerms ( ) ) { Node nextNode = currentNode . getChild ( t ) ; if ( nextNode == null ) { nextNode = currentNode . newChild ( t ) ; } currentNode = nextNode ; } // The current node is now the one corresponding to the last term in the // path. Set this as final. currentNode . setFinal ( ) ; }
Mark the given Path as being final .
115
8
137,643
public List < String > toList ( ) { List < String > list = new LinkedList < String > ( ) ; if ( authority != null ) { list . add ( authority ) ; } for ( Term t : terms ) { list . add ( t . toString ( ) ) ; } return list ; }
This method returns the Path as an unmodifiable list of the terms comprising the Path .
66
18
137,644
public int compareTo ( Path o ) { // Sanity check. if ( o == null ) { throw new NullPointerException ( ) ; } // If these are not the same type, do the simple comparison. if ( this . type != o . type ) { return type . compareTo ( o . type ) ; } // Same type of path, so check first the number of terms. If not equal, // then it is easy to decide the order. (Longer paths come before // shorter ones.) int mySize = this . terms . length ; int otherSize = o . terms . length ; if ( mySize != otherSize ) { return ( mySize < otherSize ) ? 1 : - 1 ; } // Ok, the hard case, the two paths are of the same type and have the // same number of terms. for ( int i = 0 ; i < mySize ; i ++ ) { Term myTerm = this . terms [ i ] ; Term otherTerm = o . terms [ i ] ; int comparison = myTerm . compareTo ( otherTerm ) ; if ( comparison != 0 ) { return comparison ; } } // We've gone through all of the checks, so the two paths must be equal; // return zero. return 0 ; }
The default ordering for paths is such that it will produce a post - traversal ordering . All relative paths will be before absolute paths which are before external paths .
263
32
137,645
private void sendAction ( Context context , String action ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( action ) ; LocalBroadcastManager . getInstance ( context ) . sendBroadcast ( intent ) ; }
Propagate lock screen event to the player .
54
9
137,646
public void updateMemoryInfo ( ) { MemoryMXBean meminfo = ManagementFactory . getMemoryMXBean ( ) ; MemoryUsage usage = meminfo . getHeapMemoryUsage ( ) ; long _heapUsed = usage . getUsed ( ) ; updateMaximum ( heapUsed , _heapUsed ) ; updateMaximum ( heapTotal , usage . getMax ( ) ) ; usage = meminfo . getNonHeapMemoryUsage ( ) ; updateMaximum ( nonHeapUsed , usage . getUsed ( ) ) ; updateMaximum ( nonHeapTotal , usage . getMax ( ) ) ; // Log the memory usage if requested. Check the log level before logging // to minimize object creation overheads during preparation of the call // parameters. if ( memoryLogger . isLoggable ( Level . INFO ) ) { memoryLogger . log ( Level . INFO , "MEM" , new Object [ ] { _heapUsed } ) ; } }
Take a snapshot of the current memory usage of the JVM and update the high - water marks .
201
20
137,647
private static void updateMaximum ( AtomicLong counter , long currentValue ) { boolean unset = true ; long counterValue = counter . get ( ) ; while ( ( currentValue > counterValue ) && unset ) { unset = ! counter . compareAndSet ( counterValue , currentValue ) ; counterValue = counter . get ( ) ; } }
Compares the current value against the value of the counter and updates the counter if the current value is greater . This is done in a way to ensure that no updates are lost .
73
36
137,648
public String getResults ( long totalErrors ) { Object [ ] info = { fileCount , doneTasks . get ( COMPILED ) . get ( ) , startedTasks . get ( COMPILED ) . get ( ) , doneTasks . get ( ANNOTATION ) . get ( ) , startedTasks . get ( ANNOTATION ) . get ( ) , doneTasks . get ( XML ) . get ( ) , startedTasks . get ( XML ) . get ( ) , doneTasks . get ( DEP ) . get ( ) , startedTasks . get ( DEP ) . get ( ) , totalErrors , buildTime , convertToMB ( heapUsed . get ( ) ) , convertToMB ( heapTotal . get ( ) ) , convertToMB ( nonHeapUsed . get ( ) ) , convertToMB ( nonHeapTotal . get ( ) ) } ; return MessageUtils . format ( MSG_STATISTICS_TEMPLATE , info ) ; }
Generates a terse String representation of the statistics .
216
11
137,649
@ Override public void onConnect ( final Object newClient ) { meta . commandsForDomainModel ( new CommandsForDomainModelCallback ( ) { @ Override public void commandsReady ( final List < Command > commands ) { networkLayer . onConnectFinished ( newClient ) ; networkLayer . send ( commands , newClient ) ; } } ) ; // TODO networkLayer onConnectFinished(); javadoc that networklayer should then enable sendToAll for new // client. }
Sends the current domain model to a newly connecting client .
102
12
137,650
@ Override public void onClientConnectionError ( final Object client , final SynchronizeFXException e ) { serverCallback . onClientConnectionError ( client , e ) ; }
Logs the unexpected disconnection of an client .
37
10
137,651
private void removeDefinedFields ( Context context , List < Term > undefinedFields ) throws ValidationException { // Loop through all of the required and optional fields removing each // from the list of undefined fields. for ( Term term : reqKeys ) { undefinedFields . remove ( term ) ; } for ( Term term : optKeys ) { undefinedFields . remove ( term ) ; } // Now we must apply this method to any included types as well. for ( String s : includes ) { try { // Pull out the type and base type of the included type. // Ensure that the base type is a record definition. FullType fullType = context . getFullType ( s ) ; BaseType baseType = fullType . getBaseType ( ) ; RecordType recordType = ( RecordType ) baseType ; recordType . removeDefinedFields ( context , undefinedFields ) ; } catch ( ClassCastException cce ) { // Should have been checked when the type was defined. throw CompilerError . create ( MSG_NONRECORD_TYPE_REF , s ) ; } catch ( NullPointerException npe ) { // Should have been checked when the type was defined. throw CompilerError . create ( MSG_NONEXISTANT_REFERENCED_TYPE , s ) ; } } }
This method will loop through all of the fields defined in this record and remove them from the given list . This is used in the validation of the fields .
277
31
137,652
public static void activateLoggers ( String loggerList ) { // Create an empty set. This will contain the list of all of the loggers // to activate. (Note that NONE may be a logger; in this case, all // logging will be deactivated.) EnumSet < LoggingType > flags = EnumSet . noneOf ( LoggingType . class ) ; // Split on commas and remove white space. for ( String name : loggerList . split ( "\\s*,\\s*" ) ) { try { flags . add ( LoggingType . valueOf ( name . trim ( ) . toUpperCase ( ) ) ) ; } catch ( IllegalArgumentException consumed ) { } } // Loop over the flags, enabling each one. for ( LoggingType type : flags ) { type . activate ( ) ; } }
Enable the given types of logging . Note that NONE will take precedence over active logging flags and turn all logging off . Illegal logging values will be silently ignored .
178
32
137,653
private static void initializeLogger ( Logger logger ) { // Do NOT send any logging information to parent loggers. topLogger . setUseParentHandlers ( false ) ; // Remove any existing handlers. for ( Handler handler : topLogger . getHandlers ( ) ) { try { topLogger . removeHandler ( handler ) ; } catch ( SecurityException consumed ) { System . err . println ( "WARNING: missing 'LoggingPermission(\"control\")' permission" ) ; } } }
Remove all handlers associated with the given logger .
107
9
137,654
public synchronized static void setLogFile ( File logfile ) { // Add a file logger that will use the compiler's customized // formatter. This formatter provides a terse representation of the // logging information. try { if ( logfile != null ) { String absolutePath = logfile . getAbsolutePath ( ) ; if ( initializedLogFile == null || ( ! initializedLogFile . equals ( absolutePath ) ) ) { // Remove any existing handlers. initializeLogger ( topLogger ) ; // Set the new handler. FileHandler handler = new FileHandler ( absolutePath ) ; handler . setFormatter ( new LogFormatter ( ) ) ; topLogger . addHandler ( handler ) ; // Make sure we save the name of the log file to avoid // inappropriate reinitialization. initializedLogFile = absolutePath ; } } } catch ( IOException consumed ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "WARNING: unable to open logging file handler\n" ) ; sb . append ( "WARNING: logfile = '" + logfile . getAbsolutePath ( ) + "'" ) ; sb . append ( "\nWARNING: message = " ) ; sb . append ( consumed . getMessage ( ) ) ; System . err . println ( sb . toString ( ) ) ; } }
Define the file that will contain the logging information . If this is called with null then the log file will be removed . The log file and logging parameters are global to the JVM . Interference is possible between multiple threads .
284
46
137,655
public void put ( String url , String result ) { if ( TextUtils . isEmpty ( url ) ) { return ; } ContentValues contentValues = new ContentValues ( ) ; contentValues . put ( OfflinerDBHelper . REQUEST_RESULT , result ) ; contentValues . put ( OfflinerDBHelper . REQUEST_URL , url ) ; contentValues . put ( OfflinerDBHelper . REQUEST_TIMESTAMP , Calendar . getInstance ( ) . getTime ( ) . getTime ( ) ) ; this . startQuery ( TOKEN_CHECK_SAVED_STATUS , contentValues , getUri ( OfflinerDBHelper . TABLE_CACHE ) , OfflinerDBHelper . PARAMS_CACHE , OfflinerDBHelper . REQUEST_URL + " = '" + url + "'" , null , null ) ; }
Save a result for offline access .
185
7
137,656
public String get ( Context context , String url ) { final Cursor cursor = context . getContentResolver ( ) . query ( getUri ( OfflinerDBHelper . TABLE_CACHE ) , OfflinerDBHelper . PARAMS_CACHE , OfflinerDBHelper . REQUEST_URL + " = '" + url + "'" , null , null ) ; String result = null ; if ( cursor != null ) { if ( cursor . getCount ( ) != 0 ) { cursor . moveToFirst ( ) ; result = cursor . getString ( cursor . getColumnIndex ( OfflinerDBHelper . REQUEST_RESULT ) ) ; } cursor . close ( ) ; } return result ; }
Retrieve a value saved for offline access .
150
9
137,657
private Uri getUri ( String string ) { return Uri . parse ( OfflinerProvider . CONTENT + OfflinerProvider . getAuthority ( mPackageName ) + OfflinerProvider . SLASH + string ) ; }
Retrieve the URI with Cache database provider authority .
46
10
137,658
public void setPlaybackState ( int state ) { if ( sHasRemoteControlAPIs ) { try { sRCCSetPlayStateMethod . invoke ( mActualRemoteControlClient , state ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }
Sets the current playback state .
61
7
137,659
public void setTransportControlFlags ( int transportControlFlags ) { if ( sHasRemoteControlAPIs ) { try { sRCCSetTransportControlFlags . invoke ( mActualRemoteControlClient , transportControlFlags ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }
Sets the flags for the media transport control buttons that this client supports .
67
15
137,660
@ SuppressWarnings ( "deprecation" ) public void onDestroy ( ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { mRemoteControlClientCompat . setPlaybackState ( RemoteControlClient . PLAYSTATE_STOPPED ) ; mAudioManager . unregisterMediaButtonEventReceiver ( mMediaButtonReceiverComponent ) ; mLocalBroadcastManager . unregisterReceiver ( mLockScreenReceiver ) ; } mMediaSession . release ( ) ; }
Should be called to released the internal component .
118
9
137,661
@ SuppressWarnings ( "deprecation" ) public void setMetaData ( SoundCloudTrack track , Bitmap artwork ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { // set meta data on the lock screen for pre lollipop. mRemoteControlClientCompat . setPlaybackState ( RemoteControlClient . PLAYSTATE_PLAYING ) ; RemoteControlClientCompat . MetadataEditorCompat mediaEditorCompat = mRemoteControlClientCompat . editMetadata ( true ) . putString ( MediaMetadataRetriever . METADATA_KEY_TITLE , track . getTitle ( ) ) . putString ( MediaMetadataRetriever . METADATA_KEY_ARTIST , track . getArtist ( ) ) ; if ( artwork != null ) { mediaEditorCompat . putBitmap ( RemoteControlClientCompat . MetadataEditorCompat . METADATA_KEY_ARTWORK , artwork ) ; } mediaEditorCompat . apply ( ) ; } // set meta data to the media session. MediaMetadataCompat . Builder metadataCompatBuilder = new MediaMetadataCompat . Builder ( ) . putString ( MediaMetadataCompat . METADATA_KEY_TITLE , track . getTitle ( ) ) . putString ( MediaMetadataCompat . METADATA_KEY_ARTIST , track . getArtist ( ) ) ; if ( artwork != null ) { metadataCompatBuilder . putBitmap ( MediaMetadataCompat . METADATA_KEY_ART , artwork ) ; } mMediaSession . setMetadata ( metadataCompatBuilder . build ( ) ) ; setMediaSessionCompatPlaybackState ( PlaybackStateCompat . STATE_PLAYING ) ; }
Update meta data used by the remote control client and the media session .
366
14
137,662
private void setRemoteControlClientPlaybackState ( int state ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { mRemoteControlClientCompat . setPlaybackState ( state ) ; } }
Propagate playback state to the remote control client on the lock screen .
56
14
137,663
private void setMediaSessionCompatPlaybackState ( int state ) { mStateBuilder . setState ( state , PlaybackStateCompat . PLAYBACK_POSITION_UNKNOWN , 1.0f ) ; mMediaSession . setPlaybackState ( mStateBuilder . build ( ) ) ; }
Propagate playback state to the media session compat .
62
10
137,664
private void initPlaybackStateBuilder ( ) { mStateBuilder = new PlaybackStateCompat . Builder ( ) ; mStateBuilder . setActions ( PlaybackStateCompat . ACTION_PLAY | PlaybackStateCompat . ACTION_PAUSE | PlaybackStateCompat . ACTION_PLAY_PAUSE | PlaybackStateCompat . ACTION_SKIP_TO_NEXT | PlaybackStateCompat . ACTION_SKIP_TO_PREVIOUS ) ; }
Initialize the playback state builder with supported actions .
96
10
137,665
@ SuppressWarnings ( "deprecation" ) private void initLockScreenRemoteControlClient ( Context context ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { mMediaButtonReceiverComponent = new ComponentName ( mRuntimePackageName , MediaSessionReceiver . class . getName ( ) ) ; mAudioManager . registerMediaButtonEventReceiver ( mMediaButtonReceiverComponent ) ; if ( mRemoteControlClientCompat == null ) { Intent remoteControlIntent = new Intent ( Intent . ACTION_MEDIA_BUTTON ) ; remoteControlIntent . setComponent ( mMediaButtonReceiverComponent ) ; mRemoteControlClientCompat = new RemoteControlClientCompat ( PendingIntent . getBroadcast ( context , 0 , remoteControlIntent , 0 ) ) ; RemoteControlHelper . registerRemoteControlClient ( mAudioManager , mRemoteControlClientCompat ) ; } mRemoteControlClientCompat . setPlaybackState ( RemoteControlClient . PLAYSTATE_PLAYING ) ; mRemoteControlClientCompat . setTransportControlFlags ( RemoteControlClient . FLAG_KEY_MEDIA_PLAY | RemoteControlClient . FLAG_KEY_MEDIA_PAUSE | RemoteControlClient . FLAG_KEY_MEDIA_NEXT | RemoteControlClient . FLAG_KEY_MEDIA_STOP | RemoteControlClient . FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient . FLAG_KEY_MEDIA_PLAY_PAUSE ) ; registerLockScreenReceiver ( context ) ; } }
Initialize the remote control client on the lock screen .
340
11
137,666
private void registerLockScreenReceiver ( Context context ) { mLockScreenReceiver = new LockScreenReceiver ( ) ; IntentFilter intentFilter = new IntentFilter ( ) ; intentFilter . addAction ( ACTION_TOGGLE_PLAYBACK ) ; intentFilter . addAction ( ACTION_NEXT_TRACK ) ; intentFilter . addAction ( ACTION_PREVIOUS_TRACK ) ; mLocalBroadcastManager = LocalBroadcastManager . getInstance ( context ) ; mLocalBroadcastManager . registerReceiver ( mLockScreenReceiver , intentFilter ) ; }
Register the lock screen receiver used to catch lock screen media buttons events .
123
14
137,667
public void repairLocalCommandsVersion ( final Queue < ListCommand > localCommands , final ListCommand originalRemoteCommand ) { localCommands . add ( repairCommand ( localCommands . poll ( ) , originalRemoteCommand . getListVersionChange ( ) . getToVersion ( ) , randomUUID ( ) ) ) ; final int count = localCommands . size ( ) ; for ( int i = 1 ; i < count ; i ++ ) { localCommands . add ( repairCommand ( localCommands . poll ( ) , randomUUID ( ) , randomUUID ( ) ) ) ; } }
Updates the versions of repaired local commands that should be resent to the server so that they are based on the version the original remote command produced .
129
29
137,668
public List < ? extends ListCommand > repairRemoteCommandVersion ( final List < ? extends ListCommand > indexRepairedRemoteCommands , final List < ListCommand > versionRepairedLocalCommands ) { final int commandCount = indexRepairedRemoteCommands . size ( ) ; final ListCommand lastLocalCommand = versionRepairedLocalCommands . get ( versionRepairedLocalCommands . size ( ) - 1 ) ; if ( commandCount == 0 ) { return asList ( new RemoveFromList ( lastLocalCommand . getListId ( ) , new ListVersionChange ( randomUUID ( ) , lastLocalCommand . getListVersionChange ( ) . getToVersion ( ) ) , 0 , 0 ) ) ; } final List < ListCommand > repaired = new ArrayList < ListCommand > ( commandCount ) ; for ( int i = 0 ; i < commandCount - 1 ; i ++ ) { repaired . add ( indexRepairedRemoteCommands . get ( i ) ) ; } repaired . add ( repairCommand ( indexRepairedRemoteCommands . get ( commandCount - 1 ) , randomUUID ( ) , lastLocalCommand . getListVersionChange ( ) . getToVersion ( ) ) ) ; return repaired ; }
Updates the version of the remote commands that should be executed locally to ensure that the local list version equals the version that is resent to the server when they are executed .
258
34
137,669
private void checkRangeValues ( long minimum , long maximum ) { if ( minimum > maximum ) { throw EvaluationException . create ( MSG_MIN_MUST_BE_LESS_OR_EQUAL_TO_MAX , minimum , maximum ) ; } }
Checks whether the range values are valid . Specifically whether the minimum is less than or equal to the maximum . This will throw an EvaluationException if any problems are found .
54
34
137,670
@ Override public void shutdown ( ) { synchronized ( connections ) { parent . channelCloses ( this ) ; for ( final MessageInbound connection : connections ) { try { connection . getWsOutbound ( ) . close ( 0 , null ) ; } catch ( final IOException e ) { LOG . error ( "Connection [" + connection . toString ( ) + "] can't be closed." , e ) ; } finally { final ExecutorService executorService = connectionThreads . get ( connection ) ; if ( executorService != null ) { executorService . shutdown ( ) ; } connectionThreads . remove ( connection ) ; } } connections . clear ( ) ; } callback = null ; }
Disconnects all clients and makes the servlet refuse new connections .
148
14
137,671
public List < Command > setPropertyValue ( final UUID propertyId , final Object value ) throws SynchronizeFXException { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { setPropertyValue ( propertyId , value , state ) ; } } , true ) ; return state . commands ; }
Creates the commands necessary to set a new value for a property .
77
14
137,672
public List < Command > addToList ( final UUID listId , final int position , final Object value , final int newSize ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { addToList ( listId , position , value , newSize , state ) ; } } , true ) ; return state . commands ; }
Creates the list with commands necessary for an add to list action .
85
14
137,673
public List < Command > addToSet ( final UUID setId , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { addToSet ( setId , value , state ) ; } } , true ) ; return state . commands ; }
Creates the list with commands necessary for an add to set action .
71
14
137,674
public List < Command > putToMap ( final UUID mapId , final Object key , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { putToMap ( mapId , key , value , state ) ; } } , true ) ; return state . commands ; }
Creates the list with commands necessary to put a mapping into a map .
77
15
137,675
public List < Command > removeFromList ( final UUID listId , final int startPosition , final int removeCount ) { final ListVersionChange change = increaseListVersion ( listId ) ; final RemoveFromList msg = new RemoveFromList ( listId , change , startPosition , removeCount ) ; final List < Command > commands = new ArrayList <> ( 1 ) ; commands . add ( msg ) ; return commands ; }
Creates the list with commands necessary to remove a object from a list .
90
15
137,676
public List < Command > removeFromMap ( final UUID mapId , final Object key ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { createObservableObject ( key , state ) ; } } , false ) ; final boolean keyIsObservableObject = state . lastObjectWasObservable ; final RemoveFromMap msg = new RemoveFromMap ( ) ; msg . setMapId ( mapId ) ; msg . setKey ( valueMapper . map ( key , keyIsObservableObject ) ) ; state . commands . add ( state . commands . size ( ) - 1 , msg ) ; return state . commands ; }
Creates the list with command necessary to remove a mapping from a map .
152
15
137,677
public List < Command > removeFromSet ( final UUID setId , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { createObservableObject ( value , state ) ; } } , false ) ; final boolean keyIsObservableObject = state . lastObjectWasObservable ; final RemoveFromSet msg = new RemoveFromSet ( ) ; msg . setSetId ( setId ) ; msg . setValue ( valueMapper . map ( value , keyIsObservableObject ) ) ; state . commands . add ( state . commands . size ( ) - 1 , msg ) ; return state . commands ; }
Creates the list with commands necessary to remove a object from a set .
152
15
137,678
public List < Command > replaceInList ( final UUID listId , final int position , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { @ Override public void invoke ( final State state ) { final boolean isObservableObject = createObservableObject ( value , state ) ; final ListVersionChange versionChange = increaseListVersion ( listId ) ; final ReplaceInList replaceInList = new ReplaceInList ( listId , versionChange , valueMapper . map ( value , isObservableObject ) , position ) ; state . commands . add ( replaceInList ) ; } } , true ) ; return state . commands ; }
Creates the list of commands necessary to replace an object in a list .
145
15
137,679
static void replaceHeredocStrings ( ASTTemplate tnode , List < StringProperty > strings ) { // Only something to do if there were heredoc strings defined. if ( strings . size ( ) > 0 ) { processHeredocStrings ( tnode , strings ) ; } }
A utility to replace HEREDOC operations with the associated StringProperty operations . This must be done at the end of the template processing to be sure that all heredoc strings have been captured .
62
39
137,680
static void processSingleQuotedString ( StringBuilder sb ) { // Sanity checking. Make sure input string has at least two characters // and that the first and last are single quotes. assert ( sb . length ( ) >= 2 ) ; assert ( sb . charAt ( 0 ) == ' ' && sb . charAt ( sb . length ( ) - 1 ) == ' ' ) ; // Remove the starting and ending quotes. sb . deleteCharAt ( sb . length ( ) - 1 ) ; sb . deleteCharAt ( 0 ) ; // Loop through the string and replace any doubled apostrophes with // a single apostrophe. (Really just delete the second apostrophe.) int i = sb . indexOf ( "''" , 0 ) + 1 ; while ( i > 0 ) { sb . deleteCharAt ( i ) ; i = sb . indexOf ( "''" , i ) + 1 ; } }
This takes a single - quoted string as identified by the parser and processes it into a standard java string . It removes the surrounding quotes and substitues a single apostrophe or doubled apostrophes .
202
39
137,681
public SourceFile retrievePanSource ( String name , List < String > loadpath ) { String cacheKey = name + ( ( String ) " " ) + String . join ( ":" , loadpath ) ; SourceFile cachedResult = retrievePanCacheLoadpath . get ( cacheKey ) ; if ( cachedResult == null ) { File file = lookupSource ( name , loadpath ) ; cachedResult = createPanSourceFile ( name , file ) ; retrievePanCacheLoadpath . put ( cacheKey , cachedResult ) ; } return cachedResult ; }
Optimised due to lots of calls and slow lookupSource
113
12
137,682
public Resource . Iterator get ( Resource resource ) { Integer key = Integer . valueOf ( System . identityHashCode ( resource ) ) ; return map . get ( key ) ; }
Lookup the iterator associated with the given resource . If there is no iterator null is returned .
38
19
137,683
public void put ( Resource resource , Resource . Iterator iterator ) { assert ( resource != null ) ; Integer key = Integer . valueOf ( System . identityHashCode ( resource ) ) ; if ( iterator != null ) { map . put ( key , iterator ) ; } else { map . remove ( key ) ; } }
Associate the iterator to the given resource . If the iterator is null then the mapping is removed .
67
20
137,684
private void addFiles ( FileSet fs ) { // Get the files included in the fileset. DirectoryScanner ds = fs . getDirectoryScanner ( getProject ( ) ) ; // The base directory for all files. File basedir = ds . getBasedir ( ) ; // Loop over each file creating a File object. for ( String f : ds . getIncludedFiles ( ) ) { if ( SourceType . hasSourceFileExtension ( f ) ) { sourceFiles . add ( new File ( basedir , f ) ) ; } } }
Utility method that adds all of the files in a fileset to the list of files to be processed . Duplicate files appear only once in the final list . Files not ending with a valid source file extension are ignored .
118
45
137,685
public void setWarnings ( String warnings ) { try { deprecationWarnings = CompilerOptions . DeprecationWarnings . fromString ( warnings ) ; } catch ( IllegalArgumentException e ) { throw new BuildException ( "invalid value for warnings: " + warnings ) ; } }
Determines whether deprecation warnings are emitted and if so whether to treat them as fatal errors .
66
21
137,686
public void setObjectAndLoadpath ( ) { StringProperty sname = StringProperty . getInstance ( objectTemplate . name ) ; setGlobalVariable ( "OBJECT" , sname , true ) ; setGlobalVariable ( "LOADPATH" , new ListResource ( ) , false ) ; }
Set the name of the object template . Define the necessary variables .
61
14
137,687
public void setIterator ( Resource resource , Resource . Iterator iterator ) { iteratorMap . put ( resource , iterator ) ; }
Register a Resource iterator in the context .
26
8
137,688
public Element getVariable ( String name ) { Element result = localVariables . get ( name ) ; // If the result is null, then try to look up a global variable. if ( result == null ) { result = getGlobalVariable ( name ) ; } return result ; }
Return the Element which corresponds to the given variable name . It will first check local variables and then global variables . This method will return null if the variable doesn t exist or the argument is null . Note that this will clone the value before returning it if it came from a global variable .
58
57
137,689
public Element dereferenceVariable ( String name , boolean lookupOnly , Term [ ] terms ) throws InvalidTermException { boolean duplicate = false ; Element result = localVariables . get ( name ) ; // If the result is null, then try to look up a global variable. if ( result == null ) { duplicate = true ; result = getGlobalVariable ( name ) ; } // Now actually dereference the given variable. The caller must deal // with any invalid term exceptions or evaluation exceptions. We just // pass those on. if ( result != null ) { if ( ! ( result instanceof Undef ) ) { // FIXME: Determine if the result needs to be protected. result = result . rget ( terms , 0 , false , lookupOnly ) ; } else { // Trying to dereference an undefined value. Therefore, the // value does not exist; return null to caller. result = null ; } } // FIXME: This is inefficient and should be avoided. However, one must // ensure that global variables are protected against changes. // To ensure that global variables are not inadvertently modified via // copies in local variables, duplicate the result. Do this only AFTER // the dereference to limit the amount of potentially unnecessary // cloning. if ( duplicate && result != null ) { result = result . duplicate ( ) ; } return result ; }
Return the Element which corresponds to the given variable name . It will first check local variables and then the parent context . This method will return null if the variable doesn t exist or the argument is null . Note that this will clone the final value if it originated from a global variable .
276
56
137,690
protected int convertMatchFlags ( Element opts ) { int flags = 0 ; String sopts = ( ( StringProperty ) opts ) . getValue ( ) ; for ( int i = 0 ; i < sopts . length ( ) ; i ++ ) { char c = sopts . charAt ( i ) ; switch ( c ) { case ' ' : flags |= Pattern . CASE_INSENSITIVE ; break ; case ' ' : flags |= Pattern . DOTALL ; break ; case ' ' : flags |= Pattern . MULTILINE ; break ; case ' ' : flags |= Pattern . UNICODE_CASE ; break ; case ' ' : flags |= Pattern . COMMENTS ; break ; default : throw EvaluationException . create ( sourceRange , MSG_INVALID_REGEXP_FLAG , c ) ; } } return flags ; }
A utility function to convert a string containing match options to the associated integer with the appropriate bits set .
185
20
137,691
protected Pattern compilePattern ( Element regex , int flags ) { Pattern p = null ; try { String re = ( ( StringProperty ) regex ) . getValue ( ) ; p = Pattern . compile ( re , flags ) ; } catch ( PatternSyntaxException pse ) { throw EvaluationException . create ( sourceRange , MSG_INVALID_REGEXP , pse . getLocalizedMessage ( ) ) ; } return p ; }
Generate a Pattern from the given string and flags .
89
11
137,692
synchronized public void setDependency ( String objectName , String dependencyName ) throws EvaluationException { // Determine if adding this dependency will create a cycle. String nextObjectName = dependencies . get ( dependencyName ) ; while ( nextObjectName != null ) { if ( objectName . equals ( nextObjectName ) ) { throw EvaluationException . create ( MSG_CIRCULAR_OBJECT_DEPENDENCY , getCycle ( objectName , dependencyName ) ) ; } nextObjectName = dependencies . get ( nextObjectName ) ; } // If we get to here, then we reached the end of the chain without // creating a cycle. It is OK to add this to the dependencies. dependencies . put ( objectName , dependencyName ) ; // To avoid deadlock, ensure that the number of available threads is // larger than number of entries in the dependencies. compiler . ensureMinimumBuildThreadLimit ( dependencies . size ( ) + 1 ) ; }
This method will set the given dependency in the map which holds them . This method will throw an exception if the specified dependency would create a cycle in the dependency map . In this case the dependency will not be inserted .
199
43
137,693
synchronized private String getCycle ( String objectName , String dependencyName ) { // Determine if adding this dependency will create a cycle. StringBuilder sb = new StringBuilder ( ) ; sb . append ( objectName ) ; sb . append ( " -> " ) ; sb . append ( dependencyName ) ; String nextObjectName = dependencies . get ( dependencyName ) ; while ( nextObjectName != null && ! objectName . equals ( nextObjectName ) ) { sb . append ( " -> " ) ; sb . append ( nextObjectName ) ; nextObjectName = dependencies . get ( nextObjectName ) ; } sb . append ( " -> " ) ; sb . append ( objectName ) ; return sb . toString ( ) ; }
This method creates a string describing a cycle which has been detected . It should only be called if a cycle with the specified dependency has actually been detected .
165
30
137,694
@ Override public Element execute ( Context context ) { try { Element [ ] args = calculateArgs ( context ) ; Property a = ( Property ) args [ 0 ] ; Property b = ( Property ) args [ 1 ] ; return execute ( sourceRange , a , b ) ; } catch ( ClassCastException cce ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_ARGS_ADD ) , sourceRange ) ; } }
Perform the addition of the two top values on the data stack in the given DMLContext . This method will handle long double and string values . Exceptions are thrown if the types of the arguments do not match or they are another type .
96
49
137,695
private static Element execute ( SourceRange sourceRange , Property a , Property b ) { assert ( a != null ) ; assert ( b != null ) ; Element result = null ; if ( ( a instanceof LongProperty ) && ( b instanceof LongProperty ) ) { long l1 = ( ( Long ) a . getValue ( ) ) . longValue ( ) ; long l2 = ( ( Long ) b . getValue ( ) ) . longValue ( ) ; result = LongProperty . getInstance ( l1 + l2 ) ; } else if ( ( a instanceof NumberProperty ) && ( b instanceof NumberProperty ) ) { double d1 = ( ( NumberProperty ) a ) . doubleValue ( ) ; double d2 = ( ( NumberProperty ) b ) . doubleValue ( ) ; result = DoubleProperty . getInstance ( d1 + d2 ) ; } else if ( ( a instanceof StringProperty ) && ( b instanceof StringProperty ) ) { String s1 = ( String ) a . getValue ( ) ; String s2 = ( String ) b . getValue ( ) ; result = StringProperty . getInstance ( s1 + s2 ) ; } else { throw new EvaluationException ( MessageUtils . format ( MSG_MISMATCHED_ARGS_ADD ) , sourceRange ) ; } return result ; }
Do the actual addition .
282
5
137,696
public void setIncludeRoot ( File includeroot ) { this . includeroot = includeroot ; if ( ! includeroot . exists ( ) ) { throw new BuildException ( "includeroot doesn't exist: " + includeroot ) ; } if ( ! includeroot . isDirectory ( ) ) { throw new BuildException ( "includeroot must be a directory: " + includeroot ) ; } }
Set the directory to use for the include globs . This is required only if the includes parameter is set .
94
22
137,697
public void setIncludes ( String includes ) { // Split the string into separate file globs. String [ ] globs = includes . split ( "[\\s,]+" ) ; // Loop over these globs and create dirsets from them. // Do not set the root directory until the task is // executed. for ( String glob : globs ) { DirSet dirset = new DirSet ( ) ; dirset . setIncludes ( glob ) ; this . includes . add ( dirset ) ; } }
Set the include globs to use for the pan compiler loadpath .
106
14
137,698
private void addPaths ( Path p ) { for ( String d : p . list ( ) ) { File dir = new File ( d ) ; if ( dir . exists ( ) && dir . isDirectory ( ) ) { if ( ! includeDirectories . contains ( dir ) ) includeDirectories . add ( dir ) ; } } }
Collect all of the directories listed within enclosed path tags . Order of the path elements is preserved . Duplicates are included where first specified .
71
27
137,699
public HashResource restoreRelativeRoot ( HashResource previousValue ) { HashResource value = relativeRoot ; relativeRoot = previousValue ; return value ; }
Retrieve and clear the relative root for this context .
31
11