signature:
public class InstructionListUtils { /** * Replace instruction ih in list il with the instructions in new _ il . If new _ il is null , do
 * nothing .
 * @ param mg MethodGen containing the instruction handle
 * @ param il InstructionList containing ih
 * @ param ih InstructionHandle indicating where to insert new code
 * @ param new _ il InstructionList holding the new code */
protected final void replace_instructions ( MethodGen mg , InstructionList il , InstructionHandle ih , @ Nullable InstructionList new_il ) { } }

implementation:
if ( new_il == null ) { return ; } InstructionHandle new_end ; InstructionHandle new_start ; int old_length = ih . getInstruction ( ) . getLength ( ) ; new_il . setPositions ( ) ; InstructionHandle end = new_il . getEnd ( ) ; int new_length = end . getPosition ( ) + end . getInstruction ( ) . getLength ( ) ; debug_instrument . log ( "  replace_inst: %s %d%n%s%n" , ih , new_il . getLength ( ) , new_il ) ; print_il ( ih , "Before replace_inst" ) ; // If there is only one new instruction , just replace it in the handle
if ( new_il . getLength ( ) == 1 ) { ih . setInstruction ( new_il . getEnd ( ) . getInstruction ( ) ) ; if ( old_length == new_length ) { // no possible changes downstream , so we can exit now
return ; } print_stack_map_table ( "replace_inst_with_single_inst B" ) ; il . setPositions ( ) ; new_end = ih ; // Update stack map for change in length of instruction bytes .
update_stack_map_offset ( ih . getPosition ( ) , ( new_length - old_length ) ) ; // We need to see if inserting the additional instructions caused
// a change in the amount of switch instruction padding bytes .
// If so , we may need to update the corresponding stackmap .
modify_stack_maps_for_switches ( new_end , il ) ; } else { print_stack_map_table ( "replace_inst_with_inst_list B" ) ; // We are inserting more than one instruction .
// Get the start and end handles of the new instruction list .
new_end = new_il . getEnd ( ) ; new_start = il . insert ( ih , new_il ) ; il . setPositions ( ) ; // Just in case there is a switch instruction in new _ il we need
// to recalculate new _ length as the padding may have changed .
new_length = new_end . getNext ( ) . getPosition ( ) - new_start . getPosition ( ) ; // Move all of the branches from the old instruction to the new start
il . redirectBranches ( ih , new_start ) ; print_il ( new_end , "replace_inst #1" ) ; // Move other targets to the new instuctions .
if ( ih . hasTargeters ( ) ) { for ( InstructionTargeter it : ih . getTargeters ( ) ) { if ( it instanceof LineNumberGen ) { it . updateTarget ( ih , new_start ) ; } else if ( it instanceof LocalVariableGen ) { it . updateTarget ( ih , new_end ) ; } else if ( it instanceof CodeExceptionGen ) { CodeExceptionGen exc = ( CodeExceptionGen ) it ; if ( exc . getStartPC ( ) == ih ) exc . updateTarget ( ih , new_start ) ; else if ( exc . getEndPC ( ) == ih ) exc . updateTarget ( ih , new_end ) ; else if ( exc . getHandlerPC ( ) == ih ) exc . setHandlerPC ( new_start ) ; else System . out . printf ( "Malformed CodeException: %s%n" , exc ) ; } else { System . out . printf ( "unexpected target %s%n" , it ) ; } } } print_il ( new_end , "replace_inst #2" ) ; // Remove the old handle . There should be no targeters left to it .
try { il . delete ( ih ) ; } catch ( Exception e ) { System . out . printf ( "Can't delete instruction: %s at %s%n" , mg . getClassName ( ) , mg . getName ( ) ) ; throw new Error ( "Can't delete instruction" , e ) ; } // Need to update instruction address due to delete above .
il . setPositions ( ) ; print_il ( new_end , "replace_inst #3" ) ; if ( needStackMap ) { // Before we look for branches in the inserted code we need
// to update any existing stack maps for locations in the old
// code that are after the inserted code .
update_stack_map_offset ( new_start . getPosition ( ) , ( new_length - old_length ) ) ; // We need to see if inserting the additional instructions caused
// a change in the amount of switch instruction padding bytes .
// If so , we may need to update the corresponding stackmap .
modify_stack_maps_for_switches ( new_end , il ) ; print_stack_map_table ( "replace_inst_with_inst_list C" ) ; // Look for branches within the new il ; i . e . , both the source
// and target must be within the new il . If we find any , the
// target will need a stack map entry .
// This situation is caused by a call to " instrument _ object _ call " .
InstructionHandle nih = new_start ; int target_count = 0 ; int target_offsets [ ] = new int [ 2 ] ; // see note below for why ' 2'
// Any targeters on the first instruction will be from ' outside '
// the new il so we start with the second instruction . ( We already
// know there is more than one instruction in the new il . )
nih = nih . getNext ( ) ; // We assume there is more code after the new il insertion point
// so this getNext will not fail .
new_end = new_end . getNext ( ) ; while ( nih != new_end ) { if ( nih . hasTargeters ( ) ) { for ( InstructionTargeter it : nih . getTargeters ( ) ) { if ( it instanceof BranchInstruction ) { target_offsets [ target_count ++ ] = nih . getPosition ( ) ; debug_instrument . log ( "New branch target: %s %n" , nih ) ; } } } nih = nih . getNext ( ) ; } print_il ( new_end , "replace_inst #4" ) ; if ( target_count != 0 ) { // Currently , target _ count is always 2 ; but code is
// written to allow more .
int cur_loc = new_start . getPosition ( ) ; int orig_size = stack_map_table . length ; StackMapEntry [ ] new_stack_map_table = new StackMapEntry [ orig_size + target_count ] ; // Calculate the operand stack value ( s ) for revised code .
mg . setMaxStack ( ) ; StackTypes stack_types = bcel_calc_stack_types ( mg ) ; OperandStack stack ; // Find last stack map entry prior to first new branch target ;
// returns - 1 if there isn ' t one . Also sets running _ offset and number _ active _ locals .
// The ' + 1 ' below means new _ index points to the first stack map entry after our
// inserted code . There may not be one ; in which case new _ index = = orig _ size .
int new_index = find_stack_map_index_before ( target_offsets [ 0 ] ) + 1 ; // The Java compiler can ' simplfy ' the generated class file by not
// inserting a stack map entry every time a local is defined if
// that stack map entry is not needed as a branch target . Thus ,
// there can be more live locals than defined by the stack maps .
// This leads to serious complications if we wish to insert instrumentation
// code , that contains internal branches and hence needs stack
// map entries , into a section of code with ' extra ' live locals .
// If we don ' t include these extra locals in our inserted stack
// map entries and they are subsequently referenced , that would
// cause a verification error . But if we do include them the locals
// state might not be correct when execution reaches the first
// stack map entry after our inserted code and that
// would also cause a verification error . Dicey stuff .
// I think one possibllity would be to insert a nop instruction
// with a stack map of CHOP right after the last use of an ' extra '
// local prior to the next stack map entry . An interesting alternative
// might be , right as we start to process a method , make a pass over
// the byte codes and add any ' missing ' stack maps . This would
// probably be too heavy as most instrumentation does not contain branches .
// Not sure which of these two methods is ' easier ' at this point .
// I ' m going to try a simplification . If there are ' extra ' locals
// and we need to generate a FULL stack map - then go through and
// make all subsequent StackMaps FULL as well .
// The inserted code has pushed an object reference on the stack .
// The StackMap ( s ) we create as targets of an internal branch
// must account for this item . Normally , we would use
// SAME _ LOCALS _ 1 _ STACK _ ITEM _ FRAME for this case , but there is a
// possibility that the compiler has already allocated extra local items
// that it plans to identify in a subsequent StackMap APPEND entry .
// First , lets calculate the number and types of the live locals .
StackMapType [ ] local_map_types = calculate_live_local_types ( mg , cur_loc ) ; int local_map_index = local_map_types . length ; // local _ map _ index now contains the number of live locals .
// number _ active _ locals has been calculated from the existing StackMap .
// If these two are equal , we should be ok .
int number_extra_locals = local_map_index - number_active_locals ; // lets do a sanity check
assert number_extra_locals >= 0 : "invalid extra locals count: " + number_active_locals + ", " + local_map_index ; // Copy any existing stack maps prior to inserted code .
System . arraycopy ( stack_map_table , 0 , new_stack_map_table , 0 , new_index ) ; boolean need_full_maps = false ; for ( int i = 0 ; i < target_count ; i ++ ) { stack = stack_types . get ( target_offsets [ i ] ) ; debug_instrument . log ( "stack: %s %n" , stack ) ; if ( number_extra_locals == 0 && stack . size ( ) == 1 && ! need_full_maps ) { // the simple case
StackMapType stack_map_type0 = generate_StackMapType_from_Type ( stack . peek ( 0 ) ) ; StackMapType [ ] stack_map_types0 = { stack_map_type0 } ; new_stack_map_table [ new_index + i ] = new StackMapEntry ( Const . SAME_LOCALS_1_STACK_ITEM_FRAME , 0 , // byte _ code _ offset set below
null , stack_map_types0 , pool . getConstantPool ( ) ) ; } else { // need a FULL _ FRAME stack map entry
need_full_maps = true ; new_stack_map_table [ new_index + i ] = new StackMapEntry ( Const . FULL_FRAME , 0 , // byte _ code _ offset set below
calculate_live_local_types ( mg , target_offsets [ i ] ) , calculate_live_stack_types ( stack ) , pool . getConstantPool ( ) ) ; } // now set the offset from the previous Stack Map entry to our new one .
new_stack_map_table [ new_index + i ] . updateByteCodeOffset ( target_offsets [ i ] - ( running_offset + 1 ) ) ; running_offset = target_offsets [ i ] ; } // now copy remaining ' old ' stack maps
int remainder = orig_size - new_index ; if ( remainder > 0 ) { // before we copy , we need to update first map after insert
l1 : while ( nih != null ) { if ( nih . hasTargeters ( ) ) { for ( InstructionTargeter it : nih . getTargeters ( ) ) { if ( it instanceof BranchInstruction ) { stack_map_table [ new_index ] . updateByteCodeOffset ( nih . getPosition ( ) - target_offsets [ target_count - 1 ] - 1 - stack_map_table [ new_index ] . getByteCodeOffset ( ) ) ; break l1 ; } else if ( it instanceof CodeExceptionGen ) { CodeExceptionGen exc = ( CodeExceptionGen ) it ; if ( exc . getHandlerPC ( ) == nih ) { stack_map_table [ new_index ] . updateByteCodeOffset ( nih . getPosition ( ) - target_offsets [ target_count - 1 ] - 1 - stack_map_table [ new_index ] . getByteCodeOffset ( ) ) ; break l1 ; } } } } nih = nih . getNext ( ) ; } // Now we can copy the remaining stack map entries .
if ( need_full_maps ) { // Must convert all remaining stack map entries to FULL .
while ( remainder > 0 ) { int stack_map_offset = stack_map_table [ new_index ] . getByteCodeOffset ( ) ; running_offset = running_offset + stack_map_offset + 1 ; stack = stack_types . get ( running_offset ) ; // System . out . printf ( " running _ offset : % d , stack : % s % n " , running _ offset , stack ) ;
new_stack_map_table [ new_index + target_count ] = new StackMapEntry ( Const . FULL_FRAME , stack_map_offset , calculate_live_local_types ( mg , running_offset ) , calculate_live_stack_types ( stack ) , pool . getConstantPool ( ) ) ; new_index ++ ; remainder -- ; } } else { System . arraycopy ( stack_map_table , new_index , new_stack_map_table , new_index + target_count , remainder ) ; } } stack_map_table = new_stack_map_table ; } } } debug_instrument . log ( "%n" ) ; print_il ( new_end , "replace_inst #5" ) ;


signature:
public class RawTcpdumpReader { /** * private static String macToString ( byte [ ] mac ) {
 * StringBuilder sb = new StringBuilder ( 18 ) ;
 * for ( byte b : mac ) {
 * if ( sb . length ( ) > 0)
 * sb . append ( ' : ' ) ;
 * sb . append ( String . format ( " % 02x " , b ) ) ;
 * return sb . toString ( ) ; */
@ Override public void read ( InputStream input , Handler handler ) throws IOException { } }

implementation:
@ SuppressWarnings ( "resource" ) LittleEndianDataInputStream in = new LittleEndianDataInputStream ( input ) ; LOGGER . debug ( "Reading tcpdump stream" ) ; long header = in . readInt ( ) & 0xFFFFFFFF ; if ( header != 0xA1B2C3D4 ) { throw new IOException ( "Bad header: 0x" + Long . toHexString ( header ) ) ; } int majorVersionNumber = in . readUnsignedShort ( ) ; int minorVersionNumber = in . readUnsignedShort ( ) ; long zone = in . readInt ( ) & 0xFFFFFFFF ; @ SuppressWarnings ( "unused" ) long timestampAccuracy = in . readInt ( ) & 0xFFFFFFFF ; long maxCaptureLength = in . readInt ( ) & 0xFFFFFFFF ; long dataLinkType = in . readInt ( ) & 0xFFFFFFFF ; LOGGER . debug ( "Tcpdump header recognized (version = {}/{}, zone = {}, maxCaptureLength = {}, dataLinkType = {})" , majorVersionNumber , minorVersionNumber , zone , maxCaptureLength , dataLinkType ) ; /* https : / / wiki . wireshark . org / Development / LibpcapFileFormat
 typedef struct pcap _ hdr _ s {
 guint32 magic _ number ; / * magic number * /
 guint16 version _ major ; / * major version number * /
 guint16 version _ minor ; / * minor version number * /
 gint32 thiszone ; / * GMT to local correction * /
 guint32 sigfigs ; / * accuracy of timestamps * /
 guint32 snaplen ; / * max length of captured packets , in octets * /
 guint32 network ; / * data link type * /
 } pcap _ hdr _ t ; */
