signature:
public class Dfa { /** * ' miss ' - - the state set was not found in the stateSets .
 * @ param co
 * @ param cp
 * @ return */
StateSet miss ( StateSet css , short co , int cp ) { } }

implementation:
if ( css . outs [ co ] != null ) { return css . outs [ co ] ; } /* first , what set of states would we end up in ? */
BitSet work = new BitSet ( nstates ) ; boolean ispost = false ; boolean noprogress = true ; boolean gotstate = false ; for ( int i = 0 ; i < nstates ; i ++ ) { if ( css . states . get ( i ) ) { long ca ; int ax ; short caco ; int catarget ; for ( ax = cnfa . states [ i ] + 1 , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ; caco != Constants . COLORLESS ; ax ++ , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ) { if ( caco == co ) { work . set ( catarget ) ; gotstate = true ; if ( catarget == cnfa . post ) { ispost = true ; } // get target state , index arcs , get color , compare to 0.
if ( 0 == Cnfa . carcColor ( cnfa . arcs [ cnfa . states [ catarget ] ] ) ) { noprogress = false ; } } } } } boolean dolacons = gotstate && cnfa . hasLacons ; boolean sawlacons = false ; while ( dolacons ) { /* transitive closure */
dolacons = false ; for ( int i = 0 ; i < nstates ; i ++ ) { if ( work . get ( i ) ) { long ca ; int ax ; short caco ; int catarget ; for ( ax = cnfa . states [ i ] + 1 , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ; caco != Constants . COLORLESS ; ax ++ , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ) { if ( caco <= ncolors ) { continue ; /* NOTE CONTINUE */
} sawlacons = true ; if ( work . get ( catarget ) ) { continue ; /* NOTE CONTINUE */
} if ( ! lacon ( cp , caco ) ) { continue ; /* NOTE CONTINUE */
} work . set ( catarget ) ; dolacons = true ; if ( catarget == cnfa . post ) { ispost = true ; } if ( 0 == Cnfa . carcColor ( cnfa . arcs [ cnfa . states [ catarget ] ] ) ) { noprogress = false ; } } } } } if ( ! gotstate ) { return null ; } StateSet stateSet = stateSets . get ( work ) ; if ( stateSet == null ) { stateSet = new StateSet ( work , ncolors ) ; stateSet . ins = new Arcp ( null , Constants . WHITE ) ; stateSet . poststate = ispost ; stateSet . noprogress |= noprogress ; /* lastseen to be dealt with by caller */
stateSets . put ( work , stateSet ) ; } if ( ! sawlacons ) { css . outs [ co ] = stateSet ; css . inchain [ co ] = stateSet . ins ; stateSet . ins = new Arcp ( css , co ) ; } return stateSet ;


signature:
public class Dfa { /** * longest - longest - preferred matching engine
 * @ return endpoint or - 1 */
int longest ( int start , int stop , boolean [ ] hitstop ) { } }

implementation:
int cp ; int realstop = ( stop == runtime . dataLength ) ? stop : stop + 1 ; short co ; StateSet css ; int post ; /* initialize */
css = initialize ( start ) ; cp = start ; if ( hitstop != null ) { hitstop [ 0 ] = false ; } /* startup */
if ( cp == 0 ) { co = cnfa . bos [ 0 != ( runtime . eflags & Flags . REG_NOTBOL ) ? 0 : 1 ] ; } else { char theChar = runtime . data . charAt ( cp - 1 ) ; if ( Character . isLowSurrogate ( theChar ) ) { // collect the other end of the surrogate .
theChar = runtime . data . charAt ( cp - 2 ) ; char high = theChar ; int codepoint = Character . toCodePoint ( high , theChar ) ; co = cm . getcolor ( codepoint ) ; // and get a color for the pair .
} else { co = cm . getcolor ( theChar ) ; } } css = miss ( css , co , cp ) ; if ( css == null ) { return - 1 ; } css . setLastSeen ( cp ) ; StateSet ss ; /* main loop */
while ( cp < realstop ) { char theChar = runtime . data . charAt ( cp ) ; int increment = 1 ; if ( Character . isHighSurrogate ( theChar ) ) { int codepoint = Character . toCodePoint ( theChar , runtime . data . charAt ( cp + 1 ) ) ; co = cm . getcolor ( codepoint ) ; increment = 2 ; } else { co = cm . getcolor ( theChar ) ; } ss = css . outs [ co ] ; if ( ss == null ) { ss = miss ( css , co , cp + increment ) ; if ( ss == null ) { break ; /* NOTE BREAK OUT */
} } cp = cp + increment ; ss . setLastSeen ( cp ) ; css = ss ; } /* shutdown */
if ( cp == runtime . dataLength && stop == runtime . dataLength ) { if ( hitstop != null ) { hitstop [ 0 ] = true ; } co = cnfa . eos [ 0 != ( runtime . eflags & Flags . REG_NOTEOL ) ? 0 : 1 ] ; ss = miss ( css , co , cp ) ; /* special case : match ended at eol ? */
if ( ss != null && ss . poststate ) { return cp ; } else if ( ss != null ) { ss . setLastSeen ( cp ) ; /* to be tidy */
} } /* find last match , if any */
post = - 1 ; for ( StateSet thisSS : stateSets . values ( ) ) { // . object2ObjectEntrySet ( ) ) {
if ( thisSS . poststate && post != thisSS . getLastSeen ( ) && ( post == - 1 || post < thisSS . getLastSeen ( ) ) ) { post = thisSS . getLastSeen ( ) ; } } if ( post != - 1 ) { /* found one */
/* Post points after the codepoint after the last one in the match ( ! ) */
/* So , if that is an SMP codepoint , we need to back up 2 to get to the beginning of it ,
 * and thus be just after the last character of the match . */
char postChar = runtime . data . charAt ( post - 1 ) ; if ( Character . isLowSurrogate ( postChar ) ) { return post - 2 ; } else { return post - 1 ; } } return - 1 ;


signature:
public class Dfa { /** * lastcold - determine last point at which no progress had been made
 * @ return offset or - 1 */
int lastcold ( ) { } }

implementation: int nopr = 0 ; for ( StateSet ss : stateSets . values ( ) ) { if ( ss . noprogress && nopr < ss . getLastSeen ( ) ) { nopr = ss . getLastSeen ( ) ; } } return nopr ;


signature:
public class Locale { /** * eclass - Because we have no MCCE support , this
 * just processing single characters . */
static UnicodeSet eclass ( char c , boolean cases ) { } }

implementation:
/* otherwise , none */
if ( cases ) { return allcases ( c ) ; } else { UnicodeSet set = new UnicodeSet ( ) ; set . add ( c ) ; return set ; }


signature:
public class Locale { /** * allcases - supply cvec for all case counterparts of a chr ( including itself )
 * This is a shortcut , preferably an efficient one , for simple characters ;
 * messy cases are done via range ( ) . */
static UnicodeSet allcases ( int c ) { } }

implementation: UnicodeSet set = new UnicodeSet ( ) ; set . add ( c ) ; set . closeOver ( UnicodeSet . ADD_CASE_MAPPINGS ) ; return set ;


signature:
public class Locale { /** * Return a UnicodeSet for a character class name .
 * It appears that the names that TCL accepts are also acceptable to ICU .
 * @ param cclassName class name
 * @ param casefold whether to include casefolding
 * @ return set */
public static UnicodeSet cclass ( String cclassName , boolean casefold ) throws RegexException { } }

implementation: try { if ( casefold ) { return KNOWN_SETS_CI . get ( cclassName ) ; } else { return KNOWN_SETS_CS . get ( cclassName ) ; } } catch ( ExecutionException e ) { Throwables . propagateIfInstanceOf ( e . getCause ( ) , RegexException . class ) ; throw new RegexRuntimeException ( e . getCause ( ) ) ; }


signature:
public class CnfaBuilder { /** * carcsort - sort compacted - NFA arcs by color
 * Really dumb algorithm , but if the list is long enough for that to matter ,
 * you ' re in real trouble anyway . */
void carcsort ( int first , int last ) { } }

implementation: int p ; int q ; long tmp ; if ( last - first <= 1 ) { return ; } for ( p = first ; p <= last ; p ++ ) { for ( q = p ; q <= last ; q ++ ) { short pco = Cnfa . carcColor ( arcs [ p ] ) ; short qco = Cnfa . carcColor ( arcs [ q ] ) ; int pto = Cnfa . carcTarget ( arcs [ p ] ) ; int qto = Cnfa . carcTarget ( arcs [ q ] ) ; if ( pco > qco || ( pco == qco && pto > qto ) ) { assert p != q ; tmp = arcs [ p ] ; arcs [ p ] = arcs [ q ] ; arcs [ q ] = tmp ; } } }


