signature:
public class XsdAbstractElement { /** * In special cases such as { @ link XsdAppInfo } and { @ link XsdDocumentation } the contents are a simple text node ,
 * in which case this function is more suited than using the { @ link XsdAbstractElement # xsdParseSkeleton } since
 * those types of elements can ' t have children nodes .
 * @ param node The { @ link Node } containing either a { @ link XsdAppInfo } or { @ link XsdDocumentation } .
 * @ return The textual value contained in the { @ link Node } parameter . */
static String xsdRawContentParse ( Node node ) { } }

implementation: Node child = node . getFirstChild ( ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; while ( child != null ) { if ( child . getNodeType ( ) == Node . TEXT_NODE ) { stringBuilder . append ( child . getTextContent ( ) ) ; } child = child . getNextSibling ( ) ; } return stringBuilder . toString ( ) ;


signature:
public class XsdIntegerRestrictions { /** * Compares two different objects of this type .
 * @ param o1 The first object .
 * @ param o2 The object to compare .
 * @ return True if the value of both classes is different , False if the value is equal . */
public static boolean hasDifferentValue ( XsdIntegerRestrictions o1 , XsdIntegerRestrictions o2 ) { } }

implementation: if ( o1 == null && o2 == null ) { return false ; } int o1Value = Integer . MAX_VALUE ; int o2Value ; if ( o1 != null ) { o1Value = o1 . getValue ( ) ; } if ( o2 != null ) { o2Value = o2 . getValue ( ) ; return o2Value == o1Value ; } return false ;


signature:
public class AttributeValidations { /** * Verifies if a given value is present in a given { @ link Enum } type .
 * @ param instance An instance of the concrete { @ link Enum } type that is expected to contain the { @ code value } received .
 * @ param value The value that is expected to be present in the received { @ link Enum } type .
 * @ param < T > The concrete type of the { @ link Enum } type .
 * @ return The instance of the concrete { @ link Enum } type that represents { @ code value } in the respective { @ link Enum } . */
public static < T extends XsdEnum > T belongsToEnum ( final XsdEnum < T > instance , final String value ) { } }

implementation: if ( value == null ) { return null ; } Optional < T > enumValue = Arrays . stream ( instance . getValues ( ) ) . filter ( enumField -> enumField . getValue ( ) . equals ( value ) ) . findFirst ( ) ; if ( enumValue . isPresent ( ) ) { return enumValue . get ( ) ; } else { StringBuilder possibleValues = new StringBuilder ( ) ; instance . getSupportedValues ( ) . forEach ( supportedValue -> possibleValues . append ( supportedValue ) . append ( ", " ) ) ; String values = possibleValues . toString ( ) ; values = values . substring ( 0 , values . length ( ) - 2 ) ; throw new ParsingException ( "The attribute " + instance . getVariableName ( ) + " doesn't support the value \"" + value + "\".\n" + "The possible values for the " + instance . getVariableName ( ) + " attribute are:\n" + values ) ; }


signature:
public class AttributeValidations { /** * Checks if the maxOccurs attribute is unbounded or an { @ link Integer } value .
 * @ param value The possible maxOccurs value .
 * @ param elementName The name of the element containing the maxOccurs attribute .
 * @ return The validated maxOccurs value . */
static String maxOccursValidation ( String elementName , String value ) { } }

implementation: if ( value . equals ( "unbounded" ) ) { return value ; } validateNonNegativeInteger ( elementName , MAX_OCCURS_TAG , value ) ; return value ;


signature:
public class AttributeValidations { /** * Validates if a given String is a non negative { @ link Integer } . Throws an exception if the { @ link String } isn ' t a non
 * negative { @ link Integer } .
 * @ param elementName The element name containing the field with the { @ link Integer } value .
 * @ param attributeName The name of the attribute with the { @ link Integer } .
 * @ param value The value to be parsed to a { @ link Integer } object .
 * @ return The parsed { @ link Integer } value . */
static Integer validateNonNegativeInteger ( String elementName , String attributeName , String value ) { } }

implementation: try { int intValue = Integer . parseInt ( value ) ; if ( intValue < 0 ) { throw new ParsingException ( "The " + elementName + " " + attributeName + " attribute should be a non negative integer. (greater or equal than 0)" ) ; } return intValue ; } catch ( NumberFormatException e ) { throw new ParsingException ( "The " + elementName + " " + attributeName + "  attribute should be a non negative integer." ) ; }


signature:
public class AttributeValidations { /** * Validates if a given String is a non negative { @ link Integer } . Throws an exception if the { @ link String } isn ' t a
 * non negative { @ link Integer } .
 * @ param elementName The element name containing the field with the { @ link Integer } value .
 * @ param attributeName The name of the attribute with the { @ link Integer } .
 * @ param value The value to be parsed to a { @ link Integer } object .
 * @ return The parsed { @ link Integer } value . */
public static Integer validateRequiredNonNegativeInteger ( String elementName , String attributeName , String value ) { } }

implementation: if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validateNonNegativeInteger ( elementName , attributeName , value ) ;


signature:
public class AttributeValidations { /** * Validates if a given String is a positive { @ link Integer } . Throws an exception if the { @ link String } isn ' t a
 * positive { @ link Integer } .
 * @ param elementName The element name containing the field with the { @ link Integer } value .
 * @ param attributeName The name of the attribute with the { @ link Integer } type .
 * @ param value The value to be parsed to a { @ link Integer } object .
 * @ return The parsed { @ link Integer } value . */
public static Integer validateRequiredPositiveInteger ( String elementName , String attributeName , String value ) { } }

implementation: if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validatePositiveInteger ( elementName , attributeName , value ) ;


signature:
public class AttributeValidations { /** * Validates if a given { @ link String } is a { @ link Double } . Throws an exception if the { @ link String } isn ' t a
 * { @ link Double } .
 * @ param elementName The element name containing the field with the { @ link Double } value .
 * @ param attributeName The name of the attribute with the type { @ link Double } .
 * @ param value The value to be parsed to a { @ link Double } object .
 * @ return The parsed { @ link Double } value . */
private static Double validateDouble ( String elementName , String attributeName , String value ) { } }

implementation: try { return Double . parseDouble ( value ) ; } catch ( NumberFormatException e ) { throw new ParsingException ( "The " + elementName + " " + attributeName + "  attribute should be a numeric value." ) ; }


signature:
public class AttributeValidations { /** * Validates if a given { @ link String } is a { @ link Double } . Throws an exception if the { @ link String } isn ' t a { @ link Double } .
 * @ param elementName The element name containing the field with the { @ link Double } value .
 * @ param attributeName The name of the attribute with the type { @ link Double } .
 * @ param value The value to be parsed to a { @ link Double } object .
 * @ return The parsed { @ link Double } value . */
public static Double validateRequiredDouble ( String elementName , String attributeName , String value ) { } }

implementation: if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validateDouble ( elementName , attributeName , value ) ;


signature:
public class AttributeValidations { /** * Obtains the default value of the { @ link XsdSchema # attributeFormDefault } attribute by iterating in the element tree
 * by going from { @ link XsdAbstractElement # parent } to { @ link XsdAbstractElement # parent } until reaching the top level
 * element .
 * @ param parent The parent of the element requesting the default form value .
 * @ return The default value for the form attribute . */
static String getFormDefaultValue ( XsdAbstractElement parent ) { } }

implementation: if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getElementFormDefault ( ) ; } return getFormDefaultValue ( parent . getParent ( ) ) ;


signature:
public class AttributeValidations { /** * Obtains the default value of the { @ link XsdSchema # finalDefault } attribute by iterating in the element tree by
 * going from { @ link XsdAbstractElement # parent } to { @ link XsdAbstractElement # parent } until reaching the top level
 * element .
 * @ param parent The parent of the element requesting the default final value .
 * @ return The default value for the final attribute . */
static String getFinalDefaultValue ( XsdAbstractElement parent ) { } }

implementation: if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getFinalDefault ( ) ; } return getFinalDefaultValue ( parent . getParent ( ) ) ;


signature:
public class AttributeValidations { /** * Obtains the default value of the { @ link XsdSchema # blockDefault } attribute by iterating in the element tree by
 * going from { @ link XsdAbstractElement # parent } to { @ link XsdAbstractElement # parent } until reaching the top level
 * element .
 * @ param parent The parent of the element requesting the default block value .
 * @ return The default value for the block attribute . */
static String getBlockDefaultValue ( XsdAbstractElement parent ) { } }

implementation: if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getBlockDefault ( ) ; } return getBlockDefaultValue ( parent . getParent ( ) ) ;


signature:
public class ReferenceBase { /** * This method creates a ReferenceBase object that serves as a wrapper to { @ link XsdAbstractElement } objects .
 * If a { @ link XsdAbstractElement } has a ref attribute it results in a { @ link UnsolvedReference } object . If it
 * doesn ' t have a ref attribute and has a name attribute it ' s a { @ link NamedConcreteElement } . If it isn ' t a
 * { @ link UnsolvedReference } or a { @ link NamedConcreteElement } then it ' s a { @ link ConcreteElement } .
 * @ param element The element which will be " wrapped " .
 * @ return A wrapper object for the element received . */
public static ReferenceBase createFromXsd ( XsdAbstractElement element ) { } }

implementation: String ref = getRef ( element ) ; String name = getName ( element ) ; if ( ! ( element instanceof XsdNamedElements ) ) { return new ConcreteElement ( element ) ; } if ( ref == null ) { if ( name == null ) { return new ConcreteElement ( element ) ; } else { return new NamedConcreteElement ( ( XsdNamedElements ) element , name ) ; } } else { return new UnsolvedReference ( ( XsdNamedElements ) element ) ; }


signature:
public class XsdExtension { /** * This method should always receive two elements , one to replace the { @ link UnsolvedReference } created due to
 * the value present in the base attribute and another if it has an { @ link UnsolvedReference } as a child element .
 * @ param element A concrete element with a name that will replace the { @ link UnsolvedReference } object created in the
 * { @ link XsdExtension } constructor . The { @ link UnsolvedReference } is only replaced if there
 * is a match between the { @ link UnsolvedReference # ref } and the { @ link NamedConcreteElement # name } . */
@ Override public void replaceUnsolvedElements ( NamedConcreteElement element ) { } }

implementation: super . replaceUnsolvedElements ( element ) ; XsdNamedElements elem = element . getElement ( ) ; String elemName = elem . getRawName ( ) ; boolean isComplexOrSimpleType = elem instanceof XsdComplexType || elem instanceof XsdSimpleType ; if ( this . base instanceof UnsolvedReference && isComplexOrSimpleType && ( ( UnsolvedReference ) this . base ) . getRef ( ) . equals ( elemName ) ) { this . base = element ; } if ( this . childElement instanceof UnsolvedReference && elem instanceof XsdGroup && ( ( UnsolvedReference ) this . childElement ) . getRef ( ) . equals ( elemName ) ) { this . childElement = element ; } visitor . replaceUnsolvedAttributes ( element ) ;


