protected TreeNode convert(TreeNode parent, Node node) {

        // Construct a new TreeNode for this node
        TreeNode treeNode = new TreeNode(node.getNodeName(), parent);

        // Convert all attributes of this node
        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int n = attributes.getLength();
            for (int i = 0; i < n; i++) {
                Node attribute = attributes.item(i);
                treeNode.addAttribute(attribute.getNodeName(),
                                      attribute.getNodeValue());
            }
        }

        // Create and attach all children of this node
        NodeList children = node.getChildNodes();
        if (children != null) {
            int n = children.getLength();
            for (int i = 0; i < n; i++) {
                Node child = children.item(i);
                if (child instanceof Comment)
                    continue;
                if (child instanceof Text) {
                    String body = ((Text) child).getData();
                    if (body != null) {
                        body = body.trim();
                        if (body.length() > 0)
                            treeNode.setBody(body);
                    }
                } else {
                    TreeNode treeChild = convert(treeNode, child);
                }
            }
        }

        // Return the completed TreeNode graph
        return (treeNode);
    }

Create and return a TreeNode that corresponds to the specified Node,
including processing all of the attributes and children nodes.

@param parent The parent TreeNode (if any) for the new TreeNode
@param node The XML document Node to be converted

Create and return a TreeNode that corresponds to the specified Node including processing all of the attributes and children nodes .


private static void mergeErrors ( final BindingResult bindingResult, final BindingResult result )
    {
        if ( bindingResult == null )
        {
            return;
        }

        result.addErrors ( bindingResult.getLocalErrors () );

        for ( final Map.Entry<String, BindingResult> child : bindingResult.getChildren ().entrySet () )
        {
            mergeErrors ( child.getValue (), result.getChildOrAdd ( child.getKey () ) );
        }
    }

private static void mergeErrors ( final BindingResult bindingResult , final BindingResult result ) { if ( bindingResult == null ) { return ; } result . addErrors ( bindingResult . getLocalErrors ( ) ) ; for ( final Map . Entry < String , BindingResult > child : bindingResult . getChildren ( ) . entrySet ( ) ) { mergeErrors ( child . getValue ( ) , result . getChildOrAdd ( child . getKey ( ) ) ) ; } }

Merge all errors of this binding into this result

@param binding
the binding to merge
@param result
the result to merge into


private void initializeBinder ( final Binder binder )
    {
        for ( final Method m : binder.getClass ().getMethods () )
        {
            if ( !m.isAnnotationPresent ( Binder.Initializer.class ) )
            {
                continue;
            }

            final Call call = bind ( m, binder );

            try
            {
                call.invoke ();
            }
            catch ( final Exception e )
            {
                throw new RuntimeException ( String.format ( "Failed to initialze binder: %s # %s", binder, m ), e );
            }
        }
    }

private
void
initializeBinder
(
final
Binder
binder
)
{
for
(
final
Method
m
:
binder
.
getClass
(
)
.
getMethods
(
)
)
{
if
(
!
m
.
isAnnotationPresent
(
Binder
.
Initializer
.
class
)
)
{
continue
;
}
final
Call
call
=
bind
(
m
,
binder
)
;
try
{
call
.
invoke
(
)
;
}
catch
(
final
Exception
e
)
{
throw
new
RuntimeException
(
String
.
format
(
"Failed to initialze binder: %s # %s"
,
binder
,
m
)
,
e
)
;
}
}
}

Initialize the binder with our current state

@param binder
the binder to initialize


public static Map<String, ChannelAspectInformation> scanAspectInformations ( final BundleContext context )
    {
        Collection<ServiceReference<ChannelAspectFactory>> refs;
        try
        {
            refs = context.getServiceReferences ( ChannelAspectFactory.class, null );
        }
        catch ( final InvalidSyntaxException e )
        {
            // this should never happen since we don't specific a filter
            return Collections.emptyMap ();
        }

        if ( refs == null )
        {
            return Collections.emptyMap ();
        }

        final Map<String, ChannelAspectInformation> result = new HashMap<> ( refs.size () );

        for ( final ServiceReference<ChannelAspectFactory> ref : refs )
        {
            final ChannelAspectInformation info = makeInformation ( ref );
            result.put ( info.getFactoryId (), info );
        }

        return result;
    }

This actively scans for available aspects and returns their information
objects

@param context
the context to use
@return the result map, never returns null


private static String unqualify(String path) {
        path = path.replace('\\', '/');
        return path.substring(path.lastIndexOf('/') + 1);
    }

private static String unqualify ( String path ) { path = path . replace ( ' ' , ' ' ) ; return path . substring ( path . lastIndexOf ( ' ' ) + 1 ) ; }

Returns an unqualified version of the given file path.

Returns an unqualified version of the given file path .


private void invokePlugin(Node.CustomTag n) {
	TagPlugin tagPlugin = tagPlugins.get(n.getTagHandlerClass().getName());
	if (tagPlugin == null) {
	    return;
	}

	TagPluginContext tagPluginContext = new TagPluginContextImpl(n, pageInfo);
	n.setTagPluginContext(tagPluginContext);
	tagPlugin.doTag(tagPluginContext);
    }

private void invokePlugin ( Node . CustomTag n ) { TagPlugin tagPlugin = tagPlugins . get ( n . getTagHandlerClass ( ) . getName ( ) ) ; if ( tagPlugin == null ) { return ; } TagPluginContext tagPluginContext = new TagPluginContextImpl ( n , pageInfo ) ; n . setTagPluginContext ( tagPluginContext ) ; tagPlugin . doTag ( tagPluginContext ) ; }

Invoke tag plugin for the given custom tag, if a plugin exists for
the custom tag's tag handler.

The given custom tag node will be manipulated by the plugin.

Invoke tag plugin for the given custom tag if a plugin exists for the custom tag s tag handler .


public byte[] getByteArray(int size, boolean fillWithZeros) {
        byte[] array = getArray(byteArrayCache, size);

        if (array == null)
            array = new byte[size];
        else if (fillWithZeros)
            Arrays.fill(array, (byte)0x00);

        return array;
    }

public byte [ ] getByteArray ( int size , boolean fillWithZeros ) { byte [ ] array = getArray ( byteArrayCache , size ) ; if ( array == null ) array = new byte [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , ( byte ) 0x00 ) ; return array ; }

Allocates a new byte array, hopefully reusing an existing
array from the cache.

@param       size        size of the array to allocate

@param       fillWithZeros
if true, all the elements of the returned
array will be zero; if false, the contents
of the returned array is undefined

Allocates a new byte array hopefully reusing an existing array from the cache .


public int[] getIntArray(int size, boolean fillWithZeros) {
        int[] array = getArray(intArrayCache, size);

        if (array == null)
            array = new int[size];
        else if (fillWithZeros)
            Arrays.fill(array, 0);

        return array;
    }

public int [ ] getIntArray ( int size , boolean fillWithZeros ) { int [ ] array = getArray ( intArrayCache , size ) ; if ( array == null ) array = new int [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , 0 ) ; return array ; }

This is like getByteArray but for int arrays.

This is like getByteArray but for int arrays .


public static AetherResult asResult ( final Collection<ArtifactResult> results, final ImportConfiguration cfg, final Optional<DependencyResult> dependencyResult )
    {
        final AetherResult result = new AetherResult ();

        // create set of requested coordinates

        final Set<String> requested = new HashSet<> ( cfg.getCoordinates ().size () );
        for ( final MavenCoordinates mc : cfg.getCoordinates () )
        {
            requested.add ( mc.toString () );
        }

        // generate dependency map

        final Map<String, Boolean> optionalDeps = new HashMap<> ();
        fillOptionalDependenciesMap ( dependencyResult, optionalDeps );

        // convert artifacts

        for ( final ArtifactResult ar : results )
        {
            final AetherResult.Entry entry = new AetherResult.Entry ();

            final MavenCoordinates coordinates = MavenCoordinates.fromResult ( ar );
            final String key = coordinates.toBase ().toString ();

            entry.setCoordinates ( coordinates );
            entry.setResolved ( ar.isResolved () );
            entry.setRequested ( requested.contains ( key ) );
            entry.setOptional ( optionalDeps.getOrDefault ( key, Boolean.FALSE ) );

            // convert error

            if ( ar.getExceptions () != null && !ar.getExceptions ().isEmpty () )
            {
                final StringBuilder sb = new StringBuilder ( ar.getExceptions ().get ( 0 ).getMessage () );
                if ( ar.getExceptions ().size () > 1 )
                {
                    sb.append ( " ..." );
                }
                entry.setError ( sb.toString () );
            }

            // add to list

            result.getArtifacts ().add ( entry );
        }

        // sort by coordinates

        Collections.sort ( result.getArtifacts (), Comparator.comparing ( AetherResult.Entry::getCoordinates ) );

        // set repo url

        result.setRepositoryUrl ( cfg.getRepositoryUrl () );

        return result;
    }

public
static
AetherResult
asResult
(
final
Collection
<
ArtifactResult
>
results
,
final
ImportConfiguration
cfg
,
final
Optional
<
DependencyResult
>
dependencyResult
)
{
final
AetherResult
result
=
new
AetherResult
(
)
;
// create set of requested coordinates
final
Set
<
String
>
requested
=
new
HashSet
<>
(
cfg
.
getCoordinates
(
)
.
size
(
)
)
;
for
(
final
MavenCoordinates
mc
:
cfg
.
getCoordinates
(
)
)
{
requested
.
add
(
mc
.
toString
(
)
)
;
}
// generate dependency map
final
Map
<
String
,
Boolean
>
optionalDeps
=
new
HashMap
<>
(
)
;
fillOptionalDependenciesMap
(
dependencyResult
,
optionalDeps
)
;
// convert artifacts
for
(
final
ArtifactResult
ar
:
results
)
{
final
AetherResult
.
Entry
entry
=
new
AetherResult
.
Entry
(
)
;
final
MavenCoordinates
coordinates
=
MavenCoordinates
.
fromResult
(
ar
)
;
final
String
key
=
coordinates
.
toBase
(
)
.
toString
(
)
;
entry
.
setCoordinates
(
coordinates
)
;
entry
.
setResolved
(
ar
.
isResolved
(
)
)
;
entry
.
setRequested
(
requested
.
contains
(
key
)
)
;
entry
.
setOptional
(
optionalDeps
.
getOrDefault
(
key
,
Boolean
.
FALSE
)
)
;
// convert error
if
(
ar
.
getExceptions
(
)
!=
&&
!
ar
.
getExceptions
(
)
.
isEmpty
(
)
)
{
final
StringBuilder
sb
=
new
StringBuilder
(
ar
.
getExceptions
(
)
.
get
(
0
)
.
getMessage
(
)
)
;
if
(
ar
.
getExceptions
(
)
.
size
(
)
>
1
)
{
sb
.
append
(
" ..."
)
;
}
entry
.
setError
(
sb
.
toString
(
)
)
;
}
// add to list
result
.
getArtifacts
(
)
.
add
(
entry
)
;
}
// sort by coordinates
Collections
.
sort
(
result
.
getArtifacts
(
)
,
Comparator
.
comparing
(
AetherResult
.
Entry
::
getCoordinates
)
)
;
// set repo url
result
.
setRepositoryUrl
(
cfg
.
getRepositoryUrl
(
)
)
;
return
result
;
}