while ( true ) { try { // % % LOGGER . debug ( " Tcpdump loop , step 1 " ) ;
/* typedef struct pcaprec _ hdr _ s {
 guint32 ts _ sec ; / * timestamp seconds * /
 guint32 ts _ usec ; / * timestamp microseconds * /
 guint32 incl _ len ; / * number of octets of packet saved in file * /
 guint32 orig _ len ; / * actual length of packet * /
 } pcaprec _ hdr _ t ; */
long timestampSeconds = in . readInt ( ) & 0xFFFFFFFF ; long timestampMicroSeconds = in . readInt ( ) & 0xFFFFFFFF ; @ SuppressWarnings ( "unused" ) int savedLength = in . readInt ( ) ; int actualLength = in . readInt ( ) ; double timestamp = ( ( double ) timestampSeconds ) + ( ( ( double ) timestampMicroSeconds ) / 1_000_000d ) ; // sec , usec
byte [ ] destinationMac = new byte [ 6 ] ; byte [ ] sourceMac = new byte [ 6 ] ; in . readFully ( destinationMac ) ; in . readFully ( sourceMac ) ; // % % System . out . println ( " mac0 = " + macToString ( destinationMac ) ) ;
// % % System . out . println ( " mac1 = " + macToString ( sourceMac ) ) ;
// IPV4 UNICAST : 0800
// IPV6 UNICAST : 86dd
// IPV4 MULTICAST : 00000800
// IPV6 MULTICAST : 000086dd
byte [ ] unused = new byte [ any ? 4 : 2 ] ; in . readFully ( unused ) ; LOGGER . trace ( "Tcpdump packet ({} bytes)" , actualLength ) ; int l = actualLength - destinationMac . length - sourceMac . length - unused . length ; if ( l > MAX_SIZE ) { throw new IOException ( "Packet too big: " + l ) ; } byte [ ] bytes = new byte [ l ] ; in . readFully ( bytes ) ; IpPacketReadUtils . read ( timestamp , bytes , 0 , bytes . length , handler ) ; } catch ( EOFException eof ) { break ; } }


signature:
public class Supervision { /** * TODO Change this config key */
private static double floorTime ( double now , double period ) { } }

implementation: double precision = 1000d ; long t = ( long ) ( now * precision ) ; long d = ( long ) ( period * precision ) ; return ( t - ( t % d ) ) / precision ;


signature:
public class UncipheringConnection { /** * Initial IV client to server : HASH ( K | | H | | " A " | | session _ id )
 * Initial IV server to client : HASH ( K | | H | | " B " | | session _ id )
 * Encryption key client to server : HASH ( K | | H | | " C " | | session _ id )
 * Encryption key server to client : HASH ( K | | H | | " D " | | session _ id )
 * Integrity key client to server : HASH ( K | | H | | " E " | | session _ id )
 * Integrity key server to client : HASH ( K | | H | | " F " | | session _ id ) */
public void init ( String encryptionAlgorithm , String cipherAlgorithm , int keyLength , String macAlgorithm , byte [ ] K , byte [ ] H , byte [ ] sessionId ) throws GeneralSecurityException { } }

implementation: MessageDigest sha = MessageDigest . getInstance ( "SHA-1" ) ; sha . reset ( ) ; sha . update ( new SshPacketBuilder ( ) . writeMpInt ( K ) . append ( H ) . writeByte ( 'B' ) . append ( sessionId ) . finish ( ) ) ; byte [ ] iv = sha . digest ( ) ; sha . reset ( ) ; sha . update ( new SshPacketBuilder ( ) . writeMpInt ( K ) . append ( H ) . writeByte ( 'D' ) . append ( sessionId ) . finish ( ) ) ; byte [ ] cipherKey = sha . digest ( ) ; try { cipher = Cipher . getInstance ( encryptionAlgorithm + "/" + cipherAlgorithm + "/NoPadding" ) ; iv = CipherUtils . expandKey ( K , H , iv , sha , cipher . getBlockSize ( ) ) ; cipherKey = CipherUtils . expandKey ( K , H , cipherKey , sha , keyLength ) ; iv = CipherUtils . shrinkKey ( iv , cipher . getBlockSize ( ) ) ; cipherKey = CipherUtils . shrinkKey ( cipherKey , keyLength ) ; cipher . init ( Cipher . DECRYPT_MODE , new SecretKeySpec ( cipherKey , encryptionAlgorithm ) , new IvParameterSpec ( iv ) ) ; sha . reset ( ) ; sha . update ( new SshPacketBuilder ( ) . writeMpInt ( K ) . append ( H ) . writeByte ( 'F' ) . append ( sessionId ) . finish ( ) ) ; byte [ ] macKey = sha . digest ( ) ; mac = Mac . getInstance ( macAlgorithm ) ; macKey = CipherUtils . expandKey ( K , H , macKey , sha , mac . getMacLength ( ) ) ; macKey = CipherUtils . shrinkKey ( macKey , mac . getMacLength ( ) ) ; mac . init ( new SecretKeySpec ( macKey , macAlgorithm ) ) ; firstBuffer = ByteBuffer . allocate ( cipher . getBlockSize ( ) ) ; macBuffer = ByteBuffer . allocate ( mac . getMacLength ( ) ) ; } catch ( GeneralSecurityException e ) { cipher = null ; mac = null ; throw e ; }


signature:
public class HttpService { /** * private static final class HandlerElement {
 * public HttpServiceHandler handler ;
 * public double streamingRate = Double . NaN ; */
public static Builder builder ( ) { } }

implementation:
return new Builder ( ) { private final ImmutableList . Builder < HttpServiceHandler > handlers = ImmutableList . builder ( ) ; private int threads = DEFAULT_THREADS ; @ Override public Builder threading ( int threads ) { this . threads = threads ; return this ; } @ Override public Builder register ( HttpServiceHandler handler ) { // % % final HandlerElement h = new HandlerElement ( ) ;
// % % h . handler = handler ;
handlers . add ( handler ) ; /* return new HandlerBuilder ( ) {
 @ Override
 public HandlerBuilder limit ( double streamingRate ) {
 h . streamingRate = streamingRate ;
 return this ; */
return this ; } @ Override public HttpService build ( ) { return new HttpService ( threads , handlers . build ( ) ) ; } } ;


signature:
public class HttpRequest { /** * public static HttpRequest of ( String url ) {
 * return of ( url , HttpMethod . GET , ImmutableMultimap . < String , String > of ( ) ) ;
 * public static HttpRequest of ( String url , HttpMethod method , ImmutableMultimap < String , String > headers ) {
 * String protocol ;
 * boolean secure ;
 * int defaultPort ;
 * if ( url . startsWith ( HttpSpecification . PROTOCOL ) ) {
 * protocol = HttpSpecification . PROTOCOL ;
 * secure = false ;
 * defaultPort = HttpSpecification . DEFAULT _ PORT ;
 * } else if ( url . startsWith ( HttpSpecification . SECURE _ PROTOCOL ) ) {
 * protocol = HttpSpecification . SECURE _ PROTOCOL ;
 * secure = true ;
 * defaultPort = HttpSpecification . DEFAULT _ SECURE _ PORT ;
 * } else {
 * throw new IllegalArgumentException ( " URL must starts with " + HttpSpecification . PROTOCOL + " or " + HttpSpecification . SECURE _ PROTOCOL ) ;
 * int i = url . indexOf ( HttpSpecification . PATH _ SEPARATOR , protocol . length ( ) ) ;
 * if ( i < 0 ) {
 * String a = url . substring ( protocol . length ( ) ) ;
 * int k = a . indexOf ( ' : ' ) ;
 * Address address ;
 * if ( k < 0 ) {
 * address = Address . of ( a , defaultPort ) ;
 * } else {
 * String h = a . substring ( 0 , k ) ;
 * int p = Integer . parseInt ( a . substring ( k + 1 ) ) ;
 * address = Address . of ( h , p ) ;
 * return new HttpRequest ( address , secure , method , String . valueOf ( HttpSpecification . PATH _ SEPARATOR ) , headers ) ;
 * } else {
 * String a = url . substring ( protocol . length ( ) , i ) ;
 * int k = a . indexOf ( ' : ' ) ;
 * Address address ;
 * if ( k < 0 ) {
 * address = Address . of ( a , defaultPort ) ;
 * } else {
 * String h = a . substring ( 0 , k ) ;
 * int p = Integer . parseInt ( a . substring ( k + 1 ) ) ;
 * address = Address . of ( h , p ) ;
 * return new HttpRequest ( address , secure , method , url . substring ( i ) , headers ) ; */
public static ImmutableList < String > path ( String path ) { } }

implementation: int i = path . indexOf ( HttpSpecification . PARAMETERS_START ) ; if ( i < 0 ) { i = path . indexOf ( HttpSpecification . HASH_SEPARATOR ) ; } else { int j = path . indexOf ( HttpSpecification . HASH_SEPARATOR ) ; if ( ( j >= 0 ) && ( j < i ) ) { i = j ; } } if ( i < 0 ) { i = path . length ( ) ; } String p = path . substring ( 0 , i ) ; if ( p . charAt ( 0 ) != HttpSpecification . PATH_SEPARATOR ) { throw new IllegalArgumentException ( "Path must start with '" + HttpSpecification . PATH_SEPARATOR + "': " + p ) ; } String s = p . substring ( 1 ) ; Deque < String > l = new LinkedList < > ( ) ; for ( String k : Splitter . on ( HttpSpecification . PATH_SEPARATOR ) . splitToList ( s ) ) { if ( k . isEmpty ( ) ) { continue ; } if ( k . equals ( "." ) ) { continue ; } if ( k . equals ( ".." ) ) { if ( ! l . isEmpty ( ) ) { l . removeLast ( ) ; } continue ; } l . add ( k ) ; } return ImmutableList . copyOf ( l ) ;


signature:
public class InternalQueue { /** * @ Override
 * public void waitFor ( ) {
 * Wait w = new Wait ( ) ;
 * execute ( w ) ;
 * w . waitFor ( ) ; */
@ Override public void close ( ) { } }

implementation: Thread t = new ClassThreadFactory ( InternalQueue . class ) . newThread ( new Runnable ( ) { @ Override public void run ( ) { try { Thread . sleep ( ( long ) ( WAIT_ON_CLOSE * 1000d ) ) ; } catch ( InterruptedException ie ) { } try { selector . close ( ) ; } catch ( IOException e ) { } selector . wakeup ( ) ; } } ) ; t . setDaemon ( true ) ; t . start ( ) ;


signature:
public class ContentLengthReader { /** * MUST sync - ly consume buffer */
@ Override public void received ( ByteBuffer buffer ) { } }

implementation: if ( ended ) { throw new IllegalStateException ( ) ; } if ( ( countRead + buffer . remaining ( ) ) > contentLength ) { ByteBuffer b = buffer . duplicate ( ) ; int l = ( int ) ( contentLength - countRead ) ; b . limit ( b . position ( ) + l ) ; buffer . position ( buffer . position ( ) + l ) ; buffer = b ; } countRead += buffer . remaining ( ) ; if ( buffer . hasRemaining ( ) ) { wrappee . received ( buffer ) ; } if ( countRead == contentLength ) { ended = true ; wrappee . ended ( ) ; }


signature:
public class Ninio { /** * @ Override
 * public void close ( ) {
 * for ( Queues [ ] q : internalQueues ) {
 * for ( Queues internalQueue : q ) {
 * internalQueue . close ( ) ; */
public Queue register ( NinioPriority priority ) { } }

implementation: int i ; synchronized ( lock ) { i = index ; index ++ ; if ( index == THREADING ) { index = 0 ; } } return internalQueues [ priority . ordinal ( ) ] [ i ] . open ( ) ;


signature:
public class BerReader { /** * checked */
private static int doReadLength ( ByteBuffer buffer ) throws IOException { } }

implementation:
int lengthbyte = buffer . get ( ) & 0xFF ; if ( ( lengthbyte & BerConstants . ASN_BIT8 ) == BerConstants . ASN_BIT8 ) { lengthbyte &= ~ BerConstants . ASN_BIT8 ; if ( lengthbyte == 0 ) { throw new IOException ( "Indefinite lengths are not supported" ) ; } if ( lengthbyte > 4 ) { throw new IOException ( "Data length > 4 bytes are not supported" ) ; } int length = 0 ; for ( int i = 0 ; i < lengthbyte ; i ++ ) { length <<= 8 ; length |= buffer . get ( ) & 0xFF ; } if ( length < 0 ) { throw new IOException ( "SNMP does not support data lengths > 2^31" ) ; } return length ; } else { // Short asnlength
return lengthbyte ; }


