signature:
public class Play2BuildFailure { /** * copied from AbstractPlay2SourcePositionMapper . java */
private String readFileAsString ( ) throws IOException { } }

implementation: FileInputStream is = new FileInputStream ( e . source ( ) ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; }


signature:
public class Reloader { /** * Contrary to its name , this doesn ' t necessarily reload the app . It is invoked on every request , and will only
 * trigger a reload of the app if something has changed .
 * Since this communicates across classloaders , it must return only simple objects .
 * @ return Either
 * - Throwable - If something went wrong ( eg , a compile error ) .
 * - ClassLoader - If the classloader has changed , and the application should be reloaded .
 * - null - If nothing changed . */
@ Override /* BuildLink interface */
public synchronized Object reload ( ) { } }

implementation: Object result = null ; try { boolean reloadRequired = buildLink . build ( ) ; if ( reloadRequired ) { int version = ++ classLoaderVersion ; String name = "ReloadableClassLoader(v" + version + ")" ; currentApplicationClassLoader = new DelegatedResourcesClassLoader ( name , toUrls ( outputDirectories ) , baseLoader ) ; result = currentApplicationClassLoader ; } } catch ( MalformedURLException e ) { throw new UnexpectedException ( "Unexpected reloader exception" , e ) ; } catch ( Play2BuildFailure e ) { result = new CompilationException ( e . getMessage ( ) , e . line ( ) , e . position ( ) , e . source ( ) != null ? e . source ( ) . getAbsolutePath ( ) : null , e . input ( ) ) ; } catch ( Play2BuildError e ) { result = new UnexpectedException ( e . getMessage ( ) , e . getCause ( ) ) ; } return result ;


signature:
public class Play23LessCompiler { /** * Called from Less script , must be " public " */
public static String readContent ( File file ) throws IOException { } }

implementation: String result = null ; BufferedReader is = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , "UTF-8" ) ) ; try { StringBuilder sb = new StringBuilder ( ) ; String line = is . readLine ( ) ; while ( line != null ) { sb . append ( line ) . append ( '\n' ) ; line = is . readLine ( ) ; } result = sb . toString ( ) ; } finally { is . close ( ) ; } return result ;


signature:
public class Play23LessCompiler { /** * Called from Less script , must be " public " */
public static File resolve ( File originalSource , String imported ) { } }

implementation: return new File ( originalSource . getParentFile ( ) , imported ) ;


signature:
public class Play2EbeanEnhanceMojo { /** * Process all the comma delimited list of packages .
 * Package names are effectively converted into a directory on the file
 * system , and the class files are found and processed .
 * @ param lastEnhanced previous enhancement timestamp
 * @ param outputDirectory directory containing classes to enhance
 * @ param packageNames package names include filter
 * @ return list of files to enhance */
public List < File > collectClassFilesToEnhance ( long lastEnhanced , File outputDirectory , String packageNames ) { } }

implementation:
if ( packageNames == null || packageNames . isEmpty ( ) ) { return collectClassFilesToEnhanceFromPackage ( lastEnhanced , outputDirectory , "" , true ) ; // return ;
} List < File > result = new ArrayList < File > ( ) ; String [ ] pkgs = packageNames . split ( "," ) ; for ( int i = 0 ; i < pkgs . length ; i ++ ) { String pkg = pkgs [ i ] . trim ( ) . replace ( '.' , '/' ) ; boolean recurse = false ; if ( pkg . endsWith ( "**" ) ) { recurse = true ; pkg = pkg . substring ( 0 , pkg . length ( ) - 2 ) ; } else if ( pkg . endsWith ( "*" ) ) { recurse = true ; pkg = pkg . substring ( 0 , pkg . length ( ) - 1 ) ; } pkg = trimSlash ( pkg ) ; result . addAll ( collectClassFilesToEnhanceFromPackage ( lastEnhanced , outputDirectory , pkg , recurse ) ) ; } return result ;


signature:
public class AbstractArchivingMojo { /** * Returns preconfigured archiver
 * @ param archiverName archiver name
 * @ return archiver
 * @ throws NoSuchArchiverException for unsupported archiver name */
protected Archiver getArchiver ( String archiverName ) throws NoSuchArchiverException { } }

implementation:
Archiver result = archiverManager . getArchiver ( archiverName ) ; result . setDuplicateBehavior ( Archiver . DUPLICATES_FAIL ) ; // Just in case
return result ;


signature:
public class AbstractArchivingMojo { /** * Check for potential " Duplicate file " exception before archive processing starts
 * @ param archiver archiver to check */
protected void checkArchiverForProblems ( Archiver archiver ) { } }

implementation: for ( ResourceIterator iter = archiver . getResources ( ) ; iter . hasNext ( ) ; ) { iter . next ( ) ; }


signature:
public class AbstractPlay2Mojo { /** * Private utility methods */
protected /* private */
Set < Artifact > getResolvedArtifact ( String groupId , String artifactId , String version ) throws ArtifactResolutionException { } }

implementation: return getResolvedArtifact ( groupId , artifactId , version , true ) ;


signature:
public class AbstractPlay2SourcePositionMapper { /** * Reads the content of the file to a string .
 * @ param file a file to read the content of
 * @ return the content of the file
 * @ throws IOException I / O exception when reading from the file */
protected String readFileAsString ( File file ) throws IOException { } }

implementation: FileInputStream is = new FileInputStream ( file ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; }


signature:
public class MavenPlay2Builder { /** * = = = TEST = = = = = */
private List < MavenProject > calculateProjectsToBuild ( Set < String > changedFilePaths ) { } }

implementation:
Set < MavenProject > changedProjects = new HashSet < MavenProject > ( projects . size ( ) ) ; for ( String path : changedFilePaths ) { MavenProject p = findProjectFor ( path ) ; changedProjects . add ( p ) ; } Set < MavenProject > changedAndDependentProjects = new HashSet < MavenProject > ( projects . size ( ) ) ; for ( MavenProject p : changedProjects ) { changedAndDependentProjects . add ( p ) ; List < MavenProject > deps = session . getProjectDependencyGraph ( ) . getDownstreamProjects ( p , true /* transitive */
) ; for ( MavenProject depP : deps ) { if ( projects . contains ( depP ) ) { changedAndDependentProjects . addAll ( deps ) ; } } } List < MavenProject > result = new ArrayList < MavenProject > ( changedAndDependentProjects . size ( ) ) ; for ( MavenProject p : projects ) { if ( changedAndDependentProjects . contains ( p ) ) { result . add ( p ) ; } } return result ;


signature:
public class PollingFileWatchService { /** * { @ inheritDoc } */
@ Override public void initialize ( FileWatchLogger log ) throws FileWatchException { } }

implementation:
super . initialize ( log ) ; pollInterval = DEFAULT_POLL_INTERVAL ; String pollIntervalProp = System . getProperty ( "play2.pollInterval" ) ; if ( pollIntervalProp != null ) { try { pollInterval = Integer . parseInt ( pollIntervalProp ) ; } catch ( NumberFormatException e ) { log . warn ( String . format ( "Unparsable property value \"%s\", using default poll interval %d ms" , pollIntervalProp , Integer . valueOf ( DEFAULT_POLL_INTERVAL ) ) ) ; // throw new FileWatchException ( " PollingFileWatcher initialization failed " , e ) ;
} }


signature:
public class PollingFileWatchService { /** * { @ inheritDoc } */
@ Override public FileWatcher watch ( List < File > filesToWatch , FileWatchCallback watchCallback ) { } }

