idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
11,800 | public StatusCode removeItem ( String sessionId , String listId , int mediaId ) throws MovieDbException { return modifyMovieList ( sessionId , listId , mediaId , MethodSub . REMOVE_ITEM ) ; } | This method lets users delete items from a list that they created . | 49 | 13 |
11,801 | public StatusCode clear ( String sessionId , String listId , boolean confirm ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . SESSION_ID , sessionId ) ; parameters . add ( Param . ID , listId ) ; parameters . add ( Param . CONFIRM , confirm ) ; URL url = new ApiUrl ( apiKey , MethodBase . LIST ) . subMethod ( MethodSub . CLEAR ) . buildUrl ( parameters ) ; String webpage = httpTools . postRequest ( url , "" ) ; try { return MAPPER . readValue ( webpage , StatusCode . class ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to clear list" , url , ex ) ; } } | Clear all of the items within a list . | 181 | 9 |
11,802 | public Keyword getKeyword ( String keywordId ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , keywordId ) ; URL url = new ApiUrl ( apiKey , MethodBase . KEYWORD ) . buildUrl ( parameters ) ; String webpage = httpTools . getRequest ( url ) ; try { return MAPPER . readValue ( webpage , Keyword . class ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get keyword " + keywordId , url , ex ) ; } } | Get the basic information for a specific keyword id . | 141 | 10 |
11,803 | public String getRequest ( final URL url ) throws MovieDbException { try { HttpGet httpGet = new HttpGet ( url . toURI ( ) ) ; httpGet . addHeader ( HttpHeaders . ACCEPT , APPLICATION_JSON ) ; DigestedResponse response = DigestedResponseReader . requestContent ( httpClient , httpGet , CHARSET ) ; long retryCount = 0L ; // If we have a 429 response, wait and try again while ( response . getStatusCode ( ) == STATUS_TOO_MANY_REQUESTS && retryCount ++ <= RETRY_MAX ) { delay ( retryCount ) ; // Retry the request response = DigestedResponseReader . requestContent ( httpClient , httpGet , CHARSET ) ; } return validateResponse ( response , url ) ; } catch ( URISyntaxException | IOException ex ) { throw new MovieDbException ( ApiExceptionType . CONNECTION_ERROR , null , url , ex ) ; } catch ( RuntimeException ex ) { throw new MovieDbException ( ApiExceptionType . HTTP_503_ERROR , "Service Unavailable" , url , ex ) ; } } | GET data from the URL | 254 | 5 |
11,804 | private void delay ( long multiplier ) { try { // Wait for the timeout to finish Thread . sleep ( TimeUnit . SECONDS . toMillis ( RETRY_DELAY * multiplier ) ) ; } catch ( InterruptedException ex ) { // Doesn't matter if we're interrupted } } | Sleep for a period of time | 62 | 6 |
11,805 | public String deleteRequest ( final URL url ) throws MovieDbException { try { HttpDelete httpDel = new HttpDelete ( url . toURI ( ) ) ; return validateResponse ( DigestedResponseReader . deleteContent ( httpClient , httpDel , CHARSET ) , url ) ; } catch ( URISyntaxException | IOException ex ) { throw new MovieDbException ( ApiExceptionType . CONNECTION_ERROR , null , url , ex ) ; } } | Execute a DELETE on the URL | 101 | 9 |
11,806 | public String postRequest ( final URL url , final String jsonBody ) throws MovieDbException { try { HttpPost httpPost = new HttpPost ( url . toURI ( ) ) ; httpPost . addHeader ( HTTP . CONTENT_TYPE , APPLICATION_JSON ) ; httpPost . addHeader ( HttpHeaders . ACCEPT , APPLICATION_JSON ) ; StringEntity params = new StringEntity ( jsonBody , ContentType . APPLICATION_JSON ) ; httpPost . setEntity ( params ) ; return validateResponse ( DigestedResponseReader . postContent ( httpClient , httpPost , CHARSET ) , url ) ; } catch ( URISyntaxException | IOException ex ) { throw new MovieDbException ( ApiExceptionType . CONNECTION_ERROR , null , url , ex ) ; } } | POST content to the URL with the specified body | 175 | 9 |
11,807 | private String validateResponse ( final DigestedResponse response , final URL url ) throws MovieDbException { if ( response . getStatusCode ( ) == 0 ) { throw new MovieDbException ( ApiExceptionType . CONNECTION_ERROR , response . getContent ( ) , response . getStatusCode ( ) , url , null ) ; } else if ( response . getStatusCode ( ) >= HttpStatus . SC_INTERNAL_SERVER_ERROR ) { throw new MovieDbException ( ApiExceptionType . HTTP_503_ERROR , response . getContent ( ) , response . getStatusCode ( ) , url , null ) ; } else if ( response . getStatusCode ( ) >= HttpStatus . SC_MULTIPLE_CHOICES ) { throw new MovieDbException ( ApiExceptionType . HTTP_404_ERROR , response . getContent ( ) , response . getStatusCode ( ) , url , null ) ; } return response . getContent ( ) ; } | Check the status codes of the response and throw exceptions if needed | 209 | 12 |
11,808 | public void add ( final Param key , final String [ ] value ) { if ( value != null && value . length > 0 ) { parameters . put ( key , toList ( value ) ) ; } } | Add an array parameter to the collection | 43 | 7 |
11,809 | public void add ( final Param key , final String value ) { if ( StringUtils . isNotBlank ( value ) ) { parameters . put ( key , value ) ; } } | Add a string parameter to the collection | 39 | 7 |
11,810 | public void add ( final Param key , final Integer value ) { if ( value != null && value > 0 ) { parameters . put ( key , String . valueOf ( value ) ) ; } } | Add an integer parameter to the collection | 41 | 7 |
11,811 | public String toList ( final String [ ] appendToResponse ) { StringBuilder sb = new StringBuilder ( ) ; boolean first = Boolean . TRUE ; for ( String append : appendToResponse ) { if ( first ) { first = Boolean . FALSE ; } else { sb . append ( "," ) ; } sb . append ( append ) ; } return sb . toString ( ) ; } | Append any optional parameters to the URL | 85 | 8 |
11,812 | protected static TypeReference getTypeReference ( Class aClass ) throws MovieDbException { if ( TYPE_REFS . containsKey ( aClass ) ) { return TYPE_REFS . get ( aClass ) ; } else { throw new MovieDbException ( ApiExceptionType . UNKNOWN_CAUSE , "Class type reference for '" + aClass . getSimpleName ( ) + "' not found!" ) ; } } | Helper function to get a pre - generated TypeReference for a class | 89 | 13 |
11,813 | protected < T > List < T > processWrapperList ( TypeReference typeRef , URL url , String errorMessageSuffix ) throws MovieDbException { WrapperGenericList < T > val = processWrapper ( typeRef , url , errorMessageSuffix ) ; return val . getResults ( ) ; } | Process the wrapper list and return the results | 67 | 8 |
11,814 | protected < T > WrapperGenericList < T > processWrapper ( TypeReference typeRef , URL url , String errorMessageSuffix ) throws MovieDbException { String webpage = httpTools . getRequest ( url ) ; try { // Due to type erasure, this doesn't work // TypeReference<WrapperGenericList<T>> typeRef = new TypeReference<WrapperGenericList<T>>() {}; return MAPPER . readValue ( webpage , typeRef ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get " + errorMessageSuffix , url , ex ) ; } } | Process the wrapper list and return the whole wrapper | 148 | 9 |
11,815 | public ResultList < JobDepartment > getJobs ( ) throws MovieDbException { URL url = new ApiUrl ( apiKey , MethodBase . JOB ) . subMethod ( MethodSub . LIST ) . buildUrl ( ) ; String webpage = httpTools . getRequest ( url ) ; try { WrapperJobList wrapper = MAPPER . readValue ( webpage , WrapperJobList . class ) ; ResultList < JobDepartment > results = new ResultList <> ( wrapper . getJobs ( ) ) ; wrapper . setResultProperties ( results ) ; return results ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get job list" , url , ex ) ; } } | Get a list of valid jobs | 164 | 6 |
11,816 | public ResultsMap < String , List < String > > getTimezones ( ) throws MovieDbException { URL url = new ApiUrl ( apiKey , MethodBase . TIMEZONES ) . subMethod ( MethodSub . LIST ) . buildUrl ( ) ; String webpage = httpTools . getRequest ( url ) ; List < Map < String , List < String > > > tzList ; try { tzList = MAPPER . readValue ( webpage , new TypeReference < List < Map < String , List < String > > > > ( ) { } ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get timezone list" , url , ex ) ; } ResultsMap < String , List < String > > timezones = new ResultsMap <> ( ) ; for ( Map < String , List < String > > tzMap : tzList ) { for ( Map . Entry < String , List < String > > x : tzMap . entrySet ( ) ) { timezones . put ( x . getKey ( ) , x . getValue ( ) ) ; } } return timezones ; } | Get the list of supported timezones for the API methods that support them | 259 | 15 |
11,817 | public ResultList < Genre > getGenreMovieList ( String language ) throws MovieDbException { return getGenreList ( language , MethodSub . MOVIE_LIST ) ; } | Get the list of movie genres . | 39 | 7 |
11,818 | public ResultList < Genre > getGenreTVList ( String language ) throws MovieDbException { return getGenreList ( language , MethodSub . TV_LIST ) ; } | Get the list of TV genres . | 38 | 7 |
11,819 | private ResultList < Genre > getGenreList ( String language , MethodSub sub ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . LANGUAGE , language ) ; URL url = new ApiUrl ( apiKey , MethodBase . GENRE ) . subMethod ( sub ) . buildUrl ( parameters ) ; String webpage = httpTools . getRequest ( url ) ; try { WrapperGenres wrapper = MAPPER . readValue ( webpage , WrapperGenres . class ) ; ResultList < Genre > results = new ResultList <> ( wrapper . getGenres ( ) ) ; wrapper . setResultProperties ( results ) ; return results ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get genre " + sub . toString ( ) , url , ex ) ; } } | Get the list of genres for movies or TV | 203 | 9 |
11,820 | public ResultList < MovieBasic > getGenreMovies ( int genreId , String language , Integer page , Boolean includeAllMovies , Boolean includeAdult ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , genreId ) ; parameters . add ( Param . LANGUAGE , language ) ; parameters . add ( Param . PAGE , page ) ; parameters . add ( Param . INCLUDE_ALL_MOVIES , includeAllMovies ) ; parameters . add ( Param . INCLUDE_ADULT , includeAdult ) ; URL url = new ApiUrl ( apiKey , MethodBase . GENRE ) . subMethod ( MethodSub . MOVIES ) . buildUrl ( parameters ) ; String webpage = httpTools . getRequest ( url ) ; WrapperGenericList < MovieBasic > wrapper = processWrapper ( getTypeReference ( MovieBasic . class ) , url , webpage ) ; return wrapper . getResultsList ( ) ; } | Get the list of movies for a particular genre by id . | 215 | 12 |
11,821 | public ResultList < ChangeKeyItem > getEpisodeChanges ( int episodeID , String startDate , String endDate ) throws MovieDbException { return getMediaChanges ( episodeID , startDate , endDate ) ; } | Look up a TV episode s changes by episode ID | 45 | 10 |
11,822 | public Account getAccount ( String sessionId ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . SESSION_ID , sessionId ) ; URL url = new ApiUrl ( apiKey , MethodBase . ACCOUNT ) . buildUrl ( parameters ) ; String webpage = httpTools . getRequest ( url ) ; try { return MAPPER . readValue ( webpage , Account . class ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get Account" , url , ex ) ; } } | Get the basic information for an account . You will need to have a valid session id . | 137 | 18 |
11,823 | public StatusCode modifyWatchList ( String sessionId , int accountId , MediaType mediaType , Integer movieId , boolean addToWatchlist ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . SESSION_ID , sessionId ) ; parameters . add ( Param . ID , accountId ) ; String jsonBody = new PostTools ( ) . add ( PostBody . MEDIA_TYPE , mediaType . toString ( ) . toLowerCase ( ) ) . add ( PostBody . MEDIA_ID , movieId ) . add ( PostBody . WATCHLIST , addToWatchlist ) . build ( ) ; URL url = new ApiUrl ( apiKey , MethodBase . ACCOUNT ) . subMethod ( MethodSub . WATCHLIST ) . buildUrl ( parameters ) ; String webpage = httpTools . postRequest ( url , jsonBody ) ; try { return MAPPER . readValue ( webpage , StatusCode . class ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to modify watch list" , url , ex ) ; } } | Add or remove a movie to an accounts watch list . | 252 | 11 |
11,824 | public Company getCompanyInfo ( int companyId ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , companyId ) ; URL url = new ApiUrl ( apiKey , MethodBase . COMPANY ) . buildUrl ( parameters ) ; String webpage = httpTools . getRequest ( url ) ; try { return MAPPER . readValue ( webpage , Company . class ) ; } catch ( IOException ex ) { throw new MovieDbException ( ApiExceptionType . MAPPING_FAILED , "Failed to get company information" , url , ex ) ; } } | This method is used to retrieve the basic information about a production company on TMDb . | 136 | 18 |
11,825 | public ResultList < AlternativeTitle > getTVAlternativeTitles ( int tvID ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , tvID ) ; URL url = new ApiUrl ( apiKey , MethodBase . TV ) . subMethod ( MethodSub . ALT_TITLES ) . buildUrl ( parameters ) ; WrapperGenericList < AlternativeTitle > wrapper = processWrapper ( getTypeReference ( AlternativeTitle . class ) , url , "alternative titles" ) ; return wrapper . getResultsList ( ) ; } | Get the alternative titles for a specific show ID . | 127 | 10 |
11,826 | public ResultList < ChangeKeyItem > getTVChanges ( int tvID , String startDate , String endDate ) throws MovieDbException { return getMediaChanges ( tvID , startDate , endDate ) ; } | Get the changes for a specific TV show id . | 45 | 10 |
11,827 | public ResultList < ContentRating > getTVContentRatings ( int tvID ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , tvID ) ; URL url = new ApiUrl ( apiKey , MethodBase . TV ) . subMethod ( MethodSub . CONTENT_RATINGS ) . buildUrl ( parameters ) ; WrapperGenericList < ContentRating > wrapper = processWrapper ( getTypeReference ( ContentRating . class ) , url , "content rating" ) ; return wrapper . getResultsList ( ) ; } | Get the content ratings for a specific TV show id . | 127 | 11 |
11,828 | public ResultList < Keyword > getTVKeywords ( int tvID ) throws MovieDbException { TmdbParameters parameters = new TmdbParameters ( ) ; parameters . add ( Param . ID , tvID ) ; URL url = new ApiUrl ( apiKey , MethodBase . TV ) . subMethod ( MethodSub . KEYWORDS ) . buildUrl ( parameters ) ; WrapperGenericList < Keyword > wrapper = processWrapper ( getTypeReference ( Keyword . class ) , url , "keywords" ) ; return wrapper . getResultsList ( ) ; } | Get the plot keywords for a specific TV show id . | 123 | 11 |
11,829 | protected void init ( ) { Log . d ( TAG , "init" ) ; if ( isInEditMode ( ) ) return ; this . mediaPlayer = null ; this . shouldAutoplay = false ; this . fullscreen = false ; this . initialConfigOrientation = - 1 ; this . videoIsReady = false ; this . surfaceIsReady = false ; this . initialMovieHeight = - 1 ; this . initialMovieWidth = - 1 ; this . setBackgroundColor ( Color . BLACK ) ; initObjects ( ) ; } | Initializes the default configuration | 114 | 5 |
11,830 | protected void release ( ) { Log . d ( TAG , "release" ) ; releaseObjects ( ) ; if ( this . mediaPlayer != null ) { this . mediaPlayer . setOnBufferingUpdateListener ( null ) ; this . mediaPlayer . setOnPreparedListener ( null ) ; this . mediaPlayer . setOnErrorListener ( null ) ; this . mediaPlayer . setOnSeekCompleteListener ( null ) ; this . mediaPlayer . setOnCompletionListener ( null ) ; this . mediaPlayer . setOnInfoListener ( null ) ; this . mediaPlayer . setOnVideoSizeChangedListener ( null ) ; this . mediaPlayer . release ( ) ; this . mediaPlayer = null ; } this . currentState = State . END ; } | Releases and ends the current Object | 159 | 7 |
11,831 | protected void initObjects ( ) { Log . d ( TAG , "initObjects" ) ; if ( this . mediaPlayer == null ) { this . mediaPlayer = new MediaPlayer ( ) ; this . mediaPlayer . setOnInfoListener ( this ) ; this . mediaPlayer . setOnErrorListener ( this ) ; this . mediaPlayer . setOnPreparedListener ( this ) ; this . mediaPlayer . setOnCompletionListener ( this ) ; this . mediaPlayer . setOnSeekCompleteListener ( this ) ; this . mediaPlayer . setOnBufferingUpdateListener ( this ) ; this . mediaPlayer . setOnVideoSizeChangedListener ( this ) ; this . mediaPlayer . setAudioStreamType ( AudioManager . STREAM_MUSIC ) ; } RelativeLayout . LayoutParams layoutParams ; View view ; if ( android . os . Build . VERSION . SDK_INT >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { if ( this . textureView == null ) { this . textureView = new TextureView ( this . context ) ; this . textureView . setSurfaceTextureListener ( this ) ; } view = this . textureView ; } else { if ( this . surfaceView == null ) { this . surfaceView = new SurfaceView ( context ) ; } view = this . surfaceView ; if ( this . surfaceHolder == null ) { this . surfaceHolder = this . surfaceView . getHolder ( ) ; //noinspection deprecation this . surfaceHolder . setType ( SurfaceHolder . SURFACE_TYPE_PUSH_BUFFERS ) ; this . surfaceHolder . addCallback ( this ) ; } } layoutParams = new RelativeLayout . LayoutParams ( LayoutParams . MATCH_PARENT , LayoutParams . MATCH_PARENT ) ; layoutParams . addRule ( CENTER_IN_PARENT ) ; view . setLayoutParams ( layoutParams ) ; addView ( view ) ; // Try not reset onProgressView if ( this . onProgressView == null ) this . onProgressView = new ProgressBar ( context ) ; layoutParams = new RelativeLayout . LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ; layoutParams . addRule ( CENTER_IN_PARENT ) ; this . onProgressView . setLayoutParams ( layoutParams ) ; addView ( this . onProgressView ) ; stopLoading ( ) ; this . currentState = State . IDLE ; } | Initializes all objects FullscreenVideoView depends on It does not interfere with configuration properties because it is supposed to be called when this Object still exists | 553 | 29 |
11,832 | protected void releaseObjects ( ) { Log . d ( TAG , "releaseObjects" ) ; if ( this . mediaPlayer != null ) { this . mediaPlayer . setSurface ( null ) ; this . mediaPlayer . reset ( ) ; } this . videoIsReady = false ; this . surfaceIsReady = false ; this . initialMovieHeight = - 1 ; this . initialMovieWidth = - 1 ; if ( android . os . Build . VERSION . SDK_INT >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { if ( this . textureView != null ) { this . textureView . setSurfaceTextureListener ( null ) ; removeView ( this . textureView ) ; this . textureView = null ; } } else { if ( this . surfaceHolder != null ) { this . surfaceHolder . removeCallback ( this ) ; this . surfaceHolder = null ; } if ( this . surfaceView != null ) { removeView ( this . surfaceView ) ; this . surfaceView = null ; } } if ( this . onProgressView != null ) { removeView ( this . onProgressView ) ; } } | Releases all objects FullscreenVideoView depends on It does not interfere with configuration properties because it is supposed to be called when this Object still exists | 249 | 29 |
11,833 | protected void tryToPrepare ( ) { Log . d ( TAG , "tryToPrepare" ) ; if ( this . surfaceIsReady && this . videoIsReady ) { if ( this . mediaPlayer != null && this . mediaPlayer . getVideoWidth ( ) != 0 && this . mediaPlayer . getVideoHeight ( ) != 0 ) { this . initialMovieWidth = this . mediaPlayer . getVideoWidth ( ) ; this . initialMovieHeight = this . mediaPlayer . getVideoHeight ( ) ; } resize ( ) ; stopLoading ( ) ; currentState = State . PREPARED ; if ( shouldAutoplay ) start ( ) ; if ( this . preparedListener != null ) this . preparedListener . onPrepared ( mediaPlayer ) ; } } | Try to call state PREPARED Only if SurfaceView is already created and MediaPlayer is prepared Video is loaded and is ok to play . | 162 | 28 |
11,834 | public void setFullscreen ( final boolean fullscreen ) throws RuntimeException { if ( mediaPlayer == null ) throw new RuntimeException ( "Media Player is not initialized" ) ; if ( this . currentState != State . ERROR ) { if ( FullscreenVideoView . this . fullscreen == fullscreen ) return ; FullscreenVideoView . this . fullscreen = fullscreen ; final boolean wasPlaying = mediaPlayer . isPlaying ( ) ; if ( wasPlaying ) pause ( ) ; if ( FullscreenVideoView . this . fullscreen ) { if ( activity != null ) activity . setRequestedOrientation ( ActivityInfo . SCREEN_ORIENTATION_UNSPECIFIED ) ; View rootView = getRootView ( ) ; View v = rootView . findViewById ( android . R . id . content ) ; ViewParent viewParent = getParent ( ) ; if ( viewParent instanceof ViewGroup ) { if ( parentView == null ) parentView = ( ViewGroup ) viewParent ; // Prevents MediaPlayer to became invalidated and released detachedByFullscreen = true ; // Saves the last state (LayoutParams) of view to restore after currentLayoutParams = FullscreenVideoView . this . getLayoutParams ( ) ; parentView . removeView ( FullscreenVideoView . this ) ; } else Log . e ( TAG , "Parent View is not a ViewGroup" ) ; if ( v instanceof ViewGroup ) { ( ( ViewGroup ) v ) . addView ( FullscreenVideoView . this ) ; } else Log . e ( TAG , "RootView is not a ViewGroup" ) ; } else { if ( activity != null ) activity . setRequestedOrientation ( initialConfigOrientation ) ; ViewParent viewParent = getParent ( ) ; if ( viewParent instanceof ViewGroup ) { // Check if parent view is still available boolean parentHasParent = false ; if ( parentView != null && parentView . getParent ( ) != null ) { parentHasParent = true ; detachedByFullscreen = true ; } ( ( ViewGroup ) viewParent ) . removeView ( FullscreenVideoView . this ) ; if ( parentHasParent ) { parentView . addView ( FullscreenVideoView . this ) ; FullscreenVideoView . this . setLayoutParams ( currentLayoutParams ) ; } } } resize ( ) ; Handler handler = new Handler ( Looper . getMainLooper ( ) ) ; handler . post ( new Runnable ( ) { @ Override public void run ( ) { if ( wasPlaying && mediaPlayer != null ) start ( ) ; } } ) ; } } | Turn VideoView fulllscreen mode on or off . | 558 | 11 |
11,835 | @ Override public void onClick ( View v ) { if ( v . getId ( ) == R . id . vcv_img_play ) { if ( isPlaying ( ) ) { pause ( ) ; } else { start ( ) ; } } else { setFullscreen ( ! isFullscreen ( ) ) ; } } | Onclick action Controls play button and fullscreen button . | 70 | 11 |
11,836 | public void populate ( final AnnotationData data , final Annotation annotation , final Class < ? extends Annotation > expectedAnnotationClass , final Method targetMethod ) throws Exception { if ( support ( expectedAnnotationClass ) ) { build ( data , annotation , expectedAnnotationClass , targetMethod ) ; } } | Populates additional data into annotation data . | 64 | 8 |
11,837 | protected Cache createCache ( ) throws IOException { // this factory creates only one single cache and return it if someone invoked this method twice or // more if ( cache != null ) { throw new IllegalStateException ( String . format ( "This factory has already created memcached client for cache %s" , cacheName ) ) ; } if ( isCacheDisabled ( ) ) { LOGGER . warn ( "Cache {} is disabled" , cacheName ) ; cache = ( Cache ) Proxy . newProxyInstance ( Cache . class . getClassLoader ( ) , new Class [ ] { Cache . class } , new DisabledCacheInvocationHandler ( cacheName , cacheAliases ) ) ; return cache ; } if ( configuration == null ) { throw new RuntimeException ( String . format ( "The MemcachedConnectionBean for cache %s must be defined!" , cacheName ) ) ; } List < InetSocketAddress > addrs = addressProvider . getAddresses ( ) ; cache = new CacheImpl ( cacheName , cacheAliases , createClient ( addrs ) , defaultSerializationType , jsonTranscoder , javaTranscoder , customTranscoder , new CacheProperties ( configuration . isUseNameAsKeyPrefix ( ) , configuration . getKeyPrefixSeparator ( ) ) ) ; return cache ; } | Only one cache is created . | 279 | 6 |
11,838 | @ Override public String getCacheKey ( final Object keyObject , final String namespace ) { return namespace + SEPARATOR + defaultKeyProvider . generateKey ( keyObject ) ; } | Builds cache key from one key object . | 38 | 9 |
11,839 | private String buildCacheKey ( final String [ ] objectIds , final String namespace ) { if ( objectIds . length == 1 ) { checkKeyPart ( objectIds [ 0 ] ) ; return namespace + SEPARATOR + objectIds [ 0 ] ; } StringBuilder cacheKey = new StringBuilder ( namespace ) ; cacheKey . append ( SEPARATOR ) ; for ( String id : objectIds ) { checkKeyPart ( id ) ; cacheKey . append ( id ) ; cacheKey . append ( ID_SEPARATOR ) ; } cacheKey . deleteCharAt ( cacheKey . length ( ) - 1 ) ; return cacheKey . toString ( ) ; } | Build cache key . | 144 | 4 |
11,840 | public void removeCache ( final String nameOrAlias ) { final Cache cache = cacheMap . get ( nameOrAlias ) ; if ( cache == null ) { return ; } final SSMCache ssmCache = ( SSMCache ) cache ; if ( ssmCache . isRegisterAliases ( ) ) { ssmCache . getCache ( ) . getAliases ( ) . forEach ( this :: unregisterCache ) ; } unregisterCache ( nameOrAlias ) ; unregisterCache ( cache . getName ( ) ) ; caches . removeIf ( c -> c . getName ( ) . equals ( cache . getName ( ) ) ) ; } | Removes given cache and related aliases . | 138 | 8 |
11,841 | protected Object deserialize ( final byte [ ] in ) { Object o = null ; ByteArrayInputStream bis = null ; ConfigurableObjectInputStream is = null ; try { if ( in != null ) { bis = new ByteArrayInputStream ( in ) ; is = new ConfigurableObjectInputStream ( bis , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; o = is . readObject ( ) ; is . close ( ) ; bis . close ( ) ; } } catch ( IOException e ) { LOGGER . warn ( String . format ( "Caught IOException decoding %d bytes of data" , in . length ) , e ) ; } catch ( ClassNotFoundException e ) { LOGGER . warn ( String . format ( "Caught CNFE decoding %d bytes of data" , in . length ) , e ) ; } finally { close ( is ) ; close ( bis ) ; } return o ; } | Deserialize given stream using java deserialization . | 199 | 11 |
11,842 | @ Override @ SuppressWarnings ( "unchecked" ) public < T > T get ( final Object key , final Class < T > type ) { if ( ! cache . isEnabled ( ) ) { LOGGER . warn ( "Cache {} is disabled. Cannot get {} from cache" , cache . getName ( ) , key ) ; return null ; } Object value = getValue ( key ) ; if ( value == null ) { LOGGER . info ( "Cache miss. Get by key {} and type {} from cache {}" , new Object [ ] { key , type , cache . getName ( ) } ) ; return null ; } if ( value instanceof PertinentNegativeNull ) { return null ; } if ( type != null && ! type . isInstance ( value ) ) { // in such case default Spring back end for EhCache throws IllegalStateException which interrupts // intercepted method invocation String msg = "Cached value is not of required type [" + type . getName ( ) + "]: " + value ; LOGGER . error ( msg , new IllegalStateException ( msg ) ) ; return null ; } LOGGER . info ( "Cache hit. Get by key {} and type {} from cache {} value '{}'" , new Object [ ] { key , type , cache . getName ( ) , value } ) ; return ( T ) value ; } | Required by Spring 4 . 0 | 288 | 6 |
11,843 | @ Override @ SuppressWarnings ( "unchecked" ) public < T > T get ( final Object key , final Callable < T > valueLoader ) { if ( ! cache . isEnabled ( ) ) { LOGGER . warn ( "Cache {} is disabled. Cannot get {} from cache" , cache . getName ( ) , key ) ; return loadValue ( key , valueLoader ) ; } final ValueWrapper valueWrapper = get ( key ) ; if ( valueWrapper != null ) { return ( T ) valueWrapper . get ( ) ; } synchronized ( key . toString ( ) . intern ( ) ) { final T value = loadValue ( key , valueLoader ) ; put ( key , value ) ; return value ; } } | Required by Spring 4 . 3 | 159 | 6 |
11,844 | @ Override public ValueWrapper putIfAbsent ( final Object key , final Object value ) { if ( ! cache . isEnabled ( ) ) { LOGGER . warn ( "Cache {} is disabled. Cannot put value under key {}" , cache . getName ( ) , key ) ; return null ; } if ( key != null ) { final String cacheKey = getKey ( key ) ; try { LOGGER . info ( "Put '{}' under key {} to cache {}" , new Object [ ] { value , key , cache . getName ( ) } ) ; final Object store = toStoreValue ( value ) ; final boolean added = cache . add ( cacheKey , expiration , store , null ) ; return added ? null : get ( key ) ; } catch ( TimeoutException | CacheException | RuntimeException e ) { logOrThrow ( e , "An error has ocurred for cache {} and key {}" , getName ( ) , cacheKey , e ) ; } } else { LOGGER . info ( "Cannot put to cache {} because key is null" , cache . getName ( ) ) ; } return null ; } | Required by Spring 4 . 1 | 242 | 6 |
11,845 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static Seq toScalaSeq ( Object [ ] o ) { ArrayList list = new ArrayList ( ) ; for ( int i = 0 ; i < o . length ; i ++ ) { list . add ( o [ i ] ) ; } return scala . collection . JavaConversions . asScalaBuffer ( list ) . toList ( ) ; } | Takes an array of objects and returns a scala Seq | 97 | 13 |
11,846 | public static UnsignedInteger64 add ( UnsignedInteger64 x , UnsignedInteger64 y ) { return new UnsignedInteger64 ( x . bigInt . add ( y . bigInt ) ) ; } | Add an unsigned integer to another unsigned integer . | 43 | 9 |
11,847 | public static UnsignedInteger64 add ( UnsignedInteger64 x , int y ) { return new UnsignedInteger64 ( x . bigInt . add ( BigInteger . valueOf ( y ) ) ) ; } | Add an unsigned integer to an int . | 44 | 8 |
11,848 | public byte [ ] toByteArray ( ) { byte [ ] raw = new byte [ 8 ] ; byte [ ] bi = bigIntValue ( ) . toByteArray ( ) ; System . arraycopy ( bi , 0 , raw , raw . length - bi . length , bi . length ) ; return raw ; } | Returns a byte array encoded with the unsigned integer . | 66 | 10 |
11,849 | public void remove ( SshPublicKey key ) throws SshException , PublicKeySubsystemException { try { Packet msg = createPacket ( ) ; msg . writeString ( "remove" ) ; msg . writeString ( key . getAlgorithm ( ) ) ; msg . writeBinaryString ( key . getEncoded ( ) ) ; sendMessage ( msg ) ; readStatusResponse ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Remove a public key from the users list of acceptable keys . | 104 | 12 |
11,850 | public SshPublicKey [ ] list ( ) throws SshException , PublicKeySubsystemException { try { Packet msg = createPacket ( ) ; msg . writeString ( "list" ) ; sendMessage ( msg ) ; Vector < SshPublicKey > keys = new Vector < SshPublicKey > ( ) ; while ( true ) { ByteArrayReader response = new ByteArrayReader ( nextMessage ( ) ) ; try { String type = response . readString ( ) ; if ( type . equals ( "publickey" ) ) { @ SuppressWarnings ( "unused" ) String comment = response . readString ( ) ; String algorithm = response . readString ( ) ; keys . addElement ( SshPublicKeyFileFactory . decodeSSH2PublicKey ( algorithm , response . readBinaryString ( ) ) ) ; } else if ( type . equals ( "status" ) ) { int status = ( int ) response . readInt ( ) ; String desc = response . readString ( ) ; if ( status != PublicKeySubsystemException . SUCCESS ) { throw new PublicKeySubsystemException ( status , desc ) ; } SshPublicKey [ ] array = new SshPublicKey [ keys . size ( ) ] ; keys . copyInto ( array ) ; return array ; } else { throw new SshException ( "The server sent an invalid response to a list command" , SshException . PROTOCOL_VIOLATION ) ; } } finally { try { response . close ( ) ; } catch ( IOException e ) { } } } } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | List all of the users acceptable keys . | 355 | 8 |
11,851 | public void associateCommand ( SshPublicKey key , String command ) throws SshException , PublicKeySubsystemException { try { Packet msg = createPacket ( ) ; msg . writeString ( "command" ) ; msg . writeString ( key . getAlgorithm ( ) ) ; msg . writeBinaryString ( key . getEncoded ( ) ) ; msg . writeString ( command ) ; sendMessage ( msg ) ; readStatusResponse ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Associate a command with an accepted public key . The request will fail if the public key is not currently in the users acceptable list . Also some server implementations may choose not to support this feature . | 116 | 39 |
11,852 | void readStatusResponse ( ) throws SshException , PublicKeySubsystemException { ByteArrayReader msg = new ByteArrayReader ( nextMessage ( ) ) ; try { msg . readString ( ) ; int status = ( int ) msg . readInt ( ) ; String desc = msg . readString ( ) ; if ( status != PublicKeySubsystemException . SUCCESS ) { throw new PublicKeySubsystemException ( status , desc ) ; } } catch ( IOException ex ) { throw new SshException ( ex ) ; } finally { try { msg . close ( ) ; } catch ( IOException e ) { } } } | Read a status response and throw an exception if an error has occurred . | 133 | 14 |
11,853 | public void setTerminalMode ( int mode , int value ) throws SshException { try { encodedModes . write ( mode ) ; if ( version == 1 && mode <= 127 ) { encodedModes . write ( value ) ; } else { encodedModes . writeInt ( value ) ; } } catch ( IOException ex ) { throw new SshException ( SshException . INTERNAL_ERROR , ex ) ; } } | Set an integer value mode | 92 | 5 |
11,854 | protected ProxyMessage exchange ( ProxyMessage request ) throws SocksException { ProxyMessage reply ; try { request . write ( out ) ; reply = formMessage ( in ) ; } catch ( SocksException s_ex ) { throw s_ex ; } catch ( IOException ioe ) { throw ( new SocksException ( SOCKS_PROXY_IO_ERROR , "" + ioe ) ) ; } return reply ; } | Sends the request reads reply and returns it throws exception if something wrong with IO or the reply code is not zero | 90 | 23 |
11,855 | public String [ ] matchFileNamesWithPattern ( File [ ] files , String fileNameRegExp ) throws SshException , SftpStatusException { String [ ] thefile = new String [ 1 ] ; thefile [ 0 ] = files [ 0 ] . getName ( ) ; return thefile ; } | opens and returns the requested filename string | 65 | 7 |
11,856 | public synchronized void addListener ( String threadPrefix , EventListener listener ) { if ( threadPrefix . trim ( ) . equals ( "" ) ) { globalListeners . addElement ( listener ) ; } else { keyedListeners . put ( threadPrefix . trim ( ) , listener ) ; } } | Add a J2SSH Listener to the list of listeners that will be sent events | 65 | 18 |
11,857 | public synchronized void fireEvent ( Event evt ) { if ( evt == null ) { return ; } // Process global listeners for ( Enumeration < EventListener > keys = globalListeners . elements ( ) ; keys . hasMoreElements ( ) ; ) { EventListener mListener = keys . nextElement ( ) ; try { mListener . processEvent ( evt ) ; } catch ( Throwable t ) { } } String sourceThread = Thread . currentThread ( ) . getName ( ) ; for ( Enumeration < String > keys = keyedListeners . keys ( ) ; keys . hasMoreElements ( ) ; ) { String key = ( String ) keys . nextElement ( ) ; // We don't want badly behaved listeners to throw uncaught // exceptions and upset other listeners try { String prefix = "" ; if ( sourceThread . indexOf ( ' ' ) > - 1 ) { prefix = sourceThread . substring ( 0 , sourceThread . indexOf ( ' ' ) ) ; if ( key . startsWith ( prefix ) ) { EventListener mListener = keyedListeners . get ( key ) ; mListener . processEvent ( evt ) ; } } } catch ( Throwable thr ) { // log.error("Event failed.", thr); } } } | Send an SSH Event to each registered listener | 270 | 8 |
11,858 | public void close ( ) throws IOException { try { while ( processNextResponse ( 0 ) ) ; file . close ( ) ; } catch ( SshException ex ) { throw new SshIOException ( ex ) ; } catch ( SftpStatusException ex ) { throw new IOException ( ex . getMessage ( ) ) ; } } | Closes the file s handle | 72 | 6 |
11,859 | public static void setCharsetEncoding ( String charset ) { try { String test = "123456890" ; test . getBytes ( charset ) ; CHARSET_ENCODING = charset ; encode = true ; } catch ( UnsupportedEncodingException ex ) { // Reset the encoding to default CHARSET_ENCODING = "" ; encode = false ; } } | Allows the default encoding to be overriden for String variables processed by the class . This currently defaults to UTF - 8 . | 84 | 25 |
11,860 | public BigInteger readBigInteger ( ) throws IOException { int len = ( int ) readInt ( ) ; byte [ ] raw = new byte [ len ] ; readFully ( raw ) ; return new BigInteger ( raw ) ; } | Read a BigInteger from the array . | 50 | 8 |
11,861 | public String readString ( String charset ) throws IOException { long len = readInt ( ) ; if ( len > available ( ) ) throw new IOException ( "Cannot read string of length " + len + " bytes when only " + available ( ) + " bytes are available" ) ; byte [ ] raw = new byte [ ( int ) len ] ; readFully ( raw ) ; if ( encode ) { return new String ( raw , charset ) ; } return new String ( raw ) ; } | Read a String from the array converting using the given character set . | 107 | 13 |
11,862 | public BigInteger readMPINT32 ( ) throws IOException { int bits = ( int ) readInt ( ) ; byte [ ] raw = new byte [ ( bits + 7 ) / 8 + 1 ] ; raw [ 0 ] = 0 ; readFully ( raw , 1 , raw . length - 1 ) ; return new BigInteger ( raw ) ; } | Reads an MPINT using the first 32 bits as the length prefix | 74 | 14 |
11,863 | public BigInteger readMPINT ( ) throws IOException { short bits = readShort ( ) ; byte [ ] raw = new byte [ ( bits + 7 ) / 8 + 1 ] ; raw [ 0 ] = 0 ; readFully ( raw , 1 , raw . length - 1 ) ; return new BigInteger ( raw ) ; } | Reads a standard SSH1 MPINT using the first 16 bits as the length prefix | 70 | 17 |
11,864 | public static SocksProxyTransport connectViaSocks4Proxy ( String remoteHost , int remotePort , String proxyHost , int proxyPort , String userId ) throws IOException , UnknownHostException { SocksProxyTransport proxySocket = new SocksProxyTransport ( remoteHost , remotePort , proxyHost , proxyPort , SOCKS4 ) ; proxySocket . username = userId ; try { InputStream proxyIn = proxySocket . getInputStream ( ) ; OutputStream proxyOut = proxySocket . getOutputStream ( ) ; InetAddress hostAddr = InetAddress . getByName ( remoteHost ) ; proxyOut . write ( SOCKS4 ) ; proxyOut . write ( CONNECT ) ; proxyOut . write ( ( remotePort >>> 8 ) & 0xff ) ; proxyOut . write ( remotePort & 0xff ) ; proxyOut . write ( hostAddr . getAddress ( ) ) ; proxyOut . write ( userId . getBytes ( ) ) ; proxyOut . write ( NULL_TERMINATION ) ; proxyOut . flush ( ) ; int res = proxyIn . read ( ) ; if ( res == - 1 ) { throw new IOException ( "SOCKS4 server " + proxyHost + ":" + proxyPort + " disconnected" ) ; } if ( res != 0x00 ) { throw new IOException ( "Invalid response from SOCKS4 server (" + res + ") " + proxyHost + ":" + proxyPort ) ; } int code = proxyIn . read ( ) ; if ( code != 90 ) { if ( ( code > 90 ) && ( code < 93 ) ) { throw new IOException ( "SOCKS4 server unable to connect, reason: " + SOCKSV4_ERROR [ code - 91 ] ) ; } throw new IOException ( "SOCKS4 server unable to connect, reason: " + code ) ; } byte [ ] data = new byte [ 6 ] ; if ( proxyIn . read ( data , 0 , 6 ) != 6 ) { throw new IOException ( "SOCKS4 error reading destination address/port" ) ; } proxySocket . setProviderDetail ( data [ 2 ] + "." + data [ 3 ] + "." + data [ 4 ] + "." + data [ 5 ] + ":" + ( ( data [ 0 ] << 8 ) | data [ 1 ] ) ) ; } catch ( SocketException e ) { throw new SocketException ( "Error communicating with SOCKS4 server " + proxyHost + ":" + proxyPort + ", " + e . getMessage ( ) ) ; } return proxySocket ; } | Connect the socket to a SOCKS 4 proxy and request forwarding to our remote host . | 560 | 18 |
11,865 | protected void sendMessage ( byte [ ] msg ) throws SshException { try { Packet pkt = createPacket ( ) ; pkt . write ( msg ) ; sendMessage ( pkt ) ; } catch ( IOException ex ) { throw new SshException ( SshException . UNEXPECTED_TERMINATION , ex ) ; } } | Send a byte array as a message . | 75 | 8 |
11,866 | protected Packet createPacket ( ) throws IOException { synchronized ( packets ) { if ( packets . size ( ) == 0 ) return new Packet ( ) ; Packet p = ( Packet ) packets . elementAt ( 0 ) ; packets . removeElementAt ( 0 ) ; return p ; } } | Get a packet from the available pool or create if non available | 64 | 12 |
11,867 | public static SshKeyPair generateKeyPair ( String algorithm , int bits ) throws IOException , SshException { if ( ! SSH2_RSA . equalsIgnoreCase ( algorithm ) && ! SSH2_DSA . equalsIgnoreCase ( algorithm ) ) { throw new IOException ( algorithm + " is not a supported key algorithm!" ) ; } SshKeyPair pair = new SshKeyPair ( ) ; if ( SSH2_RSA . equalsIgnoreCase ( algorithm ) ) { pair = ComponentManager . getInstance ( ) . generateRsaKeyPair ( bits ) ; } else { pair = ComponentManager . getInstance ( ) . generateDsaKeyPair ( bits ) ; } return pair ; } | Generates a new key pair . | 158 | 7 |
11,868 | public void setUID ( String uid ) { if ( version > 3 ) { flags |= SSH_FILEXFER_ATTR_OWNERGROUP ; } else flags |= SSH_FILEXFER_ATTR_UIDGID ; this . uid = uid ; } | Set the UID of the owner . | 60 | 7 |
11,869 | public void setGID ( String gid ) { if ( version > 3 ) { flags |= SSH_FILEXFER_ATTR_OWNERGROUP ; } else flags |= SSH_FILEXFER_ATTR_UIDGID ; this . gid = gid ; } | Set the GID of this file . | 61 | 8 |
11,870 | public void setSize ( UnsignedInteger64 size ) { this . size = size ; // Set the flag if ( size != null ) { flags |= SSH_FILEXFER_ATTR_SIZE ; } else { flags ^= SSH_FILEXFER_ATTR_SIZE ; } } | Set the size of the file . | 62 | 7 |
11,871 | public void setPermissions ( UnsignedInteger32 permissions ) { this . permissions = permissions ; // Set the flag if ( permissions != null ) { flags |= SSH_FILEXFER_ATTR_PERMISSIONS ; } else { flags ^= SSH_FILEXFER_ATTR_PERMISSIONS ; } } | Set the permissions of the file . This value should be a valid mask of the permissions flags defined within this class . | 69 | 23 |
11,872 | public void setPermissionsFromMaskString ( String mask ) { if ( mask . length ( ) != 4 ) { throw new IllegalArgumentException ( "Mask length must be 4" ) ; } try { setPermissions ( new UnsignedInteger32 ( String . valueOf ( Integer . parseInt ( mask , 8 ) ) ) ) ; } catch ( NumberFormatException nfe ) { throw new IllegalArgumentException ( "Mask must be 4 digit octal number." ) ; } } | Set permissions given a UNIX style mask for example 0644 | 102 | 12 |
11,873 | public void setPermissionsFromUmaskString ( String umask ) { if ( umask . length ( ) != 4 ) { throw new IllegalArgumentException ( "umask length must be 4" ) ; } try { setPermissions ( new UnsignedInteger32 ( String . valueOf ( Integer . parseInt ( umask , 8 ) ^ 0777 ) ) ) ; } catch ( NumberFormatException ex ) { throw new IllegalArgumentException ( "umask must be 4 digit octal number" ) ; } } | Set the permissions given a UNIX style umask for example 0022 will result in 0022 ^ 0777 . | 110 | 23 |
11,874 | public String getMaskString ( ) { StringBuffer buf = new StringBuffer ( ) ; if ( permissions != null ) { int i = ( int ) permissions . longValue ( ) ; buf . append ( ' ' ) ; buf . append ( octal ( i , 6 ) ) ; buf . append ( octal ( i , 3 ) ) ; buf . append ( octal ( i , 0 ) ) ; } else { buf . append ( "----" ) ; } return buf . toString ( ) ; } | Return the UNIX style mode mask | 107 | 7 |
11,875 | public boolean isDirectory ( ) { if ( sftp . getVersion ( ) > 3 ) { return type == SSH_FILEXFER_TYPE_DIRECTORY ; } else if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFDIR ) == SftpFileAttributes . S_IFDIR ) { return true ; } else { return false ; } } | Determine whether these attributes refer to a directory | 87 | 10 |
11,876 | public boolean isLink ( ) { if ( sftp . getVersion ( ) > 3 ) { return type == SSH_FILEXFER_TYPE_SYMLINK ; } else if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFLNK ) == SftpFileAttributes . S_IFLNK ) { return true ; } else { return false ; } } | Determine whether these attributes refer to a symbolic link . | 89 | 12 |
11,877 | public boolean isFifo ( ) { if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFIFO ) == SftpFileAttributes . S_IFIFO ) { return true ; } return false ; } | Determine whether these attributes refer to a pipe . | 56 | 11 |
11,878 | public boolean isBlock ( ) { if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFBLK ) == SftpFileAttributes . S_IFBLK ) { return true ; } return false ; } | Determine whether these attributes refer to a block special file . | 55 | 13 |
11,879 | public boolean isCharacter ( ) { if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFCHR ) == SftpFileAttributes . S_IFCHR ) { return true ; } return false ; } | Determine whether these attributes refer to a character device . | 53 | 12 |
11,880 | public boolean isSocket ( ) { if ( permissions != null && ( permissions . longValue ( ) & SftpFileAttributes . S_IFSOCK ) == SftpFileAttributes . S_IFSOCK ) { return true ; } return false ; } | Determine whether these attributes refer to a socket . | 55 | 11 |
11,881 | public static Provider getProviderForAlgorithm ( String jceAlgorithm ) { if ( specficProviders . containsKey ( jceAlgorithm ) ) { return ( Provider ) specficProviders . get ( jceAlgorithm ) ; } return defaultProvider ; } | Get the provider for a specific algorithm . | 58 | 8 |
11,882 | public static SecureRandom getSecureRandom ( ) throws NoSuchAlgorithmException { if ( secureRandom == null ) { try { return secureRandom = JCEProvider . getProviderForAlgorithm ( JCEProvider . getSecureRandomAlgorithm ( ) ) == null ? SecureRandom . getInstance ( JCEProvider . getSecureRandomAlgorithm ( ) ) : SecureRandom . getInstance ( JCEProvider . getSecureRandomAlgorithm ( ) , JCEProvider . getProviderForAlgorithm ( JCEProvider . getSecureRandomAlgorithm ( ) ) ) ; } catch ( NoSuchAlgorithmException e ) { return secureRandom = SecureRandom . getInstance ( JCEProvider . getSecureRandomAlgorithm ( ) ) ; } } return secureRandom ; } | Get the secure random implementation for the API . | 157 | 9 |
11,883 | public boolean containsFile ( File f ) { return unchangedFiles . contains ( f ) || newFiles . contains ( f ) || updatedFiles . contains ( f ) || deletedFiles . contains ( f ) || recursedDirectories . contains ( f ) || failedTransfers . containsKey ( f ) ; } | Determine whether the operation contains a file . | 64 | 10 |
11,884 | public boolean containsFile ( SftpFile f ) { return unchangedFiles . contains ( f ) || newFiles . contains ( f ) || updatedFiles . contains ( f ) || deletedFiles . contains ( f ) || recursedDirectories . contains ( f . getAbsolutePath ( ) ) || failedTransfers . containsKey ( f ) ; } | Determine whether the directory operation contains an SftpFile | 74 | 13 |
11,885 | public void addDirectoryOperation ( DirectoryOperation op , File f ) { addAll ( op . getUpdatedFiles ( ) , updatedFiles ) ; addAll ( op . getNewFiles ( ) , newFiles ) ; addAll ( op . getUnchangedFiles ( ) , unchangedFiles ) ; addAll ( op . getDeletedFiles ( ) , deletedFiles ) ; Object obj ; for ( Enumeration e = op . failedTransfers . keys ( ) ; e . hasMoreElements ( ) ; ) { obj = e . nextElement ( ) ; failedTransfers . put ( obj , op . failedTransfers . get ( obj ) ) ; } recursedDirectories . addElement ( f ) ; } | Add the contents of another directory operation . This is used to record changes when recuring through directories . | 152 | 20 |
11,886 | public long getTransferSize ( ) throws SftpStatusException , SshException { Object obj ; long size = 0 ; SftpFile sftpfile ; File file ; for ( Enumeration e = newFiles . elements ( ) ; e . hasMoreElements ( ) ; ) { obj = e . nextElement ( ) ; if ( obj instanceof File ) { file = ( File ) obj ; if ( file . isFile ( ) ) { size += file . length ( ) ; } } else if ( obj instanceof SftpFile ) { sftpfile = ( SftpFile ) obj ; if ( sftpfile . isFile ( ) ) { size += sftpfile . getAttributes ( ) . getSize ( ) . longValue ( ) ; } } } for ( Enumeration e = updatedFiles . elements ( ) ; e . hasMoreElements ( ) ; ) { obj = e . nextElement ( ) ; if ( obj instanceof File ) { file = ( File ) obj ; if ( file . isFile ( ) ) { size += file . length ( ) ; } } else if ( obj instanceof SftpFile ) { sftpfile = ( SftpFile ) obj ; if ( sftpfile . isFile ( ) ) { size += sftpfile . getAttributes ( ) . getSize ( ) . longValue ( ) ; } } } // Add a value for deleted files?? return size ; } | Get the total number of bytes that this operation will transfer | 314 | 11 |
11,887 | public void writeBigInteger ( BigInteger bi ) throws IOException { byte [ ] raw = bi . toByteArray ( ) ; writeInt ( raw . length ) ; write ( raw ) ; } | Write a BigInteger to the array . | 41 | 8 |
11,888 | public void writeInt ( long i ) throws IOException { byte [ ] raw = new byte [ 4 ] ; raw [ 0 ] = ( byte ) ( i >> 24 ) ; raw [ 1 ] = ( byte ) ( i >> 16 ) ; raw [ 2 ] = ( byte ) ( i >> 8 ) ; raw [ 3 ] = ( byte ) ( i ) ; write ( raw ) ; } | Write an integer to the array | 83 | 6 |
11,889 | public static byte [ ] encodeInt ( int i ) { byte [ ] raw = new byte [ 4 ] ; raw [ 0 ] = ( byte ) ( i >> 24 ) ; raw [ 1 ] = ( byte ) ( i >> 16 ) ; raw [ 2 ] = ( byte ) ( i >> 8 ) ; raw [ 3 ] = ( byte ) ( i ) ; return raw ; } | Encode an integer into a 4 byte array . | 81 | 10 |
11,890 | public void writeString ( String str , String charset ) throws IOException { if ( str == null ) { writeInt ( 0 ) ; } else { byte [ ] tmp ; if ( ByteArrayReader . encode ) tmp = str . getBytes ( charset ) ; else tmp = str . getBytes ( ) ; writeInt ( tmp . length ) ; write ( tmp ) ; } } | Write a String to the byte array converting the bytes using the given character set . | 81 | 16 |
11,891 | public void initialize ( ) throws SshException , UnsupportedEncodingException { // Initialize the SFTP subsystem try { Packet packet = createPacket ( ) ; packet . write ( SSH_FXP_INIT ) ; packet . writeInt ( this_MAX_VERSION ) ; sendMessage ( packet ) ; byte [ ] msg = nextMessage ( ) ; if ( msg [ 0 ] != SSH_FXP_VERSION ) { close ( ) ; throw new SshException ( "Unexpected response from SFTP subsystem." , SshException . CHANNEL_FAILURE ) ; } ByteArrayReader bar = new ByteArrayReader ( msg ) ; try { bar . skip ( 1 ) ; serverVersion = ( int ) bar . readInt ( ) ; version = Math . min ( serverVersion , MAX_VERSION ) ; try { while ( bar . available ( ) > 0 ) { String name = bar . readString ( ) ; byte [ ] data = bar . readBinaryString ( ) ; extensions . put ( name , data ) ; } } catch ( Throwable t ) { } } finally { bar . close ( ) ; } if ( version <= 3 ) setCharsetEncoding ( "ISO-8859-1" ) ; else setCharsetEncoding ( "UTF8" ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( SshException . CHANNEL_FAILURE , ex ) ; } catch ( Throwable t ) { throw new SshException ( SshException . CHANNEL_FAILURE , t ) ; } } | Initializes the sftp subsystem and negotiates a version with the server . This method must be the first method called after the channel has been opened . This implementation current supports SFTP protocol version 4 and below . | 356 | 43 |
11,892 | public void setCharsetEncoding ( String charset ) throws SshException , UnsupportedEncodingException { if ( version == - 1 ) throw new SshException ( "SFTP Channel must be initialized before setting character set encoding" , SshException . BAD_API_USAGE ) ; String test = "123456890" ; test . getBytes ( charset ) ; CHARSET_ENCODING = charset ; } | Allows the default character encoding to be overriden for filename strings . This method should only be called once the channel has been initialized if the version of the protocol is less than or equal to 3 the encoding is defaulted to latin1 as no encoding is specified by the protocol . If the version is greater than 3 the default encoding will be UTF - 8 . | 94 | 73 |
11,893 | public SftpMessage sendExtensionMessage ( String request , byte [ ] requestData ) throws SshException , SftpStatusException { try { UnsignedInteger32 id = nextRequestId ( ) ; Packet packet = createPacket ( ) ; packet . write ( SSH_FXP_EXTENDED ) ; packet . writeUINT32 ( id ) ; packet . writeString ( request ) ; sendMessage ( packet ) ; return getResponse ( id ) ; } catch ( IOException ex ) { throw new SshException ( SshException . INTERNAL_ERROR , ex ) ; } } | Send an extension message and return the response . This is for advanced use only . | 127 | 16 |
11,894 | public UnsignedInteger32 postWriteRequest ( byte [ ] handle , long position , byte [ ] data , int off , int len ) throws SftpStatusException , SshException { if ( ( data . length - off ) < len ) { throw new IndexOutOfBoundsException ( "Incorrect data array size!" ) ; } try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_WRITE ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeBinaryString ( handle ) ; msg . writeUINT64 ( position ) ; msg . writeBinaryString ( data , off , len ) ; sendMessage ( msg ) ; return requestId ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Send a write request for an open file but do not wait for the response from the server . | 205 | 19 |
11,895 | public void writeFile ( byte [ ] handle , UnsignedInteger64 offset , byte [ ] data , int off , int len ) throws SftpStatusException , SshException { getOKRequestStatus ( postWriteRequest ( handle , offset . longValue ( ) , data , off , len ) ) ; } | Write a block of data to an open file . | 65 | 10 |
11,896 | public void performSynchronousRead ( byte [ ] handle , int blocksize , OutputStream out , FileTransferProgress progress , long position ) throws SftpStatusException , SshException , TransferCancelledException { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Performing synchronous read postion=" + position + " blocksize=" + blocksize ) ; } if ( blocksize < 1 || blocksize > 32768 ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Blocksize to large for some SFTP servers, reseting to 32K" ) ; } blocksize = 32768 ; } if ( position < 0 ) { throw new SshException ( "Position value must be greater than zero!" , SshException . BAD_API_USAGE ) ; } byte [ ] tmp = new byte [ blocksize ] ; int read ; UnsignedInteger64 offset = new UnsignedInteger64 ( position ) ; if ( position > 0 ) { if ( progress != null ) progress . progressed ( position ) ; } try { while ( ( read = readFile ( handle , offset , tmp , 0 , tmp . length ) ) > - 1 ) { if ( progress != null && progress . isCancelled ( ) ) { throw new TransferCancelledException ( ) ; } out . write ( tmp , 0 , read ) ; offset = UnsignedInteger64 . add ( offset , read ) ; if ( progress != null ) progress . progressed ( offset . longValue ( ) ) ; } } catch ( IOException e ) { throw new SshException ( e ) ; } } | Perform a synchronous read of a file from the remote file system . This implementation waits for acknowledgement of every data packet before requesting additional data . | 347 | 29 |
11,897 | public UnsignedInteger32 postReadRequest ( byte [ ] handle , long offset , int len ) throws SftpStatusException , SshException { try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_READ ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeBinaryString ( handle ) ; msg . writeUINT64 ( offset ) ; msg . writeInt ( len ) ; sendMessage ( msg ) ; return requestId ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Post a read request to the server and return the request id ; this is used to optimize file downloads . In normal operation the files are transfered by using a synchronous set of requests however this slows the download as the client has to wait for the servers response before sending another request . | 158 | 57 |
11,898 | public int readFile ( byte [ ] handle , UnsignedInteger64 offset , byte [ ] output , int off , int len ) throws SftpStatusException , SshException { try { if ( ( output . length - off ) < len ) { throw new IndexOutOfBoundsException ( "Output array size is smaller than read length!" ) ; } UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_READ ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeBinaryString ( handle ) ; msg . write ( offset . toByteArray ( ) ) ; msg . writeInt ( len ) ; sendMessage ( msg ) ; SftpMessage bar = getResponse ( requestId ) ; if ( bar . getType ( ) == SSH_FXP_DATA ) { byte [ ] msgdata = bar . readBinaryString ( ) ; System . arraycopy ( msgdata , 0 , output , off , msgdata . length ) ; return msgdata . length ; } else if ( bar . getType ( ) == SSH_FXP_STATUS ) { int status = ( int ) bar . readInt ( ) ; if ( status == SftpStatusException . SSH_FX_EOF ) return - 1 ; if ( version >= 3 ) { String desc = bar . readString ( ) . trim ( ) ; throw new SftpStatusException ( status , desc ) ; } throw new SftpStatusException ( status ) ; } else { close ( ) ; throw new SshException ( "The server responded with an unexpected message" , SshException . CHANNEL_FAILURE ) ; } } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Read a block of data from an open file . | 407 | 10 |
11,899 | public void createSymbolicLink ( String targetpath , String linkpath ) throws SftpStatusException , SshException { if ( version < 3 ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_OP_UNSUPPORTED , "Symbolic links are not supported by the server SFTP version " + String . valueOf ( version ) ) ; } try { UnsignedInteger32 requestId = nextRequestId ( ) ; Packet msg = createPacket ( ) ; msg . write ( SSH_FXP_SYMLINK ) ; msg . writeInt ( requestId . longValue ( ) ) ; msg . writeString ( linkpath , CHARSET_ENCODING ) ; msg . writeString ( targetpath , CHARSET_ENCODING ) ; sendMessage ( msg ) ; getOKRequestStatus ( requestId ) ; } catch ( SshIOException ex ) { throw ex . getRealException ( ) ; } catch ( IOException ex ) { throw new SshException ( ex ) ; } } | Create a symbolic link . | 225 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.