@Override
   public void visit(Class<?> clazz)
   {

      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();

         }
      }

   }

Processes the annotation on the supplied class.

Processes the annotation on the supplied class .


private String prependContextPath(ExternalContext externalContext, String url)
   {
      String contextPath = externalContext.getRequestContextPath();
      if ("/".equals(contextPath) || (url.startsWith(contextPath))) {
         return url;
      }
      return contextPath + url;
   }

private String prependContextPath ( ExternalContext externalContext , String url ) { String contextPath = externalContext . getRequestContextPath ( ) ; if ( "/" . equals ( contextPath ) || ( url . startsWith ( contextPath ) ) ) { return url ; } return contextPath + url ; }

Adds the context path to the given context-relative URL.

Adds the context path to the given context - relative URL .


private String stripContextPath(final String contextPath, String uri)
   {
      if (!contextPath.equals("/") && uri.startsWith(contextPath))
      {
         uri = uri.substring(contextPath.length());
      }
      return uri;
   }

private String stripContextPath ( final String contextPath , String uri ) { if ( ! contextPath . equals ( "/" ) && uri . startsWith ( contextPath ) ) { uri = uri . substring ( contextPath . length ( ) ) ; } return uri ; }

If the given URL is prefixed with this request's context-path, return the URI without the context path. Otherwise
return the URI unchanged.

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 translate(String lang, String value)
   {
      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;
   }

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.

Translate a value into the matching one from a resource bundle in specified language .


public String buildDynaViewId(final String facesServletMapping)
   {
      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();
   }

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.

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 void processDynaView(final PrettyContext prettyContext, final FacesContext facesContext)
   {
      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);
      }
   }

public
void
processDynaView
(
final
PrettyContext
prettyContext
,
final
FacesContext
facesContext
)
{
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
)
;
}
}

Handle DynaView processing. This method will end the Faces life-cycle.

Handle DynaView processing . This method will end the Faces life - cycle .


private Type getRequiredType(Class<?> clazz)
   {

      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;
   }

private Type getRequiredType ( Class < ? > clazz ) { 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 ; }

Builds the correct "required type" including actual type arguments in case of parameterized types.

@see https://github.com/ocpsoft/rewrite/issues/137

Builds the correct required type including actual type arguments in case of parameterized types .


@SuppressWarnings("unchecked")
    public static <T extends Annotation> T getAnnotationProxy(Annotation customAnnotation, Class<T> referenceAnnotation) {
        InvocationHandler handler = new AnnotationInvocationHandler(customAnnotation);
        return (T)Proxy.newProxyInstance(referenceAnnotation.getClassLoader(), new Class[] { referenceAnnotation }, handler);
    }

@ SuppressWarnings ( "unchecked" ) public static < T extends Annotation > T getAnnotationProxy ( Annotation customAnnotation , Class < T > referenceAnnotation ) { InvocationHandler handler = new AnnotationInvocationHandler ( customAnnotation ) ; return ( T ) Proxy . newProxyInstance ( referenceAnnotation . getClassLoader ( ) , new Class [ ] { referenceAnnotation } , handler ) ; }

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

Returns a proxy on the customAnnotation having the same type than the referenceAnnotation


private Collection<Field> getFilteredFields(Class<?> refClass) {
        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;
        }
    }

Returns the filtered fields for a particular type

@param refClass the type
@return A collection of fields to be visited


private static Collection<Field> getAllFields(Class<?> refClass) {
        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;
    }

Returns all non-primitive fields for the entire class hierarchy of a type

@param refClass the type
@return all fields for that type

Returns all non - primitive fields for the entire class hierarchy of a type


public V put(K key, V value) {
        cleanUp();
        return map.put(new IdentityWeakReference<>(key, queue), value);
    }

public V put ( K key , V value ) { cleanUp ( ) ; return map . put ( new IdentityWeakReference <> ( key , queue ) , value ) ; }

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 remove(K key) {
        cleanUp();
        return map.remove(new IdentityWeakReference<>(key, queue));
    }

public V remove ( K key ) { cleanUp ( ) ; return map . remove ( new IdentityWeakReference <> ( key , queue ) ) ; }

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>.


static boolean loadAgent() {
        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;
        }
    }

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 agentIsAvailable() {
        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;
        }
    }

Checks whether the agent is available

@return true if available


public static void copyFile( PlexusIoResource in, File outFile )
        throws IOException
    {
        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 );
        }
    }

public static void copyFile ( PlexusIoResource in , File outFile ) throws IOException { 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 ) ; } }

Copies the sources contents to the given destination file.

Copies the sources contents to the given destination file .


public static boolean isSame( PlexusIoResource resource, File file )
    {
        if ( resource instanceof FileSupplier )
        {
            File resourceFile = ((FileSupplier) resource).getFile();
            return file.equals( resourceFile );
        }
        return false;
    }

public static boolean isSame ( PlexusIoResource resource , File file ) { if ( resource instanceof FileSupplier ) { File resourceFile = ( ( FileSupplier ) resource ) . getFile ( ) ; return file . equals ( resourceFile ) ; } return false ; }

Checks, whether the resource and the file are identical.

Checks whether the resource and the file are identical .


public void addWebinf( File directoryName, String[] includes, String[] excludes )
        throws ArchiverException
    {
        addDirectory( directoryName, "WEB-INF/", includes, excludes );
    }

public void addWebinf ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { addDirectory ( directoryName , "WEB-INF/" , includes , excludes ) ; }


protected void initZipOutputStream( ZipArchiveOutputStream zOut )
        throws ArchiverException, IOException
    {
        // 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 );
    }

override of  parent; validates configuration
before initializing the output stream.

override of parent ; validates configuration before initializing the output stream .


protected void zipFile( ArchiveEntry entry, ZipArchiveOutputStream zOut, String vPath )
        throws IOException, ArchiverException
    {
        // 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 );
        }
    }

Overridden from ZipArchiver class to deal with web.xml

Overridden from ZipArchiver class to deal with web . xml


public static Manifest getDefaultManifest()
        throws ArchiverException
    {
        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 );
        }
    }

Construct a manifest from Ant's default manifest file.

@return the default manifest.
@throws ArchiverException if there is a problem loading the
default manifest

Construct a manifest from Ant s default manifest file .


public void addConfiguredSection( Section section )
        throws ManifestException
    {
        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() );
        }
    }

public
void
addConfiguredSection
(
Section
section
)
throws
ManifestException
{
String
sectionName
=
section
.
getName
(
)
;
if
(
sectionName
==
)
{
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
(
)
)
;
}
}

Add a section to the manifest

@param section the manifest section to be added
@throws ManifestException if the secti0on is not valid.


public void write( PrintWriter writer )
        throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        super.write( byteArrayOutputStream );
        for ( byte b : byteArrayOutputStream.toByteArray() )
        {
            writer.write( (char) b );
        }
    }