implementation: PollingFileWatcher result = new PollingFileWatcher ( log , filesToWatch , watchCallback , pollInterval ) ; Thread thread = new Thread ( result , "polling-play-watch-service" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; return result ;


signature:
public class AbstractAntJavaBasedPlay2Mojo { /** * Creates and configures Ant project for Java task .
 * @ return Ant project for Java task */
protected Project createProject ( ) { } }

implementation:
final Project antProject = new Project ( ) ; final ProjectHelper helper = ProjectHelper . getProjectHelper ( ) ; antProject . addReference ( ProjectHelper . PROJECTHELPER_REFERENCE , helper ) ; helper . getImportStack ( ) . addElement ( "AntBuilder" ) ; // import checks that stack is not empty
final BuildLogger logger = new NoBannerLogger ( ) ; logger . setMessageOutputLevel ( Project . MSG_INFO ) ; logger . setOutputPrintStream ( System . out ) ; logger . setErrorPrintStream ( System . err ) ; antProject . addBuildListener ( logger ) ; antProject . init ( ) ; antProject . getBaseDir ( ) ; return antProject ;


signature:
public class AbstractAntJavaBasedPlay2Mojo { /** * Adds string type system property to Ant Java task .
 * @ param java Ant Java task
 * @ param propertyName system property name
 * @ param propertyValue system property value */
protected void addSystemProperty ( Java java , String propertyName , String propertyValue ) { } }

implementation: Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setValue ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ;


signature:
public class AbstractAntJavaBasedPlay2Mojo { /** * Adds file type system property to Ant Java task .
 * @ param java Ant Java task
 * @ param propertyName system property name
 * @ param propertyValue system property value */
protected void addSystemProperty ( Java java , String propertyName , File propertyValue ) { } }

implementation: Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setFile ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ;


signature:
public class JNotifyFileWatchService { /** * { @ inheritDoc } */
@ Override public void initialize ( FileWatchLogger log ) throws FileWatchException { } }

implementation:
super . initialize ( log ) ; File nativeLibsDirectory = new File ( "." ) ; // maybe change to temporary directory ?
String nativeLibsDirectoryProp = System . getProperty ( "play2.nativeLibsDirectory" ) ; if ( nativeLibsDirectoryProp != null && ! "" . equals ( nativeLibsDirectoryProp ) ) { nativeLibsDirectory = new File ( nativeLibsDirectoryProp ) ; } else { String targetDirectoryProp = System . getProperty ( "project.build.directory" ) ; if ( targetDirectoryProp != null && ! "" . equals ( targetDirectoryProp ) ) { File targetDirectory = new File ( targetDirectoryProp ) ; nativeLibsDirectory = new File ( targetDirectory , "native_libraries" ) ; } } String nativeLibsPath = nativeLibsDirectory . getAbsolutePath ( ) ; if ( ! nativeLibsDirectory . exists ( ) && ! nativeLibsDirectory . mkdirs ( ) ) { throw new FileWatchException ( String . format ( "Cannot create \"%s\" directory" , nativeLibsPath ) ) ; } String libraryOS = null ; String libraryName = "jnotify" ; String osName = System . getProperty ( "os.name" ) ; if ( osName != null ) { osName = osName . toLowerCase ( Locale . ENGLISH ) ; String architecture = System . getProperty ( "sun.arch.data.model" ) ; if ( osName . startsWith ( "windows" ) ) { libraryOS = "windows" + architecture ; if ( "amd64" . equals ( System . getProperty ( "os.arch" ) ) ) { libraryName = "jnotify_64bit" ; } } else if ( osName . equals ( "linux" ) ) { libraryOS = "linux" + architecture ; } else if ( osName . startsWith ( "mac os x" ) ) { libraryOS = "osx" ; } } if ( libraryOS == null ) { throw new FileWatchException ( String . format ( "JNotifyFileWatchService initialization failed - unsupported OS \"%s\"" , osName ) ) ; } String libraryResourceName = System . mapLibraryName ( libraryName ) ; libraryResourceName = libraryResourceName . replace ( ".dylib" , ".jnilib" ) ; // fix for JDK - 7134701 bug
File outputFile = new File ( nativeLibsDirectory , libraryResourceName ) ; if ( ! outputFile . exists ( ) ) { try { copyResourceToFile ( "META-INF/native/" + libraryOS , libraryResourceName , nativeLibsDirectory ) ; } catch ( IOException e ) { throw new FileWatchException ( "JNotifyFileWatchService initialization failed" , e ) ; } } // hack to update java . library . path
try { String javaLibraryPath = System . getProperty ( "java.library.path" ) ; javaLibraryPath = javaLibraryPath != null ? javaLibraryPath + File . pathSeparator + nativeLibsPath : nativeLibsPath ; System . setProperty ( "java.library.path" , javaLibraryPath ) ; Field fieldSysPath = ClassLoader . class . getDeclaredField ( "sys_paths" ) ; fieldSysPath . setAccessible ( true ) ; fieldSysPath . set ( null , null ) ; } catch ( Exception e ) { throw new FileWatchException ( "JNotifyFileWatchService initialization failed" , e ) ; } // initialize JNotify
try { JNotify . removeWatch ( 0 ) ; } catch ( JNotifyException e ) { throw new FileWatchException ( "JNotifyFileWatchService initialization failed" , e ) ; }


signature:
public class JNotifyFileWatchService { /** * { @ inheritDoc } */
@ Override public FileWatcher watch ( List < File > filesToWatch , FileWatchCallback watchCallback ) throws FileWatchException { } }

implementation: try { return new JNotifyFileWatcher ( log , filesToWatch , watchCallback ) ; } catch ( JNotifyException e ) { throw new FileWatchException ( "JNotifyFileWatcher initialization failed" , e ) ; }


signature:
public class Play2TemplateSourcePositionMapper { /** * Performs mapping from the position in generated source file to the position in Twirl template file it was
 * generated from . < br >
 * < br >
 * Returns :
 * < ul >
 * < li > position in Twirl template file < / li >
 * < li > { @ code null } value if file of the input position is not recognized as generated from Twirl template file < / li >
 * < / ul >
 * @ param p compilation error / warning position in generated file
 * @ return position in { @ code routes } file or { @ code null } value if file of the input position is not recognized as
 * generated from Twirl template file
 * @ throws IOException I / O exception during generated or original source file reading */
@ Override public SourcePosition map ( SourcePosition p ) throws IOException { } }

implementation:
SourcePosition result = null ; File generatedFile = p . getFile ( ) ; int generatedOffset = p . getOffset ( ) ; if ( generatedFile != null && generatedFile . isFile ( ) && generatedOffset >= 0 ) { Play2TemplateGeneratedSource generated = getGeneratedSource ( generatedFile ) ; if ( generated != null ) { String sourceFileName = generated . getSourceFileName ( ) ; if ( sourceFileName != null ) { File sourceFile = new File ( sourceFileName ) ; if ( sourceFile . isFile ( ) ) { int sourceOffset = generated . mapPosition ( generatedOffset ) ; String sourceFileContent = readFileAsString ( sourceFile ) ; if ( sourceFileContent . length ( ) > sourceOffset ) { String [ ] sourceFileLines = sourceFileContent . split ( "\n" ) ; Play2TemplateLocation sourceLocation = new Play2TemplateMapping ( sourceFileLines ) . location ( sourceOffset ) ; // if ( sourceLocation ! = null )
result = new Play2TemplateSourcePosition ( sourceFile , sourceLocation ) ; } } } } } return result ;


signature: public class LessDependencyCache { public void set ( String fileName , Collection < String > dependencies ) { } }

implementation: allDependencies . put ( fileName , new TreeSet < String > ( dependencies ) ) ;


signature:
public class NumerusRollingNumber { /** * Increment the counter in the current bucket by one for the given { @ link NumerusRollingNumberEvent } type .
 * The { @ link NumerusRollingNumberEvent } must be a " counter " type < code > HystrixRollingNumberEvent . isCounter ( ) = = true < / code > .
 * @ param type
 * HystrixRollingNumberEvent defining which counter to increment
 * Boolean doNotBlock if currentBucket is null */
public void increment ( NumerusRollingNumberEvent type , Boolean doNotBlock ) { } }

implementation: Bucket lastBucket = getCurrentBucket ( doNotBlock ) ; if ( lastBucket == null ) return ; lastBucket . getAdder ( type ) . increment ( ) ;


signature:
public class NumerusRollingNumber { /** * Get the sum of all buckets in the rolling counter for the given { @ link NumerusRollingNumberEvent } type .
 * The { @ link NumerusRollingNumberEvent } must be a " counter " type < code > HystrixRollingNumberEvent . isCounter ( ) = = true < / code > .
 * @ param type
 * HystrixRollingNumberEvent defining which counter to retrieve values from
 * Boolean doNotBlock if currentBucket is null
 * @ return
 * value from the given { @ link NumerusRollingNumberEvent } counter type */
public long getRollingSum ( NumerusRollingNumberEvent type , Boolean doNotBlock ) { } }

implementation: Bucket lastBucket = getCurrentBucket ( doNotBlock ) ; if ( lastBucket == null ) return 0 ; long sum = 0 ; for ( Bucket b : buckets ) { sum += b . getAdder ( type ) . sum ( ) ; } return sum ;


signature:
public class NumerusRollingNumber { /** * Get an array of values for all buckets in the rolling counter for the given { @ link NumerusRollingNumberEvent } type .
 * Index 0 is the oldest bucket .
 * The { @ link NumerusRollingNumberEvent } must be a " counter " type < code > HystrixRollingNumberEvent . isCounter ( ) = = true < / code > .
 * @ param type
 * HystrixRollingNumberEvent defining which counter to retrieve values from
 * @ return array of values from each of the rolling buckets for given { @ link NumerusRollingNumberEvent } counter type */
public long [ ] getValues ( NumerusRollingNumberEvent type ) { } }

implementation:
Bucket lastBucket = getCurrentBucket ( ) ; if ( lastBucket == null ) return new long [ 0 ] ; // get buckets as an array ( which is a copy of the current state at this point in time )
Bucket [ ] bucketArray = buckets . getArray ( ) ; // we have bucket data so we ' ll return an array of values for all buckets
long values [ ] = new long [ bucketArray . length ] ; int i = 0 ; for ( Bucket bucket : bucketArray ) { if ( type . isCounter ( ) ) { values [ i ++ ] = bucket . getAdder ( type ) . sum ( ) ; } else if ( type . isMaxUpdater ( ) ) { values [ i ++ ] = bucket . getMaxUpdater ( type ) . max ( ) ; } } return values ;


signature:
public class NumerusRollingNumber { /** * Get the max value of values in all buckets for the given { @ link NumerusRollingNumberEvent } type .
 * The { @ link NumerusRollingNumberEvent } must be a " max updater " type < code > HystrixRollingNumberEvent . isMaxUpdater ( ) = = true < / code > .
 * @ param type
 * HystrixRollingNumberEvent defining which " max updater " to retrieve values from
 * @ return max value for given { @ link NumerusRollingNumberEvent } type during rolling window */
public long getRollingMaxValue ( NumerusRollingNumberEvent type ) { } }

implementation: long values [ ] = getValues ( type ) ; if ( values . length == 0 ) { return 0 ; } else { Arrays . sort ( values ) ; return values [ values . length - 1 ] ; }


signature:
public class NumerusRollingPercentile { /** * Add value ( or values ) to current bucket .
 * @ param value
 * Value to be stored in current bucket such as execution latency in milliseconds */
public void addValue ( int ... value ) { } }

implementation:
/* no - op if disabled */
if ( ! enabled . get ( ) ) return ; for ( int v : value ) { getCurrentBucket ( ) . data . addValue ( v ) ; }


signature:
public class LongMaxUpdater { /** * Returns the current maximum . The returned value is
 * < em > NOT < / em > an atomic snapshot : Invocation in the absence of
 * concurrent updates returns an accurate result , but concurrent
 * updates that occur while the value is being calculated might
 * not be incorporated .
 * @ return the maximum */
public long max ( ) { } }

implementation: Cell [ ] as = cells ; long max = base ; if ( as != null ) { int n = as . length ; long v ; for ( int i = 0 ; i < n ; ++ i ) { Cell a = as [ i ] ; if ( a != null && ( v = a . value ) > max ) max = v ; } } return max ;


signature:
public class DirectoryChooserActivity { /** * / * package */
void setupActionBar ( ) { } }

implementation:
// there might not be an ActionBar , for example when started in Theme . Holo . Dialog . NoActionBar theme
@ SuppressLint ( "AppCompatMethod" ) final ActionBar actionBar = getActionBar ( ) ; if ( actionBar != null ) { actionBar . setDisplayHomeAsUpEnabled ( true ) ; }


signature:
public class DirectoryChooserFragment { /** * To create the config , make use of the provided
 * { @ link DirectoryChooserConfig # builder ( ) } .
 * @ return A new instance of DirectoryChooserFragment . */
public static DirectoryChooserFragment newInstance ( @ NonNull final DirectoryChooserConfig config ) { } }

implementation: final DirectoryChooserFragment fragment = new DirectoryChooserFragment ( ) ; final Bundle args = new Bundle ( ) ; args . putParcelable ( ARG_CONFIG , config ) ; fragment . setArguments ( args ) ; return fragment ;


signature:
public class DirectoryChooserFragment { /** * Shows a confirmation dialog that asks the user if he wants to create a
 * new folder . User can modify provided name , if it was not disallowed . */
private void openNewFolderDialog ( ) { } }

implementation: @ SuppressLint ( "InflateParams" ) final View dialogView = getActivity ( ) . getLayoutInflater ( ) . inflate ( R . layout . dialog_new_folder , null ) ; final TextView msgView = ( TextView ) dialogView . findViewById ( R . id . msgText ) ; final EditText editText = ( EditText ) dialogView . findViewById ( R . id . editText ) ; editText . setText ( mNewDirectoryName ) ; msgView . setText ( getString ( R . string . create_folder_msg , mNewDirectoryName ) ) ; final AlertDialog alertDialog = new AlertDialog . Builder ( getActivity ( ) ) . setTitle ( R . string . create_folder_label ) . setView ( dialogView ) . setNegativeButton ( R . string . cancel_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; } } ) . setPositiveButton ( R . string . confirm_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; mNewDirectoryName = editText . getText ( ) . toString ( ) ; final int msg = createFolder ( ) ; Toast . makeText ( getActivity ( ) , msg , Toast . LENGTH_SHORT ) . show ( ) ; } } ) . show ( ) ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( editText . getText ( ) . length ( ) != 0 ) ; editText . addTextChangedListener ( new TextWatcher ( ) { @ Override public void beforeTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { } @ Override public void onTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { final boolean textNotEmpty = charSequence . length ( ) != 0 ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( textNotEmpty ) ; msgView . setText ( getString ( R . string . create_folder_msg , charSequence . toString ( ) ) ) ; } @ Override public void afterTextChanged ( final Editable editable ) { } } ) ; editText . setVisibility ( mConfig . allowNewDirectoryNameModification ( ) ? View . VISIBLE : View . GONE ) ;


signature:
public class DirectoryChooserFragment { /** * Change the directory that is currently being displayed .
 * @ param dir The file the activity should switch to . This File must be
 * non - null and a directory , otherwise the displayed directory
 * will not be changed */
private void changeDirectory ( final File dir ) { } }

implementation: if ( dir == null ) { debug ( "Could not change folder: dir was null" ) ; } else if ( ! dir . isDirectory ( ) ) { debug ( "Could not change folder: dir is no directory" ) ; } else { final File [ ] contents = dir . listFiles ( ) ; if ( contents != null ) { int numDirectories = 0 ; for ( final File f : contents ) { if ( f . isDirectory ( ) ) { numDirectories ++ ; } } mFilesInDir = new File [ numDirectories ] ; mFilenames . clear ( ) ; for ( int i = 0 , counter = 0 ; i < numDirectories ; counter ++ ) { if ( contents [ counter ] . isDirectory ( ) ) { mFilesInDir [ i ] = contents [ counter ] ; mFilenames . add ( contents [ counter ] . getName ( ) ) ; i ++ ; } } Arrays . sort ( mFilesInDir ) ; Collections . sort ( mFilenames ) ; mSelectedDir = dir ; mTxtvSelectedFolder . setText ( dir . getAbsolutePath ( ) ) ; mListDirectoriesAdapter . notifyDataSetChanged ( ) ; mFileObserver = createFileObserver ( dir . getAbsolutePath ( ) ) ; mFileObserver . startWatching ( ) ; debug ( "Changed directory to %s" , dir . getAbsolutePath ( ) ) ; } else { debug ( "Could not change folder: contents of dir were null" ) ; } } refreshButtonState ( ) ;


signature:
public class DirectoryChooserFragment { /** * Changes the state of the buttons depending on the currently selected file
 * or folder . */
private void refreshButtonState ( ) { } }

implementation: final Activity activity = getActivity ( ) ; if ( activity != null && mSelectedDir != null ) { mBtnConfirm . setEnabled ( isValidFile ( mSelectedDir ) ) ; getActivity ( ) . invalidateOptionsMenu ( ) ; }


signature:
public class DirectoryChooserFragment { /** * Sets up a FileObserver to watch the current directory . */
private FileObserver createFileObserver ( final String path ) { } }

implementation: return new FileObserver ( path , FileObserver . CREATE | FileObserver . DELETE | FileObserver . MOVED_FROM | FileObserver . MOVED_TO ) { @ Override public void onEvent ( final int event , final String path ) { debug ( "FileObserver received event %d" , event ) ; final Activity activity = getActivity ( ) ; if ( activity != null ) { activity . runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { refreshDirectory ( ) ; } } ) ; } } } ;


