signature:
public class ClassVisitorImpl { /** * Processes the annotation on the supplied class . */
@ Override public void visit ( Class < ? > clazz ) { } }

implementation:
ClassContextImpl context = new ClassContextImpl ( builder , clazz ) ; context . put ( clazz , payload ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Scanning class: {}" , clazz . getName ( ) ) ; } // first process the class
visit ( clazz , context ) ; // only process fields and classes if a rule building has been started
if ( context . hasRuleBuildingStarted ( ) ) { // walk up the inheritance hierarchy
Class < ? > currentType = clazz ; while ( currentType != null ) { // then process the fields
for ( Field field : currentType . getDeclaredFields ( ) ) { visit ( field , new FieldContextImpl ( context , field ) ) ; } // then the methods
for ( Method method : currentType . getDeclaredMethods ( ) ) { MethodContextImpl methodContext = new MethodContextImpl ( context , method ) ; visit ( method , methodContext ) ; // then the method parameters
for ( int i = 0 ; i < method . getParameterTypes ( ) . length ; i ++ ) { ParameterImpl parameter = new ParameterImpl ( method , method . getParameterTypes ( ) [ i ] , method . getParameterAnnotations ( ) [ i ] , i ) ; visit ( parameter , new ParameterContextImpl ( methodContext , parameter ) ) ; } } currentType = currentType . getSuperclass ( ) ; } }


signature:
public class ClassVisitorImpl { /** * Process one { @ link AnnotatedElement } of the class . */
private void visit ( AnnotatedElement element , ClassContext context ) { } }

implementation:
List < AnnotationHandler < Annotation > > elementHandlers = new ArrayList < AnnotationHandler < Annotation > > ( ) ; // check if any of the handlers is responsible
for ( AnnotationHandler < Annotation > handler : handlerList ) { // each annotation on the element may be interesting for us
for ( Annotation annotation : element . getAnnotations ( ) ) { if ( handler . handles ( ) . equals ( annotation . annotationType ( ) ) ) { elementHandlers . add ( handler ) ; } } } if ( ! elementHandlers . isEmpty ( ) ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Executing handler chain on " + element + ": " + elementHandlers ) ; } // execute the handler chain
new HandlerChainImpl ( context , element , elementHandlers ) . proceed ( ) ; }


signature:
public class RewriteNavigationHandler { /** * Adds the context path to the given context - relative URL . */
private String prependContextPath ( ExternalContext externalContext , String url ) { } }

implementation: String contextPath = externalContext . getRequestContextPath ( ) ; if ( "/" . equals ( contextPath ) || ( url . startsWith ( contextPath ) ) ) { return url ; } return contextPath + url ;


signature:
public class ParameterUtils { /** * Initialize the { @ link Parameterized } instance with the { @ link ParameterStore } from the given
 * { @ link EvaluationContext } , also record required parameter names in the { @ link ParameterStore } and initialize with
 * a new { @ link Parameter } instance . */
public static void initialize ( EvaluationContext context , Object parameterized ) { } }

implementation: initialize ( DefaultParameterStore . getInstance ( context ) , parameterized ) ;


signature:
public class ParameterUtils { /** * Initialize the { @ link Parameterized } instance with the given { @ link ParameterStore } , also record required
 * parameter names in the { @ link ParameterStore } and initialize with a new { @ link Parameter } instance . */
public static void initialize ( ParameterStore store , Object parameterized ) { } }

implementation: if ( parameterized instanceof Parameterized ) { Set < String > names = ( ( Parameterized ) parameterized ) . getRequiredParameterNames ( ) ; for ( String name : names ) { store . get ( name , new DefaultParameter ( name ) ) ; } ( ( Parameterized ) parameterized ) . setParameterStore ( store ) ; }


signature:
public class ParameterUtils { /** * Submit the given value to all registered { @ link Binding } instances of the given { @ link Parameter } . Perform this by
 * adding individual { @ link BindingOperation } instances via { @ link EvaluationContext # addPreOperation ( Operation ) } */
public static boolean enqueueSubmission ( final Rewrite event , final EvaluationContext context , final Parameter < ? > parameter , final Object value ) { } }

implementation:
if ( value == null ) return true ; List < Operation > operations = new ArrayList < Operation > ( ) ; List < Binding > bindings = parameter . getBindings ( ) ; for ( Binding binding : bindings ) { try { if ( binding instanceof Evaluation ) { /* * Binding to the EvaluationContext is available immediately . */
Object convertedValue = ValueHolderUtil . convert ( event , context , parameter . getConverter ( ) , value ) ; if ( ValueHolderUtil . validates ( event , context , parameter . getValidator ( ) , convertedValue ) ) { Evaluation evaluation = ( Evaluation ) binding ; evaluation . submit ( event , context , value ) ; evaluation . submitConverted ( event , context , convertedValue ) ; } else return false ; } else { Object convertedValue = ValueHolderUtil . convert ( event , context , parameter . getConverter ( ) , value ) ; if ( ValueHolderUtil . validates ( event , context , parameter . getValidator ( ) , convertedValue ) ) { operations . add ( new BindingOperation ( binding , convertedValue ) ) ; } else return false ; } } catch ( Exception e ) { throw new RewriteException ( "Failed to bind value [" + value + "] to binding [" + binding + "]" , e ) ; } } for ( Operation operation : operations ) { context . addPreOperation ( operation ) ; } return true ;


signature:
public class ParameterUtils { /** * Extract bound values from configured { @ link Parameter } instances . Return a { @ link List } of the extracted values . */
public static Object performRetrieval ( final Rewrite event , final EvaluationContext context , final Parameter < ? > parameter ) { } }

implementation:
Object result = null ; List < Binding > bindings = new ArrayList < Binding > ( parameter . getBindings ( ) ) ; Collections . reverse ( bindings ) ; // FIXME Should not have to worry about order here .
for ( Binding binding : bindings ) { if ( result == null && ! ( binding instanceof Evaluation ) && binding . supportsRetrieval ( ) ) { result = binding . retrieve ( event , context ) ; } } for ( Binding binding : bindings ) { if ( binding instanceof Evaluation ) { if ( ( ( Evaluation ) binding ) . hasValue ( event , context ) ) { result = binding . retrieve ( event , context ) ; } } } return result ;


signature:
public class OutboundRewriteRuleAdaptor { /** * If the given URL is prefixed with this request ' s context - path , return the URI without the context path . Otherwise
 * return the URI unchanged . */
private String stripContextPath ( final String contextPath , String uri ) { } }

implementation: if ( ! contextPath . equals ( "/" ) && uri . startsWith ( contextPath ) ) { uri = uri . substring ( contextPath . length ( ) ) ; } return uri ;


signature:
public class Operations { /** * Wrap the given { @ link Operation } in a new { @ link InboundOperation } which will invoke the wrapped operation only
 * for inbound rewrites . */
public static Operation onInbound ( final Operation operation ) { } }

implementation: return new DefaultOperationBuilderInternal ( operation ) { @ Override public void perform ( Rewrite event , EvaluationContext context ) { if ( event instanceof InboundRewrite ) operation . perform ( event , context ) ; } @ Override public String toString ( ) { return "Operations.onInbound(" + operation + ")" ; } } ;


signature:
public class Operations { /** * Wrap the given { @ link Operation } in a new { @ link Operation } which will invoke the wrapped operation only for
 * outbound rewrites . */
public static Operation onOutbound ( final Operation operation ) { } }

implementation: return new DefaultOperationBuilderInternal ( operation ) { @ Override public void perform ( Rewrite event , EvaluationContext context ) { if ( event instanceof OutboundRewrite ) operation . perform ( event , context ) ; } @ Override public String toString ( ) { return "Operations.onOutbound(" + operation + ")" ; } } ;


signature:
public class Operations { /** * Wrap a given { @ link Operation } as a new { @ link DefaultOperationBuilder } that performs the action of the original
 * { @ link Operation } when { @ link # perform ( Rewrite , EvaluationContext ) } is invoked . */
public static OperationBuilder wrap ( final Operation operation ) { } }

implementation: if ( operation == null ) return create ( ) ; if ( operation instanceof OperationBuilder ) return ( OperationBuilder ) operation ; return new DefaultOperationBuilderInternal ( operation ) { @ Override public void perform ( Rewrite event , EvaluationContext context ) { operation . perform ( event , context ) ; } } ;


signature:
public class AddressBuilderSchemeSpecificPart { /** * Set a parameter name and value or values . The supplied values will be stored without additional encoding . */
public AddressBuilderSchemeSpecificPart set ( CharSequence name , Object ... values ) { } }

implementation: parent . set ( name , values ) ; return this ;


signature:
public class AddressBuilderSchemeSpecificPart { /** * Set a parameter name and value or values . The values will be decoded before they are stored . */
public AddressBuilderSchemeSpecificPart setDecoded ( CharSequence name , Object ... values ) { } }

implementation: parent . setDecoded ( name , values ) ; return this ;


signature:
public class AddressBuilderSchemeSpecificPart { /** * Set a parameter name and value or values . The values will be encoded before they are stored . */
public AddressBuilderSchemeSpecificPart setEncoded ( CharSequence name , Object ... values ) { } }

implementation: parent . setEncoded ( name , values ) ; return this ;


signature:
public class BaseRewrite { /** * Get the { @ link org . ocpsoft . rewrite . context . Context } for the current { @ link org . ocpsoft . rewrite . event . Rewrite } . */
@ Override public Context getRewriteContext ( ) { } }

implementation: if ( this . context == null ) { Context context = ( Context ) request . getAttribute ( RewriteLifecycleContext . LIFECYCLE_CONTEXT_KEY ) ; if ( context == null ) { throw new RewriteException ( "RewriteContext was null. Something is seriously wrong, " + "or you are attempting to access this event outside of the Rewrite lifecycle." ) ; } this . context = context ; } return this . context ;


signature:
public class Or { /** * Creates a new { @ link Or } condition . If any provided conditions return true , this condition returns true .
 * @ param conditions the array of conditions to be evaluated */
public static Or any ( final Condition ... conditions ) { } }

implementation: Assert . notNull ( conditions , "At least one condition is required." ) ; Assert . assertTrue ( conditions . length > 0 , "At least one condition is required." ) ; return new Or ( flattenConditions ( Arrays . asList ( conditions ) ) . toArray ( new Condition [ ] { } ) ) ;


signature:
public class LocaleTransposition { /** * Translate a value into the matching one from a resource bundle in specified language .
 * @ param lang
 * @ param value
 * @ return translated value or null if no bundle can be found for the specified language or no entries in the bundle
 * match the given value . */
private String translate ( String lang , String value ) { } }

implementation:
String translatation = null ; if ( value != null ) { if ( ! bundleMap . containsKey ( lang ) ) { Locale locale = new Locale ( lang ) ; try { ResourceBundle loadedBundle = ResourceBundle . getBundle ( bundleName , locale , ResourceBundle . Control . getNoFallbackControl ( ResourceBundle . Control . FORMAT_DEFAULT ) ) ; bundleMap . put ( lang , loadedBundle ) ; } catch ( MissingResourceException e ) { return null ; } } try { // can we received more than one path section ? e . g . / search / service /
translatation = bundleMap . get ( lang ) . getString ( value ) ; } catch ( MissingResourceException mrEx ) { // ignore
} } return translatation ;


signature:
public class LazyExpression { /** * @ see com . ocpsoft . pretty . faces . expression . PrettyExpression # getELExpression ( ) */
public String getELExpression ( ) { } }

implementation:
// build the expression if not already done
if ( expression == null ) { /* * Build the expression . Note that findBeanName ( ) will either
 * return the resolved bean name or throw a runtime exception */
expression = "#{" + finder . findBeanName ( beanClass ) + "." + component + "}" ; // log the resolved expression on trace level
if ( log . isTraceEnabled ( ) ) { log . trace ( "Lazy expression resolved to: " + expression ) ; } } return expression ;


signature:
public class DefaultParameterValueStore { /** * Retrieve the current { @ link ParameterValueStore } from the given { @ link EvaluationContext } instance .
 * @ throws IllegalStateException If the { @ link ParameterValueStore } could not be located . */
public static ParameterValueStore getInstance ( EvaluationContext context ) throws IllegalStateException { } }

implementation: ParameterValueStore valueStore = ( ParameterValueStore ) context . get ( ParameterValueStore . class ) ; if ( valueStore == null ) { throw new IllegalStateException ( "Could not retrieve " + ParameterValueStore . class . getName ( ) + " from " + EvaluationContext . class . getName ( ) + ". Has the " + EvaluationContext . class . getSimpleName ( ) + " been set up properly?" ) ; } return valueStore ;


signature:
public class Header { /** * Create a { @ link Header } condition that matches against both header name and values .
 * The given name and value patterns may be parameterized :
 * < code >
 * Header . matches ( " Accept - Encoding " , " { encoding } " ) < br >
 * Header . matches ( " Accept - { type } " , " { value } " ) < br >
 * < / code >
 * @ see { @ link ConfigurationRuleParameterBuilder # where ( String ) { @ link HttpServletRequest # getHeader ( String ) }
 * @ param name { @ link ParameterizedPattern } matching the header name .
 * @ param value { @ link ParameterizedPattern } matching the header value . */
public static Header matches ( final String name , final String value ) { } }

implementation: return new Header ( name , value ) { @ Override public String toString ( ) { return "Header.matches(\"" + name + "\", \"" + value + "\")" ; } } ;


signature:
public class Header { /** * Create a { @ link Header } condition that matches only against the existence of a header with a name matching the
 * given pattern . The header value is ignored .
 * The given name pattern may be parameterized :
 * < code >
 * Header . exists ( " Accept - Encoding " ) < br >
 * Header . exists ( " Accept - { acceptType } " ) < br >
 * Header . exists ( " { anything } " ) < br >
 * < / code >
 * @ see { @ link ConfigurationRuleParameterBuilder # where ( String ) { @ link HttpServletRequest # getHeader ( String ) }
 * @ param name { @ link ParameterizedPattern } matching the header name . */
public static Header exists ( final String name ) { } }

implementation: return new Header ( name , "{" + Header . class . getName ( ) + "_value}" ) { @ Override public String toString ( ) { return "Header.exists(\"" + name + "\")" ; } } ;


signature:
public class Header { /** * Create a { @ link Header } condition that matches only against the existence of a header with value matching the
 * given pattern . The header name is ignored .
 * The given value pattern may be parameterized :
 * < code >
 * Header . valueExists ( " application / xml " ) < br >
 * Header . valueExists ( " application / { type } " ) < br >
 * Header . valueExists ( " { anything } " ) < br >
 * < / code >
 * @ see { @ link ConfigurationRuleParameterBuilder # where ( String ) { @ link HttpServletRequest # getHeader ( String ) }
 * @ param value { @ link ParameterizedPattern } matching the header value . */
public static Header valueExists ( final String value ) { } }

implementation: return new Header ( "{" + Header . class . getName ( ) + "_name}" , value ) { @ Override public String toString ( ) { return "Header.valueExists(\"" + value + "\")" ; } } ;


signature:
public class ConfigurationBuilder { /** * Add a new fluent { @ link Rule } . */
@ Override public ConfigurationRuleBuilderCustom addRule ( ) { } }

implementation: RuleBuilder rule = RuleBuilder . define ( ) ; setDefaultLocation ( rule ) ; rules . add ( rule ) ; return new ConfigurationRuleBuilder ( this , rule ) ;


signature:
public class ConfigurationBuilder { /** * Add a { @ link Rule } . */
@ Override public ConfigurationRuleBuilder addRule ( Rule rule ) { } }

implementation: RuleBuilder wrapped = null ; if ( rule instanceof RuleBuilder ) wrapped = ( RuleBuilder ) rule ; else wrapped = RuleBuilder . wrap ( rule ) ; rules . add ( wrapped ) ; setDefaultLocation ( wrapped ) ; return new ConfigurationRuleBuilder ( this , wrapped ) ;


signature:
public class FacesStateUtils { /** * Determine if the current request / FacesContext is in PostBack state */
public static boolean isPostback ( final FacesContext context ) { } }

implementation: RenderKitFactory factory = ( RenderKitFactory ) FactoryFinder . getFactory ( FactoryFinder . RENDER_KIT_FACTORY ) ; RenderKit renderKit = factory . getRenderKit ( context , RenderKitFactory . HTML_BASIC_RENDER_KIT ) ; return renderKit . getResponseStateManager ( ) . isPostback ( context ) ;


signature:
public class DynaviewEngine { /** * Given the string value of the Faces Servlet mapping , return a string that is guaranteed to match when a servlet
 * forward is issued . It doesn ' t matter which FacesServlet we get to , as long as we get to one . */
public String buildDynaViewId ( final String facesServletMapping ) { } }

implementation:
StringBuffer result = new StringBuffer ( ) ; Map < Pattern , String > patterns = new LinkedHashMap < Pattern , String > ( ) ; Pattern pathMapping = Pattern . compile ( "^(/.*/)\\*$" ) ; Pattern extensionMapping = Pattern . compile ( "^\\*(\\..*)$" ) ; Pattern defaultMapping = Pattern . compile ( "^/$" ) ; patterns . put ( pathMapping , "$1" + DYNAVIEW + ".jsf" ) ; patterns . put ( extensionMapping , "/" + DYNAVIEW + "$1" ) ; patterns . put ( defaultMapping , "/" + DYNAVIEW + ".jsf" ) ; boolean matched = false ; Iterator < Pattern > iterator = patterns . keySet ( ) . iterator ( ) ; while ( ( matched == false ) && iterator . hasNext ( ) ) { Pattern p = iterator . next ( ) ; Matcher m = p . matcher ( facesServletMapping ) ; if ( m . matches ( ) ) { String replacement = patterns . get ( p ) ; m . appendReplacement ( result , replacement ) ; matched = true ; } } if ( matched == false ) { // This is an exact url - mapping , use it .
result . append ( facesServletMapping ) ; } return result . toString ( ) ;


signature:
public class DynaviewEngine { /** * Handle DynaView processing . This method will end the Faces life - cycle . */
public void processDynaView ( final PrettyContext prettyContext , final FacesContext facesContext ) { } }

implementation: log . trace ( "Requesting DynaView processing for: " + prettyContext . getRequestURL ( ) ) ; String viewId = "" ; try { viewId = prettyContext . getCurrentViewId ( ) ; log . trace ( "Invoking DynaView method: " + viewId ) ; Object result = computeDynaViewId ( facesContext ) ; if ( result instanceof String ) { viewId = ( String ) result ; log . trace ( "Forwarding to DynaView: " + viewId ) ; prettyContext . setDynaviewProcessed ( true ) ; facesContext . getExternalContext ( ) . dispatch ( viewId ) ; facesContext . responseComplete ( ) ; } } catch ( Exception e ) { log . error ( "Failed to process dynaview" , e ) ; PrettyRedirector prettyRedirector = new PrettyRedirector ( ) ; prettyRedirector . send404 ( facesContext ) ; throw new PrettyException ( "Could not forward to view: " + viewId + "" , e ) ; }


signature:
public class DynaviewEngine { /** * Calculate the Faces ViewId to which this request URI resolves . This method will recursively call any dynamic
 * mapping viewId functions as needed until a String viewId is returned , or supplied by a static mapping .
 * This phase does not support FacesNavigation or PrettyRedirecting . Its SOLE purpose is to resolve a viewId .
 * < i > < b > Note : < / b > Precondition - parameter injection must take place before this < / i >
 * < i > Postcondition - currentViewId is set to computed View Id < / i >
 * @ param facesContext2
 * @ return JSF viewID to which this request resolves . */
public String computeDynaViewId ( final FacesContext facesContext ) { } }

implementation: PrettyContext context = PrettyContext . getCurrentInstance ( facesContext ) ; UrlMapping urlMapping = context . getCurrentMapping ( ) ; return calculateDynaviewId ( facesContext , urlMapping ) ;


signature:
public class ConditionVisit { /** * Method to call the visitor for the supplied { @ link Condition } and recursively calls itself , if the
 * { @ link Condition } is a { @ link CompositeCondition } . */
private void visit ( Condition condition , Visitor < Condition > visitor ) { } }

implementation: visitor . visit ( condition ) ; if ( condition instanceof CompositeCondition ) { if ( ( ( CompositeCondition ) condition ) . getConditions ( ) != null ) { for ( Condition child : ( ( CompositeCondition ) condition ) . getConditions ( ) ) { visit ( child , visitor ) ; } } }


signature:
public class Perform { /** * Creates a new { @ link Perform } operation . If all provided { @ link Operation } instances return < code > true < / code > ,
 * this operation returns < code > true < / code > . If any provided operations return < code > false < / code > , this operation
 * returns < code > false < / code > .
 * @ param operations the array of operations to be evaluated */
public static Perform all ( final Operation ... operations ) { } }

implementation: Assert . notNull ( operations , "At least one operation is required." ) ; Assert . assertTrue ( operations . length > 0 , "At least one operation is required." ) ; return new Perform ( flattenOperations ( Arrays . asList ( operations ) ) . toArray ( new Operation [ ] { } ) ) ;


signature:
public class CdiServiceLocator { /** * Builds the correct " required type " including actual type arguments in case of parameterized types .
 * @ see https : / / github . com / ocpsoft / rewrite / issues / 137 */
private Type getRequiredType ( Class < ? > clazz ) { } }

implementation: TypeVariable < ? > [ ] typeParameters = clazz . getTypeParameters ( ) ; if ( typeParameters . length > 0 ) { Type [ ] actualTypeParameters = new Type [ typeParameters . length ] ; for ( int i = 0 ; i < typeParameters . length ; i ++ ) { actualTypeParameters [ i ] = new WildcardTypeImpl ( new Type [ ] { Object . class } , new Type [ ] { } ) ; } return new ParameterizedTypeImpl ( clazz , actualTypeParameters , null ) ; } return clazz ;


signature:
public class MultiPageMessagesSupport { /** * Save messages into the session after every phase . */
public void afterPhase ( final PhaseEvent event ) { } }

implementation: if ( ! PhaseId . RENDER_RESPONSE . equals ( event . getPhaseId ( ) ) ) { FacesContext facesContext = event . getFacesContext ( ) ; messagesUtils . saveMessages ( facesContext , facesContext . getExternalContext ( ) . getSessionMap ( ) ) ; }


signature:
public class AnnotationProxyFactory { /** * Returns a proxy on the customAnnotation , having the same type than the referenceAnnotation
 * @ param customAnnotation annotation proxied
 * @ param referenceAnnotation type of the returned annotation
 * @ return proxied customAnnotation with the type of referenceAnnotation */
@ SuppressWarnings ( "unchecked" ) public static < T extends Annotation > T getAnnotationProxy ( Annotation customAnnotation , Class < T > referenceAnnotation ) { } }

implementation: InvocationHandler handler = new AnnotationInvocationHandler ( customAnnotation ) ; return ( T ) Proxy . newProxyInstance ( referenceAnnotation . getClassLoader ( ) , new Class [ ] { referenceAnnotation } , handler ) ;


signature:
public class ObjectGraphWalker { /** * Walk the graph and call into the " visitor "
 * @ param visitorListener A decorator for the Visitor
 * @ param root the roots of the objects ( a shared graph will only be visited once )
 * @ return the sum of all Visitor # visit returned values */
long walk ( VisitorListener visitorListener , Object ... root ) { } }

implementation: final StringBuilder traversalDebugMessage ; if ( USE_VERBOSE_DEBUG_LOGGING && LOG . isDebugEnabled ( ) ) { traversalDebugMessage = new StringBuilder ( ) ; } else { traversalDebugMessage = null ; } long result = 0 ; Deque < Object > toVisit = new ArrayDeque < > ( ) ; Set < Object > visited = newSetFromMap ( new IdentityHashMap < > ( ) ) ; if ( root != null ) { if ( traversalDebugMessage != null ) { traversalDebugMessage . append ( "visiting " ) ; } for ( Object object : root ) { nullSafeAdd ( toVisit , object ) ; if ( traversalDebugMessage != null && object != null ) { traversalDebugMessage . append ( object . getClass ( ) . getName ( ) ) . append ( "@" ) . append ( System . identityHashCode ( object ) ) . append ( ", " ) ; } } if ( traversalDebugMessage != null ) { traversalDebugMessage . deleteCharAt ( traversalDebugMessage . length ( ) - 2 ) . append ( "\n" ) ; } } while ( ! toVisit . isEmpty ( ) ) { Object ref = toVisit . pop ( ) ; if ( visited . add ( ref ) ) { Class < ? > refClass = ref . getClass ( ) ; if ( ! byPassIfFlyweight ( ref ) && shouldWalkClass ( refClass ) ) { if ( refClass . isArray ( ) && ! refClass . getComponentType ( ) . isPrimitive ( ) ) { for ( int i = 0 ; i < Array . getLength ( ref ) ; i ++ ) { nullSafeAdd ( toVisit , Array . get ( ref , i ) ) ; } } else { for ( Field field : getFilteredFields ( refClass ) ) { try { nullSafeAdd ( toVisit , field . get ( ref ) ) ; } catch ( IllegalAccessException ex ) { throw new RuntimeException ( ex ) ; } } } final long visitSize = visitor . visit ( ref ) ; if ( visitorListener != null ) { visitorListener . visited ( ref , visitSize ) ; } if ( traversalDebugMessage != null ) { traversalDebugMessage . append ( "  " ) . append ( visitSize ) . append ( "b\t\t" ) . append ( ref . getClass ( ) . getName ( ) ) . append ( "@" ) . append ( System . identityHashCode ( ref ) ) . append ( "\n" ) ; } result += visitSize ; } else if ( traversalDebugMessage != null ) { traversalDebugMessage . append ( "  ignored\t" ) . append ( ref . getClass ( ) . getName ( ) ) . append ( "@" ) . append ( System . identityHashCode ( ref ) ) . append ( "\n" ) ; } } } if ( traversalDebugMessage != null ) { traversalDebugMessage . append ( "Total size: " ) . append ( result ) . append ( " bytes\n" ) ; LOG . debug ( traversalDebugMessage . toString ( ) ) ; } return result ;


signature:
public class ObjectGraphWalker { /** * Returns the filtered fields for a particular type
 * @ param refClass the type
 * @ return A collection of fields to be visited */
private Collection < Field > getFilteredFields ( Class < ? > refClass ) { } }

implementation: SoftReference < Collection < Field > > ref = fieldCache . get ( refClass ) ; Collection < Field > fieldList = ref != null ? ref . get ( ) : null ; if ( fieldList != null ) { return fieldList ; } else { Collection < Field > result ; result = sizeOfFilter . filterFields ( refClass , getAllFields ( refClass ) ) ; if ( USE_VERBOSE_DEBUG_LOGGING && LOG . isDebugEnabled ( ) ) { for ( Field field : result ) { if ( Modifier . isTransient ( field . getModifiers ( ) ) ) { LOG . debug ( "SizeOf engine walking transient field '{}' of class {}" , field . getName ( ) , refClass . getName ( ) ) ; } } } fieldCache . put ( refClass , new SoftReference < > ( result ) ) ; return result ; }


signature:
public class ObjectGraphWalker { /** * Returns all non - primitive fields for the entire class hierarchy of a type
 * @ param refClass the type
 * @ return all fields for that type */
private static Collection < Field > getAllFields ( Class < ? > refClass ) { } }

implementation: Collection < Field > fields = new ArrayList < > ( ) ; for ( Class < ? > klazz = refClass ; klazz != null ; klazz = klazz . getSuperclass ( ) ) { for ( Field field : klazz . getDeclaredFields ( ) ) { if ( ! Modifier . isStatic ( field . getModifiers ( ) ) && ! field . getType ( ) . isPrimitive ( ) ) { try { field . setAccessible ( true ) ; } catch ( SecurityException e ) { LOG . error ( "Security settings prevent Ehcache from accessing the subgraph beneath '{}'" + " - cache sizes may be underestimated as a result" , field , e ) ; continue ; } fields . add ( field ) ; } } } return fields ;


signature:
public class WeakIdentityConcurrentMap { /** * Puts into the underlying
 * @ param key key with which the specified value is to be associated
 * @ param value value to be associated with the specified key
 * @ return the previous value associated with < tt > key < / tt > , or
 * < tt > null < / tt > if there was no mapping for < tt > key < / tt > .
 * ( A < tt > null < / tt > return can also indicate that the map
 * previously associated < tt > null < / tt > with < tt > key < / tt > ,
 * if the implementation supports < tt > null < / tt > values . ) */
public V put ( K key , V value ) { } }

implementation: cleanUp ( ) ; return map . put ( new IdentityWeakReference < > ( key , queue ) , value ) ;


signature:
public class WeakIdentityConcurrentMap { /** * Remove from the underlying
 * @ param key key whose mapping is to be removed from the map
 * @ return the previous value associated with < tt > key < / tt > , or
 * < tt > null < / tt > if there was no mapping for < tt > key < / tt > . */
public V remove ( K key ) { } }

implementation: cleanUp ( ) ; return map . remove ( new IdentityWeakReference < > ( key , queue ) ) ;


signature:
public class AgentLoader { /** * Attempts to load the agent through the Attach API
 * @ return true if agent was loaded ( which could have happened thought the - javaagent switch ) */
static boolean loadAgent ( ) { } }

implementation: synchronized ( AgentLoader . class . getName ( ) . intern ( ) ) { if ( ! agentIsAvailable ( ) && VIRTUAL_MACHINE_LOAD_AGENT != null ) { try { warnIfOSX ( ) ; String name = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; Object vm = VIRTUAL_MACHINE_ATTACH . invoke ( null , name . substring ( 0 , name . indexOf ( '@' ) ) ) ; try { File agent = getAgentFile ( ) ; LOGGER . info ( "Trying to load agent @ {}" , agent ) ; if ( agent != null ) { VIRTUAL_MACHINE_LOAD_AGENT . invoke ( vm , agent . getAbsolutePath ( ) ) ; } } finally { VIRTUAL_MACHINE_DETACH . invoke ( vm ) ; } } catch ( InvocationTargetException ite ) { Throwable cause = ite . getCause ( ) ; LOGGER . info ( "Failed to attach to VM and load the agent: {}: {}" , cause . getClass ( ) , cause . getMessage ( ) ) ; } catch ( Throwable t ) { LOGGER . info ( "Failed to attach to VM and load the agent: {}: {}" , t . getClass ( ) , t . getMessage ( ) ) ; } } final boolean b = agentIsAvailable ( ) ; if ( b ) { LOGGER . info ( "Agent successfully loaded and available!" ) ; } return b ; }


signature:
public class AgentLoader { /** * Checks whether the agent is available
 * @ return true if available */
static boolean agentIsAvailable ( ) { } }

implementation: try { if ( instrumentation == null ) { instrumentation = ( Instrumentation ) System . getProperties ( ) . get ( INSTRUMENTATION_INSTANCE_SYSTEM_PROPERTY_NAME ) ; } if ( instrumentation == null ) { Class < ? > sizeOfAgentClass = ClassLoader . getSystemClassLoader ( ) . loadClass ( SIZEOF_AGENT_CLASSNAME ) ; Method getInstrumentationMethod = sizeOfAgentClass . getMethod ( "getInstrumentation" ) ; instrumentation = ( Instrumentation ) getInstrumentationMethod . invoke ( sizeOfAgentClass ) ; } return instrumentation != null ; } catch ( SecurityException e ) { LOGGER . warn ( "Couldn't access the system classloader because of the security policies applied by " + "the security manager. You either want to loosen these, so ClassLoader.getSystemClassLoader() and " + "reflection API calls are permitted or the sizing will be done using some other mechanism.\n" + "Alternatively, set the system property org.ehcache.sizeof.agent.instrumentationSystemProperty to true " + "to have the agent put the required instances in the System Properties for the loader to access." ) ; return false ; } catch ( Throwable e ) { return false ; }


signature:
public class UnsafeSizeOf { /** * { @ inheritDoc } */
@ Override public long sizeOf ( Object obj ) { } }

implementation: if ( obj . getClass ( ) . isArray ( ) ) { Class < ? > klazz = obj . getClass ( ) ; int base = UNSAFE . arrayBaseOffset ( klazz ) ; int scale = UNSAFE . arrayIndexScale ( klazz ) ; long size = base + ( scale * Array . getLength ( obj ) ) ; size += CURRENT_JVM_INFORMATION . getFieldOffsetAdjustment ( ) ; if ( ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) != 0 ) { size += CURRENT_JVM_INFORMATION . getObjectAlignment ( ) - ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) ; } return Math . max ( CURRENT_JVM_INFORMATION . getMinimumObjectSize ( ) , size ) ; } else { for ( Class < ? > klazz = obj . getClass ( ) ; klazz != null ; klazz = klazz . getSuperclass ( ) ) { long lastFieldOffset = - 1 ; for ( Field f : klazz . getDeclaredFields ( ) ) { if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) { lastFieldOffset = Math . max ( lastFieldOffset , UNSAFE . objectFieldOffset ( f ) ) ; } } if ( lastFieldOffset > 0 ) { lastFieldOffset += CURRENT_JVM_INFORMATION . getFieldOffsetAdjustment ( ) ; lastFieldOffset += 1 ; if ( ( lastFieldOffset % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) != 0 ) { lastFieldOffset += CURRENT_JVM_INFORMATION . getObjectAlignment ( ) - ( lastFieldOffset % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) ; } return Math . max ( CURRENT_JVM_INFORMATION . getMinimumObjectSize ( ) , lastFieldOffset ) ; } } long size = CURRENT_JVM_INFORMATION . getObjectHeaderSize ( ) ; if ( ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) != 0 ) { size += CURRENT_JVM_INFORMATION . getObjectAlignment ( ) - ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) ; } return Math . max ( CURRENT_JVM_INFORMATION . getMinimumObjectSize ( ) , size ) ; }