public void write ( PrintWriter writer ) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; super . write ( byteArrayOutputStream ) ; for ( byte b : byteArrayOutputStream . toByteArray ( ) ) { writer . write ( ( char ) b ) ; } }

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

Write the manifest out to a print writer .


Enumeration<String> getWarnings()
    {
        Vector<String> warnings = new Vector<String>();

        Enumeration<String> warnEnum = mainSection.getWarnings();
        while ( warnEnum.hasMoreElements() )
        {
            warnings.addElement( warnEnum.nextElement() );
        }

        return warnings.elements();
    }

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

Get the warnings for this manifest.

@return an enumeration of warning strings


public ExistingSection getSection( String name )
    {
        Attributes attributes = getAttributes( name );
        if ( attributes != null )
        {
            return new ExistingSection( attributes, name );
        }
        return null;
    }

public ExistingSection getSection ( String name ) { Attributes attributes = getAttributes ( name ) ; if ( attributes != null ) { return new ExistingSection ( attributes , name ) ; } return null ; }

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


protected void copyFile( final ArchiveEntry entry, final String vPath )
        throws ArchiverException, IOException
    {
        // 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 );
    }

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

Copies the specified file to the specified path creating any ancestor directory structure as necessary .


public void addConfiguredManifest( Manifest newManifest )
        throws ManifestException
    {
        if ( configuredManifest == null )
        {
            configuredManifest = newManifest;
        }
        else
        {
            JdkManifestFactory.merge( configuredManifest, newManifest, false );
        }
        savedConfiguredManifest = configuredManifest;
    }

public void addConfiguredManifest ( Manifest newManifest ) throws ManifestException { if ( configuredManifest == null ) { configuredManifest = newManifest ; } else { JdkManifestFactory . merge ( configuredManifest , newManifest , false ) ; } savedConfiguredManifest = configuredManifest ; }

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 .

Allows the manifest for the archive file to be provided inline in the build file rather than in an external file .


protected void zipFile( InputStream is, ZipArchiveOutputStream zOut, String vPath, long lastModified, File fromArchive,
                            int mode, String symlinkDestination )
        throws IOException, ArchiverException
    {
        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 );
        }
    }

Overridden from Zip class to deal with manifests and index lists.

Overridden from Zip class to deal with manifests and index lists .


protected void cleanUp()
        throws IOException
    {
        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();
    }

Make sure we don't think we already have a MANIFEST next time this task
gets executed.

@see ZipArchiver#cleanUp

Make sure we don t think we already have a MANIFEST next time this task gets executed .


public void reset()
    {
        super.reset();
        configuredManifest = null;
        filesetManifestConfig = null;
        mergeManifestsMain = false;
        manifestFile = null;
        index = false;
    }

public void reset ( ) { super . reset ( ) ; configuredManifest = null ; filesetManifestConfig = null ; mergeManifestsMain = false ; manifestFile = null ; index = false ; }

reset to default values.

@see ZipArchiver#reset


protected final void writeIndexLikeList( List<String> dirs, List<String> files, PrintWriter writer )
    {
        // 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() );
        }
    }

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 ;)

Writes the directory entries from the first and the filenames from the second list to the given writer one entry per line .


protected static void grabFilesAndDirs( String file, List<String> dirs, List<String> files )
        throws IOException
    {
        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();
                }
            }
        }
    }

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 .

Grab lists of all root - level files and all directories contained in the given archive .


private InputStream decompress( UntarCompressionMethod compression, final File file, final InputStream istream )
			throws IOException, ArchiverException
	{
		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;
	}

private InputStream decompress ( UntarCompressionMethod compression , final File file , final InputStream istream ) throws IOException , ArchiverException { 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 ; }

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


public void compress()
        throws ArchiverException
    {
        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 );
        }
    }

public
void
compress
(
)
throws
ArchiverException
{
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
)
;
}
}

perform the GZip compression operation .


public static void mergeAttributes( java.util.jar.Attributes target, java.util.jar.Attributes section )
    {
        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 );
        }
    }

public
static
void
mergeAttributes
(
java
.
util
.
jar
.
Attributes
target
,
java
.
util
.
jar
.
Attributes
section
)
{
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
)
;
}
}

Merge in another section

@param target The target manifest of the merge
@param section the section to be merged with this one.


public void setAppxml( File descr )
        throws ArchiverException
    {
        deploymentDescriptor = descr;
        if ( !deploymentDescriptor.exists() )
        {
            throw new ArchiverException( "Deployment descriptor: " + deploymentDescriptor + " does not exist." );
        }

        addFile( descr, "META-INF/application.xml" );
    }

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

File to incorporate as application . xml .


public void addArchive( File fileName )
        throws ArchiverException
    {
        addDirectory( fileName.getParentFile(), "/", new String[]{fileName.getName()}, null );
    }

public void addArchive ( File fileName ) throws ArchiverException { addDirectory ( fileName . getParentFile ( ) , "/" , new String [ ] { fileName . getName ( ) } , null ) ; }


public void addArchives( File directoryName, String[] includes, String[] excludes )
        throws ArchiverException
    {
        addDirectory( directoryName, "/", includes, excludes );
    }

public void addArchives ( File directoryName , String [ ] includes , String [ ] excludes ) throws ArchiverException { addDirectory ( directoryName , "/" , includes , excludes ) ; }


public void compress()
        throws ArchiverException
    {
        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 );
        }
    }

public
void
compress
(
)
throws
ArchiverException
{
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
)
;
}
}

perform the Snappy compression operation.

perform the Snappy compression operation .


@SuppressWarnings({"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() );
            }
        }
    }

@ SuppressWarnings ( { "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 ( ) ) ; } } }

Add the given resources.

@param resources the resources to add
@param zOut      the stream to write to


@SuppressWarnings({"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() );
            }
        }
    }

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.

Ensure all parent dirs of a given entry have been added .


@SuppressWarnings({"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();
        }
    }

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

Adds a new entry to the archive takes care of duplicates as well .


@SuppressWarnings({"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; // P
            empty[1] = 75; // K
            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;
    }

Create an empty zip file

@param zipFile The file
@return true for historic reasons


public void reset()
    {
        setDestFile( null );
//        duplicate = "add";
        archiveType = "zip";
        doCompress = true;
        doUpdate = false;
        doFilesonly = false;
        encoding = null;
    }

public
void
reset
(
)
{
setDestFile
(
)
;
//        duplicate = "add";
archiveType
=
"zip"
;
doCompress
=
true
;
doUpdate
=
false
;
doFilesonly
=
false
;
encoding
=
;
}

Makes this instance reset all attributes to their default
values and forget all children.

@see #cleanUp

Makes this instance reset all attributes to their default values and forget all children .


private void compressFile( InputStream in, OutputStream zOut )
        throws IOException
    {
        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 );
    }

private void compressFile ( InputStream in , OutputStream zOut ) throws IOException { 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 ) ; }

compress a stream to an output stream

