signature:
public class ServiceComponentImpl { /** * Retrieves the set of ra entity links referenced by the sbbs related with the service .
 * @ param componentRepository
 * @ return */
public Set < String > getResourceAdaptorEntityLinks ( ComponentRepository componentRepository ) { } }

implementation: Set < String > result = new HashSet < String > ( ) ; for ( SbbID sbbID : getSbbIDs ( componentRepository ) ) { SbbComponent sbbComponent = componentRepository . getComponentByID ( sbbID ) ; for ( ResourceAdaptorTypeBindingDescriptor raTypeBinding : sbbComponent . getDescriptor ( ) . getResourceAdaptorTypeBindings ( ) ) { for ( ResourceAdaptorEntityBindingDescriptor raEntityBinding : raTypeBinding . getResourceAdaptorEntityBinding ( ) ) { result . add ( raEntityBinding . getResourceAdaptorEntityLink ( ) ) ; } } } return result ;


signature:
public class DefaultSleeEntityResolver { /** * Adds a URL to the specified resource ( as returned by the system classloader ) .
 * to the resource table of the resolver .
 * @ param publicID the public id of the resource
 * @ param resourceName the path ( starting from a location in the class path )
 * and name of the dtd that should be used by the resolver for documents
 * with the specified public id . */
private void registerResource ( String publicID , String resourceName ) { } }

implementation:
URL url = this . getClass ( ) . getClassLoader ( ) . getResource ( resourceName ) ; if ( url != null ) { resources . put ( publicID , url ) ; } else { // All the slee dtds should be packaged locally in sar of slee itself
throw new IllegalStateException ( "Cannot find resource:" + resourceName ) ; }


signature:
public class SleeContainer { /** * dumps the container state as a string , useful for debug / profiling
 * @ return */
public String dumpState ( ) { } }

implementation: return componentManagement + "\n" + resourceManagement + "\n" + timerFacility + "\n" + traceMBeanImpl + "\n" + sleeProfileTableManager + "\n" + activityContextFactory + "\n" + activityContextNamingFacility + "\n" + nullActivityFactory + "\n" + getEventRouter ( ) + "\n" + getEventContextFactory ( ) + "\n" + getTransactionManager ( ) + "\n" ; // + cluster . getMobicentsCache ( ) . getCacheContent ( ) ;


signature:
public class SleeContainer { /** * Initiates the SLEE container */
public void initSlee ( ) throws InvalidStateException { } }

implementation:
if ( sleeState != null ) { throw new InvalidStateException ( "slee in " + sleeState + " state" ) ; } // slee init
beforeModulesInitialization ( ) ; for ( Iterator < SleeContainerModule > i = modules . iterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) . sleeInitialization ( ) ; } afterModulesInitialization ( ) ; sleeState = SleeState . STOPPED ;


signature:
public class SleeContainer { /** * Shutdown of the SLEE container
 * @ throws InvalidStateException */
public void shutdownSlee ( ) throws InvalidStateException { } }

implementation:
if ( sleeState != SleeState . STOPPED ) { throw new InvalidStateException ( "slee in " + sleeState + " state" ) ; } // slee shutdown
beforeModulesShutdown ( ) ; for ( Iterator < SleeContainerModule > i = modules . descendingIterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) . sleeShutdown ( ) ; } afterModulesShutdown ( ) ; sleeState = null ;


signature:
public class SleeContainer { /** * Ensures the standard SLEE lifecycle .
 * @ param oldState
 * @ param newState
 * @ throws InvalidStateException */
private void validateStateTransition ( SleeState oldState , SleeState newState ) throws InvalidStateException { } }

implementation: if ( oldState == SleeState . STOPPED ) { if ( newState == SleeState . STARTING ) { return ; } } else if ( oldState == SleeState . STARTING ) { if ( newState == SleeState . RUNNING || newState == SleeState . STOPPING ) { return ; } } else if ( oldState == SleeState . RUNNING ) { if ( newState == SleeState . STOPPING ) { return ; } } else if ( oldState == SleeState . STOPPING ) { if ( newState == SleeState . STOPPED ) { return ; } } throw new InvalidStateException ( "illegal slee state transition: " + oldState + " -> " + newState ) ;


signature:
public class EventRouterConfiguration { /** * / * ( non - Javadoc )
 * @ see org . mobicents . slee . container . management . jmx . EventRouterConfigurationMBean # setExecutorMapperClassName ( java . lang . String ) */
public void setExecutorMapperClassName ( String className ) throws ClassNotFoundException { } }

implementation: Class . forName ( className ) ; if ( this . executorMapperClassName != null ) { logger . warn ( "Setting executorMapperClassName property to " + className + ". If called with server running a stop and start is need to apply changes." ) ; } this . executorMapperClassName = className ;


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getProfileLocalObject ( ) */
public ProfileLocalObject getProfileLocalObject ( ) throws IllegalStateException , SLEEException { } }

implementation:
// check state
if ( profileObject == null || profileObject . getState ( ) == ProfileObjectState . PROFILE_INITIALIZATION || profileObject . getProfileEntity ( ) == null ) { throw new IllegalStateException ( ) ; } // check if it is default profile
if ( profileObject . getProfileEntity ( ) . getProfileName ( ) == null ) { throw new IllegalStateException ( ) ; } return profileObject . getProfileLocalObject ( ) ;


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getProfileName ( ) */
public String getProfileName ( ) throws IllegalStateException , SLEEException { } }

implementation: doGeneralChecks ( ) ; if ( profileObject == null || profileObject . getState ( ) == ProfileObjectState . PROFILE_INITIALIZATION || profileObject . getProfileEntity ( ) == null ) { throw new IllegalStateException ( ) ; } return this . profileObject . getProfileEntity ( ) . getProfileName ( ) ;


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getProfileTable ( java . lang . String ) */
public ProfileTable getProfileTable ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , SLEEException { } }

implementation: return this . profileTable . getSleeContainer ( ) . getSleeProfileTableManager ( ) . getProfileTable ( profileTableName ) ;


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getProfileTableName ( ) */
public String getProfileTableName ( ) throws SLEEException { } }

implementation: doGeneralChecks ( ) ; try { return this . profileTable . getProfileTableName ( ) ; } catch ( Exception e ) { throw new SLEEException ( "Operaion failed." , e ) ; }


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getRollbackOnly ( ) */
public boolean getRollbackOnly ( ) throws TransactionRequiredLocalException , SLEEException { } }

implementation: doGeneralChecks ( ) ; final SleeTransactionManager txMgr = profileTable . getSleeContainer ( ) . getTransactionManager ( ) ; txMgr . mandateTransaction ( ) ; try { return txMgr . getRollbackOnly ( ) ; } catch ( SystemException e ) { throw new SLEEException ( "Problem with the tx manager!" ) ; }


signature:
public class ProfileContextImpl { /** * ( non - Javadoc )
 * @ see javax . slee . profile . ProfileContext # getTracer ( java . lang . String ) */
public Tracer getTracer ( String tracerName ) throws NullPointerException , IllegalArgumentException , SLEEException { } }

implementation: doGeneralChecks ( ) ; try { TracerImpl . checkTracerName ( tracerName , this . profileTable . getProfileTableNotification ( ) . getNotificationSource ( ) ) ; } catch ( InvalidArgumentException e1 ) { throw new IllegalArgumentException ( e1 ) ; } try { return profileTable . getSleeContainer ( ) . getTraceManagement ( ) . createTracer ( this . profileTable . getProfileTableNotification ( ) . getNotificationSource ( ) , tracerName , true ) ; } catch ( Exception e ) { throw new SLEEException ( "Failed to obtain tracer" , e ) ; }


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . EventTypeID ) */
public EventTypeComponent getComponentByID ( EventTypeID id ) { } }

implementation:
// get from repository
EventTypeComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getEventTypeComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . profile . ProfileSpecificationID ) */
public ProfileSpecificationComponent getComponentByID ( ProfileSpecificationID id ) { } }

implementation:
// get from repository
ProfileSpecificationComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getProfileSpecificationComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . management . LibraryID ) */
public LibraryComponent getComponentByID ( LibraryID id ) { } }

implementation:
// get from repository
LibraryComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getLibraryComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . resource . ResourceAdaptorID ) */
public ResourceAdaptorComponent getComponentByID ( ResourceAdaptorID id ) { } }

implementation:
// get from repository
ResourceAdaptorComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getResourceAdaptorComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . resource . ResourceAdaptorTypeID ) */
public ResourceAdaptorTypeComponent getComponentByID ( ResourceAdaptorTypeID id ) { } }

implementation:
// get from repository
ResourceAdaptorTypeComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getResourceAdaptorTypeComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . SbbID ) */
public SbbComponent getComponentByID ( SbbID id ) { } }

implementation:
// get from repository
SbbComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getSbbComponents ( ) . get ( id ) ; } return component ;


signature:
public class DeployableUnitRepositoryImpl { /** * ( non - Javadoc )
 * @ see org . mobicents . slee . core . component . ComponentRepository # getComponentByID ( javax . slee . ServiceID ) */
public ServiceComponent getComponentByID ( ServiceID id ) { } }

implementation:
// get from repository
ServiceComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository , get it from deployable unit
component = deployableUnit . getServiceComponents ( ) . get ( id ) ; } return component ;


signature:
public class ConcreteProfileGenerator { /** * Create a named usage parameter getter .
 * @ param profileConcreteClass
 * @ throws SLEEException */
private void generateNamedUsageParameterGetter ( CtClass profileConcreteClass ) { } }