Convert aether result list to AetherResult object

@param results
the result collection
@param cfg
the import configuration
@param dependencyResult
The result of the dependency resolution
@return the AetherResult object


private InputStream getResourceAsStream(String uri)
        throws JasperException
    {
        try {
            // see if file exists on the filesystem first
            String real = ctxt.getRealPath(uri);
            if (real == null) {
                return ctxt.getResourceAsStream(uri);
            } else {
                return new FileInputStream(real);
            }
        }
        catch (FileNotFoundException ex) {
            // if file not found on filesystem, get the resource through
            // the context
            return ctxt.getResourceAsStream(uri);
        }

    }

the following is a workaround until these problems are resolved.

the following is a workaround until these problems are resolved .


public ValidationMessage[] validate(PageData thePage) {
	TagLibraryValidator tlv = getTagLibraryValidator();
	if (tlv == null) return null;

        String uri = getURI();
        if (uri.startsWith("/")) {
            uri = URN_JSPTLD + uri;
        }

        ValidationMessage[] messages = tlv.validate(getPrefixString(), uri,
                                                    thePage);
        tlv.release();

        return messages;
    }

public ValidationMessage [ ] validate ( PageData thePage ) { TagLibraryValidator tlv = getTagLibraryValidator ( ) ; if ( tlv == null ) return null ; String uri = getURI ( ) ; if ( uri . startsWith ( "/" ) ) { uri = URN_JSPTLD + uri ; } ValidationMessage [ ] messages = tlv . validate ( getPrefixString ( ) , uri , thePage ) ; tlv . release ( ) ; return messages ; }

Translation-time validation of the XML document
associated with the JSP page.
This is a convenience method on the associated
TagLibraryValidator class.

@param thePage The JSP page object
@return A string indicating whether the page is valid or not.

Translation - time validation of the XML document associated with the JSP page . This is a convenience method on the associated TagLibraryValidator class .


public void pushStream(char[] inStream, int inFileid, String name,
			   String inBaseDir, String inEncoding)
    {

	// store current state in stack
	includeStack.push(new IncludeState(cursor, line, col, fileid, fileName, baseDir,
					   encoding, stream) );

	// set new variables
	cursor = 0;
	line = 1;
	col = 1;
	fileid = inFileid;
	fileName = name;
	baseDir = inBaseDir;
	encoding = inEncoding;
	stream = inStream;
    }

public
void
pushStream
(
char
[
]
inStream
,
int
inFileid
,
String
name
,
String
inBaseDir
,
String
inEncoding
)
{
// store current state in stack
includeStack
.
push
(
new
IncludeState
(
cursor
,
line
,
col
,
fileid
,
fileName
,
baseDir
,
encoding
,
stream
)
)
;
// set new variables
cursor
=
0
;
line
=
1
;
col
=
1
;
fileid
=
inFileid
;
fileName
=
name
;
baseDir
=
inBaseDir
;
encoding
=
inEncoding
;
stream
=
inStream
;
}

Sets this mark's state to a new stream.
It will store the current stream in it's includeStack.
@param inStream new stream for mark
@param inFileid id of new file from which stream comes from
@param inBaseDir directory of file
@param inEncoding encoding of new file

Sets this mark s state to a new stream . It will store the current stream in it s includeStack .


public static Object[] getEncoding(String fname, JarFile jarFile,
                                       JspCompilationContext ctxt,
                                       ErrorDispatcher err)
        throws IOException, JasperException
    {
        InputStream inStream = JspUtil.getInputStream(fname, jarFile, ctxt,
                                                      err);
        XMLEncodingDetector detector = new XMLEncodingDetector();
        Object[] ret = detector.getEncoding(inStream, err);
        inStream.close();

        return ret;
    }

public static Object [ ] getEncoding ( String fname , JarFile jarFile , JspCompilationContext ctxt , ErrorDispatcher err ) throws IOException , JasperException { InputStream inStream = JspUtil . getInputStream ( fname , jarFile , ctxt , err ) ; XMLEncodingDetector detector = new XMLEncodingDetector ( ) ; Object [ ] ret = detector . getEncoding ( inStream , err ) ; inStream . close ( ) ; return ret ; }

Autodetects the encoding of the XML document supplied by the given
input stream.

Encoding autodetection is done according to the XML 1.0 specification,
Appendix F.1: Detection Without External Encoding Information.

@return Two-element array, where the first element (of type
java.lang.String) contains the name of the (auto)detected encoding, and
the second element (of type java.lang.Boolean) specifies whether the
encoding was specified using the 'encoding' attribute of an XML prolog
(TRUE) or autodetected (FALSE).

Autodetects the encoding of the XML document supplied by the given input stream .


private void scanXMLDecl() throws IOException, JasperException {

	if (skipString("<?xml")) {
	    fMarkupDepth++;
	    // NOTE: special case where document starts with a PI
	    //       whose name starts with "xml" (e.g. "xmlfoo")
	    if (XMLChar.isName(peekChar())) {
		fStringBuffer.clear();
		fStringBuffer.append("xml");
		while (XMLChar.isName(peekChar())) {
		    fStringBuffer.append((char)scanChar());
		}
		String target = fSymbolTable.addSymbol(fStringBuffer.ch,
						       fStringBuffer.offset,
						       fStringBuffer.length);
		scanPIData(target, fString);
	    }

	    // standard XML declaration
	    else {
		scanXMLDeclOrTextDecl(false);
	    }
	}
    }

org . apache . xerces . impl . XMLDocumentScannerImpl . dispatch


private void reportFatalError(String msgId, String arg)
                throws JasperException {
        err.jspError(msgId, arg);
    }

private void reportFatalError ( String msgId , String arg ) throws JasperException { err . jspError ( msgId , arg ) ; }

Convenience function used in all XML scanners.

Convenience function used in all XML scanners .


public String getRealPath(String path) {

        if (!myResourceBaseURL.getProtocol().equals("file"))
            return (null);
        if (!path.startsWith("/"))
            return (null);
        try {
            return
                (getResource(path).getFile().replace('/', File.separatorChar));
        } catch (Throwable t) {
            return (null);
        }

    }

public String getRealPath ( String path ) { if ( ! myResourceBaseURL . getProtocol ( ) . equals ( "file" ) ) return ( null ) ; if ( ! path . startsWith ( "/" ) ) return ( null ) ; try { return ( getResource ( path ) . getFile ( ) . replace ( ' ' , File . separatorChar ) ) ; } catch ( Throwable t ) { return ( null ) ; } }

Return the real path for the specified context-relative
virtual path.

@param path The context-relative virtual path to resolve

Return the real path for the specified context - relative virtual path .


public URL getResource(String path) throws MalformedURLException {

        if (!path.startsWith("/"))
            throw new MalformedURLException("Path '" + path +
                                            "' does not start with '/'");
        URL url = new URL(myResourceBaseURL, path.substring(1));
        InputStream is = null;
        try {
            is = url.openStream();
        } catch (Throwable t) {
            url = null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Throwable t2) {
                    // Ignore
                }
            }
        }
        return url;
    }

public
URL
getResource
(
String
path
)
throws
MalformedURLException
{
if
(
!
path
.
startsWith
(
"/"
)
)
throw
new
MalformedURLException
(
"Path '"
+
path
+
"' does not start with '/'"
)
;
URL
url
=
new
URL
(
myResourceBaseURL
,
path
.
substring
(
1
)
)
;
InputStream
is
=
;
try
{
is
=
url
.
openStream
(
)
;
}
catch
(
Throwable
t
)
{
url
=
;
}
finally
{
if
(
is
!=
)
{
try
{
is
.
close
(
)
;
}
catch
(
Throwable
t2
)
{
// Ignore
}
}
}
return
url
;
}

Return a URL object of a resource that is mapped to the
specified context-relative path.

@param path Context-relative path of the desired resource

@exception MalformedURLException if the resource path is
not properly formed

Return a URL object of a resource that is mapped to the specified context - relative path .


public InputStream getResourceAsStream(String path) {

        try {
            return (getResource(path).openStream());
        } catch (Throwable t) {
            return (null);
        }

    }

public InputStream getResourceAsStream ( String path ) { try { return ( getResource ( path ) . openStream ( ) ) ; } catch ( Throwable t ) { return ( null ) ; } }

Return an InputStream allowing access to the resource at the
specified context-relative path.

@param path Context-relative path of the desired resource

Return an InputStream allowing access to the resource at the specified context - relative path .


public Set<String> getResourcePaths(String path) {

        Set<String> thePaths = new HashSet<String>();
        if (!path.endsWith("/"))
            path += "/";
        String basePath = getRealPath(path);
        if (basePath == null)
            return (thePaths);
        File theBaseDir = new File(basePath);
        if (!theBaseDir.exists() || !theBaseDir.isDirectory())
            return (thePaths);
        String theFiles[] = theBaseDir.list();
        for (int i = 0; i < theFiles.length; i++) {
            File testFile = new File(basePath + File.separator + theFiles[i]);
            if (testFile.isFile())
                thePaths.add(path + theFiles[i]);
            else if (testFile.isDirectory())
                thePaths.add(path + theFiles[i] + "/");
        }
        return (thePaths);

    }

public Set < String > getResourcePaths ( String path ) { Set < String > thePaths = new HashSet < String > ( ) ; if ( ! path . endsWith ( "/" ) ) path += "/" ; String basePath = getRealPath ( path ) ; if ( basePath == null ) return ( thePaths ) ; File theBaseDir = new File ( basePath ) ; if ( ! theBaseDir . exists ( ) || ! theBaseDir . isDirectory ( ) ) return ( thePaths ) ; String theFiles [ ] = theBaseDir . list ( ) ; for ( int i = 0 ; i < theFiles . length ; i ++ ) { File testFile = new File ( basePath + File . separator + theFiles [ i ] ) ; if ( testFile . isFile ( ) ) thePaths . add ( path + theFiles [ i ] ) ; else if ( testFile . isDirectory ( ) ) thePaths . add ( path + theFiles [ i ] + "/" ) ; } return ( thePaths ) ; }

Return the set of resource paths for the "directory" at the
specified context path.

@param path Context-relative base path

Return the set of resource paths for the directory at the specified context path .


public void log(String message, Throwable exception) {

        myLogWriter.println(message);
        exception.printStackTrace(myLogWriter);

    }

public void log ( String message , Throwable exception ) { myLogWriter . println ( message ) ; exception . printStackTrace ( myLogWriter ) ; }

Log the specified message and exception.

@param message The message to be logged
@param exception The exception to be logged

Log the specified message and exception .


public void addFilter(String filterName,
                          String description,
                          String className,
                          Map<String, String> initParameters) {
        // Do nothing
        return;
    }

public
void
addFilter
(
String
filterName
,
String
description
,
String
className
,
Map
<
String
,
String
>
initParameters
)
{
// Do nothing
return
;
}

Adds the filter with the given name, description, and class name to
this servlet context.

Adds the filter with the given name description and class name to this servlet context .


private static int getBufSize(
            int dictSize, int extraSizeBefore, int extraSizeAfter,
            int matchLenMax) {
        int keepSizeBefore = extraSizeBefore + dictSize;
        int keepSizeAfter = extraSizeAfter + matchLenMax;
        int reserveSize = Math.min(dictSize / 2 + (256 << 10), 512 << 20);
        return keepSizeBefore + keepSizeAfter + reserveSize;
    }