signature:
public class ConvertTypeOfObject { /** * If T is assignable from value , then return the value . Otherwise tries to
 * create an instance of this type using the provided argument .
 * Will first attempt to find a static method called " valueOf " which returns
 * this type and takes a single argument compatible with the type of the
 * value given . If that is not found , tries to find a constructor which
 * takes an argument of the type of the given value . Otherwise throws a
 * ClassCastException
 * @ param value
 * the value to be converted
 * @ throws ClassCastException
 * if the types cannot be converted
 * @ return the converted value */
@ Override public T convert ( final Object value ) { } }

implementation: if ( value == null ) { return null ; } else if ( isIterable ( ) && Iterable . class . isAssignableFrom ( value . getClass ( ) ) ) { return convertIterable ( value ) ; } else if ( reflectedKlass . assignableFromObject ( value ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeUnboxed ( value . getClass ( ) ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeBoxed ( value . getClass ( ) ) ) { return ( T ) value ; } FluentClass < ? > klassToCreate ; if ( reflectedKlass . isPrimitive ( ) ) { klassToCreate = reflectedKlass . boxedType ( ) ; } else { klassToCreate = reflectedKlass ; } return ( T ) convertValueTo ( value , klassToCreate ) ;


signature:
public class CliFactory { /** * Construct a Cli from an annotated interface definition
 * @ param < O >
 * The type of the interface that will be used to present the
 * arguments
 * @ param klass
 * The annotated interface definition
 * @ return A Cli configured to create instance of klass
 * @ throws ArgumentValidationException the arguments do not meet the CLI specification
 * @ throws InvalidOptionSpecificationException the CLI specification is not valid */
public static < O > Cli < O > createCli ( final Class < O > klass ) throws InvalidOptionSpecificationException { } }

implementation: return new CliInterfaceImpl < O > ( klass ) ;


signature:
public class CliFactory { /** * Construct a Cli from an annotated class
 * @ param < O >
 * The type of the class used to present the arguments
 * @ param options
 * The annotated class
 * @ return A Cli configured to configure the options
 * @ throws ArgumentValidationException the arguments do not meet the CLI specification
 * @ throws InvalidOptionSpecificationException the CLI specification is not valid */
public static < O > Cli < O > createCliUsingInstance ( final O options ) throws InvalidOptionSpecificationException { } }

implementation: return new CliInstanceImpl < O > ( options ) ;


signature:
public class CliFactory { /** * Parse arguments from an annotated interface definition
 * @ param < O >
 * The type of the interface that will be used to present the
 * arguments
 * @ param klass
 * The annotated interface definition
 * @ param arguments
 * @ return The parsed arguments
 * @ throws ArgumentValidationException the arguments do not meet the CLI specification
 * @ throws InvalidOptionSpecificationException the CLI specification is not valid */
public static < O > O parseArguments ( final Class < O > klass , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { } }

implementation: return createCli ( klass ) . parseArguments ( arguments ) ;


signature:
public class CliFactory { /** * Parse arguments from an annotated class instance
 * @ param < O >
 * The type of the class used to present the arguments
 * @ param klass
 * The annotated interface definition
 * @ param arguments
 * @ return The parsed arguments
 * @ throws ArgumentValidationException the arguments do not meet the CLI specification
 * @ throws InvalidOptionSpecificationException the CLI specification is not valid */
public static < O > O parseArgumentsUsingInstance ( final O options , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { } }

implementation: return createCliUsingInstance ( options ) . parseArguments ( arguments ) ;


signature:
public class ArgumentParserImpl { /** * { @ inheritDoc } */
@ Override public void parseArguments ( final ParsedArguments parsedArguments , final String ... arguments ) throws ArgumentValidationException { } }

implementation: boolean finishedOptions = false ; for ( final String argument : arguments ) { if ( finishedOptions ) { parsedArguments . addValue ( argument ) ; } else { finishedOptions = add ( parsedArguments , argument ) ; } }


signature:
public class AsciiArtTableExample { /** * Note : The following methods are used to get a String representation of the different POJO
 * ( while handling null value ) */
private static String getEventDate ( Date dates ) { } }

implementation: return Optional . ofNullable ( dates ) . map ( Date :: getStart ) . map ( Start :: getDateTime ) . map ( dt -> dt . toString ( ) ) . orElse ( "No date" ) ;


signature:
public class DiscoveryApi { /** * Package protected for testing purposess */
Builder urlBuilder ( String path ) { } }

implementation: Builder builder = baseUrlBuilder ( ) . addPathSegment ( configuration . getApiPackage ( ) ) . addPathSegment ( configuration . getApiVersion ( ) ) . addPathSegment ( path ) ; if ( configuration . getPathModifier ( ) != DiscoveryApiConfiguration . PathModifier . NONE ) { builder . addPathSegment ( configuration . getPathModifier ( ) . getModifier ( ) ) ; } return builder ;


signature:
public class HeaderGridView { /** * Add a fixed view to appear at the top of the list . If this method is
 * called more than once , the views will appear in the order they were
 * added . Views added using this call can take focus if they want .
 * Note : When first introduced , this method could only be called before
 * setting the adapter with { @ link # setAdapter ( ListAdapter ) } . Starting with
 * { @ link android . os . Build . VERSION _ CODES # KITKAT } , this method may be
 * called at any time . If the ListView ' s adapter does not extend
 * { @ link FooterViewGridAdapter } , it will be wrapped with a supporting
 * instance of { @ link android . widget . WrapperListAdapter } .
 * @ param v The view to add .
 * @ param data Data to associate with this view
 * @ param isSelectable whether the item is selectable */
public void addHeaderView ( View v , Object data , boolean isSelectable ) { } }

implementation:
final FixedViewInfo info = new FixedViewInfo ( ) ; FrameLayout fl = new FullWidthFixedViewLayout ( getContext ( ) ) ; fl . addView ( v ) ; info . view = v ; info . viewContainer = fl ; info . data = data ; info . isSelectable = isSelectable ; mHeaderViewInfos . add ( info ) ; // Wrap the adapter if it wasn ' t already wrapped .
if ( mAdapter != null ) { if ( ! ( mAdapter instanceof FooterViewGridAdapter ) ) { mAdapter = new FooterViewGridAdapter ( mHeaderViewInfos , mFooterViewInfos , mAdapter ) ; } // Do not know if this really helps
notifiyChanged ( ) ; }


signature:
public class HeaderGridView { /** * Removes a previously - added footer view .
 * @ param v The view to remove
 * @ return
 * true if the view was removed , false if the view was not a footer view */
public boolean removeFooterView ( View v ) { } }

implementation: if ( mFooterViewInfos . size ( ) > 0 ) { boolean result = false ; if ( mAdapter != null && ( ( FooterViewGridAdapter ) mAdapter ) . removeFooter ( v ) ) { notifiyChanged ( ) ; result = true ; } removeFixedViewInfo ( v , mFooterViewInfos ) ; return result ; } return false ;


signature:
public class Line { /** * Sets the position ( @ a x , @ a y , @ a z ) of the start of the line segment to choose values along .
 * @ param x x coordinate of the start position .
 * @ param y y coordinate of the start position .
 * @ param z z coordinate of the start position . */
public void setStartPoint ( double x , double y , double z ) { } }

implementation: this . x0 = x ; this . y0 = y ; this . z0 = z ;


signature:
public class Line { /** * Sets the position ( @ a x , @ a y , @ a z ) of the end of the line segment to choose values along .
 * @ param x x coordinate of the end position .
 * @ param y y coordinate of the end position .
 * @ param z z coordinate of the end position . */
public void setEndPoint ( double x , double y , double z ) { } }

implementation: this . x1 = x ; this . y1 = y ; this . z1 = z ;


signature:
public class Line { /** * Returns the output value from the noise module given the one - dimensional coordinate of the specified input value located on the line segment .
 * @ param p The distance along the line segment ( ranges from 0.0 to 1.0)
 * @ return The output value from the noise module . */
public double getValue ( double p ) { } }

implementation: if ( module == null ) { throw new NoModuleException ( ) ; } double x = ( x1 - x0 ) * p + x0 ; double y = ( y1 - y0 ) * p + y0 ; double z = ( z1 - z0 ) * p + z0 ; double value = module . getValue ( x , y , z ) ; if ( attenuate ) { return p * ( 1.0 - p ) * 4 * value ; } else { return value ; }


signature:
public class Plane { /** * Returns the output value from the noise module given the ( @ a x , @ a z ) coordinates of the specified input value located on the surface of the plane .
 * @ param x The @ a x coordinate of the input value .
 * @ param z The @ a z coordinate of the input value .
 * @ return The output value from the noise module . */
public double getValue ( double x , double z ) { } }

implementation: if ( module == null ) { throw new NoModuleException ( ) ; } return module . getValue ( x , 0 , z ) ;


signature:
public class Noise { /** * Generates a gradient - coherent - noise value from the coordinates of a three - dimensional input value .
 * @ param x The @ a x coordinate of the input value .
 * @ param y The @ a y coordinate of the input value .
 * @ param z The @ a z coordinate of the input value .
 * @ param seed The random number seed .
 * @ param quality The quality of the coherent - noise .
 * @ return The generated gradient - coherent - noise value .
 * The return value ranges from 0 to 1.
 * For an explanation of the difference between < i > gradient < / i > noise and < i > value < / i > noise , see the comments for the GradientNoise3D ( ) function . */
public static double gradientCoherentNoise3D ( double x , double y , double z , int seed , NoiseQuality quality ) { } }

implementation:
// Create a unit - length cube aligned along an integer boundary . This cube
// surrounds the input point .
int x0 = ( ( x > 0.0 ) ? ( int ) x : ( int ) x - 1 ) ; int x1 = x0 + 1 ; int y0 = ( ( y > 0.0 ) ? ( int ) y : ( int ) y - 1 ) ; int y1 = y0 + 1 ; int z0 = ( ( z > 0.0 ) ? ( int ) z : ( int ) z - 1 ) ; int z1 = z0 + 1 ; // Map the difference between the coordinates of the input value and the
// coordinates of the cube ' s outer - lower - left vertex onto an S - curve .
double xs , ys , zs ; if ( quality == NoiseQuality . FAST ) { xs = ( x - ( double ) x0 ) ; ys = ( y - ( double ) y0 ) ; zs = ( z - ( double ) z0 ) ; } else if ( quality == NoiseQuality . STANDARD ) { xs = Utils . sCurve3 ( x - ( double ) x0 ) ; ys = Utils . sCurve3 ( y - ( double ) y0 ) ; zs = Utils . sCurve3 ( z - ( double ) z0 ) ; } else { xs = Utils . sCurve5 ( x - ( double ) x0 ) ; ys = Utils . sCurve5 ( y - ( double ) y0 ) ; zs = Utils . sCurve5 ( z - ( double ) z0 ) ; } // Now calculate the noise values at each vertex of the cube . To generate
// the coherent - noise value at the input point , interpolate these eight
// noise values using the S - curve value as the interpolant ( trilinear
// interpolation . )
double n0 , n1 , ix0 , ix1 , iy0 , iy1 ; n0 = gradientNoise3D ( x , y , z , x0 , y0 , z0 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y0 , z0 , seed ) ; ix0 = Utils . linearInterp ( n0 , n1 , xs ) ; n0 = gradientNoise3D ( x , y , z , x0 , y1 , z0 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y1 , z0 , seed ) ; ix1 = Utils . linearInterp ( n0 , n1 , xs ) ; iy0 = Utils . linearInterp ( ix0 , ix1 , ys ) ; n0 = gradientNoise3D ( x , y , z , x0 , y0 , z1 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y0 , z1 , seed ) ; ix0 = Utils . linearInterp ( n0 , n1 , xs ) ; n0 = gradientNoise3D ( x , y , z , x0 , y1 , z1 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y1 , z1 , seed ) ; ix1 = Utils . linearInterp ( n0 , n1 , xs ) ; iy1 = Utils . linearInterp ( ix0 , ix1 , ys ) ; return Utils . linearInterp ( iy0 , iy1 , zs ) ;


signature:
public class Noise { /** * Generates a gradient - noise value from the coordinates of a three - dimensional input value and the integer coordinates of a nearby three - dimensional value .
 * @ param fx The floating - point @ a x coordinate of the input value .
 * @ param fy The floating - point @ a y coordinate of the input value .
 * @ param fz The floating - point @ a z coordinate of the input value .
 * @ param ix The integer @ a x coordinate of a nearby value .
 * @ param iy The integer @ a y coordinate of a nearby value .
 * @ param iz The integer @ a z coordinate of a nearby value .
 * @ param seed The random number seed .
 * @ return The generated gradient - noise value .
 * The difference between fx and ix must be less than or equal to one . The difference between @ a fy and @ a iy must be less than or equal to one . The difference between @ a fz and @ a iz must be less
 * than or equal to one .
 * A < i > gradient < / i > - noise function generates better - quality noise than a < i > value < / i > - noise function . Most noise modules use gradient noise for this reason , although it takes much longer to
 * calculate .
 * The return value ranges from 0 to 1.
 * This function generates a gradient - noise value by performing the following steps : - It first calculates a random normalized vector based on the nearby integer value passed to this function . -
 * It then calculates a new value by adding this vector to the nearby integer value passed to this function . - It then calculates the dot product of the above - generated value and the
 * floating - point input value passed to this function .
 * A noise function differs from a random - number generator because it always returns the same output value if the same input value is passed to it . */
public static double gradientNoise3D ( double fx , double fy , double fz , int ix , int iy , int iz , int seed ) { } }

implementation:
// Randomly generate a gradient vector given the integer coordinates of the
// input value . This implementation generates a random number and uses it
// as an index into a normalized - vector lookup table .
int vectorIndex = ( X_NOISE_GEN * ix + Y_NOISE_GEN * iy + Z_NOISE_GEN * iz + SEED_NOISE_GEN * seed ) ; vectorIndex ^= ( vectorIndex >> SHIFT_NOISE_GEN ) ; vectorIndex &= 0xff ; double xvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) ] ; double yvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) + 1 ] ; double zvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) + 2 ] ; // Set up us another vector equal to the distance between the two vectors
// passed to this function .
double xvPoint = ( fx - ix ) ; double yvPoint = ( fy - iy ) ; double zvPoint = ( fz - iz ) ; // Now compute the dot product of the gradient vector with the distance
// vector . The resulting value is gradient noise . Apply a scaling and
// offset value so that this noise value ranges from 0 to 1.
return ( ( xvGradient * xvPoint ) + ( yvGradient * yvPoint ) + ( zvGradient * zvPoint ) ) + 0.5 ;