@param in
@param zOut
@throws IOException


protected void compress( PlexusIoResource resource, OutputStream zOut )
        throws IOException
    {
        InputStream in = Streams.bufferedInputStream( resource.getContents() );
        try
        {
            compressFile( in, zOut );
        }
        finally
        {
            IOUtil.close( in );
        }
    }

protected void compress ( PlexusIoResource resource , OutputStream zOut ) throws IOException { InputStream in = Streams . bufferedInputStream ( resource . getContents ( ) ) ; try { compressFile ( in , zOut ) ; } finally { IOUtil . close ( in ) ; } }


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

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.

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 .


private static int decodeULE128(InputStream in) throws IOException {
    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;
  }

Unsigned Little Endian Base 128 Variable-Length Integer Encoding

Unsigned Little Endian Base 128 Variable - Length Integer Encoding


static int getIndex(byte[] name) {
    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;
  }

static int getIndex ( byte [ ] name ) { 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 ; }

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.

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, byte[] value) {
    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;
  }

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.

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 .


private static Map<String, Integer> createMap() {
    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;
  }

create a map of header name to index value to allow quick lookup


public int getEncodedLength(byte[] data) {
    if (data == null) {
      throw new NullPointerException("data");
    }
    long len = 0;
    for (byte b : data) {
      len += lengths[b & 0xFF];
    }
    return (int)((len + 7) >> 3);
  }

public int getEncodedLength ( byte [ ] data ) { if ( data == null ) { throw new NullPointerException ( "data" ) ; } long len = 0 ; for ( byte b : data ) { len += lengths [ b & 0xFF ] ; } return ( int ) ( ( len + 7 ) >> 3 ) ; }

Returns the number of bytes required to Huffman encode the input string literal.
@param  data the string literal to be Huffman encoded
@return the number of bytes required to Huffman encode data

Returns the number of bytes required to Huffman encode the input string literal .


public int length() {
    int length;
    if (head < tail) {
      length = headerFields.length - tail + head;
    } else {
      length = head - tail;
    }
    return length;
  }

public int length ( ) { int length ; if ( head < tail ) { length = headerFields . length - tail + head ; } else { length = head - tail ; } return length ; }

Return the number of header fields in the dynamic table.

Return the number of header fields in the dynamic table .


public void add(HeaderField header) {
    int headerSize = header.size();
    if (headerSize > capacity) {
      clear();
      return;
    }
    while (size + headerSize > capacity) {
      remove();
    }
    headerFields[head++] = header;
    size += header.size();
    if (head == headerFields.length) {
      head = 0;
    }
  }

public void add ( HeaderField header ) { int headerSize = header . size ( ) ; if ( headerSize > capacity ) { clear ( ) ; return ; } while ( size + headerSize > capacity ) { remove ( ) ; } headerFields [ head ++ ] = header ; size += header . size ( ) ; if ( head == headerFields . length ) { head = 0 ; } }

Add the header field to the dynamic table.
Entries are evicted from the dynamic table until the size of the table
and the new header field is less than or equal to the table's capacity.
If the size of the new entry is larger than the table's capacity,
the dynamic table will be cleared.

Add the header field to the dynamic table . Entries are evicted from the dynamic table until the size of the table and the new header field is less than or equal to the table s capacity . If the size of the new entry is larger than the table s capacity the dynamic table will be cleared .


public void setCapacity(int capacity) {
    if (capacity < 0) {
      throw new IllegalArgumentException("Illegal Capacity: "+ capacity);
    }

    // initially capacity will be -1 so init won't return here
    if (this.capacity == capacity) {
      return;
    }
    this.capacity = capacity;

    if (capacity == 0) {
      clear();
    } else {
      // initially size will be 0 so remove won't be called
      while (size > capacity) {
        remove();
      }
    }

    int maxEntries = capacity / HEADER_ENTRY_OVERHEAD;
    if (capacity % HEADER_ENTRY_OVERHEAD != 0) {
      maxEntries++;
    }

    // check if capacity change requires us to reallocate the array
    if (headerFields != null && headerFields.length == maxEntries) {
      return;
    }

    HeaderField[] tmp = new HeaderField[maxEntries];

    // initially length will be 0 so there will be no copy
    int len = length();
    int cursor = tail;
    for (int i = 0; i < len; i++) {
      HeaderField entry = headerFields[cursor++];
      tmp[i] = entry;
      if (cursor == headerFields.length) {
        cursor = 0;
      }
    }

    this.tail = 0;
    this.head = tail + len;
    this.headerFields = tmp;
  }

Set the maximum size of the dynamic table.
Entries are evicted from the dynamic table until the size of the table
is less than or equal to the maximum size.

Set the maximum size of the dynamic table . Entries are evicted from the dynamic table until the size of the table is less than or equal to the maximum size .


public void encodeHeader(OutputStream out, byte[] name, byte[] value, boolean sensitive) throws IOException {

    // If the header value is sensitive then it must never be indexed
    if (sensitive) {
      int nameIndex = getNameIndex(name);
      encodeLiteral(out, name, value, IndexType.NEVER, nameIndex);
      return;
    }

    // If the peer will only use the static table
    if (capacity == 0) {
      int staticTableIndex = StaticTable.getIndex(name, value);
      if (staticTableIndex == -1) {
        int nameIndex = StaticTable.getIndex(name);
        encodeLiteral(out, name, value, IndexType.NONE, nameIndex);
      } else {
        encodeInteger(out, 0x80, 7, staticTableIndex);
      }
      return;
    }

    int headerSize = HeaderField.sizeOf(name, value);

    // If the headerSize is greater than the max table size then it must be encoded literally
    if (headerSize > capacity) {
      int nameIndex = getNameIndex(name);
      encodeLiteral(out, name, value, IndexType.NONE, nameIndex);
      return;
    }

    HeaderEntry headerField = getEntry(name, value);
    if (headerField != null) {
      int index = getIndex(headerField.index) + StaticTable.length;
      // Section 6.1. Indexed Header Field Representation
      encodeInteger(out, 0x80, 7, index);
    } else {
      int staticTableIndex = StaticTable.getIndex(name, value);
      if (staticTableIndex != -1) {
        // Section 6.1. Indexed Header Field Representation
        encodeInteger(out, 0x80, 7, staticTableIndex);
      } else {
        int nameIndex = getNameIndex(name);
        if (useIndexing) {
          ensureCapacity(headerSize);
        }
        IndexType indexType = useIndexing ? IndexType.INCREMENTAL : IndexType.NONE;
        encodeLiteral(out, name, value, indexType, nameIndex);
        if (useIndexing) {
          add(name, value);
        }
      }
    }
  }

Encode the header field into the header block.

Encode the header field into the header block .