signature:
public class DirectoryChooserFragment { /** * Returns the selected folder as a result to the activity the fragment ' s attached to . The
 * selected folder can also be null . */
private void returnSelectedFolder ( ) { } }

implementation: if ( mSelectedDir != null ) { debug ( "Returning %s as result" , mSelectedDir . getAbsolutePath ( ) ) ; mListener . foreach ( new UnitFunction < OnFragmentInteractionListener > ( ) { @ Override public void apply ( final OnFragmentInteractionListener f ) { f . onSelectDirectory ( mSelectedDir . getAbsolutePath ( ) ) ; } } ) ; } else { mListener . foreach ( new UnitFunction < OnFragmentInteractionListener > ( ) { @ Override public void apply ( final OnFragmentInteractionListener f ) { f . onCancelChooser ( ) ; } } ) ; }


signature:
public class DirectoryChooserFragment { /** * Creates a new folder in the current directory with the name
 * CREATE _ DIRECTORY _ NAME . */
private int createFolder ( ) { } }

implementation: if ( mNewDirectoryName != null && mSelectedDir != null && mSelectedDir . canWrite ( ) ) { final File newDir = new File ( mSelectedDir , mNewDirectoryName ) ; if ( newDir . exists ( ) ) { return R . string . create_folder_error_already_exists ; } else { final boolean result = newDir . mkdir ( ) ; if ( result ) { return R . string . create_folder_success ; } else { return R . string . create_folder_error ; } } } else if ( mSelectedDir != null && ! mSelectedDir . canWrite ( ) ) { return R . string . create_folder_error_no_write_access ; } else { return R . string . create_folder_error ; }


signature:
public class DirectoryChooserFragment { /** * Returns true if the selected file or directory would be valid selection . */
private boolean isValidFile ( final File file ) { } }

implementation: return ( file != null && file . isDirectory ( ) && file . canRead ( ) && ( mConfig . allowReadOnlyDirectory ( ) || file . canWrite ( ) ) ) ;


signature:
public class DirChooserSample { /** * Called when the activity is first created . */
@ Override public void onCreate ( Bundle savedInstanceState ) { } }

implementation:
super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . main ) ; mDirectoryTextView = ( TextView ) findViewById ( R . id . textDirectory ) ; // Set up click handler for " Choose Directory " button
findViewById ( R . id . btnChoose ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { final Intent chooserIntent = new Intent ( DirChooserSample . this , DirectoryChooserActivity . class ) ; final DirectoryChooserConfig config = DirectoryChooserConfig . builder ( ) . newDirectoryName ( "DirChooserSample" ) . allowReadOnlyDirectory ( true ) . allowNewDirectoryNameModification ( true ) . build ( ) ; chooserIntent . putExtra ( DirectoryChooserActivity . EXTRA_CONFIG , config ) ; startActivityForResult ( chooserIntent , REQUEST_DIRECTORY ) ; } } ) ; findViewById ( R . id . btnChange ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { final Intent fragmentSampleIntent = new Intent ( DirChooserSample . this , DirChooserFragmentSample . class ) ; startActivity ( fragmentSampleIntent ) ; } } ) ;


signature:
public class DomainValidator { /** * Returns true if the specified < code > String < / code > parses
 * as a valid domain name with a recognized top - level domain .
 * The parsing is case - insensitive .
 * @ param domain the parameter to check for domain name syntax
 * @ return true if the parameter is a valid domain name */
public boolean isValid ( String domain ) { } }

implementation:
if ( domain == null ) { return false ; } domain = unicodeToASCII ( domain ) ; // hosts must be equally reachable via punycode and Unicode ;
// Unicode is never shorter than punycode , so check punycode
// if domain did not convert , then it will be caught by ASCII
// checks in the regexes below
if ( domain . length ( ) > 253 ) { return false ; } String [ ] groups = domainRegex . match ( domain ) ; if ( groups != null && groups . length > 0 ) { return isValidTld ( groups [ 0 ] ) ; } return allowLocal && hostnameRegex . isValid ( domain ) ;


signature:
public class DomainValidator { /** * Returns true if the specified < code > String < / code > matches any
 * IANA - defined infrastructure top - level domain . Leading dots are
 * ignored if present . The search is case - insensitive .
 * @ param iTld the parameter to check for infrastructure TLD status , not null
 * @ return true if the parameter is an infrastructure TLD */
public boolean isValidInfrastructureTld ( String iTld ) { } }

implementation: iTld = unicodeToASCII ( iTld ) ; return Arrays . binarySearch ( INFRASTRUCTURE_TLDS , ( chompLeadingDot ( iTld . toLowerCase ( Locale . ENGLISH ) ) ) ) >= 0 ;


signature:
public class DomainValidator { /** * Returns true if the specified < code > String < / code > matches any
 * IANA - defined generic top - level domain . Leading dots are ignored
 * if present . The search is case - insensitive .
 * @ param gTld the parameter to check for generic TLD status , not null
 * @ return true if the parameter is a generic TLD */
public boolean isValidGenericTld ( String gTld ) { } }