signature:
public class BerReader { /** * TODO Check the OPAQUE UINT64 format */
private static long doReadLong ( ByteBuffer buffer , int length ) throws IOException { } }

implementation:
long value = 0L ; for ( int i = 0 ; i < length ; i ++ ) { int b = buffer . get ( ) & 0xFF ; if ( ( i == 0 ) && ( ( b & 0x80 ) == 0x80 ) ) { value = 0xFFFFFFFFL ; // Negative , in two ' s complement form
} value <<= 8 ; value |= b ; } return value ;


signature:
public class ChunkedReader { /** * MUST sync - ly consume buffer */
@ Override public void received ( ByteBuffer buffer ) { } }

implementation: if ( ended ) { throw new IllegalStateException ( ) ; } while ( true ) { while ( ! chunkHeaderRead ) { String line = lineReader . handle ( buffer ) ; if ( line == null ) { return ; } try { chunkLength = Integer . parseInt ( line , 16 ) ; } catch ( NumberFormatException e ) { ended = true ; failing . failed ( new IOException ( "Invalid chunk size: " + line ) ) ; return ; } chunkHeaderRead = true ; chunkCountRead = 0 ; } if ( chunkHeaderRead ) { if ( chunkCountRead < chunkLength ) { if ( ! buffer . hasRemaining ( ) ) { return ; } long toRead = chunkLength - chunkCountRead ; ByteBuffer d = buffer . duplicate ( ) ; if ( toRead >= 0 ) { if ( d . remaining ( ) > toRead ) { d . limit ( ( int ) ( buffer . position ( ) + toRead ) ) ; } } chunkCountRead += d . remaining ( ) ; buffer . position ( ( int ) ( buffer . position ( ) + d . remaining ( ) ) ) ; wrappee . received ( d ) ; } if ( chunkCountRead == chunkLength ) { while ( chunkHeaderRead ) { String line = lineReader . handle ( buffer ) ; if ( line == null ) { return ; } if ( ! line . isEmpty ( ) ) { ended = true ; failing . failed ( new IOException ( "Invalid chunk footer" ) ) ; return ; } chunkHeaderRead = false ; } if ( chunkLength == 0 ) { ended = true ; wrappee . ended ( ) ; return ; } } } }


signature:
public class Version3PacketBuilder { /** * private static Iterable < OidValue > single ( Oid oid ) {
 * List < OidValue > l = new LinkedList < > ( ) ;
 * l . add ( new OidValue ( oid , new Value ( ) {
 * @ Override
 * public BerPacket ber ( ) {
 * return new NullBerPacket ( ) ;
 * return l ; */
public static Version3PacketBuilder getBulk ( AuthRemoteEngine authEngine , int requestId , Oid oid , int bulkLength ) { } }

implementation: return new Version3PacketBuilder ( authEngine , requestId , BerConstants . GETBULK , bulkLength , oid ) ;


signature:
public class Extractor { /** * public String contents ( ) throws IOException {
 * StringBuilder b = null ;
 * if ( from . length = = 0 ) {
 * b = new StringBuilder ( ) ;
 * int [ ] iFrom = new int [ from . length ] ; / / Filled with zeros
 * int [ ] iTo = new int [ to . length ] ; / / Filled with zeros
 * while ( true ) {
 * int k = on . read ( ) ;
 * if ( k < 0 ) {
 * if ( b = = null ) {
 * return null ;
 * if ( to . length = = 0 ) {
 * return b . toString ( ) ;
 * return null ;
 * char c = ( char ) k ;
 * if ( b ! = null ) {
 * b . append ( c ) ;
 * if ( b = = null ) {
 * for ( int u = 0 ; u < iFrom . length ; u + + ) {
 * if ( c = = from [ u ] . charAt ( iFrom [ u ] ) ) {
 * iFrom [ u ] + + ;
 * if ( iFrom [ u ] = = from [ u ] . length ( ) ) {
 * b = new StringBuilder ( ) ;
 * break ;
 * } else if ( iFrom [ u ] > 0 ) {
 * iFrom [ u ] = 0;
 * if ( c = = from [ u ] . charAt ( iFrom [ u ] ) ) {
 * iFrom [ u ] + + ;
 * if ( iFrom [ u ] = = from [ u ] . length ( ) ) {
 * b = new StringBuilder ( ) ;
 * break ;
 * for ( int u = 0 ; u < iTo . length ; u + + ) {
 * if ( c = = to [ u ] . charAt ( iTo [ u ] ) ) {
 * iTo [ u ] + + ;
 * if ( iTo [ u ] = = to [ u ] . length ( ) ) {
 * if ( b = = null ) {
 * return null ;
 * b . delete ( b . length ( ) - to [ u ] . length ( ) , b . length ( ) ) ;
 * return b . toString ( ) ;
 * } else if ( iTo [ u ] > 0 ) {
 * iTo [ u ] = 0;
 * if ( c = = to [ u ] . charAt ( iTo [ u ] ) ) {
 * iTo [ u ] + + ;
 * if ( iTo [ u ] = = to [ u ] . length ( ) ) {
 * if ( b = = null ) {
 * return null ;
 * b . delete ( b . length ( ) - to [ u ] . length ( ) , b . length ( ) ) ;
 * return b . toString ( ) ; */
public Extractor extract ( ) throws IOException { } }

implementation:
// % % % % % LOGGER . debug ( " - - - > to = { } " , Arrays . asList ( to ) ) ;
int [ ] iFrom = new int [ from . length ] ; // Filled with zeros
int [ ] iTo = new int [ to . length ] ; // Filled with zeros
while ( true ) { int k = on . read ( ) ; if ( k < 0 ) { return null ; } char c = ( char ) k ; for ( StringBuilder b : accumulators ) { b . append ( c ) ; } if ( ignoreWhitespaces && Character . isWhitespace ( c ) ) { continue ; } for ( int u = 0 ; u < iFrom . length ; u ++ ) { if ( c == from [ u ] . charAt ( iFrom [ u ] ) ) { iFrom [ u ] ++ ; if ( iFrom [ u ] == from [ u ] . length ( ) ) { return new Extractor ( from [ u ] , Lists . newLinkedList ( accumulators ) ) . on ( on ) . to ( to ) . ignoreWhitespaces ( ignoreWhitespaces ) ; } } else if ( iFrom [ u ] > 0 ) { iFrom [ u ] = 0 ; if ( c == from [ u ] . charAt ( iFrom [ u ] ) ) { iFrom [ u ] ++ ; if ( iFrom [ u ] == from [ u ] . length ( ) ) { return new Extractor ( from [ u ] , Lists . newLinkedList ( accumulators ) ) . on ( on ) . to ( to ) . ignoreWhitespaces ( ignoreWhitespaces ) ; } } } } for ( int u = 0 ; u < iTo . length ; u ++ ) { if ( c == to [ u ] . charAt ( iTo [ u ] ) ) { iTo [ u ] ++ ; if ( iTo [ u ] == to [ u ] . length ( ) ) { if ( accumulator != null ) { accumulator . delete ( accumulator . length ( ) - to [ u ] . length ( ) , accumulator . length ( ) ) ; } return null ; } } else if ( iTo [ u ] > 0 ) { iTo [ u ] = 0 ; if ( c == to [ u ] . charAt ( iTo [ u ] ) ) { iTo [ u ] ++ ; if ( iTo [ u ] == to [ u ] . length ( ) ) { if ( accumulator != null ) { accumulator . delete ( accumulator . length ( ) - to [ u ] . length ( ) , accumulator . length ( ) ) ; } return null ; } } } } }


signature:
public class CipherUtils { /** * RFC 4253 7.2 . Output from Key Exchange
 * If the key length needed is longer than the output of the HASH , the
 * key is extended by computing HASH of the concatenation of K and H and
 * the entire key so far , and appending the resulting bytes ( as many as
 * HASH generates ) to the key . This process is repeated until enough
 * key material is available ; the key is taken from the beginning of
 * this value . In other words :
 * K1 = HASH ( K | | H | | X | | session _ id ) ( X is e . g . , " A " )
 * K2 = HASH ( K | | H | | K1)
 * K3 = HASH ( K | | H | | K1 | | K2)
 * key = K1 | | K2 | | K3 | | . . . */
public static byte [ ] expandKey ( byte [ ] K , byte [ ] H , byte [ ] key , MessageDigest hash , int requiredLength ) { } }

implementation: byte [ ] result = key ; while ( result . length < requiredLength ) { SshPacketBuilder buf = new SshPacketBuilder ( ) ; buf . writeMpInt ( K ) ; buf . append ( H ) ; buf . append ( result ) ; hash . update ( buf . finish ( ) ) ; byte [ ] d = hash . digest ( ) ; byte [ ] tmp = new byte [ result . length + d . length ] ; System . arraycopy ( result , 0 , tmp , 0 , result . length ) ; System . arraycopy ( d , 0 , tmp , result . length , d . length ) ; result = tmp ; } return result ;


signature:
public class ConfigUtils { /** * Application conf ( configure . conf is used over resource ) */
public static synchronized Config load ( Dependencies dependencies , String resource ) { } }

implementation: return load ( dependencies , resource , new Override ( ) ) ;


signature:
public class Trust { /** * private static class SavingTrustManager implements X509TrustManager {
 * private final X509TrustManager tm ;
 * private X509Certificate [ ] chain ;
 * SavingTrustManager ( X509TrustManager tm ) {
 * this . tm = tm ;
 * @ Override
 * public X509Certificate [ ] getAcceptedIssuers ( ) {
 * throw new UnsupportedOperationException ( ) ;
 * @ Override
 * public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException {
 * throw new UnsupportedOperationException ( ) ;
 * @ Override
 * public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException {
 * this . chain = chain ;
 * tm . checkServerTrusted ( chain , authType ) ; */
public PrivateKey getPrivateKey ( String alias , String password ) { } }