private static int getBufSize ( int dictSize , int extraSizeBefore , int extraSizeAfter , int matchLenMax ) { int keepSizeBefore = extraSizeBefore + dictSize ; int keepSizeAfter = extraSizeAfter + matchLenMax ; int reserveSize = Math . min ( dictSize / 2 + ( 256 << 10 ) , 512 << 20 ) ; return keepSizeBefore + keepSizeAfter + reserveSize ; }

Gets the size of the LZ window buffer that needs to be allocated.

Gets the size of the LZ window buffer that needs to be allocated .


public static int getMemoryUsage(
            int dictSize, int extraSizeBefore, int extraSizeAfter,
            int matchLenMax, int mf) {
        // Buffer size + a little extra
        int m = getBufSize(dictSize, extraSizeBefore, extraSizeAfter,
                           matchLenMax) / 1024 + 10;

        switch (mf) {
            case MF_HC4:
                m += HC4.getMemoryUsage(dictSize);
                break;

            case MF_BT4:
                m += BT4.getMemoryUsage(dictSize);
                break;

            default:
                throw new IllegalArgumentException();
        }

        return m;
    }

public
static
int
getMemoryUsage
(
int
dictSize
,
int
extraSizeBefore
,
int
extraSizeAfter
,
int
matchLenMax
,
int
mf
)
{
// Buffer size + a little extra
int
m
=
getBufSize
(
dictSize
,
extraSizeBefore
,
extraSizeAfter
,
matchLenMax
)
/
1024
+
10
;
switch
(
mf
)
{
case
MF_HC4
:
m
+=
HC4
.
getMemoryUsage
(
dictSize
)
;
break
;
case
MF_BT4
:
m
+=
BT4
.
getMemoryUsage
(
dictSize
)
;
break
;
default
:
throw
new
IllegalArgumentException
(
)
;
}
return
m
;
}

Gets approximate memory usage of the LZEncoder base structure and
the match finder as kibibytes.

Gets approximate memory usage of the LZEncoder base structure and the match finder as kibibytes .


public void setPresetDict(int dictSize, byte[] presetDict) {
        assert !isStarted();
        assert writePos == 0;

        if (presetDict != null) {
            // If the preset dictionary buffer is bigger than the dictionary
            // size, copy only the tail of the preset dictionary.
            int copySize = Math.min(presetDict.length, dictSize);
            int offset = presetDict.length - copySize;
            System.arraycopy(presetDict, offset, buf, 0, copySize);
            writePos += copySize;
            skip(copySize);
        }
    }

Sets a preset dictionary. If a preset dictionary is wanted, this
function must be called immediately after creating the LZEncoder
before any data has been encoded.

Sets a preset dictionary . If a preset dictionary is wanted this function must be called immediately after creating the LZEncoder before any data has been encoded .


private void moveWindow() {
        // Align the move to a multiple of 16 bytes. LZMA2 needs this
        // because it uses the lowest bits from readPos to get the
        // alignment of the uncompressed data.
        int moveOffset = (readPos + 1 - keepSizeBefore) & ~15;
        int moveSize = writePos - moveOffset;
        System.arraycopy(buf, moveOffset, buf, 0, moveSize);

        readPos -= moveOffset;
        readLimit -= moveOffset;
        writePos -= moveOffset;
    }

Moves data from the end of the buffer to the beginning, discarding
old data and making space for new input.

Moves data from the end of the buffer to the beginning discarding old data and making space for new input .


public int fillWindow(byte[] in, int off, int len) {
        assert !finishing;

        // Move the sliding window if needed.
        if (readPos >= bufSize - keepSizeAfter)
            moveWindow();

        // Try to fill the dictionary buffer. If it becomes full,
        // some of the input bytes may be left unused.
        if (len > bufSize - writePos)
            len = bufSize - writePos;

        System.arraycopy(in, off, buf, writePos, len);
        writePos += len;

        // Set the new readLimit but only if there's enough data to allow
        // encoding of at least one more byte.
        if (writePos >= keepSizeAfter)
            readLimit = writePos - keepSizeAfter;

        processPendingBytes();

        // Tell the caller how much input we actually copied into
        // the dictionary.
        return len;
    }

Copies new data into the LZEncoder's buffer.

Copies new data into the LZEncoder s buffer .


private void processPendingBytes() {
        // After flushing or setting a preset dictionary there will be
        // pending data that hasn't been ran through the match finder yet.
        // Run it through the match finder now if there is enough new data
        // available (readPos < readLimit) that the encoder may encode at
        // least one more input byte. This way we don't waste any time
        // looping in the match finder (and marking the same bytes as
        // pending again) if the application provides very little new data
        // per write call.
        if (pendingSize > 0 && readPos < readLimit) {
            readPos -= pendingSize;
            int oldPendingSize = pendingSize;
            pendingSize = 0;
            skip(oldPendingSize);
            assert pendingSize < oldPendingSize;
        }
    }

Process pending bytes remaining from preset dictionary initialization
or encoder flush operation.

Process pending bytes remaining from preset dictionary initialization or encoder flush operation .


public int getMatchLen(int dist, int lenLimit) {
        int backPos = readPos - dist - 1;
        int len = 0;

        while (len < lenLimit && buf[readPos + len] == buf[backPos + len])
            ++len;

        return len;
    }

public int getMatchLen ( int dist , int lenLimit ) { int backPos = readPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ readPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }

Get the length of a match at the given distance.

@param       dist        zero-based distance of the match to test
@param       lenLimit    don't test for a match longer than this

@return      length of the match; it is in the range [0, lenLimit]

Get the length of a match at the given distance .


public int getMatchLen(int forward, int dist, int lenLimit) {
        int curPos = readPos + forward;
        int backPos = curPos - dist - 1;
        int len = 0;

        while (len < lenLimit && buf[curPos + len] == buf[backPos + len])
            ++len;

        return len;
    }

public int getMatchLen ( int forward , int dist , int lenLimit ) { int curPos = readPos + forward ; int backPos = curPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ curPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }

Get the length of a match at the given distance and forward offset.

@param       forward     forward offset
@param       dist        zero-based distance of the match to test
@param       lenLimit    don't test for a match longer than this

@return      length of the match; it is in the range [0, lenLimit]

Get the length of a match at the given distance and forward offset .


public boolean verifyMatches(Matches matches) {
        int lenLimit = Math.min(getAvail(), matchLenMax);

        for (int i = 0; i < matches.count; ++i)
            if (getMatchLen(matches.dist[i], lenLimit) != matches.len[i])
                return false;

        return true;
    }

public boolean verifyMatches ( Matches matches ) { int lenLimit = Math . min ( getAvail ( ) , matchLenMax ) ; for ( int i = 0 ; i < matches . count ; ++ i ) if ( getMatchLen ( matches . dist [ i ] , lenLimit ) != matches . len [ i ] ) return false ; return true ; }

Verifies that the matches returned by the match finder are valid.
This is meant to be used in an assert statement. This is totally
useless for actual encoding since match finder's results should
naturally always be valid if it isn't broken.

@param       matches     return value from getMatches

@return      true if matches are valid, false if match finder is broken

Verifies that the matches returned by the match finder are valid . This is meant to be used in an assert statement . This is totally useless for actual encoding since match finder s results should naturally always be valid if it isn t broken .


int movePos(int requiredForFlushing, int requiredForFinishing) {
        assert requiredForFlushing >= requiredForFinishing;

        ++readPos;
        int avail = writePos - readPos;

        if (avail < requiredForFlushing) {
            if (avail < requiredForFinishing || !finishing) {
                ++pendingSize;
                avail = 0;
            }
        }

        return avail;
    }

int movePos ( int requiredForFlushing , int requiredForFinishing ) { assert requiredForFlushing >= requiredForFinishing ; ++ readPos ; int avail = writePos - readPos ; if ( avail < requiredForFlushing ) { if ( avail < requiredForFinishing || ! finishing ) { ++ pendingSize ; avail = 0 ; } } return avail ; }

Moves to the next byte, checks if there is enough input available,
and returns the amount of input available.

@param       requiredForFlushing
minimum number of available bytes when
flushing; encoding may be continued with
new input after flushing
@param       requiredForFinishing
minimum number of available bytes when
finishing; encoding must not be continued
after finishing or the match finder state
may be corrupt

@return      the number of bytes available or zero if there
is not enough input available

Moves to the next byte checks if there is enough input available and returns the amount of input available .


void recycle() {
	flushed = false;
        closed = false;
        out = null;
        byteOut = null;
        releaseCharBuffer();
        response = null;
    }

void recycle ( ) { flushed = false ; closed = false ; out = null ; byteOut = null ; releaseCharBuffer ( ) ; response = null ; }


protected final void flushBuffer() throws IOException {
        if (bufferSize == 0)
            return;
        flushed = true;
        ensureOpen();
        if (buf.pos == buf.offset)
            return;
        initOut();
        out.write(buf.buf, buf.offset, buf.pos - buf.offset);
        buf.pos = buf.offset;
    }

protected final void flushBuffer ( ) throws IOException { if ( bufferSize == 0 ) return ; flushed = true ; ensureOpen ( ) ; if ( buf . pos == buf . offset ) return ; initOut ( ) ; out . write ( buf . buf , buf . offset , buf . pos - buf . offset ) ; buf . pos = buf . offset ; }

Flush the output buffer to the underlying character stream, without
flushing the stream itself.  This method is non-private only so that it
may be invoked by PrintStream.

Flush the output buffer to the underlying character stream without flushing the stream itself . This method is non - private only so that it may be invoked by PrintStream .


public final void clear() throws IOException {
        if ((bufferSize == 0) && (out != null))
            // clear() is illegal after any unbuffered output (JSP.5.5)
            throw new IllegalStateException(
                    getLocalizeMessage("jsp.error.ise_on_clear"));
        if (flushed)
            throw new IOException(
                    getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer"));
        ensureOpen();
        if (buf != null)
            buf.pos = buf.offset;
    }


public void flush()  throws IOException {
        flushBuffer();
        if (out != null) {
            out.flush();
        }
        // START 6426898
        else {
            // Set the default character encoding if there isn't any present,
            // see CR 6699416
            response.setCharacterEncoding(response.getCharacterEncoding());

            // Cause response headers to be sent
            response.flushBuffer();
        }
        // END 6426898
    }


public void close() throws IOException {
        if (response == null || closed)
            // multiple calls to close is OK
            return;
        flush();
        if (out != null)
            out.close();
        out = null;
        byteOut = null;
        closed = true;
    }

public
void
close
(
)
throws
IOException
{
if
(
response
==
||
closed
)
// multiple calls to close is OK
return
;
flush
(
)
;
if
(
out
!=
)
out
.
close
(
)
;
out
=
;
byteOut
=
;
closed
=
true
;
}


public void write(boolean bytesOK, byte buf[], String str)
            throws IOException {

        ensureOpen();
        if (bufferSize == 0 && bytesOK) {
            initByteOut();
            if (implementsByteWriter) {
                write(buf, 0, buf.length);
                return;
            }
        }
        write(str);
    }

public void write ( boolean bytesOK , byte buf [ ] , String str ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 && bytesOK ) { initByteOut ( ) ; if ( implementsByteWriter ) { write ( buf , 0 , buf . length ) ; return ; } } write ( str ) ; }