implementation: gTld = unicodeToASCII ( gTld ) ; return Arrays . binarySearch ( GENERIC_TLDS , chompLeadingDot ( gTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ;


signature:
public class DomainValidator { /** * Returns true if the specified < code > String < / code > matches any
 * IANA - defined country code top - level domain . Leading dots are
 * ignored if present . The search is case - insensitive .
 * @ param ccTld the parameter to check for country code TLD status , not null
 * @ return true if the parameter is a country code TLD */
public boolean isValidCountryCodeTld ( String ccTld ) { } }

implementation: ccTld = unicodeToASCII ( ccTld ) ; return Arrays . binarySearch ( COUNTRY_CODE_TLDS , chompLeadingDot ( ccTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ;


signature:
public class DomainValidator { /** * Returns true if the specified < code > String < / code > matches any
 * widely used " local " domains ( localhost or localdomain ) . Leading dots are
 * ignored if present . The search is case - insensitive .
 * @ param lTld the parameter to check for local TLD status , not null
 * @ return true if the parameter is an local TLD */
public boolean isValidLocalTld ( String lTld ) { } }

implementation: lTld = unicodeToASCII ( lTld ) ; return Arrays . binarySearch ( LOCAL_TLDS , chompLeadingDot ( lTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ;


signature:
public class DomainValidator { /** * Helper method to invoke java . net . IDN . toAscii ( String ) .
 * Allows code to be compiled with Java 1.4 and 1.5
 * @ throws IllegalArgumentException if the input string doesn ' t conform to RFC 3490 specification */
private static final String toASCII ( String line ) throws IllegalArgumentException { } }

implementation:
// java . net . IDN . toASCII ( line ) ; / / Java 1.6 +
// implementation for Java 1.4 and 1.5
// effectively this is done by IDN . toASCII but we want to skip the entire call
if ( isOnlyASCII ( line ) ) { return line ; } Method m = IDNHolder . JAVA_NET_IDN_TO_ASCII ; if ( m == null ) { // avoid NPE
return line ; } try { return ( String ) m . invoke ( null , new String [ ] { line . toLowerCase ( Locale . ENGLISH ) } ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; // Should not happen
} catch ( InvocationTargetException e ) { Throwable t = e . getCause ( ) ; if ( t instanceof IllegalArgumentException ) { // this is expected from toASCII method
throw ( IllegalArgumentException ) t ; } throw new RuntimeException ( e ) ; // Should not happen
}


signature:
public class MonitoredActivity { /** * * * * * * Lifecycle Methods * * * * * */
@ Override protected void onCreate ( Bundle savedInstanceState ) { } }

implementation:
super . onCreate ( savedInstanceState ) ; // set theme
setTheme ( RTApi . useDarkTheme ( ) ? R . style . RTE_BaseThemeDark : R . style . RTE_BaseThemeLight ) ; if ( ! isFinishing ( ) ) { mHandler = new Handler ( ) ; for ( LifeCycleListener listener : mListeners ) { listener . onActivityCreated ( this ) ; } }


signature:
public class MonitoredActivity { /** * Start a foreground job showing a progress bar as long as the job runs .
 * A foreground job shows a modal dialog that can ' t be cancelled while the app
 * does some processing . This should be used for short jobs only that block the ui .
 * Of course this contradicts many of the Android guidelines but with short jobs
 * we mean < 1 second and only in rare cases should it me more ( e . g . when the garbage
 * collector kicks in which would normally lead to stuttering ) .
 * Using foreground jobs gives a better user experience in these rare cases .
 * The user has to wait but he / she knows it because there ' s a progess bar . */
public < T > T startForegroundJob ( int msgId , ForegroundJob < T > job ) { } }

implementation:
// make the progress dialog uncancelable , so that we can guarantee
// that the thread is done before the activity gets destroyed
ProgressDialog dialog = ProgressDialog . show ( this , null , getString ( msgId ) , true , false ) ; Job < T > managedJob = new Job < T > ( job , dialog ) ; return managedJob . runForegroundJob ( ) ;


signature:
public class MonitoredActivity { /** * Start a background job showing a progress bar as long as the job runs .
 * This seems contradictory but with background job we mean one that runs off
 * the ui thread to prevent an ANR .
 * We still have to wait for the processing to be done because we need the result . */
public void startBackgroundJob ( int msgId , Runnable runnable ) { } }

implementation:
// make the progress dialog uncancelable , so that we can guarantee
// that the thread is done before the activity gets destroyed
ProgressDialog dialog = ProgressDialog . show ( this , null , getString ( msgId ) , true , false ) ; Job < Object > managedJob = new Job < Object > ( runnable , dialog ) ; managedJob . runBackgroundJob ( ) ;


signature:
public class ConverterHtmlToSpanned { /** * * * * * * Handle Tags * * * * * */
private void handleStartTag ( String tag , Attributes attributes ) { } }

implementation:
if ( tag . equalsIgnoreCase ( "br" ) ) { // We don ' t need to handle this . TagSoup will ensure that there ' s a < / br > for each < br >
// so we can safely omit the line breaks when we handle the close tag .
} else if ( tag . equalsIgnoreCase ( "p" ) ) { handleP ( ) ; } else if ( tag . equalsIgnoreCase ( "div" ) ) { startDiv ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "ul" ) ) { startList ( false , attributes ) ; } else if ( tag . equalsIgnoreCase ( "ol" ) ) { startList ( true , attributes ) ; } else if ( tag . equalsIgnoreCase ( "li" ) ) { startList ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "strong" ) ) { start ( new Bold ( ) ) ; } else if ( tag . equalsIgnoreCase ( "b" ) ) { start ( new Bold ( ) ) ; } else if ( tag . equalsIgnoreCase ( "em" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( "cite" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( "dfn" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( "i" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( "strike" ) ) { start ( new Strikethrough ( ) ) ; } else if ( tag . equalsIgnoreCase ( "del" ) ) { start ( new Strikethrough ( ) ) ; } else if ( tag . equalsIgnoreCase ( "big" ) ) { start ( new Big ( ) ) ; } else if ( tag . equalsIgnoreCase ( "small" ) ) { start ( new Small ( ) ) ; } else if ( tag . equalsIgnoreCase ( "font" ) ) { startFont ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "blockquote" ) ) { handleP ( ) ; start ( new Blockquote ( ) ) ; } else if ( tag . equalsIgnoreCase ( "tt" ) ) { start ( new Monospace ( ) ) ; } else if ( tag . equalsIgnoreCase ( "a" ) ) { startAHref ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "u" ) ) { start ( new Underline ( ) ) ; } else if ( tag . equalsIgnoreCase ( "sup" ) ) { start ( new Super ( ) ) ; } else if ( tag . equalsIgnoreCase ( "sub" ) ) { start ( new Sub ( ) ) ; } else if ( tag . length ( ) == 2 && Character . toLowerCase ( tag . charAt ( 0 ) ) == 'h' && tag . charAt ( 1 ) >= '1' && tag . charAt ( 1 ) <= '6' ) { handleP ( ) ; start ( new Header ( tag . charAt ( 1 ) - '1' ) ) ; } else if ( tag . equalsIgnoreCase ( "img" ) ) { startImg ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "video" ) ) { startVideo ( attributes ) ; } else if ( tag . equalsIgnoreCase ( "embed" ) ) { startAudio ( attributes ) ; } else if ( sIgnoreTags . contains ( tag . toLowerCase ( Locale . getDefault ( ) ) ) ) { mIgnoreContent = true ; }


signature:
public class ConverterHtmlToSpanned { /** * Handles OL and UL start tags */
private void startList ( boolean isOrderedList , Attributes attributes ) { } }

implementation:
boolean isIndentation = isIndentation ( attributes ) ; ParagraphType newType = isIndentation && isOrderedList ? ParagraphType . INDENTATION_OL : isIndentation && ! isOrderedList ? ParagraphType . INDENTATION_UL : isOrderedList ? ParagraphType . NUMBERING : ParagraphType . BULLET ; AccumulatedParagraphStyle currentStyle = mParagraphStyles . isEmpty ( ) ? null : mParagraphStyles . peek ( ) ; if ( currentStyle == null ) { // no previous style found - > create new AccumulatedParagraphStyle with indentations of 1
AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle ( newType , 1 , 1 ) ; mParagraphStyles . push ( newStyle ) ; } else if ( currentStyle . getType ( ) == newType ) { // same style found - > increase indentations by 1
currentStyle . setAbsoluteIndent ( currentStyle . getAbsoluteIndent ( ) + 1 ) ; currentStyle . setRelativeIndent ( currentStyle . getRelativeIndent ( ) + 1 ) ; } else { // different style found - > create new AccumulatedParagraphStyle with incremented indentations
AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle ( newType , currentStyle . getAbsoluteIndent ( ) + 1 , 1 ) ; mParagraphStyles . push ( newStyle ) ; }


signature:
public class ConverterHtmlToSpanned { /** * Handles OL and UL end tags */
private void endList ( boolean orderedList ) { } }

implementation:
if ( ! mParagraphStyles . isEmpty ( ) ) { AccumulatedParagraphStyle style = mParagraphStyles . peek ( ) ; ParagraphType type = style . getType ( ) ; if ( ( orderedList && ( type . isNumbering ( ) || type == ParagraphType . INDENTATION_OL ) ) || ( ! orderedList && ( type . isBullet ( ) || type == ParagraphType . INDENTATION_UL ) ) ) { // the end tag matches the current style
int indent = style . getRelativeIndent ( ) ; if ( indent > 1 ) { style . setRelativeIndent ( indent - 1 ) ; style . setAbsoluteIndent ( style . getAbsoluteIndent ( ) - 1 ) ; } else { mParagraphStyles . pop ( ) ; } } else { // the end tag doesn ' t match the current style
mParagraphStyles . pop ( ) ; endList ( orderedList ) ; // find the next matching style
} }


signature:
public class ConverterHtmlToSpanned { /** * Handles LI tags */
private void startList ( Attributes attributes ) { } }

implementation: List listTag = null ; if ( ! mParagraphStyles . isEmpty ( ) ) { AccumulatedParagraphStyle currentStyle = mParagraphStyles . peek ( ) ; ParagraphType type = currentStyle . getType ( ) ; int indent = currentStyle . getAbsoluteIndent ( ) ; boolean isIndentation = isIndentation ( attributes ) ; if ( type . isIndentation ( ) || isIndentation ) { listTag = new UL ( indent , true ) ; } else if ( type . isNumbering ( ) ) { listTag = new OL ( indent , false ) ; } else if ( type . isBullet ( ) ) { listTag = new UL ( indent , false ) ; } } else { listTag = new UL ( 0 , false ) ; } if ( listTag != null ) start ( listTag ) ;


signature:
public class ConverterHtmlToSpanned { /** * Handles LI tags */
private void endList ( ) { } }

implementation:
List list = ( List ) getLast ( List . class ) ; if ( list != null ) { if ( mResult . length ( ) == 0 || mResult . charAt ( mResult . length ( ) - 1 ) != '\n' ) { mResult . append ( '\n' ) ; } int start = mResult . getSpanStart ( list ) ; int end = mResult . length ( ) ; int nrOfIndents = list . mNrOfIndents ; if ( ! list . mIsIndentation ) { nrOfIndents -- ; int margin = Helper . getLeadingMarging ( ) ; // use SPAN _ EXCLUSIVE _ EXCLUSIVE here , will be replaced later anyway when the cleanup function is called
Object span = list instanceof UL ? new BulletSpan ( margin , start == end , false , false ) : new NumberSpan ( 1 , margin , start == end , false , false ) ; mResult . setSpan ( span , start , end , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } if ( nrOfIndents > 0 ) { int margin = nrOfIndents * Helper . getLeadingMarging ( ) ; // use SPAN _ EXCLUSIVE _ EXCLUSIVE here , will be replaced later anyway when the cleanup function is called
IndentationSpan span = new IndentationSpan ( margin , start == end , false , false ) ; mResult . setSpan ( span , start , end , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } mResult . removeSpan ( list ) ; }


signature:
public class ConverterHtmlToSpanned { /** * Converts an HTML color ( named or numeric ) to an integer RGB value .
 * @ param color Non - null color string .
 * @ return A color value , or { @ code - 1 } if the color string could not be interpreted . */
@ SuppressLint ( "DefaultLocale" ) private static int getHtmlColor ( String color ) { } }

implementation: Integer i = COLORS . get ( color . toLowerCase ( ) ) ; if ( i != null ) { return i ; } else { try { return convertValueToInt ( color , - 1 ) ; } catch ( NumberFormatException nfe ) { return - 1 ; } }


signature:
public class HighlightView { /** * Determines which edges are hit by touching at ( x , y ) . */
public int getHit ( float x , float y ) { } }

implementation:
Rect r = computeLayout ( ) ; final float hysteresis = 20F ; int retval = GROW_NONE ; if ( mCircle ) { float distX = x - r . centerX ( ) ; float distY = y - r . centerY ( ) ; int distanceFromCenter = ( int ) Math . sqrt ( distX * distX + distY * distY ) ; int radius = mDrawRect . width ( ) / 2 ; int delta = distanceFromCenter - radius ; if ( Math . abs ( delta ) <= hysteresis ) { if ( Math . abs ( distY ) > Math . abs ( distX ) ) { if ( distY < 0 ) { retval = GROW_TOP_EDGE ; } else { retval = GROW_BOTTOM_EDGE ; } } else { if ( distX < 0 ) { retval = GROW_LEFT_EDGE ; } else { retval = GROW_RIGHT_EDGE ; } } } else if ( distanceFromCenter < radius ) { retval = MOVE ; } else { retval = GROW_NONE ; } } else { // verticalCheck makes sure the position is between the top and
// the bottom edge ( with some tolerance ) . Similar for horizCheck .
boolean verticalCheck = ( y >= r . top - hysteresis ) && ( y < r . bottom + hysteresis ) ; boolean horizCheck = ( x >= r . left - hysteresis ) && ( x < r . right + hysteresis ) ; // Check whether the position is near some edge ( s ) .
if ( ( Math . abs ( r . left - x ) < hysteresis ) && verticalCheck ) { retval |= GROW_LEFT_EDGE ; } if ( ( Math . abs ( r . right - x ) < hysteresis ) && verticalCheck ) { retval |= GROW_RIGHT_EDGE ; } if ( ( Math . abs ( r . top - y ) < hysteresis ) && horizCheck ) { retval |= GROW_TOP_EDGE ; } if ( ( Math . abs ( r . bottom - y ) < hysteresis ) && horizCheck ) { retval |= GROW_BOTTOM_EDGE ; } // Not near any edge but inside the rectangle : move .
if ( retval == GROW_NONE && r . contains ( ( int ) x , ( int ) y ) ) { retval = MOVE ; } } return retval ;


signature:
public class HighlightView { /** * The " edge " parameter specifies which edges the user is dragging . */
void handleMotion ( int edge , float dx , float dy ) { } }

implementation:
Rect r = computeLayout ( ) ; if ( edge == GROW_NONE ) { return ; } else if ( edge == MOVE ) { // Convert to image space before sending to moveBy ( ) .
moveBy ( dx * ( mCropRect . width ( ) / r . width ( ) ) , dy * ( mCropRect . height ( ) / r . height ( ) ) ) ; } else { if ( ( ( GROW_LEFT_EDGE | GROW_RIGHT_EDGE ) & edge ) == 0 ) { dx = 0 ; } if ( ( ( GROW_TOP_EDGE | GROW_BOTTOM_EDGE ) & edge ) == 0 ) { dy = 0 ; } // Convert to image space before sending to growBy ( ) .
float xDelta = dx * ( mCropRect . width ( ) / r . width ( ) ) ; float yDelta = dy * ( mCropRect . height ( ) / r . height ( ) ) ; growBy ( ( ( ( edge & GROW_LEFT_EDGE ) != 0 ) ? - 1 : 1 ) * xDelta , ( ( ( edge & GROW_TOP_EDGE ) != 0 ) ? - 1 : 1 ) * yDelta ) ; }


signature:
public class HighlightView { /** * Grows the cropping rectange by ( dx , dy ) in image space . */
void moveBy ( float dx , float dy ) { } }

implementation:
Rect invalRect = new Rect ( mDrawRect ) ; mCropRect . offset ( dx , dy ) ; // Put the cropping rectangle inside image rectangle .
mCropRect . offset ( Math . max ( 0 , mImageRect . left - mCropRect . left ) , Math . max ( 0 , mImageRect . top - mCropRect . top ) ) ; mCropRect . offset ( Math . min ( 0 , mImageRect . right - mCropRect . right ) , Math . min ( 0 , mImageRect . bottom - mCropRect . bottom ) ) ; mDrawRect = computeLayout ( ) ; invalRect . union ( mDrawRect ) ; invalRect . inset ( - 10 , - 10 ) ; mContext . invalidate ( invalRect ) ;


signature:
public class HighlightView { /** * Grows the cropping rectange by ( dx , dy ) in image space . */
void growBy ( float dx , float dy ) { } }

implementation:
if ( mMaintainAspectRatio ) { if ( dx != 0 ) { dy = dx / mInitialAspectRatio ; } else if ( dy != 0 ) { dx = dy * mInitialAspectRatio ; } } // Don ' t let the cropping rectangle grow too fast .
// Grow at most half of the difference between the image rectangle and
// the cropping rectangle .
RectF r = new RectF ( mCropRect ) ; if ( dx > 0F && r . width ( ) + 2 * dx > mImageRect . width ( ) ) { float adjustment = ( mImageRect . width ( ) - r . width ( ) ) / 2F ; dx = adjustment ; if ( mMaintainAspectRatio ) { dy = dx / mInitialAspectRatio ; } } if ( dy > 0F && r . height ( ) + 2 * dy > mImageRect . height ( ) ) { float adjustment = ( mImageRect . height ( ) - r . height ( ) ) / 2F ; dy = adjustment ; if ( mMaintainAspectRatio ) { dx = dy * mInitialAspectRatio ; } } r . inset ( - dx , - dy ) ; // Don ' t let the cropping rectangle shrink too fast .
final float widthCap = 25F ; if ( r . width ( ) < widthCap ) { r . inset ( - ( widthCap - r . width ( ) ) / 2F , 0F ) ; } float heightCap = mMaintainAspectRatio ? ( widthCap / mInitialAspectRatio ) : widthCap ; if ( r . height ( ) < heightCap ) { r . inset ( 0F , - ( heightCap - r . height ( ) ) / 2F ) ; } // Put the cropping rectangle inside the image rectangle .
if ( r . left < mImageRect . left ) { r . offset ( mImageRect . left - r . left , 0F ) ; } else if ( r . right > mImageRect . right ) { r . offset ( - ( r . right - mImageRect . right ) , 0 ) ; } if ( r . top < mImageRect . top ) { r . offset ( 0F , mImageRect . top - r . top ) ; } else if ( r . bottom > mImageRect . bottom ) { r . offset ( 0F , - ( r . bottom - mImageRect . bottom ) ) ; } mCropRect . set ( r ) ; mDrawRect = computeLayout ( ) ; mContext . invalidate ( ) ;


signature:
public class HighlightView { /** * Returns the cropping rectangle in image space . */
public Rect getCropRect ( ) { } }

implementation: return new Rect ( ( int ) mCropRect . left , ( int ) mCropRect . top , ( int ) mCropRect . right , ( int ) mCropRect . bottom ) ;


signature:
public class HighlightView { /** * Maps the cropping rectangle from image space to screen space . */
private Rect computeLayout ( ) { } }

implementation: RectF r = new RectF ( mCropRect . left , mCropRect . top , mCropRect . right , mCropRect . bottom ) ; mMatrix . mapRect ( r ) ; return new Rect ( Math . round ( r . left ) , Math . round ( r . top ) , Math . round ( r . right ) , Math . round ( r . bottom ) ) ;


signature:
public class RTEditText { /** * This needs to be called before anything else because we need the media
 * factory .
 * @ param listener The RTEditTextListener ( the RTManager )
 * @ param mediaFactory The RTMediaFactory */
void register ( RTEditTextListener listener , RTMediaFactory < RTImage , RTAudio , RTVideo > mediaFactory ) { } }

implementation: mListener = listener ; mMediaFactory = mediaFactory ;


signature:
public class RTEditText { /** * Find the start and end of the paragraph ( s ) encompassing the current selection .
 * A paragraph spans from one \ n ( exclusive ) to the next one ( inclusive ) */
public Selection getParagraphsInSelection ( ) { } }

implementation: RTLayout layout = getRTLayout ( ) ; Selection selection = new Selection ( this ) ; int firstLine = layout . getLineForOffset ( selection . start ( ) ) ; int end = selection . isEmpty ( ) ? selection . end ( ) : selection . end ( ) - 1 ; int lastLine = layout . getLineForOffset ( end ) ; return new Selection ( layout . getLineStart ( firstLine ) , layout . getLineEnd ( lastLine ) ) ;


signature:
public class RTEditText { /** * Sets the edit mode to plain or rich text . The text will be converted
 * automatically to rich / plain text if autoConvert is True .
 * @ param useRTFormatting True if the edit mode should be rich text , False if the edit
 * mode should be plain text
 * @ param autoConvert Automatically convert the content to plain or rich text if
 * this is True */
public void setRichTextEditing ( boolean useRTFormatting , boolean autoConvert ) { } }

implementation: assertRegistration ( ) ; if ( useRTFormatting != mUseRTFormatting ) { mUseRTFormatting = useRTFormatting ; if ( autoConvert ) { RTFormat targetFormat = useRTFormatting ? RTFormat . PLAIN_TEXT : RTFormat . HTML ; setText ( getRichText ( targetFormat ) ) ; } if ( mListener != null ) { mListener . onRichTextEditingChanged ( this , mUseRTFormatting ) ; } }


signature:
public class RTEditText { /** * Sets the edit mode to plain or rich text and updates the content at the
 * same time . The caller needs to make sure the content matches the correct
 * format ( if you pass in html code as plain text the editor will show the
 * html code ) .
 * @ param useRTFormatting True if the edit mode should be rich text , False if the edit
 * mode should be plain text
 * @ param content The new content */
public void setRichTextEditing ( boolean useRTFormatting , String content ) { } }

implementation: assertRegistration ( ) ; if ( useRTFormatting != mUseRTFormatting ) { mUseRTFormatting = useRTFormatting ; if ( mListener != null ) { mListener . onRichTextEditingChanged ( this , mUseRTFormatting ) ; } } RTText rtText = useRTFormatting ? new RTHtml < RTImage , RTAudio , RTVideo > ( RTFormat . HTML , content ) : new RTPlainText ( content ) ; setText ( rtText ) ;


signature:
public class RTEditText { /** * Set the text for this editor .
 * It will convert the text from rich text to plain text if the editor ' s
 * mode is set to use plain text . or to a spanned text ( only supported
 * formatting ) if the editor ' s mode is set to use rich text
 * We need to prevent onSelectionChanged ( ) to do anything as long as
 * setText ( ) hasn ' t finished because the Layout doesn ' t seem to update
 * before setText has finished but onSelectionChanged will still be called
 * during setText and will receive the out - dated Layout which doesn ' t allow
 * us to apply styles and such . */
public void setText ( RTText rtText ) { } }

implementation:
assertRegistration ( ) ; if ( rtText . getFormat ( ) instanceof RTFormat . Html ) { if ( mUseRTFormatting ) { RTText rtSpanned = rtText . convertTo ( RTFormat . SPANNED , mMediaFactory ) ; super . setText ( rtSpanned . getText ( ) , TextView . BufferType . EDITABLE ) ; addSpanWatcher ( ) ; // collect all current media
Spannable text = getText ( ) ; for ( MediaSpan span : text . getSpans ( 0 , text . length ( ) , MediaSpan . class ) ) { mOriginalMedia . add ( span . getMedia ( ) ) ; } Effects . cleanupParagraphs ( this ) ; } else { RTText rtPlainText = rtText . convertTo ( RTFormat . PLAIN_TEXT , mMediaFactory ) ; super . setText ( rtPlainText . getText ( ) ) ; } } else if ( rtText . getFormat ( ) instanceof RTFormat . PlainText ) { CharSequence text = rtText . getText ( ) ; super . setText ( text == null ? "" : text . toString ( ) ) ; } onSelectionChanged ( 0 , 0 ) ;


signature:
public class RTEditText { /** * Same as " String getText ( RTFormat format ) " but this method returns the
 * RTText instead of just the actual text . */
public RTText getRichText ( RTFormat format ) { } }

implementation: assertRegistration ( ) ; RTEditable rtEditable = new RTEditable ( this ) ; return rtEditable . convertTo ( format , mMediaFactory ) ;


signature:
public class RTEditText { /** * Add a SpanWatcher for the Changeable implementation */
private void addSpanWatcher ( ) { } }

implementation: Spannable spannable = getText ( ) ; if ( spannable . getSpans ( 0 , spannable . length ( ) , getClass ( ) ) != null ) { spannable . setSpan ( this , 0 , spannable . length ( ) , Spanned . SPAN_INCLUSIVE_INCLUSIVE ) ; }


signature:
public class RTEditText { /** * Call this to have an effect applied to the current selection .
 * You get the Effect object via the static data members ( e . g . , RTEditText . BOLD ) .
 * The value for most effects is a Boolean , indicating whether to add or remove the effect . */
public < V extends Object , C extends RTSpan < V > > void applyEffect ( Effect < V , C > effect , V value ) { } }

implementation: if ( mUseRTFormatting && ! mIsSelectionChanging && ! mIsSaving ) { Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable ( ) ; effect . applyToSelection ( this , value ) ; synchronized ( this ) { if ( mListener != null && ! mIgnoreTextChanges ) { Spannable newSpannable = cloneSpannable ( ) ; mListener . onTextChanged ( this , oldSpannable , newSpannable , getSelectionStart ( ) , getSelectionEnd ( ) , getSelectionStart ( ) , getSelectionEnd ( ) ) ; } mLayoutChanged = true ; } }


signature:
public class ConverterHtmlToText { /** * space */
public static RTPlainText convert ( RTHtml < ? extends RTImage , ? extends RTAudio , ? extends RTVideo > input ) { } }

implementation: String result = Html . fromHtml ( input . getText ( ) , null , new HtmlToTextTagHandler ( ) ) . toString ( ) . replace ( PREVIEW_OBJECT_CHARACTER , PREVIEW_OBJECT_REPLACEMENT ) . replace ( NBSP_CHARACTER , NBSP_REPLACEMENT ) ; return new RTPlainText ( result ) ;


signature:
public class RTText { /** * Converts this rich text to another rich text . The default implementation
 * doesn ' t support any conversion except the one to itself ( which is
 * technically no conversion ) .
 * The method has to make sure that the original rich text isn ' t modified .
 * It does however not make sure that the returned RTText isn ' t referencing
 * the original RTText meaning modifying the resulting object might also
 * modify the original object .
 * @ param destFormat The rich text we want to convert to .
 * @ param mediaFactory The media factory we might need for the conversion .
 * @ return The converted RTText
 * @ throws UnsupportedOperationException if this RTText doesn ' t support the conversion . */
public RTText convertTo ( RTFormat destFormat , RTMediaFactory < RTImage , RTAudio , RTVideo > mediaFactory ) { } }

implementation: if ( destFormat == mRTFormat ) { return this ; } throw new UnsupportedOperationException ( "Can't convert from " + mRTFormat . getClass ( ) . getSimpleName ( ) + " to " + destFormat . getClass ( ) . getSimpleName ( ) ) ;


signature:
public class ClonedSpannableString { /** * * * * * * SpannableString Methods * * * * * */
@ Override public void setSpan ( Object what , int start , int end , int flags ) { } }

implementation: if ( mSpanCount + 1 >= mSpans . length ) { int newsize = mSpanCount + 10 ; Object [ ] newtags = new Object [ newsize ] ; int [ ] newdata = new int [ newsize * 3 ] ; System . arraycopy ( mSpans , 0 , newtags , 0 , mSpanCount ) ; System . arraycopy ( mSpanData , 0 , newdata , 0 , mSpanCount * 3 ) ; mSpans = newtags ; mSpanData = newdata ; } mSpans [ mSpanCount ] = what ; mSpanData [ mSpanCount * COLUMNS + START ] = start ; mSpanData [ mSpanCount * COLUMNS + END ] = end ; mSpanData [ mSpanCount * COLUMNS + FLAGS ] = flags ; mSpanCount ++ ;


signature:
public class SpinnerItemAdapter { /** * This method returns the spinner view */
@ SuppressLint ( "ViewHolder" ) @ Override public final View getView ( int position , View convertView , ViewGroup parent ) { } }

implementation: View spinnerView = mInflater . inflate ( mSpinnerId , parent , false ) ; mParent = parent ; TextView spinnerTitleView = ( TextView ) spinnerView . findViewById ( R . id . title ) ; updateSpinnerTitle ( spinnerTitleView ) ; return spinnerView ;


signature:
public class SpinnerItemAdapter { /** * Returns the spinner entry view */
@ SuppressLint ( "InlinedApi" ) @ Override public View getDropDownView ( int position , View convertView , ViewGroup parent ) { } }

implementation:
SpinnerItem spinnerItem = mItems . get ( position ) ; spinnerItem . setOnChangedListener ( this , position ) ; // we can ' t use the convertView because it keeps handing us spinner layouts ( mSpinnerId )
View spinnerItemView = mInflater . inflate ( mSpinnerItemId , parent , false ) ; int key = ( position << 16 ) + getItemViewType ( position ) ; mViewCache . put ( key , spinnerItemView ) ; bindView ( position , spinnerItemView , spinnerItem ) ; return spinnerItemView ;


signature:
public class ConverterSpannedToHtml { /** * Converts a spanned text to HTML */
public RTHtml < RTImage , RTAudio , RTVideo > convert ( final Spanned text , RTFormat . Html rtFormat ) { } }

implementation:
mText = text ; mRTFormat = rtFormat ; mOut = new StringBuilder ( ) ; mImages = new ArrayList < > ( ) ; mParagraphStyles . clear ( ) ; // convert paragraphs
convertParagraphs ( ) ; return new RTHtml < > ( rtFormat , mOut . toString ( ) , mImages ) ;


signature:
public class ConverterSpannedToHtml { /** * * * * * * Process Paragraphs * * * * * */
private void convertParagraphs ( ) { } }

implementation:
RTLayout rtLayout = new RTLayout ( mText ) ; // a manual for loop is faster than the for - each loop for an ArrayList :
// see https : / / developer . android . com / training / articles / perf - tips . html # Loops
ArrayList < Paragraph > paragraphs = rtLayout . getParagraphs ( ) ; for ( int i = 0 , size = paragraphs . size ( ) ; i < size ; i ++ ) { Paragraph paragraph = paragraphs . get ( i ) ; // retrieve all spans for this paragraph
Set < SingleParagraphStyle > styles = getParagraphStyles ( mText , paragraph ) ; // get the alignment span if there is any
ParagraphType alignmentType = null ; for ( SingleParagraphStyle style : styles ) { if ( style . getType ( ) . isAlignment ( ) ) { alignmentType = style . getType ( ) ; break ; } } /* * start tag : bullet points , numbering and indentation */
int newIndent = 0 ; ParagraphType newType = ParagraphType . NONE ; for ( SingleParagraphStyle style : styles ) { newIndent += style . getIndentation ( ) ; ParagraphType type = style . getType ( ) ; newType = type . isBullet ( ) ? ParagraphType . BULLET : type . isNumbering ( ) ? ParagraphType . NUMBERING : type . isIndentation ( ) && newType . isUndefined ( ) ? ParagraphType . INDENTATION_UL : newType ; } // process leading margin style
processLeadingMarginStyle ( new AccumulatedParagraphStyle ( newType , newIndent , 0 ) ) ; // add start list tag
mOut . append ( newType . getListStartTag ( ) ) ; /* * start tag : alignment ( left , center , right ) */
if ( alignmentType != null ) { mOut . append ( alignmentType . getStartTag ( ) ) ; } /* * Convert the plain text */
withinParagraph ( mText , paragraph . start ( ) , paragraph . end ( ) ) ; /* * end tag : alignment ( left , center , right ) */
if ( alignmentType != null ) { removeTrailingLineBreak ( alignmentType ) ; mOut . append ( alignmentType . getEndTag ( ) ) ; } // add end list tag
removeTrailingLineBreak ( newType ) ; mOut . append ( newType . getListEndTag ( ) ) ; } /* * end tag : bullet points and indentation */
while ( ! mParagraphStyles . isEmpty ( ) ) { removeParagraph ( ) ; }


signature:
public class ConverterSpannedToHtml { /** * Convert a spanned text within a paragraph */
private void withinParagraph ( final Spanned text , int start , int end ) { } }

implementation:
// create sorted set of CharacterStyles
SortedSet < CharacterStyle > sortedSpans = new TreeSet < > ( ( s1 , s2 ) -> { int start1 = text . getSpanStart ( s1 ) ; int start2 = text . getSpanStart ( s2 ) ; if ( start1 != start2 ) return start1 - start2 ; // span which starts first comes first
int end1 = text . getSpanEnd ( s1 ) ; int end2 = text . getSpanEnd ( s2 ) ; if ( end1 != end2 ) return end2 - end1 ; // longer span comes first
// if the paragraphs have the same span [ start , end ] we compare their name
// compare the name only because local + anonymous classes have no canonical name
return s1 . getClass ( ) . getName ( ) . compareTo ( s2 . getClass ( ) . getName ( ) ) ; } ) ; List < CharacterStyle > spanList = Arrays . asList ( text . getSpans ( start , end , CharacterStyle . class ) ) ; sortedSpans . addAll ( spanList ) ; // process paragraphs / divs
convertText ( text , start , end , sortedSpans ) ;


signature:
public class ConverterSpannedToHtml { /** * Escape plain text parts : < , > , & , Space - - > ^ lt ; , & gt ; etc . */
private void escape ( CharSequence text , int start , int end ) { } }

implementation:
for ( int i = start ; i < end ; i ++ ) { char c = text . charAt ( i ) ; if ( c == '\n' ) { mOut . append ( BR ) ; } else if ( c == '<' ) { mOut . append ( LT ) ; } else if ( c == '>' ) { mOut . append ( GT ) ; } else if ( c == '&' ) { mOut . append ( AMP ) ; } else if ( c == ' ' ) { while ( i + 1 < end && text . charAt ( i + 1 ) == ' ' ) { mOut . append ( NBSP ) ; i ++ ; } mOut . append ( ' ' ) ; } // removed the c > 0x7E check to leave emoji unaltered
else if ( /* c > 0x7E | | */
c < ' ' ) { mOut . append ( "&#" + ( ( int ) c ) + ";" ) ; } else { mOut . append ( c ) ; } }


signature:
public class MediaUtils { /** * Creates a file with a non - conflicting file name in a specified folder based on an existing file name .
 * @ param targetFolder The target folder ( e . g . / sdcard / Android / data )
 * @ param originalFile The source file including the path ( e . g . / sdcard / image . jpg )
 * @ param mimeType If the originalFile has no extension ( e . g . for files provided by picasa ) we use the mime type
 * to determine the file extension
 * @ return The non - conflicting file name in targetFolder ( e . g . / sdcard / Android / data / 158867324_201308071234568 . jpg ) */
public static File createUniqueFile ( File targetFolder , String originalFile , boolean keepOriginal ) { } }

implementation: String mimeType = MimeTypeMap . getSingleton ( ) . getMimeTypeFromExtension ( originalFile ) ; return createUniqueFile ( targetFolder , originalFile , mimeType , keepOriginal ) ;


signature:
public class MediaUtils { /** * Creates a file Uri for a file defined by its absolute path .
 * The method can handle the case of an absolute path ( e . g . / data / data . . . . )
 * and a Uri path containing the file : / / scheme ( e . g . file : / / / data / data . . . ) */
public static Uri createFileUri ( String path ) { } }

implementation: if ( path . startsWith ( "file://" ) ) { return Uri . parse ( path ) ; } return Uri . fromFile ( new File ( path ) ) ;


signature:
public class MediaUtils { /** * Retrieve local file path for an arbitrary Uri
 * @ throws IllegalArgumentException If the uri is null or we can ' t resolve the uri to an absolute file path
 * ( meaning the uri isn ' t valid ) */
public static String determineOriginalFile ( Context context , Uri uri ) throws IllegalArgumentException { } }

implementation:
String originalFile = null ; if ( uri != null ) { // Picasa on Android > = 3.0 or other files using content providers
if ( uri . getScheme ( ) . startsWith ( "content" ) ) { originalFile = getPathFromUri ( context , uri ) ; } // Picasa on Android < 3.0
if ( uri . toString ( ) . matches ( "https?://\\w+\\.googleusercontent\\.com/.+" ) ) { originalFile = uri . toString ( ) ; } // local storage
if ( uri . getScheme ( ) . startsWith ( "file" ) ) { originalFile = uri . toString ( ) . substring ( 7 ) ; } if ( isNullOrEmpty ( originalFile ) ) { throw new IllegalArgumentException ( "File path was null" ) ; } } else { throw new IllegalArgumentException ( "Image Uri was null!" ) ; } return originalFile ;


signature:
public class ElementType { /** * Return a namespace name from a Qname . The attribute flag tells us whether
 * to return an empty namespace name if there is no prefix , or use the
 * schema default instead .
 * @ param name The Qname
 * @ param attribute True if name is an attribute name
 * @ return The namespace name */
public String namespace ( String name , boolean attribute ) { } }

implementation: int colon = name . indexOf ( ':' ) ; if ( colon == - 1 ) { return attribute ? "" : theSchema . getURI ( ) ; } String prefix = name . substring ( 0 , colon ) ; if ( prefix . equals ( "xml" ) ) { return "http://www.w3.org/XML/1998/namespace" ; } else { return ( "urn:x-prefix:" + prefix ) . intern ( ) ; }


signature:
public class ElementType { /** * Return a local name from a Qname .
 * @ param name The Qname
 * @ return The local name */
public String localName ( String name ) { } }

implementation: int colon = name . indexOf ( ':' ) ; if ( colon == - 1 ) { return name ; } else { return name . substring ( colon + 1 ) . intern ( ) ; }


signature:
public class ElementType { /** * Sets an attribute and its value into an AttributesImpl object . Attempts
 * to set a namespace declaration are ignored .
 * @ param atts The AttributesImpl object
 * @ param name The name ( Qname ) of the attribute
 * @ param type The type of the attribute
 * @ param value The value of the attribute */
public void setAttribute ( AttributesImpl atts , String name , String type , String value ) { } }

implementation: if ( name . equals ( "xmlns" ) || name . startsWith ( "xmlns:" ) ) { return ; } ; String namespace = namespace ( name , true ) ; String localName = localName ( name ) ; int i = atts . getIndex ( name ) ; if ( i == - 1 ) { name = name . intern ( ) ; if ( type == null ) type = "CDATA" ; if ( ! type . equals ( "CDATA" ) ) value = normalize ( value ) ; atts . addAttribute ( namespace , localName , name , type , value ) ; } else { if ( type == null ) type = atts . getType ( i ) ; if ( ! type . equals ( "CDATA" ) ) value = normalize ( value ) ; atts . setAttribute ( i , namespace , localName , name , type , value ) ; }


signature:
public class ElementType { /** * Normalize an attribute value ( ID - style ) . CDATA - style attribute
 * normalization is already done .
 * @ param value The value to normalize
 * @ return The normalized value */
public static String normalize ( String value ) { } }

implementation: if ( value == null ) return value ; value = value . trim ( ) ; if ( value . indexOf ( "  " ) == - 1 ) return value ; boolean space = false ; int len = value . length ( ) ; StringBuffer b = new StringBuffer ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { char v = value . charAt ( i ) ; if ( v == ' ' ) { if ( ! space ) b . append ( v ) ; space = true ; } else { b . append ( v ) ; space = false ; } } return b . toString ( ) ;


signature:
public class ElementType { /** * Sets an attribute and its value into this element type .
 * @ param name The name of the attribute
 * @ param type The type of the attribute
 * @ param value The value of the attribute */
public void setAttribute ( String name , String type , String value ) { } }

implementation: setAttribute ( theAtts , name , type , value ) ;


signature:
public class StringBuilderWriter { /** * Append a portion of a character sequence to the { @ link StringBuilder } .
 * @ param value The character to append
 * @ param start The index of the first character
 * @ param end The index of the last character + 1
 * @ return This writer instance */
@ Override public Writer append ( CharSequence value , int start , int end ) { } }

implementation: builder . append ( value , start , end ) ; return this ;


signature:
public class StringBuilderWriter { /** * Write a portion of a character array to the { @ link StringBuilder } .
 * @ param value The value to write
 * @ param offset The index of the first character
 * @ param length The number of characters to write */
@ Override public void write ( char [ ] value , int offset , int length ) { } }

implementation: if ( value != null ) { builder . append ( value , offset , length ) ; }


signature:
public class TTFAnalyzer { /** * Retrieve the file name for a system font .
 * @ param filePath the full path for the font to retrieve .
 * @ return The file name or null of none could be retrieved . */
static String getFontName ( String filePath ) { } }

implementation:
TTFRandomAccessFile in = null ; try { RandomAccessFile file = new RandomAccessFile ( filePath , "r" ) ; in = new TTFRandomAccessFile ( file ) ; return getTTFFontName ( in , filePath ) ; } catch ( IOException e ) { return null ; // Missing permissions or corrupted font file ?
} finally { IOUtils . closeQuietly ( in ) ; }


signature:
public class TTFAnalyzer { /** * Retrieve the file name for a font in the asset folder .
 * @ param filePath the full path for the font in the asset folder to retrieve .
 * @ return The file name or null of none could be retrieved . */
static String getFontName ( AssetManager assets , String filePath ) { } }

implementation:
TTFAssetInputStream in = null ; try { InputStream file = assets . open ( filePath , AssetManager . ACCESS_RANDOM ) ; in = new TTFAssetInputStream ( file ) ; return getTTFFontName ( in , filePath ) ; } catch ( FileNotFoundException e ) { return null ; // Missing permissions ?
} catch ( IOException e ) { return null ; // Corrupted font file ?
} finally { IOUtils . closeQuietly ( in ) ; }


signature:
public class ByteArrayOutputStream { /** * Makes a new buffer available either by allocating
 * a new one or re - cycling an existing one .
 * @ param newcount the size of the buffer if one is created */
private void needNewBuffer ( int newcount ) { } }

implementation:
if ( currentBufferIndex < buffers . size ( ) - 1 ) { // Recycling old buffer
filledBufferSum += currentBuffer . length ; currentBufferIndex ++ ; currentBuffer = buffers . get ( currentBufferIndex ) ; } else { // Creating new buffer
int newBufferSize ; if ( currentBuffer == null ) { newBufferSize = newcount ; filledBufferSum = 0 ; } else { newBufferSize = Math . max ( currentBuffer . length << 1 , newcount - filledBufferSum ) ; filledBufferSum += currentBuffer . length ; } currentBufferIndex ++ ; currentBuffer = new byte [ newBufferSize ] ; buffers . add ( currentBuffer ) ; }


signature:
public class ByteArrayOutputStream { /** * Write the bytes to byte array .
 * @ param b the bytes to write
 * @ param off The start offset
 * @ param len The number of bytes to write */
@ Override public void write ( byte [ ] b , int off , int len ) { } }

implementation: if ( ( off < 0 ) || ( off > b . length ) || ( len < 0 ) || ( ( off + len ) > b . length ) || ( ( off + len ) < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } synchronized ( this ) { int newcount = count + len ; int remaining = len ; int inBufferPos = count - filledBufferSum ; while ( remaining > 0 ) { int part = Math . min ( remaining , currentBuffer . length - inBufferPos ) ; System . arraycopy ( b , off + len - remaining , currentBuffer , inBufferPos , part ) ; remaining -= part ; if ( remaining > 0 ) { needNewBuffer ( newcount ) ; inBufferPos = 0 ; } } count = newcount ; }


signature:
public class ByteArrayOutputStream { /** * Write a byte to byte array .
 * @ param b the byte to write */
@ Override public synchronized void write ( int b ) { } }

implementation: int inBufferPos = count - filledBufferSum ; if ( inBufferPos == currentBuffer . length ) { needNewBuffer ( count + 1 ) ; inBufferPos = 0 ; } currentBuffer [ inBufferPos ] = ( byte ) b ; count ++ ;


signature:
public class ByteArrayOutputStream { /** * Writes the entire contents of the specified input stream to this
 * byte stream . Bytes from the input stream are read directly into the
 * internal buffers of this streams .
 * @ param in the input stream to read from
 * @ return total number of bytes read from the input stream
 * ( and written to this stream )
 * @ throws IOException if an I / O error occurs while reading the input stream
 * @ since 1.4 */
public synchronized int write ( InputStream in ) throws IOException { } }

implementation: int readCount = 0 ; int inBufferPos = count - filledBufferSum ; int n = in . read ( currentBuffer , inBufferPos , currentBuffer . length - inBufferPos ) ; while ( n != - 1 ) { readCount += n ; inBufferPos += n ; count += n ; if ( inBufferPos == currentBuffer . length ) { needNewBuffer ( currentBuffer . length ) ; inBufferPos = 0 ; } n = in . read ( currentBuffer , inBufferPos , currentBuffer . length - inBufferPos ) ; } return readCount ;


signature:
public class ByteArrayOutputStream { /** * Writes the entire contents of this byte stream to the
 * specified output stream .
 * @ param out the output stream to write to
 * @ throws IOException if an I / O error occurs , such as if the stream is closed
 * @ see java . io . ByteArrayOutputStream # writeTo ( OutputStream ) */
public synchronized void writeTo ( OutputStream out ) throws IOException { } }

implementation: int remaining = count ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; out . write ( buf , 0 , c ) ; remaining -= c ; if ( remaining == 0 ) { break ; } }


signature:
public class ByteArrayOutputStream { /** * Fetches entire contents of an < code > InputStream < / code > and represent
 * same data as result InputStream .
 * This method is useful where ,
 * < ul >
 * < li > Source InputStream is slow . < / li >
 * < li > It has network resources associated , so we cannot keep it open for
 * long time . < / li >
 * < li > It has network timeout associated . < / li >
 * < / ul >
 * It can be used in favor of { @ link # toByteArray ( ) } , since it
 * avoids unnecessary allocation and copy of byte [ ] . < br >
 * This method buffers the input internally , so there is no need to use a
 * < code > BufferedInputStream < / code > .
 * @ param input Stream to be fully buffered .
 * @ return A fully buffered stream .
 * @ throws IOException if an I / O error occurs
 * @ since 2.0 */
public static InputStream toBufferedInputStream ( InputStream input ) throws IOException { } }

implementation: ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; output . write ( input ) ; return output . toBufferedInputStream ( ) ;


signature:
public class ByteArrayOutputStream { /** * Gets the current contents of this byte stream as a Input Stream . The
 * returned stream is backed by buffers of < code > this < / code > stream ,
 * avoiding memory allocation and copy , thus saving space and time . < br >
 * @ return the current contents of this output stream .
 * @ see java . io . ByteArrayOutputStream # toByteArray ( )
 * @ see # reset ( )
 * @ since 2.0 */
private InputStream toBufferedInputStream ( ) { } }

implementation: int remaining = count ; if ( remaining == 0 ) { return new ClosedInputStream ( ) ; } List < ByteArrayInputStream > list = new ArrayList < ByteArrayInputStream > ( buffers . size ( ) ) ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; list . add ( new ByteArrayInputStream ( buf , 0 , c ) ) ; remaining -= c ; if ( remaining == 0 ) { break ; } } return new SequenceInputStream ( Collections . enumeration ( list ) ) ;


signature:
public class ByteArrayOutputStream { /** * Gets the curent contents of this byte stream as a byte array .
 * The result is independent of this stream .
 * @ return the current contents of this output stream , as a byte array
 * @ see java . io . ByteArrayOutputStream # toByteArray ( ) */
public synchronized byte [ ] toByteArray ( ) { } }

implementation: int remaining = count ; if ( remaining == 0 ) { return EMPTY_BYTE_ARRAY ; } byte newbuf [ ] = new byte [ remaining ] ; int pos = 0 ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; System . arraycopy ( buf , 0 , newbuf , pos , c ) ; pos += c ; remaining -= c ; if ( remaining == 0 ) { break ; } } return newbuf ;


signature:
public class HorizontalRTToolbar { /** * Set the text size .
 * @ param size the text size , if - 1 then no text size is set ( e . g . when selection spans more than one text size ) */
@ Override public void setFontSize ( int size ) { } }

implementation: if ( mFontSize != null ) { if ( size <= 0 ) { mFontSizeAdapter . updateSpinnerTitle ( "" ) ; mFontSizeAdapter . setSelectedItem ( 0 ) ; mFontSize . setSelection ( 0 ) ; } else { size = Helper . convertSpToPx ( size ) ; mFontSizeAdapter . updateSpinnerTitle ( Integer . toString ( size ) ) ; for ( int pos = 0 ; pos < mFontSizeAdapter . getCount ( ) ; pos ++ ) { FontSizeSpinnerItem item = mFontSizeAdapter . getItem ( pos ) ; if ( size == item . getFontSize ( ) ) { mFontSizeAdapter . setSelectedItem ( pos ) ; mFontSize . setSelection ( pos ) ; break ; } } } }


signature:
public class FilenameUtils { /** * Normalizes a path , removing double and single dot path steps ,
 * and removing any final directory separator .
 * This method normalizes a path to a standard format .
 * The input may contain separators in either Unix or Windows format .
 * The output will contain separators in the format specified .
 * A trailing slash will be removed .
 * A double slash will be merged to a single slash ( but UNC names are handled ) .
 * A single dot path segment will be removed .
 * A double dot will cause that path segment and the one before to be removed .
 * If the double dot has no parent path segment to work with , { @ code null }
 * is returned .
 * The output will be the same on both Unix and Windows including
 * the separator character .
 * < pre >
 * / foo / / - - > / foo
 * / foo / . / - - > / foo
 * / foo / . . / bar - - > / bar
 * / foo / . . / bar / - - > / bar
 * / foo / . . / bar / . . / baz - - > / baz
 * / / foo / / . / bar - - > / foo / bar
 * / . . / - - > null
 * . . / foo - - > null
 * foo / bar / . . - - > foo
 * foo / . . / . . / bar - - > null
 * foo / . . / bar - - > bar
 * / / server / foo / . . / bar - - > / / server / bar
 * / / server / . . / bar - - > null
 * C : \ foo \ . . \ bar - - > C : \ bar
 * C : \ . . \ bar - - > null
 * ~ / foo / . . / bar / - - > ~ / bar
 * ~ / . . / bar - - > null
 * < / pre >
 * @ param filename the filename to normalize , null returns null
 * @ param unixSeparator { @ code true } if a unix separator should
 * be used or { @ code false } if a windows separtor should be used .
 * @ return the normalized filename , or null if invalid
 * @ since 2.0 */
public static String normalizeNoEndSeparator ( String filename , boolean unixSeparator ) { } }

implementation: char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR ; return doNormalize ( filename , separator , false ) ;


signature:
public class FilenameUtils { /** * Internal method to perform the normalization .
 * @ param filename the filename
 * @ param separator The separator character to use
 * @ param keepSeparator true to keep the final separator
 * @ return the normalized filename */
private static String doNormalize ( String filename , char separator , boolean keepSeparator ) { } }

implementation:
if ( filename == null ) { return null ; } int size = filename . length ( ) ; if ( size == 0 ) { return filename ; } int prefix = getPrefixLength ( filename ) ; if ( prefix < 0 ) { return null ; } char [ ] array = new char [ size + 2 ] ; // + 1 for possible extra slash , + 2 for arraycopy
filename . getChars ( 0 , filename . length ( ) , array , 0 ) ; // fix separators throughout
char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == otherSeparator ) { array [ i ] = separator ; } } // add extra separator on the end to simplify code below
boolean lastIsDirectory = true ; if ( array [ size - 1 ] != separator ) { array [ size ++ ] = separator ; lastIsDirectory = false ; } // adjoining slashes
for ( int i = prefix + 1 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == separator ) { System . arraycopy ( array , i , array , i - 1 , size - i ) ; size -- ; i -- ; } } // dot slash
for ( int i = prefix + 1 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == '.' && ( i == prefix + 1 || array [ i - 2 ] == separator ) ) { if ( i == size - 1 ) { lastIsDirectory = true ; } System . arraycopy ( array , i + 1 , array , i - 1 , size - i ) ; size -= 2 ; i -- ; } } // double dot slash
outer : for ( int i = prefix + 2 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == '.' && array [ i - 2 ] == '.' && ( i == prefix + 2 || array [ i - 3 ] == separator ) ) { if ( i == prefix + 2 ) { return null ; } if ( i == size - 1 ) { lastIsDirectory = true ; } int j ; for ( j = i - 4 ; j >= prefix ; j -- ) { if ( array [ j ] == separator ) { // remove b / . . / from a / b / . . / c
System . arraycopy ( array , i + 1 , array , j + 1 , size - i ) ; size -= i - j ; i = j + 1 ; continue outer ; } } // remove a / . . / from a / . . / c
System . arraycopy ( array , i + 1 , array , prefix , size - i ) ; size -= i + 1 - prefix ; i = prefix + 1 ; } } if ( size <= 0 ) { // should never be less than 0
return "" ; } if ( size <= prefix ) { // should never be less than prefix
return new String ( array , 0 , size ) ; } if ( lastIsDirectory && keepSeparator ) { return new String ( array , 0 , size ) ; // keep trailing separator
} return new String ( array , 0 , size - 1 ) ; // lose trailing separator


signature:
public class FilenameUtils { /** * Converts all separators to the Unix separator of forward slash .
 * @ param path the path to be changed , null ignored
 * @ return the updated path */
public static String separatorsToUnix ( String path ) { } }

implementation: if ( path == null || path . indexOf ( WINDOWS_SEPARATOR ) == - 1 ) { return path ; } return path . replace ( WINDOWS_SEPARATOR , UNIX_SEPARATOR ) ;


signature:
public class FilenameUtils { /** * Returns the index of the last extension separator character , which is a dot .
 * This method also checks that there is no directory separator after the last dot .
 * To do this it uses { @ link # indexOfLastSeparator ( String ) } which will
 * handle a file in either Unix or Windows format .
 * The output will be the same irrespective of the machine that the code is running on .
 * @ param filename the filename to find the last path separator in , null returns - 1
 * @ return the index of the last separator character , or - 1 if there
 * is no such character */
public static int indexOfExtension ( String filename ) { } }

implementation: if ( filename == null ) { return - 1 ; } int extensionPos = filename . lastIndexOf ( EXTENSION_SEPARATOR ) ; int lastSeparator = indexOfLastSeparator ( filename ) ; return lastSeparator > extensionPos ? - 1 : extensionPos ;


signature:
public class SpanCollector { /** * Return an array of the markup objects attached to the specified slice of a Spannable and whose
 * type is the specified type or a subclass of it ( see Spanned . getSpans ( int , int , Class < T > ) ) . */
final protected RTSpan < V > [ ] getSpansAndroid ( Spannable str , int selStart , int selEnd ) { } }

implementation: RTSpan < V > [ ] spans = str . getSpans ( selStart , selEnd , mSpanClazz ) ; return spans == null ? ( RTSpan < V > [ ] ) Array . newInstance ( mSpanClazz ) : spans ;


signature:
public class CropImageView { /** * hitting cropping rectangle . */
private void recomputeFocus ( MotionEvent event ) { } }

implementation: for ( int i = 0 ; i < mHighlightViews . size ( ) ; i ++ ) { HighlightView hv = mHighlightViews . get ( i ) ; hv . setFocus ( false ) ; hv . invalidate ( ) ; } for ( int i = 0 ; i < mHighlightViews . size ( ) ; i ++ ) { HighlightView hv = mHighlightViews . get ( i ) ; int edge = hv . getHit ( event . getX ( ) , event . getY ( ) ) ; if ( edge != HighlightView . GROW_NONE ) { if ( ! hv . hasFocus ( ) ) { hv . setFocus ( true ) ; hv . invalidate ( ) ; } break ; } } invalidate ( ) ;


signature:
public class CropImageView { /** * Pan the displayed image to make sure the cropping rectangle is visible . */
private void ensureVisible ( HighlightView hv ) { } }

implementation: Rect r = hv . mDrawRect ; int panDeltaX1 = Math . max ( 0 , mLeft - r . left ) ; int panDeltaX2 = Math . min ( 0 , mRight - r . right ) ; int panDeltaY1 = Math . max ( 0 , mTop - r . top ) ; int panDeltaY2 = Math . min ( 0 , mBottom - r . bottom ) ; int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2 ; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2 ; if ( panDeltaX != 0 || panDeltaY != 0 ) { panBy ( panDeltaX , panDeltaY ) ; }


signature:
public class CropImageView { /** * view ' s center and scale according to the cropping rectangle . */
private void centerBasedOnHighlightView ( HighlightView hv ) { } }

implementation: Rect drawRect = hv . mDrawRect ; float width = drawRect . width ( ) ; float height = drawRect . height ( ) ; float thisWidth = getWidth ( ) ; float thisHeight = getHeight ( ) ; float z1 = thisWidth / width * .8F ; float z2 = thisHeight / height * .8F ; float zoom = Math . min ( z1 , z2 ) ; zoom = zoom * this . getScale ( ) ; zoom = Math . max ( 1F , zoom ) ; if ( ( Math . abs ( zoom - getScale ( ) ) / zoom ) > .1 ) { float [ ] coordinates = new float [ ] { hv . mCropRect . centerX ( ) , hv . mCropRect . centerY ( ) } ; getImageMatrix ( ) . mapPoints ( coordinates ) ; zoomTo ( zoom , coordinates [ 0 ] , coordinates [ 1 ] , 300F ) ; } ensureVisible ( hv ) ;


signature:
public class HTMLScanner { /** * Reset document locator , supplying systemid and publicid .
 * @ param systemid System id
 * @ param publicid Public id */
public void resetDocumentLocator ( String publicid , String systemid ) { } }

implementation: thePublicid = publicid ; theSystemid = systemid ; theLastLine = theLastColumn = theCurrentLine = theCurrentColumn = 0 ;


signature:
public class HTMLScanner { /** * Scan HTML source , reporting lexical events .
 * @ param r0 Reader that provides characters
 * @ param h ScanHandler that accepts lexical events . */
public void scan ( Reader r0 , ScanHandler h ) throws IOException , SAXException { } }

implementation:
theState = S_PCDATA ; PushbackReader r ; if ( r0 instanceof PushbackReader ) { r = ( PushbackReader ) r0 ; } else if ( r0 instanceof BufferedReader ) { r = new PushbackReader ( r0 ) ; } else { r = new PushbackReader ( new BufferedReader ( r0 , 200 ) ) ; } int firstChar = r . read ( ) ; // Remove any leading BOM
if ( firstChar != '\uFEFF' ) unread ( r , firstChar ) ; while ( theState != S_DONE ) { int c1 = r . read ( ) ; char c = ( char ) c1 ; boolean is32BitChar = Character . isHighSurrogate ( c ) ; int c2 = is32BitChar ? r . read ( ) : - 1 ; String s = is32BitChar ? new StringBuffer ( ) . append ( c ) . append ( ( char ) c2 ) . toString ( ) : null ; // Process control characters
if ( ! is32BitChar && c1 >= 0x80 && c1 <= 0x9F ) c1 = theWinMap [ c1 - 0x80 ] ; if ( ! is32BitChar && c1 == '\r' ) { c1 = r . read ( ) ; // expect LF next
if ( c1 != '\n' ) { unread ( r , c1 ) ; // nope
c1 = '\n' ; } } if ( ! is32BitChar && c1 == '\n' ) { theCurrentLine ++ ; theCurrentColumn = 0 ; } else { theCurrentColumn ++ ; } if ( ! ! is32BitChar && ! ( c1 >= 0x20 || c1 == '\n' || c1 == '\t' || c1 == - 1 ) ) continue ; // Search state table
int action = 0 ; for ( int i = 0 ; i < statetable . length ; i += 4 ) { if ( theState != statetable [ i ] ) { if ( action != 0 ) break ; continue ; } if ( statetable [ i + 1 ] == 0 ) { action = statetable [ i + 2 ] ; theNextState = statetable [ i + 3 ] ; } else if ( ! is32BitChar && statetable [ i + 1 ] == c1 ) { action = statetable [ i + 2 ] ; theNextState = statetable [ i + 3 ] ; break ; } } switch ( action ) { case 0 : throw new Error ( "HTMLScanner can't cope with " + Integer . toString ( c1 ) + " in state " + Integer . toString ( theState ) ) ; case A_ADUP : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ADUP_SAVE : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; if ( s != null ) save ( s , c1 , h ) ; break ; case A_ADUP_STAGC : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_ANAME : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ANAME_ADUP : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . adup ( theOutputBuffer , 0 , theSize ) ; break ; case A_ANAME_ADUP_STAGC : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . adup ( theOutputBuffer , 0 , theSize ) ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_AVAL : h . aval ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_AVAL_STAGC : h . aval ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_CDATA : mark ( ) ; // suppress the final " ] ] " in the buffer
if ( theSize > 1 ) theSize -= 2 ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ENTITY_START : h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; save ( s , c1 , h ) ; break ; case A_ENTITY : mark ( ) ; if ( theState == S_ENT && c == '#' ) { theNextState = S_NCR ; save ( s , c1 , h ) ; break ; } else if ( theState == S_NCR && ( c == 'x' || c == 'X' ) ) { theNextState = S_XNCR ; save ( s , c1 , h ) ; break ; } else if ( theState == S_ENT && Character . isLetterOrDigit ( c ) ) { save ( s , c1 , h ) ; break ; } else if ( theState == S_NCR && Character . isDigit ( c ) ) { save ( s , c1 , h ) ; break ; } else if ( theState == S_XNCR && ( Character . isDigit ( c ) || "abcdefABCDEF" . indexOf ( c ) != - 1 ) ) { save ( s , c1 , h ) ; break ; } // The whole entity reference has been collected
h . entity ( theOutputBuffer , 1 , theSize - 1 ) ; int ent = h . getEntity ( ) ; if ( ent != 0 ) { theSize = 0 ; if ( ent >= 0x80 && ent <= 0x9F ) { ent = theWinMap [ ent - 0x80 ] ; } if ( ent < 0x20 ) { // Control becomes space
ent = 0x20 ; } else if ( ent >= 0xD800 && ent <= 0xDFFF ) { // Surrogates get dropped
ent = 0 ; } else if ( ent <= 0xFFFF ) { // BMP character
save ( ent , h ) ; } else { // Astral converted to two surrogates
ent -= 0x10000 ; save ( ( ent >> 10 ) + 0xD800 , h ) ; save ( ( ent & 0x3FF ) + 0xDC00 , h ) ; } if ( is32BitChar || c1 != ';' ) { if ( is32BitChar ) { unread ( r , c2 ) ; theCurrentColumn -- ; } unread ( r , c1 ) ; theCurrentColumn -- ; } } else { if ( is32BitChar ) { unread ( r , c2 ) ; theCurrentColumn -- ; } unread ( r , c1 ) ; theCurrentColumn -- ; } theNextState = S_PCDATA ; break ; case A_ETAG : h . etag ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_DECL : h . decl ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_GI : h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_GI_STAGC : h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_LT : mark ( ) ; save ( '<' , h ) ; save ( s , c1 , h ) ; break ; case A_LT_PCDATA : mark ( ) ; save ( '<' , h ) ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PCDATA : mark ( ) ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_CMNT : mark ( ) ; h . cmnt ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_MINUS3 : save ( '-' , h ) ; save ( ' ' , h ) ; break ; case A_MINUS2 : save ( '-' , h ) ; save ( ' ' , h ) ; // fall through into A _ MINUS
case A_MINUS : save ( '-' , h ) ; save ( s , c1 , h ) ; break ; case A_PI : mark ( ) ; h . pi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PITARGET : h . pitarget ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PITARGET_PI : h . pitarget ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . pi ( theOutputBuffer , 0 , theSize ) ; break ; case A_SAVE : save ( s , c1 , h ) ; break ; case A_SKIP : break ; case A_SP : save ( ' ' , h ) ; break ; case A_STAGC : h . stagc ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_EMPTYTAG : mark ( ) ; if ( theSize > 0 ) h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stage ( theOutputBuffer , 0 , theSize ) ; break ; case A_UNGET : unread ( r , c1 ) ; theCurrentColumn -- ; break ; case A_UNSAVE_PCDATA : if ( theSize > 0 ) theSize -- ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; default : throw new Error ( "Can't process state " + action ) ; } theState = theNextState ; } h . eof ( theOutputBuffer , 0 , 0 ) ;


signature:
public class RegexValidator { /** * Validate a value against the set of regular expressions
 * returning a String value of the aggregated groups .
 * @ param value The value to validate .
 * @ return Aggregated String value comprised of the
 * < i > groups < / i > matched if valid or < code > null < / code > if invalid */
public String validate ( String value ) { } }

implementation: if ( value == null ) { return null ; } for ( int i = 0 ; i < patterns . length ; i ++ ) { Matcher matcher = patterns [ i ] . matcher ( value ) ; if ( matcher . matches ( ) ) { int count = matcher . groupCount ( ) ; if ( count == 1 ) { return matcher . group ( 1 ) ; } StringBuffer buffer = new StringBuffer ( ) ; for ( int j = 0 ; j < count ; j ++ ) { String component = matcher . group ( j + 1 ) ; if ( component != null ) { buffer . append ( component ) ; } } return buffer . toString ( ) ; } } return null ;


signature:
public class Paragraph { /** * The paragraph is selected by the Selection if :
 * - they have at least one character in common
 * - the selection is a point within the paragraph ( " 01 \ n " - > 0 till 2 intersects while the span is [ 0 , 3 ] )
 * - the selection is a point within or at the end of the LAST paragraph ( " 01 " - > 0 till 2 intersects while the span is [ 0 , 2 ] ) ,
 * e . g . [ 10 , 10 ] will intersect the paragraph [ 0 , 10 ] only if it ' s the last paragraph */
public boolean isSelected ( Selection sel ) { } }

implementation:
if ( sel == null ) { return false ; } if ( sel . isEmpty ( ) ) { // selection is a point
boolean isCompletelyWithin = sel . start ( ) >= start ( ) && sel . end ( ) < end ( ) ; // selection is completely within paragraph ( not at the end )
boolean isWithin = sel . start ( ) >= start ( ) && sel . end ( ) <= end ( ) ; // selection is within or at the end of the paragraph
return isCompletelyWithin || ( isWithin && mIsLast ) ; } else { // selection is a range - - > at least one character in common
int start = Math . max ( start ( ) , sel . start ( ) ) ; int end = Math . min ( end ( ) , sel . end ( ) ) ; return start < end ; }


signature:
public class LineIterator { /** * Indicates whether the < code > Reader < / code > has more lines .
 * If there is an < code > IOException < / code > then { @ link # close ( ) } will
 * be called on this instance .
 * @ return { @ code true } if the Reader has more lines
 * @ throws IllegalStateException if an IO exception occurs */
public boolean hasNext ( ) { } }

implementation: if ( cachedLine != null ) { return true ; } else if ( finished ) { return false ; } else { try { while ( true ) { String line = bufferedReader . readLine ( ) ; if ( line == null ) { finished = true ; return false ; } else if ( isValidLine ( line ) ) { cachedLine = line ; return true ; } } } catch ( IOException ioe ) { close ( ) ; throw new IllegalStateException ( ioe ) ; } }


signature:
public class LineIterator { /** * Returns the next line in the wrapped < code > Reader < / code > .
 * @ return the next line from the input
 * @ throws NoSuchElementException if there is no line to return */
public String nextLine ( ) { } }

implementation: if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "No more lines" ) ; } String currentLine = cachedLine ; cachedLine = null ; return currentLine ;


signature:
public class Schema { /** * Add or replace an element type for this schema .
 * @ param name Name ( Qname ) of the element
 * @ param model Models of the element ' s content as a vector of bits
 * @ param memberOf Models the element is a member of as a vector of bits
 * @ param flags Flags for the element */
@ SuppressLint ( "DefaultLocale" ) public void elementType ( String name , int model , int memberOf , int flags ) { } }

implementation: ElementType e = new ElementType ( name , model , memberOf , flags , this ) ; theElementTypes . put ( name . toLowerCase ( ) , e ) ; if ( memberOf == M_ROOT ) theRoot = e ;


signature:
public class Schema { /** * Add or replace a default attribute for an element type in this schema .
 * @ param elemName Name ( Qname ) of the element type
 * @ param attrName Name ( Qname ) of the attribute
 * @ param type Type of the attribute
 * @ param value Default value of the attribute ; null if no default */
public void attribute ( String elemName , String attrName , String type , String value ) { } }

implementation: ElementType e = getElementType ( elemName ) ; if ( e == null ) { throw new Error ( "Attribute " + attrName + " specified for unknown element type " + elemName ) ; } e . setAttribute ( attrName , type , value ) ;