implementation: try { return ( PrivateKey ) ksKeys . getKey ( alias , password . toCharArray ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class StringHandler { /** * Beware , with the current algorithm , this function cannot find ' \ ' */
private static final int find ( boolean skipBlocks , String s , char toFind , int from ) { } }

implementation: int open = 0 ; boolean escaping = false ; for ( int i = from ; i < s . length ( ) ; i ++ ) { if ( escaping ) { escaping = false ; continue ; } char c = s . charAt ( i ) ; if ( c == '\\' ) { escaping = true ; continue ; } if ( ( open == 0 ) && ( c == toFind ) ) { return i ; } else if ( skipBlocks && ( c == '{' ) ) { open ++ ; } else if ( skipBlocks && ( c == '}' ) ) { open -- ; } } return - 1 ;


signature:
public class GzipReader { /** * MUST sync - ly consume buffer */
@ Override public void received ( ByteBuffer deflated ) { } }

implementation: if ( ended ) { throw new IllegalStateException ( ) ; } if ( deflated . remaining ( ) >= FOOTER_LENGTH ) { for ( ByteBuffer b : previewFooter ) { if ( ! read ( b ) ) { return ; } } previewFooter . clear ( ) ; currentPreviewFooterLength = 0 ; ByteBuffer deflatedKeepingFooter = deflated . duplicate ( ) ; deflatedKeepingFooter . limit ( deflatedKeepingFooter . limit ( ) - FOOTER_LENGTH ) ; deflated . position ( deflated . position ( ) + deflatedKeepingFooter . remaining ( ) ) ; if ( ! read ( deflatedKeepingFooter ) ) { return ; } currentPreviewFooterLength += deflated . remaining ( ) ; previewFooter . addLast ( deflated . duplicate ( ) ) ; deflated . position ( deflated . position ( ) + deflated . remaining ( ) ) ; return ; } else { currentPreviewFooterLength += deflated . remaining ( ) ; previewFooter . addLast ( deflated . duplicate ( ) ) ; deflated . position ( deflated . position ( ) + deflated . remaining ( ) ) ; int toFlush = FOOTER_LENGTH - currentPreviewFooterLength ; while ( toFlush > 0 ) { ByteBuffer b = previewFooter . getFirst ( ) ; ByteBuffer d = b . duplicate ( ) ; d . limit ( Math . min ( d . limit ( ) , toFlush ) ) ; b . position ( b . position ( ) + d . remaining ( ) ) ; toFlush -= d . remaining ( ) ; if ( ! read ( d ) ) { return ; } if ( ! b . hasRemaining ( ) ) { previewFooter . removeFirst ( ) ; } } }


signature:
public class TNettyTransport { /** * Reads from the shared input queue , blocking if there is not enough input
 * in the buffer . It ' s the only way we can emulate the synchronous nature of
 * TTransport using netty . */
@ Override public int read ( final byte [ ] output , final int offset , final int length ) throws TTransportException { } }

implementation: int read = 0 ; int index = offset ; int space = length - offset ; while ( space > 0 ) { byte aByte = readAsynchrously ( ) ; output [ index ] = aByte ; space -- ; index ++ ; read ++ ; } return read ;


signature:
public class TNettyTransport { /** * We need data to be written and flushed at once . */
@ Override public void flush ( ) throws TTransportException { } }

implementation: ChannelBuffer flush = ChannelBuffers . dynamicBuffer ( ) ; flush . writeBytes ( output ) ; channel . write ( flush ) . awaitUninterruptibly ( ) ;


signature:
public class WebSocketClientFactory { /** * Create a new WebSocket client
 * @ param url URL to connect to .
 * @ param callback Callback interface to receive events
 * @ return A WebSocket client . Call { @ link WebSocketClient # connect ( ) } to connect . */
public WebSocketClient newClient ( final URI url , final WebSocketCallback callback ) { } }

implementation: ClientBootstrap bootstrap = new ClientBootstrap ( socketChannelFactory ) ; String protocol = url . getScheme ( ) ; if ( ! protocol . equals ( "ws" ) && ! protocol . equals ( "wss" ) ) { throw new IllegalArgumentException ( "Unsupported protocol: " + protocol ) ; } final WebSocketClientHandler clientHandler = new WebSocketClientHandler ( bootstrap , url , callback ) ; bootstrap . setPipelineFactory ( new ChannelPipelineFactory ( ) { public ChannelPipeline getPipeline ( ) throws Exception { ChannelPipeline pipeline = Channels . pipeline ( ) ; pipeline . addLast ( "decoder" , new HttpResponseDecoder ( ) ) ; pipeline . addLast ( "encoder" , new HttpRequestEncoder ( ) ) ; pipeline . addLast ( "ws-handler" , clientHandler ) ; return pipeline ; } } ) ; return clientHandler ;


signature:
public class MainActivity_ListView_Express { /** * Inits an adapter with items , wrapping your adapter with a { @ link AdmobExpressAdapterWrapper } and setting the listview to this wrapper
 * FIRST OF ALL Please notice that the following code will work on a real devices but emulator ! */
private void initListViewItems ( ) { } }

implementation:
lvMessages = ( ListView ) findViewById ( R . id . lvMessages ) ; // creating your adapter , it could be a custom adapter as well
ArrayAdapter < String > adapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 ) ; // your test devices ' ids
String [ ] testDevicesIds = new String [ ] { getString ( R . string . testDeviceID ) , AdRequest . DEVICE_ID_EMULATOR } ; // when you ' ll be ready for release please use another ctor with admobReleaseUnitId instead .
adapterWrapper = AdmobExpressAdapterWrapper . builder ( this ) . setLimitOfAds ( 10 ) . setFirstAdIndex ( 2 ) . setNoOfDataBetweenAds ( 10 ) . setTestDeviceIds ( testDevicesIds ) . setAdapter ( adapter ) . setAdViewWrappingStrategy ( new AdViewWrappingStrategyBase ( ) { @ NonNull @ Override protected ViewGroup getAdViewWrapper ( ViewGroup parent ) { return ( ViewGroup ) LayoutInflater . from ( parent . getContext ( ) ) . inflate ( R . layout . web_ad_container , parent , false ) ; } @ Override protected void recycleAdViewWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // iterating through all children of the container view and remove the first occured { @ link NativeExpressAdView } . It could be different with { @ param ad } ! ! ! * / / *
for ( int i = 0 ; i < container . getChildCount ( ) ; i ++ ) { View v = container . getChildAt ( i ) ; if ( v instanceof NativeExpressAdView ) { container . removeViewAt ( i ) ; break ; } } } @ Override protected void addAdViewToWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // add the { @ param ad } directly to the end of container * / / *
container . addView ( ad ) ; } } ) . build ( ) ; lvMessages . setAdapter ( adapterWrapper ) ; // setting an AdmobAdapterWrapper to a ListView
// preparing the collection of data
final String sItem = "item #" ; ArrayList < String > lst = new ArrayList < String > ( 100 ) ; for ( int i = 1 ; i <= 100 ; i ++ ) lst . add ( sItem . concat ( Integer . toString ( i ) ) ) ; // adding a collection of data to your adapter and rising the data set changed event
adapter . addAll ( lst ) ; adapter . notifyDataSetChanged ( ) ;


signature:
public class AdmobExpressAdapterWrapper { /** * < p > Gets the count of all data , including interspersed ads . < / p >
 * < p > If data size is 10 and an ad is to be showed after every 5 items starting at the index 0 , this method
 * will return 12 . < / p >
 * @ return the total number of items this adapter can show , including ads .
 * @ see AdmobExpressAdapterWrapper # setNoOfDataBetweenAds ( int )
 * @ see AdmobExpressAdapterWrapper # getNoOfDataBetweenAds ( ) */
@ Override public int getCount ( ) { } }

implementation:
if ( mAdapter != null ) { /* Cnt of currently fetched ads , as long as it isn ' t more than no of max ads that can
 fit dataset . */
int noOfAds = AdapterCalculator . getAdsCountToPublish ( adFetcher . getFetchingAdsCount ( ) , mAdapter . getCount ( ) ) ; return mAdapter . getCount ( ) > 0 ? mAdapter . getCount ( ) + noOfAds : 0 ; } else { return 0 ; }


signature:
public class AdmobExpressAdapterWrapper { /** * Gets the item in a given position in the dataset . If an ad is to be returned ,
 * a { @ link NativeExpressAdView } object is returned .
 * @ param position the adapter position
 * @ return the object or ad contained in this adapter position */
@ Override public Object getItem ( int position ) { } }

implementation: if ( AdapterCalculator . canShowAdAtPosition ( position , adFetcher . getFetchingAdsCount ( ) ) ) { int adPos = AdapterCalculator . getAdIndex ( position ) ; return adFetcher . getAdForIndex ( adPos ) ; } else { int origPos = AdapterCalculator . getOriginalContentPosition ( position , adFetcher . getFetchingAdsCount ( ) , mAdapter . getCount ( ) ) ; return mAdapter . getItem ( origPos ) ; }


signature:
public class BannerAdPresetCyclingList { /** * Gets next ad preset for Admob banners from FIFO .
 * It works like cycling FIFO ( first in = first out , cycling from end to start ) .
 * Each ad block will get one from the queue .
 * If the desired count of ad blocks is greater than this collection size
 * then it will go again to the first item and iterate as much as it required .
 * ID should be active , please check it in your Admob ' s account . */
public BannerAdPreset get ( ) { } }

implementation: if ( size ( ) == 0 ) return null ; if ( size ( ) == 1 ) return get ( 0 ) ; currentIdx = ++ currentIdx % size ( ) ; return get ( currentIdx ) ;


signature:
public class BannerAdPresetCyclingList { /** * Tries to add an item to collection if it is valid { @ link BannerAdPreset # isValid ( ) }
 * @ return true if item was added , false - otherwise */
@ Override public boolean add ( BannerAdPreset expressAdPreset ) { } }

implementation: return ! ( expressAdPreset == null || ! expressAdPreset . isValid ( ) ) && super . add ( expressAdPreset ) ;


signature:
public class BannerAdPresetCyclingList { /** * Tries to add items to collection if valid { @ link BannerAdPreset # isValid ( ) }
 * @ return true if items were added , false - otherwise */
@ Override public boolean addAll ( Collection < ? extends BannerAdPreset > c ) { } }

implementation: ArrayList < BannerAdPreset > lst = new ArrayList < > ( ) ; for ( BannerAdPreset eap : c ) { if ( eap != null && eap . isValid ( ) ) lst . add ( eap ) ; } return super . addAll ( lst ) ;


signature:
public class AdmobBannerRecyclerAdapterWrapper { /** * Creates N instances { @ link AdView } from the next N taken instances { @ link BannerAdPreset }
 * Will start async prefetch of ad blocks to use its further
 * @ return last created banner AdView */
private AdView prefetchAds ( int cntToPrefetch ) { } }

implementation:
AdView last = null ; for ( int i = 0 ; i < cntToPrefetch ; i ++ ) { final AdView item = AdViewHelper . getBannerAdView ( mContext , adFetcher . takeNextAdPreset ( ) ) ; adFetcher . setupAd ( item ) ; // 50 ms throttling to prevent a high - load of server
new Handler ( mContext . getMainLooper ( ) ) . postDelayed ( new Runnable ( ) { @ Override public void run ( ) { adFetcher . fetchAd ( item ) ; } } , 50 * i ) ; last = item ; } return last ;


signature:
public class AdmobFetcher { /** * Gets native ad at a particular index in the fetched ads list .
 * @ param index the index of ad in the fetched ads list
 * @ return the native ad in the list
 * @ see # getFetchedAdsCount ( ) */
public synchronized NativeAd getAdForIndex ( final int index ) { } }

implementation:
NativeAd adNative = null ; if ( index >= 0 ) adNative = ( NativeAd ) adMapAtIndex . get ( index ) ; if ( adNative == null && mPrefetchedAdList . size ( ) > 0 ) { adNative = mPrefetchedAdList . remove ( 0 ) ; if ( adNative != null ) { adMapAtIndex . put ( index , adNative ) ; } } ensurePrefetchAmount ( ) ; // Make sure we have enough pre - fetched ads
return adNative ;


signature:
public class AdmobFetcher { /** * Destroys ads that have been fetched , that are still being fetched and removes all resource
 * references that this instance still has . This should only be called when the Activity that
 * is showing ads is closing , preferably from the { @ link android . app . Activity # onDestroy ( ) } .
 * The converse of this call is { @ link # prefetchAds ( Context ) } . */
public synchronized void destroyAllAds ( ) { } }

implementation: mFetchingAdsCnt = 0 ; adMapAtIndex . clear ( ) ; mPrefetchedAdList . clear ( ) ; Log . i ( TAG , "destroyAllAds adList " + adMapAtIndex . size ( ) + " prefetched " + mPrefetchedAdList . size ( ) ) ; super . destroyAllAds ( ) ;


signature:
public class AdmobFetcher { /** * Fetches a new native ad . */
protected synchronized void fetchAd ( ) { } }

implementation:
Context context = mContext . get ( ) ; if ( context != null ) { Log . i ( TAG , "Fetching Ad now" ) ; if ( lockFetch . getAndSet ( true ) ) return ; mFetchingAdsCnt ++ ; adLoader . loadAd ( getAdRequest ( ) ) ; // Fetching the ads item
} else { mFetchFailCount ++ ; Log . i ( TAG , "Context is null, not fetching Ad" ) ; }


signature:
public class AdmobFetcher { /** * Determines if the native ad can be used .
 * @ param adNative the native ad object
 * @ return < code > true < / code > if the ad object can be used , false otherwise */
private boolean canUseThisAd ( NativeAd adNative ) { } }

implementation: if ( adNative != null ) { NativeAd . Image logoImage = null ; CharSequence header = null , body = null ; if ( adNative instanceof NativeContentAd ) { NativeContentAd ad = ( NativeContentAd ) adNative ; logoImage = ad . getLogo ( ) ; header = ad . getHeadline ( ) ; body = ad . getBody ( ) ; } else if ( adNative instanceof NativeAppInstallAd ) { NativeAppInstallAd ad = ( NativeAppInstallAd ) adNative ; logoImage = ad . getIcon ( ) ; header = ad . getHeadline ( ) ; body = ad . getBody ( ) ; } if ( ! TextUtils . isEmpty ( header ) && ! TextUtils . isEmpty ( body ) ) { return true ; } } return false ;


signature:
public class AdmobFetcher { /** * Subscribing to the native ads events */
protected synchronized void setupAds ( ) { } }

implementation:
String unitId = getReleaseUnitId ( ) != null ? getReleaseUnitId ( ) : getDefaultUnitId ( ) ; AdLoader . Builder adloaderBuilder = new AdLoader . Builder ( mContext . get ( ) , unitId ) . withAdListener ( new AdListener ( ) { @ Override public void onAdFailedToLoad ( int errorCode ) { // Handle the failure by logging , altering the UI , etc .
Log . i ( TAG , "onAdFailedToLoad " + errorCode ) ; lockFetch . set ( false ) ; mFetchFailCount ++ ; mFetchingAdsCnt -- ; ensurePrefetchAmount ( ) ; onAdFailed ( mPrefetchedAdList . size ( ) , errorCode , null ) ; } } ) . withNativeAdOptions ( new NativeAdOptions . Builder ( ) // Methods in the NativeAdOptions . Builder class can be
// used here to specify individual options settings .
. build ( ) ) ; if ( getAdTypeToFetch ( ) . contains ( EAdType . ADVANCED_INSTALLAPP ) ) adloaderBuilder . forAppInstallAd ( new NativeAppInstallAd . OnAppInstallAdLoadedListener ( ) { @ Override public void onAppInstallAdLoaded ( NativeAppInstallAd appInstallAd ) { onAdFetched ( appInstallAd ) ; } } ) ; if ( getAdTypeToFetch ( ) . contains ( EAdType . ADVANCED_CONTENT ) ) adloaderBuilder . forContentAd ( new NativeContentAd . OnContentAdLoadedListener ( ) { @ Override public void onContentAdLoaded ( NativeContentAd contentAd ) { onAdFetched ( contentAd ) ; } } ) ; adLoader = adloaderBuilder . build ( ) ;