Attempt to write a String pre-encoded with the page encoding.

@param bytesOK If true, write out the byte array,
else, write out the String.
@param buf     The text encoded with the page encoding
@param str     The original text

Attempt to write a String pre - encoded with the page encoding .


private void allocateCharBuffer() {
        if (bufferSize == 0) return;

        if (bufferSize > MAX_BUFFER_SIZE) {
            buf =  new CharBuffer(new char[bufferSize], 0, bufferSize);
        } else {
            buf = getCharBufferThreadLocalPool().allocate(bufferSize);
        }
    }

private void allocateCharBuffer ( ) { if ( bufferSize == 0 ) return ; if ( bufferSize > MAX_BUFFER_SIZE ) { buf = new CharBuffer ( new char [ bufferSize ] , 0 , bufferSize ) ; } else { buf = getCharBufferThreadLocalPool ( ) . allocate ( bufferSize ) ; } }


public void javacError(String errorReport, Exception exception)
            throws JasperException {

 	throw new JasperException(
            Localizer.getMessage("jsp.error.unable.compile"), exception);
    }

public void javacError ( String errorReport , Exception exception ) throws JasperException { throw new JasperException ( Localizer . getMessage ( "jsp.error.unable.compile" ) , exception ) ; }

Processes the given javac error report and exception.

@param errorReport Compilation error report
@param exception Compilation exception

Processes the given javac error report and exception .


public List<String> makeKey ( final Map<MetaKey, String> metaData, final boolean requireAll )
    {
        final List<String> result = new ArrayList<> ( this.fields.size () );

        for ( final MetaKey field : this.fields )
        {
            final String value = metaData.get ( field );
            if ( requireAll && value == null )
            {
                return null;
            }

            result.add ( value );
        }

        return result;
    }

public List < String > makeKey ( final Map < MetaKey , String > metaData , final boolean requireAll ) { final List < String > result = new ArrayList <> ( this . fields . size ( ) ) ; for ( final MetaKey field : this . fields ) { final String value = metaData . get ( field ) ; if ( requireAll && value == null ) { return null ; } result . add ( value ) ; } return result ; }

Make a key from the aggregator fields

@param metaData
the metadata to build the key from
@param requireAll
if this is {@code true} then all aggregator fields must be
present in the meta data map
@return
the key or {@code null} if {@code requireAll} is {@code true} and
at least one field is missing the provided {@code metaData}


private void generateClass()
        throws FileNotFoundException, JasperException, Exception {

        long t1 = 0;
        if (log.isLoggable(Level.FINE)) {
            t1 = System.currentTimeMillis();
        }

        String javaFileName = ctxt.getServletJavaFileName();

        setJavaCompilerOptions();

        // Start java compilation
        JavacErrorDetail[] javacErrors =
            javaCompiler.compile(ctxt.getFullClassName(), pageNodes);

        if (javacErrors != null) {
            // If there are errors, always generate java files to disk.
            javaCompiler.doJavaFile(true);

            log.severe("Error compiling file: " + javaFileName);
            errDispatcher.javacError(javacErrors);
        }

        if (log.isLoggable(Level.FINE)) {
            long t2 = System.currentTimeMillis();
            log.fine("Compiled " + javaFileName + " " + (t2-t1) + "ms");
        }

        // Save or delete the generated Java files, depending on the
        // value of "keepgenerated" attribute
        javaCompiler.doJavaFile(ctxt.keepGenerated());

        // JSR45 Support
        if (!ctxt.isPrototypeMode() && !options.isSmapSuppressed()) {
            smapUtil.installSmap();
        }

        // START CR 6373479
        if (jsw != null && jsw.getServletClassLastModifiedTime() <= 0) {
            jsw.setServletClassLastModifiedTime(
                javaCompiler.getClassLastModified());
        }
        // END CR 6373479

        if (options.getSaveBytecode()) {
            javaCompiler.saveClassFile(ctxt.getFullClassName(),
                                       ctxt.getClassFileName());
        }

        // On some systems, due to file caching, the time stamp for the updated
        // JSP file may actually be greater than that of the newly created byte
        // codes in the cache.  In such cases, adjust the cache time stamp to
        // JSP page time, to avoid unnecessary recompilations.
        ctxt.getRuntimeContext().adjustBytecodeTime(ctxt.getFullClassName(),
                                                    jspModTime);
    }

Compile the servlet from .java file to .class file

Compile the servlet from . java file to . class file


public void compile(boolean compileClass)
        throws FileNotFoundException, JasperException, Exception
    {

        try {
            // Create the output directory for the generated files
            // Always try and create the directory tree, in case the generated
            // directories were deleted after the server was started.
            ctxt.makeOutputDir(ctxt.getOutputDir());

            // If errDispatcher is nulled from a previous compilation of the
            // same page, instantiate one here.
            if (errDispatcher == null) {
                errDispatcher = new ErrorDispatcher(jspcMode);
            }
            generateJava();
            if (compileClass) {
                generateClass();
            }
            else {
                // If called from jspc to only compile to .java files,
                // make sure that .java files are written to disk.
                javaCompiler.doJavaFile(ctxt.keepGenerated());
            }
        } finally {
            if (tfp != null) {
                tfp.removeProtoTypeFiles(null);
            }
            javaCompiler.release();
            // Make sure these object which are only used during the
            // generation and compilation of the JSP page get
            // dereferenced so that they can be GC'd and reduce the
            // memory footprint.
            tfp = null;
            errDispatcher = null;
            if (!jspcMode) {
                pageInfo = null;
            }
            pageNodes = null;
            if (ctxt.getWriter() != null) {
                ctxt.getWriter().close();
                ctxt.setWriter(null);
            }
        }
    }

Compile the jsp file from the current engine context.  As an side-
effect, tag files that are referenced by this page are also compiled.

@param compileClass If true, generate both .java and .class file
If false, generate only .java file

Compile the jsp file from the current engine context . As an side - effect tag files that are referenced by this page are also compiled .


public void removeGeneratedFiles() {
        try {
            String classFileName = ctxt.getClassFileName();
            if (classFileName != null) {
                File classFile = new File(classFileName);
                if( log.isLoggable(Level.FINE) )
                    log.fine( "Deleting " + classFile );
                classFile.delete();
            }
        } catch (Exception e) {
            // Remove as much as possible, ignore possible exceptions
        }
        try {
            String javaFileName = ctxt.getServletJavaFileName();
            if (javaFileName != null) {
                File javaFile = new File(javaFileName);
                if( log.isLoggable(Level.FINE) )
                    log.fine( "Deleting " + javaFile );
                javaFile.delete();
            }
        } catch (Exception e) {
            // Remove as much as possible, ignore possible exceptions
        }
    }


private void initJavaCompiler() throws JasperException {
        boolean disablejsr199 = Boolean.TRUE.toString().equals(
            System.getProperty("org.apache.jasper.compiler.disablejsr199"));
        Double version =
            Double.valueOf(System.getProperty("java.specification.version"));
        if (!disablejsr199 &&
               (version >= 1.6 || getClassFor("javax.tools.Tool") != null)) {
            // JDK 6 or bundled with jsr199 compiler
            javaCompiler = new Jsr199JavaCompiler();
        } else {
            Class c = getClassFor("org.eclipse.jdt.internal.compiler.Compiler");
            if (c != null) {
                c = getClassFor("org.apache.jasper.compiler.JDTJavaCompiler");
                if (c != null) {
                    try {
                        javaCompiler = (JavaCompiler) c.newInstance();
                    } catch (Exception ex) {
                    }
                }
            }
        }
        if (javaCompiler == null) {
            Class c = getClassFor("org.apache.tools.ant.taskdefs.Javac");
            if (c != null) {
                c = getClassFor("org.apache.jasper.compiler.AntJavaCompiler");
                if (c != null) {
                    try {
                        javaCompiler = (JavaCompiler) c.newInstance();
                    } catch (Exception ex) {
                    }
                }
            }
        }
        if (javaCompiler == null) {
            errDispatcher.jspError("jsp.error.nojavac");
        }

        javaCompiler.init(ctxt, errDispatcher, jspcMode);
    }

Get an instance of JavaCompiler.
If Running with JDK 6, use a Jsr199JavaCompiler that supports JSR199,
else if eclipse's JDT compiler is available, use that.
The default is to use javac from ant.

Get an instance of JavaCompiler . If Running with JDK 6 use a Jsr199JavaCompiler that supports JSR199 else if eclipse s JDT compiler is available use that . The default is to use javac from ant .


private boolean systemJarInWebinf(String path) {

        if (path.indexOf("/WEB-INF/") < 0) {
            return false;
        }

        Boolean useMyFaces = (Boolean) ctxt.getServletContext().
                getAttribute("com.sun.faces.useMyFaces");

        if (useMyFaces == null || !useMyFaces) {
            for (String jar: systemJsfJars) {
                if (path.indexOf(jar) > 0) {
                    return true;
                }
            }
        }

        for (String jar: systemJars) {
            if (path.indexOf(jar) > 0) {
                return true;
            }
        }
        return false;
    }

private boolean systemJarInWebinf ( String path ) { if ( path . indexOf ( "/WEB-INF/" ) < 0 ) { return false ; } Boolean useMyFaces = ( Boolean ) ctxt . getServletContext ( ) . getAttribute ( "com.sun.faces.useMyFaces" ) ; if ( useMyFaces == null || ! useMyFaces ) { for ( String jar : systemJsfJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } } for ( String jar : systemJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } return false ; }

Return true if the path refers to a jar file in WEB-INF and is a
system jar.

Return true if the path refers to a jar file in WEB - INF and is a system jar .


static String quote(char c) {

        StringBuilder b = new StringBuilder();
        b.append('\'');
        if (c == '\'')
            b.append('\\').append('\'');
        else if (c == '\\')
            b.append('\\').append('\\');
        else if (c == '\n')
            b.append('\\').append('n');
        else if (c == '\r')
            b.append('\\').append('r');
        else
            b.append(c);
        b.append('\'');
        return b.toString();
    }

static String quote ( char c ) { StringBuilder b = new StringBuilder ( ) ; b . append ( ' ' ) ; if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else b . append ( c ) ; b . append ( ' ' ) ; return b . toString ( ) ; }


private void generateDeclarations(Node.Nodes page) throws JasperException {

        class DeclarationVisitor extends Node.Visitor {

            private boolean getServletInfoGenerated = false;

            /*
             * Generates getServletInfo() method that returns the value of the
             * page directive's 'info' attribute, if present.
             *
             * The Validator has already ensured that if the translation unit
             * contains more than one page directive with an 'info' attribute,
             * their values match.
             */
            public void visit(Node.PageDirective n) throws JasperException {

                if (getServletInfoGenerated) {
                    return;
                }

                String info = n.getAttributeValue("info");
                if (info == null)
                    return;

                getServletInfoGenerated = true;
                out.printil("public String getServletInfo() {");
                out.pushIndent();
                out.printin("return ");
                out.print(quote(info));
                out.println(";");
                out.popIndent();
                out.printil("}");
                out.println();
            }

            public void visit(Node.Declaration n) throws JasperException {
                n.setBeginJavaLine(out.getJavaLine());
                out.printMultiLn(n.getText());
                out.println();
                n.setEndJavaLine(out.getJavaLine());
            }

            // Custom Tags may contain declarations from tag plugins.
            public void visit(Node.CustomTag n) throws JasperException {
                if (n.useTagPlugin()) {
                    if (n.getAtSTag() != null) {
                        n.getAtSTag().visit(this);
                    }
                    visitBody(n);
                    if (n.getAtETag() != null) {
                        n.getAtETag().visit(this);
                    }
                } else {
                    visitBody(n);
                }
            }
        }

        out.println();
        page.visit(new DeclarationVisitor());
    }

