idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
14,200 | 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 . |
14,201 | 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 . |
14,202 | 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 . |
14,203 | 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 . |
14,204 | public int addAttribute ( String attrId ) { if ( attributeMapper . containsKey ( attrId ) ) { return attributeMapper . get ( attrId ) ; } 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 |
14,205 | 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 |
14,206 | 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 ( ) ; CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream ( old , null ) ; 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 . |
14,207 | 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 . |
14,208 | 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 . |
14,209 | 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 . |
14,210 | 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 ) ; if ( hasApp ( ) ) { sb . append ( getApp ( ) ) . append ( SLF ) ; sb . append ( hasDlg ( ) ? getDlg ( ) : "" ) . append ( SLF ) ; } return sb . toString ( ) ; } | Generate base string for HMAC generation . |
14,211 | 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 . |
14,212 | public byte [ ] decompress ( InputStream strm ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; LZFInputStream in = new LZFInputStream ( strm ) ; byte [ ] buffer = new byte [ 8192 ] ; int len = 0 ; 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 |
14,213 | public static GregorianCalendar getRandomDate ( long seed ) { GregorianCalendar gc = new GregorianCalendar ( ) ; Random rand = new Random ( seed ) ; gc . set ( GregorianCalendar . YEAR , 1900 + rand . nextInt ( 120 ) ) ; gc . set ( GregorianCalendar . DAY_OF_YEAR , rand . nextInt ( 364 ) + 1 ) ; return gc ; } | Gets a random date in the last 100 years |
14,214 | 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 |
14,215 | 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 > > ( ) ; 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 ( ) ) ; } List < EndPoint < T > > sortedBounds = new ArrayList < EndPoint < T > > ( boundSet ) ; Collections . sort ( sortedBounds ) ; List < Interval < T > > tempPartition = new ArrayList < Interval < T > > ( ) ; 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 ) ) ; } 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 |
14,216 | 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 ) ; 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 . |
14,217 | 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 ) { if ( compareUp > 0 ) { return true ; } else if ( ( compareUp == 0 ) && ( this . upperBoundClosed || ! i . upperBoundClosed ) ) { return true ; } } else if ( compareLow == 0 ) { if ( this . lowerBoundClosed || ! i . lowerBoundClosed ) { { 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 . |
14,218 | public boolean hasValue ( final T value ) throws MIDDException { 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 . |
14,219 | 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 |
14,220 | 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 . |
14,221 | 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 . |
14,222 | 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 . |
14,223 | public String getFinalReason ( Path path ) { StringBuilder sb = new StringBuilder ( path + " cannot be modified; " ) ; StringBuilder finalPath = new StringBuilder ( "/" ) ; 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 ; } finalPath . deleteCharAt ( finalPath . length ( ) - 1 ) ; 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 . |
14,224 | public void setFinal ( Path path ) { Node currentNode = root ; for ( Term t : path . getTerms ( ) ) { Node nextNode = currentNode . getChild ( t ) ; if ( nextNode == null ) { nextNode = currentNode . newChild ( t ) ; } currentNode = nextNode ; } currentNode . setFinal ( ) ; } | Mark the given Path as being final . |
14,225 | 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 . |
14,226 | public int compareTo ( Path o ) { if ( o == null ) { throw new NullPointerException ( ) ; } if ( this . type != o . type ) { return type . compareTo ( o . type ) ; } int mySize = this . terms . length ; int otherSize = o . terms . length ; if ( mySize != otherSize ) { return ( mySize < otherSize ) ? 1 : - 1 ; } 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 ; } } 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 . |
14,227 | 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 . |
14,228 | 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 ( ) ) ; 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 . |
14,229 | 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 . |
14,230 | 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 . |
14,231 | public void onConnect ( final Object newClient ) { meta . commandsForDomainModel ( new CommandsForDomainModelCallback ( ) { public void commandsReady ( final List < Command > commands ) { networkLayer . onConnectFinished ( newClient ) ; networkLayer . send ( commands , newClient ) ; } } ) ; } | Sends the current domain model to a newly connecting client . |
14,232 | public void onClientConnectionError ( final Object client , final SynchronizeFXException e ) { serverCallback . onClientConnectionError ( client , e ) ; } | Logs the unexpected disconnection of an client . |
14,233 | private void removeDefinedFields ( Context context , List < Term > undefinedFields ) throws ValidationException { for ( Term term : reqKeys ) { undefinedFields . remove ( term ) ; } for ( Term term : optKeys ) { undefinedFields . remove ( term ) ; } for ( String s : includes ) { try { FullType fullType = context . getFullType ( s ) ; BaseType baseType = fullType . getBaseType ( ) ; RecordType recordType = ( RecordType ) baseType ; recordType . removeDefinedFields ( context , undefinedFields ) ; } catch ( ClassCastException cce ) { throw CompilerError . create ( MSG_NONRECORD_TYPE_REF , s ) ; } catch ( NullPointerException npe ) { 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 . |
14,234 | public static void activateLoggers ( String loggerList ) { EnumSet < LoggingType > flags = EnumSet . noneOf ( LoggingType . class ) ; for ( String name : loggerList . split ( "\\s*,\\s*" ) ) { try { flags . add ( LoggingType . valueOf ( name . trim ( ) . toUpperCase ( ) ) ) ; } catch ( IllegalArgumentException consumed ) { } } 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 . |
14,235 | private static void initializeLogger ( Logger logger ) { topLogger . setUseParentHandlers ( false ) ; 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 . |
14,236 | public synchronized static void setLogFile ( File logfile ) { try { if ( logfile != null ) { String absolutePath = logfile . getAbsolutePath ( ) ; if ( initializedLogFile == null || ( ! initializedLogFile . equals ( absolutePath ) ) ) { initializeLogger ( topLogger ) ; FileHandler handler = new FileHandler ( absolutePath ) ; handler . setFormatter ( new LogFormatter ( ) ) ; topLogger . addHandler ( handler ) ; 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 . |
14,237 | 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 . |
14,238 | 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 . |
14,239 | private Uri getUri ( String string ) { return Uri . parse ( OfflinerProvider . CONTENT + OfflinerProvider . getAuthority ( mPackageName ) + OfflinerProvider . SLASH + string ) ; } | Retrieve the URI with Cache database provider authority . |
14,240 | public void setPlaybackState ( int state ) { if ( sHasRemoteControlAPIs ) { try { sRCCSetPlayStateMethod . invoke ( mActualRemoteControlClient , state ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } | Sets the current playback state . |
14,241 | 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 . |
14,242 | @ 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 . |
14,243 | @ SuppressWarnings ( "deprecation" ) public void setMetaData ( SoundCloudTrack track , Bitmap artwork ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . 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 ( ) ; } 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 . |
14,244 | 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 . |
14,245 | 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 . |
14,246 | 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 . |
14,247 | @ 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 . |
14,248 | 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 . |
14,249 | 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 . |
14,250 | 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 . |
14,251 | 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 . |
14,252 | 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 . |
14,253 | public List < Command > setPropertyValue ( final UUID propertyId , final Object value ) throws SynchronizeFXException { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,254 | public List < Command > addToList ( final UUID listId , final int position , final Object value , final int newSize ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,255 | public List < Command > addToSet ( final UUID setId , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,256 | public List < Command > putToMap ( final UUID mapId , final Object key , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,257 | 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 . |
14,258 | public List < Command > removeFromMap ( final UUID mapId , final Object key ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,259 | public List < Command > removeFromSet ( final UUID setId , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,260 | public List < Command > replaceInList ( final UUID listId , final int position , final Object value ) { final State state = createCommandList ( new WithCommandType ( ) { 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 . |
14,261 | static void replaceHeredocStrings ( ASTTemplate tnode , List < StringProperty > strings ) { 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 . |
14,262 | static void processSingleQuotedString ( StringBuilder sb ) { assert ( sb . length ( ) >= 2 ) ; assert ( sb . charAt ( 0 ) == '\'' && sb . charAt ( sb . length ( ) - 1 ) == '\'' ) ; sb . deleteCharAt ( sb . length ( ) - 1 ) ; sb . deleteCharAt ( 0 ) ; 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 . |
14,263 | 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 |
14,264 | 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 . |
14,265 | 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 . |
14,266 | private void addFiles ( FileSet fs ) { DirectoryScanner ds = fs . getDirectoryScanner ( getProject ( ) ) ; File basedir = ds . getBasedir ( ) ; 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 . |
14,267 | 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 . |
14,268 | 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 . |
14,269 | public void setIterator ( Resource resource , Resource . Iterator iterator ) { iteratorMap . put ( resource , iterator ) ; } | Register a Resource iterator in the context . |
14,270 | public Element getVariable ( String name ) { Element result = localVariables . get ( name ) ; 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 . |
14,271 | public Element dereferenceVariable ( String name , boolean lookupOnly , Term [ ] terms ) throws InvalidTermException { boolean duplicate = false ; Element result = localVariables . get ( name ) ; if ( result == null ) { duplicate = true ; result = getGlobalVariable ( name ) ; } if ( result != null ) { if ( ! ( result instanceof Undef ) ) { result = result . rget ( terms , 0 , false , lookupOnly ) ; } else { result = null ; } } 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 . |
14,272 | 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 'i' : flags |= Pattern . CASE_INSENSITIVE ; break ; case 's' : flags |= Pattern . DOTALL ; break ; case 'm' : flags |= Pattern . MULTILINE ; break ; case 'u' : flags |= Pattern . UNICODE_CASE ; break ; case 'x' : 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 . |
14,273 | 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 . |
14,274 | synchronized public void setDependency ( String objectName , String dependencyName ) throws EvaluationException { 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 ) ; } dependencies . put ( objectName , dependencyName ) ; 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 . |
14,275 | synchronized private String getCycle ( String objectName , String dependencyName ) { 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 . |
14,276 | 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 . |
14,277 | 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 . |
14,278 | 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 . |
14,279 | public void setIncludes ( String includes ) { String [ ] globs = includes . split ( "[\\s,]+" ) ; 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 . |
14,280 | 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 . |
14,281 | public HashResource restoreRelativeRoot ( HashResource previousValue ) { HashResource value = relativeRoot ; relativeRoot = previousValue ; return value ; } | Retrieve and clear the relative root for this context . |
14,282 | public Set < SourceFile > getDependencies ( ) { Set < SourceFile > sourceFiles = new TreeSet < SourceFile > ( ) ; for ( Template t : dependencies . values ( ) ) { sourceFiles . add ( t . sourceFile ) ; } sourceFiles . addAll ( otherDependencies ) ; return Collections . unmodifiableSet ( sourceFiles ) ; } | Returns an unmodifiable copy of the dependencies . |
14,283 | public Template globalLoad ( String name , boolean lookupOnly ) { if ( compiler == null ) { return null ; } SourceRepository repository = compiler . getSourceRepository ( ) ; SourceFile source = repository . retrievePanSource ( name , relativeLoadpaths ) ; if ( source . isAbsent ( ) ) { if ( lookupOnly ) { otherDependencies . add ( source ) ; return null ; } else { throw EvaluationException . create ( ( SourceRange ) null , ( BuildContext ) this , MSG_CANNOT_LOCATE_TEMPLATE , name ) ; } } CompileCache ccache = compiler . getCompileCache ( ) ; CompileResult cresult = ccache . waitForResult ( source . getPath ( ) . getAbsolutePath ( ) ) ; Template template = null ; try { template = cresult . template ; template . templateNameVerification ( name ) ; if ( ! lookupOnly ) { dependencies . put ( name , template ) ; if ( template . type == TemplateType . OBJECT ) { objectDependencies . add ( template . name ) ; } } } catch ( SyntaxException se ) { if ( ! lookupOnly ) { throw new EvaluationException ( se . getMessage ( ) ) ; } else { template = null ; } } catch ( EvaluationException ee ) { if ( ! lookupOnly ) { throw ee ; } else { template = null ; } } return template ; } | A method to load a template from the global cache . This may trigger the global cache to compile the template . |
14,284 | public void setBinding ( Path path , FullType fullType , Template template , SourceRange sourceRange ) { assert ( path != null ) ; assert ( path . isAbsolute ( ) ) ; assert ( fullType != null ) ; try { fullType . verifySubtypesDefined ( types ) ; } catch ( EvaluationException ee ) { throw ee . addExceptionInfo ( sourceRange , template . source , this . getTraceback ( sourceRange ) ) ; } List < FullType > list = bindings . get ( path ) ; if ( list == null ) { list = new LinkedList < FullType > ( ) ; bindings . put ( path , list ) ; } assert ( list != null ) ; list . add ( fullType ) ; } | This method associates a type definition to a path . These bindings are checked as part of the validation process . Note that there can be more than one binding per path . |
14,285 | public void setGlobalVariable ( String name , Element value ) { assert ( name != null ) ; GlobalVariable gvar = globalVariables . get ( name ) ; gvar . setValue ( value ) ; } | Set the variable to the given value preserving the status of the final flag . This will unconditionally set the value without checking if the value is final ; be careful . The value must already exist . |
14,286 | public void setGlobalVariable ( String name , GlobalVariable variable ) { assert ( name != null ) ; if ( variable != null ) { globalVariables . put ( name , variable ) ; } else { globalVariables . remove ( name ) ; } } | Set the variable to the given GlobalVariable . If variable is null then the global variable definition is removed . |
14,287 | public GlobalVariable replaceGlobalVariable ( String name , Element value , boolean finalFlag ) { assert ( name != null ) ; GlobalVariable oldVariable = globalVariables . get ( name ) ; GlobalVariable newVariable = new GlobalVariable ( finalFlag , value ) ; globalVariables . put ( name , newVariable ) ; return oldVariable ; } | Replaces the given global variable with the given value . The flag indicates whether or not the variable should be marked as final . Note however that this routine does not respect the final flag and replaces the value unconditionally . The function returns the old value of the variable or null if it didn t exist . |
14,288 | public void setGlobalVariable ( String name , Element value , boolean finalFlag ) { assert ( name != null ) ; if ( globalVariables . containsKey ( name ) ) { GlobalVariable gvar = globalVariables . get ( name ) ; gvar . setValue ( value ) ; gvar . setFinalFlag ( finalFlag ) ; } else if ( value != null ) { GlobalVariable gvar = new GlobalVariable ( finalFlag , value ) ; globalVariables . put ( name , gvar ) ; } } | Set the variable to the given value . If the value is null then the variable will be removed from the context . |
14,289 | public Element getGlobalVariable ( String name ) { GlobalVariable gvar = globalVariables . get ( name ) ; return ( gvar != null ) ? gvar . getValue ( ) : null ; } | Return the Element which corresponds to the given variable name without duplicating the value . This is useful when dealing with SELF or with variables in a context where it is known that the value won t be modified . |
14,290 | public Element getElement ( Path path , boolean errorIfNotFound ) throws EvaluationException { Element node = null ; switch ( path . getType ( ) ) { case ABSOLUTE : node = root ; break ; case RELATIVE : if ( relativeRoot != null ) { node = relativeRoot ; } else { throw new EvaluationException ( "relative path ('" + path + "') cannot be used to retrieve element in configuration" ) ; } break ; case EXTERNAL : String myObject = objectTemplate . name ; String externalObject = path . getAuthority ( ) ; if ( myObject . equals ( externalObject ) ) { node = root ; } else { Template externalTemplate = localAndGlobalLoad ( externalObject , ! errorIfNotFound ) ; if ( externalTemplate != null && ! errorIfNotFound ) { dependencies . put ( externalObject , externalTemplate ) ; objectDependencies . add ( externalObject ) ; } else if ( externalTemplate == null ) { if ( errorIfNotFound ) { throw new EvaluationException ( "object template " + externalObject + " could not be found" , null ) ; } else { return null ; } } if ( externalTemplate . type != TemplateType . OBJECT ) { throw new EvaluationException ( externalObject + " does not refer to an object template" ) ; } BuildCache bcache = compiler . getBuildCache ( ) ; if ( checkObjectDependencies ) { bcache . setDependency ( myObject , externalObject ) ; } BuildResult result = ( BuildResult ) bcache . waitForResult ( externalObject ) ; node = result . getRoot ( ) ; } break ; } assert ( node != null ) ; try { node = node . rget ( path . getTerms ( ) , 0 , node . isProtected ( ) , ! errorIfNotFound ) ; } catch ( InvalidTermException ite ) { throw new EvaluationException ( ite . formatMessage ( path ) ) ; } if ( ! errorIfNotFound || node != null ) { return node ; } else { throw new EvaluationException ( MessageUtils . format ( MSG_NO_VALUE_FOR_PATH , path . toString ( ) ) ) ; } } | Pull the value of an element from a configuration tree . This can either be an absolute relative or external path . |
14,291 | public void setLocalVariable ( String name , Term [ ] terms , Element value ) throws EvaluationException { assert ( name != null ) ; if ( globalVariables . containsKey ( name ) ) { throw new EvaluationException ( MessageUtils . format ( MSG_CANNOT_MODIFY_GLOBAL_VARIABLE_FROM_DML , name ) ) ; } if ( terms == null || terms . length == 0 ) { setLocalVariable ( name , value ) ; } else { Element var = getLocalVariable ( name ) ; if ( var != null && var . isProtected ( ) ) { var = var . writableCopy ( ) ; setLocalVariable ( name , var ) ; } if ( var == null || var instanceof Undef ) { Term term = terms [ 0 ] ; if ( term . isKey ( ) ) { var = new HashResource ( ) ; } else { var = new ListResource ( ) ; } setLocalVariable ( name , var ) ; } assert ( var != null ) ; try { var . rput ( terms , 0 , value ) ; } catch ( InvalidTermException ite ) { throw new EvaluationException ( ite . formatVariableMessage ( name , terms ) ) ; } } } | Set the local variable to the given value . If the value is null then the corresponding variable will be removed . If there is a global variable of the same name then an EvaluationException will be thrown . |
14,292 | public void execute ( final Object observable , final Runnable change ) { listeners . disableFor ( observable ) ; change . run ( ) ; listeners . enableFor ( observable ) ; } | Executes a change to an observable of the users domain model without generating change commands for this change . |
14,293 | protected void executeWithNamedTemplate ( Context context , String name ) throws EvaluationException { assert ( context != null ) ; assert ( name != null ) ; Template template = null ; boolean runStatic = false ; try { template = context . localLoad ( name ) ; if ( template == null ) { template = context . globalLoad ( name ) ; runStatic = true ; } } catch ( EvaluationException ee ) { throw ee . addExceptionInfo ( getSourceRange ( ) , context ) ; } if ( template == null ) { throw new EvaluationException ( "failed to load template: " + name , getSourceRange ( ) ) ; } TemplateType includeeType = context . getCurrentTemplate ( ) . type ; TemplateType includedType = template . type ; if ( ! Template . checkValidInclude ( includeeType , includedType ) ) { throw new EvaluationException ( includeeType + " template cannot include " + includedType + " template" , getSourceRange ( ) ) ; } context . pushTemplate ( template , getSourceRange ( ) , Level . INFO , includedType . toString ( ) ) ; template . execute ( context , runStatic ) ; context . popTemplate ( Level . INFO , includedType . toString ( ) ) ; } | This is a utility method which performs an include from a fixed template name . The validity of the name should be checked by the subclass ; this avoids unnecessary regular expression matching . |
14,294 | static private Element runDefaultDml ( Operation dml ) throws SyntaxException { if ( dml == null ) { return null ; } Context context = new CompileTimeContext ( ) ; Element value = null ; try { value = context . executeDmlBlock ( dml ) ; } catch ( EvaluationException consumed ) { value = null ; } return value ; } | can be reused . |
14,295 | private String retrieveFromCache ( String url ) { String savedJson ; savedJson = mCacheQueryHandler . get ( getContext ( ) , url ) ; log ( "---------- body found in offline saver : " + savedJson ) ; log ( "----- NO NETWORK : retrieving ends" ) ; return savedJson ; } | Get a saved body for a given url . |
14,296 | private Context getContext ( ) { Context context = mContext . get ( ) ; if ( context == null ) { throw new IllegalStateException ( "Context used by the instance has been destroyed." ) ; } return context ; } | Retrieve the context if not yet garbage collected . |
14,297 | private Response save ( Response response ) { String jsonBody ; String key = response . request ( ) . url ( ) . toString ( ) ; log ( "----- SAVE FOR OFFLINE : saving starts" ) ; log ( "---------- for request : " + key ) ; log ( "---------- trying to parse response body" ) ; BufferedReader reader ; StringBuilder sb = new StringBuilder ( ) ; log ( "---------- trying to parse response body" ) ; InputStream bodyStream = response . body ( ) . byteStream ( ) ; InputStreamReader bodyReader = new InputStreamReader ( bodyStream , Charset . forName ( "UTF-8" ) ) ; reader = new BufferedReader ( bodyReader ) ; String line ; try { while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) ; } bodyReader . close ( ) ; bodyReader . close ( ) ; reader . close ( ) ; } catch ( IOException e ) { Log . e ( TAG , "IOException : " + e . getMessage ( ) ) ; } jsonBody = sb . toString ( ) ; log ( "---------- trying to save response body for offline" ) ; mCacheQueryHandler . put ( key , jsonBody ) ; log ( "---------- url : " + key ) ; log ( "---------- body : " + jsonBody ) ; log ( "----- SAVE FOR OFFLINE : saving ends" ) ; return response . newBuilder ( ) . body ( ResponseBody . create ( response . body ( ) . contentType ( ) , jsonBody ) ) . build ( ) ; } | Allow to save the Response body for offline usage . |
14,298 | public void destroy ( ) { if ( mIsClosed ) { return ; } if ( mState != STATE_STOPPED ) { mDestroyDelayed = true ; return ; } mIsClosed = true ; PlaybackService . unregisterListener ( getContext ( ) , mInternalListener ) ; mInternalListener = null ; mApplicationContext . clear ( ) ; mApplicationContext = null ; mClientKey = null ; mPlayerPlaylist = null ; mCheerleaderPlayerListeners . clear ( ) ; } | Release resources associated with the player . |
14,299 | public void play ( int position ) { checkState ( ) ; ArrayList < SoundCloudTrack > tracks = mPlayerPlaylist . getPlaylist ( ) . getTracks ( ) ; if ( position >= 0 && position < tracks . size ( ) ) { SoundCloudTrack trackToPlay = tracks . get ( position ) ; mPlayerPlaylist . setPlayingTrack ( position ) ; PlaybackService . play ( getContext ( ) , mClientKey , trackToPlay ) ; } } | Play a track at a given position in the player playlist . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.