signature:
public class Noise { /** * Generates an integer - noise value from the coordinates of a three - dimensional input value .
 * @ param x The integer @ a x coordinate of the input value .
 * @ param y The integer @ a y coordinate of the input value .
 * @ param z The integer @ a z coordinate of the input value .
 * @ param seed A random number seed .
 * @ return The generated integer - noise value .
 * The return value ranges from 0 to 2147483647.
 * A noise function differs from a random - number generator because it always returns the same output value if the same input value is passed to it . */
public static int intValueNoise3D ( int x , int y , int z , int seed ) { } }

implementation:
// All constants are primes and must remain prime in order for this noise
// function to work correctly .
int n = ( X_NOISE_GEN * x + Y_NOISE_GEN * y + Z_NOISE_GEN * z + SEED_NOISE_GEN * seed ) & 0x7fffffff ; n = ( n >> 13 ) ^ n ; return ( n * ( n * n * 60493 + 19990303 ) + 1376312589 ) & 0x7fffffff ;


signature:
public class Noise { /** * Generates a value - noise value from the coordinates of a three - dimensional input value .
 * @ param x The @ a x coordinate of the input value .
 * @ param y The @ a y coordinate of the input value .
 * @ param z The @ a z coordinate of the input value .
 * @ param seed A random number seed .
 * @ return The generated value - noise value .
 * The return value ranges from 0 to 1.
 * A noise function differs from a random - number generator because it always returns the same output value if the same input value is passed to it . */
public static double valueNoise3D ( int x , int y , int z , int seed ) { } }

implementation: return intValueNoise3D ( x , y , z , seed ) / 2147483647.0 ;


signature:
public class Cylinder { /** * Returns the output value from the noise module given the ( angle , height ) coordinates of the specified input value located on the surface of the cylinder .
 * @ param angle The angle around the cylinder ' s center , in degrees .
 * @ param height The height along the @ a y axis .
 * @ return The output value from the noise module . */
public double getValue ( double angle , double height ) { } }

implementation: if ( module == null ) { throw new NoModuleException ( ) ; } double x , y , z ; x = Math . cos ( Math . toRadians ( angle ) ) ; y = height ; z = Math . sin ( Math . toRadians ( angle ) ) ; return module . getValue ( x , y , z ) ;


signature:
public class Sphere { /** * Returns the output value from the noise module given the ( latitude , longitude ) coordinates of the specified input value located on the surface of the sphere .
 * @ param lat The latitude of the input value , in degrees .
 * @ param lon The longitude of the input value , in degrees .
 * @ return The output value from the noise module . */
public double getValue ( double lat , double lon ) { } }

implementation: if ( module == null ) { throw new NoModuleException ( ) ; } double [ ] vec = Utils . latLonToXYZ ( lat , lon ) ; return module . getValue ( vec [ 0 ] , vec [ 1 ] , vec [ 2 ] ) ;


signature:
public class Utils { /** * Performs cubic interpolation between two values bound between two other values
 * @ param n0 the value before the first value
 * @ param n1 the first value
 * @ param n2 the second value
 * @ param n3 the value after the second value
 * @ param a the alpha value
 * @ return the interpolated value */
public static double cubicInterp ( double n0 , double n1 , double n2 , double n3 , double a ) { } }

implementation: double p = ( n3 - n2 ) - ( n0 - n1 ) ; double q = ( n0 - n1 ) - p ; double r = n2 - n0 ; return p * a * a * a + q * a * a + r * a + n1 ;


signature:
public class Utils { /** * maps a value onto a quitnic S - Curve
 * @ param a the value to map onto a quitic S - curve
 * @ return the mapped value */
public static double sCurve5 ( double a ) { } }


signature:
public class Range { /** * Calculate the scale and biased to be a applied during Range # getValue ( int x , int y , int z )
 * Should be called when the bounds are modified */
private void recalculateScaleBias ( ) { } }

implementation: scale = ( getNewUpperBound ( ) - getNewLowerBound ( ) ) / ( getCurrentUpperBound ( ) - getCurrentLowerBound ( ) ) ; bias = getNewLowerBound ( ) - getCurrentLowerBound ( ) * scale ;


signature:
public class Range { /** * Configure bounds for range module
 * @ param currentLower current lower bound
 * @ param currentUpper current upper bound
 * @ param newLower new lower bound
 * @ param newUpper new upper bound */
public void setBounds ( double currentLower , double currentUpper , double newLower , double newUpper ) { } }

implementation: if ( currentLower == currentUpper ) { throw new IllegalArgumentException ( "currentLower must not equal currentUpper. Both are " + currentUpper ) ; } if ( newLower == newUpper ) { throw new IllegalArgumentException ( "newLowerBound must not equal newUpperBound. Both are " + newUpper ) ; } currentLowerBound = currentLower ; currentUpperBound = currentUpper ; newLowerBound = newLower ; newUpperBound = newUpper ; recalculateScaleBias ( ) ;


signature:
public class PluginEventsProcessor { /** * Processes an single event by looping available plugins .
 * @ see # doProcess ( CloudTrailEvent , FullstopPlugin ) */
protected void doProcess ( final CloudTrailEvent event ) { } }

implementation: for ( final FullstopPlugin plugin : getPluginsForEvent ( event ) ) { doProcess ( event , plugin ) ; }


signature:
public class PluginEventsProcessor { /** * Processes a specific event on specified plugin . */
protected void doProcess ( final CloudTrailEvent event , final FullstopPlugin plugin ) { } }

implementation: try { plugin . processEvent ( event ) ; } catch ( HystrixRuntimeException | HttpServerErrorException e ) { log . warn ( e . getMessage ( ) , e ) ; } catch ( final Exception e ) { log . error ( e . getMessage ( ) , e ) ; }


signature:
public class CloudTrailEventSupport { /** * Extracts list of instanceIds from { @ link CloudTrailEvent } s ' responseElements ' . */
public static List < String > getInstanceIds ( final CloudTrailEvent event ) { } }

implementation: final CloudTrailEventData eventData = getEventData ( event ) ; final String responseElements = eventData . getResponseElements ( ) ; if ( isNullOrEmpty ( responseElements ) ) { return newArrayList ( ) ; } return read ( responseElements , INSTANCE_ID_JSON_PATH ) ;


signature:
public class CloudTrailEventSupport { /** * Extracts the ' accountId ' . */
public static String getAccountId ( final CloudTrailEvent event ) { } }

implementation: final CloudTrailEventData eventData = getEventData ( event ) ; final UserIdentity userIdentity = checkNotNull ( eventData . getUserIdentity ( ) , USER_IDENTITY_SHOULD_NEVER_BE_NULL ) ; final String value = ofNullable ( userIdentity . getAccountId ( ) ) . orElse ( eventData . getRecipientAccountId ( ) ) ; return checkNotNull ( value , ACCOUNT_ID_OR_RECIPIENT_SHOULD_NEVER_BE_NULL ) ;


signature:
public class CloudTrailEventSupport { /** * Reads the given ' responseElements ' and extracts information based on given ' pattern ' . < br / >
 * If ' responseElements ' is null or empty you can handle the { @ link IllegalArgumentException } raised or got an empty
 * list . */
public static List < String > read ( final String responseElements , final String pattern , final boolean emptyListOnNullOrEmptyResponse ) { } }