signature:
public class AdmobFetcher { /** * A handler for received native ads */
private synchronized void onAdFetched ( NativeAd adNative ) { } }

implementation: Log . i ( TAG , "onAdFetched" ) ; int index = - 1 ; if ( canUseThisAd ( adNative ) ) { mPrefetchedAdList . add ( adNative ) ; index = mPrefetchedAdList . size ( ) - 1 ; mNoOfFetchedAds ++ ; } lockFetch . set ( false ) ; mFetchFailCount = 0 ; ensurePrefetchAmount ( ) ; onAdLoaded ( index ) ;


signature:
public class MainActivity_RecyclerView { /** * Inits an adapter with items , wrapping your adapter with a { @ link AdmobRecyclerAdapterWrapper } and setting the recyclerview to this wrapper
 * FIRST OF ALL Please notice that the following code will work on a real devices but emulator ! */
private void initRecyclerViewItems ( ) { } }

implementation:
rvMessages = ( RecyclerView ) findViewById ( R . id . rvMessages ) ; rvMessages . setLayoutManager ( new LinearLayoutManager ( this ) ) ; // creating your adapter , it could be a custom adapter as well
RecyclerExampleAdapter adapter = new RecyclerExampleAdapter ( this ) ; // your test devices ' ids
String [ ] testDevicesIds = new String [ ] { getString ( R . string . testDeviceID ) , AdRequest . DEVICE_ID_EMULATOR } ; // when you ' ll be ready for release please use another ctor with admobReleaseUnitId instead .
adapterWrapper = new AdmobRecyclerAdapterWrapper ( this , testDevicesIds ) ; // By default both types of ads are loaded by wrapper .
// To set which of them to show in the list you should use an appropriate ctor
// adapterWrapper = new AdmobRecyclerAdapterWrapper ( this , testDevicesIds , EnumSet . of ( EAdType . ADVANCED _ INSTALLAPP ) ) ;
// wrapping your adapter with a AdmobAdapterWrapper .
adapterWrapper . setAdapter ( adapter ) ; // inject your custom layout and strategy of binding for installapp / content ads
// here you should pass the extended NativeAdLayoutContext
// by default it has a value InstallAppAdLayoutContext . getDefault ( )
// adapterWrapper . setInstallAdsLayoutContext ( . . . ) ;
// by default it has a value ContentAdLayoutContext . getDefault ( )
// adapterWrapper . setContentAdsLayoutContext ( . . . ) ;
// Sets the max count of ad blocks per dataset , by default it equals to 3 ( according to the Admob ' s policies and rules )
adapterWrapper . setLimitOfAds ( 3 ) ; // Sets the number of your data items between ad blocks , by default it equals to 10.
// You should set it according to the Admob ' s policies and rules which says not to
// display more than one ad block at the visible part of the screen ,
// so you should choose this parameter carefully and according to your item ' s height and screen resolution of a target devices
adapterWrapper . setNoOfDataBetweenAds ( 10 ) ; adapterWrapper . setFirstAdIndex ( 2 ) ; // if you use several view types in your source adapter then you have to set the biggest view type value with the following method
// adapterWrapper . setViewTypeBiggestSource ( 100 ) ;
rvMessages . setAdapter ( adapterWrapper ) ; // setting an AdmobRecyclerAdapterWrapper to a RecyclerView
// preparing the collection of data
final String sItem = "item #" ; ArrayList < String > lst = new ArrayList < String > ( 100 ) ; for ( int i = 1 ; i <= 100 ; i ++ ) lst . add ( sItem . concat ( Integer . toString ( i ) ) ) ; // adding a collection of data to your adapter and rising the data set changed event
adapter . addAll ( lst ) ; adapter . notifyDataSetChanged ( ) ;


signature:
public class MainActivity_RecyclerView { /** * Could be omitted . It ' s only for updating an ad blocks in each 60 seconds without refreshing the list */
private void initUpdateAdsTimer ( ) { } }

implementation: updateAdsTimer = new Timer ( ) ; updateAdsTimer . schedule ( new TimerTask ( ) { @ Override public void run ( ) { runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { adapterWrapper . requestUpdateAd ( ) ; } } ) ; } } , 60 * 1000 , 60 * 1000 ) ;


signature:
public class AdmobFetcherBanner { /** * Sets an unit IDs for admob banners .
 * It works like cycling FIFO ( first in = first out , cycling from end to start ) .
 * Each ad block will get one from the queue .
 * If the desired count of ad blocks is greater than this collection size
 * then it will go again to the first item and iterate as much as it required .
 * ID should be active , please check it in your Admob ' s account . */
public void setAdPresets ( Collection < BannerAdPreset > adPresets ) { } }

implementation: Collection < BannerAdPreset > mAdPresets = adPresets == null || adPresets . size ( ) == 0 ? Collections . singletonList ( BannerAdPreset . DEFAULT ) : adPresets ; mAdPresetCyclingList . clear ( ) ; mAdPresetCyclingList . addAll ( mAdPresets ) ;


signature:
public class AdmobFetcherBanner { /** * Gets banner ad at a particular index in the fetched ads list .
 * @ param adPos the index of ad in the fetched ads list
 * @ return the banner ad in the list
 * @ see # getFetchedAdsCount ( ) */
public synchronized AdView getAdForIndex ( int adPos ) { } }

implementation: if ( adPos >= 0 && mPrefetchedAds . size ( ) > adPos ) return mPrefetchedAds . get ( adPos ) ; return null ;


signature:
public class AdmobFetcherBanner { /** * A handler for failed banner ads
 * @ param adView */
private synchronized void onFailedToLoad ( AdView adView , int errorCode ) { } }

implementation:
Log . i ( TAG , "onAdFailedToLoad " + errorCode ) ; mFetchFailCount ++ ; mNoOfFetchedAds = Math . max ( mNoOfFetchedAds - 1 , 0 ) ; // Since Fetch Ad is only called once without retries
// hide ad row / rollback its count if still not added to list
mPrefetchedAds . remove ( adView ) ; onAdFailed ( mNoOfFetchedAds - 1 , errorCode , adView ) ;


signature:
public class MainActivity_RecyclerView_Banner { /** * Inits an adapter with items , wrapping your adapter with a { @ link AdmobBannerRecyclerAdapterWrapper } and setting the recyclerview to this wrapper
 * FIRST OF ALL Please notice that the following code will work on a real devices but emulator ! */
private void initRecyclerViewItems ( ) { } }

implementation:
rvMessages = ( RecyclerView ) findViewById ( R . id . rvMessages ) ; rvMessages . setLayoutManager ( new LinearLayoutManager ( this ) ) ; // creating your adapter , it could be a custom adapter as well
RecyclerExampleAdapter adapter = new RecyclerExampleAdapter ( this ) ; // your test devices ' ids
String [ ] testDevicesIds = new String [ ] { getString ( R . string . testDeviceID ) , AdRequest . DEVICE_ID_EMULATOR } ; // when you ' ll be ready for release please use another ctor with admobReleaseUnitId instead .
adapterWrapper = AdmobBannerRecyclerAdapterWrapper . builder ( this ) . setLimitOfAds ( 10 ) . setFirstAdIndex ( 2 ) . setNoOfDataBetweenAds ( 10 ) . setTestDeviceIds ( testDevicesIds ) . setAdapter ( adapter ) // Use the following for the default Wrapping behaviour
// . setAdViewWrappingStrategy ( new BannerAdViewWrappingStrategy ( ) )
// Or implement your own custom wrapping behaviour :
. setAdViewWrappingStrategy ( new BannerAdViewWrappingStrategyBase ( ) { @ NonNull @ Override protected ViewGroup getAdViewWrapper ( ViewGroup parent ) { return ( ViewGroup ) LayoutInflater . from ( parent . getContext ( ) ) . inflate ( R . layout . native_express_ad_container , parent , false ) ; } @ Override protected void recycleAdViewWrapper ( @ NonNull ViewGroup wrapper , @ NonNull AdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // iterating through all children of the container view and remove the first occured { @ link NativeExpressAdView } . It could be different with { @ param ad } ! ! ! * / / *
for ( int i = 0 ; i < container . getChildCount ( ) ; i ++ ) { View v = container . getChildAt ( i ) ; if ( v instanceof AdView ) { container . removeViewAt ( i ) ; break ; } } } @ Override protected void addAdViewToWrapper ( @ NonNull ViewGroup wrapper , @ NonNull AdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // add the { @ param ad } directly to the end of container * / / *
container . addView ( ad ) ; } } ) . build ( ) ; rvMessages . setAdapter ( adapterWrapper ) ; // setting an AdmobBannerRecyclerAdapterWrapper to a RecyclerView
// use the following commented block to use a grid layout with spanning ad blocks
GridLayoutManager mLayoutManager = new GridLayoutManager ( this , 2 ) ; mLayoutManager . setSpanSizeLookup ( new GridLayoutManager . SpanSizeLookup ( ) { @ Override public int getSpanSize ( int position ) { if ( adapterWrapper . getItemViewType ( position ) == adapterWrapper . getViewTypeAdBanner ( ) ) return 2 ; else return 1 ; } } ) ; rvMessages . setLayoutManager ( mLayoutManager ) ; // preparing the collection of data
final String sItem = "item #" ; ArrayList < String > lst = new ArrayList < String > ( 100 ) ; for ( int i = 1 ; i <= 100 ; i ++ ) lst . add ( sItem . concat ( Integer . toString ( i ) ) ) ; // adding a collection of data to your adapter and rising the data set changed event
adapter . addAll ( lst ) ; adapter . notifyDataSetChanged ( ) ;


signature:
public class AdmobFetcherBase { /** * Notifies all registered { @ link AdmobListener } on a change of ad count . */
protected void onAdsCountChanged ( ) { } }

implementation:
final Context context = mContext . get ( ) ; // context may be null if activity is destroyed
if ( context != null ) { new Handler ( context . getMainLooper ( ) ) . post ( new Runnable ( ) { @ Override public void run ( ) { for ( AdmobListener listener : mAdNativeListeners ) listener . onAdsCountChanged ( ) ; } } ) ; }


signature:
public class AdmobFetcherBase { /** * Notifies all registered { @ link AdmobListener } on a failed ad . */
protected void onAdFailed ( final int adIdx , final int errorCode , final Object adPayload ) { } }

implementation:
final Context context = mContext . get ( ) ; // context may be null if activity is destroyed
if ( context != null ) { for ( AdmobListener listener : mAdNativeListeners ) listener . onAdFailed ( adIdx , errorCode , adPayload ) ; }


signature:
public class AdmobFetcherBase { /** * Setup and get an ads request */
protected synchronized AdRequest getAdRequest ( ) { } }

implementation: AdRequest . Builder adBldr = new AdRequest . Builder ( ) ; for ( String id : getTestDeviceIds ( ) ) { adBldr . addTestDevice ( id ) ; } return adBldr . build ( ) ;


signature:
public class MainActivity_RecyclerView_Express { /** * Inits an adapter with items , wrapping your adapter with a { @ link AdmobExpressRecyclerAdapterWrapper } and setting the recyclerview to this wrapper
 * FIRST OF ALL Please notice that the following code will work on a real devices but emulator ! */
private void initRecyclerViewItems ( ) { } }

implementation:
rvMessages = ( RecyclerView ) findViewById ( R . id . rvMessages ) ; rvMessages . setLayoutManager ( new LinearLayoutManager ( this ) ) ; // creating your adapter , it could be a custom adapter as well
RecyclerExampleAdapter adapter = new RecyclerExampleAdapter ( this ) ; // your test devices ' ids
String [ ] testDevicesIds = new String [ ] { getString ( R . string . testDeviceID ) , AdRequest . DEVICE_ID_EMULATOR } ; // when you ' ll be ready for release please use another ctor with admobReleaseUnitId instead .
adapterWrapper = AdmobExpressRecyclerAdapterWrapper . builder ( this ) . setLimitOfAds ( 10 ) . setFirstAdIndex ( 2 ) . setNoOfDataBetweenAds ( 10 ) . setTestDeviceIds ( testDevicesIds ) . setAdapter ( adapter ) . setAdViewWrappingStrategy ( new AdViewWrappingStrategyBase ( ) { @ NonNull @ Override protected ViewGroup getAdViewWrapper ( ViewGroup parent ) { return ( ViewGroup ) LayoutInflater . from ( parent . getContext ( ) ) . inflate ( R . layout . web_ad_container , parent , false ) ; } @ Override protected void recycleAdViewWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // iterating through all children of the container view and remove the first occured { @ link NativeExpressAdView } . It could be different with { @ param ad } ! ! ! * / / *
for ( int i = 0 ; i < container . getChildCount ( ) ; i ++ ) { View v = container . getChildAt ( i ) ; if ( v instanceof NativeExpressAdView ) { container . removeViewAt ( i ) ; break ; } } } @ Override protected void addAdViewToWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { // get the view which directly will contain ad
ViewGroup container = ( ViewGroup ) wrapper . findViewById ( R . id . ad_container ) ; // add the { @ param ad } directly to the end of container * / / *
container . addView ( ad ) ; } } ) . build ( ) ; rvMessages . setAdapter ( adapterWrapper ) ; // setting an AdmobBannerRecyclerAdapterWrapper to a RecyclerView
// use the following commented block to use a grid layout with spanning ad blocks
/* GridLayoutManager mLayoutManager = new GridLayoutManager ( this , 2 ) ;
 mLayoutManager . setSpanSizeLookup ( new GridLayoutManager . SpanSizeLookup ( ) {
 @ Override
 public int getSpanSize ( int position ) {
 if ( adapterWrapper . getItemViewType ( position ) = = adapterWrapper . getViewTypeAdExpress ( ) )
 return 2;
 else return 1;
 rvMessages . setLayoutManager ( mLayoutManager ) ; */
