idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
14,300
public void addTrack ( SoundCloudTrack track , boolean playNow ) { checkState ( ) ; mPlayerPlaylist . add ( track ) ; for ( CheerleaderPlaylistListener listener : mCheerleaderPlaylistListeners ) { listener . onTrackAdded ( track ) ; } if ( playNow ) { play ( mPlayerPlaylist . size ( ) - 1 ) ; } }
Add a track to the current SoundCloud player playlist .
14,301
public void addTracks ( List < SoundCloudTrack > tracks ) { checkState ( ) ; for ( SoundCloudTrack track : tracks ) { addTrack ( track ) ; } }
Add a list of track to thr current SoundCloud player playlist .
14,302
public void registerPlayerListener ( CheerleaderPlayerListener listener ) { checkState ( ) ; mCheerleaderPlayerListeners . add ( listener ) ; if ( mState == STATE_PLAYING ) { listener . onPlayerPlay ( mPlayerPlaylist . getCurrentTrack ( ) , mPlayerPlaylist . getCurrentTrackIndex ( ) ) ; } else if ( mState == STATE_PAUSED ) { listener . onPlayerPause ( ) ; } }
Register a listener to catch player events .
14,303
private void initInternalListener ( Context context ) { mInternalListener = new PlaybackListener ( ) { protected void onPlay ( SoundCloudTrack track ) { super . onPlay ( track ) ; mState = STATE_PLAYING ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerPlay ( track , mPlayerPlaylist . getCurrentTrackIndex ( ) ) ; } } protected void onPause ( ) { super . onPause ( ) ; mState = STATE_PAUSED ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerPause ( ) ; } } protected void onPlayerDestroyed ( ) { super . onPlayerDestroyed ( ) ; mState = STATE_STOPPED ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerDestroyed ( ) ; } if ( mDestroyDelayed ) { CheerleaderPlayer . this . destroy ( ) ; } } protected void onSeekTo ( int milli ) { super . onSeekTo ( milli ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerSeekTo ( milli ) ; } } protected void onBufferingStarted ( ) { super . onBufferingStarted ( ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onBufferingStarted ( ) ; } } protected void onBufferingEnded ( ) { super . onBufferingEnded ( ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onBufferingEnded ( ) ; } } protected void onProgressChanged ( int milli ) { super . onProgressChanged ( milli ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onProgressChanged ( milli ) ; } } } ; PlaybackService . registerListener ( context , mInternalListener ) ; }
Initialize the internal listener .
14,304
public static String getMessageString ( String msgKey ) { assert ( msgKey != null ) ; try { return bundle . getString ( msgKey ) ; } catch ( MissingResourceException mre ) { throw new CompilerError ( mre . getLocalizedMessage ( ) ) ; } catch ( ClassCastException cce ) { throw new CompilerError ( "bundle contains non-string object for key '" + msgKey + "'" ) ; } }
Look up a localized message in the message bundle and return a MessageFormat for it .
14,305
public static String format ( String msgKey , Object ... args ) { try { return MessageFormat . format ( getMessageString ( msgKey ) , args ) ; } catch ( IllegalArgumentException iae ) { throw new CompilerError ( "bundle contains invalid message format for key '" + msgKey + "'\n" + "error: " + iae . getMessage ( ) ) ; } }
Format a message corresponding to the given key and using the given arguments .
14,306
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private void execute ( final ListCommand command ) { getMetaData ( command ) ; final Queue < ListCommand > log = metaData . getUnapprovedCommands ( ) ; if ( log . isEmpty ( ) ) { updateVersion ( command ) ; executeCommand ( command ) ; } else if ( log . peek ( ) . getListVersionChange ( ) . equals ( command . getListVersionChange ( ) ) ) { updateVersion ( command ) ; log . remove ( ) ; } else { List < ? extends ListCommand > repairedCommands = indexRepairer . repairCommands ( metaData . getUnapprovedCommands ( ) , command ) ; versionRepairer . repairLocalCommandsVersion ( metaData . getUnapprovedCommands ( ) , command ) ; repairedCommands = versionRepairer . repairRemoteCommandVersion ( repairedCommands , metaData . getUnapprovedCommandsAsList ( ) ) ; topologyLayerCallback . sendCommands ( ( List ) metaData . getUnapprovedCommandsAsList ( ) ) ; for ( final ListCommand repaired : repairedCommands ) { executeCommand ( repaired ) ; } updateVersion ( command ) ; } }
Executes a remotely received command repairs it when necessary and resends repaired versions of local commands that where obsoleted by the received command .
14,307
public void checkValidReplacement ( Element newValue ) throws EvaluationException { if ( ! ( newValue instanceof Undef ) && ! ( newValue instanceof Null ) ) { if ( ! this . getClass ( ) . isAssignableFrom ( newValue . getClass ( ) ) ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_REPLACEMENT , this . getTypeAsString ( ) , newValue . getTypeAsString ( ) ) ) ; } } }
Check that the newValue is a valid replacement for the this value . This implementation will check if the newValue is assignable from the current value or that the newValue is either undef or null . If not an evaluation exception will be thrown . This implementation should be overridden if more liberal replacements are allowed .
14,308
public Element rget ( Term [ ] terms , int index , boolean protect , boolean lookupOnly ) throws InvalidTermException { if ( ! lookupOnly ) { throw new EvaluationException ( MessageUtils . format ( MSG_ILLEGAL_DEREFERENCE , this . getTypeAsString ( ) ) ) ; } return null ; }
Dereference the Element to return the value of a child . Any resource should return the value of the given child . The default implementation of this method will throw an EvaluationException indicating that this Element cannot be dereferenced .
14,309
public ListResource rgetList ( Term [ ] terms , int index ) throws InvalidTermException { throw new EvaluationException ( MessageUtils . format ( MSG_ILLEGAL_DEREFERENCE , this . getTypeAsString ( ) ) ) ; }
This is a special lookup function that will retrieve a list from the resource . If the resource does not exist an empty list will be created . All necessary parent resources are created . The returned list is guaranteed to be a writable resource .
14,310
public void rput ( Term [ ] terms , int index , Element value ) throws InvalidTermException { throw new EvaluationException ( MessageUtils . format ( MSG_CANNOT_ADD_CHILD , this . getTypeAsString ( ) ) ) ; }
Add the given child to this resource creating intermediate resources as necessary . If this Element is not a resource then this will throw an InvalidTermException . The default implementation of this method throws such an exception . This resource must be a writable resource otherwise an exception will be thrown .
14,311
public static void main ( final String ... args ) { System . out . println ( "starting server" ) ; final Model model = new Model ( ) ; final SynchronizeFxServer syncFxServer = SynchronizeFxBuilder . create ( ) . server ( ) . model ( model ) . callback ( new ServerCallback ( ) { public void onError ( final SynchronizeFXException exception ) { System . err . println ( "Server Error:" + exception . getLocalizedMessage ( ) ) ; } public void onClientConnectionError ( final Object client , final SynchronizeFXException exception ) { System . err . println ( "An exception in the communication to a client occurred." + exception ) ; } } ) . build ( ) ; syncFxServer . start ( ) ; final Scanner console = new Scanner ( System . in ) ; boolean exit = false ; while ( ! exit ) { System . out . println ( "press 'q' for quit" ) ; final String input = console . next ( ) ; if ( "q" . equals ( input ) ) { exit = true ; } } console . close ( ) ; syncFxServer . shutdown ( ) ; }
The main entry point to the server application .
14,312
private static void checkNumericIndex ( long index ) { if ( index > Integer . MAX_VALUE ) { throw EvaluationException . create ( MSG_INDEX_EXCEEDS_MAXIMUM , index , Integer . MAX_VALUE ) ; } else if ( index < Integer . MIN_VALUE ) { throw EvaluationException . create ( MSG_INDEX_BELOW_MINIMUM , index , Integer . MIN_VALUE ) ; } }
An internal method to check that a numeric index is valid . It must be a non - negative integer .
14,313
private static long [ ] checkStringIndex ( String term ) { assert ( term != null ) ; long [ ] result = { 0L , 1L } ; if ( "" . equals ( term ) ) { throw EvaluationException . create ( MSG_KEY_CANNOT_BE_EMPTY_STRING ) ; } if ( isIndexPattern . matcher ( term ) . matches ( ) ) { if ( isIndexLeadingZerosPattern . matcher ( term ) . matches ( ) ) { throw EvaluationException . create ( MSG_INVALID_LEADING_ZEROS_INDEX , term ) ; } else { try { result [ 0 ] = Long . decode ( term ) . longValue ( ) ; checkNumericIndex ( result [ 0 ] ) ; } catch ( NumberFormatException nfe ) { throw EvaluationException . create ( MSG_KEY_CANNOT_BEGIN_WITH_DIGIT , term ) ; } } } else if ( isKeyPattern . matcher ( term ) . matches ( ) ) { result [ 1 ] = - 1L ; } else { throw EvaluationException . create ( MSG_INVALID_KEY , term ) ; } return result ; }
An internal method to check that a string value is valid . It can either be an Integer or String which is returned .
14,314
public static Term create ( String term ) { Term res = createStringCache . get ( term ) ; if ( res == null ) { if ( term != null && term . length ( ) >= 2 && term . charAt ( 0 ) == '{' && term . charAt ( term . length ( ) - 1 ) == '}' ) { term = EscapeUtils . escape ( term . substring ( 1 , term . length ( ) - 1 ) ) ; } long [ ] value = checkStringIndex ( term ) ; if ( value [ 1 ] < 0L ) { res = ( Term ) StringProperty . getInstance ( term ) ; } else { res = ( Term ) create ( value [ 0 ] ) ; } createStringCache . put ( term , res ) ; } return res ; }
Constructor of a path from a String . If the path does not have the correct syntax an IllegalArgumentException will be thrown .
14,315
public static Term create ( long index ) { Term res = createLongCache . get ( index ) ; if ( res == null ) { checkNumericIndex ( index ) ; res = ( Term ) LongProperty . getInstance ( index ) ; createLongCache . put ( index , res ) ; return res ; } return res ; }
Create a term directly from a long index .
14,316
public static Term create ( Element element ) { if ( element instanceof StringProperty ) { return create ( ( ( StringProperty ) element ) . getValue ( ) ) ; } else if ( element instanceof LongProperty ) { return create ( ( ( LongProperty ) element ) . getValue ( ) . longValue ( ) ) ; } else { throw EvaluationException . create ( MSG_INVALID_ELEMENT_FOR_INDEX , element . getTypeAsString ( ) ) ; } }
Create a term from a given element .
14,317
public static int compare ( Term self , Term other ) { if ( self == null || other == null ) { throw new NullPointerException ( ) ; } if ( self == other ) { return 0 ; } if ( self . isKey ( ) != other . isKey ( ) ) { return ( self . isKey ( ) ) ? 1 : - 1 ; } try { if ( self . isKey ( ) ) { return self . getKey ( ) . compareTo ( other . getKey ( ) ) ; } else { return self . getIndex ( ) . compareTo ( other . getIndex ( ) ) ; } } catch ( InvalidTermException consumed ) { assert ( false ) ; return 0 ; } }
A utility method to allow the comparison of any two terms .
14,318
public void execute ( final List < Command > commands ) { try { modelWalkingSynchronizer . doWhenModelWalkerFinished ( ActionType . INCOMMING_COMMANDS , new Runnable ( ) { public void run ( ) { for ( Object command : commands ) { execute ( command ) ; } } } ) ; } catch ( final SynchronizeFXException e ) { topology . onError ( e ) ; } }
Executes commands to change the domain model of the user .
14,319
public void commandsForDomainModel ( final CommandsForDomainModelCallback callback ) { if ( this . root == null ) { topology . onError ( new SynchronizeFXException ( "Request to create necessary commands to reproduce the domain model " + " but the root object of the domain model is not set." ) ) ; return ; } try { modelWalkingSynchronizer . startModelWalking ( ) ; creator . commandsForDomainModel ( this . root , callback ) ; modelWalkingSynchronizer . finishedModelWalking ( ) ; } catch ( final SynchronizeFXException e ) { topology . onError ( e ) ; } }
This method creates the commands necessary to reproduce the entire domain model .
14,320
public void shutDown ( ) { synchronized ( channels ) { isCurrentlyShutingDown = true ; for ( final SynchronizeFXWebsocketChannel server : channels . values ( ) ) { server . shutdown ( ) ; } servers . clear ( ) ; channels . clear ( ) ; clients . clear ( ) ; isCurrentlyShutingDown = false ; } }
Shuts down this servers with all its channels and disconnects all remaining clients .
14,321
public void ensureMinimumBuildThreadLimit ( int minLimit ) { if ( buildThreadLimit . get ( ) < minLimit ) { synchronized ( buildThreadLock ) { buildThreadLimit . set ( minLimit ) ; ThreadPoolExecutor buildExecutor = executors . get ( TaskResult . ResultType . BUILD ) ; buildExecutor . setMaximumPoolSize ( minLimit ) ; buildExecutor . setCorePoolSize ( minLimit ) ; } } }
Ensures that the number of threads in the build pool is at least as large as the number given . Because object templates can have dependencies on each other it is possible to deadlock the compilation with a rigidly fixed build queue . To avoid this allow the build queue limit to be increased .
14,322
public synchronized CompilerResults process ( ) { Set < Throwable > exceptions = new TreeSet < Throwable > ( new ThrowableComparator ( ) ) ; long start = new Date ( ) . getTime ( ) ; stats . setFileCount ( files . size ( ) ) ; if ( options . formatters . size ( ) > 0 ) { for ( File f : files ) { ccache . retrieve ( f . getAbsolutePath ( ) , false ) ; } } else { for ( File f : files ) { if ( ! f . isAbsolute ( ) && options . annotationBaseDirectory != null ) { f = new File ( options . annotationBaseDirectory , f . getPath ( ) ) ; } ccache . compile ( f . getAbsolutePath ( ) ) ; } } while ( remainingTasks . get ( ) > 0 ) { try { Future < ? extends TaskResult > future = resultsQueue . take ( ) ; try { stats . incrementFinishedTasks ( future . get ( ) . type ) ; } catch ( ExecutionException ee ) { exceptions . add ( ee . getCause ( ) ) ; } remainingTasks . decrementAndGet ( ) ; stats . updateMemoryInfo ( ) ; } catch ( InterruptedException consumed ) { } } try { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( new RuntimePermission ( "modifyThread" ) ) ; } for ( TaskResult . ResultType t : TaskResult . ResultType . values ( ) ) { executors . get ( t ) . shutdown ( ) ; } } catch ( SecurityException se ) { System . err . println ( "WARNING: missing modifyThread permission" ) ; } long end = new Date ( ) . getTime ( ) ; stats . setBuildTime ( end - start ) ; return new CompilerResults ( stats , exceptions ) ; }
Process the templates referenced by the CompilerOptions object used to initialize this instance . This will run through the complete compiling building and validation stages as requested . This method should only be invoked once per instance .
14,323
public void submit ( Task < ? extends TaskResult > task ) { remainingTasks . incrementAndGet ( ) ; stats . incrementStartedTasks ( task . resultType ) ; executors . get ( task . resultType ) . submit ( task ) ; resultsQueue . add ( task ) ; stats . updateMemoryInfo ( ) ; }
Submits a task to one of the compiler s task queues for processing . Although public this method should only be called by tasks started by the compiler itself .
14,324
public static SSLEngine createEngine ( final boolean clientMode ) { if ( context == null ) { context = createContext ( ) ; } SSLEngine engine = context . createSSLEngine ( ) ; engine . setUseClientMode ( clientMode ) ; return engine ; }
Creates a new engine for TLS communication in client or server mode .
14,325
public void readChild ( Element element , PrintWriter ps , int level , String name ) { String nbTab = tabMaker ( level ) ; if ( element instanceof Resource ) { Resource resource = ( Resource ) element ; writeBegin ( ps , nbTab , name , level , element . getTypeAsString ( ) ) ; for ( Resource . Entry entry : resource ) { Property key = entry . getKey ( ) ; Element value = entry . getValue ( ) ; level ++ ; readChild ( value , ps , level , key . toString ( ) ) ; level -- ; } writeEnd ( ps , nbTab , element . getTypeAsString ( ) ) ; } else { Property elem = ( Property ) element ; writeProperties ( ps , nbTab , name , element . getTypeAsString ( ) , elem . toString ( ) ) ; } }
Reads each child .
14,326
public String tabMaker ( int n ) { StringBuilder buf = new StringBuilder ( "" ) ; for ( int i = 1 ; i <= n ; i ++ ) { buf . append ( " " ) ; } String tab = buf . toString ( ) ; return tab ; }
Calculates the number of tabulations to write at the beginning of a line
14,327
public Element put ( String name , Element value ) { assert ( name != null ) ; Element oldValue = null ; if ( value != null ) { oldValue = map . put ( name , value ) ; if ( oldValue != null ) { oldValue . checkValidReplacement ( value ) ; } } else { oldValue = map . remove ( name ) ; } return oldValue ; }
Assign the value to the given variable name . If the value is null then the variable is undefined . If an old value existed then this method will check that the new value is a valid replacement for the old one . If not an exception will be thrown .
14,328
private boolean checkField ( EditText editText ) { boolean valid = true ; if ( TextUtils . isEmpty ( editText . getText ( ) ) ) { editText . startAnimation ( mWiggle ) ; editText . requestFocus ( ) ; valid = false ; } return valid ; }
Check if the edit text is valid or not .
14,329
public Element put ( int index , Element newValue ) { Element oldValue = null ; int size = list . size ( ) ; if ( index < 0 ) { if ( index < - size ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_NEGATIVE_LIST_INDEX , Integer . toString ( index ) , size ) ) ; } else { index += size ; } } try { if ( ( newValue != null ) && ! ( newValue instanceof Null ) ) { if ( index >= size ) { for ( int i = 0 ; i < index - size ; i ++ ) { list . add ( Undef . VALUE ) ; } list . add ( newValue ) ; } else { oldValue = list . set ( index , newValue ) ; if ( oldValue != null ) { oldValue . checkValidReplacement ( newValue ) ; } } } else { try { oldValue = list . remove ( index ) ; } catch ( IndexOutOfBoundsException ioobe ) { } } } catch ( IndexOutOfBoundsException ioobe ) { throw new EvaluationException ( MessageUtils . format ( MSG_NONEXISTANT_LIST_ELEMENT , Integer . toString ( index ) ) ) ; } return oldValue ; }
This is an optimized version of the put method which doesn t require creating a Term object .
14,330
public SoundCloudTrack getCurrentTrack ( ) { if ( mCurrentTrackIndex > - 1 && mCurrentTrackIndex < mSoundCloudPlaylist . getTracks ( ) . size ( ) ) { return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; } return null ; }
Return the current track .
14,331
public void addAll ( List < SoundCloudTrack > tracks ) { for ( SoundCloudTrack track : tracks ) { add ( mSoundCloudPlaylist . getTracks ( ) . size ( ) , track ) ; } }
Add all tracks at the end of the playlist .
14,332
public void add ( int position , SoundCloudTrack track ) { if ( mCurrentTrackIndex == - 1 ) { mCurrentTrackIndex = 0 ; } mSoundCloudPlaylist . addTrack ( position , track ) ; }
Add a track to the given position .
14,333
public SoundCloudTrack next ( ) { mCurrentTrackIndex = ( mCurrentTrackIndex + 1 ) % mSoundCloudPlaylist . getTracks ( ) . size ( ) ; return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; }
Retrieve the next track .
14,334
public SoundCloudTrack previous ( ) { int tracks = mSoundCloudPlaylist . getTracks ( ) . size ( ) ; mCurrentTrackIndex = ( tracks + mCurrentTrackIndex - 1 ) % tracks ; return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; }
Retrieve the previous track .
14,335
void setPlayingTrack ( int playingTrackPosition ) { if ( playingTrackPosition < 0 || playingTrackPosition >= mSoundCloudPlaylist . getTracks ( ) . size ( ) ) { throw new IllegalArgumentException ( "No tracks a the position " + playingTrackPosition ) ; } mCurrentTrackIndex = playingTrackPosition ; }
Allow to set the current playing song index . private package .
14,336
protected String getChannelName ( final HttpServletRequest request ) { final String path = request . getPathInfo ( ) ; return path == null ? "" : path . startsWith ( "/" ) ? path . substring ( 1 ) : path ; }
Extracts the name of the channel the client that invoked a request wants to connect to .
14,337
public void destroy ( ) { synchronized ( channels ) { isCurrentlyShutingDown = true ; for ( final SynchronizeFXTomcatChannel server : channels . values ( ) ) { server . shutdown ( ) ; } servers . clear ( ) ; channels . clear ( ) ; isCurrentlyShutingDown = false ; } }
Disconnect all clients an clear the connections when the handler is destroyed by CDI .
14,338
public < T > void registerSerializableClass ( final Class < T > clazz , final Serializer < T > serializer ) { kryo . registerSerializableClass ( clazz , serializer ) ; }
Registers a class that may be send over the network .
14,339
public static NotificationManager getInstance ( Context context ) { if ( sInstance == null ) { sInstance = new NotificationManager ( context ) ; } return sInstance ; }
Encapsulate player notification behaviour .
14,340
private void initializeArtworkTarget ( ) { mThumbnailArtworkTarget = new Target ( ) { public void onBitmapLoaded ( Bitmap bitmap , Picasso . LoadedFrom from ) { mNotificationView . setImageViewBitmap ( R . id . simple_sound_cloud_notification_thumbnail , bitmap ) ; mNotificationExpandedView . setImageViewBitmap ( R . id . simple_sound_cloud_notification_thumbnail , bitmap ) ; mNotificationManager . notify ( NOTIFICATION_ID , buildNotification ( ) ) ; } public void onBitmapFailed ( Drawable errorDrawable ) { } public void onPrepareLoad ( Drawable placeHolderDrawable ) { } } ; }
Initialize target used to load artwork asynchronously .
14,341
private void initNotificationBuilder ( Context context ) { mNotificationBuilder = new NotificationCompat . Builder ( context ) ; mNotificationView = new RemoteViews ( context . getPackageName ( ) , R . layout . simple_sound_cloud_notification ) ; mNotificationExpandedView = new RemoteViews ( context . getPackageName ( ) , R . layout . simple_sound_cloud_notification_expanded ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { addSmallIcon ( mNotificationView ) ; addSmallIcon ( mNotificationExpandedView ) ; } mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_previous , mPreviousPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_previous , mPreviousPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_next , mNextPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_next , mNextPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_play , mTogglePlaybackPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_play , mTogglePlaybackPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_clear , mClearPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_clear , mClearPendingIntent ) ; mNotificationBuilder . setSmallIcon ( mNotificationConfig . getNotificationIcon ( ) ) ; mNotificationBuilder . setContent ( mNotificationView ) ; mNotificationBuilder . setPriority ( NotificationCompat . PRIORITY_HIGH ) ; mNotificationBuilder . setStyle ( new NotificationCompat . DecoratedCustomViewStyle ( ) ) ; Class < ? > playerActivity = mNotificationConfig . getNotificationActivity ( ) ; if ( playerActivity != null ) { Intent i = new Intent ( context , playerActivity ) ; PendingIntent contentIntent = PendingIntent . getActivity ( context , REQUEST_DISPLAYING_CONTROLLER , i , PendingIntent . FLAG_UPDATE_CURRENT ) ; mNotificationBuilder . setContentIntent ( contentIntent ) ; } }
Init all static components of the notification .
14,342
private void addSmallIcon ( RemoteViews notificationView ) { notificationView . setInt ( R . id . simple_sound_cloud_notification_icon , "setBackgroundResource" , mNotificationConfig . getNotificationIconBackground ( ) ) ; notificationView . setImageViewResource ( R . id . simple_sound_cloud_notification_icon , mNotificationConfig . getNotificationIcon ( ) ) ; }
Add the small right icon for Lollipop device .
14,343
static public boolean isValidTemplateName ( String name ) { if ( ! validTemplateNameChars . matcher ( name ) . matches ( ) ) { return false ; } for ( String t : name . split ( "/" ) ) { if ( "" . equals ( t ) || t . startsWith ( "." ) ) { return false ; } } return true ; }
Check to see if the given name is a valid template name . Valid template names may include only letters digits underscores hyphens periods pluses and slashes . In addition each term when split by slashes must not be empty and must not start with a period . The second case excludes potential hidden files and special names like . and .. .
14,344
public Object execute ( Context context , boolean runStatic ) { for ( Statement s : ( ( runStatic ) ? staticStatements : normalStatements ) ) { s . execute ( context ) ; } return null ; }
Execute each of the statements in turn .
14,345
public static boolean checkValidInclude ( TemplateType includeeType , TemplateType includedType ) { return allowedIncludes [ includeeType . ordinal ( ) ] [ includedType . ordinal ( ) ] ; }
Determine whether a particular include combination is legal .
14,346
public void templateNameVerification ( String expectedName ) throws SyntaxException { if ( ! name . equals ( expectedName ) ) { throw SyntaxException . create ( null , source , MSG_MISNAMED_TPL , expectedName ) ; } }
Check that the internal template name matches the expected template name .
14,347
public Observable < ArrayList < SoundCloudTrack > > getArtistTracks ( ) { checkState ( ) ; if ( mCacheRam . tracks . size ( ) != 0 ) { return Observable . create ( new Observable . OnSubscribe < ArrayList < SoundCloudTrack > > ( ) { public void call ( Subscriber < ? super ArrayList < SoundCloudTrack > > subscriber ) { subscriber . onNext ( mCacheRam . tracks ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getUserTracks ( mArtistName ) . map ( RxParser . PARSE_USER_TRACKS ) . map ( cacheTracks ( ) ) ; } }
Retrieve the public tracks of the supported artist .
14,348
public Observable < SoundCloudUser > getArtistProfile ( ) { checkState ( ) ; if ( mCacheRam . artistProfile != null ) { return Observable . create ( new Observable . OnSubscribe < SoundCloudUser > ( ) { public void call ( Subscriber < ? super SoundCloudUser > subscriber ) { subscriber . onNext ( mCacheRam . artistProfile ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getUser ( mArtistName ) . map ( RxParser . PARSE_USER ) . map ( cacheArtistProfile ( ) ) ; } }
Retrieve SoundCloud artist profile .
14,349
public Observable < ArrayList < SoundCloudComment > > getTrackComments ( final SoundCloudTrack track ) { checkState ( ) ; if ( mCacheRam . tracksComments . get ( track . getId ( ) ) != null ) { return Observable . create ( new Observable . OnSubscribe < ArrayList < SoundCloudComment > > ( ) { public void call ( Subscriber < ? super ArrayList < SoundCloudComment > > subscriber ) { subscriber . onNext ( mCacheRam . tracksComments . get ( track . getId ( ) ) ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getTrackComments ( track . getId ( ) ) . map ( RxParser . PARSE_COMMENTS ) . map ( cacheTrackComments ( ) ) ; } }
Retrieve comments related to a track of the supported artist .
14,350
private Func1 < SoundCloudUser , SoundCloudUser > cacheArtistProfile ( ) { return new Func1 < SoundCloudUser , SoundCloudUser > ( ) { public SoundCloudUser call ( SoundCloudUser soundCloudUser ) { mCacheRam . artistProfile = soundCloudUser ; return soundCloudUser ; } } ; }
Cache the artist profile retrieved from network in RAM to avoid requesting SoundCloud API for next call .
14,351
private Func1 < ArrayList < SoundCloudComment > , ArrayList < SoundCloudComment > > cacheTrackComments ( ) { return new Func1 < ArrayList < SoundCloudComment > , ArrayList < SoundCloudComment > > ( ) { public ArrayList < SoundCloudComment > call ( ArrayList < SoundCloudComment > trackComments ) { if ( trackComments . size ( ) > 0 ) { mCacheRam . tracksComments . put ( trackComments . get ( 0 ) . getTrackId ( ) , trackComments ) ; } return trackComments ; } } ; }
Cache the comments linked to a track retrieved from network in RAM to avoid requesting SoundCloud API for next call .
14,352
private Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > cacheTracks ( ) { return new Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > ( ) { public ArrayList < SoundCloudTrack > call ( ArrayList < SoundCloudTrack > soundCloudTracks ) { if ( soundCloudTracks . size ( ) > 0 ) { mCacheRam . tracks = soundCloudTracks ; } return soundCloudTracks ; } } ; }
Cache the tracks list of the supported artist retrieved from network in RAM to avoid requesting SoundCloud API for next call .
14,353
protected Term [ ] calculateTerms ( Context context ) throws EvaluationException { Term [ ] terms = new Term [ ops . length ] ; for ( int i = 0 ; i < ops . length ; i ++ ) { terms [ i ] = TermFactory . create ( ops [ i ] . execute ( context ) ) ; } return terms ; }
A utility method that creates a list of terms from the given arguments .
14,354
public void cleanReferenceCache ( ) { final long now = currentDateSupplier . get ( ) . getTime ( ) ; final Iterator < HardReference > it = hardReferences . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . keeptSince . getTime ( ) + REFERENCE_KEEPING_TIME <= now ) { it . remove ( ) ; } } }
Checks and cleans cached references that have timed out .
14,355
Iterable < Object > getHardReferences ( ) { final List < Object > references = new ArrayList < Object > ( hardReferences . size ( ) ) ; for ( final HardReference reference : hardReferences ) { references . add ( reference . referenceToKeep ) ; } return references ; }
The list of all references that are currently kept .
14,356
public Element execute ( Context context ) { assert ( ops . length == 2 || ops . length == 3 ) ; boolean condition = false ; try { condition = ( ( BooleanProperty ) ops [ 0 ] . execute ( context ) ) . getValue ( ) ; } catch ( ClassCastException cce ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_IF_ELSE_TEST ) , sourceRange ) ; } Operation op = null ; if ( condition ) { op = ops [ 1 ] ; } else if ( ops . length > 2 ) { op = ops [ 2 ] ; } else { op = Undef . VALUE ; } return op . execute ( context ) ; }
Perform the if statement . It will pop a boolean from the data stack . If that boolean is false the next operand if popped from the operand stack ; if true nothing is done .
14,357
public void stop ( ) { System . out . print ( "Stopping the client..." ) ; client . disconnect ( ) ; System . out . println ( "done" ) ; }
Disconnect the client when the application is closed .
14,358
public static DeprecationWarnings getDeprecationWarnings ( int deprecationLevel , boolean failOnWarn ) { if ( deprecationLevel < 0 ) { return DeprecationWarnings . OFF ; } else { return failOnWarn ? DeprecationWarnings . FATAL : DeprecationWarnings . ON ; } }
Utility method to turn old options into new deprecation flag .
14,359
public static CompilerOptions createCheckSyntaxOptions ( DeprecationWarnings deprecationWarnings ) { Pattern debugNsInclude = null ; Pattern debugNsExclude = null ; int maxIteration = 5000 ; int maxRecursion = 50 ; Set < Formatter > formatters = new HashSet < Formatter > ( ) ; File outputDirectory = null ; File annotationDirectory = null ; File annotationBaseDirectory = null ; LinkedList < File > includeDirectories = new LinkedList < File > ( ) ; try { return new CompilerOptions ( debugNsInclude , debugNsExclude , maxIteration , maxRecursion , formatters , outputDirectory , includeDirectories , deprecationWarnings , annotationDirectory , annotationBaseDirectory , null , 0 ) ; } catch ( SyntaxException consumed ) { throw CompilerError . create ( MSG_FILE_BUG_REPORT ) ; } }
Create a CompilerOptions object that is appropriate for just doing a syntax check .
14,360
private void checkDirectory ( File d , String dtype ) { if ( ! d . isAbsolute ( ) ) { throw new IllegalArgumentException ( dtype + " directory must be an absolute path (" + d . getPath ( ) + ")" ) ; } if ( ! d . exists ( ) ) { throw new IllegalArgumentException ( dtype + " directory does not exist (" + d . getPath ( ) + ")" ) ; } if ( ! d . isDirectory ( ) ) { throw new IllegalArgumentException ( dtype + " directory value is not a directory (" + d . getPath ( ) + ")" ) ; } }
A private utility function to verify that the directory is really a directory exists and absolute .
14,361
public Set < File > resolveFileList ( List < String > objectNames , Collection < File > tplFiles ) { Set < File > filesToProcess = new TreeSet < File > ( ) ; if ( tplFiles != null ) { filesToProcess . addAll ( tplFiles ) ; } if ( objectNames != null ) { for ( String oname : objectNames ) { SourceFile source = sourceRepository . retrievePanSource ( oname ) ; if ( ! source . isAbsent ( ) ) { filesToProcess . add ( source . getPath ( ) ) ; } else { throw EvaluationException . create ( ( SourceRange ) null , ( Context ) null , MSG_CANNOT_LOCATE_OBJECT_TEMPLATE , oname ) ; } } } return Collections . unmodifiableSet ( filesToProcess ) ; }
Resolve a list of object template names and template Files to a set of files based on this instance s include directories .
14,362
public boolean checkDebugEnabled ( String tplName ) { if ( debugNsExclude != null && debugNsExclude . matcher ( tplName ) . matches ( ) ) { return false ; } if ( debugNsInclude != null && debugNsInclude . matcher ( tplName ) . matches ( ) ) { return true ; } return false ; }
A utility function that checks a given template name against the list of debug include and exclude patterns .
14,363
public static Set < Formatter > getFormatters ( String s ) { HashSet < Formatter > formatters = new HashSet < Formatter > ( ) ; String [ ] names = s . trim ( ) . split ( "\\s*,\\s*" ) ; for ( String fname : names ) { if ( "text" . equals ( fname ) ) { formatters . add ( TxtFormatter . getInstance ( ) ) ; } else if ( "json" . equals ( fname ) ) { formatters . add ( JsonFormatter . getInstance ( ) ) ; } else if ( "json.gz" . equals ( fname ) ) { formatters . add ( JsonGzipFormatter . getInstance ( ) ) ; } else if ( "dot" . equals ( fname ) ) { formatters . add ( DotFormatter . getInstance ( ) ) ; } else if ( "pan" . equals ( fname ) ) { formatters . add ( PanFormatter . getInstance ( ) ) ; } else if ( "pan.gz" . equals ( fname ) ) { formatters . add ( PanGzipFormatter . getInstance ( ) ) ; } else if ( "xml" . equals ( fname ) ) { formatters . add ( XmlFormatter . getInstance ( ) ) ; } else if ( "xml.gz" . equals ( fname ) ) { formatters . add ( XmlGzipFormatter . getInstance ( ) ) ; } else if ( "dep" . equals ( fname ) ) { formatters . add ( DepFormatter . getInstance ( ) ) ; } else if ( "dep.gz" . equals ( fname ) ) { formatters . add ( DepGzipFormatter . getInstance ( ) ) ; } else if ( "null" . equals ( fname ) ) { formatters . add ( NullFormatter . getInstance ( ) ) ; } else if ( "none" . equals ( fname ) ) { } } return formatters ; }
be used for a compilation .
14,364
public static void startActivity ( Context context , String artistName ) { Intent i = new Intent ( context , ArtistActivity . class ) ; i . putExtra ( BUNDLE_KEY_ARTIST_NAME , artistName ) ; context . startActivity ( i ) ; }
Start an ArtistActivity for a given artist name . Start activity pattern .
14,365
private void setTrackListPadding ( ) { mPlaylistRecyclerView . getViewTreeObserver ( ) . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { public boolean onPreDraw ( ) { mPlaylistRecyclerView . getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; int headerListHeight = getResources ( ) . getDimensionPixelOffset ( R . dimen . playback_view_height ) ; mPlaylistRecyclerView . setPadding ( 0 , mPlaylistRecyclerView . getHeight ( ) - headerListHeight , 0 , 0 ) ; mPlaylistRecyclerView . setAdapter ( mPlaylistAdapter ) ; new SwipeToDismissGesture . Builder ( SwipeToDismissDirection . HORIZONTAL ) . on ( mPlaylistRecyclerView ) . apply ( new DismissStrategy ( ) ) . backgroundColor ( getResources ( ) . getColor ( R . color . grey ) ) . build ( ) ; if ( mPlaylistTracks . isEmpty ( ) ) { mPlaybackView . setTranslationY ( headerListHeight ) ; } return true ; } } ) ; }
Used to position the track list at the bottom of the screen .
14,366
private void getArtistData ( ) { mRetrievedTracks . clear ( ) ; mAdapter . notifyDataSetChanged ( ) ; mTracksSubscription = mCheerleaderClient . getArtistTracks ( ) . subscribeOn ( Schedulers . io ( ) ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribe ( displayTracks ( ) ) ; mProfileSubscription = mCheerleaderClient . getArtistProfile ( ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribeOn ( Schedulers . io ( ) ) . subscribe ( displayArtist ( ) ) ; }
Used to retrieved the tracks of the artist as well as artist details .
14,367
private String getExtraArtistName ( ) { Bundle extras = getIntent ( ) . getExtras ( ) ; if ( extras == null || ! extras . containsKey ( BUNDLE_KEY_ARTIST_NAME ) ) { return "" ; } return extras . getString ( BUNDLE_KEY_ARTIST_NAME ) ; }
Used to retrieve the artist name for the bundle .
14,368
void newMessage ( final byte [ ] message , final Session session ) { callback . recive ( serializer . deserialize ( message ) , session ) ; }
Inform this channel that one of its client has send a message .
14,369
public void startModelWalking ( ) { doWhenModelWalkerFinished ( ActionType . MODEL_WALKNG , new Runnable ( ) { public void run ( ) { memberLock . lock ( ) ; modelWalkingInProgess = true ; memberLock . unlock ( ) ; } } ) ; }
Informs this synchronizer that a new model walking process has started .
14,370
public void doWhenModelWalkerFinished ( final ActionType type , final Runnable action ) { memberLock . lock ( ) ; if ( ! modelWalkingInProgess ) { memberLock . unlock ( ) ; action . run ( ) ; return ; } CountDownLatch latch = new CountDownLatch ( 1 ) ; Set < CountDownLatch > latches = getLocksForAction ( type ) ; latches . add ( latch ) ; memberLock . unlock ( ) ; awaitUninterupptetly ( latch ) ; action . run ( ) ; memberLock . lock ( ) ; latches . remove ( latch ) ; runNext ( ) ; memberLock . unlock ( ) ; }
Lets the current thread sleep until a currently running model walking thread has finished .
14,371
public static void pause ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_PAUSE_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; }
Pause the SoundCloud player .
14,372
public static void resume ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_RESUME_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; }
Resume the SoundCloud player .
14,373
public static void stop ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_STOP_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; }
Stop the SoundCloud player .
14,374
public static void registerListener ( Context context , PlaybackListener listener ) { IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( PlaybackListener . ACTION_ON_TRACK_PLAYED ) ; filter . addAction ( PlaybackListener . ACTION_ON_PLAYER_PAUSED ) ; filter . addAction ( PlaybackListener . ACTION_ON_SEEK_COMPLETE ) ; filter . addAction ( PlaybackListener . ACTION_ON_PLAYER_DESTROYED ) ; filter . addAction ( PlaybackListener . ACTION_ON_BUFFERING_STARTED ) ; filter . addAction ( PlaybackListener . ACTION_ON_BUFFERING_ENDED ) ; filter . addAction ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . registerReceiver ( listener , filter ) ; }
Register a listener to catch player event .
14,375
public static void unregisterListener ( Context context , PlaybackListener listener ) { LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . unregisterReceiver ( listener ) ; }
Unregister a registered listener .
14,376
private void resume ( ) { if ( mIsPaused ) { mIsPaused = false ; mIsPausedAfterAudioFocusChanged = false ; if ( mAudioManager . requestAudioFocus ( this , AudioManager . STREAM_MUSIC , AudioManager . AUDIOFOCUS_GAIN ) == AudioManager . AUDIOFOCUS_REQUEST_GRANTED ) { mMediaPlayer . start ( ) ; Intent intent = new Intent ( PlaybackListener . ACTION_ON_TRACK_PLAYED ) ; intent . putExtra ( PlaybackListener . EXTRA_KEY_TRACK , mPlayerPlaylist . getCurrentTrack ( ) ) ; mLocalBroadcastManager . sendBroadcast ( intent ) ; updateNotification ( ) ; mMediaSession . setPlaybackState ( MediaSessionWrapper . PLAYBACK_STATE_PLAYING ) ; resumeTimer ( ) ; } } }
Resume the playback .
14,377
private void startTimer ( long duration ) { if ( mCountDown != null ) { mCountDown . cancel ( ) ; mCountDown = null ; } mCountDown = new CountDownTimer ( duration , 1000 ) { public void onTick ( long millisUntilFinished ) { Intent i = new Intent ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; i . putExtra ( PlaybackListener . EXTRA_KEY_CURRENT_TIME , mMediaPlayer . getCurrentPosition ( ) ) ; mLocalBroadcastManager . sendBroadcast ( i ) ; } public void onFinish ( ) { Intent i = new Intent ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; i . putExtra ( PlaybackListener . EXTRA_KEY_CURRENT_TIME , ( int ) mPlayerPlaylist . getCurrentTrack ( ) . getDurationInMilli ( ) ) ; mLocalBroadcastManager . sendBroadcast ( i ) ; } } ; mCountDown . start ( ) ; }
Start internal timer used to propagate the playback position .
14,378
private void readObject ( java . io . ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; hashcode = value . hashCode ( ) ; }
This method is used to restore the volatile hashcode value when deserializing a Property object .
14,379
public UUID registerIfUnknown ( final Object object ) { final Optional < UUID > id = getId ( object ) ; if ( ! id . isPresent ( ) ) { return registerObject ( object ) ; } return id . get ( ) ; }
Registers an object in the meta model if it is not already registered .
14,380
public void registerObject ( final Object object , final UUID id ) { objectToId . put ( object , id ) ; idToObject . put ( id , object ) ; }
Registers an object in this model identified by a pre existing id .
14,381
private UUID registerObject ( final Object object ) { UUID id = UUID . randomUUID ( ) ; registerObject ( object , id ) ; return id ; }
Registers an object in this model identified by a newly created id .
14,382
public static boolean isXMLNameStart ( int codepoint ) { if ( codepoint >= Character . codePointAt ( "A" , 0 ) && codepoint <= Character . codePointAt ( "Z" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "_" , 0 ) ) { return true ; } else if ( codepoint >= Character . codePointAt ( "a" , 0 ) && codepoint <= Character . codePointAt ( "z" , 0 ) ) { return true ; } else if ( codepoint >= 0xC0 && codepoint <= 0xD6 ) { return true ; } else if ( codepoint >= 0xD8 && codepoint <= 0xF6 ) { return true ; } else if ( codepoint >= 0xF8 && codepoint <= 0x2FF ) { return true ; } else if ( codepoint >= 0x370 && codepoint <= 0x37D ) { return true ; } else if ( codepoint >= 0x37F && codepoint <= 0x1FFF ) { return true ; } else if ( codepoint >= 0x200C && codepoint <= 0x200D ) { return true ; } else if ( codepoint >= 0x2070 && codepoint <= 0x218F ) { return true ; } else if ( codepoint >= 0x2C00 && codepoint <= 0x2FEF ) { return true ; } else if ( codepoint >= 0x3001 && codepoint <= 0xD7FF ) { return true ; } else if ( codepoint >= 0xF900 && codepoint <= 0xFDCF ) { return true ; } else if ( codepoint >= 0xFDF0 && codepoint <= 0xFFFD ) { return true ; } else if ( codepoint >= 0x10000 && codepoint <= 0xEFFFF ) { return true ; } else { return false ; } }
Determine if the given character is a legal starting character for an XML name . Note that although a colon is a legal value its use is strongly discouraged and this method will return false for a colon .
14,383
public static boolean isXMLNamePart ( int codepoint ) { if ( isXMLNameStart ( codepoint ) ) { return true ; } else if ( codepoint >= Character . codePointAt ( "0" , 0 ) && codepoint <= Character . codePointAt ( "9" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "-" , 0 ) ) { return true ; } else if ( codepoint == Character . codePointAt ( "." , 0 ) ) { return true ; } else if ( codepoint == 0xB7 ) { return true ; } else if ( codepoint >= 0x0300 && codepoint <= 0x036F ) { return true ; } else if ( codepoint >= 0x203F && codepoint <= 0x2040 ) { return true ; } else { return false ; } }
Determine if the given character is a legal non - starting character for an XML name . Note that although a colon is a legal value its use is strongly discouraged and this method will return false for a colon .
14,384
public static boolean isValidXMLCharacter ( int codepoint ) { if ( codepoint >= 0x20 && codepoint <= 0xD7FF ) { return true ; } else if ( codepoint == 0x9 || codepoint == 0xA || codepoint == 0xD ) { return true ; } else if ( codepoint >= 0xE000 && codepoint <= 0xFFFD ) { return true ; } else if ( codepoint >= 0x10000 && codepoint <= 0x10FFFF ) { return true ; } else { return false ; } }
Determine if a given UNICODE character can appear in a valid XML file . The allowed characters are 0x9 0xA 0xD 0x20 - 0xD7FF 0xE000 - 0xFFFD and 0x100000 - 0x10FFFF ; all other characters may not appear in an XML file .
14,385
public static boolean isValidXMLName ( String s ) { if ( s == null || "" . equals ( s ) ) { return false ; } if ( ! isXMLNameStart ( s . codePointAt ( 0 ) ) ) { return false ; } int length = s . length ( ) ; int index = 1 ; while ( index < length ) { int codePoint = s . codePointAt ( index ) ; if ( ! isXMLNamePart ( codePoint ) ) { return false ; } index += Character . charCount ( codePoint ) ; } if ( s . toLowerCase ( ) . startsWith ( "xml" ) ) { return false ; } return true ; }
Determine if the given string is a valid XML name .
14,386
public static boolean isValidXMLString ( String s ) { int length = s . length ( ) ; int index = 0 ; while ( index < length ) { int codePoint = s . codePointAt ( index ) ; if ( ! isValidXMLCharacter ( codePoint ) ) { return false ; } index += Character . charCount ( codePoint ) ; } return true ; }
Determine if the given string can be written to an XML file without encoding . This will be the case so long as the string does not contain illegal XML characters .
14,387
public static String encodeAsXMLName ( String s ) { StringBuilder sb = new StringBuilder ( "_" ) ; for ( byte b : s . getBytes ( Charset . forName ( "UTF-8" ) ) ) { sb . append ( Integer . toHexString ( ( b >>> 4 ) & 0xF ) ) ; sb . append ( Integer . toHexString ( b & 0xF ) ) ; } return sb . toString ( ) ; }
This will encode the given string as a valid XML name . The format will be an initial underscore followed by the hexadecimal representation of the string .
14,388
public String formatErrors ( ) { if ( errors . size ( ) > 0 ) { StringBuilder results = new StringBuilder ( ) ; for ( Throwable t : errors ) { results . append ( t . getMessage ( ) ) ; results . append ( "\n" ) ; if ( t instanceof NullPointerException || t instanceof CompilerError ) { results . append ( formatStackTrace ( t ) ) ; } else if ( t instanceof SystemException ) { results . append ( formatStackTrace ( t ) ) ; Throwable cause = t . getCause ( ) ; if ( cause != null ) { results . append ( "\nCause:\n" ) ; results . append ( cause . getMessage ( ) ) ; results . append ( "\n" ) ; } results . append ( formatStackTrace ( t ) ) ; } } return results . toString ( ) ; } else { return null ; } }
Format the exceptions thrown during the compilation process . A null value will be returned if no exceptions were thrown .
14,389
private void init ( ) { this . setOrientation ( LinearLayout . VERTICAL ) ; mLayoutParams = new LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . WRAP_CONTENT ) ; }
Initialize the view .
14,390
public static void createParentDirectories ( File file ) { File parent = file . getParentFile ( ) ; if ( ! parent . isDirectory ( ) ) { boolean created = parent . mkdirs ( ) ; if ( ! created && ! parent . isDirectory ( ) ) { throw new SystemException ( MessageUtils . format ( MSG_CANNOT_CREATE_OUTPUT_DIRECTORY , parent . getAbsolutePath ( ) ) , parent ) ; } } }
Creates parent directories of the given file . The file must be absolute .
14,391
protected static void checkStaticIndexes ( SourceRange sourceRange , Operation ... operations ) throws SyntaxException { for ( int i = 0 ; i < operations . length ; i ++ ) { if ( operations [ i ] instanceof Element ) { try { TermFactory . create ( ( Element ) operations [ i ] ) ; } catch ( EvaluationException ee ) { throw SyntaxException . create ( sourceRange , MSG_INVALID_TERM , i ) ; } } } }
Ensure that any constant indexes in the operation list are valid terms .
14,392
protected void validName ( String name ) throws SyntaxException { for ( String varName : automaticVariables ) { if ( varName . equals ( name ) ) { throw SyntaxException . create ( getSourceRange ( ) , MSG_AUTO_VAR_CANNOT_BE_SET , varName ) ; } } }
A utility method to determine if the variable name collides with one of the reserved automatic variables .
14,393
private String getVersion ( boolean verbose ) { try { InputStream stream = getClass ( ) . getResourceAsStream ( "/version.properties" ) ; Properties props = new Properties ( ) ; props . load ( stream ) ; if ( verbose ) { return String . format ( "Version=%s, build date=%s" , props . getProperty ( "version" ) , props . getProperty ( "buildDate" ) ) ; } else { return props . getProperty ( "version" ) ; } } catch ( IOException e ) { log . error ( "Unable to retrieve version" , e ) ; return "unknown" ; } }
Retrieve the current version .
14,394
private void setDefaults ( ) { if ( xsdInput == null ) { setXsdInput ( DEFAULT_INPUT_FOLDER_PATH ) ; } if ( output == null ) { setOutput ( DEFAULT_OUTPUT_FOLDER_PATH ) ; } if ( avroNamespacePrefix == null ) { setAvroNamespacePrefix ( DEFAULT_AVRO_NAMESPACE_PREFIX ) ; } }
Make sure mandatory parameters have default values .
14,395
private void applyMax ( Dimension dim ) { if ( getMaxHeight ( ) > 0 ) { dim . height = Math . min ( dim . height , getMaxHeight ( ) ) ; } if ( getMaxWidth ( ) > 0 ) { dim . width = Math . min ( dim . width , getMaxWidth ( ) ) ; } }
Applies the maximum height and width to the dimension .
14,396
protected void analyzeElVars ( final T descriptor , final DescriptorContext context ) { descriptor . el = ElAnalyzer . analyzeQuery ( context . generics , descriptor . command ) ; }
Analyze query string for el variables and creates el descriptor .
14,397
protected void analyzeParameters ( final T descriptor , final DescriptorContext context ) { final CommandParamsContext paramsContext = new CommandParamsContext ( context ) ; spiService . process ( descriptor , paramsContext ) ; }
Analyze method parameters search for extensions and prepare parameters context .
14,398
private void wrapText ( ) { if ( getFont ( ) == null || text == null ) { return ; } FontMetrics fm = getFontMetrics ( getFont ( ) ) ; StringBuilder tempText = new StringBuilder ( ) ; StringBuilder finalText = new StringBuilder ( "<html>" ) ; finalText . append ( "<STYLE type='text/css'>BODY { text-align: " ) ; finalText . append ( align . name ( ) . toLowerCase ( ) ) ; finalText . append ( "}</STYLE><BODY>" ) ; ArrayList < String > words = new ArrayList < String > ( ) ; text = text . replaceAll ( "\n" , "<BR>" ) ; String split [ ] = text . split ( "<BR>" ) ; for ( int i = 0 ; i < split . length ; i ++ ) { if ( split [ i ] . length ( ) > 0 ) { String split2 [ ] = split [ i ] . split ( "[ \\t\\x0B\\f\\r]+" ) ; for ( int j = 0 ; j < split2 . length ; j ++ ) { if ( split2 [ j ] . length ( ) > 0 ) { words . add ( split2 [ j ] ) ; } } } if ( i < split . length - 1 ) { words . add ( "<BR>" ) ; } } for ( String word : words ) { if ( word . equals ( "<BR>" ) ) { finalText . append ( "<BR>" ) ; tempText . setLength ( 0 ) ; } else { tempText . append ( " " ) ; tempText . append ( word ) ; int tempWidth = SwingUtilities . computeStringWidth ( fm , tempText . toString ( ) . trim ( ) ) ; if ( ( wrapWidth > 0 && tempWidth > wrapWidth ) ) { int wordSize = SwingUtilities . computeStringWidth ( fm , word ) ; if ( wordSize >= wrapWidth ) { finalText . append ( "..." ) ; break ; } finalText . append ( "<BR>" ) ; tempText . setLength ( 0 ) ; tempText . append ( word ) ; } if ( tempText . length ( ) > 0 ) { finalText . append ( " " ) ; } finalText . append ( word ) ; } } finalText . append ( "</BODY></html>" ) ; super . setText ( finalText . toString ( ) ) ; }
The plain text is converted to HTML code . The wrap locations are calculated with the defined wrap width and component width .
14,399
public void checkFieldsCompatible ( final String ... fields ) { final Set < String > indexFields = Sets . newHashSet ( index . getDefinition ( ) . getFields ( ) ) ; final Joiner joiner = Joiner . on ( "," ) ; check ( indexFields . equals ( Sets . newHashSet ( fields ) ) , "Existing index '%s' (class '%s') fields '%s' are different from '%s'." , index . getName ( ) , index . getDefinition ( ) . getClassName ( ) , joiner . join ( indexFields ) , joiner . join ( fields ) ) ; }
Checks if existing index consists of exactly the same fields . If not error thrown to indicate probable programmer error .