implementation: if ( isNullOrEmpty ( responseElements ) && emptyListOnNullOrEmptyResponse ) { return emptyList ( ) ; } try { return JsonPath . read ( responseElements , pattern ) ; } catch ( final PathNotFoundException e ) { if ( emptyListOnNullOrEmptyResponse ) { return emptyList ( ) ; } else { throw e ; } }


signature:
public class CloudTrailEventSupport { /** * Reads the given ' responseElements ' and extracts information based on given ' pattern ' . < br / >
 * If ' responseElements ' is null or empty raises { @ link IllegalArgumentException } . */
public static List < String > read ( final String responseElements , final String pattern ) { } }

implementation: return read ( responseElements , pattern , false ) ;


signature:
public class WhitelistRulesEvaluator { /** * true if rule matches a violation and should be whitelisted .
 * @ return true if rule matches a violation */
@ Override public Boolean apply ( final RuleEntity ruleEntity , final ViolationEntity violationEntity ) { } }

implementation: final List < Predicate < ViolationEntity > > predicates = newArrayList ( ) ; trimOptional ( ruleEntity . getAccountId ( ) ) . map ( WhitelistRulesEvaluator :: accountIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getRegion ( ) ) . map ( WhitelistRulesEvaluator :: regionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getViolationTypeEntityId ( ) ) . map ( WhitelistRulesEvaluator :: violationTypeIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageName ( ) ) . map ( WhitelistRulesEvaluator :: imageNameMatches ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageOwner ( ) ) . map ( WhitelistRulesEvaluator :: imageOwnerIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationId ( ) ) . map ( WhitelistRulesEvaluator :: applicationIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationVersion ( ) ) . map ( WhitelistRulesEvaluator :: applicationVersionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getMetaInfoJsonPath ( ) ) . map ( this :: metaInfoJsonPathExists ) . ifPresent ( predicates :: add ) ; final Optional < Predicate < ViolationEntity > > whiteListTest = predicates . stream ( ) . reduce ( Predicate :: and ) ; return whiteListTest . isPresent ( ) && whiteListTest . get ( ) . test ( violationEntity ) ;


signature:
public class PrefixBuilder { /** * Builds the prefix that will be prepended to the ' bucketname ' < br / >
 * Something like ' 123456789 / eu - west - 1/2015/06/12 / '
 * @ param accountId
 * @ param region name of region
 * @ param instanceLaunchTime
 * @ return */
static String build ( final String accountId , final String region , final DateTime instanceLaunchTime ) { } }

implementation: return Paths . get ( accountId , region , instanceLaunchTime . toString ( "YYYY" ) , instanceLaunchTime . toString ( "MM" ) , instanceLaunchTime . toString ( "dd" ) ) . toString ( ) + "/" ;


signature:
public class FileEventReader { /** * Get the EventSerializer based on user ' s configuration .
 * @ param inputStream the Gzipped content from CloudTrail log file
 * @ param ctLog CloudTrail log file
 * @ return parser that parses CloudTrail log file
 * @ throws java . io . IOException */
private EventSerializer getEventSerializer ( final GZIPInputStream inputStream , final CloudTrailLog ctLog ) throws IOException { } }

implementation: final EventSerializer serializer ; if ( isEnableRawEventInfo ) { final String logFileContent = new String ( LibraryUtils . toByteArray ( inputStream ) , StandardCharsets . UTF_8 ) ; final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( logFileContent ) ; serializer = new RawLogDeliveryEventSerializer ( logFileContent , ctLog , jsonParser ) ; } else { final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( inputStream ) ; serializer = new DefaultEventSerializer ( ctLog , jsonParser ) ; } return serializer ;


signature:
public class ExtPropertiesFileConfiguration { /** * { @ inheritDoc } */
@ Override public void validate ( ) { } }

implementation: LibraryUtils . checkArgumentNotNull ( this . getAwsCredentialsProvider ( ) , ERROR_CREDENTIALS_PROVIDER_NULL ) ; LibraryUtils . checkArgumentNotNull ( this . getSqsUrl ( ) , "SQS URL is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getSqsRegion ( ) , "SQS Region is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getVisibilityTimeout ( ) , "Visibility Timeout is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getS3Region ( ) , "S3 Region is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getThreadCount ( ) , "Thread Count is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getThreadTerminationDelaySeconds ( ) , "Thread Termination Delay Seconds is null." ) ; LibraryUtils . checkArgumentNotNull ( this . getMaxEventsPerEmit ( ) , "Maximum Events Per Emit is null." ) ; LibraryUtils . checkArgumentNotNull ( this . isEnableRawEventInfo ( ) , "Is Enable Raw Event Information is null." ) ;


signature:
public class RandomBeansExtension { /** * Does this extension support injection for parameters of the type described by the given { @ code
 * parameterContext } ?
 * @ param parameterContext the context for the parameter for which an argument should be resolved
 * @ param extensionContext the extension context for the { @ code Executable } about to be invoked
 * @ return true if the given { @ code parameterContext } is annotated with { @ link Random } , false
 * otherwise
 * @ throws ParameterResolutionException */
@ Override public boolean supportsParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { } }

implementation: return parameterContext . getParameter ( ) . getAnnotation ( Random . class ) != null ;


signature:
public class RandomBeansExtension { /** * Provides a value for any parameter context which has passed the { @ link
 * # supportsParameter ( ParameterContext , ExtensionContext ) } gate .
 * @ param parameterContext the context for the parameter for which an argument should be resolved
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ return a randomly generated object
 * @ throws ParameterResolutionException */
@ Override public Object resolveParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { } }

implementation: return resolve ( parameterContext . getParameter ( ) . getType ( ) , parameterContext . getParameter ( ) . getAnnotation ( Random . class ) ) ;


signature:
public class RandomBeansExtension { /** * Maps the ' random requirements ' expressed by the given { @ code annotation } to invocations on
 * { @ link # random } .
 * @ param targetType the type to be provided
 * @ param annotation an instance of { @ link Random } which describes how the user wishes to
 * configure the ' random generation '
 * @ return a randomly generated instance of { @ code targetType } */
private Object resolve ( Class < ? > targetType , Random annotation ) { } }

implementation: if ( targetType . isAssignableFrom ( List . class ) || targetType . isAssignableFrom ( Collection . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) . collect ( Collectors . toList ( ) ) ; } else if ( targetType . isAssignableFrom ( Set . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) . collect ( Collectors . toSet ( ) ) ; } else if ( targetType . isAssignableFrom ( Stream . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) ; } else { return random . nextObject ( targetType , annotation . excludes ( ) ) ; }


signature:
public class TemporaryFolder { /** * Create a file within the temporary folder root .
 * @ param fileName the name of the file to be created
 * @ return the newly created file instance
 * @ throws IOException in case the file creation call fails */
public File createFile ( String fileName ) throws IOException { } }

implementation: Path path = Paths . get ( rootFolder . getPath ( ) , fileName ) ; return Files . createFile ( path ) . toFile ( ) ;


signature:
public class TemporaryFolder { /** * Create a directory within the temporary folder root .
 * @ param directoryName the name of the directory to be created
 * @ return the directory instance */
public File createDirectory ( String directoryName ) { } }

implementation: Path path = Paths . get ( rootFolder . getPath ( ) , directoryName ) ; try { return Files . createDirectory ( path ) . toFile ( ) ; } catch ( IOException ex ) { throw new TemporaryFolderException ( String . format ( "Failed to create directory: '%s'" , path . toString ( ) ) , ex ) ; }


signature:
public class TemporaryFolder { /** * Deletes the { @ link # rootFolder } and all of its contents . This is package protected because a
 * { @ link TemporaryFolder } ' s lifecycle is expected to be controlled by its associated extension .
 * < p > < b > Note < / b > : any exception encountered during deletion will be swallowed . */
void destroy ( ) throws IOException { } }

implementation:
if ( rootFolder . exists ( ) ) { // walk the contents deleting each
Files . walkFileTree ( rootFolder . toPath ( ) , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attributes ) throws IOException { return delete ( file ) ; } @ Override public FileVisitResult postVisitDirectory ( Path directory , IOException exception ) throws IOException { return delete ( directory ) ; } @ SuppressWarnings ( "SameReturnValue" ) private FileVisitResult delete ( Path file ) throws IOException { Files . delete ( file ) ; return CONTINUE ; } } ) ; if ( rootFolder . exists ( ) ) { // delete the parent , if it still exists
Files . delete ( rootFolder . toPath ( ) ) ; } }


signature:
public class TemporaryFolderExtension { /** * Does this extension support injection for parameters of the type described by the given { @ code
 * parameterContext } ?
 * @ param parameterContext the context for the parameter for which an argument should be resolved
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ return true if the given { @ code parameterContext } describes a parameter of type : { @ link
 * TemporaryFolder } , false otherwise
 * @ throws ParameterResolutionException */
@ Override public boolean supportsParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { } }

implementation: return appliesTo ( parameterContext . getParameter ( ) . getType ( ) ) ;


signature:
public class TemporaryFolderExtension { /** * Provides a value for any parameter context which has passed the { @ link
 * # supportsParameter ( ParameterContext , ExtensionContext ) } gate .
 * @ param parameterContext the context for the parameter for which an argument should be resolved
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ return a new { @ link TemporaryFolder }
 * @ throws ParameterResolutionException */
@ Override public Object resolveParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { } }

implementation: return extensionContext . getStore ( NAMESPACE ) . getOrComputeIfAbsent ( parameterContext , key -> new TemporaryFolder ( ) , TemporaryFolder . class ) ;


signature:
public class ExpectedExceptionExtension { /** * Maps the expectations expressed in the given { @ code annotation } to a { @ link Predicate } .
 * @ param annotation encapsulates the callers ' expression of what ' s to be deemed an acceptable
 * exception
 * @ return a predicate which can be used to assess whether an exception matches the expectations
 * expressed in the given { @ code annotation } */
private Predicate < String > getPredicate ( ExpectedException annotation ) { } }

implementation:
if ( has ( annotation . messageStartsWith ( ) ) ) { return s -> s . startsWith ( annotation . messageStartsWith ( ) ) ; } else if ( has ( annotation . messageContains ( ) ) ) { return s -> s . contains ( annotation . messageContains ( ) ) ; } else if ( has ( annotation . messageIs ( ) ) ) { return s -> s . equals ( annotation . messageIs ( ) ) ; } else { // the default
return s -> true ; }


signature:
public class ExtensionUtil { /** * Creates a { @ link ExtensionContext . Store } for a given { @ code extensionContext } . A { @ link
 * ExtensionContext . Store } is bound to an { @ link ExtensionContext } so different test invocations
 * do not share the same store . For example a test invocation on { @ code ClassA . testMethodA } will
 * have a different { @ link ExtensionContext . Store } instance to that associated with a test
 * invocation on { @ code ClassA . testMethodB } or test invocation on { @ code ClassC . testMethodC } .
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ return a { @ link ExtensionContext . Store } for the given { @ code extensionContext } */
public static ExtensionContext . Store getStore ( ExtensionContext extensionContext , Class clazz ) { } }