// preparing the collection of data
final String sItem = "item #" ; ArrayList < String > lst = new ArrayList < String > ( 100 ) ; for ( int i = 1 ; i <= 100 ; i ++ ) lst . add ( sItem . concat ( Integer . toString ( i ) ) ) ; // adding a collection of data to your adapter and rising the data set changed event
adapter . addAll ( lst ) ; adapter . notifyDataSetChanged ( ) ;


signature:
public class AdPresetCyclingList { /** * Gets next ad preset for Admob banners from FIFO .
 * It works like cycling FIFO ( first in = first out , cycling from end to start ) .
 * Each ad block will get one from the queue .
 * If the desired count of ad blocks is greater than this collection size
 * then it will go again to the first item and iterate as much as it required .
 * ID should be active , please check it in your Admob ' s account . */
public AdPreset get ( ) { } }

implementation: if ( size ( ) == 0 ) return null ; if ( size ( ) == 1 ) return get ( 0 ) ; currentIdx = ++ currentIdx % size ( ) ; return get ( currentIdx ) ;


signature:
public class AdPresetCyclingList { /** * Tries to add an item to collection if it is valid { @ link AdPreset # isValid ( ) }
 * @ return true if item was added , false - otherwise */
@ Override public boolean add ( AdPreset adPreset ) { } }

implementation: return ! ( adPreset == null || ! adPreset . isValid ( ) ) && super . add ( adPreset ) ;


signature:
public class BannerAdViewWrappingStrategy { /** * Add the Banner { @ param ad } to { @ param wrapper } .
 * See the super ' s implementation for instance . */
@ Override protected void addAdViewToWrapper ( @ NonNull ViewGroup wrapper , @ NonNull AdView ad ) { } }

implementation: wrapper . addView ( ad ) ;


signature:
public class BannerAdViewWrappingStrategy { /** * This method can be overridden to wrap the created ad view with a custom { @ link ViewGroup } . < br / >
 * For example if you need to wrap the ad with your custom CardView
 * @ return The wrapper { @ link ViewGroup } for ad , by default { @ link AdView } ad would be wrapped with a CardView which is returned by this method */
@ Override @ NonNull protected ViewGroup getAdViewWrapper ( ViewGroup parent ) { } }

implementation: return ( ViewGroup ) LayoutInflater . from ( parent . getContext ( ) ) . inflate ( R . layout . web_ad_container , parent , false ) ;


signature:
public class AdmobRecyclerAdapterWrapper { /** * < p > Gets the count of all data , including interspersed ads . < / p >
 * < p > If data size is 10 and an ad is to be showed after every 5 items starting at the index 0 , this method
 * will return 12 . < / p >
 * @ return the total number of items this adapter can show , including ads .
 * @ see AdmobRecyclerAdapterWrapper # setNoOfDataBetweenAds ( int )
 * @ see AdmobRecyclerAdapterWrapper # getNoOfDataBetweenAds ( ) */
@ Override public int getItemCount ( ) { } }

implementation:
if ( mAdapter != null ) { /* No of currently fetched ads , as long as it isn ' t more than no of max ads that can
 fit dataset . */
int noOfAds = AdapterCalculator . getAdsCountToPublish ( adFetcher . getFetchedAdsCount ( ) , mAdapter . getItemCount ( ) ) ; return mAdapter . getItemCount ( ) > 0 ? mAdapter . getItemCount ( ) + noOfAds : 0 ; } else { return 0 ; }


signature:
public class AdmobRecyclerAdapterWrapper { /** * Gets the item in a given position in the dataset . If an ad is to be returned ,
 * a { @ link NativeAd } object is returned .
 * @ return the object or ad contained in this adapter position */
public Object getItem ( int position ) { } }

implementation: if ( AdapterCalculator . canShowAdAtPosition ( position , adFetcher . getFetchedAdsCount ( ) ) ) { int adPos = AdapterCalculator . getAdIndex ( position ) ; return adFetcher . getAdForIndex ( adPos ) ; } else return null ;


signature:
public class AdmobAdapterCalculator { /** * Gets the count of ads that could be published
 * @ param fetchedAdsCount the count of completely fetched ads that are ready to be published
 * @ param sourceItemsCount the count of items in the source collection
 * @ return the original position that the adapter position would have been without ads */
public int getAdsCountToPublish ( int fetchedAdsCount , int sourceItemsCount ) { } }

implementation: if ( fetchedAdsCount <= 0 || getNoOfDataBetweenAds ( ) <= 0 ) return 0 ; int expected = 0 ; if ( sourceItemsCount > 0 && sourceItemsCount >= getOffsetValue ( ) + 1 ) expected = ( sourceItemsCount - getOffsetValue ( ) ) / getNoOfDataBetweenAds ( ) + 1 ; expected = Math . max ( 0 , expected ) ; expected = Math . min ( fetchedAdsCount , expected ) ; return Math . min ( expected , getLimitOfAds ( ) ) ;


signature:
public class AdmobAdapterCalculator { /** * Translates an adapter position to an actual position within the underlying dataset .
 * @ param position the adapter position
 * @ param fetchedAdsCount the count of completely fetched ads that are ready to be published
 * @ param sourceItemsCount the count of items in the source collection
 * @ return the original position that the adapter position would have been without ads */
public int getOriginalContentPosition ( int position , int fetchedAdsCount , int sourceItemsCount ) { } }

implementation:
int noOfAds = getAdsCountToPublish ( fetchedAdsCount , sourceItemsCount ) ; // No of spaces for ads in the dataset , according to ad placement rules
int adSpacesCount = ( getAdIndex ( position ) + 1 ) ; int originalPosition = position - Math . min ( adSpacesCount , noOfAds ) ; // Log . d ( " POSITION " , position + " is originally " + originalPosition ) ;
return originalPosition ;


signature:
public class AdmobAdapterCalculator { /** * Translates the source position to an actual position within the adapter wrapper .
 * @ param fetchedAdsCount the count of completely fetched ads that are ready to be published
 * @ param sourcePos the source index
 * @ return the position of the adapter wrapper item */
public int translateSourceIndexToWrapperPosition ( int sourcePos , int fetchedAdsCount ) { } }

implementation: int adSpacesCount = 0 ; if ( sourcePos >= getOffsetValue ( ) && getNoOfDataBetweenAds ( ) > 0 ) adSpacesCount = ( sourcePos - getOffsetValue ( ) ) / getNoOfDataBetweenAds ( ) + 1 ; adSpacesCount = Math . min ( fetchedAdsCount , adSpacesCount ) ; adSpacesCount = Math . max ( 0 , adSpacesCount ) ; adSpacesCount = Math . min ( adSpacesCount , getLimitOfAds ( ) ) ; int wrappedPosition = sourcePos + adSpacesCount ; return wrappedPosition ;


signature:
public class AdmobAdapterCalculator { /** * Gets the ad index for this adapter position within the list of currently fetched ads .
 * @ param position the adapter position
 * @ return the index of the ad within the list of fetched ads */
public int getAdIndex ( int position ) { } }

implementation:
int index = - 1 ; if ( position >= getOffsetValue ( ) ) index = ( position - getOffsetValue ( ) ) / ( getNoOfDataBetweenAds ( ) + 1 ) ; // Log . d ( " POSITION " , " index " + index + " for position " + position ) ;
return index ;


signature:
public class AdmobAdapterCalculator { /** * Checks if an ad is available for this position .
 * @ param position the adapter position
 * @ param fetchedAdsCount the count of completely fetched ads that are ready to be published
 * @ return { @ code true } if an ad is available , { @ code false } otherwise */
public boolean isAdAvailable ( int position , int fetchedAdsCount ) { } }

implementation: if ( fetchedAdsCount == 0 ) return false ; int adIndex = getAdIndex ( position ) ; int firstAdPos = getOffsetValue ( ) ; return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds ( ) && adIndex < fetchedAdsCount ;


signature:
public class AdmobAdapterCalculator { /** * Checks if we have to request the next ad block for this position .
 * @ param position the adapter position
 * @ param fetchingAdsCount the count of fetched and currently fetching ads
 * @ return { @ code true } if an ad is not available to publish and we should fetch one , { @ code false } otherwise */
public boolean hasToFetchAd ( int position , int fetchingAdsCount ) { } }

implementation: int adIndex = getAdIndex ( position ) ; int firstAdPos = getOffsetValue ( ) ; return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds ( ) && adIndex >= fetchingAdsCount ;


signature:
public class AdViewWrappingStrategy { /** * Add the Native Express { @ param ad } to { @ param wrapper } .
 * See the super ' s implementation for instance . */
@ Override protected void addAdViewToWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { } }


signature:
public class AdViewWrappingStrategy { /** * This method can be overriden to recycle ( remove ) { @ param ad } from { @ param wrapper } view before adding to wrap .
 * By default it will look for { @ param ad } in the direct children of { @ param wrapper } and remove the first occurence .
 * See the super ' s implementation for instance .
 * The NativeExpressHolder recycled by the RecyclerView may be a different
 * instance than the one used previously for this position . Clear the
 * wrapper of any subviews in case it has a different
 * AdView associated with it */
@ Override protected void recycleAdViewWrapper ( @ NonNull ViewGroup wrapper , @ NonNull NativeExpressAdView ad ) { } }

implementation: for ( int i = 0 ; i < wrapper . getChildCount ( ) ; i ++ ) { View v = wrapper . getChildAt ( i ) ; if ( v instanceof NativeExpressAdView ) { wrapper . removeViewAt ( i ) ; break ; } }


signature:
public class MainActivity_ListView { /** * Inits an adapter with items , wrapping your adapter with a { @ link AdmobAdapterWrapper } and setting the listview to this wrapper
 * FIRST OF ALL Please notice that the following code will work on a real devices but emulator ! */
private void initListViewItems ( ) { } }

implementation:
lvMessages = ( ListView ) findViewById ( R . id . lvMessages ) ; // creating your adapter , it could be a custom adapter as well
ArrayAdapter < String > adapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 ) ; // your test devices ' ids
String [ ] testDevicesIds = new String [ ] { getString ( R . string . testDeviceID ) , AdRequest . DEVICE_ID_EMULATOR } ; // when you ' ll be ready for release please use another ctor with admobReleaseUnitId instead .
adapterWrapper = new AdmobAdapterWrapper ( this , testDevicesIds ) ; // By default both types of ads are loaded by wrapper .
// To set which of them to show in the list you should use an appropriate ctor
// adapterWrapper = new AdmobAdapterWrapper ( this , testDevicesIds , EnumSet . of ( EAdType . ADVANCED _ INSTALLAPP ) ) ;
// wrapping your adapter with a AdmobAdapterWrapper .
adapterWrapper . setAdapter ( adapter ) ; // inject your custom layout and strategy of binding for installapp / content ads
// here you should pass the extended NativeAdLayoutContext
// by default it has a value InstallAppAdLayoutContext . getDefault ( )
// adapterWrapper . setInstallAdsLayoutContext ( . . . ) ;
// by default it has a value ContentAdLayoutContext . getDefault ( )
// adapterWrapper . setContentAdsLayoutContext ( . . . ) ;
// Sets the max count of ad blocks per dataset , by default it equals to 3 ( according to the Admob ' s policies and rules )
adapterWrapper . setLimitOfAds ( 3 ) ; // Sets the number of your data items between ad blocks , by default it equals to 10.
// You should set it according to the Admob ' s policies and rules which says not to
// display more than one ad block at the visible part of the screen ,
// so you should choose this parameter carefully and according to your item ' s height and screen resolution of a target devices
adapterWrapper . setNoOfDataBetweenAds ( 10 ) ; adapterWrapper . setFirstAdIndex ( 2 ) ; lvMessages . setAdapter ( adapterWrapper ) ; // setting an AdmobAdapterWrapper to a ListView
lvMessages . setOnItemClickListener ( new AdapterView . OnItemClickListener ( ) { @ Override public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { final AdmobAdapterCalculator adapterCalc = adapterWrapper . getAdapterCalculator ( ) ; int fetchedAdsCnt = adapterWrapper . getFetchedAdsCount ( ) ; int sourceCnt = adapterWrapper . getAdapter ( ) . getCount ( ) ; int originalPos = adapterCalc . getOriginalContentPosition ( position , fetchedAdsCnt , sourceCnt ) ; Toast . makeText ( getApplicationContext ( ) , "Click: " + String . valueOf ( originalPos ) , Toast . LENGTH_SHORT ) . show ( ) ; } } ) ; // preparing the collection of data
final String sItem = "item #" ; ArrayList < String > lst = new ArrayList < String > ( 100 ) ; for ( int i = 1 ; i <= 100 ; i ++ ) lst . add ( sItem . concat ( Integer . toString ( i ) ) ) ; // adding a collection of data to your adapter and rising the data set changed event
adapter . addAll ( lst ) ; adapter . notifyDataSetChanged ( ) ;