signature:
public class CombinationSizeOfFilter { /** * { @ inheritDoc } */
public Collection < Field > filterFields ( Class < ? > klazz , Collection < Field > fields ) { } }

implementation: Collection < Field > current = fields ; for ( SizeOfFilter filter : filters ) { current = filter . filterFields ( klazz , current ) ; } return current ;


signature:
public class CombinationSizeOfFilter { /** * { @ inheritDoc } */
public boolean filterClass ( Class < ? > klazz ) { } }

implementation: for ( SizeOfFilter filter : filters ) { if ( ! filter . filterClass ( klazz ) ) { return false ; } } return true ;


signature:
public class ReflectionSizeOf { /** * { @ inheritDoc } */
@ Override public long sizeOf ( Object obj ) { } }

implementation:
if ( obj == null ) { return 0 ; } Class < ? > aClass = obj . getClass ( ) ; if ( aClass . isArray ( ) ) { return guessArraySize ( obj ) ; } else { long size = CURRENT_JVM_INFORMATION . getObjectHeaderSize ( ) ; Deque < Class < ? > > classStack = new ArrayDeque < > ( ) ; for ( Class < ? > klazz = aClass ; klazz != null ; klazz = klazz . getSuperclass ( ) ) { classStack . push ( klazz ) ; } while ( ! classStack . isEmpty ( ) ) { Class < ? > klazz = classStack . pop ( ) ; // assuming default class layout
int oops = 0 ; int doubles = 0 ; int words = 0 ; int shorts = 0 ; int bytes = 0 ; for ( Field f : klazz . getDeclaredFields ( ) ) { if ( Modifier . isStatic ( f . getModifiers ( ) ) ) { continue ; } if ( f . getType ( ) . isPrimitive ( ) ) { switch ( PrimitiveType . forType ( f . getType ( ) ) ) { case BOOLEAN : case BYTE : bytes ++ ; break ; case SHORT : case CHAR : shorts ++ ; break ; case INT : case FLOAT : words ++ ; break ; case DOUBLE : case LONG : doubles ++ ; break ; default : throw new AssertionError ( ) ; } } else { oops ++ ; } } if ( doubles > 0 && ( size % PrimitiveType . LONG . getSize ( ) ) != 0 ) { long length = PrimitiveType . LONG . getSize ( ) - ( size % PrimitiveType . LONG . getSize ( ) ) ; size += PrimitiveType . LONG . getSize ( ) - ( size % PrimitiveType . LONG . getSize ( ) ) ; while ( length >= PrimitiveType . INT . getSize ( ) && words > 0 ) { length -= PrimitiveType . INT . getSize ( ) ; words -- ; } while ( length >= PrimitiveType . SHORT . getSize ( ) && shorts > 0 ) { length -= PrimitiveType . SHORT . getSize ( ) ; shorts -- ; } while ( length >= PrimitiveType . BYTE . getSize ( ) && bytes > 0 ) { length -= PrimitiveType . BYTE . getSize ( ) ; bytes -- ; } while ( length >= PrimitiveType . getReferenceSize ( ) && oops > 0 ) { length -= PrimitiveType . getReferenceSize ( ) ; oops -- ; } } size += PrimitiveType . DOUBLE . getSize ( ) * doubles ; size += PrimitiveType . INT . getSize ( ) * words ; size += PrimitiveType . SHORT . getSize ( ) * shorts ; size += PrimitiveType . BYTE . getSize ( ) * bytes ; if ( oops > 0 ) { if ( ( size % PrimitiveType . getReferenceSize ( ) ) != 0 ) { size += PrimitiveType . getReferenceSize ( ) - ( size % PrimitiveType . getReferenceSize ( ) ) ; } size += oops * PrimitiveType . getReferenceSize ( ) ; } if ( ( doubles + words + shorts + bytes + oops ) > 0 && ( size % PrimitiveType . getReferenceSize ( ) ) != 0 ) { size += PrimitiveType . getReferenceSize ( ) - ( size % PrimitiveType . getReferenceSize ( ) ) ; } } if ( ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) != 0 ) { size += CURRENT_JVM_INFORMATION . getObjectAlignment ( ) - ( size % CURRENT_JVM_INFORMATION . getObjectAlignment ( ) ) ; } return Math . max ( size , CURRENT_JVM_INFORMATION . getMinimumObjectSize ( ) ) ; }