implementation: return extensionContext . getStore ( namespace ( extensionContext , clazz ) ) ;


signature:
public class ExtensionUtil { /** * Creates a { @ link ExtensionContext . Namespace } in which extension state is stored on creation for
 * post execution destruction . Storing data in a custom namespace prevents accidental cross
 * pollination of data between extensions and between different invocations within the lifecycle
 * of a single extension .
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ return a { @ link ExtensionContext . Namespace } describing the scope for an extension */
private static ExtensionContext . Namespace namespace ( ExtensionContext extensionContext , Class clazz ) { } }

implementation: return ExtensionContext . Namespace . create ( clazz , extensionContext ) ;


signature:
public class SystemPropertyExtension { /** * If the current test class has a system property annotation ( s ) then create a { @ link
 * RestoreContext } representing the annotation ( s ) . This causes the requested system properties to
 * be set and retains a copy of pre - set values for reinstatement after test execution .
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ throws Exception */
@ Override public void beforeAll ( ExtensionContext extensionContext ) throws Exception { } }

implementation: List < SystemProperty > systemProperties = getSystemProperties ( extensionContext . getRequiredTestClass ( ) ) ; if ( ! systemProperties . isEmpty ( ) ) { RestoreContext . Builder builder = RestoreContext . createBuilder ( ) ; for ( SystemProperty systemProperty : systemProperties ) { builder . addPropertyName ( systemProperty . name ( ) ) ; if ( System . getProperty ( systemProperty . name ( ) ) != null ) { builder . addRestoreProperty ( systemProperty . name ( ) , System . getProperty ( systemProperty . name ( ) ) ) ; } set ( systemProperty ) ; } writeRestoreContext ( extensionContext , builder . build ( ) ) ; }


signature:
public class SystemPropertyExtension { /** * If a { @ link RestoreContext } exists for the given { @ code extensionContext } then restore it i . e .
 * unset any system properties which were set in { @ link # beforeAll ( ExtensionContext ) } for this
 * { @ code extensionContext } and reinstate original value , if applicable .
 * @ param extensionContext the < em > context < / em > in which the current test or container is being
 * executed
 * @ throws Exception */
@ Override public void afterAll ( ExtensionContext extensionContext ) throws Exception { } }

implementation: RestoreContext restoreContext = readRestoreContext ( extensionContext ) ; if ( restoreContext != null ) { restoreContext . restore ( ) ; }


signature:
public class SystemPropertyExtension { /** * Get a collection of { @ link SystemProperty } for the given { @ code annotatedElement } . If the given
 * { @ code annotatedElement } has no such annotations then an empty list is returned , if the given
 * { @ code annotatedElement } is annotated with { @ link SystemProperty } then a list with one element
 * is returned , if the given { @ code annotatedElement } is annotated with { @ link SystemProperties }
 * then a list with one element for each of the repeated { @ link SystemProperty } values is
 * returned .
 * < p > This is essentially a shortcut for logic such as : ' does this element have the { @ link
 * SystemProperty } annotation , if not does it have the { @ link SystemProperties } ' followed by
 * gathering these annotation values .
 * @ param annotatedElement either a test class or a test method which may be annotated with a
 * system property annotation
 * @ return 0 . . * { @ link SystemProperty } elements */
private List < SystemProperty > getSystemProperties ( AnnotatedElement annotatedElement ) { } }

implementation:
List < SystemProperty > systemProperties = new ArrayList < > ( ) ; if ( isAnnotated ( annotatedElement , SystemProperties . class ) ) { // gather the repeating system property values
systemProperties . addAll ( Arrays . asList ( annotatedElement . getAnnotation ( SystemProperties . class ) . value ( ) ) ) ; } if ( isAnnotated ( annotatedElement , SystemProperty . class ) ) { // add the single system property value
systemProperties . add ( annotatedElement . getAnnotation ( SystemProperty . class ) ) ; } return systemProperties ;


signature:
public class RestoreContext { /** * Reverse the system property ' sets ' performed on behalf of this restore context .
 * < p > For each entry in { @ link # propertyNames } , if { @ link # restoreProperties } contains an entry
 * then reset the system property with the value from { @ link # restoreProperties } otherwise just
 * remove the system property for that property name . */
public void restore ( ) { } }

implementation:
for ( String propertyName : propertyNames ) { if ( restoreProperties . containsKey ( propertyName ) ) { // reinstate the original value
System . setProperty ( propertyName , restoreProperties . get ( propertyName ) ) ; } else { // remove the ( previously unset ) property
System . clearProperty ( propertyName ) ; } }


signature: public class StreamUtils { public static Stream < JarEntry > asStream ( final JarInputStream pInputStream ) { } }