public void setMaxHeaderTableSize(OutputStream out, int maxHeaderTableSize) throws IOException {
    if (maxHeaderTableSize < 0) {
      throw new IllegalArgumentException("Illegal Capacity: " + maxHeaderTableSize);
    }
    if (capacity == maxHeaderTableSize) {
      return;
    }
    capacity = maxHeaderTableSize;
    ensureCapacity(0);
    encodeInteger(out, 0x20, 5, maxHeaderTableSize);
  }

public
void
setMaxHeaderTableSize
(
OutputStream
out
,
int
maxHeaderTableSize
)
throws
IOException
{
if
(
maxHeaderTableSize
<
0
)
{
throw
new
IllegalArgumentException
(
"Illegal Capacity: "
+
maxHeaderTableSize
)
;
}
if
(
capacity
==
maxHeaderTableSize
)
{
return
;
}
capacity
=
maxHeaderTableSize
;
ensureCapacity
(
0
)
;
encodeInteger
(
out
,
0x20
,
5
,
maxHeaderTableSize
)
;
}


private static void encodeInteger(OutputStream out, int mask, int n, int i) throws IOException {
    if (n < 0 || n > 8) {
      throw new IllegalArgumentException("N: " + n);
    }
    int nbits = 0xFF >>> (8 - n);
    if (i < nbits) {
      out.write(mask | i);
    } else {
      out.write(mask | nbits);
      int length = i - nbits;
      while (true) {
        if ((length & ~0x7F) == 0) {
          out.write(length);
          return;
        } else {
          out.write((length & 0x7F) | 0x80);
          length >>>= 7;
        }
      }
    }
  }

private
static
void
encodeInteger
(
OutputStream
out
,
int
mask
,
int
n
,
int
i
)
throws
IOException
{
if
(
n
<
0
||
n
>
8
)
{
throw
new
IllegalArgumentException
(
"N: "
+
n
)
;
}
int
nbits
=
0xFF
>>>
(
8
n
)
;
if
(
i
<
nbits
)
{
out
.
write
(
mask
|
i
)
;
}
else
{
out
.
write
(
mask
|
nbits
)
;
int
length
=
i
nbits
;
while
(
true
)
{
if
(
(
length
&
~
0x7F
)
==
0
)
{
out
.
write
(
length
)
;
return
;
}
else
{
out
.
write
(
(
length
&
0x7F
)
|
0x80
)
;
length
>>>=
7
;
}
}
}
}

Encode integer according to Section 5.1.

Encode integer according to Section 5 . 1 .


private void encodeStringLiteral(OutputStream out, byte[] string) throws IOException {
    int huffmanLength = Huffman.ENCODER.getEncodedLength(string);
    if ((huffmanLength < string.length && !forceHuffmanOff) || forceHuffmanOn) {
      encodeInteger(out, 0x80, 7, huffmanLength);
      Huffman.ENCODER.encode(out, string);
    } else {
      encodeInteger(out, 0x00, 7, string.length);
      out.write(string, 0, string.length);
    }
  }

private void encodeStringLiteral ( OutputStream out , byte [ ] string ) throws IOException { int huffmanLength = Huffman . ENCODER . getEncodedLength ( string ) ; if ( ( huffmanLength < string . length && ! forceHuffmanOff ) || forceHuffmanOn ) { encodeInteger ( out , 0x80 , 7 , huffmanLength ) ; Huffman . ENCODER . encode ( out , string ) ; } else { encodeInteger ( out , 0x00 , 7 , string . length ) ; out . write ( string , 0 , string . length ) ; } }

Encode string literal according to Section 5.2.

Encode string literal according to Section 5 . 2 .


private void encodeLiteral(OutputStream out, byte[] name, byte[] value, IndexType indexType, int nameIndex)
      throws IOException {
    int mask;
    int prefixBits;
    switch(indexType) {
    case INCREMENTAL:
      mask = 0x40;
      prefixBits = 6;
      break;
    case NONE:
      mask = 0x00;
      prefixBits = 4;
      break;
    case NEVER:
      mask = 0x10;
      prefixBits = 4;
      break;
    default:
      throw new IllegalStateException("should not reach here");
    }
    encodeInteger(out, mask, prefixBits, nameIndex == -1 ? 0 : nameIndex);
    if (nameIndex == -1) {
      encodeStringLiteral(out, name);
    }
    encodeStringLiteral(out, value);
  }

private
void
encodeLiteral
(
OutputStream
out
,
byte
[
]
name
,
byte
[
]
value
,
IndexType
indexType
,
int
nameIndex
)
throws
IOException
{
int
mask
;
int
prefixBits
;
switch
(
indexType
)
{
case
INCREMENTAL
:
mask
=
0x40
;
prefixBits
=
6
;
break
;
case
:
mask
=
0x00
;
prefixBits
=
4
;
break
;
case
NEVER
:
mask
=
0x10
;
prefixBits
=
4
;
break
;
default
:
throw
new
IllegalStateException
(
"should not reach here"
)
;
}
encodeInteger
(
out
,
mask
,
prefixBits
,
nameIndex
==
1
0
:
nameIndex
)
;
if
(
nameIndex
==
1
)
{
encodeStringLiteral
(
out
,
name
)
;
}
encodeStringLiteral
(
out
,
value
)
;
}

Encode literal header field according to Section 6.2.

Encode literal header field according to Section 6 . 2 .


private void ensureCapacity(int headerSize) throws IOException {
    while (size + headerSize > capacity) {
      int index = length();
      if (index == 0) {
        break;
      }
      remove();
    }
  }

private void ensureCapacity ( int headerSize ) throws IOException { while ( size + headerSize > capacity ) { int index = length ( ) ; if ( index == 0 ) { break ; } remove ( ) ; } }

Ensure that the dynamic table has enough room to hold 'headerSize' more bytes.
Removes the oldest entry from the dynamic table until sufficient space is available.

Ensure that the dynamic table has enough room to hold headerSize more bytes . Removes the oldest entry from the dynamic table until sufficient space is available .


HeaderField getHeaderField(int index) {
    HeaderEntry entry = head;
    while(index-- >= 0) {
      entry = entry.before;
    }
    return entry;
  }

HeaderField getHeaderField ( int index ) { HeaderEntry entry = head ; while ( index -- >= 0 ) { entry = entry . before ; } return entry ; }

Return the header field at the given index.
Exposed for testing.

Return the header field at the given index . Exposed for testing .


private HeaderEntry getEntry(byte[] name, byte[] value) {
    if (length() == 0 || name == null || value == null) {
      return null;
    }
    int h = hash(name);
    int i = index(h);
    for (HeaderEntry e = headerFields[i]; e != null; e = e.next) {
      if (e.hash == h &&
          HpackUtil.equals(name, e.name) &&
          HpackUtil.equals(value, e.value)) {
        return e;
      }
    }
    return null;
  }