signature:
public class AnnotationSizeOfFilter { /** * { @ inheritDoc } */
public Collection < Field > filterFields ( Class < ? > klazz , Collection < Field > fields ) { } }

implementation: for ( Iterator < Field > it = fields . iterator ( ) ; it . hasNext ( ) ; ) { Field field = it . next ( ) ; IgnoreSizeOf annotationOnField = getAnnotationOn ( field , IgnoreSizeOf . class , IGNORE_SIZE_OF_PATTERN ) ; if ( annotationOnField != null ) { it . remove ( ) ; } } return fields ;


signature:
public class AnnotationSizeOfFilter { /** * { @ inheritDoc } */
public boolean filterClass ( Class < ? > klazz ) { } }

implementation: boolean classAnnotated = isAnnotationPresentOrInherited ( klazz ) ; Package pack = klazz . getPackage ( ) ; IgnoreSizeOf annotationOnPackage = pack == null ? null : getAnnotationOn ( pack , IgnoreSizeOf . class , IGNORE_SIZE_OF_PATTERN ) ; boolean packageAnnotated = annotationOnPackage != null ; return ! classAnnotated && ! packageAnnotated ;


signature:
public class AnnotationSizeOfFilter { /** * EHC - 938 : looking for all types of IgnoreSizeOf annotations */
private < T extends Annotation > T getAnnotationOn ( AnnotatedElement element , Class < T > referenceAnnotation , Pattern matchingAnnotationPattern ) { } }