signature:
public class Subre { /** * dumpst - dump a subRE tree */
String dumpst ( boolean nfapresent ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%s. `%c'" , shortId ( ) , op ) ) ; if ( 0 != ( flags & LONGER ) ) { sb . append ( " longest" ) ; } if ( 0 != ( flags & SHORTER ) ) { sb . append ( " shortest" ) ; } if ( 0 != ( flags & MIXED ) ) { sb . append ( " hasmixed" ) ; } if ( 0 != ( flags & CAP ) ) { sb . append ( " hascapture" ) ; } if ( 0 != ( flags & BACKR ) ) { sb . append ( " hasbackref" ) ; } if ( 0 == ( flags & INUSE ) ) { sb . append ( " UNUSED" ) ; } if ( subno != 0 ) { sb . append ( String . format ( " (#%d)" , subno ) ) ; } if ( min != 1 || max != 1 ) { sb . append ( String . format ( " {%d," , min ) ) ; if ( max != Compiler . INFINITY ) { sb . append ( String . format ( "%d" , max ) ) ; } sb . append ( "}" ) ; } if ( nfapresent ) { sb . append ( String . format ( " %d-%d" , begin . no , end . no ) ) ; } if ( left != null ) { sb . append ( String . format ( " L:%s" , left . toString ( ) ) ) ; } if ( right != null ) { sb . append ( String . format ( " R:%s" , right . toString ( ) ) ) ; } sb . append ( "\n" ) ; if ( left != null ) { left . dumpst ( nfapresent ) ; } if ( right != null ) { right . dumpst ( nfapresent ) ; } return sb . toString ( ) ;


signature:
public class HsreMatcher { /** * Called by all the ' resetting ' functions .
 * Allows find to work as specified . */
private void resetState ( ) { } }

implementation:
// if there are any matches sitting in the runtime , eliminate .
if ( runtime != null && runtime . match != null ) { runtime . match . clear ( ) ; } nextFindOffset = regionStart ;


signature:
public class Nfa { /** * Factory method for new states .
 * @ return a new state wired into this Nfa . */
State newstate ( int flag ) { } }

implementation:
State newState = new State ( ) ; newState . no = nstates ++ ; // a unique number .
if ( states == null ) { states = newState ; } if ( slast != null ) { assert slast . next == null ; slast . next = newState ; } newState . prev = slast ; slast = newState ; newState . flag = flag ; return newState ;


signature:
public class Nfa { /** * moveouts - move all out arcs of a state to another state */
void moveouts ( State old , State newState ) { } }

implementation: Arc a ; assert old != newState ; while ( ( a = old . outs ) != null ) { cparc ( a , newState , a . to ) ; freearc ( a ) ; }


signature:
public class Nfa { /** * moveins - move all in arcs of a state to another state
 * You might think this could be done better by just updating the
 * existing arcs , and you would be right if it weren ' t for the desire
 * for duplicate suppression , which makes it easier to just make new
 * ones to exploit the suppression built into newarc . */
void moveins ( State old , State newState ) { } }

implementation: Arc a ; assert old != newState ; while ( ( a = old . ins ) != null ) { cparc ( a , a . from , newState ) ; freearc ( a ) ; } assert old . nins == 0 ; assert old . ins == null ;


signature:
public class Nfa { /** * copyins - copy all in arcs of a state to another state */
void copyins ( State old , State newState ) { } }

implementation: Arc a ; assert old != newState ; for ( a = old . ins ; a != null ; a = a . inchain ) { cparc ( a , a . from , newState ) ; }


signature:
public class Nfa { /** * copyouts - copy all out arcs of a state to another state */
void copyouts ( State old , State newState ) { } }

implementation: Arc a ; assert old != newState ; for ( a = old . outs ; a != null ; a = a . outchain ) { cparc ( a , newState , a . to ) ; }


signature:
public class Nfa { /** * get rid of a state , releasing all its arcs .
 * I ' m not sure that all this is needed , as opposed to depending on the GC .
 * @ param s the state to dispose of . */
void dropstate ( State s ) { } }

implementation: Arc a ; while ( ( a = s . ins ) != null ) { freearc ( a ) ; } while ( ( a = s . outs ) != null ) { freearc ( a ) ; } freestate ( s ) ;


signature:
public class Nfa { /** * Unwire a state from the NFA .
 * @ param s the state */
void freestate ( State s ) { } }

implementation: assert s != null ; assert s . nins == 0 ; assert s . nouts == 0 ; if ( s . next != null ) { s . next . prev = s . prev ; } else { assert s == slast ; slast = s . prev ; } if ( s . prev != null ) { s . prev . next = s . next ; } else { assert s == states ; states = s . next ; }


signature:
public class Nfa { /** * cparc - allocate a new arc within an NFA , copying details from old one */
void cparc ( Arc oa , State from , State to ) { } }

implementation: newarc ( oa . type , oa . co , from , to ) ;


signature:
public class Nfa { /** * dupnfa - duplicate sub - NFA
 * Another recursive traversal , this time using tmp to point to duplicates
 * as well as mark already - seen states . ( You knew there was a reason why
 * it ' s a state pointer , didn ' t you ? : - ) )
 * @ param start duplicate starting here
 * @ param stop ending here .
 * @ param from stringing dup from here
 * @ param to here . */
void dupnfa ( State start , State stop , State from , State to ) { } }

implementation:
if ( start == stop ) { newarc ( Compiler . EMPTY , ( short ) 0 , from , to ) ; return ; } stop . tmp = to ; duptraverse ( start , from ) ; /* done , except for clearing out the tmp pointers */
stop . tmp = null ; cleartraverse ( start ) ;


signature:
public class Nfa { /** * duptraverse - recursive heart of dupnfa */
void duptraverse ( State s , State stmp ) { } }

implementation:
Arc a ; if ( s . tmp != null ) { return ; /* already done */
} s . tmp = ( stmp == null ) ? newstate ( ) : stmp ; if ( s . tmp == null ) { return ; } for ( a = s . outs ; a != null ; a = a . outchain ) { duptraverse ( a . to , null ) ; assert a . to . tmp != null ; cparc ( a , s . tmp , a . to . tmp ) ; }


signature:
public class Nfa { /** * - cleartraverse - recursive cleanup for algorithms that leave tmp ptrs set */
void cleartraverse ( State s ) { } }

implementation: Arc a ; if ( s . tmp == null ) { return ; } s . tmp = null ; for ( a = s . outs ; a != null ; a = a . outchain ) { cleartraverse ( a . to ) ; }


signature:
public class Nfa { /** * specialcolors - fill in special colors for an NFA */
void specialcolors ( ) { } }

implementation:
/* false colors for BOS , BOL , EOS , EOL */
if ( parent == null ) { bos [ 0 ] = cm . pseudocolor ( ) ; bos [ 1 ] = cm . pseudocolor ( ) ; eos [ 0 ] = cm . pseudocolor ( ) ; eos [ 1 ] = cm . pseudocolor ( ) ; } else { assert parent . bos [ 0 ] != Constants . COLORLESS ; bos [ 0 ] = parent . bos [ 0 ] ; assert parent . bos [ 1 ] != Constants . COLORLESS ; bos [ 1 ] = parent . bos [ 1 ] ; assert parent . eos [ 0 ] != Constants . COLORLESS ; eos [ 0 ] = parent . eos [ 0 ] ; assert parent . eos [ 1 ] != Constants . COLORLESS ; eos [ 1 ] = parent . eos [ 1 ] ; }


signature:
public class Nfa { /** * dumpnfa - dump an NFA in human - readable form */
void dumpnfa ( ) { } }

implementation: if ( ! LOG . isDebugEnabled ( ) || ! IS_DEBUG ) { return ; } LOG . debug ( "dump nfa" ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "pre %d, post %d init %d final %d" , pre . no , post . no , init . no , finalState . no ) ) ; if ( bos [ 0 ] != Constants . COLORLESS ) { sb . append ( String . format ( ", bos [%d]" , bos [ 0 ] ) ) ; } if ( bos [ 1 ] != Constants . COLORLESS ) { sb . append ( String . format ( ", bol [%d]" , bos [ 1 ] ) ) ; } if ( eos [ 0 ] != Constants . COLORLESS ) { sb . append ( String . format ( ", eos [%d]" , eos [ 0 ] ) ) ; } if ( eos [ 1 ] != Constants . COLORLESS ) { sb . append ( String . format ( ", eol [%d]" , eos [ 1 ] ) ) ; } LOG . debug ( sb . toString ( ) ) ; for ( State s = states ; s != null ; s = s . next ) { dumpstate ( s ) ; } if ( parent == null ) { cm . dumpcolors ( ) ; }


signature:
public class Nfa { /** * dumpstate - dump an NFA state in human - readable form */
void dumpstate ( State s ) { } }

implementation: Arc a ; if ( ! LOG . isDebugEnabled ( ) || ! IS_DEBUG ) { return ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "State %d%s%c" , s . no , ( s . tmp != null ) ? "T" : "" , ( s . flag != 0 ) ? ( char ) s . flag : '.' ) ) ; if ( s . prev != null && s . prev . next != s ) { sb . append ( String . format ( "\tstate chain bad" ) ) ; } if ( s . nouts == 0 ) { sb . append ( "\tno out arcs" ) ; } else { dumparcs ( s , sb ) ; } LOG . debug ( sb . toString ( ) ) ; for ( a = s . ins ; a != null ; a = a . inchain ) { if ( a . to != s ) { LOG . debug ( String . format ( "\tlink from %d to %d on %d's in-chain" , a . from . no , a . to . no , s . no ) ) ; } }


signature:
public class Nfa { /** * dumparcs - dump out - arcs in human - readable form */
void dumparcs ( State s , StringBuilder sb ) { } }

implementation:
int pos ; assert s . nouts > 0 ; /* printing arcs in reverse order is usually clearer */
pos = dumprarcs ( s . outs , s , 1 , sb ) ; if ( pos != 1 ) { // sb . append ( " \ n " ) ;
}


signature:
public class Nfa { /** * dumprarcs - dump remaining outarcs , recursively , in reverse order
 * @ return resulting print position */
int dumprarcs ( Arc a , State s , int pos , StringBuilder sb ) { } }

implementation: if ( a . outchain != null ) { pos = dumprarcs ( a . outchain , s , pos , sb ) ; } dumparc ( a , s , sb ) ; if ( pos == 5 ) { sb . append ( "\n" ) ; pos = 1 ; } else { pos ++ ; } return pos ;


signature:
public class Nfa { /** * dumparc - dump one outarc in readable form , including prefixing tab */
void dumparc ( Arc a , State s , StringBuilder sb ) { } }

implementation:
sb . append ( "\t" ) ; switch ( a . type ) { case Compiler . PLAIN : sb . append ( String . format ( "[%d]" , a . co ) ) ; break ; case Compiler . AHEAD : sb . append ( String . format ( ">%d>" , a . co ) ) ; break ; case Compiler . BEHIND : sb . append ( String . format ( "<%d<" , a . co ) ) ; break ; case Compiler . LACON : sb . append ( String . format ( ":%d:" , a . co ) ) ; break ; case '^' : case '$' : sb . append ( String . format ( "%c%d" , ( char ) a . type , a . co ) ) ; break ; case Compiler . EMPTY : break ; default : sb . append ( String . format ( "0x%x/0%d" , a . type , a . co ) ) ; break ; } if ( a . from != s ) { sb . append ( String . format ( "?%d?" , a . from . no ) ) ; } sb . append ( "->" ) ; if ( a . to == null ) { sb . append ( "null" ) ; Arc aa ; for ( aa = a . to . ins ; aa != null ; aa = aa . inchain ) { if ( aa == a ) { break ; /* NOTE BREAK OUT */
} } if ( aa == null ) { LOG . debug ( "?!?" ) ; /* missing from in - chain */
} } else { sb . append ( String . format ( "%d" , a . to . no ) ) ; }


signature:
public class Nfa { /** * optimize - optimize an NFA
 * @ return re _ info bits */
long optimize ( ) throws RegexException { } }

implementation:
LOG . debug ( "initial cleanup" ) ; cleanup ( ) ; /* may simplify situation */
dumpnfa ( ) ; LOG . debug ( "empties" ) ; fixempties ( ) ; /* get rid of EMPTY arcs */
LOG . debug ( "constraints" ) ; pullback ( ) ; /* pull back constraints backward */
pushfwd ( ) ; /* push fwd constraints forward */
LOG . debug ( "final cleanup" ) ; cleanup ( ) ; /* final tidying */
return analyze ( ) ; /* and analysis */


signature:
public class Nfa { /** * analyze - ascertain potentially - useful facts about an optimized NFA
 * @ return re _ info bits . */
long analyze ( ) { } }

implementation: Arc a ; Arc aa ; if ( pre . outs == null ) { return Flags . REG_UIMPOSSIBLE ; } for ( a = pre . outs ; a != null ; a = a . outchain ) { for ( aa = a . to . outs ; aa != null ; aa = aa . outchain ) { if ( aa . to == post ) { return Flags . REG_UEMPTYMATCH ; } } } return 0 ;


signature:
public class Nfa { /** * pullback - pull back constraints backward to ( with luck ) eliminate them */
void pullback ( ) throws RegexException { } }

implementation:
State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and pull until there are no more */
do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == '^' || a . type == Compiler . BEHIND ) { if ( pull ( a ) ) { progress = true ; } } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ; for ( a = pre . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == '^' ) { assert a . co == 0 || a . co == 1 ; newarc ( Compiler . PLAIN , bos [ a . co ] , a . from , a . to ) ; freearc ( a ) ; } }


signature:
public class Nfa { /** * - pull - pull a back constraint backward past its source state
 * A significant property of this function is that it deletes at most
 * one state - - the constraint ' s from state - - and only if the constraint
 * was that state ' s last outarc .
 * @ return success */
boolean pull ( Arc con ) throws RegexException { } }

implementation:
State from = con . from ; State to = con . to ; Arc a ; Arc nexta ; State s ; if ( from == to ) { /* circular constraint is pointless */
freearc ( con ) ; return true ; } if ( 0 != from . flag ) { /* can ' t pull back beyond start */
return false ; } if ( from . nins == 0 ) { /* unreachable */
freearc ( con ) ; return true ; } /* first , clone from state if necessary to avoid other outarcs */
if ( from . nouts > 1 ) { s = newstate ( ) ; assert to != from ; /* con is not an inarc */
copyins ( from , s ) ; /* duplicate inarcs */
cparc ( con , s , to ) ; /* move constraint arc */
freearc ( con ) ; from = s ; con = from . outs ; } assert from . nouts == 1 ; /* propagate the constraint into the from state ' s inarcs */
for ( a = from . ins ; a != null ; a = nexta ) { nexta = a . inchain ; switch ( combine ( con , a ) ) { case INCOMPATIBLE : /* destroy the arc */
freearc ( a ) ; break ; case SATISFIED : /* no action needed */
break ; case COMPATIBLE : /* swap the two arcs , more or less */
s = newstate ( ) ; cparc ( a , s , to ) ; /* anticipate move */
cparc ( con , a . from , s ) ; freearc ( a ) ; break ; default : throw new RegexException ( "REG_ASSERT" ) ; } } /* remaining inarcs , if any , incorporate the constraint */
moveins ( from , to ) ; dropstate ( from ) ; /* will free the constraint */
return true ;


signature:
public class Nfa { /** * pushfwd - push forward constraints forward to ( with luck ) eliminate them */
void pushfwd ( ) throws RegexException { } }

implementation:
State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and push until there are no more */
do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . ins ; a != null ; a = nexta ) { nexta = a . inchain ; if ( a . type == '$' || a . type == Compiler . AHEAD ) { if ( push ( a ) ) { progress = true ; } } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ; for ( a = post . ins ; a != null ; a = nexta ) { nexta = a . inchain ; if ( a . type == '$' ) { assert a . co == 0 || a . co == 1 ; newarc ( Compiler . PLAIN , eos [ a . co ] , a . from , a . to ) ; freearc ( a ) ; } }


signature:
public class Nfa { /** * push - push a forward constraint forward past its destination state
 * A significant property of this function is that it deletes at most
 * one state - - the constraint ' s to state - - and only if the constraint
 * was that state ' s last inarc . */
boolean push ( Arc con ) throws RegexException { } }

implementation:
State from = con . from ; State to = con . to ; Arc a ; Arc nexta ; State s ; if ( to == from ) { /* circular constraint is pointless */
freearc ( con ) ; return true ; } if ( 0 != to . flag ) { /* can ' t push forward beyond end */
return false ; } if ( to . nouts == 0 ) { /* dead end */
freearc ( con ) ; return true ; } /* first , clone to state if necessary to avoid other inarcs */
if ( to . nins > 1 ) { s = newstate ( ) ; copyouts ( to , s ) ; /* duplicate outarcs */
cparc ( con , from , s ) ; /* move constraint */
freearc ( con ) ; to = s ; con = to . ins ; } assert to . nins == 1 ; /* propagate the constraint into the to state ' s outarcs */
for ( a = to . outs ; a != null ; a = nexta ) { nexta = a . outchain ; switch ( combine ( con , a ) ) { case INCOMPATIBLE : /* destroy the arc */
freearc ( a ) ; break ; case SATISFIED : /* no action needed */
break ; case COMPATIBLE : /* swap the two arcs , more or less */
s = newstate ( ) ; cparc ( con , s , a . to ) ; /* anticipate move */
cparc ( a , from , s ) ; freearc ( a ) ; break ; default : throw new RegexException ( "REG_ASSERT" ) ; } } /* remaining outarcs , if any , incorporate the constraint */
moveouts ( to , from ) ; dropstate ( to ) ; /* will free the constraint */
return true ;


signature:
public class Nfa { /** * combine - constraint lands on an arc , what happens ?
 * @ return result */
int combine ( Arc con , Arc a ) throws RegexException { } }

implementation:
// # define CA ( ct , at ) ( ( ( ct ) < < CHAR _ BIT ) | ( at ) )
// CA ( con - > type , a - > type ) ) {
switch ( ( con . type << 8 ) | a . type ) { case '^' << 8 | Compiler . PLAIN : /* newlines are handled separately */
case '$' << 8 | Compiler . PLAIN : return INCOMPATIBLE ; case Compiler . AHEAD << 8 | Compiler . PLAIN : /* color constraints meet colors */
case Compiler . BEHIND << 8 | Compiler . PLAIN : if ( con . co == a . co ) { return SATISFIED ; } return INCOMPATIBLE ; case '^' << 8 | '^' : /* collision , similar constraints */
case '$' << 8 | '$' : case Compiler . AHEAD << 8 | Compiler . AHEAD : case Compiler . BEHIND << 8 | Compiler . BEHIND : if ( con . co == a . co ) { /* true duplication */
return SATISFIED ; } return INCOMPATIBLE ; case '^' << 8 | Compiler . BEHIND : /* collision , dissimilar constraints */
case Compiler . BEHIND << 8 | '^' : case '$' << 8 | Compiler . AHEAD : case Compiler . AHEAD << 8 | '$' : return INCOMPATIBLE ; case '^' << 8 | Compiler . AHEAD : case Compiler . BEHIND << 8 | '$' : case Compiler . BEHIND << 8 | Compiler . AHEAD : case '$' << 8 | '^' : case '$' << 8 | Compiler . BEHIND : case Compiler . AHEAD << 8 | '^' : case Compiler . AHEAD << 8 | Compiler . BEHIND : case '^' << 8 | Compiler . LACON : case Compiler . BEHIND << 8 | Compiler . LACON : case '$' << 8 | Compiler . LACON : case Compiler . AHEAD << 8 | Compiler . LACON : return COMPATIBLE ; default : throw new RuntimeException ( "Impossible arc" ) ; }


signature:
public class Nfa { /** * cleanup - clean up NFA after optimizations */
void cleanup ( ) { } }

implementation:
State s ; State nexts ; int n ; /* clear out unreachable or dead - end states */
/* use pre to mark reachable , then post to mark can - reach - post */
markreachable ( pre , null , pre ) ; markcanreach ( post , pre , post ) ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; if ( s . tmp != post && 0 == s . flag ) { dropstate ( s ) ; } } assert post . nins == 0 || post . tmp == post ; cleartraverse ( pre ) ; assert post . nins == 0 || post . tmp == null ; /* the nins = = 0 ( final unreachable ) case will be caught later */
/* renumber surviving states */
n = 0 ; for ( s = states ; s != null ; s = s . next ) { s . no = n ++ ; } nstates = n ;


signature:
public class Nfa { /** * markreachable - recursive marking of reachable states
 * @ param s a state
 * @ param okay consider only states with this mark .
 * @ param mark the value to mark with */
void markreachable ( State s , State okay , State mark ) { } }

implementation: Arc a ; if ( s . tmp != okay ) { return ; } s . tmp = mark ; for ( a = s . outs ; a != null ; a = a . outchain ) { markreachable ( a . to , okay , mark ) ; }


signature:
public class Nfa { /** * markcanreach - recursive marking of states which can reach here */
void markcanreach ( State s , State okay , State mark ) { } }

implementation: Arc a ; if ( s . tmp != okay ) { return ; } s . tmp = mark ; for ( a = s . ins ; a != null ; a = a . inchain ) { markcanreach ( a . from , okay , mark ) ; }


signature:
public class Nfa { /** * fixempties - get rid of EMPTY arcs */
void fixempties ( ) { } }

implementation:
State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and eliminate empties until there are no more */
do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == Compiler . EMPTY && unempty ( a ) ) { progress = true ; } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ;


signature:
public class Nfa { /** * unempty - optimize out an EMPTY arc , if possible
 * Actually , as it stands this function always succeeds , but the return
 * value is kept with an eye on possible future changes . */
boolean unempty ( Arc a ) { } }

implementation:
State from = a . from ; State to = a . to ; boolean usefrom ; /* work on from , as opposed to to ? */
assert a . type == Compiler . EMPTY ; assert from != pre && to != post ; if ( from == to ) { /* vacuous loop */
freearc ( a ) ; return true ; } /* decide which end to work on */
usefrom = true ; /* default : attack from */
if ( from . nouts > to . nins ) { usefrom = false ; } else if ( from . nouts == to . nins ) { /* decide on secondary issue : move / copy fewest arcs */
if ( from . nins > to . nouts ) { usefrom = false ; } } freearc ( a ) ; if ( usefrom ) { if ( from . nouts == 0 ) { /* was the state ' s only outarc */
moveins ( from , to ) ; freestate ( from ) ; } else { copyins ( from , to ) ; } } else { if ( to . nins == 0 ) { /* was the state ' s only inarc */
moveouts ( to , from ) ; freestate ( to ) ; } else { copyouts ( to , from ) ; } } return true ;


signature:
public class AnalyzeTask { /** * Reads the given rule parameters file .
 * @ return The map containing the rule parameters .
 * @ throws CliExecutionException
 * If the file cannot be read . */
private Map < String , String > getRuleParameters ( ) throws CliExecutionException { } }

implementation: Map < String , String > ruleParameters ; if ( ruleParametersFile == null ) { ruleParameters = Collections . emptyMap ( ) ; } else { Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( ruleParametersFile ) ) ; } catch ( IOException e ) { throw new CliExecutionException ( "Cannot read rule parameters file '" + ruleParametersFile . getPath ( ) + "'." ) ; } ruleParameters = new TreeMap < > ( ) ; for ( String name : properties . stringPropertyNames ( ) ) { ruleParameters . put ( name , properties . getProperty ( name ) ) ; } } return ruleParameters ;


signature:
public class AnalyzeTask { /** * Get all configured rule interpreter plugins .
 * @ return The map of rule interpreter plugins grouped by their supported
 * languages .
 * @ throws CliExecutionException
 * If the plugins cannot be loaded or configured . */
private Map < String , Collection < RuleInterpreterPlugin > > getRuleInterpreterPlugins ( ) throws CliExecutionException { } }

implementation: try { return pluginRepository . getRuleInterpreterPluginRepository ( ) . getRuleInterpreterPlugins ( Collections . < String , Object > emptyMap ( ) ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( "Cannot get report plugins." , e ) ; }


signature:
public class AnalyzeTask { /** * Get all configured report plugins .
 * @ param reportContext
 * The ReportContext .
 * @ return The list of report plugins .
 * @ throws CliExecutionException
 * If the plugins cannot be loaded or configured .
 * @ param reportContext */
private Map < String , ReportPlugin > getReportPlugins ( ReportContext reportContext ) throws CliExecutionException { } }

implementation: ReportPluginRepository reportPluginRepository ; try { reportPluginRepository = pluginRepository . getReportPluginRepository ( ) ; return reportPluginRepository . getReportPlugins ( reportContext , pluginProperties ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( "Cannot get report plugins." , e ) ; }


signature:
public class AbstractAnalyzeTask { /** * Return the selection of rules .
 * @ param ruleSet
 * The rule set .
 * @ return The selection of rules . */
protected RuleSelection getRuleSelection ( RuleSet ruleSet ) { } }

implementation: return RuleSelection . select ( ruleSet , groupIds , constraintIds , conceptIds ) ;


signature:
public class Main { /** * The main method .
 * @ param args
 * The command line arguments .
 * @ throws IOException
 * If an error occurs . */
public static void main ( String [ ] args ) { } }

implementation: try { DefaultTaskFactoryImpl taskFactory = new DefaultTaskFactoryImpl ( ) ; new Main ( taskFactory ) . run ( args ) ; } catch ( CliExecutionException e ) { String message = getErrorMessage ( e ) ; LOGGER . error ( message ) ; System . exit ( e . getExitCode ( ) ) ; }


signature:
public class Main { /** * Run tasks according to the given arguments .
 * @ param args
 * The arguments .
 * @ throws CliExecutionException
 * If execution fails . */
public void run ( String [ ] args ) throws CliExecutionException { } }

implementation: Options options = gatherOptions ( taskFactory ) ; CommandLine commandLine = getCommandLine ( args , options ) ; interpretCommandLine ( commandLine , options , taskFactory ) ;


signature:
public class Main { /** * Extract an error message from the given exception and its causes .
 * @ param e
 * The exception .
 * @ return The error message . */
private static String getErrorMessage ( CliExecutionException e ) { } }

implementation: StringBuffer messageBuilder = new StringBuffer ( ) ; Throwable current = e ; do { messageBuilder . append ( "-> " ) ; messageBuilder . append ( current . getMessage ( ) ) ; current = current . getCause ( ) ; } while ( current != null ) ; return messageBuilder . toString ( ) ;


signature:
public class Main { /** * Gather all options which are supported by the task ( i . e . including standard and specific options ) .
 * @ return The options . */
private Options gatherOptions ( TaskFactory taskFactory ) { } }

implementation: final Options options = new Options ( ) ; gatherTasksOptions ( taskFactory , options ) ; gatherStandardOptions ( options ) ; return options ;


signature:
public class Main { /** * Gathers the standard options shared by all tasks .
 * @ param options
 * The standard options . */
@ SuppressWarnings ( "static-access" ) private void gatherStandardOptions ( final Options options ) { } }

implementation: options . addOption ( OptionBuilder . withArgName ( "p" ) . withDescription ( "Path to property file; default is jqassistant.properties in the class path" ) . withLongOpt ( "properties" ) . hasArg ( ) . create ( "p" ) ) ; options . addOption ( new Option ( "help" , "print this message" ) ) ;


signature:
public class Main { /** * Gathers the task specific options for all tasks .
 * @ param options
 * The task specific options . */
private void gatherTasksOptions ( TaskFactory taskFactory , Options options ) { } }

implementation: for ( Task task : taskFactory . getTasks ( ) ) { for ( Option option : task . getOptions ( ) ) { options . addOption ( option ) ; } }


signature:
public class Main { /** * Returns a string containing the names of all supported tasks .
 * @ return The names of all supported tasks . */
private String gatherTaskNames ( TaskFactory taskFactory ) { } }

implementation: final StringBuilder builder = new StringBuilder ( ) ; for ( String taskName : taskFactory . getTaskNames ( ) ) { builder . append ( "'" ) . append ( taskName ) . append ( "' " ) ; } return builder . toString ( ) . trim ( ) ;


signature:
public class Main { /** * Parse the command line and execute the requested task .
 * @ param commandLine
 * The command line .
 * @ param options
 * The known options .
 * @ throws CliExecutionException
 * If an error occurs . */
private void interpretCommandLine ( CommandLine commandLine , Options options , TaskFactory taskFactory ) throws CliExecutionException { } }

implementation: if ( commandLine . hasOption ( OPTION_HELP ) ) { printUsage ( options , null ) ; System . exit ( 1 ) ; } List < String > taskNames = commandLine . getArgList ( ) ; if ( taskNames . isEmpty ( ) ) { printUsage ( options , "A task must be specified, i.e. one  of " + gatherTaskNames ( taskFactory ) ) ; System . exit ( 1 ) ; } List < Task > tasks = new ArrayList < > ( ) ; for ( String taskName : taskNames ) { Task task = taskFactory . fromName ( taskName ) ; if ( task == null ) { printUsage ( options , "Unknown task " + taskName ) ; } tasks . add ( task ) ; } Map < String , Object > properties = readProperties ( commandLine ) ; PluginRepository pluginRepository = getPluginRepository ( ) ; try { executeTasks ( tasks , options , commandLine , pluginRepository , properties ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( "Unexpected plugin repository problem while executing tasks." , e ) ; }


signature:
public class Main { /** * Parse the command line
 * @ param args
 * The arguments .
 * @ param options
 * The known options .
 * @ return The command line . */
private CommandLine getCommandLine ( String [ ] args , Options options ) { } }

implementation: final CommandLineParser parser = new BasicParser ( ) ; CommandLine commandLine = null ; try { commandLine = parser . parse ( options , args ) ; } catch ( ParseException e ) { printUsage ( options , e . getMessage ( ) ) ; System . exit ( 1 ) ; } return commandLine ;


signature:
public class Main { /** * Executes a task .
 * @ param task
 * The task .
 * @ param option
 * The option .
 * @ param commandLine
 * The command line .
 * @ param properties
 * The plugin properties
 * @ throws IOException */
private void executeTask ( Task task , Options option , CommandLine commandLine , PluginRepository pluginRepository , Map < String , Object > properties ) throws CliExecutionException { } }

implementation: try { task . withStandardOptions ( commandLine ) ; task . withOptions ( commandLine ) ; } catch ( CliConfigurationException e ) { printUsage ( option , e . getMessage ( ) ) ; System . exit ( 1 ) ; } task . initialize ( pluginRepository , properties ) ; task . run ( ) ;


signature:
public class Main { /** * Read the plugin properties file if specified on the command line or if it exists on the class path .
 * @ param commandLine
 * The command line .
 * @ return The plugin properties .
 * @ throws CliConfigurationException
 * If an error occurs . */
private Map < String , Object > readProperties ( CommandLine commandLine ) throws CliConfigurationException { } }

implementation: final Properties properties = new Properties ( ) ; InputStream propertiesStream ; if ( commandLine . hasOption ( "p" ) ) { File propertyFile = new File ( commandLine . getOptionValue ( "p" ) ) ; if ( ! propertyFile . exists ( ) ) { throw new CliConfigurationException ( "Property file given by command line does not exist: " + propertyFile . getAbsolutePath ( ) ) ; } try { propertiesStream = new FileInputStream ( propertyFile ) ; } catch ( FileNotFoundException e ) { throw new CliConfigurationException ( "Cannot open property file." , e ) ; } } else { propertiesStream = Main . class . getResourceAsStream ( "/jqassistant.properties" ) ; } Map < String , Object > result = new HashMap < > ( ) ; if ( propertiesStream != null ) { try { properties . load ( propertiesStream ) ; } catch ( IOException e ) { throw new CliConfigurationException ( "Cannot load properties from file." , e ) ; } for ( String name : properties . stringPropertyNames ( ) ) { result . put ( name , properties . getProperty ( name ) ) ; } } return result ;


signature:
public class Main { /** * Print usage information .
 * @ param options
 * The known options .
 * @ param errorMessage
 * The error message to append . */
private void printUsage ( final Options options , final String errorMessage ) { } }

implementation: if ( errorMessage != null ) { System . out . println ( "Error: " + errorMessage ) ; } final HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( Main . class . getCanonicalName ( ) + " <task> [options]" , options ) ; System . out . println ( "Tasks are: " + gatherTaskNames ( taskFactory ) ) ; System . out . println ( "Example: " + Main . class . getCanonicalName ( ) + " scan -f java:classpath::target/classes java:classpath::target/test-classes" ) ;


signature:
public class Main { /** * Determine the JQASSISTANT _ HOME directory .
 * @ return The directory or ` null ` . */
private File getHomeDirectory ( ) { } }

implementation: String dirName = System . getenv ( ENV_JQASSISTANT_HOME ) ; if ( dirName != null ) { File dir = new File ( dirName ) ; if ( dir . exists ( ) ) { LOGGER . debug ( "Using JQASSISTANT_HOME '" + dir . getAbsolutePath ( ) + "'." ) ; return dir ; } else { LOGGER . warn ( "JQASSISTANT_HOME '" + dir . getAbsolutePath ( ) + "' points to a non-existing directory." ) ; return null ; } } LOGGER . warn ( "JQASSISTANT_HOME is not set." ) ; return null ;


signature:
public class Main { /** * Create the class loader to be used for detecting and loading plugins .
 * @ return The plugin class loader .
 * @ throws com . buschmais . jqassistant . commandline . CliExecutionException
 * If the plugins cannot be loaded . */
private ClassLoader createPluginClassLoader ( ) throws CliExecutionException { } }

implementation: ClassLoader parentClassLoader = Task . class . getClassLoader ( ) ; File homeDirectory = getHomeDirectory ( ) ; if ( homeDirectory != null ) { File pluginDirectory = new File ( homeDirectory , DIRECTORY_PLUGINS ) ; if ( pluginDirectory . exists ( ) ) { final List < URL > urls = new ArrayList < > ( ) ; final Path pluginDirectoryPath = pluginDirectory . toPath ( ) ; SimpleFileVisitor < Path > visitor = new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { if ( file . toFile ( ) . getName ( ) . endsWith ( ".jar" ) ) { urls . add ( file . toFile ( ) . toURI ( ) . toURL ( ) ) ; } return FileVisitResult . CONTINUE ; } } ; try { Files . walkFileTree ( pluginDirectoryPath , visitor ) ; } catch ( IOException e ) { throw new CliExecutionException ( "Cannot read plugin directory." , e ) ; } LOGGER . debug ( "Using plugin URLs: " + urls ) ; return new com . buschmais . jqassistant . commandline . PluginClassLoader ( urls , parentClassLoader ) ; } } return parentClassLoader ;


signature:
public class ScanTask { /** * Parses the given list of option values into a map of resources and their
 * associated ( optional ) scopes .
 * Example : ` maven : repository : : http : / / my - host / repo ` will be an entry with key
 * ` maven : repository ` and value ` http : / / my - host / repo ` .
 * @ param optionValues
 * The value .
 * @ return The map of resources and scopes . */
private Map < String , String > parseResources ( List < String > optionValues ) { } }

implementation: Map < String , String > resources = new HashMap < > ( ) ; for ( String file : optionValues ) { String [ ] parts = file . split ( "::" ) ; String fileName ; String scopeName = null ; if ( parts . length == 2 ) { scopeName = parts [ 0 ] ; fileName = parts [ 1 ] ; } else { fileName = parts [ 0 ] ; } resources . put ( fileName , scopeName ) ; } return resources ;


signature:
public class GeoJsonWriter { /** * Writes a geometry to GeoJSON .
 * Note that any data stored in getUserData ( ) of the geometries that is not on the top level
 * GeometryCollection , is lost in the process . */
public String write ( Geometry geometry ) { } }

implementation: try { JSONStringer b = new JSONStringer ( ) ; if ( geometry . getClass ( ) . equals ( GeometryCollection . class ) ) { writeFeatureCollection ( b , ( GeometryCollection ) geometry ) ; } else { writeFeature ( b , geometry ) ; } return b . toString ( ) ; } catch ( JSONException e ) { throw new GeoJsonException ( e ) ; }


signature:
public class GeoJsonWriter { /** * / * The shell of a polygon in GeoJSON is defined in counterclockwise order , in JTS , it is the
 * other way round */
private static Polygon createReversed ( Polygon geometry ) { } }

implementation: Polygon r = ( Polygon ) geometry . clone ( ) ; r . normalize ( ) ; return ( Polygon ) r . reverse ( ) ;


signature:
public class CountryBoundaries { /** * Identify which countries are guaranteed to contain the given bounding box fully .
 * The given bounding box may wrap around the 180th longitude , i . e minLongitude = 170 and
 * maxLongitude = - 170.
 * @ param minLongitude minimum longitude of geo position ( - 180 . . . 180)
 * @ param minLatitude minimum latitude of geo position ( - 90 . . . 90)
 * @ param maxLongitude maximum longitude of geo position ( - 180 . . . 180)
 * @ param maxLatitude maximum latitude of geo position ( - 90 . . . 90)
 * @ return the ids of the countries the given bounding box is guaranteed to be contained in ,
 * not in any particular order */
public Set < String > getContainingIds ( double minLongitude , double minLatitude , double maxLongitude , double maxLatitude ) { } }

implementation: Set < String > ids = new HashSet < > ( ) ; forCellsIn ( minLongitude , minLatitude , maxLongitude , maxLatitude , cell -> { if ( ids . isEmpty ( ) ) { ids . addAll ( cell . getContainingIds ( ) ) ; } else { ids . retainAll ( cell . getContainingIds ( ) ) ; } } ) ; return ids ;


signature:
public class CountryBoundaries { /** * Identify which countries intersect with the given bounding box . The given bounding box may
 * wrap around the 180th longitude , i . e minLongitude = 170 and maxLongitude = - 170.
 * @ param minLongitude minimum longitude of geo position ( - 180 . . . 180)
 * @ param minLatitude minimum latitude of geo position ( - 90 . . . 90)
 * @ param maxLongitude maximum longitude of geo position ( - 180 . . . 180)
 * @ param maxLatitude maximum latitude of geo position ( - 90 . . . 90)
 * @ return the ids of the countries the given bounding box intersects with , not in any
 * particular order */
public Set < String > getIntersectingIds ( double minLongitude , double minLatitude , double maxLongitude , double maxLatitude ) { } }

implementation: Set < String > ids = new HashSet < > ( ) ; forCellsIn ( minLongitude , minLatitude , maxLongitude , maxLatitude , cell -> { ids . addAll ( cell . getAllIds ( ) ) ; } ) ; return ids ;


signature:
public class CountryAreas { /** * http : / / geomalgorithms . com / a03 - _ inclusion . html */
private static boolean isPointInPolygon ( Point p , Point [ ] v ) { } }

implementation: int wn = 0 ; for ( int j = 0 , i = v . length - 1 ; j < v . length ; i = j ++ ) { if ( v [ i ] . y <= p . y ) { if ( v [ j ] . y > p . y ) { if ( isLeft ( v [ i ] , v [ j ] , p ) > 0 ) ++ wn ; } } else { if ( v [ j ] . y <= p . y ) { if ( isLeft ( v [ i ] , v [ j ] , p ) < 0 ) -- wn ; } } } return wn != 0 ;


signature:
public class Router { /** * If there ' s no match , returns the result with { @ link # notFound ( Object ) notFound }
 * as the target if it is set , otherwise returns { @ code null } . */
public RouteResult < T > route ( HttpMethod method , String uri ) { } }

implementation: MethodlessRouter < T > router = routers . get ( method ) ; if ( router == null ) { router = anyMethodRouter ; } QueryStringDecoder decoder = new QueryStringDecoder ( uri ) ; String [ ] tokens = decodePathTokens ( uri ) ; RouteResult < T > ret = router . route ( uri , decoder . path ( ) , tokens ) ; if ( ret != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , ret . pathParams ( ) , decoder . parameters ( ) , ret . target ( ) ) ; } if ( router != anyMethodRouter ) { ret = anyMethodRouter . route ( uri , decoder . path ( ) , tokens ) ; if ( ret != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , ret . pathParams ( ) , decoder . parameters ( ) , ret . target ( ) ) ; } } if ( notFound != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , Collections . < String , String > emptyMap ( ) , decoder . parameters ( ) , notFound ) ; } return null ;


signature:
public class Router { /** * Given a target and params , this method tries to do the reverse routing
 * and returns the URI .
 * < p > Placeholders in the path pattern will be filled with the params .
 * The params can be a map of { @ code placeholder name - > value }
 * or ordered values .
 * < p > If a param doesn ' t have a corresponding placeholder , it will be put
 * to the query part of the result URI .
 * @ return { @ code null } if there ' s no match */
public String uri ( HttpMethod method , T target , Object ... params ) { } }

implementation:
MethodlessRouter < T > router = ( method == null ) ? anyMethodRouter : routers . get ( method ) ; // Fallback to anyMethodRouter if no router is found for the method
if ( router == null ) { router = anyMethodRouter ; } String ret = router . uri ( target , params ) ; if ( ret != null ) { return ret ; } // Fallback to anyMethodRouter if the router was not anyMethodRouter and no path is found
return ( router != anyMethodRouter ) ? anyMethodRouter . uri ( target , params ) : null ;


signature: public class Router { public Router < T > CONNECT_FIRST ( String path , T target ) { } }

implementation: return addRouteFirst ( HttpMethod . CONNECT , path , target ) ;


signature: public class Router { public Router < T > CONNECT_LAST ( String path , T target ) { } }

implementation: return addRouteLast ( HttpMethod . CONNECT , path , target ) ;


signature:
public class OrderlessRouter { /** * This method does nothing if the path pattern has already been added .
 * A path pattern can only point to one target . */
public OrderlessRouter < T > addRoute ( String pathPattern , T target ) { } }

implementation: PathPattern p = new PathPattern ( pathPattern ) ; if ( routes . containsKey ( p ) ) { return this ; } routes . put ( p , target ) ; addReverseRoute ( target , p ) ; return this ;


signature:
public class OrderlessRouter { /** * Removes the route specified by the path pattern . */
public void removePathPattern ( String pathPattern ) { } }

implementation: PathPattern p = new PathPattern ( pathPattern ) ; T target = routes . remove ( p ) ; if ( target == null ) { return ; } Set < PathPattern > paths = reverseRoutes . remove ( target ) ; paths . remove ( p ) ;


signature:
public class OrderlessRouter { /** * Removes all routes leading to the target . */
public void removeTarget ( T target ) { } }

implementation:
Set < PathPattern > patterns = reverseRoutes . remove ( ObjectUtil . checkNotNull ( target , "target" ) ) ; if ( patterns == null ) { return ; } // A pattern can only point to one target .
// A target can have multiple patterns .
// Remove all patterns leading to this target .
for ( PathPattern pattern : patterns ) { routes . remove ( pattern ) ; }


signature:
public class MethodlessRouter { /** * Returns the number of routes in this router . */
public int size ( ) { } }

implementation: return first . routes ( ) . size ( ) + other . routes ( ) . size ( ) + last . routes ( ) . size ( ) ;


signature:
public class MethodlessRouter { /** * Adds route to the " first " section .
 * < p > A path pattern can only point to one target . This method does nothing if the pattern
 * has already been added . */
public MethodlessRouter < T > addRouteFirst ( String pathPattern , T target ) { } }

implementation: first . addRoute ( pathPattern , target ) ; return this ;


signature:
public class MethodlessRouter { /** * Adds route to the " other " section .
 * < p > A path pattern can only point to one target . This method does nothing if the pattern
 * has already been added . */
public MethodlessRouter < T > addRoute ( String pathPattern , T target ) { } }

implementation: other . addRoute ( pathPattern , target ) ; return this ;


signature:
public class MethodlessRouter { /** * Adds route to the " last " section .
 * < p > A path pattern can only point to one target . This method does nothing if the pattern
 * has already been added . */
public MethodlessRouter < T > addRouteLast ( String pathPattern , T target ) { } }

implementation: last . addRoute ( pathPattern , target ) ; return this ;


signature:
public class MethodlessRouter { /** * Removes the route specified by the path pattern . */
public void removePathPattern ( String pathPattern ) { } }

implementation: first . removePathPattern ( pathPattern ) ; other . removePathPattern ( pathPattern ) ; last . removePathPattern ( pathPattern ) ;


signature:
public class MethodlessRouter { /** * Removes all routes leading to the target . */
public void removeTarget ( T target ) { } }

implementation: first . removeTarget ( target ) ; other . removeTarget ( target ) ; last . removeTarget ( target ) ;


signature:
public class MethodlessRouter { /** * Checks if there ' s any matching route . */
public boolean anyMatched ( String [ ] requestPathTokens ) { } }

implementation: return first . anyMatched ( requestPathTokens ) || other . anyMatched ( requestPathTokens ) || last . anyMatched ( requestPathTokens ) ;


signature: public class BadClientSilencer { @ Override public void channelRead0 ( ChannelHandlerContext ctx , Object msg ) { } }

implementation:
// This handler is the last inbound handler .
// This means msg has not been handled by any previous handler .
ctx . close ( ) ; if ( msg != LastHttpContent . EMPTY_LAST_CONTENT ) { onUnknownMessage ( msg ) ; }


signature:
public class HibernateBookmarkStore { /** * There are two different Criterion for if a property is null or checking equality . This is a
 * convience method to return the one based on if value is null or not . */
private Criterion smartEqual ( String property , Object value ) { } }

implementation: if ( value == null ) { return Restrictions . isNull ( property ) ; } else { return Restrictions . eq ( property , value ) ; }


signature:
public class FileSystemBookmarkStore { /** * Generates the file name String for an owner and book name .
 * @ param owner The owner of the bookmark set .
 * @ param name The name of the bookmark set .
 * @ return The file name for the owner and name . */
protected String getStoreFileName ( String owner , String name ) { } }

implementation: final StringBuilder fileNameBuff = new StringBuilder ( ) ; fileNameBuff . append ( owner != null ? "_" + owner : "null" ) ; fileNameBuff . append ( "_" ) ; fileNameBuff . append ( name != null ? "_" + name : "null" ) ; fileNameBuff . append ( ".bms.xml" ) ; return fileNameBuff . toString ( ) ;


signature:
public class FileSystemBookmarkStore { /** * Generates the { @ link File } object to use for storing , retrieving
 * and deleting the bookmark set .
 * @ param owner The owner of the bookmark set .
 * @ param name The name of the bookmark set .
 * @ return The File for the owner and name . */
protected File getStoreFile ( String owner , String name ) { } }

implementation: final String fileStoreName = this . getStoreFileName ( owner , name ) ; final File basePath = this . getStoreDirectory ( ) ; final File storeFile = new File ( basePath , fileStoreName ) ; return storeFile ;


signature:
public class BookmarkSetRequestResolver { /** * Gets a BookmarkSet for the request using the injected { @ link OwnerResolver }
 * and { @ link NameResolver } .
 * < br >
 * < br >
 * If < code > create < / code > is false and no BookmarkSet exists for the name and owner null is returned .
 * < br >
 * < br >
 * If < code > create < / code > is true and no BookmarkSet exists for the name and owner a new BookmarkSet is created .
 * @ param request The request to resolve the name and owner from .
 * @ param create If a BookmarkSet should be created for the name and owner if one does not exist
 * @ return The BookmarkSet for the name and owner from the request , null if it does not exists and create is false . If create is true this will never return null . */
public BookmarkSet getBookmarkSet ( PortletRequest request , boolean create ) { } }

implementation: final String owner = this . ownerResolver . getOwner ( request ) ; final String name = this . nameResolver . getBookmarkSetName ( request ) ; BookmarkSet bookmarkSet = this . bookmarkStore . getBookmarkSet ( owner , name ) ; if ( bookmarkSet == null && create ) { bookmarkSet = this . bookmarkStore . createBookmarkSet ( owner , name ) ; if ( bookmarkSet == null ) { throw new IllegalStateException ( "Required BookmarkSet is null even after createBookmarkSet was called." ) ; } } return bookmarkSet ;


signature:
public class Folder { /** * Returns an immutable sorted view of the values of the children Map . The sorting is done
 * using the current childComparator . Warning , this is has a time cost of 2n log ( n )
 * on every call .
 * @ return An immutable sorted view of the folder ' s children . */
public List < Entry > getSortedChildren ( ) { } }

implementation: if ( this . children == null ) { return null ; } else { final Collection < Entry > childCollection = this . children . values ( ) ; final List < Entry > childList = new ArrayList < Entry > ( childCollection ) ; Collections . sort ( childList , this . childComparator ) ; return Collections . unmodifiableList ( childList ) ; }


signature:
public class DefaultBookmarksComparator { /** * Folders are always greater than non - Folders , if they are both Folders
 * or both not Folders they are equal . */
protected int compareFolders ( final Entry e1 , final Entry e2 ) { } }

implementation: final boolean f1 = e1 instanceof Folder ; final boolean f2 = e2 instanceof Folder ; if ( f1 && ! f2 ) { return - 1 ; } else if ( ! f1 && f2 ) { return 1 ; } else { return 0 ; }


signature:
public class DefaultBookmarksComparator { /** * Compairs the entries by name , note , created and modified properties in that
 * order . */
protected int compareEntries ( final Entry e1 , final Entry e2 ) { } }

implementation: return new CompareToBuilder ( ) . append ( e1 . getName ( ) , e2 . getName ( ) ) . append ( e1 . getNote ( ) , e2 . getNote ( ) ) . append ( e1 . getCreated ( ) , e2 . getCreated ( ) ) . append ( e1 . getModified ( ) , e2 . getModified ( ) ) . toComparison ( ) ;


signature:
public class DefaultBookmarksComparator { /** * If both classes are not Bookmarks they are equal . If they are both
 * bookmarks they are compared by url then newWindow properties . */
protected int compareBookmarks ( final Entry e1 , final Entry e2 ) { } }

implementation: if ( e1 instanceof Bookmark && e2 instanceof Bookmark ) { final Bookmark b1 = ( Bookmark ) e1 ; final Bookmark b2 = ( Bookmark ) e2 ; return new CompareToBuilder ( ) . append ( b1 . getUrl ( ) , b2 . getUrl ( ) ) . append ( b1 . isNewWindow ( ) , b2 . isNewWindow ( ) ) . toComparison ( ) ; } else { return 0 ; }


signature:
public class PreferencesRequestResolver { /** * Gets Preferences for the request using the injected { @ link OwnerResolver }
 * and { @ link NameResolver } .
 * < br >
 * < br >
 * If < code > create < / code > is false and no Preferences exists for the name and owner null is returned .
 * < br >
 * < br >
 * If < code > create < / code > is true and no Preferences exists for the name and owner a new Preferences is created .
 * @ param request The request to resolve the name and owner from .
 * @ param create If a Preferences should be created for the name and owner if one does not exist
 * @ return The Preferences for the name and owner from the request , null if it does not exists and create is false . If create is true this will never return null . */
public Preferences getPreferences ( PortletRequest request , boolean create ) { } }

implementation: final String owner = this . ownerResolver . getOwner ( request ) ; final String name = this . nameResolver . getBookmarkSetName ( request ) ; Preferences preferences = this . preferencesStore . getPreferences ( owner , name ) ; if ( preferences == null && create ) { preferences = this . preferencesStore . createPreferences ( owner , name ) ; if ( preferences == null ) { throw new IllegalStateException ( "Required Preferences is null even after createPreferences was called." ) ; } } return preferences ;


signature:
public class CollectionFolder { /** * Returns an immutable sorted view of the values of the children Map . The sorting is done
 * using the current childComparator . Warning , this is has a time cost of 2n log ( n )
 * on every call .
 * @ return An immutable sorted view of the folder ' s children . */
public List < Entry > getSortedChildren ( ) { } }

implementation: List < Entry > children = new ArrayList < Entry > ( ) ; log . debug ( "children: " + children . size ( ) ) ; HttpClient client = new HttpClient ( ) ; GetMethod get = null ; try { log . debug ( "getting url " + url ) ; get = new GetMethod ( url ) ; int rc = client . executeMethod ( get ) ; if ( rc != HttpStatus . SC_OK ) { log . error ( "HttpStatus:" + rc ) ; } DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = domBuilderFactory . newDocumentBuilder ( ) ; InputStream in = get . getResponseBodyAsStream ( ) ; builder = domBuilderFactory . newDocumentBuilder ( ) ; Document doc = builder . parse ( in ) ; get . releaseConnection ( ) ; Element e = ( Element ) doc . getElementsByTagName ( "rdf:RDF" ) . item ( 0 ) ; log . debug ( "got root " + e ) ; NodeList n = e . getElementsByTagName ( "item" ) ; log . debug ( "found items " + n . getLength ( ) ) ; for ( int i = 0 ; i < n . getLength ( ) ; i ++ ) { Bookmark bookmark = new Bookmark ( ) ; Element l = ( Element ) n . item ( i ) ; bookmark . setName ( ( ( Element ) l . getElementsByTagName ( "title" ) . item ( 0 ) ) . getTextContent ( ) ) ; bookmark . setUrl ( ( ( Element ) l . getElementsByTagName ( "link" ) . item ( 0 ) ) . getTextContent ( ) ) ; if ( l . getElementsByTagName ( "description" ) . getLength ( ) > 0 ) { bookmark . setNote ( ( ( Element ) l . getElementsByTagName ( "description" ) . item ( 0 ) ) . getTextContent ( ) ) ; } children . add ( bookmark ) ; log . debug ( "added bookmark " + bookmark . getName ( ) + " " + bookmark . getUrl ( ) ) ; } } catch ( HttpException e ) { log . error ( "Error parsing delicious" , e ) ; } catch ( IOException e ) { log . error ( "Error parsing delicious" , e ) ; } catch ( ParserConfigurationException e ) { log . error ( "Error parsing delicious" , e ) ; } catch ( SAXException e ) { log . error ( "Error parsing delicious" , e ) ; } finally { if ( get != null ) get . releaseConnection ( ) ; } log . debug ( "children: " + children . size ( ) ) ; return children ;


signature:
public class ChannelId { /** * Get the optional short description
 * The short description is the first line of { @ link # getDescription ( ) }
 * @ return the short description , or { @ code null } if none is set */
public String getShortDescription ( ) { } }

implementation: if ( this . description == null ) { return null ; } final String [ ] lines = this . description . split ( "\\R" , 2 ) ; if ( lines . length > 0 ) { return lines [ 0 ] ; } else { return "" ; }


signature:
public class JspServletWrapper { /** * Sets the last - modified time of the servlet class file associated with
 * this JspServletWrapper .
 * @ param lastModified Last - modified time of servlet class */
public void setServletClassLastModifiedTime ( long lastModified ) { } }

implementation: if ( this . servletClassLastModifiedTime < lastModified ) { synchronized ( this ) { if ( this . servletClassLastModifiedTime < lastModified ) { this . servletClassLastModifiedTime = lastModified ; reload = true ; } } }


signature:
public class JspServletWrapper { /** * Compile ( if needed ) and load a tag file */
public Class loadTagFile ( ) throws JasperException { } }

implementation: try { ctxt . compile ( ) ; if ( reload ) { tagHandlerClass = ctxt . load ( ) ; } } catch ( ClassNotFoundException ex ) { } catch ( FileNotFoundException ex ) { log . log ( Level . SEVERE , Localizer . getMessage ( "jsp.error.compiling" ) ) ; throw new JasperException ( ex ) ; } return tagHandlerClass ;


signature:
public class JspServletWrapper { /** * Compile and load a prototype for the Tag file . This is needed
 * when compiling tag files with circular dependencies . A prototpe
 * ( skeleton ) with no dependencies on other other tag files is
 * generated and compiled . */
public Class loadTagFilePrototype ( ) throws JasperException { } }

implementation: ctxt . setPrototypeMode ( true ) ; try { return loadTagFile ( ) ; } finally { ctxt . setPrototypeMode ( false ) ; }


signature:
public class JspServletWrapper { /** * Get a list of files that the current page has source dependency on . */
public java . util . List < String > getDependants ( ) { } }

implementation: try { Object target ; if ( isTagFile ) { if ( reload ) { tagHandlerClass = ctxt . load ( ) ; } target = tagHandlerClass . newInstance ( ) ; } else { target = getServlet ( ) ; } if ( target != null && target instanceof JspSourceDependent ) { return ( ( JspSourceDependent ) target ) . getDependants ( ) ; } } catch ( Throwable ex ) { } return null ;


signature:
public class JspServletWrapper { /** * Handles the case where a requested JSP file no longer exists . */
private void jspFileNotFound ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { } }

implementation:
FileNotFoundException fnfe = new FileNotFoundException ( jspUri ) ; ctxt . incrementRemoved ( ) ; String includeRequestUri = ( String ) request . getAttribute ( "javax.servlet.include.request_uri" ) ; if ( includeRequestUri != null ) { // This file was included . Throw an exception as
// a response . sendError ( ) will be ignored by the
// servlet engine .
throw new ServletException ( fnfe ) ; } else { try { response . sendError ( HttpServletResponse . SC_NOT_FOUND , fnfe . getMessage ( ) ) ; } catch ( IllegalStateException ise ) { log . log ( Level . SEVERE , Localizer . getMessage ( "jsp.error.file.not.found" , fnfe . getMessage ( ) ) , fnfe ) ; } }


signature:
public class JspDocumentParser { /** * Parses a JSP document by responding to SAX events .
 * @ throws JasperException */
public static Node . Nodes parse ( ParserController pc , String path , JarFile jarFile , Node parent , boolean isTagFile , boolean directivesOnly , String pageEnc , String jspConfigPageEnc , boolean isEncodingSpecifiedInProlog ) throws JasperException { } }

implementation:
JspDocumentParser jspDocParser = new JspDocumentParser ( pc , path , isTagFile , directivesOnly ) ; Node . Nodes pageNodes = null ; try { // Create dummy root and initialize it with given page encodings
Node . Root dummyRoot = new Node . Root ( null , parent , true ) ; dummyRoot . setPageEncoding ( pageEnc ) ; dummyRoot . setJspConfigPageEncoding ( jspConfigPageEnc ) ; dummyRoot . setIsEncodingSpecifiedInProlog ( isEncodingSpecifiedInProlog ) ; jspDocParser . current = dummyRoot ; if ( parent == null ) { jspDocParser . addInclude ( dummyRoot , jspDocParser . pageInfo . getIncludePrelude ( ) ) ; } else { jspDocParser . isTop = false ; } // Parse the input
SAXParser saxParser = getSAXParser ( false , jspDocParser ) ; InputStream inStream = null ; try { inStream = JspUtil . getInputStream ( path , jarFile , jspDocParser . ctxt , jspDocParser . err ) ; saxParser . parse ( new InputSource ( inStream ) , jspDocParser ) ; } catch ( EnableDTDValidationException e ) { saxParser = getSAXParser ( true , jspDocParser ) ; jspDocParser . isValidating = true ; if ( inStream != null ) { try { inStream . close ( ) ; } catch ( Exception any ) { } } inStream = JspUtil . getInputStream ( path , jarFile , jspDocParser . ctxt , jspDocParser . err ) ; saxParser . parse ( new InputSource ( inStream ) , jspDocParser ) ; } finally { if ( inStream != null ) { try { inStream . close ( ) ; } catch ( Exception any ) { } } } if ( parent == null ) { jspDocParser . addInclude ( dummyRoot , jspDocParser . pageInfo . getIncludeCoda ( ) ) ; jspDocParser . pageInfo . setRootPath ( path ) ; } // Create Node . Nodes from dummy root
pageNodes = new Node . Nodes ( dummyRoot ) ; } catch ( IOException ioe ) { jspDocParser . err . jspError ( "jsp.error.data.file.read" , path , ioe ) ; } catch ( SAXParseException e ) { jspDocParser . err . jspError ( new Mark ( jspDocParser . ctxt , path , e . getLineNumber ( ) , e . getColumnNumber ( ) ) , e . getMessage ( ) ) ; } catch ( Exception e ) { jspDocParser . err . jspError ( e ) ; } return pageNodes ;


signature:
public class JspDocumentParser { /** * Processes the given list of included files .
 * This is used to implement the include - prelude and include - coda
 * subelements of the jsp - config element in web . xml */
private void addInclude ( Node parent , List files ) throws SAXException { } }

implementation:
if ( files != null ) { Iterator iter = files . iterator ( ) ; while ( iter . hasNext ( ) ) { String file = ( String ) iter . next ( ) ; AttributesImpl attrs = new AttributesImpl ( ) ; attrs . addAttribute ( "" , "file" , "file" , "CDATA" , file ) ; // Create a dummy Include directive node
Node includeDir = new Node . IncludeDirective ( attrs , null , // XXX
parent ) ; processIncludeDirective ( file , includeDir ) ; } }


signature:
public class JspDocumentParser { /** * Receives notification of the start of an element .
 * This method assigns the given tag attributes to one of 3 buckets :
 * - " xmlns " attributes that represent ( standard or custom ) tag libraries .
 * - " xmlns " attributes that do not represent tag libraries .
 * - all remaining attributes .
 * For each " xmlns " attribute that represents a custom tag library , the
 * corresponding TagLibraryInfo object is added to the set of custom
 * tag libraries . */
public void startElement ( String uri , String localName , String qName , Attributes attrs ) throws SAXException { } }

implementation:
AttributesImpl taglibAttrs = null ; AttributesImpl nonTaglibAttrs = null ; AttributesImpl nonTaglibXmlnsAttrs = null ; processChars ( ) ; checkPrefixes ( uri , qName , attrs ) ; if ( directivesOnly && ! ( JSP_URI . equals ( uri ) && ( localName . startsWith ( DIRECTIVE_ACTION ) || localName . startsWith ( ROOT_ACTION ) ) ) ) { return ; } // jsp : text must not have any subelements
if ( JSP_URI . equals ( uri ) && TEXT_ACTION . equals ( current . getLocalName ( ) ) ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.text.has_subelement" ) , locator ) ; } startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; if ( attrs != null ) { /* * Notice that due to a bug in the underlying SAX parser , the
 * attributes must be enumerated in descending order . */
boolean isTaglib = false ; for ( int i = attrs . getLength ( ) - 1 ; i >= 0 ; i -- ) { isTaglib = false ; String attrQName = attrs . getQName ( i ) ; if ( ! attrQName . startsWith ( "xmlns" ) ) { if ( nonTaglibAttrs == null ) { nonTaglibAttrs = new AttributesImpl ( ) ; } nonTaglibAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } else { if ( attrQName . startsWith ( "xmlns:jsp" ) ) { isTaglib = true ; } else { String attrUri = attrs . getValue ( i ) ; // TaglibInfo for this uri already established in
// startPrefixMapping
isTaglib = pageInfo . hasTaglib ( attrUri ) ; } if ( isTaglib ) { if ( taglibAttrs == null ) { taglibAttrs = new AttributesImpl ( ) ; } taglibAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } else { if ( nonTaglibXmlnsAttrs == null ) { nonTaglibXmlnsAttrs = new AttributesImpl ( ) ; } nonTaglibXmlnsAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } } } } Node node = null ; if ( tagDependentPending && JSP_URI . equals ( uri ) && localName . equals ( BODY_ACTION ) ) { tagDependentPending = false ; tagDependentNesting ++ ; current = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; return ; } if ( tagDependentPending && JSP_URI . equals ( uri ) && localName . equals ( ATTRIBUTE_ACTION ) ) { current = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; return ; } if ( tagDependentPending ) { tagDependentPending = false ; tagDependentNesting ++ ; } if ( tagDependentNesting > 0 ) { node = new Node . UninterpretedTag ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else if ( JSP_URI . equals ( uri ) ) { node = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else { node = parseCustomAction ( qName , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; if ( node == null ) { node = new Node . UninterpretedTag ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else { // custom action
String bodyType = getBodyType ( ( Node . CustomTag ) node ) ; if ( scriptlessBodyNode == null && bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_SCRIPTLESS ) ) { scriptlessBodyNode = node ; } else if ( TagInfo . BODY_CONTENT_TAG_DEPENDENT . equalsIgnoreCase ( bodyType ) ) { tagDependentPending = true ; } } } current = node ;


signature:
public class JspDocumentParser { /** * Receives notification of character data inside an element .
 * The SAX does not call this method with all of the template text , but may
 * invoke this method with chunks of it . This is a problem when we try
 * to determine if the text contains only whitespaces , or when we are
 * looking for an EL expression string . Therefore it is necessary to
 * buffer and concatenate the chunks and process the concatenated text
 * later ( at beginTag and endTag )
 * @ param buf The characters
 * @ param offset The start position in the character array
 * @ param len The number of characters to use from the character array
 * @ throws SAXException */
public void characters ( char [ ] buf , int offset , int len ) { } }

implementation: if ( charBuffer == null ) { charBuffer = new StringBuilder ( ) ; } charBuffer . append ( buf , offset , len ) ;


signature:
public class JspDocumentParser { /** * Receives notification of the end of an element . */
public void endElement ( String uri , String localName , String qName ) throws SAXException { } }

implementation:
processChars ( ) ; if ( directivesOnly && ! ( JSP_URI . equals ( uri ) && localName . startsWith ( DIRECTIVE_ACTION ) ) ) { return ; } if ( current instanceof Node . NamedAttribute ) { boolean isTrim = ( ( Node . NamedAttribute ) current ) . isTrim ( ) ; Node . Nodes subElems = ( ( Node . NamedAttribute ) current ) . getBody ( ) ; for ( int i = 0 ; subElems != null && i < subElems . size ( ) ; i ++ ) { Node subElem = subElems . getNode ( i ) ; if ( ! ( subElem instanceof Node . TemplateText ) ) { continue ; } // Ignore any whitespace ( including spaces , carriage returns ,
// line feeds , and tabs , that appear at the beginning and at
// the end of the body of the < jsp : attribute > action , if the
// action ' s ' trim ' attribute is set to TRUE ( default ) .
// In addition , any textual nodes in the < jsp : attribute > that
// have only white space are dropped from the document , with
// the exception of leading and trailing white - space - only
// textual nodes in a < jsp : attribute > whose ' trim ' attribute
// is set to FALSE , which must be kept verbatim .
if ( i == 0 ) { if ( isTrim ) { ( ( Node . TemplateText ) subElem ) . ltrim ( ) ; } } else if ( i == subElems . size ( ) - 1 ) { if ( isTrim ) { ( ( Node . TemplateText ) subElem ) . rtrim ( ) ; } } else { if ( ( ( Node . TemplateText ) subElem ) . isAllSpace ( ) ) { subElems . remove ( subElem ) ; } } } } else if ( current instanceof Node . ScriptingElement ) { checkScriptingBody ( ( Node . ScriptingElement ) current ) ; } if ( isTagDependent ( current ) ) { tagDependentNesting -- ; } if ( scriptlessBodyNode != null && current . equals ( scriptlessBodyNode ) ) { scriptlessBodyNode = null ; } if ( current . getParent ( ) != null ) { current = current . getParent ( ) ; }


signature:
public class JspDocumentParser { /** * See org . xml . sax . ext . LexicalHandler . */
public void comment ( char [ ] buf , int offset , int len ) throws SAXException { } }

implementation:
processChars ( ) ; // Flush char buffer and remove white spaces
// ignore comments in the DTD
if ( ! inDTD ) { startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; new Node . Comment ( new String ( buf , offset , len ) , startMark , current ) ; }


signature:
public class JspDocumentParser { /** * See org . xml . sax . ext . LexicalHandler . */
public void startCDATA ( ) throws SAXException { } }

implementation:
processChars ( ) ; // Flush char buffer and remove white spaces
startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ;


signature:
public class JspDocumentParser { /** * See org . xml . sax . ext . LexicalHandler . */
public void startDTD ( String name , String publicId , String systemId ) throws SAXException { } }

implementation: if ( ! isValidating ) { fatalError ( ENABLE_DTD_VALIDATION_EXCEPTION ) ; } inDTD = true ;


signature:
public class JspDocumentParser { /** * Receives notification of the start of a Namespace mapping . */
public void startPrefixMapping ( String prefix , String uri ) throws SAXException { } }

implementation: if ( directivesOnly && ! ( JSP_URI . equals ( uri ) ) ) { return ; } try { addTaglibInfo ( prefix , uri ) ; } catch ( JasperException je ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.could.not.add.taglibraries" ) , locator , je ) ; }


signature:
public class JspDocumentParser { /** * Receives notification of the end of a Namespace mapping . */
public void endPrefixMapping ( String prefix ) throws SAXException { } }

implementation: if ( directivesOnly ) { String uri = pageInfo . getURI ( prefix ) ; if ( ! JSP_URI . equals ( uri ) ) { return ; } } pageInfo . popPrefixMapping ( prefix ) ;


signature:
public class JspDocumentParser { /** * Private utility methods */
private Node parseStandardAction ( String qName , String localName , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { } }

implementation:
Node node = null ; if ( localName . equals ( ROOT_ACTION ) ) { if ( ! ( current instanceof Node . Root ) ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.nested_jsproot" ) , locator ) ; } node = new Node . JspRoot ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; if ( isTop ) { pageInfo . setHasJspRoot ( true ) ; } } else if ( localName . equals ( PAGE_DIRECTIVE_ACTION ) ) { if ( isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.istagfile" , localName ) , locator ) ; } node = new Node . PageDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( "import" ) ; // There can only be one ' import ' attribute per page directive
if ( imports != null ) { ( ( Node . PageDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( INCLUDE_DIRECTIVE_ACTION ) ) { node = new Node . IncludeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; processIncludeDirective ( nonTaglibAttrs . getValue ( "file" ) , node ) ; } else if ( localName . equals ( DECLARATION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We ' re nested inside a node whose body is
// declared to be scriptless
throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Declaration ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SCRIPTLET_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We ' re nested inside a node whose body is
// declared to be scriptless
throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Scriptlet ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( EXPRESSION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We ' re nested inside a node whose body is
// declared to be scriptless
throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Expression ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( USE_BEAN_ACTION ) ) { node = new Node . UseBean ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SET_PROPERTY_ACTION ) ) { node = new Node . SetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( GET_PROPERTY_ACTION ) ) { node = new Node . GetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INCLUDE_ACTION ) ) { node = new Node . IncludeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FORWARD_ACTION ) ) { node = new Node . ForwardAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAM_ACTION ) ) { node = new Node . ParamAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAMS_ACTION ) ) { node = new Node . ParamsAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PLUGIN_ACTION ) ) { node = new Node . PlugIn ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TEXT_ACTION ) ) { node = new Node . JspText ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( BODY_ACTION ) ) { node = new Node . JspBody ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ATTRIBUTE_ACTION ) ) { node = new Node . NamedAttribute ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( OUTPUT_ACTION ) ) { node = new Node . JspOutput ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TAG_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . TagDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( "import" ) ; // There can only be one ' import ' attribute per tag directive
if ( imports != null ) { ( ( Node . TagDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( ATTRIBUTE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . AttributeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( VARIABLE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . VariableDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INVOKE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . InvokeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( DOBODY_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . DoBodyAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ELEMENT_ACTION ) ) { node = new Node . JspElement ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FALLBACK_ACTION ) ) { node = new Node . FallBackAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.xml.badStandardAction" , localName ) , locator ) ; } return node ;


signature:
public class JspDocumentParser { /** * Checks if the XML element with the given tag name is a custom action ,
 * and returns the corresponding Node object . */
private Node parseCustomAction ( String qName , String localName , String uri , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { } }

implementation:
if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } // Check if this is a user - defined ( custom ) tag
TagLibraryInfo tagLibInfo = pageInfo . getTaglib ( uri ) ; if ( tagLibInfo == null ) { return null ; } TagInfo tagInfo = tagLibInfo . getTag ( localName ) ; TagFileInfo tagFileInfo = tagLibInfo . getTagFile ( localName ) ; if ( tagInfo == null && tagFileInfo == null ) { throw new SAXException ( Localizer . getMessage ( "jsp.error.xml.bad_tag" , localName , uri ) ) ; } Class tagHandlerClass = null ; if ( tagInfo != null ) { String handlerClassName = tagInfo . getTagClassName ( ) ; try { tagHandlerClass = ctxt . getClassLoader ( ) . loadClass ( handlerClassName ) ; } catch ( Exception e ) { throw new SAXException ( Localizer . getMessage ( "jsp.error.loadclass.taghandler" , handlerClassName , qName ) , e ) ; } } String prefix = "" ; int colon = qName . indexOf ( ':' ) ; if ( colon != - 1 ) { prefix = qName . substring ( 0 , colon ) ; } Node . CustomTag ret = null ; if ( tagInfo != null ) { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagInfo , tagHandlerClass ) ; } else { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagFileInfo ) ; } return ret ;


signature:
public class JspDocumentParser { /** * Adds the tag library associated with the given uri namespace to the
 * translation unit that this parser is associated with .
 * If the tag library does not exist , it is created .
 * @ param prefix The prefix of the xmlns attribute
 * @ param uri The uri namespace ( value of the xmlns attribute ) */
private void addTaglibInfo ( String prefix , String uri ) throws JasperException { } }

implementation:
if ( uri . startsWith ( URN_JSPTAGDIR ) ) { // uri ( of the form " urn : jsptagdir : path " ) references tag file dir
String tagdir = uri . substring ( URN_JSPTAGDIR . length ( ) ) ; TagLibraryInfo taglibInfo = new ImplicitTagLibraryInfo ( ctxt , parserController , prefix , tagdir , err ) ; if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , taglibInfo ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { // uri references TLD file
boolean isPlainUri = false ; if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } else { isPlainUri = true ; } // START GlassFish 750
ConcurrentHashMap < String , TagLibraryInfoImpl > taglibs = ctxt . getTaglibs ( ) ; TagLibraryInfoImpl taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { synchronized ( taglibs ) { taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { // END GlassFish 750
String [ ] location = ctxt . getTldLocation ( uri ) ; if ( location != null || ! isPlainUri ) { /* * If the uri value is a plain uri , a translation
 * error must not be generated if the uri is not
 * found in the taglib map .
 * Instead , any actions in the namespace defined
 * by the uri value must be treated as
 * uninterpreted . */
taglibInfo = new TagLibraryInfoImpl ( ctxt , parserController , prefix , uri , location , err ) ; // START GlassFish 750
ctxt . addTaglib ( uri , taglibInfo ) ; pageInfo . addTaglib ( uri , taglibInfo ) ; // END GlassFish 750
} // START GlassFish 750
} } } // END GlassFish 750
if ( taglibInfo != null ) { if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , new TagLibraryInfoImpl ( prefix , uri , taglibInfo , pageInfo ) ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { pageInfo . pushPrefixMapping ( prefix , null ) ; } }


signature:
public class JspDocumentParser { /** * Ensures that the given body only contains nodes that are instances of
 * TemplateText .
 * This check is performed only for the body of a scripting ( that is :
 * declaration , scriptlet , or expression ) element , after the end tag of a
 * scripting element has been reached . */
private void checkScriptingBody ( Node . ScriptingElement scriptingElem ) throws SAXException { } }

implementation: Node . Nodes body = scriptingElem . getBody ( ) ; if ( body != null ) { int size = body . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node n = body . getNode ( i ) ; if ( ! ( n instanceof Node . TemplateText ) ) { String elemType = SCRIPTLET_ACTION ; if ( scriptingElem instanceof Node . Declaration ) elemType = DECLARATION_ACTION ; if ( scriptingElem instanceof Node . Expression ) elemType = EXPRESSION_ACTION ; String msg = Localizer . getMessage ( "jsp.error.parse.xml.scripting.invalid.body" , elemType ) ; throw new SAXException ( msg ) ; } } }


signature:
public class JspDocumentParser { /** * Parses the given file included via an include directive .
 * @ param fname The path to the included resource , as specified by the
 * ' file ' attribute of the include directive
 * @ param parent The Node representing the include directive */
private void processIncludeDirective ( String fname , Node parent ) throws SAXException { } }

implementation: if ( fname == null ) { return ; } try { parserController . parse ( fname , parent , null ) ; } catch ( FileNotFoundException fnfe ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.file.not.found" , fname ) , locator , fnfe ) ; } catch ( Exception e ) { throw new SAXException ( e ) ; }


signature:
public class JspDocumentParser { /** * Checks an element ' s given URI , qname , and attributes to see if any
 * of them hijack the ' jsp ' prefix , that is , bind it to a namespace other
 * than http : / / java . sun . com / JSP / Page .
 * @ param uri The element ' s URI
 * @ param qName The element ' s qname
 * @ param attrs The element ' s attributes */
private void checkPrefixes ( String uri , String qName , Attributes attrs ) { } }

implementation: checkPrefix ( uri , qName ) ; int len = attrs . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { checkPrefix ( attrs . getURI ( i ) , attrs . getQName ( i ) ) ; }


signature:
public class JspDocumentParser { /** * Checks the given URI and qname to see if they hijack the ' jsp ' prefix ,
 * which would be the case if qName contained the ' jsp ' prefix and
 * uri was different from http : / / java . sun . com / JSP / Page .
 * @ param uri The URI to check
 * @ param qName The qname to check */
private void checkPrefix ( String uri , String qName ) { } }

implementation: int index = qName . indexOf ( ':' ) ; if ( index != - 1 ) { String prefix = qName . substring ( 0 , index ) ; pageInfo . addPrefix ( prefix ) ; if ( "jsp" . equals ( prefix ) && ! JSP_URI . equals ( uri ) ) { pageInfo . setIsJspPrefixHijacked ( true ) ; } }


signature:
public class JspDocumentParser { /** * Gets SAXParser .
 * @ param validating Indicates whether the requested SAXParser should
 * be validating
 * @ param jspDocParser The JSP document parser
 * @ return The SAXParser */
private static SAXParser getSAXParser ( boolean validating , JspDocumentParser jspDocParser ) throws Exception { } }

implementation:
SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; // Preserve xmlns attributes
factory . setFeature ( "http://xml.org/sax/features/namespace-prefixes" , true ) ; factory . setFeature ( "http://xml.org/sax/features/validation" , validating ) ; // Configure the parser
SAXParser saxParser = factory . newSAXParser ( ) ; XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setProperty ( LEXICAL_HANDLER_PROPERTY , jspDocParser ) ; xmlReader . setErrorHandler ( jspDocParser ) ; return saxParser ;


signature:
public class JasperLoader { /** * Load the class with the specified name , searching using the following
 * algorithm until it finds and returns the class . If the class cannot
 * be found , returns < code > ClassNotFoundException < / code > .
 * < ul >
 * < li > Call < code > findLoadedClass ( String ) < / code > to check if the
 * class has already been loaded . If it has , the same
 * < code > Class < / code > object is returned . < / li >
 * < li > If the < code > delegate < / code > property is set to < code > true < / code > ,
 * call the < code > loadClass ( ) < / code > method of the parent class
 * loader , if any . < / li >
 * < li > Call < code > findClass ( ) < / code > to find this class in our locally
 * defined repositories . < / li >
 * < li > Call the < code > loadClass ( ) < / code > method of our parent
 * class loader , if any . < / li >
 * < / ul >
 * If the class was found using the above steps , and the
 * < code > resolve < / code > flag is < code > true < / code > , this method will then
 * call < code > resolveClass ( Class ) < / code > on the resulting Class object .
 * @ param name Name of the class to be loaded
 * @ param resolve If < code > true < / code > then resolve the class
 * @ exception ClassNotFoundException if the class was not found */
public synchronized Class loadClass ( final String name , boolean resolve ) throws ClassNotFoundException { } }

implementation:
Class clazz = null ; // (0 ) Check our previously loaded class cache
clazz = findLoadedClass ( name ) ; if ( clazz != null ) { if ( resolve ) resolveClass ( clazz ) ; return ( clazz ) ; } // ( . 5 ) Permission to access this class when using a SecurityManager
if ( securityManager != null ) { int dot = name . lastIndexOf ( '.' ) ; if ( dot >= 0 ) { try { // Do not call the security manager since by default , we grant that package .
if ( ! "org.apache.jasper.runtime" . equalsIgnoreCase ( name . substring ( 0 , dot ) ) ) { securityManager . checkPackageAccess ( name . substring ( 0 , dot ) ) ; } } catch ( SecurityException se ) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name ; se . printStackTrace ( ) ; throw new ClassNotFoundException ( error ) ; } } } if ( ! name . startsWith ( Constants . JSP_PACKAGE_NAME ) ) { // Class is not in org . apache . jsp , therefore , have our
// parent load it
clazz = parent . loadClass ( name ) ; if ( resolve ) resolveClass ( clazz ) ; return clazz ; } return findClass ( name ) ;


signature:
public class JasperLoader { /** * START OF IASRI 4709374 */
public Class findClass ( String className ) throws ClassNotFoundException { } }

implementation:
// If the class file is in memory , use it
byte [ ] cdata = this . bytecodes . get ( className ) ; String path = className . replace ( '.' , '/' ) + ".class" ; if ( cdata == null ) { // If the bytecode preprocessor is not enabled , use super . findClass
// as usual .
/* XXX
 if ( ! PreprocessorUtil . isPreprocessorEnabled ( ) ) {
 return super . findClass ( className ) ; */
// read class data from file
cdata = loadClassDataFromFile ( path ) ; if ( cdata == null ) { throw new ClassNotFoundException ( className ) ; } } // Preprocess the loaded byte code
/* XXX
 if ( PreprocessorUtil . isPreprocessorEnabled ( ) ) {
 cdata = PreprocessorUtil . processClass ( path , cdata ) ; */
Class clazz = null ; if ( securityManager != null ) { ProtectionDomain pd = new ProtectionDomain ( codeSource , permissionCollection ) ; clazz = defineClass ( className , cdata , 0 , cdata . length , pd ) ; } else { clazz = defineClass ( className , cdata , 0 , cdata . length ) ; } return clazz ;


signature:
public class JasperLoader { /** * Load JSP class data from file . */
private byte [ ] loadClassDataFromFile ( final String fileName ) { } }

implementation: byte [ ] classBytes = null ; try { InputStream in = null ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { in = AccessController . doPrivileged ( new PrivilegedAction < InputStream > ( ) { public InputStream run ( ) { return getResourceAsStream ( fileName ) ; } } ) ; } else { in = getResourceAsStream ( fileName ) ; } if ( in == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte buf [ ] = new byte [ 1024 ] ; for ( int i = 0 ; ( i = in . read ( buf ) ) != - 1 ; ) { baos . write ( buf , 0 , i ) ; } in . close ( ) ; baos . close ( ) ; classBytes = baos . toByteArray ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return null ; } return classBytes ;


signature:
public class Exceptions { /** * Call and wrap { @ link Exception } s into a { @ link RuntimeException }
 * @ param callable
 * the { @ link Callable } to call
 * @ param < T >
 * argument type
 * @ return the return value of the callable */
public static < T > T wrapException ( final Callable < T > callable ) { } }

implementation: try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class Exceptions { /** * Call and wrap { @ link Exception } s into an exception provided by the
 * function .
 * If the function returns { @ code null } , a { @ link RuntimeException } will be
 * created instead .
 * @ param callable
 * the { @ link Callable } to call
 * @ param < T >
 * argument type
 * @ return the return value of the callable */
public static < T > T wrapException ( final Callable < T > callable , final Function < Exception , RuntimeException > func ) { } }

implementation:
try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { RuntimeException t = func . apply ( e ) ; if ( t == null ) { t = new RuntimeException ( e ) ; } else { // fixing the stack trace to be a bit more precise
t . setStackTrace ( Thread . currentThread ( ) . getStackTrace ( ) ) ; } throw t ; }