signature:
public class AdmobFetcherExpress { /** * Gets native ad at a particular index in the fetched ads list .
 * @ param adPos the index of ad in the fetched ads list
 * @ return the native ad in the list
 * @ see # getFetchedAdsCount ( ) */
public synchronized NativeExpressAdView getAdForIndex ( int adPos ) { } }

implementation: if ( adPos >= 0 && mPrefetchedAds . size ( ) > adPos ) return mPrefetchedAds . get ( adPos ) ; return null ;


signature:
public class AdmobFetcherExpress { /** * Fetches a new native ad . */
protected synchronized void fetchAd ( final NativeExpressAdView adView ) { } }

implementation:
if ( mFetchFailCount > MAX_FETCH_ATTEMPT ) return ; Context context = mContext . get ( ) ; if ( context != null ) { Log . i ( TAG , "Fetching Ad now" ) ; new Handler ( context . getMainLooper ( ) ) . post ( new Runnable ( ) { @ Override public void run ( ) { adView . loadAd ( getAdRequest ( ) ) ; // Fetching the ads item
} } ) ; } else { mFetchFailCount ++ ; Log . i ( TAG , "Context is null, not fetching Ad" ) ; }


signature:
public class AdmobFetcherExpress { /** * Subscribing to the native ads events
 * @ param adView */
protected synchronized void setupAd ( final NativeExpressAdView adView ) { } }

implementation:
if ( mFetchFailCount > MAX_FETCH_ATTEMPT ) return ; if ( ! mPrefetchedAds . contains ( adView ) ) mPrefetchedAds . add ( adView ) ; adView . setAdListener ( new AdListener ( ) { @ Override public void onAdFailedToLoad ( int errorCode ) { super . onAdFailedToLoad ( errorCode ) ; // Handle the failure by logging , altering the UI , etc .
onFailedToLoad ( adView , errorCode ) ; } @ Override public void onAdLoaded ( ) { super . onAdLoaded ( ) ; onFetched ( adView ) ; } } ) ;


signature:
public class AdmobFetcherExpress { /** * A handler for received native ads
 * @ param adView */
private synchronized void onFetched ( NativeExpressAdView adView ) { } }

implementation: Log . i ( TAG , "onAdFetched" ) ; mFetchFailCount = 0 ; mNoOfFetchedAds ++ ; onAdLoaded ( mNoOfFetchedAds - 1 ) ;


signature:
public class SupportedTypes { /** * Collect information about the element and the corresponding code generator */
public static CodeGenInfo getCodeGenInfo ( VariableElement element , Elements elements , Types types ) { } }

implementation:
// Special classes , primitive , wrappers , etc .
String typeKey = element . asType ( ) . toString ( ) ; if ( typeMap . get ( typeKey ) != null ) { return new CodeGenInfo ( typeMap . get ( typeKey ) ) ; } // Check if its a simple parcelable
if ( isOfType ( element , "android.os.Parcelable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE ) ) ; } // Lists
if ( isOfWildCardType ( element , ArrayList . class . getName ( ) , "android.os.Parcelable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE_ARRAYLIST ) , hasGenericsTypeArgumentOf ( element , "android.os.Parcelable" , elements , types ) ) ; } if ( isOfWildCardType ( element , LinkedList . class . getName ( ) , "android.os.Parcelable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE_LINKEDLIST ) , hasGenericsTypeArgumentOf ( element , "android.os.Parcelable" , elements , types ) ) ; } if ( isOfWildCardType ( element , CopyOnWriteArrayList . class . getName ( ) , "android.os.Parcelable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE_COPYONWRITEARRAYLIST ) , hasGenericsTypeArgumentOf ( element , "android.os.Parcelable" , elements , types ) ) ; } if ( isOfWildCardType ( element , List . class . getName ( ) , "android.os.Parcelable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE_LIST ) , hasGenericsTypeArgumentOf ( element , "android.os.Parcelable" , elements , types ) ) ; } if ( isOfWildCardType ( element , List . class . getName ( ) , String . class . getName ( ) , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_STRING_LIST ) ) ; } // Arrays
if ( element . asType ( ) . getKind ( ) == TypeKind . ARRAY ) { ArrayType arrayType = ( ArrayType ) element . asType ( ) ; TypeMirror arrayOf = arrayType . getComponentType ( ) ; if ( arrayOf . getKind ( ) == TypeKind . CHAR ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_CHAR_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . BOOLEAN ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_BOOL_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . BYTE ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_BYTE_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . DOUBLE ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_DOUBLE_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . FLOAT ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_FLOAT_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . INT ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_INT_ARRAY ) ) ; } if ( arrayOf . getKind ( ) == TypeKind . LONG ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_LONG_ARRAY ) ) ; } if ( arrayOf . toString ( ) . equals ( String . class . getName ( ) ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_STRING_ARRAY ) ) ; } if ( isOfType ( arrayOf , "android.os.Parcelable" , elements , types ) ) { // It ' s an array of parcelable
return new CodeGenInfo ( typeMap . get ( TYPE_KEY_PARCELABLE_ARRAY ) , arrayOf ) ; } // Unsupported Array Type
ProcessorMessage . error ( element , "Unsuppored type %s as Array type for field %s. " + "You could write your own Serialization mechanism by using @%s " , element . asType ( ) . toString ( ) , element . getSimpleName ( ) , Bagger . class . getSimpleName ( ) ) ; } // TODO SparseArray
// if ( isOfWildCardType ( element , " android . util . SparseArray " , " android . os . Parcelable " , elements ,
// types ) ) {
// return new CodeGenInfo ( typeMap . get ( TYPE _ KEY _ SPARSE _ ARRAY ) ,
// hasGenericsTypeArgumentOf ( element , null , elements , types ) ) ;
// Serializable as last
if ( isOfType ( element , "java.io.Serializable" , elements , types ) ) { return new CodeGenInfo ( typeMap . get ( TYPE_KEY_SERIALIZABLE ) ) ; } // Unsupported type
ProcessorMessage . error ( element , "Unsuppored type %s for field %s. " + "You could write your own Serialization mechanism by using @%s " , element . asType ( ) . toString ( ) , element . getSimpleName ( ) , Bagger . class . getSimpleName ( ) ) ; return new CodeGenInfo ( null ) ;


signature:
public class SupportedTypes { /** * Get the wildcardType */
public static TypeMirror getWildcardType ( String type , String elementType , Elements elements , Types types ) { } }

implementation: TypeElement arrayList = elements . getTypeElement ( type ) ; TypeMirror elType = elements . getTypeElement ( elementType ) . asType ( ) ; return types . getDeclaredType ( arrayList , types . getWildcardType ( elType , null ) ) ;


signature:
public class SupportedTypes { /** * Checks if the variabel element has generics arguments that matches the expected type */
public static TypeMirror hasGenericsTypeArgumentOf ( Element element , String typeToCheck , Elements elements , Types types ) { } }

implementation:
if ( element . asType ( ) . getKind ( ) != TypeKind . DECLARED || ! ( element . asType ( ) instanceof DeclaredType ) ) { ProcessorMessage . error ( element , "The field %s in %s doesn't have generic type arguments!" , element . getSimpleName ( ) , element . asType ( ) . toString ( ) ) ; } DeclaredType declaredType = ( DeclaredType ) element . asType ( ) ; List < ? extends TypeMirror > typeArguments = declaredType . getTypeArguments ( ) ; if ( typeArguments . isEmpty ( ) ) { ProcessorMessage . error ( element , "The field %s in %s doesn't have generic type arguments!" , element . getSimpleName ( ) , element . asType ( ) . toString ( ) ) ; } if ( typeArguments . size ( ) > 1 ) { ProcessorMessage . error ( element , "The field %s in %s has more than 1 generic type argument!" , element . getSimpleName ( ) , element . asType ( ) . toString ( ) ) ; } // Ok it has a generic argument , check if this extends Parcelable
TypeMirror argument = typeArguments . get ( 0 ) ; if ( typeToCheck != null ) { if ( ! isOfType ( argument , typeToCheck , elements , types ) ) { ProcessorMessage . error ( element , "The fields %s  generic type argument is not of type  %s! (in %s )" , element . getSimpleName ( ) , typeToCheck , element . asType ( ) . toString ( ) ) ; } } // everything is like expected
return argument ;


signature:
public class JavaWriter { /** * Emit a package declaration and empty line . */
public JavaWriter emitPackage ( String packageName ) throws IOException { } }

implementation: if ( this . packagePrefix != null ) { throw new IllegalStateException ( ) ; } if ( packageName . isEmpty ( ) ) { this . packagePrefix = "" ; } else { out . write ( "package " ) ; out . write ( packageName ) ; out . write ( ";\n\n" ) ; this . packagePrefix = packageName + "." ; } return this ;


signature:
public class JavaWriter { /** * Emit an import for each { @ code type } provided . For the duration of the file , all references to
 * these classes will be automatically shortened . */
public JavaWriter emitImports ( Class < ? > ... types ) throws IOException { } }

implementation: List < String > classNames = new ArrayList < String > ( types . length ) ; for ( Class < ? > classToImport : types ) { classNames . add ( classToImport . getName ( ) ) ; } return emitImports ( classNames ) ;


signature:
public class JavaWriter { /** * Emit an import for each { @ code type } in the provided { @ code Collection } . For the duration of
 * the file , all references to these classes will be automatically shortened . */
public JavaWriter emitImports ( Collection < String > types ) throws IOException { } }

implementation: for ( String type : new TreeSet < String > ( types ) ) { Matcher matcher = TYPE_PATTERN . matcher ( type ) ; if ( ! matcher . matches ( ) ) { throw new IllegalArgumentException ( type ) ; } if ( importedTypes . put ( type , matcher . group ( 1 ) ) != null ) { throw new IllegalArgumentException ( type ) ; } out . write ( "import " ) ; out . write ( type ) ; out . write ( ";\n" ) ; } return this ;


signature:
public class JavaWriter { /** * Emits a name like { @ code java . lang . String } or { @ code java . util . List < java . lang . String > } ,
 * compressing it with imports if possible . Type compression will only be enabled if
 * { @ link # isCompressingTypes } is true . */
private JavaWriter emitCompressedType ( String type ) throws IOException { } }

implementation: if ( isCompressingTypes ) { out . write ( compressType ( type ) ) ; } else { out . write ( type ) ; } return this ;


signature:
public class JavaWriter { /** * Try to compress a fully - qualified class name to only the class name . */
public String compressType ( String type ) { } }

implementation:
StringBuilder sb = new StringBuilder ( ) ; if ( this . packagePrefix == null ) { throw new IllegalStateException ( ) ; } Matcher m = TYPE_PATTERN . matcher ( type ) ; int pos = 0 ; while ( true ) { boolean found = m . find ( pos ) ; // Copy non - matching characters like " < " .
int typeStart = found ? m . start ( ) : type . length ( ) ; sb . append ( type , pos , typeStart ) ; if ( ! found ) { break ; } // Copy a single class name , shortening it if possible .
String name = m . group ( 0 ) ; String imported = importedTypes . get ( name ) ; if ( imported != null ) { sb . append ( imported ) ; } else if ( isClassInPackage ( name , packagePrefix ) ) { String compressed = name . substring ( packagePrefix . length ( ) ) ; if ( isAmbiguous ( compressed ) ) { sb . append ( name ) ; } else { sb . append ( compressed ) ; } } else if ( isClassInPackage ( name , "java.lang." ) ) { sb . append ( name . substring ( "java.lang." . length ( ) ) ) ; } else { sb . append ( name ) ; } pos = m . end ( ) ; } return sb . toString ( ) ;


signature:
public class JavaWriter { /** * Emits an initializer declaration .
 * @ param isStatic true if it should be an static initializer , false for an instance initializer . */
public JavaWriter beginInitializer ( boolean isStatic ) throws IOException { } }

implementation: indent ( ) ; if ( isStatic ) { out . write ( "static" ) ; out . write ( " {\n" ) ; } else { out . write ( "{\n" ) ; } scopes . push ( Scope . INITIALIZER ) ; return this ;


signature:
public class JavaWriter { /** * Emits a type declaration .
 * @ param kind such as " class " , " interface " or " enum " . */
public JavaWriter beginType ( String type , String kind ) throws IOException { } }

implementation: return beginType ( type , kind , EnumSet . noneOf ( Modifier . class ) , null ) ;


signature:
public class JavaWriter { /** * Emits a type declaration .
 * @ param kind such as " class " , " interface " or " enum " . */
public JavaWriter beginType ( String type , String kind , Set < Modifier > modifiers ) throws IOException { } }