Generates declarations.  This includes "info" of the page directive,
and scriptlet declarations.

Generates declarations . This includes info of the page directive and scriptlet declarations .


private void compileTagHandlerPoolList(Node.Nodes page)
        throws JasperException {

        class TagHandlerPoolVisitor extends Node.Visitor {

            private Set<String> names = new HashSet<String>();

            /*
             * Constructor
             *
             * @param v Set of tag handler pool names to populate
             */
            TagHandlerPoolVisitor(Set<String> v) {
                names = v;
            }

            /*
             * Gets the name of the tag handler pool for the given custom tag
             * and adds it to the list of tag handler pool names unless it is
             * already contained in it.
             */
            public void visit(Node.CustomTag n) throws JasperException {

                if (!n.implementsSimpleTag()) {
                    String name =
                        createTagHandlerPoolName(
                            n.getPrefix(),
                            n.getLocalName(),
                            n.getAttributes(),
                            n.hasEmptyBody());
                    n.setTagHandlerPoolName(name);
                    if (!names.contains(name)) {
                        names.add(name);
                    }
                }
                visitBody(n);
            }

            /*
             * Creates the name of the tag handler pool whose tag handlers may
             * be (re)used to service this action.
             *
             * @return The name of the tag handler pool
             */
            private String createTagHandlerPoolName(
                String prefix,
                String shortName,
                Attributes attrs,
                boolean hasEmptyBody) {
                String poolName = null;

                poolName = "_jspx_tagPool_" + prefix + "_" + shortName;
                if (attrs != null) {
                    String[] attrNames = new String[attrs.getLength()];
                    for (int i = 0; i < attrNames.length; i++) {
                        attrNames[i] = attrs.getQName(i);
                    }
                    Arrays.sort(attrNames, Collections.reverseOrder());
                    for (int i = 0; i < attrNames.length; i++) {
                        poolName = poolName + "_" + attrNames[i];
                    }
                }
                if (hasEmptyBody) {
                    poolName = poolName + "_nobody";
                }
                return JspUtil.makeXmlJavaIdentifier(poolName);
            }
        }

        page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames));
    }

Compiles list of tag handler pool names.

Compiles list of tag handler pool names .


private void generateXmlProlog(Node.Nodes page) {

        /*
         * An XML declaration is generated under the following conditions:
         *
         * - 'omit-xml-declaration' attribute of <jsp:output> action is set to
         *   "no" or "false"
         * - JSP document without a <jsp:root>
         */
        String omitXmlDecl = pageInfo.getOmitXmlDecl();
        if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl))
            || (omitXmlDecl == null
                && page.getRoot().isXmlSyntax()
                && !pageInfo.hasJspRoot()
                && !ctxt.isTagFile())) {
            String cType = pageInfo.getContentType();
            String charSet = cType.substring(cType.indexOf("charset=") + 8);
            out.printil(
                "out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\""
                    + charSet
                    + "\\\"?>\\n\");");
        }

        /*
         * Output a DOCTYPE declaration if the doctype-root-element appears.
         * If doctype-public appears:
         *     <!DOCTYPE name PUBLIC "doctypePublic" "doctypeSystem">
         * else
         *     <!DOCTYPE name SYSTEM "doctypeSystem" >
         */

        String doctypeName = pageInfo.getDoctypeName();
        if (doctypeName != null) {
            String doctypePublic = pageInfo.getDoctypePublic();
            String doctypeSystem = pageInfo.getDoctypeSystem();
            out.printin("out.write(\"<!DOCTYPE ");
            out.print(doctypeName);
            if (doctypePublic == null) {
                out.print(" SYSTEM \\\"");
            } else {
                out.print(" PUBLIC \\\"");
                out.print(doctypePublic);
                out.print("\\\" \\\"");
            }
            out.print(doctypeSystem);
            out.println("\\\">\\n\");");
        }
    }

Generates an XML Prolog, which includes an XML declaration and
an XML doctype declaration.

Generates an XML Prolog which includes an XML declaration and an XML doctype declaration .


private void genCommonPostamble() {
        // Append any methods that were generated in the buffer.
        for (int i = 0; i < methodsBuffered.size(); i++) {
            GenBuffer methodBuffer = methodsBuffered.get(i);
            methodBuffer.adjustJavaLines(out.getJavaLine() - 1);
            out.printMultiLn(methodBuffer.toString());
        }

        // Append the helper class
        if (fragmentHelperClass.isUsed()) {
            fragmentHelperClass.generatePostamble();
            fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1);
            out.printMultiLn(fragmentHelperClass.toString());
        }

        // Append char array declarations
        if (arrayBuffer != null) {
            out.printMultiLn(arrayBuffer.toString());
        }

        // Close the class definition
        out.popIndent();
        out.printil("}");
    }

Common part of postamble, shared by both servlets and tag files.

Common part of postamble shared by both servlets and tag files .


private void generatePostamble(Node.Nodes page) {
        out.popIndent();
        out.printil("} catch (Throwable t) {");
        out.pushIndent();
        out.printil(
            "if (!(t instanceof SkipPageException)){");
        out.pushIndent();
        out.printil("out = _jspx_out;");
        out.printil("if (out != null && out.getBufferSize() != 0)");
        out.pushIndent();
        out.printil("out.clearBuffer();");
        out.popIndent();

        out.printil(
            "if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);");
        out.printil("else throw new ServletException(t);");
        out.popIndent();
        out.printil("}");
        out.popIndent();
        out.printil("} finally {");
        out.pushIndent();

        out.printil(
            "_jspxFactory.releasePageContext(_jspx_page_context);");

        out.popIndent();
        out.printil("}");

        // Close the service method
        out.popIndent();
        out.printil("}");

        // Generated methods, helper classes, etc.
        genCommonPostamble();
    }

Generates the ending part of the static portion of the servlet.

Generates the ending part of the static portion of the servlet .


public static void generate(
        ServletWriter out,
        Compiler compiler,
        Node.Nodes page)
        throws JasperException {

        Generator gen = new Generator(out, compiler);

        if (gen.isPoolingEnabled) {
            gen.compileTagHandlerPoolList(page);
        }
        if (gen.ctxt.isTagFile()) {
            JasperTagInfo tagInfo = (JasperTagInfo)gen.ctxt.getTagInfo();
            gen.generateTagHandlerPreamble(tagInfo, page);

            if (gen.ctxt.isPrototypeMode()) {
                return;
            }

            gen.generateXmlProlog(page);
            gen.fragmentHelperClass.generatePreamble();
            page.visit(
                gen.new GenerateVisitor(
                    gen.ctxt.isTagFile(),
                    out,
                    gen.methodsBuffered,
                    gen.fragmentHelperClass));
            gen.generateTagHandlerPostamble(tagInfo);
        } else {
            gen.generatePreamble(page);
            gen.generateXmlProlog(page);
            gen.fragmentHelperClass.generatePreamble();
            page.visit(
                gen.new GenerateVisitor(
                    gen.ctxt.isTagFile(),
                    out,
                    gen.methodsBuffered,
                    gen.fragmentHelperClass));
            gen.generatePostamble(page);
        }
    }

public static void generate ( ServletWriter out , Compiler compiler , Node . Nodes page ) throws JasperException { Generator gen = new Generator ( out , compiler ) ; if ( gen . isPoolingEnabled ) { gen . compileTagHandlerPoolList ( page ) ; } if ( gen . ctxt . isTagFile ( ) ) { JasperTagInfo tagInfo = ( JasperTagInfo ) gen . ctxt . getTagInfo ( ) ; gen . generateTagHandlerPreamble ( tagInfo , page ) ; if ( gen . ctxt . isPrototypeMode ( ) ) { return ; } gen . generateXmlProlog ( page ) ; gen . fragmentHelperClass . generatePreamble ( ) ; page . visit ( gen . new GenerateVisitor ( gen . ctxt . isTagFile ( ) , out , gen . methodsBuffered , gen . fragmentHelperClass ) ) ; gen . generateTagHandlerPostamble ( tagInfo ) ; } else { gen . generatePreamble ( page ) ; gen . generateXmlProlog ( page ) ; gen . fragmentHelperClass . generatePreamble ( ) ; page . visit ( gen . new GenerateVisitor ( gen . ctxt . isTagFile ( ) , out , gen . methodsBuffered , gen . fragmentHelperClass ) ) ; gen . generatePostamble ( page ) ; } }

The main entry for Generator.
@param out The servlet output writer
@param compiler The compiler
@param page The input page


private void generateTagHandlerAttributes(TagInfo tagInfo)
        throws JasperException {

        if (tagInfo.hasDynamicAttributes()) {
            out.printil(
                "private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();");
        }

        // Declare attributes
        TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
        for (int i = 0; i < attrInfos.length; i++) {
            out.printin("private ");
            if (attrInfos[i].isFragment()) {
                out.print("javax.servlet.jsp.tagext.JspFragment ");
            } else {
                out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
                out.print(" ");
            }
            out.print(attrInfos[i].getName());
            out.println(";");
        }
        out.println();

        // Define attribute getter and setter methods
        for (int i = 0; i < attrInfos.length; i++) {
            // getter method
            out.printin("public ");
            if (attrInfos[i].isFragment()) {
                out.print("javax.servlet.jsp.tagext.JspFragment ");
            } else {
                out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
                out.print(" ");
            }
            out.print(toGetterMethod(attrInfos[i].getName()));
            out.println(" {");
            out.pushIndent();
            out.printin("return this.");
            out.print(attrInfos[i].getName());
            out.println(";");
            out.popIndent();
            out.printil("}");
            out.println();

            // setter method
            out.printin("public void ");
            out.print(toSetterMethodName(attrInfos[i].getName()));
            if (attrInfos[i].isFragment()) {
                out.print("(javax.servlet.jsp.tagext.JspFragment ");
            } else {
                out.print("(");
                out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
                out.print(" ");
            }
            out.print(attrInfos[i].getName());
            out.println(") {");
            out.pushIndent();
            out.printin("this.");
            out.print(attrInfos[i].getName());
            out.print(" = ");
            out.print(attrInfos[i].getName());
            out.println(";");
            out.popIndent();
            out.printil("}");
            out.println();
        }
    }

Generates declarations for tag handler attributes, and defines the
getter and setter methods for each.

Generates declarations for tag handler attributes and defines the getter and setter methods for each .