implementation:
String methodName = "getUsageParameterSet" ; for ( CtMethod ctMethod : profileConcreteClass . getMethods ( ) ) { if ( ctMethod . getName ( ) . equals ( methodName ) ) { try { // copy method , we can ' t just add body becase it is in super
// class and does not sees profileObject field
CtMethod ctMethodCopy = CtNewMethod . copy ( ctMethod , profileConcreteClass , null ) ; // create the method body
String methodBody = "{ return ($r)" + ClassGeneratorUtils . MANAGEMENT_HANDLER + ".getUsageParameterSet(profileObject,$1); }" ; if ( logger . isTraceEnabled ( ) ) logger . trace ( "Implemented method " + methodName + " , body = " + methodBody ) ; ctMethodCopy . setBody ( methodBody ) ; profileConcreteClass . addMethod ( ctMethodCopy ) ; } catch ( CannotCompileException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } }


signature:
public class ConcreteProfileGenerator { /** * Generates info that indicates if a method from { @ link Profile } interface
 * should be invoked or not , in runtime . Note that all methods from { @ link ProfileManagement }
 * that we are interested are all contained in { @ link Profile } interface . */
private void generateProfileConcreteClassInfo ( CtClass profileConcreteClass ) { } }

implementation:
final ClassPool pool = profileComponent . getClassPool ( ) ; CtClass profileClass = null ; try { profileClass = pool . get ( Profile . class . getName ( ) ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } ProfileConcreteClassInfo profileConcreteClassInfo = profileComponent . getProfileConcreteClassInfo ( ) ; for ( CtMethod method : profileClass . getDeclaredMethods ( ) ) { for ( CtMethod profileConcreteMethod : profileConcreteClass . getMethods ( ) ) { if ( profileConcreteMethod . getName ( ) . equals ( method . getName ( ) ) && profileConcreteMethod . getSignature ( ) . equals ( method . getSignature ( ) ) ) { // match , save info
profileConcreteClassInfo . setInvokeInfo ( profileConcreteMethod . getMethodInfo ( ) . getName ( ) , ! profileConcreteMethod . isEmpty ( ) ) ; break ; } } }


signature:
public class NullActivityContextInterfaceFactoryImpl { /** * / * ( non - Javadoc )
 * @ see javax . slee . nullactivity . NullActivityContextInterfaceFactory # getActivityContextInterface ( javax . slee . nullactivity . NullActivity ) */
public ActivityContextInterface getActivityContextInterface ( NullActivity nullActivity ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityException , FactoryException { } }

implementation: if ( nullActivity == null ) throw new NullPointerException ( "null NullActivity ! huh!!" ) ; if ( ! ( nullActivity instanceof NullActivityImpl ) ) throw new UnrecognizedActivityException ( "unrecognized activity" ) ; NullActivityImpl nullActivityImpl = ( NullActivityImpl ) nullActivity ; ActivityContextHandle ach = new NullActivityContextHandle ( nullActivityImpl . getHandle ( ) ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { throw new UnrecognizedActivityException ( nullActivity ) ; } return ac . getActivityContextInterface ( ) ;


signature:
public class SimpleQueryRunner { /** * Find unique entry , uses { @ link QueryRunner # queryUnique ( org . polyjdbc . core . query . SelectQuery , org . polyjdbc . core . query . mapper . ObjectMapper ) } . */
public < T > T queryUnique ( final SelectQuery query , final ObjectMapper < T > mapper ) { } }

implementation: return runner . run ( new TransactionWrapper < T > ( ) { public T perform ( QueryRunner queryRunner ) { return queryRunner . queryUnique ( query , mapper ) ; } } ) ;


signature:
public class SimpleQueryRunner { /** * Retrieve list , uses { @ link QueryRunner # queryList ( org . polyjdbc . core . query . SelectQuery , org . polyjdbc . core . query . mapper . ObjectMapper ) } . */
public < T > List < T > queryList ( final SelectQuery query , final ObjectMapper < T > mapper ) { } }

implementation: return runner . run ( new TransactionWrapper < List < T > > ( ) { public List < T > perform ( QueryRunner queryRunner ) { return queryRunner . queryList ( query , mapper ) ; } } ) ;


signature:
public class SimpleQueryRunner { /** * Retrieve set , uses { @ link QueryRunner # querySet ( org . polyjdbc . core . query . SelectQuery , org . polyjdbc . core . query . mapper . ObjectMapper ) } . */
public < T > Set < T > querySet ( final SelectQuery query , final ObjectMapper < T > mapper ) { } }

implementation: return runner . run ( new TransactionWrapper < Set < T > > ( ) { public Set < T > perform ( QueryRunner queryRunner ) { return queryRunner . querySet ( query , mapper ) ; } } ) ;


signature:
public class SimpleQueryRunner { /** * Check if any result exists for query , uses { @ link QueryRunner # queryExistence ( org . polyjdbc . core . query . SelectQuery ) } . */
public boolean queryExistence ( final SelectQuery query ) { } }

implementation: return runner . run ( new TransactionWrapper < Boolean > ( ) { public Boolean perform ( QueryRunner queryRunner ) { return queryRunner . queryExistence ( query ) ; } } ) ;


signature:
public class SimpleQueryRunner { /** * Run insert query , uses { @ link QueryRunner # insert ( org . polyjdbc . core . query . InsertQuery ) } . */
public long insert ( final InsertQuery query ) { } }

implementation: return runner . run ( new TransactionWrapper < Long > ( ) { public Long perform ( QueryRunner queryRunner ) { return queryRunner . insert ( query ) ; } } ) ;


signature:
public class SimpleQueryRunner { /** * Run update query , uses { @ link QueryRunner # update ( org . polyjdbc . core . query . UpdateQuery ) } . */
public int update ( final UpdateQuery query ) { } }

implementation: return runner . run ( new TransactionWrapper < Integer > ( ) { public Integer perform ( QueryRunner queryRunner ) { return queryRunner . update ( query ) ; } } ) ;


signature:
public class UpdateQuery { /** * Set column to update . Object is automatically translated
 * onto matching JDBC type .
 * @ see org . polyjdbc . core . type . ColumnTypeMapper */
public UpdateQuery set ( String fieldName , Object value ) { } }

implementation: String updatedFieldName = "update_" + fieldName ; values . append ( fieldName ) . append ( " = :" ) . append ( updatedFieldName ) . append ( ", " ) ; query . setArgument ( updatedFieldName , value ) ; return this ;


signature:
public class UpdateQuery { /** * Sets value for placeholder defined in query . Placeholder name should
 * not start with < b > : < / b > , it is stripped off . Based on passed object type ,
 * appropriate JDBC type is chosen .
 * @ see org . polyjdbc . core . type . ColumnTypeMapper */
public UpdateQuery withArgument ( String argumentName , Object object ) { } }

implementation: query . setArgument ( argumentName , object ) ; return this ;


signature:
public class DeleteQuery { /** * Sets value for placeholder defined in query . Placeholder name should
 * not start with < b > : < / b > , it is stripped off . Based on passed object type ,
 * appropriate JDBC type is chosen .
 * @ see org . polyjdbc . core . type . ColumnTypeMapper */
public DeleteQuery withArgument ( String argumentName , Object object ) { } }


signature:
public class PolyJDBCBuilder { /** * Return new PolyJDBC instance . */
public PolyJDBC build ( ) { } }

implementation: TransactionManager manager ; if ( dataSource != null ) { manager = new DataSourceTransactionManager ( dataSource ) ; } else { manager = new ExternalTransactionManager ( connectionProvider ) ; } return new DefaultPolyJDBC ( dialect , schemaName , new ColumnTypeMapper ( customMappings ) , manager ) ;


signature:
public class PolyJDBCBuilder { /** * Register custom mapping from clazz to SQL type . SqlType should be one of { @ link java . sql . Types } . If you need to
 * add some transformations , register custom implementation of { @ link org . polyjdbc . core . type . TypeWrapper } .
 * @ param clazz class to register
 * @ param sqlType type compatible with { @ link java . sql . Types } */
public PolyJDBCBuilder withCustomMapping ( Class < ? > clazz , SqlType sqlType ) { } }

implementation: this . customMappings . put ( clazz , sqlType ) ; return this ;


signature:
public class SelectQuery { /** * Create < b > ORDER BY < / b > clause for given column , can be used multiple
 * times with multiple columns . */
public SelectQuery orderBy ( String name , Order order ) { } }

implementation: if ( orderBy == null ) { orderBy = new StringBuilder ( ORDER_BY_LENGTH ) ; orderBy . append ( " ORDER BY " ) ; } orderBy . append ( name ) . append ( " " ) . append ( order . getStringCode ( ) ) . append ( ", " ) ; return this ;


signature:
public class SelectQuery { /** * Sets value for placeholder defined in query . Placeholder name should
 * not start with < b > : < / b > , it is stripped off . Based on passed object type ,
 * appropriate JDBC type is chosen .
 * @ see org . polyjdbc . core . type . ColumnTypeMapper */
public SelectQuery withArgument ( String argumentName , Object object ) { } }


signature:
public class InsertQuery { /** * Insert value into column of given name . Object is automatically translated
 * onto matching JDBC type .
 * @ see org . polyjdbc . core . type . ColumnTypeMapper */
public InsertQuery value ( String fieldName , Object value ) { } }

implementation: valueNames . append ( fieldName ) . append ( ", " ) ; values . append ( ":" ) . append ( fieldName ) . append ( ", " ) ; setArgument ( fieldName , value ) ; return this ;


signature:
public class TransactionRunner { /** * Run specified operations in safe transaction block . */
public < T > T run ( TransactionWrapper < T > operation ) { } }

implementation: QueryRunner runner = null ; try { runner = queryRunnerFactory . create ( ) ; T result = operation . perform ( runner ) ; runner . commit ( ) ; return result ; } catch ( Throwable throwable ) { TheCloser . rollback ( runner ) ; throw new TransactionInterruptedException ( throwable ) ; } finally { TheCloser . close ( runner ) ; }


signature:
public class SearchResult { /** * Set the list of containing resources . Must all be instances of { @ link SearchLayer }
 * @ throws IllegalArgumentException if at least one of the resources is not a { @ link SearchLayer } */
@ JsonDeserialize ( contentAs = SearchLayer . class ) @ Override public void setWithin ( List < Resource > within ) throws IllegalArgumentException { } }

implementation: if ( within . stream ( ) . anyMatch ( r -> ! ( r instanceof SearchLayer ) ) ) { throw new IllegalArgumentException ( "SearchResult can only be within a SearchLayer." ) ; } super . setWithin ( within ) ;


signature:
public class SearchResult { /** * Add a new containing resource . Must be an instance of { @ link SearchLayer }
 * @ throws IllegalArgumentException if the resource is not a { @ link SearchLayer } */
@ Override public SearchResult addWithin ( Resource first , Resource ... rest ) throws IllegalArgumentException { } }

implementation: if ( ! ( first instanceof SearchLayer ) || Arrays . stream ( rest ) . anyMatch ( r -> ! ( r instanceof SearchLayer ) ) ) { throw new IllegalArgumentException ( "SearchResult can only be within a SearchLayer." ) ; } super . addWithin ( first , rest ) ; return this ;


signature:
public class RegionRequest { /** * Parse an IIIF Image API compliant region request string
 * @ param str region request string
 * @ return resulting RegionRequest instance
 * @ throws ResolvingException if the request string is malformed . */
@ JsonCreator public static RegionRequest fromString ( String str ) throws ResolvingException { } }

implementation: if ( str . equals ( "full" ) ) { return new RegionRequest ( ) ; } if ( str . equals ( "square" ) ) { return new RegionRequest ( true ) ; } Matcher matcher = PARSE_PAT . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( "Bad format: " + str ) ; } if ( matcher . group ( 1 ) == null ) { return new RegionRequest ( Integer . valueOf ( matcher . group ( 2 ) ) , Integer . valueOf ( matcher . group ( 3 ) ) , Integer . valueOf ( matcher . group ( 4 ) ) , Integer . valueOf ( matcher . group ( 5 ) ) ) ; } else { return new RegionRequest ( new BigDecimal ( matcher . group ( 2 ) ) , new BigDecimal ( matcher . group ( 3 ) ) , new BigDecimal ( matcher . group ( 4 ) ) , new BigDecimal ( matcher . group ( 5 ) ) ) ; }


signature:
public class RegionRequest { /** * Returns the requested region
 * @ return get a Rectangle2D instance representing the region */
public Rectangle2D getRegion ( ) { } }

implementation: if ( isRelative ( ) ) { return new Rectangle2D . Double ( relativeBox . x . doubleValue ( ) , relativeBox . y . doubleValue ( ) , relativeBox . w . doubleValue ( ) , relativeBox . h . doubleValue ( ) ) ; } else { return absoluteBox ; }


signature:
public class RegionRequest { /** * Resolve the region request into an actual region that can be used for cropping the image
 * @ param imageDims actual image dimensions
 * @ return Rectangle representing th actual region
 * @ throws de . digitalcollections . iiif . model . image . ResolvingException if rectangle is outside image dimensions */
public Rectangle resolve ( Dimension imageDims ) throws ResolvingException { } }

implementation: if ( square ) { if ( imageDims . width > imageDims . height ) { return new Rectangle ( ( imageDims . width - imageDims . height ) / 2 , 0 , imageDims . height , imageDims . height ) ; } else if ( imageDims . height > imageDims . width ) { return new Rectangle ( 0 , ( imageDims . height - imageDims . width ) / 2 , imageDims . width , imageDims . width ) ; } } if ( absoluteBox == null && relativeBox == null ) { return new Rectangle ( 0 , 0 , imageDims . width , imageDims . height ) ; } Rectangle rect ; if ( isRelative ( ) ) { rect = new Rectangle ( ( int ) Math . round ( relativeBox . x . doubleValue ( ) / 100. * imageDims . getWidth ( ) ) , ( int ) Math . round ( relativeBox . y . doubleValue ( ) / 100. * imageDims . getHeight ( ) ) , ( int ) Math . round ( relativeBox . w . doubleValue ( ) / 100. * imageDims . getWidth ( ) ) , ( int ) Math . round ( relativeBox . h . doubleValue ( ) / 100. * imageDims . getHeight ( ) ) ) ; } else { rect = absoluteBox ; } if ( rect . x >= imageDims . width || rect . y >= imageDims . height ) { throw new ResolvingException ( "X and Y must be smaller than the native width/height" ) ; } if ( rect . x + rect . width > imageDims . width ) { rect . width = imageDims . width - rect . x ; } if ( rect . y + rect . height > imageDims . height ) { rect . height = imageDims . height - rect . y ; } return rect ;


signature:
public class ImageApiSelector { /** * The spec says we have to urlencode values , but only characters outside of the US ASCII range and gen - delims
 * from RFC3986 . However , our URL library can only encode the full set of gen - delims ( EXCEPT the colon ) and sub - delims ,
 * which iswhy we have to manually decode the encoded sub - delims . . .
 * Great and pragmatic choice for readability , more code for us : - ) */
private static String urlEncode ( String str ) { } }

implementation: Set < String > excluded = ImmutableSet . of ( ":" , "!" , "$" , "&" , "'" , "(" , ")" , "*" , "+" , "," , ";" , "=" ) ; String encoded = new Encoded ( str ) . toString ( ) ; for ( String ex : excluded ) { encoded = encoded . replaceAll ( new Encoded ( ex ) . toString ( ) , ex ) ; } return encoded ;


signature:
public class ImageApiSelector { /** * Create the canonical of the Image API request . See http : / / iiif . io / api / image / 2.1 / # canonical - uri - syntax
 * @ param nativeSize Native size of the image the selector is applied to
 * @ param profile Image API profile used
 * @ param defaultQuality The native / default quality of the image the selector is applied to
 * @ return The canonical form of the Image API request
 * @ throws de . digitalcollections . iiif . model . image . ResolvingException if RegionRequest can not be instantiated from canonical form of region */
public String getCanonicalForm ( Dimension nativeSize , ImageApiProfile profile , Quality defaultQuality ) throws ResolvingException { } }

implementation: Dimension scaleReference = nativeSize ; Rectangle2D canonicalRegion = RegionRequest . fromString ( region . getCanonicalForm ( nativeSize ) ) . getRegion ( ) ; if ( canonicalRegion != null ) { scaleReference = new Dimension ( ( int ) canonicalRegion . getWidth ( ) , ( int ) canonicalRegion . getHeight ( ) ) ; } return String . format ( "%s%s/%s/%s/%s.%s" , identifier != null ? urlEncode ( identifier ) + "/" : "" , region . getCanonicalForm ( nativeSize ) , size . getCanonicalForm ( scaleReference , profile ) , rotation . toString ( ) , quality . equals ( defaultQuality ) ? "default" : quality . toString ( ) , format . toString ( ) ) ;


signature:
public class ResourceDeserializer { /** * Get type for " on " values that are plain URIs by deducing the type from their parent . */
private String getOnType ( DeserializationContext ctxt ) { } }

implementation:
// Easiest way : The parser has already constructed an annotation object with a motivation .
// This is highly dependendant on the order of keys in the JSON , i . e . if " on " is the first key in the annotation
// object , this won ' t work .
Object curVal = ctxt . getParser ( ) . getCurrentValue ( ) ; boolean isPaintingAnno = ( curVal != null && curVal instanceof Annotation && ( ( Annotation ) curVal ) . getMotivation ( ) != null && ( ( Annotation ) curVal ) . getMotivation ( ) . equals ( Motivation . PAINTING ) ) ; if ( isPaintingAnno ) { return "sc:Canvas" ; } // More reliable way : Walk up the parsing context until we hit a IIIF resource that we can deduce the type from
// Usually this shouldn ' t be more than two levels up
JsonStreamContext parent = ctxt . getParser ( ) . getParsingContext ( ) . getParent ( ) ; while ( parent != null && ( parent . getCurrentValue ( ) == null || ! ( parent . getCurrentValue ( ) instanceof Resource ) ) ) { parent = parent . getParent ( ) ; } if ( parent != null ) { Resource parentObj = ( Resource ) parent . getCurrentValue ( ) ; return parentObj . getType ( ) ; } return null ;


signature:
public class ModelUtilities { /** * Obtain the " completeness " ( i . e . " empty " , " id and type " , " it , type and label " , " id only " or " complex " ) of
 * a IIIF resource . Can be useful for determining how to serialize the resource , e . g . often resources with only
 * an id are serialized as a string .
 * @ param res The IIIF resource to check the completeness of
 * @ param type The type of the IIIF resource
 * @ return the completeness */
public static Completeness getCompleteness ( Object res , Class < ? > type ) { } }

implementation:
Set < Method > getters = ReflectionUtils . getAllMethods ( type , ReflectionUtils . withModifier ( Modifier . PUBLIC ) , ReflectionUtils . withPrefix ( "get" ) ) ; Set < String > gettersWithValues = getters . stream ( ) . filter ( g -> g . getAnnotation ( JsonIgnore . class ) == null ) // Only JSON - serializable fields
. filter ( g -> returnsValue ( g , res ) ) . map ( Method :: getName ) . collect ( Collectors . toSet ( ) ) ; boolean hasOnlyTypeAndId = ( gettersWithValues . size ( ) == 2 && Stream . of ( "getType" , "getIdentifier" ) . allMatch ( gettersWithValues :: contains ) ) ; if ( gettersWithValues . isEmpty ( ) ) { return Completeness . EMPTY ; } else if ( containsOnly ( gettersWithValues , "getType" , "getIdentifier" ) ) { return Completeness . ID_AND_TYPE ; } else if ( containsOnly ( gettersWithValues , "getType" , "getIdentifier" , "getLabels" ) ) { return Completeness . ID_AND_TYPE_AND_LABEL ; } else if ( containsOnly ( gettersWithValues , "getIdentifier" ) ) { return Completeness . ID_ONLY ; } else { return Completeness . COMPLEX ; }


signature:
public class Resource { /** * Set the viewing hints for this resource .
 * @ param viewingHints list of viewing hints
 * @ throws IllegalArgumentException if the resources not not support one of the viewing hints . */
public void setViewingHints ( List < ViewingHint > viewingHints ) throws IllegalArgumentException { } }

implementation: for ( ViewingHint hint : viewingHints ) { boolean supportsHint = ( hint . getType ( ) == ViewingHint . Type . OTHER || this . getSupportedViewingHintTypes ( ) . contains ( hint . getType ( ) ) ) ; if ( ! supportsHint ) { throw new IllegalArgumentException ( String . format ( "Resources of type '%s' do not support the '%s' viewing hint." , this . getType ( ) , hint . toString ( ) ) ) ; } } this . viewingHints = viewingHints ;


signature:
public class Resource { /** * Add one or more viewing hints for this resource .
 * @ param first first viewing hint to add
 * @ param rest list of second and more viewing hints
 * @ return this resource with added viewing hints
 * @ throws IllegalArgumentException if the resources not not support one of the viewing hints . */
public Resource addViewingHint ( ViewingHint first , ViewingHint ... rest ) throws IllegalArgumentException { } }

implementation: List < ViewingHint > hints = this . viewingHints ; if ( hints == null ) { hints = new ArrayList < > ( ) ; } hints . addAll ( Lists . asList ( first , rest ) ) ; this . setViewingHints ( hints ) ; return this ;


signature:
public class Resource { /** * Sets the renderings . All renderings must have both a profile and a format .
 * @ param renderings list of renderings with profile and format
 * @ throws IllegalArgumentException if at least one rendering does not have both a profile and a format . */
public void setRenderings ( List < OtherContent > renderings ) throws IllegalArgumentException { } }

implementation: renderings . forEach ( this :: verifyRendering ) ; this . renderings = renderings ;


signature:
public class Resource { /** * Add one or more renderings . All renderings must have both a profile and a format .
 * @ param first first rendering
 * @ param rest list of other renderings
 * @ return current instance
 * @ throws IllegalArgumentException if at least one rendering does not have both a profile and a format . */
public Resource addRendering ( OtherContent first , OtherContent ... rest ) { } }

implementation: if ( renderings == null ) { this . renderings = new ArrayList < > ( ) ; } List < OtherContent > renderingsToAdd = Lists . asList ( first , rest ) ; renderingsToAdd . forEach ( this :: verifyRendering ) ; this . renderings . addAll ( renderingsToAdd ) ; return this ;


signature:
public class ImageApiProfile { /** * Merge multiple profiles into one . Useful for image servers that want to consolidate the limits given in a info . json .
 * @ param profiles profiles to be merged
 * @ return merged profile */
public static ImageApiProfile merge ( List < Profile > profiles ) { } }

implementation: return profiles . stream ( ) . filter ( ImageApiProfile . class :: isInstance ) . map ( ImageApiProfile . class :: cast ) . reduce ( new ImageApiProfile ( ) , ImageApiProfile :: merge ) ;


signature:
public class ImageApiProfile { /** * Merge two profiles .
 * @ param other profile to be merged
 * @ return merged profile */
public ImageApiProfile merge ( ImageApiProfile other ) { } }

implementation: ImageApiProfile merged = new ImageApiProfile ( ) ; streamNotNull ( this . features ) . forEach ( merged :: addFeature ) ; streamNotNull ( other . features ) . forEach ( merged :: addFeature ) ; streamNotNull ( this . formats ) . forEach ( merged :: addFormat ) ; streamNotNull ( other . formats ) . forEach ( merged :: addFormat ) ; streamNotNull ( this . qualities ) . forEach ( merged :: addQuality ) ; streamNotNull ( other . qualities ) . forEach ( merged :: addQuality ) ; if ( this . maxWidth != null && other . maxWidth == null ) { merged . maxWidth = this . maxWidth ; } else if ( this . maxWidth == null && other . maxWidth != null ) { merged . maxWidth = other . maxWidth ; } else if ( this . maxWidth != null ) { merged . maxWidth = Math . min ( this . maxWidth , other . maxWidth ) ; } if ( this . maxHeight != null && other . maxHeight == null ) { merged . maxHeight = this . maxHeight ; } else if ( this . maxHeight == null && other . maxHeight != null ) { merged . maxHeight = other . maxHeight ; } else if ( this . maxHeight != null ) { merged . maxHeight = Math . min ( this . maxHeight , other . maxHeight ) ; } if ( this . maxArea != null && other . maxArea == null ) { merged . maxArea = this . maxArea ; } else if ( this . maxArea == null && other . maxArea != null ) { merged . maxArea = other . maxArea ; } else if ( this . maxArea != null ) { merged . maxArea = Math . min ( this . maxArea , other . maxArea ) ; } return merged ;


signature:
public class RotationRequest { /** * Parse a rotation request from an IIIF Image API compliant rotation string .
 * @ param str iiif image api compliant rotation string
 * @ return RotationRequest represented by th given string
 * @ throws ResolvingException if the rotation string is malformed */
@ JsonCreator public static RotationRequest fromString ( String str ) throws ResolvingException { } }

implementation: Matcher matcher = PATTERN . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( "Bad format: " + str ) ; } return new RotationRequest ( new BigDecimal ( matcher . group ( 2 ) ) , ! ( matcher . group ( 1 ) == null ) ) ;


signature:
public class IiifModule { /** * Helper function to create Converter from lambda * */
private < T > Converter < String , T > fromString ( Function < String , ? extends T > fun ) { } }

implementation: return new StdConverter < String , T > ( ) { @ Override public T convert ( String value ) { return fun . apply ( value ) ; } } ;


signature:
public class Collection { /** * Adds one or more member resources .
 * Must be either instances of { @ link Manifest } or { @ link Collection } .
 * All { @ link Collection } members must have at least one { @ link de . digitalcollections . iiif . model . enums . ViewingHint } .
 * @ param first first member
 * @ param rest other members
 * @ return this collection with added members
 * @ throws IllegalArgumentException if at least one member is not a { @ link Manifest } or { @ link Collection } or is a
 * { @ link Collection } and does not have at least one { @ link de . digitalcollections . iiif . model . enums . ViewingHint } */
public Collection addMember ( Resource first , Resource ... rest ) { } }

implementation: if ( this . members == null ) { this . members = new ArrayList < > ( ) ; checkMember ( first ) ; stream ( rest ) . forEach ( this :: checkMember ) ; } this . members . addAll ( Lists . asList ( first , rest ) ) ; return this ;


signature:
public class Range { /** * Adds one or more member resources .
 * Must be either instances of { @ link Range } or { @ link Canvas } .
 * All members must have an identifier and a label .
 * @ param first first member
 * @ param rest other members
 * @ return this instance with added members
 * @ throws IllegalArgumentException if at least one member is not a { @ link Range } or { @ link Canvas } or does not have
 * an identifier and a label ; */
public Range addMember ( Resource first , Resource ... rest ) throws IllegalArgumentException { } }

implementation: if ( this . members == null ) { this . members = new ArrayList < > ( ) ; } List < Resource > membersToAdd = Lists . asList ( first , rest ) ; membersToAdd . forEach ( this :: checkMember ) ; this . members . addAll ( membersToAdd ) ; return this ;


signature:
public class PropertyValue { /** * see http : / / iiif . io / api / presentation / 2.1 / # language - of - property - values
 * example : { " description " : { " @ value " : " Here is a longer description of the object " , " @ language " : " en " } }
 * In the case where multiple values are supplied , clients must use the following algorithm to determine
 * which values to display to the user .
 * < ul >
 * < li > If none of the values have a language associated with them , the client must display all of the values . < / li >
 * < li > Else , the client should try to determine the user ’ s language preferences , or failing that use some
 * default language preferences . Then : < / li >
 * < ul >
 * < li > If any of the values have a language associated with them , the client must display all of the values
 * associated with the language that best matches the language preference . < / li >
 * < li > If all of the values have a language associated with them , and none match the language preference ,
 * the client must select a language and display all of the values associated with that language . < / li >
 * < li > If some of the values have a language associated with them , but none match the language preference ,
 * the client must display all of the values that do not have a language associated with them . < / li >
 * < / ul >
 * < / ul > */
public String getFirstValue ( Locale locale ) { } }

implementation: List < String > values = getValues ( locale ) ; if ( values == null ) { return getFirstValue ( ) ; } else { return values . get ( 0 ) ; }


signature:
public class SizeRequest { /** * Parse an IIIF Image API compliant size request string
 * @ param str IIIF Image API compliant size request string
 * @ return parsed SizeRequest
 * @ throws ResolvingException if the request string is malformed */
@ JsonCreator public static SizeRequest fromString ( String str ) throws ResolvingException { } }

implementation: if ( str . equals ( "full" ) ) { return new SizeRequest ( ) ; } if ( str . equals ( "max" ) ) { return new SizeRequest ( true ) ; } Matcher matcher = PARSE_PAT . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( "Bad format: " + str ) ; } if ( matcher . group ( 1 ) != null ) { if ( matcher . group ( 1 ) . equals ( "!" ) ) { return new SizeRequest ( Integer . valueOf ( matcher . group ( 2 ) ) , Integer . valueOf ( matcher . group ( 3 ) ) , true ) ; } else if ( matcher . group ( 1 ) . equals ( "pct:" ) ) { return new SizeRequest ( new BigDecimal ( matcher . group ( 4 ) ) ) ; } } Integer width = null ; Integer height = null ; if ( matcher . group ( 2 ) != null ) { width = Integer . parseInt ( matcher . group ( 2 ) ) ; } if ( matcher . group ( 3 ) != null ) { height = Integer . parseInt ( matcher . group ( 3 ) ) ; } return new SizeRequest ( width , height ) ;


signature:
public class SizeRequest { /** * Get the canonical form of this request .
 * @ see < a href = " http : / / iiif . io / api / image / 2.1 / # canonical - uri - syntax " > IIIF Image API specification < / a >
 * @ param nativeSize native size of request
 * @ param profile image api profile
 * @ return canonical form of this request
 * @ throws de . digitalcollections . iiif . model . image . ResolvingException if nativeSize can not be converted to canonical form */
public String getCanonicalForm ( Dimension nativeSize , ImageApiProfile profile ) throws ResolvingException { } }

implementation:
Dimension resolved = this . resolve ( nativeSize , profile ) ; // " w , " requests are already canonical
double nativeRatio = nativeSize . getWidth ( ) / nativeSize . getHeight ( ) ; double resolvedRatio = resolved . getWidth ( ) / resolved . getHeight ( ) ; if ( resolved . equals ( nativeSize ) ) { return "full" ; } else if ( this . width != null && this . height == null ) { return this . toString ( ) ; } else if ( Math . floor ( resolvedRatio * nativeSize . getHeight ( ) ) == nativeSize . getWidth ( ) || Math . ceil ( resolvedRatio * nativeSize . getHeight ( ) ) == nativeSize . getWidth ( ) ) { return String . format ( "%d," , resolved . width ) ; } else { return String . format ( "%d,%d" , resolved . width , resolved . height ) ; }


signature:
public class SizeRequest { /** * Resolve the request to dimensions that can be used for scaling , based on the native size of the image region and the available profile .
 * @ param nativeSize native size of the image region
 * @ param availableSizes available sizes
 * @ param profile image api profile
 * @ return resolved dimension
 * @ throws de . digitalcollections . iiif . model . image . ResolvingException if params can not be resolved to Dimension */
public Dimension resolve ( Dimension nativeSize , List < Dimension > availableSizes , ImageApiProfile profile ) throws ResolvingException { } }

implementation:
double aspect = ( double ) nativeSize . width / ( double ) nativeSize . height ; // " max "
if ( max ) { // By default , identical to the largest available size or the native size if no sizes were specified
Dimension dim = availableSizes . stream ( ) // Avoid upscaling when dealing with region requests
. filter ( s -> s . width <= nativeSize . width && s . height <= nativeSize . height ) // Select the largest available size
. max ( Comparator . comparing ( Dimension :: getWidth ) . thenComparing ( Dimension :: getHeight ) ) // Otherwise , fall back to the native size
. orElse ( new Dimension ( nativeSize . width , nativeSize . height ) ) ; if ( profile != null && profile . maxWidth != null ) { if ( dim . width > profile . maxWidth ) { // If maximum width is set , width cannot exceed it
dim . width = profile . maxWidth ; dim . height = ( int ) ( profile . maxWidth / aspect ) ; } int maxHeight = profile . maxHeight != null ? profile . maxHeight : profile . maxWidth ; if ( dim . height > maxHeight ) { // Adjust height if it exceeds maximum height
dim . height = maxHeight ; dim . width = ( int ) ( aspect * dim . height ) ; } } if ( profile != null && profile . maxArea != null ) { // Fit width and height into the maximum available area , preserving the aspect ratio
long currentArea = ( long ) dim . width * ( long ) dim . height ; if ( currentArea > profile . maxArea ) { dim . width = ( int ) Math . sqrt ( aspect * ( double ) profile . maxArea ) ; dim . height = ( int ) ( dim . width / aspect ) ; if ( dim . width <= 0 || dim . height <= 0 ) { throw new ResolvingException ( String . format ( "Cannot fit image with dimensions %dx%d into maximum area of %d pixels." , nativeSize . width , nativeSize . height , profile . maxArea ) ) ; } } } return dim ; } Dimension out ; if ( percentage != null || bestFit ) { // " pct : "
double ratio ; if ( percentage != null ) { ratio = percentage . doubleValue ( ) / 100.0 ; } else { ratio = Math . min ( width / nativeSize . getWidth ( ) , height / nativeSize . getHeight ( ) ) ; } out = new Dimension ( ( int ) ( ratio * nativeSize . width ) , ( int ) ( ratio * nativeSize . height ) ) ; } else if ( width == null && height == null ) { // " full "
out = nativeSize ; } else { out = new Dimension ( ) ; if ( width != null ) { out . width = width ; } if ( height != null ) { out . height = height ; } if ( width == null ) { out . width = ( int ) ( out . height * aspect ) ; } if ( height == null ) { out . height = ( int ) ( out . width / aspect ) ; } } Integer maxHeight = profile . maxHeight != null ? profile . maxHeight : profile . maxWidth ; if ( profile . maxWidth != null && out . width > profile . maxWidth ) { throw new ResolvingException ( String . format ( "Requested width (%d) exceeds maximum width (%d) as specified in the profile." , out . width , profile . maxWidth ) ) ; } else if ( maxHeight != null && out . height > maxHeight ) { throw new ResolvingException ( String . format ( "Requested height (%d) exceeds maximum height (%d) as specified in the profile." , out . height , maxHeight ) ) ; } else if ( profile . maxArea != null && out . height * out . width > profile . maxArea ) { throw new ResolvingException ( String . format ( "Requested area (%d*%d = %d) exceeds maximum area (%d) as specified in the profile" , out . width , out . height , out . width * out . height , profile . maxArea ) ) ; } else if ( ( profile . features == null || ! profile . features . contains ( ImageApiProfile . Feature . SIZE_ABOVE_FULL ) ) && ( out . width > nativeSize . width || out . height > nativeSize . height ) ) { throw new ResolvingException ( String . format ( "Requested dimensions (%dx%d) exceed native dimensions (%dx%d), profile states that upscaling is not supported." , out . width , out . height , nativeSize . width , nativeSize . height ) ) ; } return out ;


signature:
public class SizeRequest { /** * Like { @ link # resolve ( Dimension , ImageApiProfile ) } , but can be used with a { @ link Rectangle } , e . g . as returned from { @ link RegionRequest # resolve ( Dimension ) } .
 * @ param region image region
 * @ param profile image api profile
 * @ return resolved size dimension
 * @ throws de . digitalcollections . iiif . model . image . ResolvingException if rectangle region can not be resolved */
public Dimension resolve ( Rectangle region , ImageApiProfile profile ) throws ResolvingException { } }

implementation: return resolve ( new Dimension ( region . width , region . height ) , profile ) ;


signature:
public class AndroidDeviceStore { /** * call once */
public void initAndroidDevices ( boolean shouldKeepAdbAlive ) throws AndroidDeviceException { } }

implementation:
// DdmPreferences . setLogLevel ( LogLevel . VERBOSE . getStringValue ( ) ) ;
DdmPreferences . setInitialThreadUpdate ( true ) ; DdmPreferences . setInitialHeapUpdate ( true ) ; this . initializeAdbConnection ( ) ;


signature:
public class AndroidDeviceStore { /** * Initializes the AndroidDebugBridge and registers the DefaultHardwareDeviceManager with the
 * AndroidDebugBridge device change listener . */
protected void initializeAdbConnection ( ) { } }

implementation:
// Get a device bridge instance . Initialize , create and restart .
try { AndroidDebugBridge . init ( true ) ; } catch ( IllegalStateException e ) { // When we keep the adb connection alive the AndroidDebugBridge may
// have been already
// initialized at this point and it generates an exception . Do not
// print it .
if ( ! shouldKeepAdbAlive ) { logger . error ( "The IllegalStateException is not a show " + "stopper. It has been handled. This is just debug spew. Please proceed." , e ) ; throw new NestedException ( "ADB init failed" , e ) ; } } bridge = AndroidDebugBridge . getBridge ( ) ; if ( bridge == null ) { bridge = AndroidDebugBridge . createBridge ( AndroidSdk . adb ( ) . getAbsolutePath ( ) , false ) ; } long timeout = System . currentTimeMillis ( ) + 60000 ; while ( ! bridge . hasInitialDeviceList ( ) && System . currentTimeMillis ( ) < timeout ) { try { Thread . sleep ( 50 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } // Add the existing devices to the list of devices we are tracking .
IDevice [ ] devices = bridge . getDevices ( ) ; logger . info ( "initialDeviceList size {}" , devices . length ) ; for ( int i = 0 ; i < devices . length ; i ++ ) { logger . info ( "devices state: {},{} " , devices [ i ] . getName ( ) , devices [ i ] . getState ( ) ) ; connectedDevices . put ( devices [ i ] , new DefaultHardwareDevice ( devices [ i ] ) ) ; } bridge . addDeviceChangeListener ( new DeviceChangeListener ( connectedDevices ) ) ;


signature:
public class NestedException { /** * Check whether this exception contains an exception of the given type :
 * either it is of the given class itself or it contains a nested cause of
 * the given type .
 * @ param exType
 * the exception type to look for
 * @ return whether there is a nested exception of the specified type */
@ SuppressWarnings ( "rawtypes" ) public boolean contains ( Class exType ) { } }

implementation: if ( exType == null ) { return false ; } if ( exType . isInstance ( this ) ) { return true ; } Throwable cause = getCause ( ) ; if ( cause == this ) { return false ; } if ( cause instanceof NestedException ) { return ( ( NestedException ) cause ) . contains ( exType ) ; } else { while ( cause != null ) { if ( exType . isInstance ( cause ) ) { return true ; } if ( cause . getCause ( ) == cause ) { break ; } cause = cause . getCause ( ) ; } return false ; }


signature:
public class AbstractDevice { /** * ugly implementation */
@ Override public boolean isScreenOn ( ) { } }

implementation: CommandLine command = adbCommand ( "shell" , "dumpsys power" ) ; try { String powerState = ShellCommand . exec ( command ) . toLowerCase ( ) ; if ( powerState . indexOf ( "mscreenon=true" ) > - 1 || powerState . indexOf ( "mpowerstate=0" ) == - 1 ) { return true ; } } catch ( ShellCommandException e ) { log . info ( "Could not get property init.svc.bootanim" , e ) ; } return false ;


signature:
public class AbstractDevice { /** * get current android page ' s dump file */
public String getDump ( ) { } }

implementation: pushAutomator2Device ( ) ; runtest ( ) ; String path = pullDump2PC ( ) ; String xml = "" ; try { FileInputStream fileInputStream = new FileInputStream ( path ) ; @ SuppressWarnings ( "resource" ) BufferedReader in = new BufferedReader ( new InputStreamReader ( fileInputStream ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line = "" ; while ( ( line = in . readLine ( ) ) != null ) { buffer . append ( line ) ; } xml = buffer . toString ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return xml ;


signature:
public class AbstractDevice { /** * try to click GPS Popup window */
public boolean handlePopBox ( String deviceBrand ) { } }

implementation:
pushHandleGps2Device ( ) ; CommandLine exeCommand = null ; if ( deviceBrand . contains ( "HTC" ) ) { exeCommand = adbCommand ( "shell" , "uiautomator" , "runtest" , "/data/local/tmp/handlePopBox.jar" , "-c" , "com.test.device.gps.HTCGPSTest" ) ; } else if ( deviceBrand . contains ( "Meizu" ) ) { exeCommand = adbCommand ( "shell" , "uiautomator" , "runtest" , "/data/local/tmp/handlePopBox.jar" , "-c" , "com.test.device.gps.MeizuGPSTest" ) ; } String output = executeCommandQuietly ( exeCommand ) ; log . debug ( "run test {}" , output ) ; try { // give it a second to recover from the activity start
Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } return output . contains ( "OK" ) ;


signature:
public class AbstractDevice { /** * Push handlePopBox . jar to android tmp folder
 * @ return push device successful or not */
private boolean pushHandleGps2Device ( ) { } }

implementation:
InputStream io = AbstractDevice . class . getResourceAsStream ( "handlePopBox.jar" ) ; File dest = new File ( FileUtils . getTempDirectory ( ) , "handlePopBox.jar" ) ; try { FileUtils . copyInputStreamToFile ( io , dest ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } CommandLine pushcommand = adbCommand ( "push " , dest . getAbsolutePath ( ) , "/data/local/tmp/" ) ; String outputPush = executeCommandQuietly ( pushcommand ) ; log . debug ( "Push automator.jar to device {}" , outputPush ) ; try { // give it a second to recover from the activity start
Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } return outputPush . contains ( "KB/s" ) ;


signature:
public class AbstractDevice { /** * clean file dump . xml , qian . xml , uidump . xml in tmp folder */
public void cleanTemp ( ) { } }

implementation:
CommandLine dumpcommand = adbCommand ( "shell" , "rm" , "-r" , "/data/local/tmp/local/tmp/dump.xml" ) ; executeCommandQuietly ( dumpcommand ) ; try { // give it a second to recover from the activity start
Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } CommandLine qiancommand = adbCommand ( "shell" , "rm" , "-r" , "/data/local/tmp/local/tmp/qian.xml" ) ; String output = executeCommandQuietly ( qiancommand ) ; log . debug ( "Delete file qian.xml: {}" , output ) ; try { // give it a second to recover from the activity start
Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } CommandLine command = adbCommand ( "shell" , "rm" , "-r" , "/data/local/tmp/uidump.xml" ) ; executeCommandQuietly ( command ) ; try { // give it a second to recover from the activity start
Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; }


signature:
public class AbstractDevice { /** * pull dump file from android device to pc
 * @ return pc dump file path */
public String pullDump2PC ( ) { } }

implementation: String serial = device . getSerialNumber ( ) ; File dest = new File ( FileUtils . getTempDirectory ( ) , serial + ".xml" ) ; String path = dest . getPath ( ) ; log . debug ( "pull dump file to pc's path {}" , path ) ; CommandLine commandpull = adbCommand ( "pull" , "/data/local/tmp/local/tmp/qian.xml" , path ) ; String out = executeCommandQuietly ( commandpull ) ; log . debug ( "pull dump file to pc's result {}" , out ) ; return path ;


signature:
public class AbstractDevice { /** * Use adb to send a keyevent to the device . < p > Full list of keys available here :
 * http : / / developer . android . com / reference / android / view / KeyEvent . html
 * @ param value - Key to be sent to ' adb shell input keyevent ' */
public void inputKeyevent ( int value ) { } }

implementation:
executeCommandQuietly ( adbCommand ( "shell" , "input" , "keyevent" , "" + value ) ) ; // need to wait a beat for the UI to respond
try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { log . warn ( "" , e ) ; }


signature:
public class AbstractDevice { /** * Get crash log from AUT
 * @ return empty string if there is no crash log on the device , otherwise returns the stack trace
 * caused by the crash of the AUT */
public String getCrashLog ( ) { } }

implementation:
String crashLogFileName = null ; File crashLogFile = new File ( getExternalStoragePath ( ) , crashLogFileName ) ; // the " test " utility doesn ' t exist on all devices so we ' ll check the
// output of ls .
CommandLine directoryListCommand = adbCommand ( "shell" , "ls" , crashLogFile . getParentFile ( ) . getAbsolutePath ( ) ) ; String directoryList = executeCommandQuietly ( directoryListCommand ) ; if ( directoryList . contains ( crashLogFileName ) ) { return executeCommandQuietly ( adbCommand ( "shell" , "cat" , crashLogFile . getAbsolutePath ( ) ) ) ; } return "" ;


signature:
public class TextEditor { /** * Replace all occurrences of the regular expression with the replacement . The replacement string
 * can contain $ 1 , $ 2 etc . referring to matched groups in the regular expression .
 * @ param regex
 * @ param replacement
 * @ return */
public TextEditor replaceAll ( String regex , String replacement ) { } }

implementation: if ( text . length ( ) > 0 ) { final String r = replacement ; Pattern p = Pattern . compile ( regex , Pattern . MULTILINE ) ; Matcher m = p . matcher ( text ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { m . appendReplacement ( sb , r ) ; } m . appendTail ( sb ) ; text = new StringBuilder ( sb . toString ( ) ) ; } return this ;


signature:
public class TextEditor { /** * Same as replaceAll ( String , String ) , but does not interpret
 * $ 1 , $ 2 etc . in the replacement string .
 * @ param regex
 * @ param replacement
 * @ return */
public TextEditor replaceAllLiteral ( String regex , final String replacement ) { } }

implementation: return replaceAll ( Pattern . compile ( regex , Pattern . MULTILINE ) , new Replacement ( ) { public String replacement ( Matcher m ) { return replacement ; } } ) ;


signature:
public class TextEditor { /** * Replace all occurrences of the Pattern . The Replacement object ' s replace ( ) method is
 * called on each match , and it provides a replacement , which is placed literally
 * ( i . e . , without interpreting $ 1 , $ 2 etc . )
 * @ param pattern
 * @ param replacement
 * @ return */
public TextEditor replaceAll ( Pattern pattern , Replacement replacement ) { } }

implementation: Matcher m = pattern . matcher ( text ) ; int lastIndex = 0 ; StringBuilder sb = new StringBuilder ( ) ; while ( m . find ( ) ) { sb . append ( text . subSequence ( lastIndex , m . start ( ) ) ) ; sb . append ( replacement . replacement ( m ) ) ; lastIndex = m . end ( ) ; } sb . append ( text . subSequence ( lastIndex , text . length ( ) ) ) ; text = sb ; return this ;


signature:
public class TextEditor { /** * Convert tabs to spaces .
 * @ param tabWidth Number of spaces per tab .
 * @ return */
public TextEditor detabify ( final int tabWidth ) { } }

implementation: replaceAll ( Pattern . compile ( "(.*?)\\t" ) , new Replacement ( ) { public String replacement ( Matcher m ) { String lineSoFar = m . group ( 1 ) ; int width = lineSoFar . length ( ) ; StringBuilder replacement = new StringBuilder ( lineSoFar ) ; do { replacement . append ( ' ' ) ; ++ width ; } while ( width % tabWidth != 0 ) ; return replacement . toString ( ) ; } } ) ; return this ;


signature:
public class TextEditor { /** * Introduce a number of spaces at the start of each line .
 * @ param spaces
 * @ return */
public TextEditor indent ( int spaces ) { } }

implementation: StringBuilder sb = new StringBuilder ( spaces ) ; for ( int i = 0 ; i < spaces ; i ++ ) { sb . append ( ' ' ) ; } return replaceAll ( "^" , sb . toString ( ) ) ;


signature:
public class TextEditor { /** * Parse HTML tags , returning a Collection of HTMLToken objects .
 * @ return */
public Collection < HTMLToken > tokenizeHTML ( ) { } }

implementation: List < HTMLToken > tokens = new ArrayList < HTMLToken > ( ) ; String nestedTags = nestedTagsRegex ( 6 ) ; Pattern p = Pattern . compile ( "" + "(?s:<!(--.*?--\\s*)+>)" + "|" + "(?s:<\\?.*?\\?>)" + "|" + nestedTags + "" , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( text ) ; int lastPos = 0 ; while ( m . find ( ) ) { if ( lastPos < m . start ( ) ) { tokens . add ( HTMLToken . text ( text . substring ( lastPos , m . start ( ) ) ) ) ; } tokens . add ( HTMLToken . tag ( text . substring ( m . start ( ) , m . end ( ) ) ) ) ; lastPos = m . end ( ) ; } if ( lastPos < text . length ( ) ) { tokens . add ( HTMLToken . text ( text . substring ( lastPos , text . length ( ) ) ) ) ; } return tokens ;


signature:
public class MarkdownProcessor { /** * Perform the conversion from Markdown to HTML .
 * @ param txt - input in markdown format
 * @ return HTML block corresponding to txt passed in . */
public String markdown ( String txt ) { } }

implementation:
if ( txt == null ) { txt = "" ; } TextEditor text = new TextEditor ( txt ) ; // Standardize line endings :
text . replaceAll ( "\\r\\n" , "\n" ) ; // DOS to Unix
text . replaceAll ( "\\r" , "\n" ) ; // Mac to Unix
text . replaceAll ( "^[ \\t]+$" , "" ) ; // Make sure $ text ends with a couple of newlines :
text . append ( "\n\n" ) ; text . detabify ( ) ; text . deleteAll ( "^[ ]+$" ) ; hashHTMLBlocks ( text ) ; stripLinkDefinitions ( text ) ; text = runBlockGamut ( text ) ; unEscapeSpecialChars ( text ) ; text . append ( "\n" ) ; return text . toString ( ) ;


signature:
public class MarkdownProcessor { /** * escape special characters
 * Within tags - - meaning between < and > - - encode [ \ ` * _ ] so they
 * don ' t conflict with their use in Markdown for code , italics and strong .
 * We ' re replacing each such character with its corresponding random string
 * value ; this is likely overkill , but it should prevent us from colliding
 * with the escape values by accident .
 * @ param text
 * @ return */
private TextEditor escapeSpecialCharsWithinTagAttributes ( TextEditor text ) { } }

implementation: Collection < HTMLToken > tokens = text . tokenizeHTML ( ) ; TextEditor newText = new TextEditor ( "" ) ; for ( HTMLToken token : tokens ) { String value = token . getText ( ) ; if ( token . isTag ( ) ) { value = value . replaceAll ( "\\\\" , CHAR_PROTECTOR . encode ( "\\" ) ) ; value = value . replaceAll ( "`" , CHAR_PROTECTOR . encode ( "`" ) ) ; value = value . replaceAll ( "\\*" , CHAR_PROTECTOR . encode ( "*" ) ) ; value = value . replaceAll ( "_" , CHAR_PROTECTOR . encode ( "_" ) ) ; } newText . append ( value ) ; } return newText ;


signature:
public class PoolOperations { /** * / / / / / getProxyConnection ( . . . ) / / / / / */
public Connection getProxyConnection ( long timeoutMs ) throws SQLException { } }

implementation:
int attempt = 1 ; ConnHolder connHolder = null ; SQLException sqlException = null ; long startNanoTime = System . nanoTime ( ) ; while ( connHolder == null ) { try { connHolder = getConnHolder ( timeoutMs ) ; } catch ( ViburDBCPException e ) { // thrown only if we can retry the operation , see getConnHolder ( . . . )
sqlException = chainSQLException ( e . unwrapSQLException ( ) , sqlException ) ; if ( attempt ++ > dataSource . getAcquireRetryAttempts ( ) ) { // check the max retries limit
throw sqlException ; } if ( timeoutMs > 0 ) { // check the time limit if applicable
timeoutMs = NANOSECONDS . toMillis ( connectionTimeoutInNanos - ( System . nanoTime ( ) - startNanoTime ) ) - dataSource . getAcquireRetryDelayInMs ( ) ; // calculates the remaining timeout
if ( timeoutMs <= 0 ) { throw sqlException ; } } try { MILLISECONDS . sleep ( dataSource . getAcquireRetryDelayInMs ( ) ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw chainSQLException ( new SQLException ( ie ) , sqlException ) ; } } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Taking rawConnection {}" , connHolder . rawConnection ( ) ) ; } Connection proxy = newProxyConnection ( connHolder , this , dataSource ) ; if ( dataSource . isPoolEnableConnectionTracking ( ) ) { connHolder . setProxyConnection ( proxy ) ; } return proxy ;


signature:
public class PoolOperations { /** * Tries to take a { @ code ConnHolder } object from the underlying object pool . If successful , never returns
 * { @ code null } .
 * @ param timeoutMs timeout in millis to pass to the underlying object pool { @ code take } methods
 * @ throws SQLException to indicate a generic non - recoverable error that cannot be retried
 * @ throws SQLTimeoutException to indicate a non - recoverable error due to timeout that cannot be retried
 * @ throws ViburDBCPException to indicate a recoverable error that can be retried */
private ConnHolder getConnHolder ( long timeoutMs ) throws SQLException , ViburDBCPException { } }

implementation:
Hook . GetConnection [ ] onGet = ( ( ConnHooksAccessor ) dataSource . getConnHooks ( ) ) . onGet ( ) ; ConnHolder connHolder = null ; long [ ] waitedNanos = NO_WAIT ; SQLException sqlException = null ; ViburDBCPException viburException = null ; try { if ( onGet . length > 0 ) { waitedNanos = new long [ 1 ] ; connHolder = timeoutMs > 0 ? poolService . tryTake ( timeoutMs , MILLISECONDS , waitedNanos ) : poolService . take ( waitedNanos ) ; } else { connHolder = timeoutMs > 0 ? poolService . tryTake ( timeoutMs , MILLISECONDS ) : poolService . take ( ) ; } if ( connHolder == null ) { // we were * not * able to obtain a connection from the pool
sqlException = createSQLException ( onGet . length > 0 ? waitedNanos [ 0 ] : MILLISECONDS . toNanos ( timeoutMs ) ) ; } } catch ( ViburDBCPException e ) { // thrown ( indirectly ) by the ConnectionFactory . create ( ) methods
viburException = e ; sqlException = e . unwrapSQLException ( ) ; // currently all such errors are treated as recoverable , i . e . , can be retried
} finally { Connection rawConnection = connHolder != null ? connHolder . rawConnection ( ) : null ; try { for ( Hook . GetConnection hook : onGet ) { hook . on ( rawConnection , waitedNanos [ 0 ] ) ; } } catch ( SQLException e ) { sqlException = chainSQLException ( sqlException , e ) ; } } if ( viburException != null ) { throw viburException ; // a recoverable error
} if ( sqlException != null ) { throw sqlException ; // a non - recoverable error
} return connHolder ; // never null if we reach this point


signature:
public class PoolOperations { /** * / / / / / restore ( . . . ) / / / / / */
public void restore ( ConnHolder connHolder , boolean valid , SQLException [ ] exceptions ) { } }

implementation: if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Restoring rawConnection {}" , connHolder . rawConnection ( ) ) ; } boolean reusable = valid && exceptions . length == 0 && connHolder . version ( ) == connectionFactory . version ( ) ; poolService . restore ( connHolder , reusable ) ; processSQLExceptions ( connHolder , exceptions ) ;


signature:
public class PoolOperations { /** * Processes SQL exceptions that have occurred on the given JDBC Connection ( wrapped in a { @ code ConnHolder } ) .
 * @ param connHolder the given connection
 * @ param exceptions the list of SQL exceptions that have occurred on the connection ; might be an empty list but not a { @ code null } */
private void processSQLExceptions ( ConnHolder connHolder , SQLException [ ] exceptions ) { } }

implementation:
int connVersion = connHolder . version ( ) ; SQLException criticalException = getCriticalSQLException ( exceptions ) ; if ( criticalException != null && connectionFactory . compareAndSetVersion ( connVersion , connVersion + 1 ) ) { int destroyed = poolService . drainCreated ( ) ; // destroys all connections in the pool
logger . error ( "Critical SQLState {} occurred, destroyed {} connections from pool {}, current connection version is {}." , criticalException . getSQLState ( ) , destroyed , getPoolName ( dataSource ) , connectionFactory . version ( ) , criticalException ) ; }


signature:
public class ViburConfig { /** * < b > NOTE : < / b > the pool name can be set only once ; pool renaming is not supported .
 * @ param name the pool name to use */
public void setName ( String name ) { } }

implementation: if ( name == null || ( name = name . trim ( ) ) . length ( ) == 0 ) { logger . error ( "Invalid pool name {}" , name ) ; return ; } if ( ! defaultName . equals ( this . name ) || defaultName . equals ( name ) ) { logger . error ( "Pool name is already set or duplicated, existing name = {}, incoming name = {}" , this . name , name ) ; return ; } this . name = name ;


signature:
public class ExceptionCollector { /** * This method will be called when an operation invoked on a JDBC object throws an SQLException .
 * It will accumulate a list of all non - transient SQL exceptions .
 * @ param exception the exception thrown */
final void addException ( SQLException exception ) { } }

implementation:
if ( ! ( exception instanceof SQLTimeoutException ) && ! ( exception instanceof SQLTransactionRollbackException ) ) { getOrInit ( ) . offer ( exception ) ; // SQLExceptions from the above two sub - types are not stored
}


signature:
public class ExceptionCollector { /** * Returns an array of all SQL exceptions collected by { @ link # addException } . This method will be
 * called when a pooled Connection is closed , in order to determine whether the underlying ( raw )
 * JDBC Connection also needs to be closed . */
final SQLException [ ] getExceptions ( ) { } }

implementation: Queue < SQLException > ex = exceptions ; if ( ex == null ) { return NO_EXCEPTIONS ; } return ex . toArray ( NO_EXCEPTIONS ) ;


signature:
public class ClhmStatementCache { /** * Creates and returns a new EvictionListener for the CLHM . It is worth noting that this
 * EvictionListener is called in the context of the thread that has executed an insert ( putIfAbsent )
 * operation which has increased the CLHM size above its maxSize - in which case the CLHM
 * evicts its LRU entry .
 * @ return a new EvictionListener for the CLHM */
private static EvictionListener < StatementMethod , StatementHolder > getListener ( ) { } }

implementation: return new EvictionListener < StatementMethod , StatementHolder > ( ) { @ Override public void onEviction ( StatementMethod statementMethod , StatementHolder statementHolder ) { if ( statementHolder . state ( ) . getAndSet ( EVICTED ) == AVAILABLE ) { quietClose ( statementHolder . rawStatement ( ) ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Evicted {}" , statementHolder . rawStatement ( ) ) ; } } } ;


signature:
public class ClhmStatementCache { /** * Closes this ClhmStatementCache and removes all entries from it . */
@ Override public void close ( ) { } }

implementation: if ( closed . getAndSet ( true ) ) { return ; } for ( Map . Entry < StatementMethod , StatementHolder > entry : statementCache . entrySet ( ) ) { StatementHolder value = entry . getValue ( ) ; statementCache . remove ( entry . getKey ( ) , value ) ; quietClose ( value . rawStatement ( ) ) ; }


signature:
public class ViburListener { /** * See { @ link org . vibur . dbcp . ViburDataSource # getTakenConnections } . */
public TakenConnection [ ] getTakenConnections ( ) { } }

implementation: ConnHolder [ ] takenConns = getTaken ( new ConnHolder [ config . getPoolMaxSize ( ) ] ) ; if ( takenConns . length == 0 ) { return NO_TAKEN_CONNECTIONS ; } return Arrays . copyOf ( takenConns , takenConns . length , TakenConnection [ ] . class ) ;


signature:
public class ViburDBCPDataSource { /** * { @ inheritDoc }
 * @ throws ViburDBCPException if not in a { @ code NEW } state when started ;
 * if a configuration error is found during start ;
 * if cannot start this DataSource successfully , that is , if cannot successfully
 * initialize / configure the underlying SQL system , if cannot create the underlying SQL connections ,
 * if cannot initialize the configured / needed JDBC Driver , if cannot create the configured pool reducer ,
 * or if cannot initialize JMX */
@ Override public void start ( ) throws ViburDBCPException { } }

implementation: try { doStart ( ) ; logger . info ( "Started {}" , this ) ; } catch ( IllegalStateException e ) { throw new ViburDBCPException ( e ) ; } catch ( IllegalArgumentException | NullPointerException | ViburDBCPException e ) { logger . error ( "Unable to start {} due to:" , this , e ) ; terminate ( ) ; throw e instanceof ViburDBCPException ? e : new ViburDBCPException ( e ) ; }


signature:
public class ConnectionInvocationHandler { /** * Returns < i > a possibly < / i > cached StatementHolder object for the given proxied Connection object and the
 * invoked on it " prepare . . . " Method with the given args .
 * @ param method the invoked method
 * @ param args the invoked method arguments
 * @ return a retrieved from the cache or newly created StatementHolder object wrapping the raw JDBC Statement object
 * @ throws SQLException if the invoked underlying " prepare . . . " method throws an exception */
private StatementHolder getCachedStatement ( Method method , Object [ ] args ) throws SQLException { } }

implementation: if ( statementCache != null ) { return statementCache . take ( new StatementMethod ( getTarget ( ) , this , method , args ) ) ; } return getUncachedStatement ( method , args , ( String ) args [ 0 ] ) ;


signature:
public class ConnectionInvocationHandler { /** * / / / / / The StatementCreator implementation : / / / / / */
@ Override public PreparedStatement newStatement ( Method method , Object [ ] args ) throws SQLException { } }

implementation: String methodName = method . getName ( ) ; if ( methodName != "prepareStatement" && methodName != "prepareCall" ) { throw new ViburDBCPException ( "Unexpected method passed to newStatement() " + method ) ; } return ( PreparedStatement ) targetInvoke ( method , args ) ;


signature:
public class StatementInvocationHandler { /** * / / / / / The StatementProceedingPoint implementation : / / / / / */
@ Override public Object on ( Statement proxy , Method method , Object [ ] args , String sqlQuery , List < Object [ ] > sqlQueryParams , StatementProceedingPoint proceed ) throws SQLException { } }

implementation:
if ( ++ hookIdx < executionHooks . length ) { // invoke the next statement execution hook , if any
return executionHooks [ hookIdx ] . on ( proxy , method , args , sqlQuery , sqlQueryParams , this ) ; } return doProcessExecute ( proxy , method , args ) ;


signature:
public class AbstractInvocationHandler { /** * Handles all unrestricted method invocations that we can process before passing through the
 * { @ link # restrictedAccessEntry } . This method will be overridden in the { @ code AbstractInvocationHandler }
 * subclasses , and will be the place to implement the specific to these subclasses logic for unrestricted method
 * invocations handling . When the invoked { @ code method } is not an unrestricted method the default implementation
 * returns { @ link # NO _ RESULT } to indicate this .
 * @ param proxy see { @ link java . lang . reflect . InvocationHandler # invoke }
 * @ param method as above
 * @ param args as above
 * @ return as above
 * @ throws SQLException if the invoked underlying method throws such */
Object unrestrictedInvoke ( T proxy , Method method , Object [ ] args ) throws SQLException { } }

implementation:
String methodName = method . getName ( ) ; if ( methodName == "equals" ) { // comparing with = = as the Method names are interned Strings
return proxy == args [ 0 ] ; } if ( methodName == "hashCode" ) { return System . identityHashCode ( proxy ) ; } if ( methodName == "toString" ) { return "Vibur proxy for: " + target ; } // getClass ( ) , notify ( ) , notifyAll ( ) , and wait ( ) method calls are not intercepted by the dynamic proxies
if ( methodName == "unwrap" ) { @ SuppressWarnings ( "unchecked" ) Class < T > iface = ( Class < T > ) args [ 0 ] ; return unwrap ( iface ) ; } if ( methodName == "isWrapperFor" ) { return isWrapperFor ( ( Class < ? > ) args [ 0 ] ) ; } return NO_RESULT ;


signature:
public class AbstractInvocationHandler { /** * Handles all restricted method invocations that occur after ( and if ) we have passed through the
 * { @ link # restrictedAccessEntry } . This method will be overridden in the { @ code AbstractInvocationHandler }
 * subclasses , and will be the place to implement the specific to these subclasses logic for restricted method
 * invocations handling . The default implementation simply forwards the call to the original method of the
 * proxied object .
 * @ param proxy see { @ link java . lang . reflect . InvocationHandler # invoke }
 * @ param method as above
 * @ param args as above
 * @ return as above
 * @ throws SQLException if the invoked underlying method throws such */
Object restrictedInvoke ( T proxy , Method method , Object [ ] args ) throws SQLException { } }

implementation: return targetInvoke ( method , args ) ;


signature: public class JdbcUtils { public static void setDefaultValues ( Connection rawConnection , ViburConfig config ) throws SQLException { } }

implementation:
if ( config . getDefaultAutoCommit ( ) != null ) { rawConnection . setAutoCommit ( config . getDefaultAutoCommit ( ) ) ; } if ( config . getDefaultReadOnly ( ) != null ) { rawConnection . setReadOnly ( config . getDefaultReadOnly ( ) ) ; } if ( config . getDefaultTransactionIsolationIntValue ( ) != null ) { // noinspection MagicConstant - the int value is checked / set during Vibur config validation
rawConnection . setTransactionIsolation ( config . getDefaultTransactionIsolationIntValue ( ) ) ; } if ( config . getDefaultCatalog ( ) != null ) { rawConnection . setCatalog ( config . getDefaultCatalog ( ) ) ; }


signature:
public class JdbcUtils { /** * Validates / initializes the given { @ code rawConnection } via executing the given { @ code sqlQuery } .
 * @ param rawConnection the raw connection to validate / initialize
 * @ param sqlQuery must be a valid SQL query , a special value of { @ code isValid } in which case
 * the { @ link Connection # isValid } method will be called , or { @ code null }
 * in which case no validation / initialization will be performed
 * @ param config the Vibur config
 * @ return { @ code true } if the given connection is successfully validated / initialized ; { @ code false } otherwise */
public static boolean validateOrInitialize ( Connection rawConnection , String sqlQuery , ViburConfig config ) { } }

implementation: if ( sqlQuery == null ) { return true ; } try { if ( sqlQuery . equals ( IS_VALID_QUERY ) ) { return rawConnection . isValid ( config . getValidateTimeoutInSeconds ( ) ) ; } executeSqlQuery ( rawConnection , sqlQuery , config ) ; return true ; } catch ( SQLException e ) { logger . debug ( "Couldn't validate/ initialize rawConnection {}" , rawConnection , e ) ; return false ; }


signature: public class JdbcUtils { public static SQLException chainSQLException ( SQLException main , SQLException next ) { } }

implementation: if ( main == null ) { return next ; } main . setNextException ( next ) ; return main ;


signature:
public class ViburUtils { /** * Returns the extended pool name formatted as :
 * < blockquote > { @ code poolName @ hashCode ( currentlyTakenConns / remainingCreatedConns / poolMaxSize / poolState / threadInterruptedStatus ) } < / blockquote >
 * For example , { @ code p1@2db7a79b ( 1/1/10 / w / n ) } .
 * @ param config the Vibur config */
public static String getPoolName ( ViburConfig config ) { } }

implementation:
BasePool pool = config . getPool ( ) ; boolean initialState = pool . isTerminated ( ) ; String result = config . getName ( ) + '@' + toHexString ( config . hashCode ( ) ) + '(' + pool . taken ( ) + '/' + pool . remainingCreated ( ) + '/' + pool . maxSize ( ) + '/' + ( ! initialState ? 'w' : 't' ) // poolState : w = = working , t = = terminated
+ '/' + ( Thread . currentThread ( ) . isInterrupted ( ) ? 'i' : 'n' ) + ')' ; if ( initialState == pool . isTerminated ( ) ) { // make sure the pool state has not changed in the meantime
return result ; } return getPoolName ( config ) ; // this is one level of recursion only , pool state changes only once


signature:
public class WeakHashSet { /** * Removes all garbage collected values with their keys from the map .
 * Since we don ' t know how much the ReferenceQueue . poll ( ) operation
 * costs , we should call it only in the add ( ) method . */
private void processQueue ( ) { } }

implementation: WeakElement wv = null ; while ( ( wv = ( WeakElement ) this . queue . poll ( ) ) != null ) { super . remove ( wv ) ; }


signature:
public class BarberProcessor { /** * Finds the parent barbershop type in the supplied set , if any . */
private String findParentFqcn ( TypeElement typeElement , Set < String > parents ) { } }

implementation: TypeMirror type ; while ( true ) { type = typeElement . getSuperclass ( ) ; if ( type . getKind ( ) == TypeKind . NONE ) { return null ; } typeElement = ( TypeElement ) ( ( DeclaredType ) type ) . asElement ( ) ; if ( parents . contains ( typeElement . toString ( ) ) ) { String packageName = getPackageName ( typeElement ) ; return packageName + "." + getClassName ( typeElement , packageName ) ; } }


signature:
public class Barber { /** * Searches for $ $ Barbershop class for the given instance , cached for efficiency .
 * @ param cls Source class to find a matching $ $ Barbershop class for
 * @ return $ $ Barbershop class instance */
private static IBarbershop < Object > findBarbershopForClass ( Class < ? > cls ) { } }

implementation:
IBarbershop < Object > barbershop = BARBERSHOPS . get ( cls ) ; if ( barbershop != null ) { if ( debug ) Log . d ( TAG , "HIT: Cached in barbershop map." ) ; return barbershop ; } String clsName = cls . getName ( ) ; if ( clsName . startsWith ( ANDROID_PREFIX ) || clsName . startsWith ( JAVA_PREFIX ) ) { if ( debug ) { Log . d ( TAG , "MISS: Reached framework class. Abandoning search." ) ; } return NO_OP ; } // noinspection TryWithIdenticalCatches
try { Class < ? > barbershopClass = Class . forName ( clsName + SUFFIX ) ; // noinspection unchecked
barbershop = ( IBarbershop < Object > ) barbershopClass . newInstance ( ) ; if ( debug ) { Log . d ( TAG , "HIT: Class loaded barbershop class." ) ; } } catch ( ClassNotFoundException e ) { if ( debug ) { Log . d ( TAG , "Not found. Trying superclass " + cls . getSuperclass ( ) . getName ( ) ) ; } barbershop = findBarbershopForClass ( cls . getSuperclass ( ) ) ; } catch ( InstantiationException e ) { Log . e ( TAG , e . getMessage ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( TAG , e . getMessage ( ) ) ; } BARBERSHOPS . put ( cls , barbershop ) ; return barbershop ;


signature:
public class Barbershop { /** * Generates the class code and writes to a new source file .
 * @ param filer Annotation filer instance provided by { @ link BarberProcessor }
 * @ throws IOException */
void writeToFiler ( Filer filer ) throws IOException { } }

implementation: ClassName targetClassName = ClassName . get ( classPackage , targetClass ) ; TypeSpec . Builder barberShop = TypeSpec . classBuilder ( className ) . addModifiers ( Modifier . PUBLIC ) . addTypeVariable ( TypeVariableName . get ( "T" , targetClassName ) ) . addMethod ( generateStyleMethod ( ) ) . addMethod ( generateCheckParentMethod ( ) ) ; if ( parentBarbershop == null ) { barberShop . addSuperinterface ( ParameterizedTypeName . get ( ClassName . get ( Barber . IBarbershop . class ) , TypeVariableName . get ( "T" ) ) ) ; barberShop . addField ( FieldSpec . builder ( WeakHashSet . class , "lastStyledTargets" , Modifier . PROTECTED ) . initializer ( "new $T()" , WeakHashSet . class ) . build ( ) ) ; } else { barberShop . superclass ( ParameterizedTypeName . get ( ClassName . bestGuess ( parentBarbershop ) , TypeVariableName . get ( "T" ) ) ) ; } JavaFile javaFile = JavaFile . builder ( classPackage , barberShop . build ( ) ) . build ( ) ; javaFile . writeTo ( filer ) ;


signature:
public class Barbershop { /** * This generates the actual style ( ) method implementation for the $ $ Barbershop class
 * @ return A complete MethodSpec implementation for the class ' s style ( ) method . */
private MethodSpec generateStyleMethod ( ) { } }

implementation:
MethodSpec . Builder builder = MethodSpec . methodBuilder ( "style" ) . addAnnotation ( Override . class ) . addModifiers ( Modifier . PUBLIC ) . returns ( void . class ) . addParameter ( TypeVariableName . get ( "T" ) , "target" , Modifier . FINAL ) . addParameter ( AttributeSet . class , "set" , Modifier . FINAL ) . addParameter ( int [ ] . class , "attrs" , Modifier . FINAL ) . addParameter ( int . class , "defStyleAttr" , Modifier . FINAL ) . addParameter ( int . class , "defStyleRes" , Modifier . FINAL ) ; if ( parentBarbershop != null ) { builder . beginControlFlow ( "if (!super.hasStyled(target))" ) . addStatement ( "super.style(target, set, attrs, defStyleAttr, defStyleRes)" ) . addStatement ( "return" ) . endControlFlow ( ) ; } // Update our latest target
builder . addStatement ( "this.lastStyledTargets.add(target)" ) ; // Don ' t do anything if there ' s no AttributeSet instance
builder . beginControlFlow ( "if (set == null)" ) . addStatement ( "return" ) . endControlFlow ( ) ; if ( ! styleableBindings . isEmpty ( ) ) { if ( hasDefaults ) { builder . addStatement ( "$T res = target.getContext().getResources()" , Resources . class ) ; } // Proceed with obtaining the TypedArray if we got here
builder . addStatement ( "$T a = target.getContext().obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes)" , TypedArray . class ) ; builder . addCode ( "// Retrieve custom attributes\n" ) ; for ( StyleableBinding binding : styleableBindings . values ( ) ) { if ( binding . kind == RES_ID && binding . hasDefaultValue ( ) && ! binding . isRequired ) { // No overhead in resource retrieval for these , so no need to wrap in a hasValue check
builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( "a." ) ) ; continue ; } // Wrap the styling with if - statement to check if there ' s a value first , this way we can
// keep existing default values if there isn ' t one and don ' t overwrite them .
builder . beginControlFlow ( "if (a.hasValue($L))" , binding . id ) ; builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( "a." ) ) ; if ( binding . isRequired ) { builder . nextControlFlow ( "else" ) ; builder . addStatement ( "throw new $T(\"Missing required attribute \'$L\' while styling \'$L\'\")" , IllegalStateException . class , binding . name , targetClass ) ; } else if ( binding . hasDefaultValue ( ) ) { builder . nextControlFlow ( "else" ) ; if ( binding . kind != FRACTION && binding . kind != DIMEN && ( "float" . equals ( binding . type ) || "java.lang.Float" . equals ( binding . type ) ) ) { // Getting a float from resources is nasty
builder . addStatement ( generateSetterStatement ( binding ) , binding . name , "Barber.resolveFloatResource(res, " + binding . defaultValue + ")" ) ; } else if ( "android.graphics.drawable.Drawable" . equals ( binding . type ) ) { // Compatibility using ResourcesCompat . getDrawable ( . . . )
builder . addStatement ( generateSetterStatement ( binding ) , binding . name , "android.support.v4.content.res.ResourcesCompat.getDrawable(res, " + binding . defaultValue + ", target.getContext().getTheme())" ) ; } else { builder . addStatement ( generateSetterStatement ( binding ) , binding . name , generateResourceStatement ( binding , "res." , true ) ) ; } } builder . endControlFlow ( ) ; } builder . addStatement ( "a.recycle()" ) ; } if ( ! androidAttrBindings . isEmpty ( ) ) { builder . addCode ( "// Retrieve android attr values\n" ) ; for ( AndroidAttrBinding binding : androidAttrBindings . values ( ) ) { builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( "set." ) ) ; } } return builder . build ( ) ;


signature:
public class Barbershop { /** * Remove the last param if there are multiple , used for when we want to adapt a resource getter
 * to one used with { @ link Resources } */
private static String chompLastParam ( String input ) { } }

implementation: int lastCommaIndex = input . lastIndexOf ( ',' ) ; if ( lastCommaIndex == - 1 ) { return input ; } else { return input . substring ( 0 , lastCommaIndex ) + ")" ; }


signature:
public class TrieWriter { /** * Write BitVector01Divider to OutputStream . This method doesn ' t care about
 * r0 and r1 . Caller must write these bvs .
 * @ param divider
 * @ throws IOException */
public void writeBitVector01Divider ( BitVector01Divider divider ) throws IOException { } }

implementation: dos . writeBoolean ( divider . isFirst ( ) ) ; dos . writeBoolean ( divider . isZeroCounting ( ) ) ;


signature:
public class BitVectorUtil { /** * Append bits from bit string . The " bit string " is the array
 * of string that contains 8 characters which is ' 0 ' or ' 1 ' .
 * @ param bv bit vector
 * @ param bs the array of bit string */
public static void appendBitStrings ( BitVector bv , String [ ] bs ) { } }

implementation: for ( String s : bs ) { if ( s . length ( ) != 8 ) throw new RuntimeException ( "The length of bit string must be 8  while " + s . length ( ) ) ; for ( char c : s . toCharArray ( ) ) { if ( c == '0' ) bv . append0 ( ) ; else if ( c == '1' ) bv . append1 ( ) ; else throw new RuntimeException ( "invalid char '" + c + "' for bit string." ) ; } }


signature:
public class MultilayerPatriciaTrie { /** * @ Override
 * public Iterable < String > commonPrefixSearch ( String query ) {
 * List < String > ret = new ArrayList < String > ( ) ;
 * char [ ] queryChars = query . toCharArray ( ) ;
 * int cur = 0;
 * Node node = root ;
 * while ( node ! = null ) {
 * char [ ] letters = node . getLetters ( ) ;
 * if ( letters . length > ( queryChars . length - cur ) ) return ret ;
 * for ( int i = 0 ; i < letters . length ; i + + ) {
 * if ( letters [ i ] ! = queryChars [ cur + i ] ) return ret ;
 * if ( node . isTerminate ( ) ) {
 * ret . add ( new String ( queryChars , 0 , cur + letters . length ) ) ;
 * cur + = letters . length ;
 * if ( queryChars . length = = cur ) return ret ;
 * node = node . getChild ( queryChars [ cur ] ) ;
 * return ret ; */
private static void enumLetters ( org . trie4j . Node node , String prefix , List < String > letters ) { } }

implementation: org . trie4j . Node [ ] children = node . getChildren ( ) ; if ( children == null ) return ; for ( org . trie4j . Node child : children ) { String text = prefix + new String ( child . getLetters ( ) ) ; if ( child . isTerminate ( ) ) letters . add ( text ) ; enumLetters ( child , text , letters ) ; }


signature:
public class BitVector01Divider { /** * Read data from InputStream . This method doesn ' t care about
 * r0 and r1 . Caller must load these bvs and set through setR0 and setR1.
 * @ param is
 * @ throws IOException */
public void readFrom ( InputStream is ) throws IOException { } }

implementation: DataInputStream dis = new DataInputStream ( is ) ; first = dis . readBoolean ( ) ; zeroCounting = dis . readBoolean ( ) ;


signature:
public class MTGAPI { /** * Make an HTTP GET request to the given path and map the object under the
 * given key in the JSON of the response to the Java { @ link Class } of type
 * { @ link TYPE } .
 * @ param path Controlled by what is calling the function , currently " sets " or " cards "
 * depending on the calling class .
 * @ param key The key for the JSON element we are looking for .
 * @ param expectedClass The class type we are expecting to get back .
 * @ return Object of the requested type if found . */
protected static < TYPE > TYPE get ( String path , String key , Class < TYPE > expectedClass ) { } }

implementation: Gson deserializer = new GsonBuilder ( ) . create ( ) ; JsonObject jsonObject = getJsonObject ( path , deserializer ) . get ( 0 ) ; return deserializer . fromJson ( jsonObject . get ( key ) , expectedClass ) ;


signature:
public class MTGAPI { /** * Make an HTTP GET request to the given path and map the array under the
 * given key in the JSON of the response to a { @ link List } of type
 * { @ link TYPE } .
 * @ param path Controlled by what is calling the function , currently " sets " or " cards "
 * depending on the calling class .
 * @ param key The key for the JSON element we are looking for .
 * @ param expectedClass The class type we are expecting to get back .
 * @ return a { @ link List } of { @ link TYPE } */
protected static < TYPE > List < TYPE > getList ( String path , String key , Class < TYPE > expectedClass ) { } }

implementation: Gson deserializer = new GsonBuilder ( ) . create ( ) ; List < TYPE > toReturn = new ArrayList < > ( ) ; List < JsonObject > jsonObjectList = getJsonObject ( path , deserializer ) ; for ( JsonObject jsonObject : jsonObjectList ) { for ( JsonElement jsonElement : jsonObject . get ( key ) . getAsJsonArray ( ) ) { toReturn . add ( deserializer . fromJson ( jsonElement , expectedClass ) ) ; } } return toReturn ;


signature:
public class MTGAPI { /** * Deserialize the object to the type expected .
 * @ param path Controlled by what is calling the function , currently " sets " or " cards "
 * depending on the calling class .
 * @ param deserializer { @ link Gson } object that will be used to deserialize the JSON returned
 * from the web API .
 * @ return The parsed { @ link JsonObject } */
private static List < JsonObject > getJsonObject ( String path , Gson deserializer ) { } }

implementation: String url = String . format ( "%s/%s" , ENDPOINT , path ) ; Request request = new Request . Builder ( ) . url ( url ) . build ( ) ; Response response ; try { response = CLIENT . newCall ( request ) . execute ( ) ; ArrayList < JsonObject > objectList = new ArrayList < > ( ) ; String linkHeader = response . headers ( ) . get ( "Link" ) ; if ( linkHeader == null || linkHeader . isEmpty ( ) || path . contains ( "page=" ) ) { objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; return objectList ; } else { int numberOfPages = 0 ; String [ ] linkStrings = linkHeader . split ( DELIM_LINK ) ; List < String [ ] > paramList = new ArrayList < > ( ) ; for ( String link : linkStrings ) { paramList . add ( link . split ( DELIM_LINK_PARAM ) ) ; } for ( String [ ] params : paramList ) { if ( params [ 1 ] . contains ( "last" ) ) { Matcher matcher = Pattern . compile ( "page=[0-9]+" ) . matcher ( params [ 0 ] ) ; numberOfPages = ( matcher . find ( ) ) ? Integer . parseInt ( matcher . group ( ) . substring ( 5 ) ) : 0 ; } } objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; if ( ! url . contains ( "?" ) ) { url += "?" ; } for ( int i = 1 ; i <= numberOfPages ; i ++ ) { request = new Request . Builder ( ) . url ( url + "&page=" + i ) . build ( ) ; response = CLIENT . newCall ( request ) . execute ( ) ; objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; } return objectList ; } } catch ( IOException e ) { throw new HttpRequestFailedException ( e ) ; }


signature:
public class MTGAPI { /** * Get the list of objects with a filter if there is anything that matches the filters .
 * @ param path Controlled by what is calling the function , currently " sets " or " cards "
 * depending on the calling class .
 * @ param key The key for the JSON element we are looking for .
 * @ param expectedClass The class type we are expecting to get back .
 * @ param filters List of filters we want to apply to the search , you can see a full list of
 * accepted filters at < a href = " https : / / docs . magicthegathering . io / # overview " > the web API docs < / a >
 * @ return List of found cards . */
protected static < TYPE > List < TYPE > getList ( String path , String key , Class < TYPE > expectedClass , List < String > filters ) { } }

implementation: StringBuilder tempPath = new StringBuilder ( path ) ; tempPath . append ( "?" ) ; for ( String filter : filters ) { tempPath . append ( filter ) . append ( '&' ) ; } return getList ( tempPath . substring ( 0 , tempPath . length ( ) - 1 ) , key , expectedClass ) ;


signature:
public class CardAPI { /** * Get all the { @ link Card } that match a certain filter .
 * @ param filters List of filters supported by the web API
 * @ return List of all matching { @ link Card } s .
 * @ see < a href = " https : / / docs . magicthegathering . io / # cards " >
 * https : / / docs . magicthegathering . io / # cards < / a > */
public static List < Card > getAllCards ( List < String > filters ) { } }

implementation: return getList ( RESOURCE_PATH , "cards" , Card . class , filters ) ;


signature:
public class SetAPI { /** * Returns a { @ link MtgSet } based on the given set code .
 * @ param setCode Code to find the specific set . */
public static MtgSet getSet ( String setCode ) { } }

implementation: String path = String . format ( "%s/%s/" , RESOURCE_PATH , setCode ) ; MtgSet returnSet = get ( path , "set" , MtgSet . class ) ; if ( returnSet != null ) { returnSet . setCards ( CardAPI . getAllCards ( new LinkedList < > ( Collections . singletonList ( "set=" + setCode ) ) ) ) ; } return returnSet ;


signature:
public class SetAPI { /** * The method that will generate a booster for the selected { @ link MtgSet }
 * @ param setCode Code of which set you want a booster for .
 * @ return the randomized booster for the set . */
public static List < Card > getBooster ( String setCode ) { } }

implementation: String path = String . format ( "%s/%s/%s/" , RESOURCE_PATH , setCode , "booster" ) ; return getList ( path , "cards" , Card . class ) ;