implementation: T matchingAnnotation = null ; Annotation [ ] annotations = element . getAnnotations ( ) ; for ( Annotation annotation : annotations ) { if ( validateCustomAnnotationPattern ( annotation . annotationType ( ) . getName ( ) , matchingAnnotationPattern ) ) { if ( matchingAnnotation != null ) { throw new IllegalStateException ( "You are not allowed to use more than one @" + referenceAnnotation . getName ( ) + " annotations for the same element : " + element . toString ( ) ) ; } matchingAnnotation = AnnotationProxyFactory . getAnnotationProxy ( annotation , referenceAnnotation ) ; } } return matchingAnnotation ;


signature:
public class EpollCore { /** * protected AtomicInteger eventCounter = new AtomicInteger ( 0 ) ; */
@ Override public void run ( ) { } }

implementation:
started = true ; System . out . println ( "io threads count: " + ioThreadsCount ) ; ioThreads = new IOThread [ ioThreadsCount ] ; for ( int i = 0 ; i < ioThreadsCount ; i ++ ) { ioThreads [ i ] = createIOThread ( i , ioThreadsCount ) ; ioThreads [ i ] . setTTL ( ttl ) ; ioThreads [ i ] . loadCertificates ( sslConfig ) ; ioThreads [ i ] . start ( ) ; } ByteBuffer eventsBuffer = this . events ; byte [ ] events = new byte [ eventsBuffer . capacity ( ) ] ; byte [ ] newConnections = new byte [ eventsBuffer . capacity ( ) ] ; if ( ioThreadsCount == 0 ) { IOThread < ? extends T > ioThread = createIOThread ( 1 , 1 ) ; ioThreadsCount = 1 ; ioThread . scope = scope ; ioThreads = new IOThread [ ] { ioThread } ; ioThreads [ 0 ] . setTTL ( ttl ) ; ioThreads [ 0 ] . loadCertificates ( sslConfig ) ; long prev = System . nanoTime ( ) ; while ( running ) { try { eventsBuffer . position ( 0 ) ; long now = System . nanoTime ( ) * 1000 ; long nowMinusSecond = now - 1_000_000_000_000L ; // 1 sec
int r = waitForEvents ( 500 ) ; eventsBuffer . limit ( r ) ; eventsBuffer . get ( events , 0 , r ) ; int i = 0 ; while ( i < r ) { int event = events [ i ] ; if ( event == 0 ) { acceptConnections ( newConnections ) ; } else { int fd = readInt ( events , i + 1 ) ; ioThread . handleEvent ( fd , event , now , nowMinusSecond ) ; } i += 5 ; } if ( nowMinusSecond > prev ) { ioThread . handleTimeOuts ( now ) ; prev = now ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } return ; } while ( running ) { try { eventsBuffer . position ( 0 ) ; int r = waitForEvents ( 500 ) ; eventsBuffer . limit ( r ) ; eventsBuffer . get ( events , 0 , r ) ; int i = 0 ; while ( i < r ) { int event = events [ i ] ; i += 5 ; if ( event == 0 ) acceptConnections ( newConnections ) ; else throw new IllegalStateException ( "this thread only for accepting new connections, event: " + event ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } for ( int i = 0 ; i < ioThreads . length ; i ++ ) { ioThreads [ i ] . close ( ) ; }


signature:
public class Connection { /** * @ return true if connection is ready to write data */
public boolean write ( ByteBufferProvider bufferProvider ) { } }

implementation: Queue < ReadableData > queue = this . sending ; if ( queue == null ) return true ; while ( ! queue . isEmpty ( ) && writer . compareAndSet ( null , bufferProvider ) ) { try { ReadableData readable ; while ( ( readable = queue . peek ( ) ) != null ) { while ( ! readable . isComplete ( ) && actualWrite ( readable , bufferProvider ) ) { } if ( ! readable . isComplete ( ) ) return false ; queue . poll ( ) ; readable . close ( ) ; readable . onComplete ( ) ; onWriteData ( readable , ! queue . isEmpty ( ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; close ( ) ; return false ; } finally { writer . set ( null ) ; } } return true ;


signature:
public class Connection { /** * @ return true if connection is ready to write data */
protected boolean actualWrite ( ReadableData readable , ByteBufferProvider bufferProvider ) throws IOException { } }

implementation:
if ( ! isAlive ( ) ) return false ; ByteBufferWrapper bb = readable . getByteBuffer ( bufferProvider ) ; bb . clear ( ) ; int r = readable . read ( bb ) ; if ( r > 0 ) { // int written = epoll . write ( this , bb . address , bb . offset ( ) , r ) ;
int written = write ( bb , bb . offset ( ) , r ) ; bb . clear ( ) ; // System . out . println ( " write : " + written + " ( " + readable . complete ( ) + " / " + readable . length ( ) + " ) " + " to " + this ) ;
if ( written != r ) { readable . unread ( r - written ) ; return false ; } return true ; } return false ;


signature:
public class ResourceUtils { /** * Queries , whether the given source is up - to - date relative to
 * the given modification date . */
public static boolean isUptodate ( PlexusIoResource source , long destinationDate ) { } }

implementation: final long s = source . getLastModified ( ) ; if ( s == PlexusIoResource . UNKNOWN_MODIFICATION_DATE ) { return false ; } if ( destinationDate == 0 ) { return false ; } return destinationDate > s ;


signature:
public class ResourceUtils { /** * Queries , whether the given source is up - to - date relative to
 * the given modification date . */
public static boolean isUptodate ( long sourceDate , long destinationDate ) { } }

implementation: if ( sourceDate == PlexusIoResource . UNKNOWN_MODIFICATION_DATE ) { return false ; } if ( destinationDate == 0 ) { return false ; } return destinationDate > sourceDate ;


signature:
public class ResourceUtils { /** * Copies the sources contents to the given destination file . */
public static void copyFile ( PlexusIoResource in , File outFile ) throws IOException { } }

implementation: InputStream input = null ; OutputStream output = null ; try { input = in . getContents ( ) ; output = new FileOutputStream ( outFile ) ; IOUtil . copy ( input , output ) ; } finally { IOUtil . close ( input ) ; IOUtil . close ( output ) ; }


signature:
public class ResourceUtils { /** * Checks , whether the resource and the file are identical . */
public static boolean isSame ( PlexusIoResource resource , File file ) { } }

implementation: if ( resource instanceof FileSupplier ) { File resourceFile = ( ( FileSupplier ) resource ) . getFile ( ) ; return file . equals ( resourceFile ) ; } return false ;


signature:
public class ResourceUtils { /** * Checks , whether the resource and the file are identical .
 * Uses { @ link File # getCanonicalFile ( ) } for comparison , which is much
 * slower than comparing the files . */
public static boolean isCanonicalizedSame ( PlexusIoResource resource , File file ) throws IOException { } }

implementation: if ( resource instanceof FileSupplier ) { File resourceFile = ( ( FileSupplier ) resource ) . getFile ( ) ; return file . getCanonicalFile ( ) . equals ( resourceFile . getCanonicalFile ( ) ) ; } return false ;


signature:
public class TarFile { /** * Implementation of { @ link ArchiveFile # getEntries ( ) } . Note , that there is
 * an interaction between this method and { @ link # getInputStream ( TarArchiveEntry ) } ,
 * or { @ link # getInputStream ( org . apache . commons . compress . archivers . ArchiveEntry ) } :
 * If an input stream is opened for any other entry than the enumerations
 * current entry , then entries may be skipped . */
public Enumeration < org . apache . commons . compress . archivers . ArchiveEntry > getEntries ( ) throws IOException { } }

implementation: if ( inputStream != null ) { close ( ) ; } open ( ) ; return new Enumeration < org . apache . commons . compress . archivers . ArchiveEntry > ( ) { boolean currentEntryValid ; public boolean hasMoreElements ( ) { if ( ! currentEntryValid ) { try { currentEntry = inputStream . getNextTarEntry ( ) ; } catch ( IOException e ) { throw new UndeclaredThrowableException ( e ) ; } } return currentEntry != null ; } public org . apache . commons . compress . archivers . ArchiveEntry nextElement ( ) { if ( currentEntry == null ) { throw new NoSuchElementException ( ) ; } currentEntryValid = false ; return currentEntry ; } } ;


signature:
public class TarFile { /** * Returns an { @ link InputStream } with the given entries
 * contents . This { @ link InputStream } may be closed : Nothing
 * happens in that case , because an actual close would invalidate
 * the underlying { @ link TarArchiveInputStream } . */
public InputStream getInputStream ( TarArchiveEntry entry ) throws IOException { } }

implementation:
if ( entry . equals ( ( Object ) currentEntry ) && inputStream != null ) { return new FilterInputStream ( inputStream ) { public void close ( ) throws IOException { // Does nothing .
} } ; } return getInputStream ( entry , currentEntry ) ;


signature:
public class WarArchiver { /** * set the deployment descriptor to use ( WEB - INF / web . xml ) ;
 * required unless < tt > update = true < / tt > */
public void setWebxml ( File descr ) throws ArchiverException { } }

implementation: deploymentDescriptor = descr ; if ( ! deploymentDescriptor . exists ( ) ) { throw new ArchiverException ( "Deployment descriptor: " + deploymentDescriptor + " does not exist." ) ; } addFile ( descr , "WEB-INF" + File . separatorChar + "web.xml" ) ;


signature:
public class WarArchiver { /** * add files under WEB - INF / lib / */
public void addLibs ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { } }

implementation: addDirectory ( directoryName , "WEB-INF/lib/" , includes , excludes ) ;


signature:
public class WarArchiver { /** * add files under WEB - INF / classes */
public void addClasses ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { } }

implementation: addDirectory ( directoryName , "WEB-INF/classes/" , includes , excludes ) ;


signature:
public class WarArchiver { /** * files to add under WEB - INF ; */
public void addWebinf ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { } }

implementation: addDirectory ( directoryName , "WEB-INF/" , includes , excludes ) ;


signature:
public class WarArchiver { /** * override of parent ; validates configuration
 * before initializing the output stream . */
protected void initZipOutputStream ( ZipArchiveOutputStream zOut ) throws ArchiverException , IOException { } }

implementation:
// If no webxml file is specified , it ' s an error .
if ( expectWebXml && deploymentDescriptor == null && ! isInUpdateMode ( ) ) { throw new ArchiverException ( "webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)" ) ; } super . initZipOutputStream ( zOut ) ;


signature:
public class WarArchiver { /** * Overridden from ZipArchiver class to deal with web . xml */
protected void zipFile ( ArchiveEntry entry , ZipArchiveOutputStream zOut , String vPath ) throws IOException , ArchiverException { } }

implementation:
// If the file being added is WEB - INF / web . xml , we warn if it ' s
// not the one specified in the " webxml " attribute - or if
// it ' s being added twice , meaning the same file is specified
// by the " webxml " attribute and in a < fileset > element .
if ( vPath . equalsIgnoreCase ( "WEB-INF/web.xml" ) ) { if ( descriptorAdded || ( expectWebXml && ( deploymentDescriptor == null || ! ResourceUtils . isCanonicalizedSame ( entry . getResource ( ) , deploymentDescriptor ) ) ) ) { getLogger ( ) . warn ( "Warning: selected " + archiveType + " files include a WEB-INF/web.xml which will be ignored " + "\n(webxml attribute is missing from " + archiveType + " task, or ignoreWebxml attribute is specified as 'true')" ) ; } else { super . zipFile ( entry , zOut , vPath ) ; descriptorAdded = true ; } } else { super . zipFile ( entry , zOut , vPath ) ; }


signature:
public class Manifest { /** * Construct a manifest from Ant ' s default manifest file .
 * @ return the default manifest .
 * @ throws ArchiverException if there is a problem loading the
 * default manifest */
public static Manifest getDefaultManifest ( ) throws ArchiverException { } }

implementation: try { String defManifest = "/org/codehaus/plexus/archiver/jar/defaultManifest.mf" ; InputStream in = Manifest . class . getResourceAsStream ( defManifest ) ; if ( in == null ) { throw new ArchiverException ( "Could not find default manifest: " + defManifest ) ; } try { Manifest defaultManifest = new Manifest ( new InputStreamReader ( in , "UTF-8" ) ) ; defaultManifest . getMainAttributes ( ) . putValue ( "Created-By" , System . getProperty ( "java.vm.version" ) + " (" + System . getProperty ( "java.vm.vendor" ) + ")" ) ; return defaultManifest ; } catch ( UnsupportedEncodingException e ) { return new Manifest ( new InputStreamReader ( in ) ) ; } finally { IOUtil . close ( in ) ; } } catch ( ManifestException e ) { throw new ArchiverException ( "Default manifest is invalid !!" , e ) ; } catch ( IOException e ) { throw new ArchiverException ( "Unable to read default manifest" , e ) ; }


signature:
public class Manifest { /** * Add a section to the manifest
 * @ param section the manifest section to be added
 * @ throws ManifestException if the secti0on is not valid . */
public void addConfiguredSection ( Section section ) throws ManifestException { } }

implementation: String sectionName = section . getName ( ) ; if ( sectionName == null ) { throw new ManifestException ( "Sections must have a name" ) ; } Attributes attributes = getOrCreateAttributes ( sectionName ) ; for ( String s : section . attributes . keySet ( ) ) { Attribute attribute = section . getAttribute ( s ) ; attributes . putValue ( attribute . getName ( ) , attribute . getValue ( ) ) ; }


signature:
public class Manifest { /** * Write the manifest out to a print writer .
 * @ param writer the Writer to which the manifest is written
 * @ throws IOException if the manifest cannot be written */
public void write ( PrintWriter writer ) throws IOException { } }

implementation: ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; super . write ( byteArrayOutputStream ) ; for ( byte b : byteArrayOutputStream . toByteArray ( ) ) { writer . write ( ( char ) b ) ; }


signature:
public class Manifest { /** * Get the warnings for this manifest .
 * @ return an enumeration of warning strings */
Enumeration < String > getWarnings ( ) { } }

implementation: Vector < String > warnings = new Vector < String > ( ) ; Enumeration < String > warnEnum = mainSection . getWarnings ( ) ; while ( warnEnum . hasMoreElements ( ) ) { warnings . addElement ( warnEnum . nextElement ( ) ) ; } return warnings . elements ( ) ;


signature:
public class Manifest { /** * Get a particular section from the manifest
 * @ param name the name of the section desired .
 * @ return the specified section or null if that section
 * does not exist in the manifest */
public ExistingSection getSection ( String name ) { } }

implementation: Attributes attributes = getAttributes ( name ) ; if ( attributes != null ) { return new ExistingSection ( attributes , name ) ; } return null ;


signature:
public class TarArchiver { /** * tar a file
 * @ param entry the file to tar
 * @ param tOut the output stream
 * @ param vPath the path name of the file to tar
 * @ throws IOException on error */
protected void tarFile ( ArchiveEntry entry , TarArchiveOutputStream tOut , String vPath ) throws ArchiverException , IOException { } }

implementation:
// don ' t add " " to the archive
if ( vPath . length ( ) <= 0 ) { return ; } if ( entry . getResource ( ) . isDirectory ( ) && ! vPath . endsWith ( "/" ) ) { vPath += "/" ; } if ( vPath . startsWith ( "/" ) && ! options . getPreserveLeadingSlashes ( ) ) { int l = vPath . length ( ) ; if ( l <= 1 ) { // we would end up adding " " to the archive
return ; } vPath = vPath . substring ( 1 , l ) ; } int pathLength = vPath . length ( ) ; InputStream fIn = null ; try { TarArchiveEntry te ; if ( ! longFileMode . isGnuMode ( ) && pathLength >= org . apache . commons . compress . archivers . tar . TarConstants . NAMELEN ) { int maxPosixPathLen = org . apache . commons . compress . archivers . tar . TarConstants . NAMELEN + org . apache . commons . compress . archivers . tar . TarConstants . PREFIXLEN ; if ( longFileMode . isPosixMode ( ) ) { } else if ( longFileMode . isPosixWarnMode ( ) ) { if ( pathLength > maxPosixPathLen ) { getLogger ( ) . warn ( "Entry: " + vPath + " longer than " + maxPosixPathLen + " characters." ) ; if ( ! longWarningGiven ) { getLogger ( ) . warn ( "Resulting tar file can only be processed " + "successfully by GNU compatible tar commands" ) ; longWarningGiven = true ; } } } else if ( longFileMode . isOmitMode ( ) ) { getLogger ( ) . info ( "Omitting: " + vPath ) ; return ; } else if ( longFileMode . isWarnMode ( ) ) { getLogger ( ) . warn ( "Entry: " + vPath + " longer than " + org . apache . commons . compress . archivers . tar . TarConstants . NAMELEN + " characters." ) ; if ( ! longWarningGiven ) { getLogger ( ) . warn ( "Resulting tar file can only be processed " + "successfully by GNU compatible tar commands" ) ; longWarningGiven = true ; } } else if ( longFileMode . isFailMode ( ) ) { throw new ArchiverException ( "Entry: " + vPath + " longer than " + org . apache . commons . compress . archivers . tar . TarConstants . NAMELEN + " characters." ) ; } else { throw new IllegalStateException ( "Non gnu mode should never get here?" ) ; } } if ( entry . getType ( ) == ArchiveEntry . SYMLINK ) { final SymlinkDestinationSupplier plexusIoSymlinkResource = ( SymlinkDestinationSupplier ) entry . getResource ( ) ; te = new TarArchiveEntry ( vPath , TarArchiveEntry . LF_SYMLINK ) ; te . setLinkName ( plexusIoSymlinkResource . getSymlinkDestination ( ) ) ; } else { te = new TarArchiveEntry ( vPath ) ; } long teLastModified = entry . getResource ( ) . getLastModified ( ) ; te . setModTime ( teLastModified == PlexusIoResource . UNKNOWN_MODIFICATION_DATE ? System . currentTimeMillis ( ) : teLastModified ) ; if ( entry . getType ( ) == ArchiveEntry . SYMLINK ) { te . setSize ( 0 ) ; } else if ( ! entry . getResource ( ) . isDirectory ( ) ) { final long size = entry . getResource ( ) . getSize ( ) ; te . setSize ( size == PlexusIoResource . UNKNOWN_RESOURCE_SIZE ? 0 : size ) ; } te . setMode ( entry . getMode ( ) ) ; PlexusIoResourceAttributes attributes = entry . getResourceAttributes ( ) ; te . setUserName ( ( attributes != null && attributes . getUserName ( ) != null ) ? attributes . getUserName ( ) : options . getUserName ( ) ) ; te . setGroupName ( ( attributes != null && attributes . getGroupName ( ) != null ) ? attributes . getGroupName ( ) : options . getGroup ( ) ) ; final int userId = ( attributes != null && attributes . getUserId ( ) != null ) ? attributes . getUserId ( ) : options . getUid ( ) ; if ( userId >= 0 ) { te . setUserId ( userId ) ; } final int groupId = ( attributes != null && attributes . getGroupId ( ) != null ) ? attributes . getGroupId ( ) : options . getGid ( ) ; if ( groupId >= 0 ) { te . setGroupId ( groupId ) ; } tOut . putArchiveEntry ( te ) ; try { if ( entry . getResource ( ) . isFile ( ) && ! ( entry . getType ( ) == ArchiveEntry . SYMLINK ) ) { fIn = entry . getInputStream ( ) ; Streams . copyFullyDontCloseOutput ( fIn , tOut , "xAR" ) ; } } catch ( Throwable e ) { getLogger ( ) . warn ( "When creating tar entry" , e ) ; } finally { tOut . closeArchiveEntry ( ) ; } } finally { IOUtil . close ( fIn ) ; }


signature:
public class DirectoryArchiver { /** * Copies the specified file to the specified path , creating any ancestor directory structure as necessary .
 * @ param file
 * The file to copy ( IOException will be thrown if this does not exist )
 * @ param vPath
 * The fully qualified path to copy the file to .
 * @ throws ArchiverException
 * If there is a problem creating the directory structure
 * @ throws IOException
 * If there is a problem copying the file */
protected void copyFile ( final ArchiveEntry entry , final String vPath ) throws ArchiverException , IOException { } }

implementation:
// don ' t add " " to the archive
if ( vPath . length ( ) <= 0 ) { return ; } final PlexusIoResource in = entry . getResource ( ) ; final File outFile = new File ( vPath ) ; final long inLastModified = in . getLastModified ( ) ; final long outLastModified = outFile . lastModified ( ) ; if ( ResourceUtils . isUptodate ( inLastModified , outLastModified ) ) { return ; } if ( ! in . isDirectory ( ) ) { if ( ! outFile . getParentFile ( ) . exists ( ) ) { // create the parent directory . . .
if ( ! outFile . getParentFile ( ) . mkdirs ( ) ) { // Failure , unable to create specified directory for some unknown reason .
throw new ArchiverException ( "Unable to create directory or parent directory of " + outFile ) ; } } ResourceUtils . copyFile ( entry . getInputStream ( ) , outFile ) ; if ( ! isIgnorePermissions ( ) ) { ArchiveEntryUtils . chmod ( outFile , entry . getMode ( ) , getLogger ( ) , isUseJvmChmod ( ) ) ; } } else { // file is a directory
if ( outFile . exists ( ) ) { if ( ! outFile . isDirectory ( ) ) { // should we just delete the file and replace it with a directory ?
// throw an exception , let the user delete the file manually .
throw new ArchiverException ( "Expected directory and found file at copy destination of " + in . getName ( ) + " to " + outFile ) ; } } else if ( ! outFile . mkdirs ( ) ) { // Failure , unable to create specified directory for some unknown reason .
throw new ArchiverException ( "Unable to create directory or parent directory of " + outFile ) ; } } outFile . setLastModified ( inLastModified == PlexusIoResource . UNKNOWN_MODIFICATION_DATE ? System . currentTimeMillis ( ) : inLastModified ) ;


signature:
public class JarArchiver { /** * Allows the manifest for the archive file to be provided inline
 * in the build file rather than in an external file .
 * @ param newManifest The new manifest
 * @ throws ManifestException . */
public void addConfiguredManifest ( Manifest newManifest ) throws ManifestException { } }

implementation: if ( configuredManifest == null ) { configuredManifest = newManifest ; } else { JdkManifestFactory . merge ( configuredManifest , newManifest , false ) ; } savedConfiguredManifest = configuredManifest ;


signature:
public class JarArchiver { /** * The manifest file to use . This can be either the location of a manifest , or the name of a jar added through a
 * fileset . If its the name of an added jar , the task expects the manifest to be in the jar at META - INF / MANIFEST . MF .
 * @ param manifestFile the manifest file to use .
 * @ throws org . codehaus . plexus . archiver . ArchiverException */
@ SuppressWarnings ( { } }

implementation: "UnusedDeclaration" } ) public void setManifest ( File manifestFile ) throws ArchiverException { if ( ! manifestFile . exists ( ) ) { throw new ArchiverException ( "Manifest file: " + manifestFile + " does not exist." ) ; } this . manifestFile = manifestFile ;


signature:
public class JarArchiver { /** * Behavior when a Manifest is found in a zipfileset or zipgroupfileset file .
 * Valid values are " skip " , " merge " , and " mergewithoutmain " .
 * " merge " will merge all of manifests together , and merge this into any
 * other specified manifests .
 * " mergewithoutmain " merges everything but the Main section of the manifests .
 * Default value is " skip " .
 * Note : if this attribute ' s value is not " skip " , the created jar will not
 * be readable by using java . util . jar . JarInputStream
 * @ param config setting for found manifest behavior . */
@ SuppressWarnings ( { } }

implementation: "UnusedDeclaration" } ) public void setFilesetmanifest ( FilesetManifestConfig config ) { filesetManifestConfig = config ; mergeManifestsMain = FilesetManifestConfig . merge == config ; if ( ( filesetManifestConfig != null ) && filesetManifestConfig != FilesetManifestConfig . skip ) { doubleFilePass = true ; }


signature:
public class JarArchiver { /** * Create the index list to speed up classloading .
 * This is a JDK 1.3 + specific feature and is enabled by default . See
 * < a href = " http : / / java . sun . com / j2se / 1.3 / docs / guide / jar / jar . html # JAR % 20Index " >
 * the JAR index specification < / a > for more details .
 * @ param zOut the zip stream representing the jar being built .
 * @ throws IOException thrown if there is an error while creating the
 * index and adding it to the zip stream .
 * @ throws org . codehaus . plexus . archiver . ArchiverException */
private void createIndexList ( ZipArchiveOutputStream zOut ) throws IOException , ArchiverException { } }

implementation:
ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; // encoding must be UTF8 as specified in the specs .
PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( baos , "UTF8" ) ) ; // version - info blankline
writer . println ( "JarIndex-Version: 1.0" ) ; writer . println ( ) ; // header newline
writer . println ( getDestFile ( ) . getName ( ) ) ; // filter out META - INF if it doesn ' t contain anything other than the index and manifest .
// this is what sun . misc . JarIndex does , guess we ought to be consistent .
Set < String > filteredDirs = new HashSet < String > ( addedDirs . keySet ( ) ) ; // our added dirs always have a trailing slash
if ( filteredDirs . contains ( META_INF_NAME + '/' ) ) { boolean add = false ; for ( String entry : entries . keySet ( ) ) { if ( entry . startsWith ( META_INF_NAME + '/' ) && ! entry . equals ( INDEX_NAME ) && ! entry . equals ( MANIFEST_NAME ) ) { add = true ; break ; } } if ( ! add ) { filteredDirs . remove ( META_INF_NAME + '/' ) ; } } writeIndexLikeList ( new ArrayList < String > ( filteredDirs ) , rootEntries , writer ) ; writer . println ( ) ; if ( indexJars != null ) { java . util . jar . Manifest mf = createManifest ( ) ; String classpath = mf . getMainAttributes ( ) . getValue ( ManifestConstants . ATTRIBUTE_CLASSPATH ) ; String [ ] cpEntries = null ; if ( classpath != null ) { StringTokenizer tok = new StringTokenizer ( classpath , " " ) ; cpEntries = new String [ tok . countTokens ( ) ] ; int c = 0 ; while ( tok . hasMoreTokens ( ) ) { cpEntries [ c ++ ] = tok . nextToken ( ) ; } } for ( String indexJar : indexJars ) { String name = findJarName ( indexJar , cpEntries ) ; if ( name != null ) { ArrayList < String > dirs = new ArrayList < String > ( ) ; ArrayList < String > files = new ArrayList < String > ( ) ; grabFilesAndDirs ( indexJar , dirs , files ) ; if ( dirs . size ( ) + files . size ( ) > 0 ) { writer . println ( name ) ; writeIndexLikeList ( dirs , files , writer ) ; writer . println ( ) ; } } } } writer . flush ( ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; super . zipFile ( bais , zOut , INDEX_NAME , System . currentTimeMillis ( ) , null , DEFAULT_FILE_MODE , null ) ;


signature:
public class JarArchiver { /** * Overridden from Zip class to deal with manifests and index lists . */
protected void zipFile ( InputStream is , ZipArchiveOutputStream zOut , String vPath , long lastModified , File fromArchive , int mode , String symlinkDestination ) throws IOException , ArchiverException { } }

implementation: if ( MANIFEST_NAME . equalsIgnoreCase ( vPath ) ) { if ( ! doubleFilePass || skipWriting ) { filesetManifest ( fromArchive , is ) ; } } else if ( INDEX_NAME . equalsIgnoreCase ( vPath ) && index ) { getLogger ( ) . warn ( "Warning: selected " + archiveType + " files include a META-INF/INDEX.LIST which will" + " be replaced by a newly generated one." ) ; } else { if ( index && ( ! vPath . contains ( "/" ) ) ) { rootEntries . addElement ( vPath ) ; } super . zipFile ( is , zOut , vPath , lastModified , fromArchive , mode , symlinkDestination ) ; }


signature:
public class JarArchiver { /** * Make sure we don ' t think we already have a MANIFEST next time this task
 * gets executed .
 * @ see ZipArchiver # cleanUp */
protected void cleanUp ( ) throws IOException { } }

implementation:
super . cleanUp ( ) ; // we want to save this info if we are going to make another pass
if ( ! doubleFilePass || ! skipWriting ) { manifest = null ; configuredManifest = savedConfiguredManifest ; filesetManifest = null ; originalManifest = null ; } rootEntries . removeAllElements ( ) ;


signature:
public class JarArchiver { /** * reset to default values .
 * @ see ZipArchiver # reset */
public void reset ( ) { } }

implementation: super . reset ( ) ; configuredManifest = null ; filesetManifestConfig = null ; mergeManifestsMain = false ; manifestFile = null ; index = false ;


signature:
public class JarArchiver { /** * Writes the directory entries from the first and the filenames
 * from the second list to the given writer , one entry per line .
 * @ param dirs The directories
 * @ param files The files
 * @ param writer The printwriter ; ) */
protected final void writeIndexLikeList ( List < String > dirs , List < String > files , PrintWriter writer ) { } }

implementation:
// JarIndex is sorting the directories by ascending order .
// it has no value but cosmetic since it will be read into a
// hashtable by the classloader , but we ' ll do so anyway .
Collections . sort ( dirs ) ; Collections . sort ( files ) ; Iterator iter = dirs . iterator ( ) ; while ( iter . hasNext ( ) ) { String dir = ( String ) iter . next ( ) ; // try to be smart , not to be fooled by a weird directory name
dir = dir . replace ( '\\' , '/' ) ; if ( dir . startsWith ( "./" ) ) { dir = dir . substring ( 2 ) ; } while ( dir . startsWith ( "/" ) ) { dir = dir . substring ( 1 ) ; } int pos = dir . lastIndexOf ( '/' ) ; if ( pos != - 1 ) { dir = dir . substring ( 0 , pos ) ; } // name newline
writer . println ( dir ) ; } iter = files . iterator ( ) ; while ( iter . hasNext ( ) ) { writer . println ( iter . next ( ) ) ; }


signature:
public class JarArchiver { /** * try to guess the name of the given file .
 * < p > If this jar has a classpath attribute in its manifest , we
 * can assume that it will only require an index of jars listed
 * there . try to find which classpath entry is most likely the
 * one the given file name points to . < / p >
 * < p > In the absence of a classpath attribute , assume the other
 * files will be placed inside the same directory as this jar and
 * use their basename . < / p >
 * < p > if there is a classpath and the given file doesn ' t match any
 * of its entries , return null . < / p >
 * @ param fileName .
 * @ param classpath .
 * @ return The guessed name */
protected static String findJarName ( String fileName , String [ ] classpath ) { } }

implementation:
if ( classpath == null ) { return new File ( fileName ) . getName ( ) ; } fileName = fileName . replace ( File . separatorChar , '/' ) ; SortedMap < String , String > matches = new TreeMap < String , String > ( new Comparator < String > ( ) { // longest match comes first
public int compare ( String o1 , String o2 ) { if ( ( o1 != null ) && ( o2 != null ) ) { return o2 . length ( ) - o1 . length ( ) ; } return 0 ; } } ) ; for ( String aClasspath : classpath ) { if ( fileName . endsWith ( aClasspath ) ) { matches . put ( aClasspath , aClasspath ) ; } else { int slash = aClasspath . indexOf ( "/" ) ; String candidate = aClasspath ; while ( slash > - 1 ) { candidate = candidate . substring ( slash + 1 ) ; if ( fileName . endsWith ( candidate ) ) { matches . put ( candidate , aClasspath ) ; break ; } slash = candidate . indexOf ( "/" ) ; } } } return matches . size ( ) == 0 ? null : matches . get ( matches . firstKey ( ) ) ;


signature:
public class JarArchiver { /** * Grab lists of all root - level files and all directories
 * contained in the given archive .
 * @ param file .
 * @ param files .
 * @ param dirs .
 * @ throws java . io . IOException . */
protected static void grabFilesAndDirs ( String file , List < String > dirs , List < String > files ) throws IOException { } }

implementation:
File zipFile = new File ( file ) ; if ( ! zipFile . exists ( ) ) { Logger logger = new ConsoleLogger ( Logger . LEVEL_INFO , "console" ) ; logger . error ( "JarArchive skipping non-existing file: " + zipFile . getAbsolutePath ( ) ) ; } else if ( zipFile . isDirectory ( ) ) { Logger logger = new ConsoleLogger ( Logger . LEVEL_INFO , "console" ) ; logger . info ( "JarArchiver skipping indexJar " + zipFile + " because it is not a jar" ) ; } else { org . apache . commons . compress . archivers . zip . ZipFile zf = null ; try { zf = new org . apache . commons . compress . archivers . zip . ZipFile ( file , "utf-8" ) ; Enumeration < ZipArchiveEntry > entries = zf . getEntries ( ) ; HashSet < String > dirSet = new HashSet < String > ( ) ; while ( entries . hasMoreElements ( ) ) { ZipArchiveEntry ze = entries . nextElement ( ) ; String name = ze . getName ( ) ; // avoid index for manifest - only jars .
if ( ! name . equals ( META_INF_NAME ) && ! name . equals ( META_INF_NAME + '/' ) && ! name . equals ( INDEX_NAME ) && ! name . equals ( MANIFEST_NAME ) ) { if ( ze . isDirectory ( ) ) { dirSet . add ( name ) ; } else if ( ! name . contains ( "/" ) ) { files . add ( name ) ; } else { // a file , not in the root
// since the jar may be one without directory
// entries , add the parent dir of this file as
// well .
dirSet . add ( name . substring ( 0 , name . lastIndexOf ( "/" ) + 1 ) ) ; } } } dirs . addAll ( dirSet ) ; } finally { if ( zf != null ) { zf . close ( ) ; } } }


signature:
public class TarUnArchiver { /** * This method wraps the input stream with the
 * corresponding decompression method
 * @ param file provides location information for BuildException
 * @ param istream input stream
 * @ return input stream with on - the - fly decompression
 * @ throws IOException thrown by GZIPInputStream constructor */
private InputStream decompress ( UntarCompressionMethod compression , final File file , final InputStream istream ) throws IOException , ArchiverException { } }

implementation: if ( compression == UntarCompressionMethod . GZIP ) { return new GZIPInputStream ( istream ) ; } else if ( compression == UntarCompressionMethod . BZIP2 ) { return new BZip2CompressorInputStream ( istream ) ; } else if ( compression == UntarCompressionMethod . SNAPPY ) { return new SnappyInputStream ( istream ) ; } return istream ;


signature:
public class DryRunArchiver { /** * { @ inheritDoc } */
public void addArchivedFileSet ( final @ Nonnull File archiveFile , final String prefix , final String [ ] includes , final String [ ] excludes ) { } }

implementation: debug ( "DRY RUN: Skipping delegated call to: " + getMethodName ( ) ) ;


signature:
public class DryRunArchiver { /** * { @ inheritDoc } */
public void addArchivedFileSet ( final File archiveFile , final String [ ] includes , final String [ ] excludes ) throws ArchiverException { } }


signature:
public class DryRunArchiver { /** * { @ inheritDoc } */
public void addDirectory ( final @ Nonnull File directory , final String prefix , final String [ ] includes , final String [ ] excludes ) throws ArchiverException { } }


signature:
public class DryRunArchiver { /** * { @ inheritDoc } */
public void addFile ( final @ Nonnull File inputFile , final @ Nonnull String destFileName ) throws ArchiverException { } }


signature:
public class AbstractArchiver { /** * Allows us to pull the ArchiverManager instance out of the container without causing a chicken - and - egg
 * instantiation / composition problem . */
public void contextualize ( final Context context ) throws ContextException { } }

implementation: final PlexusContainer container = ( PlexusContainer ) context . get ( PlexusConstants . PLEXUS_KEY ) ; try { archiverManager = ( ArchiverManager ) container . lookup ( ArchiverManager . ROLE ) ; } catch ( final ComponentLookupException e ) { throw new ContextException ( "Error retrieving ArchiverManager instance: " + e . getMessage ( ) , e ) ; }


signature:
public class GZipCompressor { /** * perform the GZip compression operation . */
public void compress ( ) throws ArchiverException { } }

implementation: try { zOut = new GZIPOutputStream ( Streams . bufferedOutputStream ( new FileOutputStream ( getDestFile ( ) ) ) ) ; compress ( getSource ( ) , zOut ) ; } catch ( IOException ioe ) { String msg = "Problem creating gzip " + ioe . getMessage ( ) ; throw new ArchiverException ( msg , ioe ) ; }


signature:
public class JdkManifestFactory { /** * Merge in another section
 * @ param target The target manifest of the merge
 * @ param section the section to be merged with this one . */
public static void mergeAttributes ( java . util . jar . Attributes target , java . util . jar . Attributes section ) { } }

implementation:
for ( Object o : section . keySet ( ) ) { java . util . jar . Attributes . Name key = ( Attributes . Name ) o ; final Object value = section . get ( o ) ; // the merge file always wins
target . put ( key , value ) ; }


signature:
public class ArchiveEntryUtils { /** * < b > jvm chmod will be used only if System property < code > useJvmChmod < / code > set to true < / b >
 * @ param file
 * @ param mode
 * @ param logger
 * @ throws ArchiverException */
public static void chmod ( final File file , final int mode , final Logger logger ) throws ArchiverException { } }

implementation: chmod ( file , mode , logger , Boolean . getBoolean ( "useJvmChmod" ) && jvmFilePermAvailable ) ;


signature:
public class AbstractZipUnArchiver { /** * Sets the encoding to assume for file names and comments .
 * Set to < code > native - encoding < / code > if you want your platform ' s native encoding , defaults to UTF8. */
public void setEncoding ( String encoding ) { } }

implementation: if ( NATIVE_ENCODING . equals ( encoding ) ) { encoding = null ; } this . encoding = encoding ;


signature:
public class EarArchiver { /** * File to incorporate as application . xml . */
public void setAppxml ( File descr ) throws ArchiverException { } }

implementation: deploymentDescriptor = descr ; if ( ! deploymentDescriptor . exists ( ) ) { throw new ArchiverException ( "Deployment descriptor: " + deploymentDescriptor + " does not exist." ) ; } addFile ( descr , "META-INF/application.xml" ) ;


signature:
public class EarArchiver { /** * Adds archive . */
public void addArchive ( File fileName ) throws ArchiverException { } }

implementation: addDirectory ( fileName . getParentFile ( ) , "/" , new String [ ] { fileName . getName ( ) } , null ) ;


signature:
public class EarArchiver { /** * Adds archives . */
public void addArchives ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { } }

implementation: addDirectory ( directoryName , "/" , includes , excludes ) ;


signature:
public class SnappyCompressor { /** * perform the Snappy compression operation . */
public void compress ( ) throws ArchiverException { } }

implementation: try { zOut = new SnappyOutputStream ( bufferedOutputStream ( fileOutputStream ( getDestFile ( ) ) ) ) ; compress ( getSource ( ) , zOut ) ; } catch ( IOException ioe ) { String msg = "Problem creating snappy " + ioe . getMessage ( ) ; throw new ArchiverException ( msg , ioe ) ; }


signature:
public class AbstractZipArchiver { /** * Add the given resources .
 * @ param resources the resources to add
 * @ param zOut the stream to write to */
@ SuppressWarnings ( { } }

implementation: "JavaDoc" } ) protected final void addResources ( ResourceIterator resources , ZipArchiveOutputStream zOut ) throws IOException , ArchiverException { File base = null ; while ( resources . hasNext ( ) ) { ArchiveEntry entry = resources . next ( ) ; String name = entry . getName ( ) ; name = name . replace ( File . separatorChar , '/' ) ; if ( "" . equals ( name ) ) { continue ; } if ( entry . getResource ( ) . isDirectory ( ) && ! name . endsWith ( "/" ) ) { name = name + "/" ; } addParentDirs ( entry , base , name , zOut , "" ) ; if ( entry . getResource ( ) . isFile ( ) ) { zipFile ( entry , zOut , name ) ; } else { zipDir ( entry . getResource ( ) , zOut , name , entry . getMode ( ) ) ; } }


signature:
public class AbstractZipArchiver { /** * Ensure all parent dirs of a given entry have been added .
 * This method is computed in terms of the potentially remapped entry ( that may be disconnected from the file system )
 * we do not * relly * know the entry ' s connection to the file system so establishing the attributes of the parents can
 * be impossible and is not really supported . */
@ SuppressWarnings ( { } }

implementation:
"JavaDoc" } ) private void addParentDirs ( ArchiveEntry archiveEntry , File baseDir , String entry , ZipArchiveOutputStream zOut , String prefix ) throws IOException { if ( ! doFilesonly && getIncludeEmptyDirs ( ) ) { Stack < String > directories = new Stack < String > ( ) ; // Don ' t include the last entry itself if it ' s
// a dir ; it will be added on its own .
int slashPos = entry . length ( ) - ( entry . endsWith ( "/" ) ? 1 : 0 ) ; while ( ( slashPos = entry . lastIndexOf ( '/' , slashPos - 1 ) ) != - 1 ) { String dir = entry . substring ( 0 , slashPos + 1 ) ; if ( addedDirs . contains ( prefix + dir ) ) { break ; } directories . push ( dir ) ; } while ( ! directories . isEmpty ( ) ) { String dir = directories . pop ( ) ; File f ; if ( baseDir != null ) { f = new File ( baseDir , dir ) ; } else { f = new File ( dir ) ; } // the
// At this point we could do something like read the atr
final PlexusIoResource res = new AnonymousResource ( f ) ; zipDir ( res , zOut , prefix + dir , archiveEntry . getDefaultDirMode ( ) ) ; } }


signature:
public class AbstractZipArchiver { /** * Adds a new entry to the archive , takes care of duplicates as well .
 * @ param in the stream to read data for the entry from .
 * @ param zOut the stream to write to .
 * @ param vPath the name this entry shall have in the archive .
 * @ param lastModified last modification time for the entry .
 * @ param fromArchive the original archive we are copying this
 * @ param symlinkDestination */
@ SuppressWarnings ( { } }

implementation:
"JavaDoc" } ) protected void zipFile ( InputStream in , ZipArchiveOutputStream zOut , String vPath , long lastModified , File fromArchive , int mode , String symlinkDestination ) throws IOException , ArchiverException { getLogger ( ) . debug ( "adding entry " + vPath ) ; entries . put ( vPath , vPath ) ; if ( ! skipWriting ) { ZipArchiveEntry ze = new ZipArchiveEntry ( vPath ) ; setTime ( ze , lastModified ) ; byte [ ] header = new byte [ 4 ] ; int read = in . read ( header ) ; boolean compressThis = doCompress ; if ( ! recompressAddedZips && isZipHeader ( header ) ) { compressThis = false ; } ze . setMethod ( compressThis ? ZipArchiveEntry . DEFLATED : ZipArchiveEntry . STORED ) ; ze . setUnixMode ( UnixStat . FILE_FLAG | mode ) ; /* * ZipOutputStream . putNextEntry expects the ZipEntry to
 * know its size and the CRC sum before you start writing
 * the data when using STORED mode - unless it is seekable .
 * This forces us to process the data twice . */
if ( ze . isUnixSymlink ( ) ) { zOut . putArchiveEntry ( ze ) ; ZipEncoding enc = ZipEncodingHelper . getZipEncoding ( getEncoding ( ) ) ; final byte [ ] bytes = enc . encode ( symlinkDestination ) . array ( ) ; zOut . write ( bytes , 0 , bytes . length ) ; } else if ( zOut . isSeekable ( ) || compressThis ) { zOut . putArchiveEntry ( ze ) ; if ( read > 0 ) zOut . write ( header , 0 , read ) ; IOUtil . copy ( in , zOut , 8 * 1024 ) ; } else { if ( in . markSupported ( ) ) { in . mark ( Integer . MAX_VALUE ) ; readWithZipStats ( in , header , read , ze , null ) ; in . reset ( ) ; zOut . putArchiveEntry ( ze ) ; if ( read > 0 ) zOut . write ( header , 0 , read ) ; IOUtil . copy ( in , zOut , 8 * 1024 ) ; } else { // Store data into a byte [ ]
// todo : explain how on earth this code works with zip streams > 128KB ? ? ?
ByteArrayOutputStream bos = new ByteArrayOutputStream ( 128 * 1024 ) ; readWithZipStats ( in , header , read , ze , bos ) ; zOut . putArchiveEntry ( ze ) ; if ( read > 0 ) zOut . write ( header , 0 , read ) ; bos . writeTo ( zOut ) ; } } zOut . closeArchiveEntry ( ) ; }


signature:
public class AbstractZipArchiver { /** * Method that gets called when adding from java . io . File instances .
 * < p > This implementation delegates to the six - arg version . < / p >
 * @ param entry the file to add to the archive
 * @ param zOut the stream to write to
 * @ param vPath the name this entry shall have in the archive */
@ SuppressWarnings ( { } }

implementation: "JavaDoc" } ) protected void zipFile ( ArchiveEntry entry , ZipArchiveOutputStream zOut , String vPath ) throws IOException , ArchiverException { final PlexusIoResource resource = entry . getResource ( ) ; if ( ResourceUtils . isSame ( resource , getDestFile ( ) ) ) { throw new ArchiverException ( "A zip file cannot include itself" ) ; } final boolean b = entry . getResource ( ) instanceof SymlinkDestinationSupplier ; String symlinkTarget = b ? ( ( SymlinkDestinationSupplier ) entry . getResource ( ) ) . getSymlinkDestination ( ) : null ; InputStream in = entry . getInputStream ( ) ; try { zipFile ( in , zOut , vPath , resource . getLastModified ( ) , null , entry . getMode ( ) , symlinkTarget ) ; } catch ( IOException e ) { throw new ArchiverException ( "IOException when zipping r" + entry . getName ( ) + ": " + e . getMessage ( ) , e ) ; } finally { IOUtil . close ( in ) ; }


signature:
public class AbstractZipArchiver { /** * Create an empty zip file
 * @ param zipFile The file
 * @ return true for historic reasons */
@ SuppressWarnings ( { } }

implementation:
"JavaDoc" } ) protected boolean createEmptyZip ( File zipFile ) throws ArchiverException { // In this case using java . util . zip will not work
// because it does not permit a zero - entry archive .
// Must create it manually .
getLogger ( ) . info ( "Note: creating empty " + archiveType + " archive " + zipFile ) ; OutputStream os = null ; try { os = new FileOutputStream ( zipFile ) ; // Cf . PKZIP specification .
byte [ ] empty = new byte [ 22 ] ; empty [ 0 ] = 80 ; empty [ 1 ] = 75 ; empty [ 2 ] = 5 ; empty [ 3 ] = 6 ; // remainder zeros
os . write ( empty ) ; } catch ( IOException ioe ) { throw new ArchiverException ( "Could not create empty ZIP archive " + "(" + ioe . getMessage ( ) + ")" , ioe ) ; } finally { IOUtil . close ( os ) ; } return true ;


signature:
public class AbstractZipArchiver { /** * Do any clean up necessary to allow this instance to be used again .
 * < p > When we get here , the Zip file has been closed and all we
 * need to do is to reset some globals . < / p >
 * < p > This method will only reset globals that have been changed
 * during execute ( ) , it will not alter the attributes or nested
 * child elements . If you want to reset the instance so that you
 * can later zip a completely different set of files , you must use
 * the reset method . < / p >
 * @ see # reset */
protected void cleanUp ( ) throws IOException { } }

implementation: super . cleanUp ( ) ; addedDirs . clear ( ) ; entries . clear ( ) ; addingNewFiles = false ; doUpdate = savedDoUpdate ; success = false ; zOut = null ; renamedFile = null ; zipFile = null ;


signature:
public class AbstractZipArchiver { /** * Makes this instance reset all attributes to their default
 * values and forget all children .
 * @ see # cleanUp */
public void reset ( ) { } }

implementation:
setDestFile ( null ) ; // duplicate = " add " ;
archiveType = "zip" ; doCompress = true ; doUpdate = false ; doFilesonly = false ; encoding = null ;


signature:
public class Compressor { /** * compress a stream to an output stream
 * @ param in
 * @ param zOut
 * @ throws IOException */
private void compressFile ( InputStream in , OutputStream zOut ) throws IOException { } }

implementation: byte [ ] buffer = new byte [ 8 * 1024 ] ; int count = 0 ; do { zOut . write ( buffer , 0 , count ) ; count = in . read ( buffer , 0 , buffer . length ) ; } while ( count != - 1 ) ;


signature:
public class Compressor { /** * compress a resource to an output stream */
protected void compress ( PlexusIoResource resource , OutputStream zOut ) throws IOException { } }

implementation: InputStream in = Streams . bufferedInputStream ( resource . getContents ( ) ) ; try { compressFile ( in , zOut ) ; } finally { IOUtil . close ( in ) ; }


signature:
public class Decoder { /** * Decode the header block into header fields . */
public void decode ( InputStream in , HeaderListener headerListener ) throws IOException { } }

implementation:
while ( in . available ( ) > 0 ) { switch ( state ) { case READ_HEADER_REPRESENTATION : byte b = ( byte ) in . read ( ) ; if ( maxDynamicTableSizeChangeRequired && ( b & 0xE0 ) != 0x20 ) { // Encoder MUST signal maximum dynamic table size change
throw MAX_DYNAMIC_TABLE_SIZE_CHANGE_REQUIRED ; } if ( b < 0 ) { // Indexed Header Field
index = b & 0x7F ; if ( index == 0 ) { throw ILLEGAL_INDEX_VALUE ; } else if ( index == 0x7F ) { state = State . READ_INDEXED_HEADER ; } else { indexHeader ( index , headerListener ) ; } } else if ( ( b & 0x40 ) == 0x40 ) { // Literal Header Field with Incremental Indexing
indexType = IndexType . INCREMENTAL ; index = b & 0x3F ; if ( index == 0 ) { state = State . READ_LITERAL_HEADER_NAME_LENGTH_PREFIX ; } else if ( index == 0x3F ) { state = State . READ_INDEXED_HEADER_NAME ; } else { // Index was stored as the prefix
readName ( index ) ; state = State . READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX ; } } else if ( ( b & 0x20 ) == 0x20 ) { // Dynamic Table Size Update
index = b & 0x1F ; if ( index == 0x1F ) { state = State . READ_MAX_DYNAMIC_TABLE_SIZE ; } else { setDynamicTableSize ( index ) ; state = State . READ_HEADER_REPRESENTATION ; } } else { // Literal Header Field without Indexing / never Indexed
indexType = ( ( b & 0x10 ) == 0x10 ) ? IndexType . NEVER : IndexType . NONE ; index = b & 0x0F ; if ( index == 0 ) { state = State . READ_LITERAL_HEADER_NAME_LENGTH_PREFIX ; } else if ( index == 0x0F ) { state = State . READ_INDEXED_HEADER_NAME ; } else { // Index was stored as the prefix
readName ( index ) ; state = State . READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX ; } } break ; case READ_MAX_DYNAMIC_TABLE_SIZE : int maxSize = decodeULE128 ( in ) ; if ( maxSize == - 1 ) { return ; } // Check for numerical overflow
if ( maxSize > Integer . MAX_VALUE - index ) { throw DECOMPRESSION_EXCEPTION ; } setDynamicTableSize ( index + maxSize ) ; state = State . READ_HEADER_REPRESENTATION ; break ; case READ_INDEXED_HEADER : int headerIndex = decodeULE128 ( in ) ; if ( headerIndex == - 1 ) { return ; } // Check for numerical overflow
if ( headerIndex > Integer . MAX_VALUE - index ) { throw DECOMPRESSION_EXCEPTION ; } indexHeader ( index + headerIndex , headerListener ) ; state = State . READ_HEADER_REPRESENTATION ; break ; case READ_INDEXED_HEADER_NAME : // Header Name matches an entry in the Header Table
int nameIndex = decodeULE128 ( in ) ; if ( nameIndex == - 1 ) { return ; } // Check for numerical overflow
if ( nameIndex > Integer . MAX_VALUE - index ) { throw DECOMPRESSION_EXCEPTION ; } readName ( index + nameIndex ) ; state = State . READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX ; break ; case READ_LITERAL_HEADER_NAME_LENGTH_PREFIX : b = ( byte ) in . read ( ) ; huffmanEncoded = ( b & 0x80 ) == 0x80 ; index = b & 0x7F ; if ( index == 0x7f ) { state = State . READ_LITERAL_HEADER_NAME_LENGTH ; } else { nameLength = index ; // Disallow empty names - - they cannot be represented in HTTP / 1 . x
if ( nameLength == 0 ) { throw DECOMPRESSION_EXCEPTION ; } // Check name length against max header size
if ( exceedsMaxHeaderSize ( nameLength ) ) { if ( indexType == IndexType . NONE ) { // Name is unused so skip bytes
name = EMPTY ; skipLength = nameLength ; state = State . SKIP_LITERAL_HEADER_NAME ; break ; } // Check name length against max dynamic table size
if ( nameLength + HEADER_ENTRY_OVERHEAD > dynamicTable . capacity ( ) ) { dynamicTable . clear ( ) ; name = EMPTY ; skipLength = nameLength ; state = State . SKIP_LITERAL_HEADER_NAME ; break ; } } state = State . READ_LITERAL_HEADER_NAME ; } break ; case READ_LITERAL_HEADER_NAME_LENGTH : // Header Name is a Literal String
nameLength = decodeULE128 ( in ) ; if ( nameLength == - 1 ) { return ; } // Check for numerical overflow
if ( nameLength > Integer . MAX_VALUE - index ) { throw DECOMPRESSION_EXCEPTION ; } nameLength += index ; // Check name length against max header size
if ( exceedsMaxHeaderSize ( nameLength ) ) { if ( indexType == IndexType . NONE ) { // Name is unused so skip bytes
name = EMPTY ; skipLength = nameLength ; state = State . SKIP_LITERAL_HEADER_NAME ; break ; } // Check name length against max dynamic table size
if ( nameLength + HEADER_ENTRY_OVERHEAD > dynamicTable . capacity ( ) ) { dynamicTable . clear ( ) ; name = EMPTY ; skipLength = nameLength ; state = State . SKIP_LITERAL_HEADER_NAME ; break ; } } state = State . READ_LITERAL_HEADER_NAME ; break ; case READ_LITERAL_HEADER_NAME : // Wait until entire name is readable
if ( in . available ( ) < nameLength ) { return ; } name = readStringLiteral ( in , nameLength ) ; state = State . READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX ; break ; case SKIP_LITERAL_HEADER_NAME : skipLength -= in . skip ( skipLength ) ; if ( skipLength == 0 ) { state = State . READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX ; } break ; case READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX : b = ( byte ) in . read ( ) ; huffmanEncoded = ( b & 0x80 ) == 0x80 ; index = b & 0x7F ; if ( index == 0x7f ) { state = State . READ_LITERAL_HEADER_VALUE_LENGTH ; } else { valueLength = index ; // Check new header size against max header size
long newHeaderSize = ( long ) nameLength + ( long ) valueLength ; if ( exceedsMaxHeaderSize ( newHeaderSize ) ) { // truncation will be reported during endHeaderBlock
headerSize = maxHeaderSize + 1 ; if ( indexType == IndexType . NONE ) { // Value is unused so skip bytes
state = State . SKIP_LITERAL_HEADER_VALUE ; break ; } // Check new header size against max dynamic table size
if ( newHeaderSize + HEADER_ENTRY_OVERHEAD > dynamicTable . capacity ( ) ) { dynamicTable . clear ( ) ; state = State . SKIP_LITERAL_HEADER_VALUE ; break ; } } if ( valueLength == 0 ) { insertHeader ( headerListener , name , EMPTY , indexType ) ; state = State . READ_HEADER_REPRESENTATION ; } else { state = State . READ_LITERAL_HEADER_VALUE ; } } break ; case READ_LITERAL_HEADER_VALUE_LENGTH : // Header Value is a Literal String
valueLength = decodeULE128 ( in ) ; if ( valueLength == - 1 ) { return ; } // Check for numerical overflow
if ( valueLength > Integer . MAX_VALUE - index ) { throw DECOMPRESSION_EXCEPTION ; } valueLength += index ; // Check new header size against max header size
long newHeaderSize = ( long ) nameLength + ( long ) valueLength ; if ( newHeaderSize + headerSize > maxHeaderSize ) { // truncation will be reported during endHeaderBlock
headerSize = maxHeaderSize + 1 ; if ( indexType == IndexType . NONE ) { // Value is unused so skip bytes
state = State . SKIP_LITERAL_HEADER_VALUE ; break ; } // Check new header size against max dynamic table size
if ( newHeaderSize + HEADER_ENTRY_OVERHEAD > dynamicTable . capacity ( ) ) { dynamicTable . clear ( ) ; state = State . SKIP_LITERAL_HEADER_VALUE ; break ; } } state = State . READ_LITERAL_HEADER_VALUE ; break ; case READ_LITERAL_HEADER_VALUE : // Wait until entire value is readable
if ( in . available ( ) < valueLength ) { return ; } byte [ ] value = readStringLiteral ( in , valueLength ) ; insertHeader ( headerListener , name , value , indexType ) ; state = State . READ_HEADER_REPRESENTATION ; break ; case SKIP_LITERAL_HEADER_VALUE : valueLength -= in . skip ( valueLength ) ; if ( valueLength == 0 ) { state = State . READ_HEADER_REPRESENTATION ; } break ; default : throw new IllegalStateException ( "should not reach here" ) ; } }


signature:
public class Decoder { /** * Set the maximum table size .
 * If this is below the maximum size of the dynamic table used by the encoder ,
 * the beginning of the next header block MUST signal this change . */
public void setMaxHeaderTableSize ( int maxHeaderTableSize ) { } }

implementation:
maxDynamicTableSize = maxHeaderTableSize ; if ( maxDynamicTableSize < encoderMaxDynamicTableSize ) { // decoder requires less space than encoder
// encoder MUST signal this change
maxDynamicTableSizeChangeRequired = true ; dynamicTable . setCapacity ( maxDynamicTableSize ) ; }


signature:
public class Decoder { /** * Unsigned Little Endian Base 128 Variable - Length Integer Encoding */
private static int decodeULE128 ( InputStream in ) throws IOException { } }

implementation:
in . mark ( 5 ) ; int result = 0 ; int shift = 0 ; while ( shift < 32 ) { if ( in . available ( ) == 0 ) { // Buffer does not contain entire integer ,
// reset reader index and return - 1.
in . reset ( ) ; return - 1 ; } byte b = ( byte ) in . read ( ) ; if ( shift == 28 && ( b & 0xF8 ) != 0 ) { break ; } result |= ( b & 0x7F ) << shift ; if ( ( b & 0x80 ) == 0 ) { return result ; } shift += 7 ; } // Value exceeds Integer . MAX _ VALUE
in . reset ( ) ; throw DECOMPRESSION_EXCEPTION ;


signature:
public class StaticTable { /** * Returns the lowest index value for the given header field name in the static table .
 * Returns - 1 if the header field name is not in the static table . */
static int getIndex ( byte [ ] name ) { } }

implementation: String nameString = new String ( name , 0 , name . length , ISO_8859_1 ) ; Integer index = STATIC_INDEX_BY_NAME . get ( nameString ) ; if ( index == null ) { return - 1 ; } return index ;


signature:
public class StaticTable { /** * Returns the index value for the given header field in the static table .
 * Returns - 1 if the header field is not in the static table . */
static int getIndex ( byte [ ] name , byte [ ] value ) { } }

implementation:
int index = getIndex ( name ) ; if ( index == - 1 ) { return - 1 ; } // Note this assumes all entries for a given header field are sequential .
while ( index <= length ) { HeaderField entry = getEntry ( index ) ; if ( ! HpackUtil . equals ( name , entry . name ) ) { break ; } if ( HpackUtil . equals ( value , entry . value ) ) { return index ; } index ++ ; } return - 1 ;


signature:
public class StaticTable { /** * create a map of header name to index value to allow quick lookup */
private static Map < String , Integer > createMap ( ) { } }

implementation:
int length = STATIC_TABLE . size ( ) ; HashMap < String , Integer > ret = new HashMap < String , Integer > ( length ) ; // Iterate through the static table in reverse order to
// save the smallest index for a given name in the map .
for ( int index = length ; index > 0 ; index -- ) { HeaderField entry = getEntry ( index ) ; String name = new String ( entry . name , 0 , entry . name . length , ISO_8859_1 ) ; ret . put ( name , index ) ; } return ret ;


signature:
public class HuffmanEncoder { /** * Compresses the input string literal using the Huffman coding .
 * @ param out the output stream for the compressed data
 * @ param data the string literal to be Huffman encoded
 * @ throws IOException if an I / O error occurs .
 * @ see com . twitter . hpack . HuffmanEncoder # encode ( OutputStream , byte [ ] , int , int ) */
public void encode ( OutputStream out , byte [ ] data ) throws IOException { } }

implementation: encode ( out , data , 0 , data . length ) ;


signature:
public class HuffmanEncoder { /** * Compresses the input string literal using the Huffman coding .
 * @ param out the output stream for the compressed data
 * @ param data the string literal to be Huffman encoded
 * @ param off the start offset in the data
 * @ param len the number of bytes to encode
 * @ throws IOException if an I / O error occurs . In particular ,
 * an < code > IOException < / code > may be thrown if the
 * output stream has been closed . */
public void encode ( OutputStream out , byte [ ] data , int off , int len ) throws IOException { } }

implementation:
if ( out == null ) { throw new NullPointerException ( "out" ) ; } else if ( data == null ) { throw new NullPointerException ( "data" ) ; } else if ( off < 0 || len < 0 || ( off + len ) < 0 || off > data . length || ( off + len ) > data . length ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } long current = 0 ; int n = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int b = data [ off + i ] & 0xFF ; int code = codes [ b ] ; int nbits = lengths [ b ] ; current <<= nbits ; current |= code ; n += nbits ; while ( n >= 8 ) { n -= 8 ; out . write ( ( ( int ) ( current >> n ) ) ) ; } } if ( n > 0 ) { current <<= ( 8 - n ) ; current |= ( 0xFF >>> n ) ; // this should be EOS symbol
out . write ( ( int ) current ) ; }