private HeaderEntry getEntry ( byte [ ] name , byte [ ] value ) { if ( length ( ) == 0 || name == null || value == null ) { return null ; } int h = hash ( name ) ; int i = index ( h ) ; for ( HeaderEntry e = headerFields [ i ] ; e != null ; e = e . next ) { if ( e . hash == h && HpackUtil . equals ( name , e . name ) && HpackUtil . equals ( value , e . value ) ) { return e ; } } return null ; }

Returns the header entry with the lowest index value for the header field.
Returns null if header field is not in the dynamic table.

Returns the header entry with the lowest index value for the header field . Returns null if header field is not in the dynamic table .


private int getIndex(byte[] name) {
    if (length() == 0 || name == null) {
      return -1;
    }
    int h = hash(name);
    int i = index(h);
    int index = -1;
    for (HeaderEntry e = headerFields[i]; e != null; e = e.next) {
      if (e.hash == h && HpackUtil.equals(name, e.name)) {
        index = e.index;
        break;
      }
    }
    return getIndex(index);
  }

private int getIndex ( byte [ ] name ) { if ( length ( ) == 0 || name == null ) { return - 1 ; } int h = hash ( name ) ; int i = index ( h ) ; int index = - 1 ; for ( HeaderEntry e = headerFields [ i ] ; e != null ; e = e . next ) { if ( e . hash == h && HpackUtil . equals ( name , e . name ) ) { index = e . index ; break ; } } return getIndex ( index ) ; }

Returns the lowest index value for the header field name in the dynamic table.
Returns -1 if the header field name is not in the dynamic table.

Returns the lowest index value for the header field name in the dynamic table . Returns - 1 if the header field name is not in the dynamic table .


private void add(byte[] name, byte[] value) {
    int headerSize = HeaderField.sizeOf(name, value);

    // Clear the table if the header field size is larger than the capacity.
    if (headerSize > capacity) {
      clear();
      return;
    }

    // Evict oldest entries until we have enough capacity.
    while (size + headerSize > capacity) {
      remove();
    }

    // Copy name and value that modifications of original do not affect the dynamic table.
    name = Arrays.copyOf(name, name.length);
    value = Arrays.copyOf(value, value.length);

    int h = hash(name);
    int i = index(h);
    HeaderEntry old = headerFields[i];
    HeaderEntry e = new HeaderEntry(h, name, value, head.before.index - 1, old);
    headerFields[i] = e;
    e.addBefore(head);
    size += headerSize;
  }

Add the header field to the dynamic table.
Entries are evicted from the dynamic table until the size of the table
and the new header field is less than the table's capacity.
If the size of the new entry is larger than the table's capacity,
the dynamic table will be cleared.

Add the header field to the dynamic table . Entries are evicted from the dynamic table until the size of the table and the new header field is less than the table s capacity . If the size of the new entry is larger than the table s capacity the dynamic table will be cleared .


private static int hash(byte[] name) {
    int h = 0;
    for (int i = 0; i < name.length; i++) {
      h = 31 * h + name[i];
    }
    if (h > 0) {
      return h;
    } else if (h == Integer.MIN_VALUE) {
      return Integer.MAX_VALUE;
    } else {
      return -h;
    }
  }

private static int hash ( byte [ ] name ) { int h = 0 ; for ( int i = 0 ; i < name . length ; i ++ ) { h = 31 * h + name [ i ] ; } if ( h > 0 ) { return h ; } else if ( h == Integer . MIN_VALUE ) { return Integer . MAX_VALUE ; } else { return - h ; } }

Returns the hash code for the given header field name.

Returns the hash code for the given header field name .


public byte[] decode(byte[] buf) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Node node = root;
    int current = 0;
    int bits = 0;
    for (int i = 0; i < buf.length; i++) {
      int b = buf[i] & 0xFF;
      current = (current << 8) | b;
      bits += 8;
      while (bits >= 8) {
        int c = (current >>> (bits - 8)) & 0xFF;
        node = node.children[c];
        bits -= node.bits;
        if (node.isTerminal()) {
          if (node.symbol == HpackUtil.HUFFMAN_EOS) {
            throw EOS_DECODED;
          }
          baos.write(node.symbol);
          node = root;
        }
      }
    }

    while (bits > 0) {
      int c = (current << (8 - bits)) & 0xFF;
      node = node.children[c];
      if (node.isTerminal() && node.bits <= bits) {
        bits -= node.bits;
        baos.write(node.symbol);
        node = root;
      } else {
        break;
      }
    }

    // Section 5.2. String Literal Representation
    // Padding not corresponding to the most significant bits of the code
    // for the EOS symbol (0xFF) MUST be treated as a decoding error.
    int mask = (1 << bits) - 1;
    if ((current & mask) != mask) {
      throw INVALID_PADDING;
    }

    return baos.toByteArray();
  }

Decompresses the given Huffman coded string literal.
@param  buf the string literal to be decoded
@return the output stream for the compressed data
@throws IOException if an I/O error occurs. In particular,
an IOException may be thrown if the
output stream has been closed.

Decompresses the given Huffman coded string literal .


public void setDefaultScriptNames(String scriptNames) {
		if (!scriptNames.trim().isEmpty())
			service.setDefaultScripts(asList(scriptNames.split(",")));
	}

public void setDefaultScriptNames ( String scriptNames ) { if ( ! scriptNames . trim ( ) . isEmpty ( ) ) service . setDefaultScripts ( asList ( scriptNames . split ( "," ) ) ) ; }

Set the comma delimited list of default scripts

@param scriptNames script names


public void assertEqualTo(Description description, Short actual, short expected) {
    assertNotNull(description, actual);
    if (!isEqualTo(actual, expected)) {
      throw failures.failure(description, shouldBeEqual(actual, expected));
    }
  }

public void assertEqualTo ( Description description , Short actual , short expected ) { assertNotNull ( description , actual ) ; if ( ! isEqualTo ( actual , expected ) ) { throw failures . failure ( description , shouldBeEqual ( actual , expected ) ) ; } }

Verifies that two shorts are equal.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.


public void assertNotEqualTo(Description description, Short actual, short expected) {
    assertNotNull(description, actual);
    if (isEqualTo(actual, expected)) {
      throw failures.failure(description, shouldNotBeEqual(actual, expected));
    }
  }

public void assertNotEqualTo ( Description description , Short actual , short expected ) { assertNotNull ( description , actual ) ; if ( isEqualTo ( actual , expected ) ) { throw failures . failure ( description , shouldNotBeEqual ( actual , expected ) ) ; } }

Verifies that two integers are not equal.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that two integers are not equal .


public void assertGreaterThan(Description description, Short actual, short expected) {
    assertNotNull(description, actual);
    if (!isGreaterThan(actual, expected)) {
      throw failures.failure(description, ShouldBeGreaterThan.shouldBeGreaterThan(actual, expected));
    }
  }

public void assertGreaterThan ( Description description , Short actual , short expected ) { assertNotNull ( description , actual ) ; if ( ! isGreaterThan ( actual , expected ) ) { throw failures . failure ( description , ShouldBeGreaterThan . shouldBeGreaterThan ( actual , expected ) ) ; } }