implementation: return beginType ( type , kind , modifiers , null ) ;


signature:
public class JavaWriter { /** * Emits a type declaration .
 * @ param kind such as " class " , " interface " or " enum " .
 * @ param extendsType the class to extend , or null for no extends clause . */
public JavaWriter beginType ( String type , String kind , Set < Modifier > modifiers , String extendsType , String ... implementsTypes ) throws IOException { } }

implementation: indent ( ) ; emitModifiers ( modifiers ) ; out . write ( kind ) ; out . write ( " " ) ; emitCompressedType ( type ) ; if ( extendsType != null ) { out . write ( " extends " ) ; emitCompressedType ( extendsType ) ; } if ( implementsTypes . length > 0 ) { out . write ( "\n" ) ; indent ( ) ; out . write ( "    implements " ) ; for ( int i = 0 ; i < implementsTypes . length ; i ++ ) { if ( i != 0 ) { out . write ( ", " ) ; } emitCompressedType ( implementsTypes [ i ] ) ; } } out . write ( " {\n" ) ; scopes . push ( "interface" . equals ( kind ) ? Scope . INTERFACE_DECLARATION : Scope . TYPE_DECLARATION ) ; types . push ( type ) ; return this ;


signature:
public class JavaWriter { /** * Completes the current type declaration . */
public JavaWriter endType ( ) throws IOException { } }

implementation: popScope ( Scope . TYPE_DECLARATION , Scope . INTERFACE_DECLARATION ) ; types . pop ( ) ; indent ( ) ; out . write ( "}\n" ) ; return this ;


signature:
public class JavaWriter { /** * Emits a field declaration . */
public JavaWriter emitField ( String type , String name ) throws IOException { } }

implementation: return emitField ( type , name , EnumSet . noneOf ( Modifier . class ) , null ) ;


signature:
public class JavaWriter { /** * Emits a field declaration . */
public JavaWriter emitField ( String type , String name , Set < Modifier > modifiers ) throws IOException { } }

implementation: return emitField ( type , name , modifiers , null ) ;


signature:
public class JavaWriter { /** * Emits a field declaration . */
public JavaWriter emitField ( String type , String name , Set < Modifier > modifiers , String initialValue ) throws IOException { } }

implementation: indent ( ) ; emitModifiers ( modifiers ) ; emitCompressedType ( type ) ; out . write ( " " ) ; out . write ( name ) ; if ( initialValue != null ) { out . write ( " =" ) ; if ( ! initialValue . startsWith ( "\n" ) ) { out . write ( " " ) ; } String [ ] lines = initialValue . split ( "\n" , - 1 ) ; out . write ( lines [ 0 ] ) ; for ( int i = 1 ; i < lines . length ; i ++ ) { out . write ( "\n" ) ; hangingIndent ( ) ; out . write ( lines [ i ] ) ; } } out . write ( ";\n" ) ; return this ;


signature:
public class JavaWriter { /** * Emit a method declaration .
 * < p > A { @ code null } return type may be used to indicate a constructor , but
 * { @ link # beginConstructor ( Set , String . . . ) } should be preferred . This behavior may be removed in
 * a future release .
 * @ param returnType the method ' s return type , or null for constructors
 * @ param name the method name , or the fully qualified class name for constructors .
 * @ param modifiers the set of modifiers to be applied to the method
 * @ param parameters alternating parameter types and names . */
public JavaWriter beginMethod ( String returnType , String name , Set < Modifier > modifiers , String ... parameters ) throws IOException { } }

implementation: return beginMethod ( returnType , name , modifiers , Arrays . asList ( parameters ) , null ) ;


signature:
public class JavaWriter { /** * Emit a method declaration .
 * < p > A { @ code null } return type may be used to indicate a constructor , but
 * { @ link # beginConstructor ( Set , List , List ) } should be preferred . This behavior may be removed in
 * a future release .
 * @ param returnType the method ' s return type , or null for constructors .
 * @ param name the method name , or the fully qualified class name for constructors .
 * @ param modifiers the set of modifiers to be applied to the method
 * @ param parameters alternating parameter types and names .
 * @ param throwsTypes the classes to throw , or null for no throws clause . */
public JavaWriter beginMethod ( String returnType , String name , Set < Modifier > modifiers , List < String > parameters , List < String > throwsTypes ) throws IOException { } }

implementation: indent ( ) ; emitModifiers ( modifiers ) ; if ( returnType != null ) { emitCompressedType ( returnType ) ; out . write ( " " ) ; out . write ( name ) ; } else { emitCompressedType ( name ) ; } out . write ( "(" ) ; if ( parameters != null ) { for ( int p = 0 ; p < parameters . size ( ) ; ) { if ( p != 0 ) { out . write ( ", " ) ; } emitCompressedType ( parameters . get ( p ++ ) ) ; out . write ( " " ) ; emitCompressedType ( parameters . get ( p ++ ) ) ; } } out . write ( ")" ) ; if ( throwsTypes != null && throwsTypes . size ( ) > 0 ) { out . write ( "\n" ) ; indent ( ) ; out . write ( "    throws " ) ; for ( int i = 0 ; i < throwsTypes . size ( ) ; i ++ ) { if ( i != 0 ) { out . write ( ", " ) ; } emitCompressedType ( throwsTypes . get ( i ) ) ; } } if ( modifiers . contains ( ABSTRACT ) || Scope . INTERFACE_DECLARATION . equals ( scopes . peek ( ) ) ) { out . write ( ";\n" ) ; scopes . push ( Scope . ABSTRACT_METHOD ) ; } else { out . write ( " {\n" ) ; scopes . push ( returnType == null ? Scope . CONSTRUCTOR : Scope . NON_ABSTRACT_METHOD ) ; } return this ;


signature:
public class JavaWriter { /** * Emits a single line comment . */
public JavaWriter emitSingleLineComment ( String comment , Object ... args ) throws IOException { } }

implementation: indent ( ) ; out . write ( "// " ) ; out . write ( String . format ( comment , args ) ) ; out . write ( "\n" ) ; return this ;


signature:
public class JavaWriter { /** * A simple switch to emit the proper enum depending if its last causing it to be terminated
 * by a semi - colon ( { @ code ; } ) . */
public JavaWriter emitEnumValue ( String name , boolean isLast ) throws IOException { } }

implementation: return isLast ? emitLastEnumValue ( name ) : emitEnumValue ( name ) ;


signature:
public class JavaWriter { /** * Emit a list of enum values followed by a semi - colon ( { @ code ; } ) . */
public JavaWriter emitEnumValues ( Iterable < String > names ) throws IOException { } }

implementation: Iterator < String > iterator = names . iterator ( ) ; while ( iterator . hasNext ( ) ) { String name = iterator . next ( ) ; if ( iterator . hasNext ( ) ) { emitEnumValue ( name ) ; } else { emitLastEnumValue ( name ) ; } } return this ;


signature:
public class JavaWriter { /** * Equivalent to { @ code annotation ( annotation , emptyMap ( ) ) } . */
public JavaWriter emitAnnotation ( String annotation ) throws IOException { } }

implementation: return emitAnnotation ( annotation , Collections . < String , Object > emptyMap ( ) ) ;


signature:
public class JavaWriter { /** * Equivalent to { @ code annotation ( annotationType . getName ( ) , emptyMap ( ) ) } . */
public JavaWriter emitAnnotation ( Class < ? extends Annotation > annotationType ) throws IOException { } }

implementation: return emitAnnotation ( type ( annotationType ) , Collections . < String , Object > emptyMap ( ) ) ;


signature:
public class JavaWriter { /** * Annotates the next element with { @ code annotationType } and a { @ code value } .
 * @ param value an object used as the default ( value ) parameter of the annotation . The value will
 * be encoded using Object . toString ( ) ; use { @ link # stringLiteral } for String values . Object
 * arrays are written one element per line . */
public JavaWriter emitAnnotation ( Class < ? extends Annotation > annotationType , Object value ) throws IOException { } }

implementation: return emitAnnotation ( type ( annotationType ) , value ) ;


signature:
public class JavaWriter { /** * Annotates the next element with { @ code annotation } and a { @ code value } .
 * @ param value an object used as the default ( value ) parameter of the annotation . The value will
 * be encoded using Object . toString ( ) ; use { @ link # stringLiteral } for String values . Object
 * arrays are written one element per line . */
public JavaWriter emitAnnotation ( String annotation , Object value ) throws IOException { } }

implementation: indent ( ) ; out . write ( "@" ) ; emitCompressedType ( annotation ) ; out . write ( "(" ) ; emitAnnotationValue ( value ) ; out . write ( ")" ) ; out . write ( "\n" ) ; return this ;


signature:
public class JavaWriter { /** * Equivalent to { @ code annotation ( annotationType . getName ( ) , attributes ) } . */
public JavaWriter emitAnnotation ( Class < ? extends Annotation > annotationType , Map < String , ? > attributes ) throws IOException { } }

implementation: return emitAnnotation ( type ( annotationType ) , attributes ) ;


signature:
public class JavaWriter { /** * Annotates the next element with { @ code annotation } and { @ code attributes } .
 * @ param attributes a map from annotation attribute names to their values . Values are encoded
 * using Object . toString ( ) ; use { @ link # stringLiteral } for String values . Object arrays are
 * written one element per line . */
public JavaWriter emitAnnotation ( String annotation , Map < String , ? > attributes ) throws IOException { } }

implementation: indent ( ) ; out . write ( "@" ) ; emitCompressedType ( annotation ) ; switch ( attributes . size ( ) ) { case 0 : break ; case 1 : Entry < String , ? > onlyEntry = attributes . entrySet ( ) . iterator ( ) . next ( ) ; out . write ( "(" ) ; if ( ! "value" . equals ( onlyEntry . getKey ( ) ) ) { out . write ( onlyEntry . getKey ( ) ) ; out . write ( " = " ) ; } emitAnnotationValue ( onlyEntry . getValue ( ) ) ; out . write ( ")" ) ; break ; default : boolean split = attributes . size ( ) > MAX_SINGLE_LINE_ATTRIBUTES || containsArray ( attributes . values ( ) ) ; out . write ( "(" ) ; scopes . push ( Scope . ANNOTATION_ATTRIBUTE ) ; String separator = split ? "\n" : "" ; for ( Entry < String , ? > entry : attributes . entrySet ( ) ) { out . write ( separator ) ; separator = split ? ",\n" : ", " ; if ( split ) { indent ( ) ; } out . write ( entry . getKey ( ) ) ; out . write ( " = " ) ; Object value = entry . getValue ( ) ; emitAnnotationValue ( value ) ; } popScope ( Scope . ANNOTATION_ATTRIBUTE ) ; if ( split ) { out . write ( "\n" ) ; indent ( ) ; } out . write ( ")" ) ; break ; } out . write ( "\n" ) ; return this ;


signature:
public class JavaWriter { /** * Writes a single annotation value . If the value is an array , each element in the array will be
 * written to its own line . */
private JavaWriter emitAnnotationValue ( Object value ) throws IOException { } }

implementation: if ( value instanceof Object [ ] ) { out . write ( "{" ) ; boolean firstValue = true ; scopes . push ( Scope . ANNOTATION_ARRAY_VALUE ) ; for ( Object o : ( ( Object [ ] ) value ) ) { if ( firstValue ) { firstValue = false ; out . write ( "\n" ) ; } else { out . write ( ",\n" ) ; } indent ( ) ; out . write ( o . toString ( ) ) ; } popScope ( Scope . ANNOTATION_ARRAY_VALUE ) ; out . write ( "\n" ) ; indent ( ) ; out . write ( "}" ) ; } else { out . write ( value . toString ( ) ) ; } return this ;


signature:
public class JavaWriter { /** * Completes the current method declaration . */
public JavaWriter endMethod ( ) throws IOException { } }

implementation:
Scope popped = scopes . pop ( ) ; // support calling a constructor a " method " to support the legacy code
if ( popped == Scope . NON_ABSTRACT_METHOD || popped == Scope . CONSTRUCTOR ) { indent ( ) ; out . write ( "}\n" ) ; } else if ( popped != Scope . ABSTRACT_METHOD ) { throw new IllegalStateException ( ) ; } return this ;


signature:
public class JavaWriter { /** * Returns the string literal representing { @ code data } , including wrapping quotes . */
public static String stringLiteral ( String data ) { } }

implementation: StringBuilder result = new StringBuilder ( ) ; result . append ( '"' ) ; for ( int i = 0 ; i < data . length ( ) ; i ++ ) { char c = data . charAt ( i ) ; switch ( c ) { case '"' : result . append ( "\\\"" ) ; break ; case '\\' : result . append ( "\\\\" ) ; break ; case '\b' : result . append ( "\\b" ) ; break ; case '\t' : result . append ( "\\t" ) ; break ; case '\n' : result . append ( "\\n" ) ; break ; case '\f' : result . append ( "\\f" ) ; break ; case '\r' : result . append ( "\\r" ) ; break ; default : if ( Character . isISOControl ( c ) ) { result . append ( String . format ( "\\u%04x" , ( int ) c ) ) ; } else { result . append ( c ) ; } } } result . append ( '"' ) ; return result . toString ( ) ;