private Map<MetaKey, String> readProperties ( final InputStream stream ) throws IOException
    {
        try
        {
            // wrap the input stream since we don't want the XML parser to close the stream while parsing

            final Document doc = this.xmlToolsFactory.newDocumentBuilder ().parse ( new FilterInputStream ( stream ) {
                @Override
                public void close ()
                {
                    // do nothing
                }
            } );

            final Element root = doc.getDocumentElement ();
            if ( !"properties".equals ( root.getNodeName () ) )
            {
                throw new IllegalStateException ( String.format ( "Root element must be of type '%s'", "properties" ) );
            }

            final Map<MetaKey, String> result = new HashMap<> ();

            for ( final Element ele : XmlHelper.iterElement ( root, "property" ) )
            {
                final String namespace = ele.getAttribute ( "namespace" );
                final String key = ele.getAttribute ( "key" );
                final String value = ele.getTextContent ();

                if ( namespace.isEmpty () || key.isEmpty () )
                {
                    continue;
                }

                result.put ( new MetaKey ( namespace, key ), value );
            }

            return result;
        }
        catch ( final Exception e )
        {
            throw new IOException ( "Failed to read properties", e );
        }
    }

Read in a map of properties

@param stream
input stream
@return the map of properties
@throws IOException
if anything goes wrong reading the file


private void exportChannel ( final By by, final OutputStream stream ) throws IOException
    {
        final ZipOutputStream zos = new ZipOutputStream ( stream );

        initExportFile ( zos );

        this.channelService.accessRun ( by, ReadableChannel.class, channel -> {

            putDataEntry ( zos, "names", makeNames ( channel.getId () ) );
            putDataEntry ( zos, "description", channel.getId ().getDescription () );
            putDirEntry ( zos, "artifacts" );
            putProperties ( zos, "properties.xml", channel.getContext ().getProvidedMetaData () );
            putAspects ( zos, channel.getContext ().getAspectStates ().keySet () );

            // the first run receives all artifacts and filters for the root elements

            putArtifacts ( zos, "artifacts/", channel, channel.getArtifacts (), true );
        } );

        this.channelService.accessRun ( by, TriggeredChannel.class, channel -> {
            putTriggers ( zos, channel );
        } );

        zos.finish (); // don't close stream, since there might be other channels following
    }

Export the content of a channel

@param by
the channel to export
@param stream
the stream to write the export file to
@throws IOException
if the export cannot be performed