Verifies that the actual value is greater than the expected one.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that the actual value is greater than the expected one .


public void assertGreaterThan(Description description, Float actual, float expected) {
    assertNotNull(description, actual);
    if (!isGreaterThan(actual, expected)) {
      throw failures.failure(description, shouldBeGreaterThan(actual, expected));
    }
  }

public void assertGreaterThan ( Description description , Float actual , float expected ) { assertNotNull ( description , actual ) ; if ( ! isGreaterThan ( actual , expected ) ) { throw failures . failure ( description , shouldBeGreaterThan ( actual , expected ) ) ; } }

Verifies that the actual value is great than the expected one.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that the actual value is great than the expected one .


public void assertEqual(Description description, Character actual, char expected) {
    assertNotNull(description, actual);
    if (actual.charValue() != expected) {
      throw failures.failure(description, shouldBeEqual(actual, expected));
    }
  }

public void assertEqual ( Description description , Character actual , char expected ) { assertNotNull ( description , actual ) ; if ( actual . charValue ( ) != expected ) { throw failures . failure ( description , shouldBeEqual ( actual , expected ) ) ; } }

Asserts that two characters are equal.

@param description contains information about the assertion.
@param actual the actual value.
@param expected the expected value.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is not equal to the expected one. This method will throw a
{@code org.junit.ComparisonFailure} instead if JUnit is in the classpath and the expected and actual
values are not equal.


public void assertNotEqual(Description description, Character actual, char other) {
    assertNotNull(description, actual);
    if (actual.charValue() == other) {
      throw failures.failure(description, shouldNotBeEqual(actual, other));
    }
  }

public void assertNotEqual ( Description description , Character actual , char other ) { assertNotNull ( description , actual ) ; if ( actual . charValue ( ) == other ) { throw failures . failure ( description , shouldNotBeEqual ( actual , other ) ) ; } }

Asserts that two characters are not equal.

@param description contains information about the assertion.
@param actual the actual value.
@param other the value to compare the actual value to.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is equal to the other one.

Asserts that two characters are not equal .


public void assertLessThan(Description description, Character actual, char other) {
    assertNotNull(description, actual);
    if (!isLessThan(actual, other)) {
      throw failures.failure(description, shouldBeLessThan(actual, other));
    }
  }

public void assertLessThan ( Description description , Character actual , char other ) { assertNotNull ( description , actual ) ; if ( ! isLessThan ( actual , other ) ) { throw failures . failure ( description , shouldBeLessThan ( actual , other ) ) ; } }

Asserts that the actual value is less than the other one.

@param description contains information about the assertion.
@param actual the actual value.
@param other the value to compare the actual value to.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is not less than the other one: this assertion will fail if the actual
value is equal to or greater than the other value.

Asserts that the actual value is less than the other one .


public void assertNotGreaterThan(Description description, Character actual, char other) {
    assertNotNull(description, actual);
    if (isGreaterThan(actual, other)) {
      throw failures.failure(description, shouldNotBeGreaterThan(actual, other));
    }
  }

public void assertNotGreaterThan ( Description description , Character actual , char other ) { assertNotNull ( description , actual ) ; if ( isGreaterThan ( actual , other ) ) { throw failures . failure ( description , shouldNotBeGreaterThan ( actual , other ) ) ; } }

Asserts that the actual value is less than or equal to the other one.

@param description contains information about the assertion.
@param actual the actual value.
@param other the value to compare the actual value to.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is greater than the other one.

Asserts that the actual value is less than or equal to the other one .


public void assertGreaterThan(Description description, Character actual, char other) {
    assertNotNull(description, actual);
    if (!isGreaterThan(actual, other)) {
      throw failures.failure(description, shouldBeGreaterThan(actual, other));
    }
  }

public void assertGreaterThan ( Description description , Character actual , char other ) { assertNotNull ( description , actual ) ; if ( ! isGreaterThan ( actual , other ) ) { throw failures . failure ( description , shouldBeGreaterThan ( actual , other ) ) ; } }

Asserts that the actual value is greater than the other one.

@param description contains information about the assertion.
@param actual the actual value.
@param other the value to compare the actual value to.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is not greater than the other one: this assertion will fail if the
actual value is equal to or less than the other value.

Asserts that the actual value is greater than the other one .


public void assertNotLessThan(Description description, Character actual, char other) {
    assertNotNull(description, actual);
    if (isLessThan(actual, other)) {
      throw failures.failure(description, ShouldNotBeLessThan.shouldNotBeLessThan(actual, other));
    }
  }

public void assertNotLessThan ( Description description , Character actual , char other ) { assertNotNull ( description , actual ) ; if ( isLessThan ( actual , other ) ) { throw failures . failure ( description , ShouldNotBeLessThan . shouldNotBeLessThan ( actual , other ) ) ; } }

Asserts that the actual value is greater than or equal to the other one.

@param description contains information about the assertion.
@param actual the actual value.
@param other the value to compare the actual value to.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is less than the other one.

Asserts that the actual value is greater than or equal to the other one .


public void assertLowerCase(Description description, Character actual) {
    assertNotNull(description, actual);
    if (!isLowerCase(actual)) {
      throw failures.failure(description, shouldBeLowerCase(actual));
    }
  }

public void assertLowerCase ( Description description , Character actual ) { assertNotNull ( description , actual ) ; if ( ! isLowerCase ( actual ) ) { throw failures . failure ( description , shouldBeLowerCase ( actual ) ) ; } }

Asserts that the actual value is a lowercase character.

@param description contains information about the assertion.
@param actual the actual value.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is not a lowercase character.

Asserts that the actual value is a lowercase character .


public void assertUpperCase(Description description, Character actual) {
    assertNotNull(description, actual);
    if (!isUpperCase(actual)) {
      throw failures.failure(description, shouldBeUpperCase(actual));
    }
  }

public void assertUpperCase ( Description description , Character actual ) { assertNotNull ( description , actual ) ; if ( ! isUpperCase ( actual ) ) { throw failures . failure ( description , shouldBeUpperCase ( actual ) ) ; } }

Asserts that the actual value is a uppercase character.

@param description contains information about the assertion.
@param actual the actual value.
@throws AssertionError if the actual value is {@code null}.
@throws AssertionError if the actual value is not a uppercase character.

Asserts that the actual value is a uppercase character .


public void assertHasSize(Description description, int[] actual, int expectedSize) {
    arrays.assertHasSize(description, actual, expectedSize);
  }

public void assertHasSize ( Description description , int [ ] actual , int expectedSize ) { arrays . assertHasSize ( description , actual , expectedSize ) ; }

Asserts that the number of elements in the given array is equal to the expected one.

@param description contains information about the assertion.
@param actual the given array.
@param expectedSize the expected size of {@code actual}.
@throws AssertionError if the given array is {@code null}.
@throws AssertionError if the number of elements in the given array is different than the expected one.