implementation: return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( new Iterator < JarEntry > ( ) { JarEntry entry = null ; public boolean hasNext ( ) { try { if ( entry == null ) { entry = pInputStream . getNextJarEntry ( ) ; } return entry != null ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public JarEntry next ( ) { try { JarEntry result = entry != null ? entry : pInputStream . getNextJarEntry ( ) ; entry = null ; return result ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } , Spliterator . IMMUTABLE ) , false ) ;


signature:
public class DependencyUtils { /** * public static Set < String > getDependenciesOfJar ( final InputStream pInputStream ) throws IOException {
 * final JarInputStream inputStream = new JarInputStream ( pInputStream ) ;
 * final NullOutputStream nullStream = new NullOutputStream ( ) ;
 * final Set < String > dependencies = new HashSet < String > ( ) ;
 * try {
 * while ( true ) {
 * final JarEntry entry = inputStream . getNextJarEntry ( ) ;
 * if ( entry = = null ) {
 * break ;
 * if ( entry . isDirectory ( ) ) {
 * ignore directory entries
 * IOUtils . copy ( inputStream , nullStream ) ;
 * continue ;
 * final String name = entry . getName ( ) ;
 * if ( name . endsWith ( " . class " ) ) {
 * final DependenciesClassAdapter v = new DependenciesClassAdapter ( ) ;
 * new ClassReader ( inputStream ) . accept ( v , 0 ) ;
 * dependencies . addAll ( v . getDependencies ( ) ) ;
 * } else {
 * IOUtils . copy ( inputStream , nullStream ) ;
 * } finally {
 * inputStream . close ( ) ;
 * return dependencies ; */
public static Set < String > getDependenciesOfClass ( final InputStream pInputStream ) throws IOException { } }

implementation: final DependenciesClassAdapter v = new DependenciesClassAdapter ( ) ; new ClassReader ( pInputStream ) . accept ( v , ClassReader . EXPAND_FRAMES ) ; final Set < String > depNames = v . getDependencies ( ) ; return depNames ;


signature:
public class RxActions { /** * _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / */
public static < T extends AbsListView > RxAction < T , String > setFilterText ( ) { } }

implementation: return new RxAction < T , String > ( ) { @ Override public void call ( T view , String filterText ) { if ( TextUtils . isEmpty ( filterText ) ) { view . clearTextFilter ( ) ; } else { view . setFilterText ( filterText ) ; } } } ;


signature:
public class RxActions { /** * _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / */
public static < T extends ImageView > RxAction < T , Integer > setImageLevel ( ) { } }

implementation: return new RxAction < T , Integer > ( ) { @ Override public void call ( T view , Integer level ) { view . setImageLevel ( level ) ; } } ;


signature:
public class RxActions { /** * _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / */
public static < T extends TextView > RxAction < T , Float > setTextSize ( ) { } }

implementation: return new RxAction < T , Float > ( ) { @ Override public void call ( T view , Float size ) { view . setTextSize ( TypedValue . COMPLEX_UNIT_SP , size ) ; } } ;


signature:
public class RxActions { /** * _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / _ _ / */
public static < T extends View > RxAction < T , Integer > setBackgroundColor ( ) { } }

implementation: return new RxAction < T , Integer > ( ) { @ Override public void call ( T view , Integer color ) { view . setBackgroundColor ( color ) ; } } ;


signature:
public class LazyMap { /** * Create the map implementation
 * @ return the map */
private Map < K , V > createImplementation ( ) { } }

implementation: if ( delegate instanceof HashMap == false ) return new HashMap < K , V > ( delegate ) ; return delegate ;


signature:
public class CachedCollection { /** * Add an object to the collection .
 * @ param obj Object ( or < i > null < / i > to add to the collection .
 * @ return True if object was added . */
public boolean add ( final Object obj ) { } }

implementation: maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; return collection . add ( soft ) ;


signature:
public class SoftObject { /** * Create a < tt > SoftObject < / tt > for the given object .
 * @ param obj Object to reference .
 * @ param queue Reference queue .
 * @ return < tt > SoftObject < / tt > or < tt > null < / tt > if object is null . */
public static SoftObject create ( final Object obj , final ReferenceQueue queue ) { } }

implementation: if ( obj == null ) return null ; else return new SoftObject ( obj , queue ) ;


signature:
public class Property { /** * Set a property
 * @ param name Property name
 * @ param value Property value
 * @ return Previous property value or null */
public static String set ( String name , String value ) { } }

implementation: return PropertyManager . setProperty ( name , value ) ;


signature:
public class Property { /** * Get a property
 * @ param name Property name
 * @ param defaultValue Default property value
 * @ return Property value or default */
public static String get ( String name , String defaultValue ) { } }

implementation: return PropertyManager . getProperty ( name , defaultValue ) ;


signature:
public class Property { /** * Get an array style property
 * @ param base Base property name
 * @ param defaultValues Default property values
 * @ return Array of property values or default */
public static String [ ] getArray ( String base , String [ ] defaultValues ) { } }

implementation: return PropertyManager . getArrayProperty ( base , defaultValues ) ;


signature:
public class StateMachine { /** * Transition to the next state given the name of a valid transition .
 * @ param actionName - the name of transition that is valid for the
 * current state .
 * @ return the next state
 * @ throws IllegalTransitionException */
public State nextState ( String actionName ) throws IllegalTransitionException { } }

implementation: Transition t = currentState . getTransition ( actionName ) ; if ( t == null ) { String msg = "No transition for action: '" + actionName + "' from state: '" + currentState . getName ( ) + "'" ; throw new IllegalTransitionException ( msg ) ; } State nextState = t . getTarget ( ) ; log . trace ( "nextState(" + actionName + ") = " + nextState ) ; currentState = nextState ; return currentState ;


signature:
public class SoftSet { /** * Iterate through the gcqueue for for any cleared reference , remove
 * the associated value from the underlying set . */
private void processQueue ( ) { } }

implementation: ComparableSoftReference cr ; while ( ( cr = ( ComparableSoftReference ) gcqueue . poll ( ) ) != null ) { map . remove ( cr . getKey ( ) ) ; }


signature:
public class WeakTypeCache { /** * Get the information for a type
 * @ param type the type
 * @ return the info */
@ SuppressWarnings ( { } }

implementation:
"unchecked" , "cast" } ) public T get ( Type type ) { if ( type == null ) throw new IllegalArgumentException ( "Null type" ) ; if ( type instanceof ParameterizedType ) return getParameterizedType ( ( ParameterizedType ) type ) ; else if ( type instanceof Class ) return getClass ( ( Class < ? > ) type ) ; else if ( type instanceof TypeVariable ) // TODO Figure out why we need this cast with the Sun compiler ?
return ( T ) getTypeVariable ( ( TypeVariable ) type ) ; else if ( type instanceof GenericArrayType ) return getGenericArrayType ( ( GenericArrayType ) type ) ; else if ( type instanceof WildcardType ) return getWildcardType ( ( WildcardType ) type ) ; else throw new UnsupportedOperationException ( "Unknown type: " + type + " class=" + type . getClass ( ) ) ;


signature:
public class WeakTypeCache { /** * Get the information for a class
 * @ param name the name
 * @ param cl the classloader
 * @ return the info
 * @ throws ClassNotFoundException when the class cannot be found */
public T get ( String name , ClassLoader cl ) throws ClassNotFoundException { } }

implementation: if ( name == null ) throw new IllegalArgumentException ( "Null name" ) ; if ( cl == null ) throw new IllegalArgumentException ( "Null classloader" ) ; Class < ? > clazz = cl . loadClass ( name ) ; return get ( clazz ) ;


signature:
public class WeakTypeCache { /** * Get the information for a parameterized type
 * @ param type the parameterized type
 * @ return the info */
protected T getParameterizedType ( ParameterizedType type ) { } }

implementation:
// First check if we already have it
T result = peek ( type ) ; if ( result != null ) return result ; // Instantiate
result = instantiate ( type ) ; // Put the perlimanary result into the cache
put ( type , result ) ; // Generate the details
generate ( type , result ) ; return result ;


signature:
public class WeakTypeCache { /** * Get the information for a type variable
 * @ param < D > the declaration
 * @ param type the type variable
 * @ return the info */
protected < D extends GenericDeclaration > T getTypeVariable ( TypeVariable < D > type ) { } }

implementation:
// TODO JBMICROCONT - 131 improve this
return get ( type . getBounds ( ) [ 0 ] ) ;


signature:
public class WeakTypeCache { /** * Peek into the cache
 * @ param type the type
 * @ return the value */
protected T peek ( ParameterizedType type ) { } }

implementation: Class < ? > rawType = ( Class < ? > ) type . getRawType ( ) ; ClassLoader cl = SecurityActions . getClassLoader ( rawType ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { return classLoaderCache . get ( type . toString ( ) ) ; }


signature:
public class WeakTypeCache { /** * Put a result into the cache
 * @ param type the type
 * @ param result the value */
protected void put ( ParameterizedType type , T result ) { } }

implementation:
Class < ? > rawType = ( Class < ? > ) type . getRawType ( ) ; ClassLoader cl = SecurityActions . getClassLoader ( rawType ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { // TODO JBMICROCONT - 131 something better than toString ( ) ?
classLoaderCache . put ( type . toString ( ) , result ) ; }


signature:
public class WeakTypeCache { /** * Get the information for a class
 * @ param clazz the class
 * @ return the info */
protected T getClass ( Class < ? > clazz ) { } }

implementation:
// First check if we already have it
T result = peek ( clazz ) ; if ( result != null ) return result ; // Instantiate
result = instantiate ( clazz ) ; // Put the preliminary result into the cache
put ( clazz , result ) ; // Generate the details
generate ( clazz , result ) ; return result ;


signature:
public class WeakTypeCache { /** * Peek into the cache
 * @ param clazz the class
 * @ return the value */
protected T peek ( Class < ? > clazz ) { } }

implementation: ClassLoader cl = SecurityActions . getClassLoader ( clazz ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { return classLoaderCache . get ( clazz . getName ( ) ) ; }


signature:
public class WeakTypeCache { /** * Put a result into the cache
 * @ param clazz the class
 * @ param result the value */
protected void put ( Class < ? > clazz , T result ) { } }

implementation: ClassLoader cl = SecurityActions . getClassLoader ( clazz ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { classLoaderCache . put ( clazz . getName ( ) , result ) ; }


signature:
public class WeakTypeCache { /** * Get the cache for the classloader
 * @ param cl the classloader
 * @ return the map */
protected Map < String , T > getClassLoaderCache ( ClassLoader cl ) { } }

implementation: synchronized ( cache ) { Map < String , T > result = cache . get ( cl ) ; if ( result == null ) { result = new WeakValueHashMap < String , T > ( ) ; cache . put ( cl , result ) ; } return result ; }


signature:
public class NestedRuntimeException { /** * Prints the composite message and the embedded stack trace to the
 * specified print stream .
 * @ param stream Stream to print to . */
public void printStackTrace ( final PrintStream stream ) { } }

implementation: if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( stream ) ; } NestedThrowable . Util . print ( nested , stream ) ;


signature:
public class NestedRuntimeException { /** * Prints the composite message and the embedded stack trace to the
 * specified print writer .
 * @ param writer Writer to print to . */
public void printStackTrace ( final PrintWriter writer ) { } }

implementation: if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( writer ) ; } NestedThrowable . Util . print ( nested , writer ) ;


signature:
public class ClassArrayEditor { /** * Build a Class [ ] from a comma / whitespace seperated list of classes
 * @ param text - the class name list */
public void setAsText ( final String text ) throws IllegalArgumentException { } }

implementation: ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; StringTokenizer tokenizer = new StringTokenizer ( text , ", \t\r\n" ) ; ArrayList < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; while ( tokenizer . hasMoreTokens ( ) == true ) { String name = tokenizer . nextToken ( ) ; try { Class < ? > c = loader . loadClass ( name ) ; classes . add ( c ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( "Failed to find class: " + name ) ; } } Class < ? > [ ] theValue = new Class [ classes . size ( ) ] ; classes . toArray ( theValue ) ; setValue ( theValue ) ;


signature:
public class MarshalledValueOutputStream { /** * Override replaceObject to check for Remote objects that are
 * not RemoteStubs . */
protected Object replaceObject ( Object obj ) throws IOException { } }

implementation:
if ( ( obj instanceof Remote ) && ! ( obj instanceof RemoteStub ) ) { Remote remote = ( Remote ) obj ; try { obj = RemoteObject . toStub ( remote ) ; } catch ( IOException ignore ) { // Let the Serialization layer try with the orignal obj
} } return obj ;


signature:
public class BasicTaskWrapper { /** * Called by the thread pool executor */
public void run ( ) { } }

implementation:
// Get the execution thread
this . runThread = Thread . currentThread ( ) ; // Check for a start timeout
long runTime = getElapsedTime ( ) ; if ( startTimeout > 0l && runTime >= startTimeout ) { taskRejected ( new StartTimeoutException ( "Start Timeout exceeded for task " + taskString ) ) ; return ; } // We are about to start , check for a stop
boolean stopped = false ; synchronized ( stateLock ) { if ( state == TASK_STOPPED ) { stopped = true ; } else { state = TASK_STARTED ; taskStarted ( ) ; if ( waitType == Task . WAIT_FOR_START ) stateLock . notifyAll ( ) ; } } if ( stopped ) { taskRejected ( new TaskStoppedException ( "Task stopped for task " + taskString ) ) ; return ; } // Run the task
Throwable throwable = null ; try { task . execute ( ) ; } catch ( Throwable t ) { throwable = t ; } // It is complete
taskCompleted ( throwable ) ; // We are completed
synchronized ( stateLock ) { state = TASK_COMPLETED ; if ( waitType == Task . WAIT_FOR_COMPLETE ) stateLock . notifyAll ( ) ; }


signature:
public class BasicTaskWrapper { /** * Set thetask for this wrapper
 * @ param task the task */
protected void setTask ( Task task ) { } }

implementation: if ( task == null ) throw new IllegalArgumentException ( "Null task" ) ; this . task = task ; this . taskString = task . toString ( ) ; this . startTime = System . currentTimeMillis ( ) ; this . waitType = task . getWaitType ( ) ; this . priority = task . getPriority ( ) ; this . startTimeout = task . getStartTimeout ( ) ; this . completionTimeout = task . getCompletionTimeout ( ) ;


signature:
public class BasicTaskWrapper { /** * Notify the task it has been accepted
 * @ return true when the notification succeeds , false otherwise */
protected boolean taskAccepted ( ) { } }

implementation: try { task . accepted ( getElapsedTime ( ) ) ; return true ; } catch ( Throwable t ) { log . warn ( "Unexpected error during 'accepted' for task: " + taskString , t ) ; return false ; }


signature:
public class BasicTaskWrapper { /** * Notify the task it has been rejected
 * @ param e any error associated with the rejection
 * @ return true when the notification succeeds , false otherwise */
protected boolean taskRejected ( RuntimeException e ) { } }

implementation: try { task . rejected ( getElapsedTime ( ) , e ) ; return true ; } catch ( Throwable t ) { log . warn ( "Unexpected error during 'rejected' for task: " + taskString , t ) ; if ( e != null ) log . warn ( "Original reason for rejection of task: " + taskString , e ) ; return false ; }


signature:
public class BasicTaskWrapper { /** * Notify the task it has started
 * @ return true when the notification succeeds , false otherwise */
protected boolean taskStarted ( ) { } }

implementation: try { task . started ( getElapsedTime ( ) ) ; return true ; } catch ( Throwable t ) { log . warn ( "Unexpected error during 'started' for task: " + taskString , t ) ; return false ; }


signature:
public class BasicTaskWrapper { /** * Notify the task it has completed
 * @ param throwable any throwable associated with the completion
 * @ return true when the notification succeeds , false otherwise */
protected boolean taskCompleted ( Throwable throwable ) { } }

implementation: try { task . completed ( getElapsedTime ( ) , throwable ) ; return true ; } catch ( Throwable t ) { log . warn ( "Unexpected error during 'completed' for task: " + taskString , t ) ; if ( throwable != null ) log . warn ( "Original error during 'run' for task: " + taskString , throwable ) ; return false ; }


signature:
public class BasicTaskWrapper { /** * Stop the task
 * @ return true when the notification succeeds , false otherwise */
protected boolean taskStop ( ) { } }

implementation: try { task . stop ( ) ; return true ; } catch ( Throwable t ) { log . warn ( "Unexpected error during 'stop' for task: " + taskString , t ) ; return false ; }


signature:
public class WorkerQueue { /** * Called by a thread that is not the WorkerQueue thread , this method
 * queues the job and , if necessary , wakes up this worker queue that is
 * waiting in { @ link # getJob } .
 * @ param job */
public synchronized void putJob ( Executable job ) { } }

implementation:
// Preconditions
if ( m_queueThread == null || ! m_queueThread . isAlive ( ) ) { throw new IllegalStateException ( "Can't put job, thread is not alive or not present" ) ; } if ( isInterrupted ( ) ) { throw new IllegalStateException ( "Can't put job, thread was interrupted" ) ; } putJobImpl ( job ) ;


signature:
public class WorkerQueue { /** * Never call this method , only override in subclasses to perform
 * job getting in a specific way , normally tied to the data structure
 * holding the jobs .
 * @ return the exectuable
 * @ throws InterruptedException */
protected Executable getJobImpl ( ) throws InterruptedException { } }

implementation:
// While the queue is empty , wait ( ) ;
// when notified take an event from the queue and return it .
while ( m_currentJob == null ) { wait ( ) ; } // This one is the job to return
JobItem item = m_currentJob ; // Go on to the next object for the next call .
m_currentJob = m_currentJob . m_next ; return item . m_job ;


signature:
public class WorkerQueue { /** * Never call this method , only override in subclasses to perform
 * job adding in a specific way , normally tied to the data structure
 * holding the jobs .
 * @ param job */
protected void putJobImpl ( Executable job ) { } }

implementation:
JobItem posted = new JobItem ( job ) ; if ( m_currentJob == null ) { // The queue is empty , set the current job to process and
// wake up the thread waiting in method getJob
m_currentJob = posted ; notifyAll ( ) ; } else { JobItem item = m_currentJob ; // The queue is not empty , find the end of the queue ad add the
// posted job at the end
while ( item . m_next != null ) { item = item . m_next ; } item . m_next = posted ; }


signature:
public class BlockingMode { /** * A utility method to convert a string name to a BlockingMode
 * @ param name
 * @ return The associated BlockingMode constant if name is valid , null otherwise */
public static final BlockingMode toBlockingMode ( String name ) { } }

implementation: BlockingMode mode = null ; if ( name == null ) { mode = null ; } else if ( name . equalsIgnoreCase ( "run" ) ) { mode = RUN ; } else if ( name . equalsIgnoreCase ( "wait" ) ) { mode = WAIT ; } else if ( name . equalsIgnoreCase ( "discard" ) ) { mode = DISCARD ; } else if ( name . equalsIgnoreCase ( "discardOldest" ) ) { mode = DISCARD_OLDEST ; } else if ( name . equalsIgnoreCase ( "abort" ) ) { mode = ABORT ; } return mode ;


signature:
public class BlockingMode { /** * Overriden to return the indentity instance of BlockingMode based on the
 * stream type int value . This ensures that BlockingMode enums can be
 * compared using = = .
 * @ return The BlockingMode instance for the XXX _ TYPE int .
 * @ throws ObjectStreamException */
Object readResolve ( ) throws ObjectStreamException { } }

implementation:
// Replace the marshalled instance type with the local instance
BlockingMode mode = ABORT ; switch ( type ) { case RUN_TYPE : mode = RUN ; break ; case WAIT_TYPE : mode = RUN ; break ; case DISCARD_TYPE : mode = RUN ; break ; case DISCARD_OLDEST_TYPE : mode = RUN ; break ; case ABORT_TYPE : mode = RUN ; break ; } return mode ;


signature:
public class WeakObject { /** * Create a < tt > WeakObject < / tt > for the given object .
 * @ param obj Object to reference .
 * @ param queue Reference queue .
 * @ return < tt > WeakObject < / tt > or < tt > null < / tt > if object is null . */
public static WeakObject create ( final Object obj , final ReferenceQueue queue ) { } }

implementation: if ( obj == null ) return null ; else return new WeakObject ( obj , queue ) ;


signature:
public class FileURLLister { /** * Public - - - - - */
public Collection listMembers ( URL baseUrl , URLFilter filter ) throws IOException { } }

implementation: return listMembers ( baseUrl , filter , false ) ;


signature:
public class FileURLLister { /** * Starting from baseUrl , that should point to a directory , populate the
 * resultList with the contents that pass the filter ( in the form of URLs )
 * and possibly recurse into subdris not containing a ' . ' in their name . */
private void listFiles ( final URL baseUrl , final URLFilter filter , boolean scanNonDottedSubDirs , ArrayList < URL > resultList ) throws IOException { } }

implementation:
// List the files at the current dir level , using the provided filter
final File baseDir = new File ( baseUrl . getPath ( ) ) ; String [ ] filenames = baseDir . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { try { return filter . accept ( baseUrl , name ) ; } catch ( Exception e ) { log . debug ( "Unexpected exception filtering entry '" + name + "' in directory '" + baseDir + "'" , e ) ; return true ; } } } ) ; if ( filenames == null ) { // This happens only when baseDir not a directory ( but this is already
// checked by the caller ) or some unknown IOException happens internally
// ( e . g . run out of file descriptors ? ) . Unfortunately the File API
// doesn ' t provide a way to know .
throw new IOException ( "Could not list directory '" + baseDir + "', reason unknown" ) ; } else { String baseUrlString = baseUrl . toString ( ) ; for ( int i = 0 ; i < filenames . length ; i ++ ) { String filename = filenames [ i ] ; // Find out if this is a directory
File file = new File ( baseDir , filename ) ; boolean isDir = file . isDirectory ( ) ; // The subUrl
URL subUrl = createURL ( baseUrlString , filename , isDir ) ; // If scanning subdirs and we have a directory , not containing a ' . ' in
// the name , recurse into it . This is to allow recursing into grouping
// dirs like . / deploy / jms , . / deploy / management , etc . , avoiding
// at the same time exploded packages , like . sar , . war , etc .
if ( scanNonDottedSubDirs && isDir && ( filename . indexOf ( '.' ) == - 1 ) ) { // recurse into it
listFiles ( subUrl , filter , scanNonDottedSubDirs , resultList ) ; } else { // just add to the list
resultList . add ( subUrl ) ; } } }


signature:
public class FileURLLister { /** * Create a URL by concatenating the baseUrlString that should end at ' / ' ,
 * the filename , and a trailing slash , if it points to a directory */
private URL createURL ( String baseUrlString , String filename , boolean isDirectory ) { } }

implementation:
try { return new URL ( baseUrlString + filename + ( isDirectory ? "/" : "" ) ) ; } catch ( MalformedURLException e ) { // shouldn ' t happen
throw new IllegalStateException ( ) ; }


signature:
public class Catalog { /** * Setup readers . */
public void setupReaders ( ) { } }

implementation: SAXParserFactory spf = SAXParserFactory . newInstance ( ) ; spf . setNamespaceAware ( true ) ; spf . setValidating ( false ) ; SAXCatalogReader saxReader = new SAXCatalogReader ( spf ) ; saxReader . setCatalogParser ( null , "XMLCatalog" , "org.apache.xml.resolver.readers.XCatalogReader" ) ; saxReader . setCatalogParser ( OASISXMLCatalogReader . namespaceName , "catalog" , "org.apache.xml.resolver.readers.OASISXMLCatalogReader" ) ; addReader ( "application/xml" , saxReader ) ; TR9401CatalogReader textReader = new TR9401CatalogReader ( ) ; addReader ( "text/plain" , textReader ) ;


signature:
public class Catalog { /** * Add a new CatalogReader to the Catalog .
 * < p > This method allows you to add a new CatalogReader to the
 * catalog . The reader will be associated with the specified mimeType .
 * You can only have one reader per mimeType . < / p >
 * < p > In the absence of a mimeType ( e . g . , when reading a catalog
 * directly from a file on the local system ) , the readers are attempted
 * in the order that you add them to the Catalog . < / p >
 * < p > Note that subordinate catalogs ( created by CATALOG or
 * DELEGATE * entries ) get a copy of the set of readers present in
 * the primary catalog when they are created . Readers added subsequently
 * will not be available . For this reason , it is best to add all
 * of the readers before the first call to parse a catalog . < / p >
 * @ param mimeType The MIME type associated with this reader .
 * @ param reader The CatalogReader to use . */
public void addReader ( String mimeType , CatalogReader reader ) { } }

implementation: if ( readerMap . containsKey ( mimeType ) ) { Integer pos = ( Integer ) readerMap . get ( mimeType ) ; readerArr . set ( pos . intValue ( ) , reader ) ; } else { readerArr . add ( reader ) ; Integer pos = new Integer ( readerArr . size ( ) - 1 ) ; readerMap . put ( mimeType , pos ) ; }


signature:
public class Catalog { /** * Copies the reader list from the current Catalog to a new Catalog .
 * < p > This method is used internally when constructing a new catalog .
 * It copies the current reader associations over to the new catalog .
 * @ param newCatalog The new Catalog . */
protected void copyReaders ( Catalog newCatalog ) { } }

implementation:
// Have to copy the readers in the right order . . . convert hash to arr
Vector mapArr = new Vector ( readerMap . size ( ) ) ; // Pad the mapArr out to the right length
for ( int count = 0 ; count < readerMap . size ( ) ; count ++ ) { mapArr . add ( null ) ; } Enumeration enumt = readerMap . keys ( ) ; while ( enumt . hasMoreElements ( ) ) { String mimeType = ( String ) enumt . nextElement ( ) ; Integer pos = ( Integer ) readerMap . get ( mimeType ) ; mapArr . set ( pos . intValue ( ) , mimeType ) ; } for ( int count = 0 ; count < mapArr . size ( ) ; count ++ ) { String mimeType = ( String ) mapArr . get ( count ) ; Integer pos = ( Integer ) readerMap . get ( mimeType ) ; newCatalog . addReader ( mimeType , ( CatalogReader ) readerArr . get ( pos . intValue ( ) ) ) ; }


signature:
public class Catalog { /** * Create a new Catalog object .
 * < p > This method constructs a new instance of the running Catalog
 * class ( which might be a subtype of org . apache . xml . resolver . Catalog ) .
 * All new catalogs are managed by the same CatalogManager .
 * < p > N . B . All Catalog subtypes should call newCatalog ( ) to construct
 * a new Catalog . Do not simply use " new Subclass ( ) " since that will
 * confuse future subclasses . < / p >
 * @ return the catalog */
protected Catalog newCatalog ( ) { } }

implementation: String catalogClass = this . getClass ( ) . getName ( ) ; try { Catalog c = ( Catalog ) ( Class . forName ( catalogClass ) . newInstance ( ) ) ; c . setCatalogManager ( catalogManager ) ; copyReaders ( c ) ; return c ; } catch ( ClassNotFoundException cnfe ) { catalogManager . debug . message ( 1 , "Class Not Found Exception: " + catalogClass ) ; } catch ( IllegalAccessException iae ) { catalogManager . debug . message ( 1 , "Illegal Access Exception: " + catalogClass ) ; } catch ( InstantiationException ie ) { catalogManager . debug . message ( 1 , "Instantiation Exception: " + catalogClass ) ; } catch ( ClassCastException cce ) { catalogManager . debug . message ( 1 , "Class Cast Exception: " + catalogClass ) ; } catch ( Exception e ) { catalogManager . debug . message ( 1 , "Other Exception: " + catalogClass ) ; } Catalog c = new Catalog ( ) ; c . setCatalogManager ( catalogManager ) ; copyReaders ( c ) ; return c ;


signature:
public class Catalog { /** * Load the system catalog files .
 * < p > The method adds all of the
 * catalogs specified in the < tt > xml . catalog . files < / tt > property
 * to the Catalog list . < / p >
 * @ throws MalformedURLException One of the system catalogs is
 * identified with a filename that is not a valid URL .
 * @ throws IOException One of the system catalogs cannot be read . */
public void loadSystemCatalogs ( ) throws MalformedURLException , IOException { } }

implementation:
Vector catalogs = catalogManager . getCatalogFiles ( ) ; if ( catalogs != null ) { for ( int count = 0 ; count < catalogs . size ( ) ; count ++ ) { catalogFiles . addElement ( catalogs . elementAt ( count ) ) ; } } if ( catalogFiles . size ( ) > 0 ) { // This is a little odd . The parseCatalog ( ) method expects
// a filename , but it adds that name to the end of the
// catalogFiles vector , and then processes that vector .
// This allows the system to handle CATALOG entries
// correctly .
// In this init case , we take the last element off the
// catalogFiles vector and pass it to parseCatalog . This
// will " do the right thing " in the init case , and allow
// parseCatalog ( ) to do the right thing in the non - init
// case . Honest .
String catfile = ( String ) catalogFiles . lastElement ( ) ; catalogFiles . removeElement ( catfile ) ; parseCatalog ( catfile ) ; }


signature:
public class Catalog { /** * Parse a catalog file , augmenting internal data structures .
 * @ param fileName The filename of the catalog file to process
 * @ throws MalformedURLException The fileName cannot be turned into
 * a valid URL .
 * @ throws IOException Error reading catalog file . */
public synchronized void parseCatalog ( String fileName ) throws MalformedURLException , IOException { } }

implementation:
default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , "Parse catalog: " + fileName ) ; // Put the file into the list of catalogs to process . . .
// In all cases except the case when initCatalog ( ) is the
// caller , this will be the only catalog initially in the list . . .
catalogFiles . addElement ( fileName ) ; // Now process all the pending catalogs . . .
parsePendingCatalogs ( ) ;


signature:
public class Catalog { /** * Parse a catalog file , augmenting internal data structures .
 * < p > Catalogs retrieved over the net may have an associated MIME type .
 * The MIME type can be used to select an appropriate reader . < / p >
 * @ param mimeType The MIME type of the catalog file .
 * @ param is The InputStream from which the catalog should be read
 * @ throws CatalogException Failed to load catalog
 * mimeType .
 * @ throws IOException Error reading catalog file . */
public synchronized void parseCatalog ( String mimeType , InputStream is ) throws IOException , CatalogException { } }

implementation:
default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , "Parse " + mimeType + " catalog on input stream" ) ; CatalogReader reader = null ; if ( readerMap . containsKey ( mimeType ) ) { int arrayPos = ( ( Integer ) readerMap . get ( mimeType ) ) . intValue ( ) ; reader = ( CatalogReader ) readerArr . get ( arrayPos ) ; } if ( reader == null ) { String msg = "No CatalogReader for MIME type: " + mimeType ; catalogManager . debug . message ( 2 , msg ) ; throw new CatalogException ( CatalogException . UNPARSEABLE , msg ) ; } reader . readCatalog ( this , is ) ; // Now process all the pending catalogs . . .
parsePendingCatalogs ( ) ;


signature:
public class Catalog { /** * Parse a catalog document , augmenting internal data structures .
 * < p > This method supports catalog files stored in jar files : e . g . ,
 * jar : file : / / / path / to / filename . jar ! / path / to / catalog . xml " . That URI
 * doesn ' t survive transmogrification through the URI processing that
 * the parseCatalog ( String ) performs and passing it as an input stream
 * doesn ' t set the base URI appropriately . < / p >
 * < p > Written by Stefan Wachter ( 2002-09-26 ) < / p >
 * @ param aUrl The URL of the catalog document to process
 * @ throws IOException Error reading catalog file . */
public synchronized void parseCatalog ( URL aUrl ) throws IOException { } }

implementation:
catalogCwd = aUrl ; base = aUrl ; default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , "Parse catalog: " + aUrl . toString ( ) ) ; DataInputStream inStream = null ; boolean parsed = false ; for ( int count = 0 ; ! parsed && count < readerArr . size ( ) ; count ++ ) { CatalogReader reader = ( CatalogReader ) readerArr . get ( count ) ; try { inStream = new DataInputStream ( aUrl . openStream ( ) ) ; } catch ( FileNotFoundException fnfe ) { // No catalog ; give up !
break ; } try { reader . readCatalog ( this , inStream ) ; parsed = true ; } catch ( CatalogException ce ) { if ( ce . getExceptionType ( ) == CatalogException . PARSE_FAILED ) { // give up !
break ; } else { // try again !
} } try { inStream . close ( ) ; } catch ( IOException e ) { // nop
} } if ( parsed ) parsePendingCatalogs ( ) ;


signature:
public class Catalog { /** * Parse all of the pending catalogs .
 * < p > Catalogs may refer to other catalogs , this method parses
 * all of the currently pending catalog files . < / p >
 * @ throws MalformedURLException
 * @ throws IOException */
protected synchronized void parsePendingCatalogs ( ) throws MalformedURLException , IOException { } }

implementation:
if ( ! localCatalogFiles . isEmpty ( ) ) { // Move all the localCatalogFiles into the front of
// the catalogFiles queue
Vector newQueue = new Vector ( ) ; Enumeration q = localCatalogFiles . elements ( ) ; while ( q . hasMoreElements ( ) ) { newQueue . addElement ( q . nextElement ( ) ) ; } // Put the rest of the catalogs on the end of the new list
for ( int curCat = 0 ; curCat < catalogFiles . size ( ) ; curCat ++ ) { String catfile = ( String ) catalogFiles . elementAt ( curCat ) ; newQueue . addElement ( catfile ) ; } catalogFiles = newQueue ; localCatalogFiles . clear ( ) ; } // Suppose there are no catalog files to process , but the
// single catalog already parsed included some delegate
// entries ? Make sure they don ' t get lost .
if ( catalogFiles . isEmpty ( ) && ! localDelegate . isEmpty ( ) ) { Enumeration e = localDelegate . elements ( ) ; while ( e . hasMoreElements ( ) ) { catalogEntries . addElement ( e . nextElement ( ) ) ; } localDelegate . clear ( ) ; } // Now process all the files on the catalogFiles vector . This
// vector can grow during processing if CATALOG entries are
// encountered in the catalog
while ( ! catalogFiles . isEmpty ( ) ) { String catfile = ( String ) catalogFiles . elementAt ( 0 ) ; try { catalogFiles . remove ( 0 ) ; } catch ( ArrayIndexOutOfBoundsException e ) { // can ' t happen
} if ( catalogEntries . size ( ) == 0 && catalogs . size ( ) == 0 ) { // We haven ' t parsed any catalogs yet , let this
// catalog be the first . . .
try { parseCatalogFile ( catfile ) ; } catch ( CatalogException ce ) { System . out . println ( "FIXME: " + ce . toString ( ) ) ; } } else { // This is a subordinate catalog . We save its name ,
// but don ' t bother to load it unless it ' s necessary .
catalogs . addElement ( catfile ) ; } if ( ! localCatalogFiles . isEmpty ( ) ) { // Move all the localCatalogFiles into the front of
// the catalogFiles queue
Vector newQueue = new Vector ( ) ; Enumeration q = localCatalogFiles . elements ( ) ; while ( q . hasMoreElements ( ) ) { newQueue . addElement ( q . nextElement ( ) ) ; } // Put the rest of the catalogs on the end of the new list
for ( int curCat = 0 ; curCat < catalogFiles . size ( ) ; curCat ++ ) { catfile = ( String ) catalogFiles . elementAt ( curCat ) ; newQueue . addElement ( catfile ) ; } catalogFiles = newQueue ; localCatalogFiles . clear ( ) ; } if ( ! localDelegate . isEmpty ( ) ) { Enumeration e = localDelegate . elements ( ) ; while ( e . hasMoreElements ( ) ) { catalogEntries . addElement ( e . nextElement ( ) ) ; } localDelegate . clear ( ) ; } } // We ' ve parsed them all , reinit the vector . . .
catalogFiles . clear ( ) ;


signature:
public class Catalog { /** * Parse a single catalog file , augmenting internal data structures .
 * @ param fileName The filename of the catalog file to process
 * @ throws MalformedURLException The fileName cannot be turned into
 * a valid URL .
 * @ throws IOException Error reading catalog file .
 * @ throws CatalogException for any error */
protected synchronized void parseCatalogFile ( String fileName ) throws MalformedURLException , IOException , CatalogException { } }

implementation:
// The base - base is the cwd . If the catalog file is specified
// with a relative path , this assures that it gets resolved
// properly . . .
try { // tack on a basename because URLs point to files not dirs
String userdir = fixSlashes ( System . getProperty ( "user.dir" ) ) ; catalogCwd = new URL ( "file:" + userdir + "/basename" ) ; } catch ( MalformedURLException e ) { String userdir = fixSlashes ( System . getProperty ( "user.dir" ) ) ; catalogManager . debug . message ( 1 , "Malformed URL on cwd" , userdir ) ; catalogCwd = null ; } // The initial base URI is the location of the catalog file
try { base = new URL ( catalogCwd , fixSlashes ( fileName ) ) ; } catch ( MalformedURLException e ) { try { base = new URL ( "file:" + fixSlashes ( fileName ) ) ; } catch ( MalformedURLException e2 ) { catalogManager . debug . message ( 1 , "Malformed URL on catalog filename" , fixSlashes ( fileName ) ) ; base = null ; } } catalogManager . debug . message ( 2 , "Loading catalog" , fileName ) ; catalogManager . debug . message ( 4 , "Default BASE" , base . toString ( ) ) ; fileName = base . toString ( ) ; DataInputStream inStream = null ; boolean parsed = false ; boolean notFound = false ; for ( int count = 0 ; ! parsed && count < readerArr . size ( ) ; count ++ ) { CatalogReader reader = ( CatalogReader ) readerArr . get ( count ) ; try { notFound = false ; inStream = new DataInputStream ( base . openStream ( ) ) ; } catch ( FileNotFoundException fnfe ) { // No catalog ; give up !
notFound = true ; break ; } try { reader . readCatalog ( this , inStream ) ; parsed = true ; } catch ( CatalogException ce ) { if ( ce . getExceptionType ( ) == CatalogException . PARSE_FAILED ) { // give up !
break ; } else { // try again !
} } try { inStream . close ( ) ; } catch ( IOException e ) { // nop
} } if ( ! parsed ) { if ( notFound ) { catalogManager . debug . message ( 3 , "Catalog does not exist" , fileName ) ; } else { catalogManager . debug . message ( 1 , "Failed to parse catalog" , fileName ) ; } }