private static void validateXmlView(PageData xmlView, Compiler compiler)
	        throws JasperException {

	StringBuilder errMsg = null;
	ErrorDispatcher errDisp = compiler.getErrorDispatcher();

	for (Iterator<TagLibraryInfo> iter =
                     compiler.getPageInfo().getTaglibs().iterator();
	         iter.hasNext(); ) {

	    TagLibraryInfo o = iter.next();
	    if (!(o instanceof TagLibraryInfoImpl))
		continue;
	    TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o;

	    ValidationMessage[] errors = tli.validate(xmlView);
            if ((errors != null) && (errors.length != 0)) {
                if (errMsg == null) {
		    errMsg = new StringBuilder();
		}
                errMsg.append("
");
                errMsg.append(Localizer.getMessage("jsp.error.tlv.invalid.page",
						   tli.getShortName()));
                errMsg.append("
");
                for (int i=0; i<errors.length; i++) {
		    if (errors[i] != null) {
			errMsg.append("
");
			errMsg.append(errors[i].getId());
			errMsg.append(": ");
			errMsg.append(errors[i].getMessage());
			errMsg.append("
");
		    }
                }
            }
        }

	if (errMsg != null) {
            errDisp.jspError(errMsg.toString());
	}
    }

private
static
void
validateXmlView
(
PageData
xmlView
,
Compiler
compiler
)
throws
JasperException
{
StringBuilder
errMsg
=
;
ErrorDispatcher
errDisp
=
compiler
.
getErrorDispatcher
(
)
;
for
(
Iterator
<
TagLibraryInfo
>
iter
=
compiler
.
getPageInfo
(
)
.
getTaglibs
(
)
.
iterator
(
)
;
iter
.
hasNext
(
)
;
)
{
TagLibraryInfo
o
=
iter
.
next
(
)
;
if
(
!
(
o
instanceof
TagLibraryInfoImpl
)
)
continue
;
TagLibraryInfoImpl
tli
=
(
TagLibraryInfoImpl
)
o
;
ValidationMessage
[
]
errors
=
tli
.
validate
(
xmlView
)
;
if
(
(
errors
!=
)
&&
(
errors
.
length
!=
0
)
)
{
if
(
errMsg
==
)
{
errMsg
=
new
StringBuilder
(
)
;
}
errMsg
.
append
(
"
"
)
;
errMsg
.
append
(
Localizer
.
getMessage
(
"jsp.error.tlv.invalid.page"
,
tli
.
getShortName
(
)
)
)
;
errMsg
.
append
(
"
"
)
;
for
(
int
i
=
0
;
i
<
errors
.
length
;
i
++
)
{
if
(
errors
[
i
]
!=
)
{
errMsg
.
append
(
"
"
)
;
errMsg
.
append
(
errors
[
i
]
.
getId
(
)
)
;
errMsg
.
append
(
": "
)
;
errMsg
.
append
(
errors
[
i
]
.
getMessage
(
)
)
;
errMsg
.
append
(
"
"
)
;
}
}
}
}
if
(
errMsg
!=
)
{
errDisp
.
jspError
(
errMsg
.
toString
(
)
)
;
}
}

Validate XML view against the TagLibraryValidator classes of all
imported tag libraries.

Validate XML view against the TagLibraryValidator classes of all imported tag libraries .


public <T extends JspTag> JspTag get(Class<T> handlerClass)
            throws JspException {
        synchronized( this ) {
            if (current >= 0) {
                return handlers[current--];
            }
        }

        // Out of sync block - there is no need for other threads to
        // wait for us to construct a tag for this thread.
        JspTag tagHandler = null;
        try {
            if (resourceInjector != null) {
                tagHandler = resourceInjector.createTagHandlerInstance(
                    handlerClass);
            } else {
                tagHandler = handlerClass.newInstance();
            }
        } catch (Exception e) {
            throw new JspException(e.getMessage(), e);
        }

        return tagHandler;
    }

Gets the next available tag handler from this tag handler pool,
instantiating one if this tag handler pool is empty.

@param handlerClass Tag handler class

@return Reused or newly instantiated tag handler

@throws JspException if a tag handler cannot be instantiated

Gets the next available tag handler from this tag handler pool instantiating one if this tag handler pool is empty .


public static ELNode.Nodes parse(String expression) {
	ELParser parser = new ELParser(expression);
	while (parser.hasNextChar()) {
	    String text = parser.skipUntilEL();
	    if (text.length() > 0) {
		parser.expr.add(new ELNode.Text(text));
	    }
	    ELNode.Nodes elexpr = parser.parseEL();
	    if (! elexpr.isEmpty()) {
		parser.expr.add(new ELNode.Root(elexpr, parser.isDollarExpr));
	    }
	}
	return parser.expr;
    }

public static ELNode . Nodes parse ( String expression ) { ELParser parser = new ELParser ( expression ) ; while ( parser . hasNextChar ( ) ) { String text = parser . skipUntilEL ( ) ; if ( text . length ( ) > 0 ) { parser . expr . add ( new ELNode . Text ( text ) ) ; } ELNode . Nodes elexpr = parser . parseEL ( ) ; if ( ! elexpr . isEmpty ( ) ) { parser . expr . add ( new ELNode . Root ( elexpr , parser . isDollarExpr ) ) ; } } return parser . expr ; }

Parse an EL expression
@param expression The input expression string of the form
( (Char* | (('${' | '#{') Char* '}') )+
@return Parsed EL expression in ELNode.Nodes


private JspPropertyGroup selectProperty(JspPropertyGroup prev,
                                            JspPropertyGroup curr) {
        if (prev == null) {
            return curr;
        }
        if (prev.getExtension() == null) {
            // exact match
            return prev;
        }
        if (curr.getExtension() == null) {
            // exact match
            return curr;
        }
        String prevPath = prev.getPath();
        String currPath = curr.getPath();
        if (prevPath == null && currPath == null) {
            // Both specifies a *.ext, keep the first one
            return prev;
        }
        if (prevPath == null && currPath != null) {
            return curr;
        }
        if (prevPath != null && currPath == null) {
            return prev;
        }
        if (prevPath.length() >= currPath.length()) {
            return prev;
        }
        return curr;
    }

Select the property group that has more restrictive url-pattern.
In case of tie, select the first.

Select the property group that has more restrictive url - pattern . In case of tie select the first .


public boolean isJspPage(String uri) throws JasperException {

        init();
        if (jspProperties == null) {
            return false;
        }

        String uriPath = null;
        int index = uri.lastIndexOf('/');
        if (index >=0 ) {
            uriPath = uri.substring(0, index+1);
        }
        String uriExtension = null;
        index = uri.lastIndexOf('.');
        if (index >=0) {
            uriExtension = uri.substring(index+1);
        }

        for (JspPropertyGroup jpg: jspProperties) {

            JspProperty jp = jpg.getJspProperty();

            String extension = jpg.getExtension();
            String path = jpg.getPath();

            if (extension == null) {
                if (uri.equals(path)) {
                    // There is an exact match
                    return true;
                }
            } else {
                if ((path == null || path.equals(uriPath)) &&
                    (extension.equals("*") || extension.equals(uriExtension))) {
                    // Matches *, *.ext, /p/*, or /p/*.ext
                    return true;
                }
            }
        }
        return false;
    }

public
boolean
isJspPage
(
String
uri
)
throws
JasperException
{
init
(
)
;
if
(
jspProperties
==
)
{
return
false
;
}
String
uriPath
=
;
int
index
=
uri
.
lastIndexOf
(
'
'
)
;
if
(
index
>=
0
)
{
uriPath
=
uri
.
substring
(
0
,
index
+
1
)
;
}
String
uriExtension
=
;
index
=
uri
.
lastIndexOf
(
'
'
)
;
if
(
index
>=
0
)
{
uriExtension
=
uri
.
substring
(
index
+
1
)
;
}
for
(
JspPropertyGroup
jpg
:
jspProperties
)
{
JspProperty
jp
=
jpg
.
getJspProperty
(
)
;
String
extension
=
jpg
.
getExtension
(
)
;
String
path
=
jpg
.
getPath
(
)
;
if
(
extension
==
)
{
if
(
uri
.
equals
(
path
)
)
{
// There is an exact match
return
true
;
}
}
else
{
if
(
(
path
==
||
path
.
equals
(
uriPath
)
)
&&
(
extension
.
equals
(
"*"
)
||
extension
.
equals
(
uriExtension
)
)
)
{
// Matches *, *.ext, /p/*, or /p/*.ext
return
true
;
}
}
}
return
false
;
}

To find out if an uri matches an url pattern in jsp config.  If so,
then the uri is a JSP page.  This is used primarily for jspc.

To find out if an uri matches an url pattern in jsp config . If so then the uri is a JSP page . This is used primarily for jspc .


public void printComment(Mark start, Mark stop, char[] chars) {
        if (start != null && stop != null) {
            println("// from="+start);
            println("//   to="+stop);
        }

        if (chars != null)
            for(int i = 0; i < chars.length;) {
                printin();
                print("// ");
                while (chars[i] != '\n' && i < chars.length)
                    writer.print(chars[i++]);
            }
    }

public
void
printComment
(
Mark
start
,
Mark
stop
,
char
[
]
chars
)
{
if
(
start
!=
&&
stop
!=
)
{
println
(
"// from="
+
start
)
;
println
(
"//   to="
+
stop
)
;
}
if
(
chars
!=
)
for
(
int
i
=
0
;
i
<
chars
.
length
;
)
{
printin
(
)
;
print
(
"// "
)
;
while
(
chars
[
i
]
!=
'
'
&&
i
<
chars
.
length
)
writer
.
print
(
chars
[
i
++
]
)
;
}
}

Print a standard comment for echo outputed chunk.
@param start The starting position of the JSP chunk being processed.
@param stop  The ending position of the JSP chunk being processed.

Print a standard comment for echo outputed chunk .


public void printin(String s) {
	writer.print(SPACES.substring(0, indent));
	writer.print(s);
    }

public void printin ( String s ) { writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . print ( s ) ; }

Prints the current indention, followed by the given string

Prints the current indention followed by the given string


public void printil(String s) {
        javaLine++;
	writer.print(SPACES.substring(0, indent));
	writer.println(s);
    }

public void printil ( String s ) { javaLine ++ ; writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . println ( s ) ; }

Prints the current indention, and then the string, and a '\n'.

Prints the current indention and then the string and a \ n .


public void printMultiLn(String s) {
        int index = 0;

        // look for hidden newlines inside strings
        while ((index=s.indexOf('\n',index)) > -1 ) {
            javaLine++;
            index++;
        }

	writer.print(s);
    }

Prints the given string.

If the string spans multiple lines, the line count will be adjusted
accordingly.


public static String getExprInXml(String expression) {
        String returnString;
        int length = expression.length();

        if (expression.startsWith(OPEN_EXPR)
                && expression.endsWith(CLOSE_EXPR)) {
            returnString = expression.substring (1, length - 1);
        } else {
            returnString = expression;
        }

        return escapeXml(returnString);
    }

public static String getExprInXml ( String expression ) { String returnString ; int length = expression . length ( ) ; if ( expression . startsWith ( OPEN_EXPR ) && expression . endsWith ( CLOSE_EXPR ) ) { returnString = expression . substring ( 1 , length - 1 ) ; } else { returnString = expression ; } return escapeXml ( returnString ) ; }

Takes a potential expression and converts it into XML form


public static void checkScope(String scope, Node n, ErrorDispatcher err)
            throws JasperException {
	if (scope != null && !scope.equals("page") && !scope.equals("request")
		&& !scope.equals("session") && !scope.equals("application")) {
	    err.jspError(n, "jsp.error.invalid.scope", scope);
	}
    }

public static void checkScope ( String scope , Node n , ErrorDispatcher err ) throws JasperException { if ( scope != null && ! scope . equals ( "page" ) && ! scope . equals ( "request" ) && ! scope . equals ( "session" ) && ! scope . equals ( "application" ) ) { err . jspError ( n , "jsp.error.invalid.scope" , scope ) ; } }

Checks to see if the given scope is valid.

@param scope The scope to be checked
@param n The Node containing the 'scope' attribute whose value is to be
checked
@param err error dispatcher

@throws JasperException if scope is not null and different from
"page", "request", "session", and
"application"

Checks to see if the given scope is valid .


public static String escapeXml(String s) {
        if (s == null) return null;
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            if (c == '<') {
                sb.append("<");
            } else if (c == '>') {
                sb.append(">");
            } else if (c == '\'') {
                sb.append("'");
            } else if (c == '&') {
                sb.append("&");
            } else if (c == '"') {
                sb.append(""");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

public static String escapeXml ( String s ) { if ( s == null ) return null ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' ) { sb . append ( "<" ) ; } else if ( c == ' ' ) { sb . append ( ">" ) ; } else if ( c == ' ' ) { sb . append ( "'" ) ; } else if ( c == ' ' ) { sb . append ( "&" ) ; } else if ( c == ' ' ) { sb . append ( """ ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }


public static void validateExpressions(Mark where,
                                           String expressions,
                                           FunctionMapper functionMapper,
                                           ErrorDispatcher err)
            throws JasperException {

        try {
            ELContextImpl elContext = new ELContextImpl(null);
            elContext.setFunctionMapper(functionMapper);
            getExpressionFactory().createValueExpression(
                elContext,
                expressions, Object.class);
        }
        catch( ELException e ) {
            err.jspError(where, "jsp.error.invalid.expression", expressions,
                e.toString() );
        }
    }

public static void validateExpressions ( Mark where , String expressions , FunctionMapper functionMapper , ErrorDispatcher err ) throws JasperException { try { ELContextImpl elContext = new ELContextImpl ( null ) ; elContext . setFunctionMapper ( functionMapper ) ; getExpressionFactory ( ) . createValueExpression ( elContext , expressions , Object . class ) ; } catch ( ELException e ) { err . jspError ( where , "jsp.error.invalid.expression" , expressions , e . toString ( ) ) ; } }

Validates the syntax of all EL expressions within the given string.
@param where the approximate location of the expressions in the JSP page
@param expressions a string containing an EL expressions
@param err an error dispatcher to use

Validates the syntax of all EL expressions within the given string .


public static String getTagHandlerClassName(String path,
						ErrorDispatcher err)
                throws JasperException {

        String className = null;
        int begin = 0;
        int index;

        index = path.lastIndexOf(".tag");
        if (index == -1) {
            err.jspError("jsp.error.tagfile.badSuffix", path);
        }

        //It's tempting to remove the ".tag" suffix here, but we can't.
        //If we remove it, the fully-qualified class name of this tag
        //could conflict with the package name of other tags.
        //For instance, the tag file
        //    /WEB-INF/tags/foo.tag
        //would have fully-qualified class name
        //    org.apache.jsp.tag.web.foo
        //which would conflict with the package name of the tag file
        //    /WEB-INF/tags/foo/bar.tag

        index = path.indexOf(WEB_INF_TAGS);
        if (index != -1) {
            className = "org.apache.jsp.tag.web.";
            begin = index + WEB_INF_TAGS.length();
        } else {
	    index = path.indexOf(META_INF_TAGS);
	    if (index != -1) {
		className = "org.apache.jsp.tag.meta.";
		begin = index + META_INF_TAGS.length();
	    } else {
		err.jspError("jsp.error.tagfile.illegalPath", path);
	    }
	}

        className += makeJavaPackage(path.substring(begin));

       return className;
    }

Gets the fully-qualified class name of the tag handler corresponding to
the given tag file path.

@param path Tag file path
@param err Error dispatcher

@return Fully-qualified class name of the tag handler corresponding to
the given tag file path

Gets the fully - qualified class name of the tag handler corresponding to the given tag file path .


public static final String makeJavaPackage(String path) {
        String classNameComponents[] = split(path,"/");
        StringBuilder legalClassNames = new StringBuilder();
        for (int i = 0; i < classNameComponents.length; i++) {
            legalClassNames.append(makeJavaIdentifier(classNameComponents[i]));
            if (i < classNameComponents.length - 1) {
                legalClassNames.append('.');
            }
        }
        return legalClassNames.toString();
    }

public static final String makeJavaPackage ( String path ) { String classNameComponents [ ] = split ( path , "/" ) ; StringBuilder legalClassNames = new StringBuilder ( ) ; for ( int i = 0 ; i < classNameComponents . length ; i ++ ) { legalClassNames . append ( makeJavaIdentifier ( classNameComponents [ i ] ) ) ; if ( i < classNameComponents . length - 1 ) { legalClassNames . append ( ' ' ) ; } } return legalClassNames . toString ( ) ; }

Converts the given path to a Java package or fully-qualified class name

@param path Path to convert

@return Java package corresponding to the given path

Converts the given path to a Java package or fully - qualified class name


private static final String [] split(String path, String pat) {
        ArrayList<String> comps = new ArrayList<String>();
        int pos = path.indexOf(pat);
        int start = 0;
        while( pos >= 0 ) {
            if(pos > start ) {
                String comp = path.substring(start,pos);
                comps.add(comp);
            }
            start = pos + pat.length();
            pos = path.indexOf(pat,start);
        }
        if( start < path.length()) {
            comps.add(path.substring(start));
        }
        String [] result = new String[comps.size()];
        for(int i=0; i < comps.size(); i++) {
            result[i] = comps.get(i);
        }
        return result;
    }

private static final String [ ] split ( String path , String pat ) { ArrayList < String > comps = new ArrayList < String > ( ) ; int pos = path . indexOf ( pat ) ; int start = 0 ; while ( pos >= 0 ) { if ( pos > start ) { String comp = path . substring ( start , pos ) ; comps . add ( comp ) ; } start = pos + pat . length ( ) ; pos = path . indexOf ( pat , start ) ; } if ( start < path . length ( ) ) { comps . add ( path . substring ( start ) ) ; } String [ ] result = new String [ comps . size ( ) ] ; for ( int i = 0 ; i < comps . size ( ) ; i ++ ) { result [ i ] = comps . get ( i ) ; } return result ; }

Splits a string into it's components.
@param path String to split
@param pat Pattern to split at
@return the components of the path


public static final String makeJavaIdentifier(String identifier) {
        StringBuilder modifiedIdentifier =
            new StringBuilder(identifier.length());
        if (!Character.isJavaIdentifierStart(identifier.charAt(0))) {
            modifiedIdentifier.append('_');
        }
        for (int i = 0; i < identifier.length(); i++) {
            char ch = identifier.charAt(i);
            if (Character.isJavaIdentifierPart(ch) && ch != '_') {
                modifiedIdentifier.append(ch);
            } else if (ch == '.') {
                modifiedIdentifier.append('_');
            } else {
                modifiedIdentifier.append(mangleChar(ch));
            }
        }
        if (isJavaKeyword(modifiedIdentifier.toString())) {
            modifiedIdentifier.append('_');
        }
        return modifiedIdentifier.toString();
    }

public static final String makeJavaIdentifier ( String identifier ) { StringBuilder modifiedIdentifier = new StringBuilder ( identifier . length ( ) ) ; if ( ! Character . isJavaIdentifierStart ( identifier . charAt ( 0 ) ) ) { modifiedIdentifier . append ( ' ' ) ; } for ( int i = 0 ; i < identifier . length ( ) ; i ++ ) { char ch = identifier . charAt ( i ) ; if ( Character . isJavaIdentifierPart ( ch ) && ch != ' ' ) { modifiedIdentifier . append ( ch ) ; } else if ( ch == ' ' ) { modifiedIdentifier . append ( ' ' ) ; } else { modifiedIdentifier . append ( mangleChar ( ch ) ) ; } } if ( isJavaKeyword ( modifiedIdentifier . toString ( ) ) ) { modifiedIdentifier . append ( ' ' ) ; } return modifiedIdentifier . toString ( ) ; }

Converts the given identifier to a legal Java identifier

@param identifier Identifier to convert

@return Legal Java identifier corresponding to the given identifier


public static final String mangleChar(char ch) {
        char[] result = new char[5];
        result[0] = '_';
        result[1] = Character.forDigit((ch >> 12) & 0xf, 16);
        result[2] = Character.forDigit((ch >> 8) & 0xf, 16);
        result[3] = Character.forDigit((ch >> 4) & 0xf, 16);
        result[4] = Character.forDigit(ch & 0xf, 16);
        return new String(result);
    }

public static final String mangleChar ( char ch ) { char [ ] result = new char [ 5 ] ; result [ 0 ] = ' ' ; result [ 1 ] = Character . forDigit ( ( ch >> 12 ) & 0xf , 16 ) ; result [ 2 ] = Character . forDigit ( ( ch >> 8 ) & 0xf , 16 ) ; result [ 3 ] = Character . forDigit ( ( ch >> 4 ) & 0xf , 16 ) ; result [ 4 ] = Character . forDigit ( ch & 0xf , 16 ) ; return new String ( result ) ; }

Mangle the specified character to create a legal Java class name.

Mangle the specified character to create a legal Java class name .


public static boolean isJavaKeyword(String key) {
        int i = 0;
        int j = javaKeywords.length;
        while (i < j) {
            int k = (i+j)/2;
            int result = javaKeywords[k].compareTo(key);
            if (result == 0) {
                return true;
            }
            if (result < 0) {
                i = k+1;
            } else {
                j = k;
            }
        }
        return false;
    }

public static boolean isJavaKeyword ( String key ) { int i = 0 ; int j = javaKeywords . length ; while ( i < j ) { int k = ( i + j ) / 2 ; int result = javaKeywords [ k ] . compareTo ( key ) ; if ( result == 0 ) { return true ; } if ( result < 0 ) { i = k + 1 ; } else { j = k ; } } return false ; }

Test whether the argument is a Java keyword


private static void addProperty ( final Map<String, String> props, final String key, final String value )
    {
        if ( value == null )
        {
            return;
        }

        props.put ( key, value );
    }

private static void addProperty ( final Map < String , String > props , final String key , final String value ) { if ( value == null ) { return ; } props . put ( key , value ) ; }

Add property entry only of value is not null

@param props
properties
@param key
to add
@param value
to add


public static String modifier ( final String prefix, final Modifier modifier )
    {
        if ( modifier == null )
        {
            return "";
        }

        String value = null;
        switch ( modifier )
        {
            case DEFAULT:
                value = "default";
                break;
            case PRIMARY:
                value = "primary";
                break;
            case SUCCESS:
                value = "success";
                break;
            case INFO:
                value = "info";
                break;
            case WARNING:
                value = "warning";
                break;
            case DANGER:
                value = "danger";
                break;
            case LINK:
                value = "link";
                break;
        }

        if ( value != null && prefix != null )
        {
            return prefix + value;
        }
        else
        {
            return value != null ? value : "";
        }
    }

public static String modifier ( final String prefix , final Modifier modifier ) { if ( modifier == null ) { return "" ; } String value = null ; switch ( modifier ) { case DEFAULT : value = "default" ; break ; case PRIMARY : value = "primary" ; break ; case SUCCESS : value = "success" ; break ; case INFO : value = "info" ; break ; case WARNING : value = "warning" ; break ; case DANGER : value = "danger" ; break ; case LINK : value = "link" ; break ; } if ( value != null && prefix != null ) { return prefix + value ; } else { return value != null ? value : "" ; } }

Convert a modifier value to a bootstrap type modifier

@param prefix
an optional prefix to add
@param modifier
the modifier to convert
@return the bootstrap type string, optionally with a prefix attached,
never null


public static SortedSet<String> metadata ( final Map<MetaKey, String> metadata, String namespace, String key )
    {
        final SortedSet<String> result = new TreeSet<> ();

        if ( namespace.isEmpty () )
        {
            namespace = null;
        }

        if ( key.isEmpty () )
        {
            key = null;
        }

        for ( final Map.Entry<MetaKey, String> entry : metadata.entrySet () )
        {
            if ( namespace != null && !namespace.equals ( entry.getKey ().getNamespace () ) )
            {
                continue;
            }

            if ( key != null && !key.equals ( entry.getKey ().getKey () ) )
            {
                continue;
            }

            result.add ( entry.getValue () );
        }

        return result;
    }

public static SortedSet < String > metadata ( final Map < MetaKey , String > metadata , String namespace , String key ) { final SortedSet < String > result = new TreeSet <> ( ) ; if ( namespace . isEmpty ( ) ) { namespace = null ; } if ( key . isEmpty ( ) ) { key = null ; } for ( final Map . Entry < MetaKey , String > entry : metadata . entrySet ( ) ) { if ( namespace != null && ! namespace . equals ( entry . getKey ( ) . getNamespace ( ) ) ) { continue ; } if ( key != null && ! key . equals ( entry . getKey ( ) . getKey ( ) ) ) { continue ; } result . add ( entry . getValue ( ) ) ; } return result ; }

Get all meta data values which match namespace and key

@param metadata
the map of meta data to filter
@param namespace
an optional namespace filter
@param key
an optional key filter
@return the result set


@Override
    public void run () throws Exception
    {
        this.storageManager.modifyRun ( MODEL_KEY, UserWriteModel.class, users -> {

            final Date timeout = new Date ( System.currentTimeMillis () - getTimeout () );

            final Collection<UserEntity> updates = new LinkedList<> ();
            final Collection<String> removals = new LinkedList<> ();

            for ( final UserEntity user : users.asCollection () )
            {
                if ( user.getEmailTokenDate () == null || user.getEmailTokenDate ().after ( timeout ) )
                {
                    continue;
                }

                // process timeout

                if ( user.isEmailVerified () )
                {
                    user.setEmailToken ( null );
                    user.setEmailTokenDate ( null );
                    user.setEmailTokenSalt ( null );
                    updates.add ( user );
                }
                else
                {
                    // delete
                    removals.add ( user.getId () );
                }
            }

            updates.forEach ( users::putUser );
            removals.forEach ( users::removeUser );
        } );
    }

@
Override
public
void
run
(
)
throws
Exception
{
this
.
storageManager
.
modifyRun
(
MODEL_KEY
,
UserWriteModel
.
class
,
users
->
{
final
Date
timeout
=
new
Date
(
System
.
currentTimeMillis
(
)
getTimeout
(
)
)
;
final
Collection
<
UserEntity
>
updates
=
new
LinkedList
<>
(
)
;
final
Collection
<
String
>
removals
=
new
LinkedList
<>
(
)
;
for
(
final
UserEntity
user
:
users
.
asCollection
(
)
)
{
if
(
user
.
getEmailTokenDate
(
)
==
||
user
.
getEmailTokenDate
(
)
.
after
(
timeout
)
)
{
continue
;
}
// process timeout
if
(
user
.
isEmailVerified
(
)
)
{
user
.
setEmailToken
(
)
;
user
.
setEmailTokenDate
(
)
;
user
.
setEmailTokenSalt
(
)
;
updates
.
add
(
user
)
;
}
else
{
// delete
removals
.
add
(
user
.
getId
(
)
)
;
}
}
updates
.
forEach
(
users
::
putUser
)
;
removals
.
forEach
(
users
::
removeUser
)
;
}
)
;
}


public static String getBasename ( final String name )
    {
        if ( name == null )
        {
            return null;
        }

        final String[] toks = name.split ( "/" );
        if ( toks.length < 1 )
        {
            return name;
        }

        return toks[toks.length - 1];
    }

public static String getBasename ( final String name ) { if ( name == null ) { return null ; } final String [ ] toks = name . split ( "/" ) ; if ( toks . length < 1 ) { return name ; } return toks [ toks . length - 1 ] ; }

Get the last segment of a path, the filename

@param name
the name to process
@return the last segment, or {@code null} if the input was {@code null}

Get the last segment of a path the filename


public boolean put(Locator locator, String key, String value) throws CacheException {
        if (value == null) return false;

        Timer.Context cachePutTimerContext = MetadataCache.cachePutTimer.time();
        boolean dbWrite = false;
        try {
            CacheKey cacheKey = new CacheKey(locator, key);
            String oldValue = cache.getIfPresent(cacheKey);
            // don't care if oldValue == EMPTY.
            // always put new value in the cache. it keeps reads from happening.
            cache.put(cacheKey, value);
            if (oldValue == null || !oldValue.equals(value)) {
                dbWrite = true;
            }

            if (dbWrite) {
                updatedMetricMeter.mark();
                if (!batchedWrites) {
                    databasePut(locator, key, value);
                } else {
                    databaseLazyWrite(locator, key);
                }
            }

            return dbWrite;
        } finally {
            cachePutTimerContext.stop();
        }
    }


private String databaseLoad(Locator locator, String key) throws CacheException {
        try {
            CacheKey cacheKey = new CacheKey(locator, key);
            Map<String, String> metadata = io.getAllValues(locator);
            if (metadata == null || metadata.isEmpty()) {
                cache.put(cacheKey, NULL);
                return NULL;
            }

            int metadataRowSize = 0;
            // prepopulate all other metadata other than the key we called the method with
            for (Map.Entry<String, String> meta : metadata.entrySet()) {
                metadataRowSize += meta.getKey().getBytes().length + locator.toString().getBytes().length;
                if (meta.getValue() != null)
                    metadataRowSize += meta.getValue().getBytes().length;
                if (meta.getKey().equals(key)) continue;
                CacheKey metaKey = new CacheKey(locator, meta.getKey());
                cache.put(metaKey, meta.getValue());
            }
            totalMetadataSize.update(metadataRowSize);

            String value = metadata.get(key);

            if (value == null) {
                cache.put(cacheKey, NULL);
                value = NULL;
            }

            return value;
        } catch (IOException ex) {
            throw new CacheException(ex);
        }
    }


public static Collection<IMetric> buildMetricsCollection(AggregatedPayload payload) {
        Collection<IMetric> metrics = new ArrayList<IMetric>();
        metrics.addAll(PreaggregateConversions.convertCounters(payload.getTenantId(), payload.getTimestamp(), payload.getFlushIntervalMillis(), payload.getCounters()));
        metrics.addAll(PreaggregateConversions.convertGauges(payload.getTenantId(), payload.getTimestamp(), payload.getGauges()));
        metrics.addAll(PreaggregateConversions.convertSets(payload.getTenantId(), payload.getTimestamp(), payload.getSets()));
        metrics.addAll(PreaggregateConversions.convertTimers(payload.getTenantId(), payload.getTimestamp(), payload.getTimers()));
        return metrics;
    }

public static Collection < IMetric > buildMetricsCollection ( AggregatedPayload payload ) { Collection < IMetric > metrics = new ArrayList < IMetric > ( ) ; metrics . addAll ( PreaggregateConversions . convertCounters ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getFlushIntervalMillis ( ) , payload . getCounters ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertGauges ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getGauges ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertSets ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getSets ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertTimers ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getTimers ( ) ) ) ; return metrics ; }

type comparisions we use to determine how to serialize a number.

type comparisions we use to determine how to serialize a number .


public static Number resolveNumber(Number n) {
        if (n instanceof LazilyParsedNumber) {
            try {
                return n.longValue();
            } catch (NumberFormatException ex) {
                return n.doubleValue();
            }
        } else {
            // already resolved.
            return n;
        }
    }

public
static
Number
resolveNumber
(
Number
n
)
{
if
(
n
instanceof
LazilyParsedNumber
)
{
try
{
return
n
.
longValue
(
)
;
}
catch
(
NumberFormatException
ex
)
{
return
n
.
doubleValue
(
)
;
}
}
else
{
// already resolved.
return
n
;
}
}