Asserts that the number of elements in the given array is equal to the expected one .


public void assertContains(Description description, int[] actual, int[] values) {
    arrays.assertContains(description, actual, values);
  }

public void assertContains ( Description description , int [ ] actual , int [ ] values ) { arrays . assertContains ( description , actual , values ) ; }

Asserts that the given array contains the given values, in any order.

@param description contains information about the assertion.
@param actual the given array.
@param values the values that are expected to be in the given array.
@throws NullPointerException if the array of values is {@code null}.
@throws IllegalArgumentException if the array of values is empty.
@throws AssertionError if the given array is {@code null}.
@throws AssertionError if the given array does not contain the given values.

Asserts that the given array contains the given values in any order .


public <K> void assertContainsKey(Description description, Map<?, ?> actual, K key) {
    assertNotNull(description, actual);
    if (!actual.containsKey(key)) {
      throw failures.failure(description, shouldContainKey(actual, key));
    }
  }

public < K > void assertContainsKey ( Description description , Map < ? , ? > actual , K key ) { assertNotNull ( description , actual ) ; if ( ! actual . containsKey ( key ) ) { throw failures . failure ( description , shouldContainKey ( actual , key ) ) ; } }

Asserts that the actual map contain the given key.

@param description contains information about the assertion.
@param actual the given {@code Map}.
@param key the given key
@throws AssertionError if the actual map is {@code null}.
@throws AssertionError if the actual map not contains the given key.

Asserts that the actual map contain the given key .


public <K> void assertDoesNotContainKey(Description description, Map<?, ?> actual, K key) {
    assertNotNull(description, actual);
    if (actual.containsKey(key)) {
      throw failures.failure(description, shouldNotContainKey(actual, key));
    }
  }

public < K > void assertDoesNotContainKey ( Description description , Map < ? , ? > actual , K key ) { assertNotNull ( description , actual ) ; if ( actual . containsKey ( key ) ) { throw failures . failure ( description , shouldNotContainKey ( actual , key ) ) ; } }

Asserts that the actual map not contains the given key.

@param description contains information about the assertion.
@param actual the given {@code Map}.
@param key the given key
@throws AssertionError if the actual map is {@code null}.
@throws AssertionError if the actual map contains the given key.

Asserts that the actual map not contains the given key .


public <V> void assertContainsValue(Description description, Map<?, ?> actual, V value) {
    assertNotNull(description, actual);
    if (!actual.containsValue(value)) {
      throw failures.failure(description, shouldContainValue(actual, value));
    }
  }

public < V > void assertContainsValue ( Description description , Map < ? , ? > actual , V value ) { assertNotNull ( description , actual ) ; if ( ! actual . containsValue ( value ) ) { throw failures . failure ( description , shouldContainValue ( actual , value ) ) ; } }

Asserts that the actual map contain the given value.

@param description contains information about the assertion.
@param actual the given {@code Map}.
@param value the given value
@throws AssertionError if the actual map is {@code null}.
@throws AssertionError if the actual map not contains the given value.

Asserts that the actual map contain the given value .


public <V> void assertDoesNotContainValue(Description description, Map<?, ?> actual, V value) {
    assertNotNull(description, actual);
    if (actual.containsValue(value)) {
      throw failures.failure(description, shouldNotContainValue(actual, value));
    }
  }

public < V > void assertDoesNotContainValue ( Description description , Map < ? , ? > actual , V value ) { assertNotNull ( description , actual ) ; if ( actual . containsValue ( value ) ) { throw failures . failure ( description , shouldNotContainValue ( actual , value ) ) ; } }

Asserts that the actual map does not contain the given value.

@param description contains information about the assertion.
@param actual the given {@code Map}.
@param value the given value
@throws AssertionError if the actual map is {@code null}.
@throws AssertionError if the actual map contains the given value.

Asserts that the actual map does not contain the given value .


public <K, V> void assertDoesNotContainDuplicateValues(Description description, Map<K, V> actual) {
    assertNotNull(description, actual);
    Collection<?> duplicates = duplicatesFrom(actual.values());
    if (!duplicates.isEmpty()) {
      throw failures.failure(description, shouldNotHaveDuplicates(actual, duplicates));
    }
  }

public < K , V > void assertDoesNotContainDuplicateValues ( Description description , Map < K , V > actual ) { assertNotNull ( description , actual ) ; Collection < ? > duplicates = duplicatesFrom ( actual . values ( ) ) ; if ( ! duplicates . isEmpty ( ) ) { throw failures . failure ( description , shouldNotHaveDuplicates ( actual , duplicates ) ) ; } }

Asserts that the actual map does not contain the duplicate values.

@param description contains information about the assertion.
@param actual the given {@code Map}.
@throws AssertionError if the actual map is {@code null}.
@throws AssertionError if the actual map contains the given value.

Asserts that the actual map does not contain the duplicate values .


public void assertEqual(Description description, BigDecimal actual, BigDecimal expected) {
    checkNumberIsNotNull(expected);
    assertNotNull(description, actual);
    comparables.assertEqual(description, actual, expected);
  }

public void assertEqual ( Description description , BigDecimal actual , BigDecimal expected ) { checkNumberIsNotNull ( expected ) ; assertNotNull ( description , actual ) ; comparables . assertEqual ( description , actual , expected ) ; }

Verifies that two BigDecimals are equal.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that two BigDecimals are equal .


public void assertIsZero(Description description, BigDecimal actual) {
    comparables.assertEqual(description, actual, ZERO);
  }

public void assertIsZero ( Description description , BigDecimal actual ) { comparables . assertEqual ( description , actual , ZERO ) ; }

Verifies that the actual value is zero.

@param description the description of the actual value.
@param actual the actual value.

Verifies that the actual value is zero .


public void assertIsNotZero(Description description, BigDecimal actual) {
    comparables.assertNotEqual(description, actual, ZERO);
  }

public void assertIsNotZero ( Description description , BigDecimal actual ) { comparables . assertNotEqual ( description , actual , ZERO ) ; }

Verifies that the actual value is not zero.

@param description the description of the actual value.
@param actual the actual value.

Verifies that the actual value is not zero .


public void assertIsPositive(Description description, BigDecimal actual) {
    comparables.assertGreaterThan(description, actual, ZERO);
  }

public void assertIsPositive ( Description description , BigDecimal actual ) { comparables . assertGreaterThan ( description , actual , ZERO ) ; }

Verifies that the actual value is positive.

@param description the description of the actual value.
@param actual the actual value.

Verifies that the actual value is positive .


public void assertIsNegative(Description description, BigDecimal actual) {
    comparables.assertLessThan(description, actual, ZERO);
  }

public void assertIsNegative ( Description description , BigDecimal actual ) { comparables . assertLessThan ( description , actual , ZERO ) ; }

Verifies that the actual value is negative.

@param description the description of the actual value.
@param actual the actual value.

