idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
2,800
public void setTextSize ( int sizeSp ) { mTextSize = sizeSp * mDisplayMetrics . scaledDensity ; mTextPaint . setTextSize ( mTextSize ) ; invalidate ( ) ; }
Sets the text size .
2,801
public void setStrokeWidth ( int widthDp ) { mStrokeWidth = widthDp * mDisplayMetrics . density ; mStrokePaint . setStrokeWidth ( mStrokeWidth ) ; invalidate ( ) ; }
Set the stroke width .
2,802
public Lyrics getLyrics ( int trackID ) throws MusixMatchException { Lyrics lyrics = null ; LyricsGetMessage message = null ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . TRACK_ID , new String ( "" + trackID ) ) ; String response = null ; response = MusixMatchRequest . sendRequest ( Helper . getURLString ( Methods . TRACK_LYRICS_GET , params ) ) ; Gson gson = new Gson ( ) ; try { message = gson . fromJson ( response , LyricsGetMessage . class ) ; } catch ( JsonParseException jpe ) { handleErrorResponse ( response ) ; } lyrics = message . getContainer ( ) . getBody ( ) . getLyrics ( ) ; return lyrics ; }
Get Lyrics for the specific trackID .
2,803
public Snippet getSnippet ( int trackID ) throws MusixMatchException { Snippet snippet = null ; SnippetGetMessage message = null ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . TRACK_ID , new String ( "" + trackID ) ) ; String response = null ; response = MusixMatchRequest . sendRequest ( Helper . getURLString ( Methods . TRACK_SNIPPET_GET , params ) ) ; Gson gson = new Gson ( ) ; try { message = gson . fromJson ( response , SnippetGetMessage . class ) ; } catch ( JsonParseException jpe ) { handleErrorResponse ( response ) ; } snippet = message . getContainer ( ) . getBody ( ) . getSnippet ( ) ; return snippet ; }
Get Snippet for the specified trackID .
2,804
public Subtitle getSubtitle ( int trackID ) throws MusixMatchException { Subtitle subtitle = null ; SubtitleGetMessage message = null ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . TRACK_ID , new String ( "" + trackID ) ) ; String response = null ; response = MusixMatchRequest . sendRequest ( Helper . getURLString ( Methods . TRACK_SUBTITLE_GET , params ) ) ; Gson gson = new Gson ( ) ; try { message = gson . fromJson ( response , SubtitleGetMessage . class ) ; } catch ( JsonParseException jpe ) { jpe . printStackTrace ( ) ; handleErrorResponse ( response ) ; } subtitle = message . getContainer ( ) . getBody ( ) . getSubtitle ( ) ; return subtitle ; }
Get Subtitle for the specific trackID .
2,805
public List < Track > searchTracks ( String q , String q_artist , String q_track , int page , int pageSize , boolean f_has_lyrics ) throws MusixMatchException { List < Track > trackList = null ; TrackSeachMessage message = null ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . QUERY , q ) ; params . put ( Constants . QUERY_ARTIST , q_artist ) ; params . put ( Constants . QUERY_TRACK , q_track ) ; params . put ( Constants . PAGE , page ) ; params . put ( Constants . PAGE_SIZE , pageSize ) ; if ( f_has_lyrics ) { params . put ( Constants . F_HAS_LYRICS , "1" ) ; } else { params . put ( Constants . F_HAS_LYRICS , "0" ) ; } String response = null ; response = MusixMatchRequest . sendRequest ( Helper . getURLString ( Methods . TRACK_SEARCH , params ) ) ; Gson gson = new Gson ( ) ; try { message = gson . fromJson ( response , TrackSeachMessage . class ) ; } catch ( JsonParseException jpe ) { handleErrorResponse ( response ) ; } int statusCode = message . getTrackMessage ( ) . getHeader ( ) . getStatusCode ( ) ; if ( statusCode > 200 ) { throw new MusixMatchException ( "Status Code is not 200" ) ; } trackList = message . getTrackMessage ( ) . getBody ( ) . getTrack_list ( ) ; return trackList ; }
Search tracks using the given criteria .
2,806
public Track getTrack ( int trackID ) throws MusixMatchException { Track track = new Track ( ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . TRACK_ID , new String ( "" + trackID ) ) ; track = getTrackResponse ( Methods . TRACK_GET , params ) ; return track ; }
Get the track details using the specified trackId .
2,807
public Track getMatchingTrack ( String q_track , String q_artist ) throws MusixMatchException { Track track = new Track ( ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( Constants . API_KEY , apiKey ) ; params . put ( Constants . QUERY_TRACK , q_track ) ; params . put ( Constants . QUERY_ARTIST , q_artist ) ; track = getTrackResponse ( Methods . MATCHER_TRACK_GET , params ) ; return track ; }
Get the most matching track which was retrieved using the search .
2,808
private Track getTrackResponse ( String methodName , Map < String , Object > params ) throws MusixMatchException { Track track = new Track ( ) ; String response = null ; TrackGetMessage message = null ; response = MusixMatchRequest . sendRequest ( Helper . getURLString ( methodName , params ) ) ; Gson gson = new Gson ( ) ; try { message = gson . fromJson ( response , TrackGetMessage . class ) ; } catch ( JsonParseException jpe ) { handleErrorResponse ( response ) ; } TrackData data = message . getTrackMessage ( ) . getBody ( ) . getTrack ( ) ; track . setTrack ( data ) ; return track ; }
Returns the track response which was returned through the query .
2,809
private void handleErrorResponse ( String jsonResponse ) throws MusixMatchException { StatusCode statusCode ; Gson gson = new Gson ( ) ; System . out . println ( jsonResponse ) ; ErrorMessage errMessage = gson . fromJson ( jsonResponse , ErrorMessage . class ) ; int responseCode = errMessage . getMessageContainer ( ) . getHeader ( ) . getStatusCode ( ) ; switch ( responseCode ) { case 400 : statusCode = StatusCode . BAD_SYNTAX ; break ; case 401 : statusCode = StatusCode . AUTH_FAILED ; break ; case 402 : statusCode = StatusCode . LIMIT_REACHED ; break ; case 403 : statusCode = StatusCode . NOT_AUTHORIZED ; break ; case 404 : statusCode = StatusCode . RESOURCE_NOT_FOUND ; break ; case 405 : statusCode = StatusCode . METHOD_NOT_FOUND ; break ; default : statusCode = StatusCode . ERROR ; break ; } throw new MusixMatchException ( statusCode . getStatusMessage ( ) ) ; }
Handle the error response .
2,810
public static String getURLString ( String methodName , Map < String , Object > params ) throws MusixMatchException { String paramString = new String ( ) ; paramString += methodName + "?" ; for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { try { paramString += entry . getKey ( ) + "=" + URLEncoder . encode ( entry . getValue ( ) . toString ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new MusixMatchException ( "Problem encoding " + entry . getValue ( ) , e ) ; } paramString += "&" ; } paramString = paramString . substring ( 0 , paramString . length ( ) - 1 ) ; return paramString ; }
This method is used to get a parameter string from the Map .
2,811
protected static List < Token > baseTokenize ( String text ) { String [ ] words = text . split ( " " ) ; List < Token > tokens = new LinkedList < Token > ( ) ; for ( String word : words ) { tokens . add ( new Token ( word ) ) ; } return tokens ; }
Split the text on spaces and convert each word into a Token
2,812
public static Span findWithin ( List < Repeater < ? > > tags , Span span , Pointer . PointerType pointer , Options options ) { if ( options . isDebug ( ) ) { System . out . println ( "Chronic.findWithin: " + tags + " in " + span ) ; } if ( tags . isEmpty ( ) ) { return span ; } Repeater < ? > head = tags . get ( 0 ) ; List < Repeater < ? > > rest = ( tags . size ( ) > 1 ) ? tags . subList ( 1 , tags . size ( ) ) : new LinkedList < Repeater < ? > > ( ) ; head . setStart ( ( pointer == Pointer . PointerType . FUTURE ) ? span . getBeginCalendar ( ) : span . getEndCalendar ( ) ) ; Span h = head . thisSpan ( PointerType . NONE ) ; if ( span . contains ( h . getBegin ( ) ) || span . contains ( h . getEnd ( ) ) ) { return findWithin ( rest , h , pointer , options ) ; } return null ; }
Recursively finds repeaters within other repeaters . Returns a Span representing the innermost time span or nil if no repeater union could be found
2,813
public void untag ( Class < ? > tagClass ) { Iterator < Tag < ? > > tagIter = _tags . iterator ( ) ; while ( tagIter . hasNext ( ) ) { Tag < ? > tag = tagIter . next ( ) ; if ( tagClass . isInstance ( tag ) ) { tagIter . remove ( ) ; } } }
Remove all tags of the given class
2,814
public Span nextSpan ( Pointer . PointerType pointer ) { if ( getNow ( ) == null ) { throw new IllegalStateException ( "Start point must be set before calling #next" ) ; } return _nextSpan ( pointer ) ; }
returns the next occurance of this repeatable .
2,815
private TreeNode < T > balanceOut ( ) { int balance = height ( left ) - height ( right ) ; if ( balance < - 1 ) { if ( height ( right . left ) > height ( right . right ) ) { this . right = this . right . rightRotate ( ) ; return leftRotate ( ) ; } else { return leftRotate ( ) ; } } else if ( balance > 1 ) { if ( height ( left . right ) > height ( left . left ) ) { this . left = this . left . leftRotate ( ) ; return rightRotate ( ) ; } else return rightRotate ( ) ; } else { return this ; } }
Checks if the subtree rooted at the current node is balanced and balances it if necessary .
2,816
private TreeNode < T > assimilateOverlappingIntervals ( TreeNode < T > from ) { ArrayList < Interval < T > > tmp = new ArrayList < > ( ) ; if ( midpoint . compareTo ( from . midpoint ) < 0 ) { for ( Interval < T > next : from . increasing ) { if ( next . isRightOf ( midpoint ) ) break ; tmp . add ( next ) ; } } else { for ( Interval < T > next : from . decreasing ) { if ( next . isLeftOf ( midpoint ) ) break ; tmp . add ( next ) ; } } from . increasing . removeAll ( tmp ) ; from . decreasing . removeAll ( tmp ) ; increasing . addAll ( tmp ) ; decreasing . addAll ( tmp ) ; if ( from . increasing . size ( ) == 0 ) { return deleteNode ( from ) ; } return from ; }
Transfers all intervals from a target node to the current node if they intersect the middlepoint of the current node . After this operation it is possible that the target node remains empty . If so it needs to be deleted possible causing the subtree to be rebalanced .
2,817
private static < T extends Comparable < ? super T > > TreeNode < T > deleteNode ( TreeNode < T > root ) { if ( root . left == null && root . right == null ) return null ; if ( root . left == null ) { return root . right ; } else { TreeNode < T > node = root . left ; Stack < TreeNode < T > > stack = new Stack < > ( ) ; while ( node . right != null ) { stack . push ( node ) ; node = node . right ; } if ( ! stack . isEmpty ( ) ) { stack . peek ( ) . right = node . left ; node . left = root . left ; } node . right = root . right ; TreeNode < T > newRoot = node ; while ( ! stack . isEmpty ( ) ) { node = stack . pop ( ) ; if ( ! stack . isEmpty ( ) ) stack . peek ( ) . right = newRoot . assimilateOverlappingIntervals ( node ) ; else newRoot . left = newRoot . assimilateOverlappingIntervals ( node ) ; } return newRoot . balanceOut ( ) ; } }
Deletes a node from the tree . The caller of this method needs to check if the node is actually empty because this method only performs the deletion .
2,818
static < T extends Comparable < ? super T > > void rangeQueryLeft ( TreeNode < T > node , Interval < T > query , Set < Interval < T > > result ) { while ( node != null ) { if ( query . contains ( node . midpoint ) ) { result . addAll ( node . increasing ) ; if ( node . right != null ) { for ( Interval < T > next : node . right ) result . add ( next ) ; } node = node . left ; } else { for ( Interval < T > next : node . decreasing ) { if ( next . isLeftOf ( query ) ) break ; result . add ( next ) ; } node = node . right ; } } }
A helper method for the range search used in the interval intersection query in the tree . This corresponds to the left branch of the range search once we find a node whose midpoint is contained in the query interval . All intervals in the left subtree of that node are guaranteed to intersect with the query if they have an endpoint greater or equal than the start of the query interval . Basically this means that every time we branch to the left in the binary search we need to add the whole right subtree to the result set .
2,819
static < T extends Comparable < ? super T > > void rangeQueryRight ( TreeNode < T > node , Interval < T > query , Set < Interval < T > > result ) { while ( node != null ) { if ( query . contains ( node . midpoint ) ) { result . addAll ( node . increasing ) ; if ( node . left != null ) { for ( Interval < T > next : node . left ) result . add ( next ) ; } node = node . right ; } else { for ( Interval < T > next : node . increasing ) { if ( next . isRightOf ( query ) ) break ; result . add ( next ) ; } node = node . left ; } } }
A helper method for the range search used in the interval intersection query in the tree . This corresponds to the right branch of the range search once we find a node whose midpoint is contained in the query interval . All intervals in the right subtree of that node are guaranteed to intersect with the query if they have an endpoint smaller or equal than the end of the query interval . Basically this means that every time we branch to the right in the binary search we need to add the whole left subtree to the result set .
2,820
public boolean isEmpty ( ) { if ( start == null || end == null ) return false ; int compare = start . compareTo ( end ) ; if ( compare > 0 ) return true ; if ( compare == 0 && ( ! isEndInclusive || ! isStartInclusive ) ) return true ; return false ; }
Checks if the current interval contains no points .
2,821
public boolean isPoint ( ) { if ( start == null || end == null ) { return false ; } return start . compareTo ( end ) == 0 && isStartInclusive && isEndInclusive ; }
Determines if the current interval is a single point .
2,822
public boolean contains ( T query ) { if ( isEmpty ( ) || query == null ) { return false ; } int startCompare = start == null ? 1 : query . compareTo ( start ) ; int endCompare = end == null ? - 1 : query . compareTo ( end ) ; if ( startCompare > 0 && endCompare < 0 ) { return true ; } return ( startCompare == 0 && isStartInclusive ) || ( endCompare == 0 && isEndInclusive ) ; }
Determines if the current interval contains a query point .
2,823
public static String getRequestBody ( HttpServletRequest request ) { if ( request . getMethod ( ) . equals ( "GET" ) || request . getMethod ( ) . equals ( "DELETE" ) ) { return null ; } StringBuilder stringBuilder = new StringBuilder ( ) ; BufferedReader bufferedReader = null ; try { InputStream inputStream = request . getInputStream ( ) ; if ( inputStream != null ) { bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; char [ ] charBuffer = new char [ 128 ] ; int bytesRead = - 1 ; while ( ( bytesRead = bufferedReader . read ( charBuffer ) ) > 0 ) { stringBuilder . append ( charBuffer , 0 , bytesRead ) ; } } else { stringBuilder . append ( "" ) ; } } catch ( IOException ex ) { } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException ex ) { } } } if ( ! StringUtils . isEmpty ( stringBuilder ) ) { return stringBuilder . toString ( ) ; } if ( request . getParameterMap ( ) . keySet ( ) . size ( ) > 0 ) { return request . getParameterMap ( ) . keySet ( ) . toArray ( ) [ 0 ] . toString ( ) ; } return null ; }
not easily tested
2,824
private void updatePrograms ( final Uri channelUri , final List < Program > newPrograms ) { new Thread ( new Runnable ( ) { public void run ( ) { final int fetchedProgramsCount = newPrograms . size ( ) ; if ( fetchedProgramsCount == 0 ) { return ; } List < Program > oldPrograms = TvContractUtils . getPrograms ( mContext . getContentResolver ( ) , channelUri ) ; Program firstNewProgram = newPrograms . get ( 0 ) ; int oldProgramsIndex = 0 ; int newProgramsIndex = 0 ; for ( Program program : oldPrograms ) { oldProgramsIndex ++ ; if ( program . getEndTimeUtcMillis ( ) > firstNewProgram . getStartTimeUtcMillis ( ) ) { break ; } } ArrayList < ContentProviderOperation > ops = new ArrayList < > ( ) ; while ( newProgramsIndex < fetchedProgramsCount ) { Program oldProgram = oldProgramsIndex < oldPrograms . size ( ) ? oldPrograms . get ( oldProgramsIndex ) : null ; Program newProgram = newPrograms . get ( newProgramsIndex ) ; boolean addNewProgram = false ; if ( oldProgram != null ) { if ( oldProgram . equals ( newProgram ) ) { oldProgramsIndex ++ ; newProgramsIndex ++ ; } else if ( needsUpdate ( oldProgram , newProgram ) ) { ops . add ( ContentProviderOperation . newUpdate ( TvContract . buildProgramUri ( oldProgram . getProgramId ( ) ) ) . withValues ( newProgram . toContentValues ( ) ) . build ( ) ) ; oldProgramsIndex ++ ; newProgramsIndex ++ ; } else if ( oldProgram . getEndTimeUtcMillis ( ) < newProgram . getEndTimeUtcMillis ( ) ) { ops . add ( ContentProviderOperation . newDelete ( TvContract . buildProgramUri ( oldProgram . getProgramId ( ) ) ) . build ( ) ) ; oldProgramsIndex ++ ; } else { addNewProgram = true ; newProgramsIndex ++ ; } } else { addNewProgram = true ; newProgramsIndex ++ ; } if ( addNewProgram ) { ops . add ( ContentProviderOperation . newInsert ( TvContract . Programs . CONTENT_URI ) . withValues ( newProgram . toContentValues ( ) ) . build ( ) ) ; } if ( ops . size ( ) > BATCH_OPERATION_COUNT || newProgramsIndex >= fetchedProgramsCount ) { try { mContext . getContentResolver ( ) . applyBatch ( TvContract . AUTHORITY , ops ) ; Log . d ( TAG , "Applying batch update" ) ; } catch ( SecurityException | RemoteException | OperationApplicationException e ) { Log . e ( TAG , "Failed to insert programs." , e ) ; return ; } ops . clear ( ) ; } } } } ) . start ( ) ; }
Updates the system database TvProvider with the given programs .
2,825
public static void parseGenericFileUri ( String uri , FileIdentifier identifier ) { if ( uri . startsWith ( "file://" ) ) identifier . onLocalFile ( ) ; else if ( uri . startsWith ( "http://" ) ) identifier . onHttpFile ( ) ; else if ( uri . startsWith ( "android.resource://" ) ) identifier . onAsset ( ) ; }
In order to determine the correct file parser you can provide the URI and this method will find the appropriate parser to use
2,826
public void play ( final String uri ) { Log . d ( TAG , "Start playing " + uri ) ; notifyVideoUnavailable ( REASON_BUFFERING ) ; isWeb = false ; TvInputPlayer . Callback callback = new TvInputPlayer . Callback ( ) { public void onPrepared ( ) { notifyVideoAvailable ( ) ; setOverlayEnabled ( false ) ; } public void onPlayerStateChanged ( boolean playWhenReady , int state ) { } public void onPlayWhenReadyCommitted ( ) { } public void onPlayerError ( ExoPlaybackException e ) { Log . e ( TAG , e . getMessage ( ) + "" ) ; if ( e . getMessage ( ) . contains ( "Extractor" ) ) { Log . d ( TAG , "Cannot play the stream, try loading it as a website" ) ; Log . d ( TAG , "Open " + uri ) ; loadUrl ( uri ) ; isWeb = true ; setOverlayEnabled ( false ) ; notifyVideoAvailable ( ) ; isWeb = true ; setOverlayEnabled ( false ) ; setOverlayEnabled ( true ) ; isWeb = true ; } } public void onDrawnToSurface ( Surface surface ) { } public void onText ( String text ) { } } ; try { tvInputPlayer . removeCallback ( callback ) ; } catch ( NullPointerException e ) { Log . w ( TAG , "exoplayer.removeCallback error " + e . getMessage ( ) ) ; } tvInputPlayer . addCallback ( callback ) ; tvInputPlayer . setSurface ( mSurface ) ; Log . d ( TAG , "Play " + uri + "; " + uri . indexOf ( "file:///" ) ) ; if ( uri . contains ( "file:///" ) ) { Log . i ( TAG , "Is a local file" ) ; DataSource dataSource = new DefaultUriDataSource ( getApplicationContext ( ) , TvInputPlayer . getUserAgent ( getApplicationContext ( ) ) ) ; ExtractorSampleSource extractorSampleSource = new ExtractorSampleSource ( Uri . parse ( uri ) , dataSource , new DefaultAllocator ( TvInputPlayer . BUFFER_SEGMENT_SIZE ) , TvInputPlayer . BUFFER_SEGMENTS * TvInputPlayer . BUFFER_SEGMENT_SIZE , new Mp4Extractor ( ) , new Mp3Extractor ( ) ) ; TrackRenderer audio = new MediaCodecAudioTrackRenderer ( extractorSampleSource , MediaCodecSelector . DEFAULT ) ; TrackRenderer video = new MediaCodecVideoTrackRenderer ( getApplicationContext ( ) , extractorSampleSource , MediaCodecSelector . DEFAULT , MediaCodec . VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING ) ; tvInputPlayer . prepare ( audio , video , new DummyTrackRenderer ( ) ) ; } else { try { tvInputPlayer . prepare ( getApplicationContext ( ) , Uri . parse ( uri ) , TvInputPlayer . SOURCE_TYPE_HLS ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } tvInputPlayer . setPlayWhenReady ( true ) ; }
Tries to load a video file . If one cannot be played it will be interpreted as a website and begin to load it in a web browser
2,827
public void play ( String uri ) { tvInputPlayer . setSurface ( mSurface ) ; try { Log . d ( TAG , "Play " + uri + "; " + uri . indexOf ( "asset:///" ) ) ; if ( uri . contains ( "asset:///" ) ) { Log . i ( TAG , "Is a local file" ) ; DataSource dataSource = new AssetDataSource ( getApplicationContext ( ) ) ; ExtractorSampleSource extractorSampleSource = new ExtractorSampleSource ( Uri . parse ( uri ) , dataSource , new DefaultAllocator ( 1000 ) , 5000 ) ; TrackRenderer audio = new MediaCodecAudioTrackRenderer ( extractorSampleSource , null , null , true ) ; tvInputPlayer . prepare ( audio , null , null ) ; } else { tvInputPlayer . prepare ( getApplicationContext ( ) , Uri . parse ( uri ) , TvInputPlayer . SOURCE_TYPE_HLS ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } tvInputPlayer . setPlayWhenReady ( true ) ; }
Will load and begin to play any RTMP HLS or MPEG2 - DASH stream Should also be able to play local videos and audio files
2,828
public static Account getAccount ( Context mContext ) { String ACCOUNT_NAME = mContext . getString ( R . string . app_name ) ; return new Account ( ACCOUNT_NAME , ACCOUNT_NAME ) ; }
public static final String ACCOUNT_NAME = ;
2,829
public List < Channel > getCurrentChannels ( Context mContext ) { try { ApplicationInfo app = getApplicationContext ( ) . getPackageManager ( ) . getApplicationInfo ( getApplicationContext ( ) . getPackageName ( ) , PackageManager . GET_META_DATA ) ; Bundle bundle = app . metaData ; final String service = bundle . getString ( "TvInputService" ) ; String channels = TvContract . buildInputId ( new ComponentName ( getPackageName ( ) , service . substring ( getPackageName ( ) . length ( ) ) ) ) ; Uri channelsQuery = TvContract . buildChannelsUriForInput ( channels ) ; Log . d ( TAG , channels + " " + channelsQuery . toString ( ) ) ; List < Channel > list = new ArrayList < > ( ) ; Cursor cursor = null ; try { cursor = mContext . getContentResolver ( ) . query ( channelsQuery , null , null , null , null ) ; while ( cursor != null && cursor . moveToNext ( ) ) { Channel channel = new Channel ( ) . setNumber ( cursor . getString ( cursor . getColumnIndex ( TvContract . Channels . COLUMN_DISPLAY_NUMBER ) ) ) . setName ( cursor . getString ( cursor . getColumnIndex ( TvContract . Channels . COLUMN_DISPLAY_NAME ) ) ) . setOriginalNetworkId ( cursor . getInt ( cursor . getColumnIndex ( TvContract . Channels . COLUMN_ORIGINAL_NETWORK_ID ) ) ) . setTransportStreamId ( cursor . getInt ( cursor . getColumnIndex ( TvContract . Channels . COLUMN_TRANSPORT_STREAM_ID ) ) ) . setServiceId ( cursor . getInt ( cursor . getColumnIndex ( TvContract . Channels . COLUMN_SERVICE_ID ) ) ) . setVideoHeight ( 1080 ) . setVideoWidth ( 1920 ) . setPrograms ( getPrograms ( getApplicationContext ( ) , TvContract . buildChannelUri ( cursor . getInt ( cursor . getColumnIndex ( TvContract . Channels . _ID ) ) ) ) ) ; list . add ( channel ) ; } } finally { if ( cursor != null ) { cursor . close ( ) ; } } return list ; } catch ( PackageManager . NameNotFoundException e ) { e . printStackTrace ( ) ; } return null ; }
Goes into the TV guide and obtains the channels currently registered
2,830
public Program getGenericProgram ( Channel channel ) { TvContentRating rating = RATING_PG ; return new Program . Builder ( ) . setTitle ( channel . getName ( ) + " Live" ) . setProgramId ( channel . getServiceId ( ) ) . setDescription ( "Currently streaming" ) . setLongDescription ( channel . getName ( ) + " is currently streaming live." ) . setCanonicalGenres ( new String [ ] { TvContract . Programs . Genres . ENTERTAINMENT } ) . setThumbnailUri ( channel . getLogoUrl ( ) ) . setPosterArtUri ( channel . getLogoUrl ( ) ) . setInternalProviderData ( channel . getName ( ) ) . setContentRatings ( new TvContentRating [ ] { rating } ) . setVideoHeight ( 1080 ) . setVideoWidth ( 1920 ) . build ( ) ; }
If you don t have access to an EPG or don t want to supply programs you can simply add several instances of this generic program object .
2,831
public String getLocalVideoUri ( String assetname ) { File f = new File ( assetname ) ; Log . d ( TAG , "Video path " + f . getAbsolutePath ( ) ) ; String uri = Uri . fromFile ( f ) . toString ( ) ; Log . d ( TAG , "Uri " + uri ) ; return uri ; }
Gets a valid Uri of a local video file
2,832
private InputStream downloadUrl ( String myurl ) throws IOException { InputStream is = null ; try { URL url = new URL ( myurl ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setReadTimeout ( 28000 ) ; conn . setConnectTimeout ( 30000 ) ; conn . setRequestMethod ( "GET" ) ; conn . setDoInput ( true ) ; conn . connect ( ) ; is = conn . getInputStream ( ) ; return is ; } finally { if ( is != null ) { is . close ( ) ; } } }
Given a URL establishes an HttpUrlConnection and retrieves the web page content as a InputStream which it returns as a string .
2,833
public long getCurrentPosition ( ) { try { return mPlayer . getCurrentPosition ( ) ; } catch ( Exception e ) { Log . e ( TAG , e . getMessage ( ) ) ; return - 1 ; } }
Returns the current position of the media in milliseconds if applicable
2,834
public static TvInputProvider getTvInputProvider ( Context mContext , final TvInputProviderCallback callback ) { ApplicationInfo app = null ; try { Log . d ( TAG , mContext . getPackageName ( ) + " >" ) ; app = mContext . getPackageManager ( ) . getApplicationInfo ( mContext . getPackageName ( ) , PackageManager . GET_META_DATA ) ; Bundle bundle = app . metaData ; final String service = bundle . getString ( "TvInputService" ) ; Log . d ( TAG , service ) ; Log . d ( TAG , mContext . getString ( R . string . app_name ) ) ; try { Log . d ( TAG , "Constructors: " + Class . forName ( service ) . getConstructors ( ) . length ) ; new Handler ( Looper . getMainLooper ( ) ) . post ( new Runnable ( ) { public void run ( ) { TvInputProvider provider = null ; try { provider = ( TvInputProvider ) Class . forName ( service ) . getConstructors ( ) [ 0 ] . newInstance ( ) ; Log . d ( TAG , provider . toString ( ) ) ; callback . onTvInputProviderCallback ( provider ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e ) { e . printStackTrace ( ) ; } } } ) ; } catch ( ClassNotFoundException e ) { Log . e ( TAG , e . getMessage ( ) ) ; e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } catch ( PackageManager . NameNotFoundException e ) { e . printStackTrace ( ) ; } return null ; }
Returns the TvInputProvider that was defined by the project s manifest
2,835
public void setReal ( T value , int m , int n ) { setReal ( value , getIndex ( m , n ) ) ; }
Sets single real array element .
2,836
public void setReal ( T [ ] vector ) { if ( vector . length != getSize ( ) ) { throw new IllegalArgumentException ( "Matrix dimensions do not match. " + getSize ( ) + " not " + vector . length ) ; } System . arraycopy ( vector , 0 , real , 0 , vector . length ) ; }
Sets real part of matrix
2,837
public void setImaginary ( T value , int m , int n ) { setImaginary ( value , getIndex ( m , n ) ) ; }
Sets single imaginary array element .
2,838
public void set ( String value , int idx ) { int rowOffset = getM ( ) ; for ( int i = 0 ; i < getN ( ) ; i ++ ) { if ( i < value . length ( ) ) { setChar ( value . charAt ( i ) , idx + ( rowOffset * i ) ) ; } else { setChar ( ' ' , idx + ( rowOffset * i ) ) ; } } }
Set one row specifying the row .
2,839
public int [ ] getIR ( ) { int [ ] ir = new int [ nzmax ] ; int i = 0 ; for ( IndexMN index : indexSet ) { ir [ i ++ ] = index . m ; } return ir ; }
Gets row indices
2,840
public int [ ] getIC ( ) { int [ ] ic = new int [ nzmax ] ; int i = 0 ; for ( IndexMN index : indexSet ) { ic [ i ++ ] = index . n ; } return ic ; }
Gets column indices
2,841
public int [ ] getJC ( ) { int [ ] jc = new int [ getN ( ) + 1 ] ; for ( IndexMN index : indexSet ) { for ( int column = index . n + 1 ; column < jc . length ; column ++ ) { jc [ column ] ++ ; } } return jc ; }
Gets column indices .
2,842
public void setField ( String name , MLArray value , int index ) { keys . add ( name ) ; currentIndex = index ; if ( mlStructArray . isEmpty ( ) || mlStructArray . size ( ) <= index ) { mlStructArray . add ( index , new LinkedHashMap < String , MLArray > ( ) ) ; } mlStructArray . get ( index ) . put ( name , value ) ; }
Sets filed for structure described by index in struct array
2,843
public int getMaxFieldLenth ( ) { int maxLen = 0 ; for ( String s : keys ) { maxLen = s . length ( ) > maxLen ? s . length ( ) : maxLen ; } return maxLen + 1 ; }
Gets the maximum length of field descriptor
2,844
public byte [ ] getKeySetToByteArray ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( baos ) ; char [ ] buffer = new char [ getMaxFieldLenth ( ) ] ; try { for ( String s : keys ) { Arrays . fill ( buffer , ( char ) 0 ) ; System . arraycopy ( s . toCharArray ( ) , 0 , buffer , 0 , s . length ( ) ) ; dos . writeBytes ( new String ( buffer ) ) ; } } catch ( IOException e ) { System . err . println ( "Could not write Structure key set to byte array: " + e ) ; return new byte [ 0 ] ; } return baos . toByteArray ( ) ; }
Dumps field names to byte array . Field names are written as Zero End Strings
2,845
public Collection < MLArray > getAllFields ( ) { ArrayList < MLArray > fields = new ArrayList < MLArray > ( ) ; for ( Map < String , MLArray > struct : mlStructArray ) { fields . addAll ( struct . values ( ) ) ; } return fields ; }
Gets all field from sruct array as flat list of fields .
2,846
public MLArray getField ( String name , int index ) { if ( mlStructArray . isEmpty ( ) ) { return null ; } return mlStructArray . get ( index ) . get ( name ) ; }
Gets a value of the field described by name from index th struct in struct array or null if the field doesn t exist .
2,847
public synchronized Map < String , MLArray > read ( InputStream stream , MatFileFilter filter ) throws IOException { this . filter = filter ; data . clear ( ) ; ByteBuffer buf = null ; final ByteArrayOutputStream2 baos = new ByteArrayOutputStream2 ( ) ; copy ( stream , baos ) ; buf = ByteBuffer . wrap ( baos . getBuf ( ) , 0 , baos . getCount ( ) ) ; parseData ( buf ) ; return getContent ( ) ; }
Read a mat file from a stream . Internally this will read the stream fully into memory before parsing it .
2,848
private int [ ] readFlags ( ByteBuffer buf ) throws IOException { ISMatTag tag = new ISMatTag ( buf ) ; int [ ] flags = tag . readToIntArray ( ) ; return flags ; }
Reads Matrix flags .
2,849
private int [ ] readDimension ( ByteBuffer buf ) throws IOException { ISMatTag tag = new ISMatTag ( buf ) ; int [ ] dims = tag . readToIntArray ( ) ; return dims ; }
Reads Matrix dimensions .
2,850
private String readName ( ByteBuffer buf ) throws IOException { ISMatTag tag = new ISMatTag ( buf ) ; return tag . readToString ( ) ; }
Reads Matrix name .
2,851
private void readHeader ( ByteBuffer buf ) throws IOException { String description ; int version ; byte [ ] endianIndicator = new byte [ 2 ] ; if ( matType == MatFileType . Regular ) { byte [ ] descriptionBuffer = new byte [ 116 ] ; buf . get ( descriptionBuffer ) ; description = zeroEndByteArrayToString ( descriptionBuffer ) ; if ( ! description . matches ( "MATLAB 5.0 MAT-file.*" ) ) { throw new MatlabIOException ( "This is not a valid MATLAB 5.0 MAT-file." ) ; } buf . position ( buf . position ( ) + 8 ) ; } else { description = "Simulink generated MATLAB 5.0 MAT-file" ; } byte [ ] bversion = new byte [ 2 ] ; buf . get ( bversion ) ; buf . get ( endianIndicator ) ; if ( ( char ) endianIndicator [ 0 ] == 'I' && ( char ) endianIndicator [ 1 ] == 'M' ) { byteOrder = ByteOrder . LITTLE_ENDIAN ; version = bversion [ 1 ] & 0xff | bversion [ 0 ] << 8 ; } else { byteOrder = ByteOrder . BIG_ENDIAN ; version = bversion [ 0 ] & 0xff | bversion [ 1 ] << 8 ; } buf . order ( byteOrder ) ; matFileHeader = new MatFileHeader ( description , version , endianIndicator , byteOrder ) ; buf . position ( ( buf . position ( ) + 7 ) & 0xfffffff8 ) ; }
Reads MAT - file header .
2,852
public static int sizeOf ( int type ) { switch ( type ) { case MatDataTypes . miINT8 : return miSIZE_INT8 ; case MatDataTypes . miUINT8 : return miSIZE_UINT8 ; case MatDataTypes . miINT16 : return miSIZE_INT16 ; case MatDataTypes . miUINT16 : return miSIZE_UINT16 ; case MatDataTypes . miINT32 : return miSIZE_INT32 ; case MatDataTypes . miUINT32 : return miSIZE_UINT32 ; case MatDataTypes . miINT64 : return miSIZE_INT64 ; case MatDataTypes . miUINT64 : return miSIZE_UINT64 ; case MatDataTypes . miDOUBLE : return miSIZE_DOUBLE ; default : return 1 ; } }
Return number of bytes for given type .
2,853
public static String typeToString ( int type ) { String s ; switch ( type ) { case MatDataTypes . miUNKNOWN : s = "unknown" ; break ; case MatDataTypes . miINT8 : s = "int8" ; break ; case MatDataTypes . miUINT8 : s = "uint8" ; break ; case MatDataTypes . miINT16 : s = "int16" ; break ; case MatDataTypes . miUINT16 : s = "uint16" ; break ; case MatDataTypes . miINT32 : s = "int32" ; break ; case MatDataTypes . miUINT32 : s = "uint32" ; break ; case MatDataTypes . miSINGLE : s = "single" ; break ; case MatDataTypes . miDOUBLE : s = "double" ; break ; case MatDataTypes . miINT64 : s = "int64" ; break ; case MatDataTypes . miUINT64 : s = "uint64" ; break ; case MatDataTypes . miMATRIX : s = "matrix" ; break ; case MatDataTypes . miCOMPRESSED : s = "compressed" ; break ; case MatDataTypes . miUTF8 : s = "uft8" ; break ; case MatDataTypes . miUTF16 : s = "utf16" ; break ; case MatDataTypes . miUTF32 : s = "utf32" ; break ; default : s = "unknown" ; } return s ; }
Get String representation of a data type
2,854
public double [ ] [ ] getArray ( ) { double [ ] [ ] result = new double [ getM ( ) ] [ ] ; for ( int m = 0 ; m < getM ( ) ; m ++ ) { result [ m ] = new double [ getN ( ) ] ; for ( int n = 0 ; n < getN ( ) ; n ++ ) { result [ m ] [ n ] = getReal ( m , n ) ; } } return result ; }
Gets two - dimensional real array .
2,855
private String [ ] getParameterNames ( Method method ) { if ( notSupportParameterNameDiscoverer ) { return null ; } else { try { ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer ( ) ; String [ ] strs = parameterNameDiscoverer . getParameterNames ( method ) ; if ( strs == null ) { notSupportParameterNameDiscoverer = true ; } return strs ; } catch ( NoClassDefFoundError e ) { notSupportParameterNameDiscoverer = true ; return null ; } } }
DefaultParameterNameDiscoverer is supported spring 4 . 0
2,856
private static EvaluationContext buildEvaluationContext ( final String expression ) { return new DDRSpelEvaluationContext ( ) { public Object lookupVariable ( String name ) { Object val = null ; if ( isReservedWords ( name ) ) { val = super . lookupVariable ( name ) ; if ( val == null ) { throw new ExpressionValueNotFoundException ( "Value of '" + name + "' is not found when parsing expression '" + expression + "'" ) ; } } else { val = ShardRouteRuleExpressionContext . lookupVariable ( name ) ; } return val ; } } ; }
load order 1 . reserved words 2 . function 3 . user - define var
2,857
public static void main ( String [ ] args ) { ShardRouter shardRouter = buildShardRouter ( ) ; String createDatabaseSql = "CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" ; String createTableSql = "CREATE TABLE `%s`(`id` bigint(20) NOT NULL, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`), KEY `idx_name` (`name`) USING BTREE ) ENGINE=InnoDB;" ; build ( shardRouter , createDatabaseSql , createTableSql , "base" , "user" ) ; }
run this method
2,858
public void visit ( Delete delete ) { if ( enableLimitCheck && delete . getLimit ( ) == null ) { throw new IllegalStateException ( "no limit in sql: " + sql ) ; } this . getStack ( ) . push ( new FrameContext ( StatementType . DELETE ) ) ; visit0 ( delete ) ; afterVisitBaseStatement ( ) ; }
mysql delete doesn t support alais
2,859
public void type ( final String text ) { autoHover ( ) ; if ( text == null ) return ; waitUntilEnabled ( ) ; runWithRetries ( ( ) -> { elementImpl . locateElement ( ) . clear ( ) ; elementImpl . locateElement ( ) . sendKeys ( text ) ; } ) ; }
Clears out the value of the input field first then types specified text .
2,860
private List < WebElement > getListWebElements ( Callable < List < WebElement > > callable ) { int retries = 0 ; long expireTime = Instant . now ( ) . toEpochMilli ( ) + SECONDS . toMillis ( INTERACT_WAIT_S ) ; while ( Instant . now ( ) . toEpochMilli ( ) < expireTime && retries < LOCATE_RETRIES ) { try { List < WebElement > elements = callable . call ( ) ; if ( elements . size ( ) == 0 ) continue ; return elements ; } catch ( WebDriverException e ) { retries ++ ; } catch ( Exception e ) { Throwables . propagate ( e ) ; } } return new ArrayList < > ( ) ; }
If nothing found by the timeout return an empty list
2,861
public void switchWindow ( ) { List < String > windowHandles = new ArrayList < > ( getWindowHandles ( ) ) ; getDriver ( ) . switchTo ( ) . window ( windowHandles . get ( windowHandles . size ( ) - 1 ) ) ; }
switches to the last opened window
2,862
private static void putCachedResource ( String baseName , Resources resources ) { synchronized ( ResourceManager . class ) { WeakReference < Resources > ref = new WeakReference < Resources > ( resources ) ; RESOURCES . put ( baseName , ref ) ; } }
Cache specified resource in weak reference .
2,863
private static Resources getCachedResource ( String baseName ) { synchronized ( ResourceManager . class ) { WeakReference weakReference = RESOURCES . get ( baseName ) ; if ( null == weakReference ) { return null ; } else { return ( Resources ) weakReference . get ( ) ; } } }
Retrieve cached resource .
2,864
public static Resources getPackageResources ( Class clazz , Locale locale ) { return getBaseResources ( getPackageResourcesBaseName ( clazz ) , locale , clazz . getClassLoader ( ) ) ; }
Retrieve resource for specified Classes package . The basename is determined by name of classes package postfixed with . Resources .
2,865
public static Resources getClassResources ( Class clazz , Locale locale ) { return getBaseResources ( getClassResourcesBaseName ( clazz ) , locale , clazz . getClassLoader ( ) ) ; }
Retrieve resource for specified Class . The basename is determined by name of Class postfixed with Resources .
2,866
public static String getPackageResourcesBaseName ( Class clazz ) { final Package pkg = clazz . getPackage ( ) ; String baseName ; if ( null == pkg ) { String name = clazz . getName ( ) ; if ( - 1 == name . lastIndexOf ( "." ) ) { baseName = "Resources" ; } else { baseName = name . substring ( 0 , name . lastIndexOf ( "." ) ) + ".Resources" ; } } else { baseName = pkg . getName ( ) + ".Resources" ; } return baseName ; }
Retrieve resource basename for specified Classes package . The basename is determined by name of classes package postfixed with . Resources .
2,867
public static < T > List < T > findServiceProviders ( Class < T > klass ) { ServiceLoader < T > loader = ServiceLoader . load ( klass ) ; List < T > providers = new ArrayList < T > ( ) ; Iterator < T > it = loader . iterator ( ) ; while ( it . hasNext ( ) ) { providers . add ( it . next ( ) ) ; } return providers ; }
Finds all providers for a given service .
2,868
public static < T > T findAnyServiceProvider ( Class < T > klass ) { ServiceLoader < T > loader = ServiceLoader . load ( klass ) ; Iterator < T > it = loader . iterator ( ) ; return it . hasNext ( ) ? it . next ( ) : null ; }
Finds any provider for a given service .
2,869
public static < T > T loadAnyServiceProvider ( Class < T > klass ) { T provider = findAnyServiceProvider ( klass ) ; if ( provider == null ) { throw new NoServiceProviderException ( klass . getName ( ) + ": no service provider found in META-INF/services on classpath" ) ; } return provider ; }
Returns any provider for a given service and throws an exception when no provider is found on the classpath .
2,870
public static < T > T loadUniqueServiceProvider ( Class < T > klass ) { List < T > providers = findServiceProviders ( klass ) ; if ( providers . isEmpty ( ) ) { throw new NoServiceProviderException ( klass . getName ( ) + ": no service provider found in META-INF/services on classpath" ) ; } else if ( providers . size ( ) > 1 ) { throw new NonUniqueServiceProviderException ( klass . getName ( ) + ": multiple service providers found in META-INF/services on classpath" ) ; } return providers . get ( 0 ) ; }
Returns the unique service provider for a given service and throws an exception if there is no unique provider
2,871
public synchronized Pipe start ( final String name ) { if ( null == m_pump && null != m_in && null != m_out ) { m_pump = startPump ( m_in ) ; m_pump . setName ( name ) ; m_pump . connect ( m_out ) ; } return this ; }
Start piping data from input to output .
2,872
public synchronized void stop ( ) { if ( null != m_pump ) { m_pump . connect ( null ) ; m_pump . setName ( m_pump . getName ( ) + " (disconnected)" ) ; m_pump = null ; } }
Stop piping data from input to output .
2,873
public static File getFileFromClasspath ( final String filePath ) throws FileNotFoundException { try { URL fileURL = FileUtils . class . getClassLoader ( ) . getResource ( filePath ) ; if ( fileURL == null ) { throw new FileNotFoundException ( "File [" + filePath + "] could not be found in classpath" ) ; } return new File ( fileURL . toURI ( ) ) ; } catch ( URISyntaxException e ) { throw new FileNotFoundException ( "File [" + filePath + "] could not be found: " + e . getMessage ( ) ) ; } }
Searches the classpath for the file denoted by the file path and returns the corresponding file .
2,874
public static boolean delete ( final File file ) { boolean delete = false ; if ( file != null && file . exists ( ) ) { delete = file . delete ( ) ; if ( ! delete && file . isDirectory ( ) ) { File [ ] childs = file . listFiles ( ) ; if ( childs != null && childs . length > 0 ) { for ( File child : childs ) { delete ( child ) ; } delete = file . delete ( ) ; } } } return delete ; }
Deletes the file or recursively deletes a directory depending on the file passed .
2,875
public static Pattern parseFilter ( final String spec ) { StringBuffer sb = new StringBuffer ( ) ; for ( int j = 0 ; j < spec . length ( ) ; j ++ ) { char c = spec . charAt ( j ) ; switch ( c ) { case '.' : sb . append ( "\\." ) ; break ; case '*' : if ( j < spec . length ( ) - 1 && spec . charAt ( j + 1 ) == '*' ) { sb . append ( ".*" ) ; j ++ ; } else { sb . append ( "[^/]*" ) ; } break ; default : sb . append ( c ) ; break ; } } String s = sb . toString ( ) ; try { return Pattern . compile ( s ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Invalid character used in the filter name" , e ) ; } }
Parses a usual filter into a regex pattern .
2,876
public static Element getRootElement ( InputStream input ) throws ParserConfigurationException , IOException , SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setValidating ( false ) ; factory . setNamespaceAware ( false ) ; try { factory . setFeature ( "http://xml.org/sax/features/namespaces" , false ) ; factory . setFeature ( "http://xml.org/sax/features/validation" , false ) ; factory . setFeature ( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar" , false ) ; factory . setFeature ( "http://apache.org/xml/features/nonvalidating/load-external-dtd" , false ) ; } catch ( Throwable ignore ) { } DocumentBuilder builder = factory . newDocumentBuilder ( ) ; try { builder . setEntityResolver ( new EntityResolver ( ) { public InputSource resolveEntity ( java . lang . String publicId , java . lang . String systemId ) throws SAXException , java . io . IOException { return new InputSource ( new ByteArrayInputStream ( "<?xml version='1.0' encoding='UTF-8'?>" . getBytes ( ) ) ) ; } } ) ; } catch ( Throwable ignore ) { } Document document = builder . parse ( input ) ; return document . getDocumentElement ( ) ; }
Return the root element of the supplied input stream .
2,877
public static Element getChild ( Element root , String name ) { if ( null == root ) { return null ; } NodeList list = root . getElementsByTagName ( name ) ; int n = list . getLength ( ) ; if ( n < 1 ) { return null ; } return ( Element ) list . item ( 0 ) ; }
Return a named child relative to a supplied element .
2,878
public static Element [ ] getChildren ( Element root , String name ) { if ( null == root ) { return new Element [ 0 ] ; } NodeList list = root . getElementsByTagName ( name ) ; int n = list . getLength ( ) ; ArrayList < Element > result = new ArrayList < Element > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node item = list . item ( i ) ; if ( item instanceof Element ) { result . add ( ( Element ) item ) ; } } Element [ ] retval = new Element [ result . size ( ) ] ; result . toArray ( retval ) ; return retval ; }
Return all children matching the supplied element name .
2,879
public static String getValue ( Element node ) { if ( null == node ) { return null ; } String value ; if ( node . getChildNodes ( ) . getLength ( ) > 0 ) { value = node . getFirstChild ( ) . getNodeValue ( ) ; } else { value = node . getNodeValue ( ) ; } return normalize ( value ) ; }
Return the value of an element .
2,880
private static String normalize ( String value , Properties props ) { return PropertyResolver . resolve ( props , value ) ; }
Parse the value for any property tokens relative to the supplied properties .
2,881
public URLConnection get ( Object key ) { synchronized ( this ) { Entry entry = m_hardStore . get ( key ) ; if ( entry == null ) { return null ; } return entry . m_connection ; } }
Returns the URLConnection associated with the given key .
2,882
public void put ( Object key , URLConnection conn ) { synchronized ( this ) { Entry entry = new Entry ( conn ) ; m_hardStore . put ( key , entry ) ; if ( m_thread == null ) { m_thread = new Thread ( this , "ConnectionCache-cleaner" ) ; m_thread . setDaemon ( true ) ; m_thread . start ( ) ; } } }
Stores a URLConnection in association with a key .
2,883
private boolean mainLoop ( ) throws InterruptedException { long now = System . currentTimeMillis ( ) ; Iterator list = m_hardStore . values ( ) . iterator ( ) ; while ( list . hasNext ( ) ) { Entry entry = ( Entry ) list . next ( ) ; if ( entry . m_collectTime < now ) { m_weakStore . put ( entry . m_connection , DUMMY ) ; list . remove ( ) ; } } if ( m_hardStore . size ( ) == 0 ) { m_thread = null ; return true ; } wait ( 10000 ) ; return false ; }
The main loop of the cache which checks for expirations .
2,884
public void unregisterExceptionMonitor ( ExceptionMonitor monitor ) { synchronized ( this ) { if ( monitor == null || ! monitor . equals ( m_exceptionMonitor ) ) { return ; } m_exceptionMonitor = null ; } }
Unregister a ExceptionMonitor with the source .
2,885
public List < ExceptionMonitor > getExceptionMonitors ( ) { synchronized ( this ) { ArrayList < ExceptionMonitor > result = new ArrayList < ExceptionMonitor > ( ) ; result . add ( m_exceptionMonitor ) ; return result ; } }
Returns all ExceptionMonitors that are registered .
2,886
public static Properties readProps ( URL propsUrl , Properties mappings ) throws IOException { InputStream stream = propsUrl . openStream ( ) ; return readProperties ( stream , mappings , true ) ; }
Read a set of properties from a property file specificed by a url .
2,887
public static String resolveProperty ( Properties props , String value ) { return PropertyResolver . resolve ( props , value ) ; }
Resolve symbols in a supplied value against supplied known properties .
2,888
public static String getProperty ( Properties props , String key , String def ) { String value = props . getProperty ( key , def ) ; if ( value == null ) { return null ; } if ( "" . equals ( value ) ) { return value ; } value = PropertyResolver . resolve ( props , value ) ; return value ; }
Return the value of a property .
2,889
public static String [ ] readListFile ( URL listFile ) throws IOException { ArrayList < String > list = new ArrayList < String > ( ) ; InputStream stream = listFile . openStream ( ) ; try { InputStreamReader isr = new InputStreamReader ( stream , "UTF-8" ) ; BufferedReader reader = new BufferedReader ( isr ) ; String line = reader . readLine ( ) ; while ( line != null ) { list . add ( line ) ; line = reader . readLine ( ) ; } String [ ] items = new String [ list . size ( ) ] ; list . toArray ( items ) ; return items ; } finally { stream . close ( ) ; } }
Read a file and return the list of lines in an array of strings .
2,890
private static String toFirstCap ( String applicationname ) { char first = applicationname . charAt ( 0 ) ; first = Character . toUpperCase ( first ) ; String name = first + applicationname . substring ( 1 ) ; return name ; }
Capitalizes the first character .
2,891
public static String getEnvVariable ( String name ) throws EnvironmentException { if ( isUnix ( ) ) { Properties properties = getUnixShellVariables ( ) ; return properties . getProperty ( name ) ; } else if ( isWindows ( ) ) { Properties properties = getWindowsShellVariables ( ) ; return properties . getProperty ( name ) ; } String osName = System . getProperty ( "os.name" ) ; throw new EnvironmentException ( name , "Non-supported operating system: " + osName ) ; }
Gets the value of a shell environment variable .
2,892
public static Properties getEnvVariables ( ) throws EnvironmentException { if ( isUnix ( ) ) { return getUnixShellVariables ( ) ; } if ( isWindows ( ) ) { return getWindowsShellVariables ( ) ; } String message = "Environment operations not supported on unrecognized operatings system" ; UnsupportedOperationException cause = new UnsupportedOperationException ( message ) ; throw new EnvironmentException ( cause ) ; }
Gets all environment variables within a Properties instance where the key is the environment variable name and value is the value of the property .
2,893
public static String getUserShell ( ) throws EnvironmentException { if ( isMacOsX ( ) ) { return getMacUserShell ( ) ; } if ( isWindows ( ) ) { return getWindowsUserShell ( ) ; } if ( isUnix ( ) ) { return getUnixUserShell ( ) ; } String message = "Environment operations not supported on unrecognized operatings system" ; UnsupportedOperationException cause = new UnsupportedOperationException ( message ) ; throw new EnvironmentException ( cause ) ; }
Gets the user s shell executable .
2,894
private static String getWindowsUserShell ( ) { if ( null != m_SHELL ) { return m_SHELL ; } if ( - 1 != OSNAME . indexOf ( "98" ) || - 1 != OSNAME . indexOf ( "95" ) || - 1 != OSNAME . indexOf ( "Me" ) ) { m_SHELL = "command.com" ; return m_SHELL ; } m_SHELL = "cmd.exe" ; return m_SHELL ; }
Gets the shell used by the Windows user .
2,895
private static String getMacUserShell ( ) throws EnvironmentException { if ( null != m_SHELL ) { return m_SHELL ; } String [ ] args = { "nidump" , "passwd" , "/" } ; return readShellFromPasswdFile ( args ) ; }
Gets the default login shell used by a mac user .
2,896
private static String getUnixUserShell ( ) throws EnvironmentException { if ( null != m_SHELL ) { return m_SHELL ; } String [ ] args = { "cat" , "/etc/passwd" } ; return readShellFromPasswdFile ( args ) ; }
Gets the default login shell used by a unix user .
2,897
private static void processPasswdFile ( BufferedReader reader ) throws IOException { String entry = reader . readLine ( ) ; while ( null != entry ) { if ( entry . startsWith ( USERNAME ) ) { int index = entry . lastIndexOf ( ':' ) ; if ( index == - 1 ) { String message = "passwd database contains malformed user entry for " + USERNAME ; throw new EnvironmentException ( message ) ; } m_SHELL = entry . substring ( index + 1 ) ; break ; } entry = reader . readLine ( ) ; } }
Process a password file .
2,898
private static String getUnixEnv ( ) throws EnvironmentException { File env = new File ( "/bin/env" ) ; if ( env . exists ( ) && env . canRead ( ) && env . isFile ( ) ) { return env . getAbsolutePath ( ) ; } env = new File ( "/usr/bin/env" ) ; if ( env . exists ( ) && env . canRead ( ) && env . isFile ( ) ) { return env . getAbsolutePath ( ) ; } String message = "Could not find the UNIX env executable" ; throw new EnvironmentException ( message ) ; }
Gets the UNIX env executable path .
2,899
private static void processLinesOfEnvironmentVariables ( BufferedReader reader , Properties properties ) throws IOException { String line = reader . readLine ( ) ; while ( null != line ) { int index = line . indexOf ( '=' ) ; if ( - 1 == index && line . length ( ) != 0 ) { String message = "Skipping line - could not find '=' in line: '" + line + "'" ; System . err . println ( message ) ; } else { String name = line . substring ( 0 , index ) ; String value = line . substring ( index + 1 , line . length ( ) ) ; properties . setProperty ( name , value ) ; } line = reader . readLine ( ) ; } }
Process the lines of the environment variables returned .