Verifies that the actual value is negative .


public FloatAssert isEqualTo(float expected, Offset<Float> offset) {
    floats.assertEqual(description, actual, expected, offset);
    return this;
  }

public FloatAssert isEqualTo ( float expected , Offset < Float > offset ) { floats . assertEqual ( description , actual , expected , offset ) ; return this ; }

Verifies that the actual value is equal to the given one, within a positive offset.

@param expected the given value to compare the actual value to.
@param offset   the given positive offset.
@return {@code this} assertion object.
@throws NullPointerException if the given offset is {@code null}.
@throws AssertionError       if the actual value is {@code null}.
@throws AssertionError       if the actual value is not equal to the given one.

Verifies that the actual value is equal to the given one within a positive offset .


public ByteArrayAssert contains(byte value, Index index) {
    arrays.assertContains(description, actual, value, index);
    return this;
  }

public ByteArrayAssert contains ( byte value , Index index ) { arrays . assertContains ( description , actual , value , index ) ; return this ; }

Verifies that the given array contains the given value at the given index.

@param value the value to look for.
@param index the index where the value should be stored in the given array.
@return {@code this} assertion object.
@throws AssertionError if the given array is {@code null} or empty.
@throws NullPointerException if the given {@code Index} is {@code null}.
@throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of
the given array.
@throws AssertionError if the given array does not contain the given value at the given index.

Verifies that the given array contains the given value at the given index .


public void assertNotEqual(Description description, Double actual, Double expected, Offset<Double> offset) {
    checkOffsetIsNotNull(offset);
    checkNumberIsNotNull(expected);
    assertNotNull(description, actual);
    if (isEqualTo(actual, expected, offset)) {
      throw failures.failure(description, shouldNotBeEqual(actual, expected));
    }
  }

public void assertNotEqual ( Description description , Double actual , Double expected , Offset < Double > offset ) { checkOffsetIsNotNull ( offset ) ; checkNumberIsNotNull ( expected ) ; assertNotNull ( description , actual ) ; if ( isEqualTo ( actual , expected , offset ) ) { throw failures . failure ( description , shouldNotBeEqual ( actual , expected ) ) ; } }

Verifies that two doubles are not equal.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.
@param offset the given positive offset.

Verifies that two doubles are not equal .


public void assertNotGreaterThan(Description description, Double actual, double expected) {
    assertNotNull(description, actual);
    if (isGreaterThan(actual, expected)) {
      throw failures.failure(description, shouldNotBeGreaterThan(actual, expected));
    }
  }

public void assertNotGreaterThan ( Description description , Double actual , double expected ) { assertNotNull ( description , actual ) ; if ( isGreaterThan ( actual , expected ) ) { throw failures . failure ( description , shouldNotBeGreaterThan ( actual , expected ) ) ; } }

Verifies that the actual value is not greater than the expected.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that the actual value is not greater than the expected .


public void assertLessThan(Description description, Double actual, double expected) {
    assertNotNull(description, actual);
    if (!isLessThan(actual, expected)) {
      throw failures.failure(description, shouldBeLessThan(actual, expected));
    }
  }

public void assertLessThan ( Description description , Double actual , double expected ) { assertNotNull ( description , actual ) ; if ( ! isLessThan ( actual , expected ) ) { throw failures . failure ( description , shouldBeLessThan ( actual , expected ) ) ; } }

Verifies that the actual value is less than the expected.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that the actual value is less than the expected .


public void assertNotLessThan(Description description, Double actual, double expected) {
    assertNotNull(description, actual);
    if (isLessThan(actual, expected)) {
      throw failures.failure(description, shouldNotBeLessThan(actual, expected));
    }
  }

public void assertNotLessThan ( Description description , Double actual , double expected ) { assertNotNull ( description , actual ) ; if ( isLessThan ( actual , expected ) ) { throw failures . failure ( description , shouldNotBeLessThan ( actual , expected ) ) ; } }

Verifies that the actual value is not less than the expected.

@param description the description of the actual value.
@param actual the actual value.
@param expected the expected value.

Verifies that the actual value is not less than the expected .


public void assertContainsOnly(Description description, byte[] actual, byte[] values) {
    arrays.assertContainsOnly(description, actual, values);
  }

public void assertContainsOnly ( Description description , byte [ ] actual , byte [ ] values ) { arrays . assertContainsOnly ( description , actual , values ) ; }

Asserts that the given array contains only the given values and nothing else, in any order.

@param description contains information about the assertion.
@param actual the given array.
@param values the values that are expected to be in the given array.
@throws NullPointerException if the array of values is {@code null}.
@throws IllegalArgumentException if the array of values is empty.
@throws AssertionError if the given array is {@code null}.
@throws AssertionError if the given array does not contain the given values or if the given array contains values
that are not in the given array.

Asserts that the given array contains only the given values and nothing else in any order .


public void assertContainsSequence(Description description, byte[] actual, byte[] sequence) {
    arrays.assertContainsSequence(description, actual, sequence);
  }

public void assertContainsSequence ( Description description , byte [ ] actual , byte [ ] sequence ) { arrays . assertContainsSequence ( description , actual , sequence ) ; }

Verifies that the given array contains the given sequence of values, without any other values between them.

@param description contains information about the assertion.
@param actual the given array.
@param sequence the sequence of values to look for.
@throws AssertionError if the given array is {@code null}.
@throws NullPointerException if the given sequence is {@code null}.
@throws IllegalArgumentException if the given sequence is empty.
@throws AssertionError if the given array does not contain the given sequence of values.

Verifies that the given array contains the given sequence of values without any other values between them .


public void assertEqual(Description description, Object actual, Object expected) {
    if (!areEqual(actual, expected)) {
      throw shouldBeEqual(actual, expected).newAssertionError(description);
    }
  }

public void assertEqual ( Description description , Object actual , Object expected ) { if ( ! areEqual ( actual , expected ) ) { throw shouldBeEqual ( actual , expected ) . newAssertionError ( description ) ; } }

Asserts that two objects are equal.

@param description the description of the actual object.
@param actual the actual object.
@param expected the expected object.
@throws AssertionError if {@code actual} is not equal to {@code expected}. This method will throw a
{@code org.junit.ComparisonFailure} instead if JUnit is in the classpath and the given objects are not
equal.


public void assertNotEqual(Description description, Object actual, Object other) {
    if (areEqual(actual, other)) {
      throw failures.failure(description, shouldNotBeEqual(actual, other));
    }
  }

public void assertNotEqual ( Description description , Object actual , Object other ) { if ( areEqual ( actual , other ) ) { throw failures . failure ( description , shouldNotBeEqual ( actual , other ) ) ; } }

Asserts that two objects are not equal.

@param description the description of the actual object.
@param actual the actual object.
@param other the object to compare {@code actual} to.
@throws AssertionError if {@code actual} is equal to {@code other}.

Asserts that two objects are not equal .