protected static List<MavenVersionedArtifact> getMavenArtifacts ( final String channelId, final Supplier<Collection<ArtifactInformation>> artifactsSupplier, final String groupId, final String artifactId, final boolean snapshot, final Predicate<ComparableVersion> versionFilter )
    {
        final List<MavenVersionedArtifact> arts = new ArrayList<> ();

        for ( final ArtifactInformation ai : artifactsSupplier.get () )
        {
            if ( !isZip ( ai ) )
            {
                // if is is anot a zip, then this is not for the unzip plugin
                continue;
            }

            // fetch meta data

            final String mvnGroupId = ai.getMetaData ().get ( MK_GROUP_ID );
            final String mvnArtifactId = ai.getMetaData ().get ( MK_ARTIFACT_ID );

            final String classifier = ai.getMetaData ().get ( MK_CLASSIFIER );

            final String mvnVersion = ai.getMetaData ().get ( MK_VERSION );
            final String mvnSnapshotVersion = ai.getMetaData ().get ( MK_SNAPSHOT_VERSION );

            if ( mvnGroupId == null || mvnArtifactId == null || mvnVersion == null )
            {
                // no GAV information
                continue;
            }

            if ( classifier != null && !classifier.isEmpty () )
            {
                // no classifiers right now
                continue;
            }

            if ( !mvnGroupId.equals ( groupId ) || !mvnArtifactId.equals ( artifactId ) )
            {
                // wrong group or artifact id
                continue;
            }

            if ( !snapshot && ( mvnSnapshotVersion != null || mvnVersion.endsWith ( "-SNAPSHOT" ) ) )
            {
                // we are not looking for snapshots
                continue;
            }

            final ComparableVersion v = parseVersion ( mvnVersion );
            final ComparableVersion sv = parseVersion ( mvnSnapshotVersion );

            if ( v == null )
            {
                // unable to parse v
                continue;
            }

            if ( versionFilter == null )
            {
                // no filter, add it
                arts.add ( new MavenVersionedArtifact ( sv != null ? sv : v, channelId, ai ) );
            }
            else if ( versionFilter.test ( v ) )
            {
                // filter matched, add it
                arts.add ( new MavenVersionedArtifact ( sv != null ? sv : v, channelId, ai ) );
            }
            else if ( sv != null && versionFilter.test ( sv ) )
            {
                // we have a snapshot version and it matched, add it
                arts.add ( new MavenVersionedArtifact ( sv, channelId, ai ) );
            }
        }

        return arts;
    }

Get a list of all relevant maven artifacts

@param artifactsSupplier
the supplier of artifacts
@param groupId
the group id to filter for, must not be null
@param artifactId
the artifact id to filter for, must not be null
@param snapshot
whether to consider snapshot versions of not
@param versionFilter
an optional version filter
@return a list of all matching artifacts wrapped in
{@link MavenVersionedArtifact}, if there is a snapshot version
present, then the snapshot version of used as version


private void updateOptStateAndReps() {
        int optPrev = opts[optCur].optPrev;
        assert optPrev < optCur;

        if (opts[optCur].prev1IsLiteral) {
            --optPrev;

            if (opts[optCur].hasPrev2) {
                opts[optCur].state.set(opts[opts[optCur].optPrev2].state);
                if (opts[optCur].backPrev2 < REPS)
                    opts[optCur].state.updateLongRep();
                else
                    opts[optCur].state.updateMatch();
            } else {
                opts[optCur].state.set(opts[optPrev].state);
            }

            opts[optCur].state.updateLiteral();
        } else {
            opts[optCur].state.set(opts[optPrev].state);
        }

        if (optPrev == optCur - 1) {
            // Must be either a short rep or a literal.
            assert opts[optCur].backPrev == 0 || opts[optCur].backPrev == -1;

            if (opts[optCur].backPrev == 0)
                opts[optCur].state.updateShortRep();
            else
                opts[optCur].state.updateLiteral();

            System.arraycopy(opts[optPrev].reps, 0,
                             opts[optCur].reps, 0, REPS);
        } else {
            int back;
            if (opts[optCur].prev1IsLiteral && opts[optCur].hasPrev2) {
                optPrev = opts[optCur].optPrev2;
                back = opts[optCur].backPrev2;
                opts[optCur].state.updateLongRep();
            } else {
                back = opts[optCur].backPrev;
                if (back < REPS)
                    opts[optCur].state.updateLongRep();
                else
                    opts[optCur].state.updateMatch();
            }

            if (back < REPS) {
                opts[optCur].reps[0] = opts[optPrev].reps[back];

                int rep;
                for (rep = 1; rep <= back; ++rep)
                    opts[optCur].reps[rep] = opts[optPrev].reps[rep - 1];

                for (; rep < REPS; ++rep)
                    opts[optCur].reps[rep] = opts[optPrev].reps[rep];
            } else {
                opts[optCur].reps[0] = back - REPS;
                System.arraycopy(opts[optPrev].reps, 0,
                                 opts[optCur].reps, 1, REPS - 1);
            }
        }
    }

Updates the state and reps for the current byte in the opts array.

Updates the state and reps for the current byte in the opts array .


private void calc1BytePrices(int pos, int posState,
                                 int avail, int anyRepPrice) {
        // This will be set to true if using a literal or a short rep.
        boolean nextIsByte = false;

        int curByte = lz.getByte(0);
        int matchByte = lz.getByte(opts[optCur].reps[0] + 1);

        // Try a literal.
        int literalPrice = opts[optCur].price
                + literalEncoder.getPrice(curByte, matchByte, lz.getByte(1),
                                          pos, opts[optCur].state);
        if (literalPrice < opts[optCur + 1].price) {
            opts[optCur + 1].set1(literalPrice, optCur, -1);
            nextIsByte = true;
        }

        // Try a short rep.
        if (matchByte == curByte && (opts[optCur + 1].optPrev == optCur
                                      || opts[optCur + 1].backPrev != 0)) {
            int shortRepPrice = getShortRepPrice(anyRepPrice,
                                                 opts[optCur].state,
                                                 posState);
            if (shortRepPrice <= opts[optCur + 1].price) {
                opts[optCur + 1].set1(shortRepPrice, optCur, 0);
                nextIsByte = true;
            }
        }

        // If neither a literal nor a short rep was the cheapest choice,
        // try literal + long rep0.
        if (!nextIsByte && matchByte != curByte && avail > MATCH_LEN_MIN) {
            int lenLimit = Math.min(niceLen, avail - 1);
            int len = lz.getMatchLen(1, opts[optCur].reps[0], lenLimit);

            if (len >= MATCH_LEN_MIN) {
                nextState.set(opts[optCur].state);
                nextState.updateLiteral();
                int nextPosState = (pos + 1) & posMask;
                int price = literalPrice
                            + getLongRepAndLenPrice(0, len,
                                                    nextState, nextPosState);

                int i = optCur + 1 + len;
                while (optEnd < i)
                    opts[++optEnd].reset();

                if (price < opts[i].price)
                    opts[i].set2(price, optCur, 0);
            }
        }
    }

Calculates prices of a literal, a short rep, and literal + rep0.

Calculates prices of a literal a short rep and literal + rep0 .


private int calcLongRepPrices(int pos, int posState,
                                  int avail, int anyRepPrice) {
        int startLen = MATCH_LEN_MIN;
        int lenLimit = Math.min(avail, niceLen);

        for (int rep = 0; rep < REPS; ++rep) {
            int len = lz.getMatchLen(opts[optCur].reps[rep], lenLimit);
            if (len < MATCH_LEN_MIN)
                continue;

            while (optEnd < optCur + len)
                opts[++optEnd].reset();

            int longRepPrice = getLongRepPrice(anyRepPrice, rep,
                                               opts[optCur].state, posState);

            for (int i = len; i >= MATCH_LEN_MIN; --i) {
                int price = longRepPrice
                            + repLenEncoder.getPrice(i, posState);
                if (price < opts[optCur + i].price)
                    opts[optCur + i].set1(price, optCur, rep);
            }

            if (rep == 0)
                startLen = len + 1;

            int len2Limit = Math.min(niceLen, avail - len - 1);
            int len2 = lz.getMatchLen(len + 1, opts[optCur].reps[rep],
                                      len2Limit);

            if (len2 >= MATCH_LEN_MIN) {
                // Rep
                int price = longRepPrice
                            + repLenEncoder.getPrice(len, posState);
                nextState.set(opts[optCur].state);
                nextState.updateLongRep();

                // Literal
                int curByte = lz.getByte(len, 0);
                int matchByte = lz.getByte(0); // lz.getByte(len, len)
                int prevByte = lz.getByte(len, 1);
                price += literalEncoder.getPrice(curByte, matchByte, prevByte,
                                                 pos + len, nextState);
                nextState.updateLiteral();

                // Rep0
                int nextPosState = (pos + len + 1) & posMask;
                price += getLongRepAndLenPrice(0, len2,
                                               nextState, nextPosState);

                int i = optCur + len + 1 + len2;
                while (optEnd < i)
                    opts[++optEnd].reset();

                if (price < opts[i].price)
                    opts[i].set3(price, optCur, rep, len, 0);
            }
        }

        return startLen;
    }

private
int
calcLongRepPrices
(
int
pos
,
int
posState
,
int
avail
,
int
anyRepPrice
)
{
int
startLen
=
MATCH_LEN_MIN
;
int
lenLimit
=
Math
.
min
(
avail
,
niceLen
)
;
for
(
int
rep
=
0
;
rep
<
REPS
;
++
rep
)
{
int
len
=
lz
.
getMatchLen
(
opts
[
optCur
]
.
reps
[
rep
]
,
lenLimit
)
;
if
(
len
<
MATCH_LEN_MIN
)
continue
;
while
(
optEnd
<
optCur
+
len
)
opts
[
++
optEnd
]
.
reset
(
)
;
int
longRepPrice
=
getLongRepPrice
(
anyRepPrice
,
rep
,
opts
[
optCur
]
.
state
,
posState
)
;
for
(
int
i
=
len
;
i
>=
MATCH_LEN_MIN
;
i
)
{
int
price
=
longRepPrice
+
repLenEncoder
.
getPrice
(
i
,
posState
)
;
if
(
price
<
opts
[
optCur
+
i
]
.
price
)
opts
[
optCur
+
i
]
.
set1
(
price
,
optCur
,
rep
)
;
}
if
(
rep
==
0
)
startLen
=
len
+
1
;
int
len2Limit
=
Math
.
min
(
niceLen
,
avail
len
1
)
;
int
len2
=
lz
.
getMatchLen
(
len
+
1
,
opts
[
optCur
]
.
reps
[
rep
]
,
len2Limit
)
;
if
(
len2
>=
MATCH_LEN_MIN
)
{
// Rep
int
price
=
longRepPrice
+
repLenEncoder
.
getPrice
(
len
,
posState
)
;
nextState
.
set
(
opts
[
optCur
]
.
state
)
;
nextState
.
updateLongRep
(
)
;
// Literal
int
curByte
=
lz
.
getByte
(
len
,
0
)
;
int
matchByte
=
lz
.
getByte
(
0
)
;
// lz.getByte(len, len)
int
prevByte
=
lz
.
getByte
(
len
,
1
)
;
price
+=
literalEncoder
.
getPrice
(
curByte
,
matchByte
,
prevByte
,
pos
+
len
,
nextState
)
;
nextState
.
updateLiteral
(
)
;
// Rep0
int
nextPosState
=
(
pos
+
len
+
1
)
&
posMask
;
price
+=
getLongRepAndLenPrice
(
0
,
len2
,
nextState
,
nextPosState
)
;
int
i
=
optCur
+
len
+
1
+
len2
;
while
(
optEnd
<
i
)
opts
[
++
optEnd
]
.
reset
(
)
;
if
(
price
<
opts
[
i
]
.
price
)
opts
[
i
]
.
set3
(
price
,
optCur
,
rep
,
len
,
0
)
;
}
}
return
startLen
;
}

Calculates prices of long rep and long rep + literal + rep0.

Calculates prices of long rep and long rep + literal + rep0 .


private void calcNormalMatchPrices(int pos, int posState, int avail,
                                       int anyMatchPrice, int startLen) {
        // If the longest match is so long that it would not fit into
        // the opts array, shorten the matches.
        if (matches.len[matches.count - 1] > avail) {
            matches.count = 0;
            while (matches.len[matches.count] < avail)
                ++matches.count;

            matches.len[matches.count++] = avail;
        }

        if (matches.len[matches.count - 1] < startLen)
            return;

        while (optEnd < optCur + matches.len[matches.count - 1])
            opts[++optEnd].reset();

        int normalMatchPrice = getNormalMatchPrice(anyMatchPrice,
                                                   opts[optCur].state);

        int match = 0;
        while (startLen > matches.len[match])
            ++match;

        for (int len = startLen; ; ++len) {
            int dist = matches.dist[match];

            // Calculate the price of a match of len bytes from the nearest
            // possible distance.
            int matchAndLenPrice = getMatchAndLenPrice(normalMatchPrice,
                                                       dist, len, posState);
            if (matchAndLenPrice < opts[optCur + len].price)
                opts[optCur + len].set1(matchAndLenPrice,
                                        optCur, dist + REPS);

            if (len != matches.len[match])
                continue;

            // Try match + literal + rep0. First get the length of the rep0.
            int len2Limit = Math.min(niceLen, avail - len - 1);
            int len2 = lz.getMatchLen(len + 1, dist, len2Limit);

            if (len2 >= MATCH_LEN_MIN) {
                nextState.set(opts[optCur].state);
                nextState.updateMatch();

                // Literal
                int curByte = lz.getByte(len, 0);
                int matchByte = lz.getByte(0); // lz.getByte(len, len)
                int prevByte = lz.getByte(len, 1);
                int price = matchAndLenPrice
                        + literalEncoder.getPrice(curByte, matchByte,
                                                  prevByte, pos + len,
                                                  nextState);
                nextState.updateLiteral();

                // Rep0
                int nextPosState = (pos + len + 1) & posMask;
                price += getLongRepAndLenPrice(0, len2,
                                               nextState, nextPosState);

                int i = optCur + len + 1 + len2;
                while (optEnd < i)
                    opts[++optEnd].reset();

                if (price < opts[i].price)
                    opts[i].set3(price, optCur, dist + REPS, len, 0);
            }

            if (++match == matches.count)
                break;
        }
    }

Calculates prices of a normal match and normal match + literal + rep0.

Calculates prices of a normal match and normal match + literal + rep0 .


private void expectedByte(int position, int count)
        throws UTFDataFormatException {

        throw new UTFDataFormatException(
                Localizer.getMessage("jsp.error.xml.expectedByte",
				     Integer.toString(position),
				     Integer.toString(count)));

    }

private void expectedByte ( int position , int count ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( "jsp.error.xml.expectedByte" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }


private void invalidByte(int position, int count, int c)
        throws UTFDataFormatException {

        throw new UTFDataFormatException(
                Localizer.getMessage("jsp.error.xml.invalidByte",
				     Integer.toString(position),
				     Integer.toString(count)));
    }

private void invalidByte ( int position , int count , int c ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( "jsp.error.xml.invalidByte" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }


private void scanTlds() throws JasperException {

        mappings = new HashMap<String, String[]>();

        // Make a local copy of the system jar cache
        jarTldCacheLocal.putAll(jarTldCache);

        try {
            processWebDotXml();
            scanJars();
            processTldsInFileSystem("/WEB-INF/");
        } catch (JasperException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new JasperException(
                Localizer.getMessage("jsp.error.internal.tldinit"),
                ex);
        }
    }

Scan the all the tlds accessible in the web app.
For performance reasons, this is done in two stages.  At servlet
initialization time, we only scan the jar files for listeners.  The
container passes a list of system jar files that are known to contain
tlds with listeners.  The rest of the jar files will be scanned when
a JSP page with a tld referenced is compiled.

Scan the all the tlds accessible in the web app . For performance reasons this is done in two stages . At servlet initialization time we only scan the jar files for listeners . The container passes a list of system jar files that are known to contain tlds with listeners . The rest of the jar files will be scanned when a JSP page with a tld referenced is compiled .


private TldInfo scanTld(String resourcePath, String entryName,
                         InputStream stream)
                throws JasperException {
        try {
            // Parse the tag library descriptor at the specified resource path
            TreeNode tld = new ParserUtils().parseXMLDocument(
                                resourcePath, stream, isValidationEnabled);

            String uri = null;
            TreeNode uriNode = tld.findChild("uri");
            if (uriNode != null) {
                uri = uriNode.getBody();
            }

            ArrayList<String> listeners = new ArrayList<String>();

            Iterator<TreeNode>listenerNodes = tld.findChildren("listener");
            while (listenerNodes.hasNext()) {
                TreeNode listener = listenerNodes.next();
                TreeNode listenerClass = listener.findChild("listener-class");
                if (listenerClass != null) {
                    String listenerClassName = listenerClass.getBody();
                    if (listenerClassName != null) {
                        listeners.add(listenerClassName);
                    }
                }
            }

            return new TldInfo(uri, entryName,
                               listeners.toArray(new String[listeners.size()]));

        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (Throwable t) {
                    // do nothing
                }
            }
        }
    }

Scan the given TLD for uri and listeners elements.

@param resourcePath the resource path for the jar file or the tld file.
@param entryName If the resource path is a jar file, then the name of
the tld file in the jar, else should be null.
@param stream The input stream for the tld
@return The TldInfo for this tld

Scan the given TLD for uri and listeners elements .


public void addWrapper(String jspUri, JspServletWrapper jsw) {
        jsps.remove(jspUri);
        jsps.put(jspUri,jsw);
    }

public void addWrapper ( String jspUri , JspServletWrapper jsw ) { jsps . remove ( jspUri ) ; jsps . put ( jspUri , jsw ) ; }

Add a new JspServletWrapper.

@param jspUri JSP URI
@param jsw Servlet wrapper for JSP


public ClassLoader getParentClassLoader() {
        ClassLoader parentClassLoader =
                Thread.currentThread().getContextClassLoader();
        if (parentClassLoader == null) {
            parentClassLoader = this.getClass().getClassLoader();
        }
        return parentClassLoader;
    }

public ClassLoader getParentClassLoader ( ) { ClassLoader parentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( parentClassLoader == null ) { parentClassLoader = this . getClass ( ) . getClassLoader ( ) ; } return parentClassLoader ; }

Get the parent class loader.

@return ClassLoader parent


public void setBytecode(String name, byte[] bytecode) {
        if (bytecode == null) {
            bytecodes.remove(name);
            bytecodeBirthTimes.remove(name);
            return;
        }
        bytecodes.put(name, bytecode);
        bytecodeBirthTimes.put(name, Long.valueOf(System.currentTimeMillis()));
    }

public void setBytecode ( String name , byte [ ] bytecode ) { if ( bytecode == null ) { bytecodes . remove ( name ) ; bytecodeBirthTimes . remove ( name ) ; return ; } bytecodes . put ( name , bytecode ) ; bytecodeBirthTimes . put ( name , Long . valueOf ( System . currentTimeMillis ( ) ) ) ; }

Save the bytecode for the class in a map.  The current time is noted.
@param name The name of the class
@param bytecode The bytecode in byte array

Save the bytecode for the class in a map . The current time is noted .


public long getBytecodeBirthTime(String name) {
        Long time = bytecodeBirthTimes.get(name);
        return (time != null? time.longValue(): 0);
    }

public long getBytecodeBirthTime ( String name ) { Long time = bytecodeBirthTimes . get ( name ) ; return ( time != null ? time . longValue ( ) : 0 ) ; }

Retrieve the time the bytecode for a class was created


public void saveBytecode(String className, String classFileName) {
        byte[] bytecode = getBytecode(className);
        if (bytecode != null) {
            try {
                FileOutputStream fos = new FileOutputStream(classFileName);
                fos.write(bytecode);
                fos.close();
            } catch (IOException ex) {
                context.log("Error in saving bytecode for " + className +
                    " to " + classFileName, ex);
            }
        }
    }

public
void
saveBytecode
(
String
className
,
String
classFileName
)
{
byte
[
]
bytecode
=
getBytecode
(
className
)
;
if
(
bytecode
!=
)
{
try
{
FileOutputStream
fos
=
new
FileOutputStream
(
classFileName
)
;
fos
.
write
(
bytecode
)
;
fos
.
close
(
)
;
}
catch
(
IOException
ex
)
{
context
.
log
(
"Error in saving bytecode for "
+
className
+
" to "
+
classFileName
,
ex
)
;
}
}
}


private void checkCompile() {
        for (JspServletWrapper jsw: jsps.values()) {
            if (jsw.isTagFile()) {
                // Skip tag files in background compiliations, since modified
                // tag files will be recompiled anyway when their client JSP
                // pages are compiled.  This also avoids problems when the
                // tag files and their clients are not modified simultaneously.
                continue;
            }

            JspCompilationContext ctxt = jsw.getJspEngineContext();
            // JspServletWrapper also synchronizes on this when
            // it detects it has to do a reload
            synchronized(jsw) {
                try {
                    ctxt.compile();
                } catch (FileNotFoundException ex) {
                    ctxt.incrementRemoved();
                } catch (Throwable t) {
                    jsw.getServletContext().log(
                        Localizer.getMessage("jsp.error.background.compile"),
                        t);
                }
            }
        }
    }

Method used by background thread to check the JSP dependencies
registered with this class for JSP's.

Method used by background thread to check the JSP dependencies registered with this class for JSP s .


private void initClassPath() {

        /* Classpath can be specified in one of two ways, depending on
           whether the compilation is embedded or invoked from Jspc.
           1. Calculated by the web container, and passed to Jasper in the
              context attribute.
           2. Jspc directly invoke JspCompilationContext.setClassPath, in
              case the classPath initialzed here is ignored.
        */

        StringBuilder cpath = new StringBuilder();
        String sep = System.getProperty("path.separator");

	cpath.append(options.getScratchDir() + sep);

        String cp = (String) context.getAttribute(Constants.SERVLET_CLASSPATH);
        if (cp == null || cp.equals("")) {
            cp = options.getClassPath();
        }

        if (cp != null) {
            classpath = cpath.toString() + cp;
        }

        // START GlassFish Issue 845
        if (classpath != null) {
            try {
                classpath = URLDecoder.decode(classpath, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                if (log.isLoggable(Level.FINE))
                    log.log(Level.FINE,
                            "Exception decoding classpath : " + classpath, e);
            }
        }
        // END GlassFish Issue 845
    }

Method used to initialize classpath for compiles.

Method used to initialize classpath for compiles .


protected void threadStart() {

        // Has the background thread already been started?
        if (thread != null) {
            return;
        }

        // Start the background thread
        threadDone = false;
        thread = new Thread(this, threadName);
        thread.setDaemon(true);
        thread.start();

    }

Start the background thread that will periodically check for
changes to compile time included files in a JSP.

@exception IllegalStateException if we should not be starting
a background thread now

Start the background thread that will periodically check for changes to compile time included files in a JSP .


protected void threadStop() {

        if (thread == null) {
            return;
        }

        threadDone = true;
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            ;
        }

        thread = null;

    }

protected void threadStop ( ) { if ( thread == null ) { return ; } threadDone = true ; thread . interrupt ( ) ; try { thread . join ( ) ; } catch ( InterruptedException e ) { ; } thread = null ; }

Stop the background thread that is periodically checking for
changes to compile time included files in a JSP.

Stop the background thread that is periodically checking for changes to compile time included files in a JSP .


public void run() {

        // Loop until the termination semaphore is set
        while (!threadDone) {

            // Wait for our check interval
            threadSleep();

            // Check for included files which are newer than the
            // JSP which uses them.
            try {
                checkCompile();
            } catch (Throwable t) {
                t.printStackTrace();
                log.log(Level.SEVERE, Localizer
                        .getMessage("jsp.error.recompile"), t);
            }
        }

    }

The background thread that checks for changes to files
included by a JSP and flags that a recompile is required.

The background thread that checks for changes to files included by a JSP and flags that a recompile is required .


private Optional<ChannelInstance> findByName ( final String name )
    {
        if ( name == null )
        {
            return empty ();
        }

        final String id = this.manager.accessCall ( KEY_STORAGE, ChannelServiceAccess.class, channels -> {
            return channels.mapToId ( name );
        } );

        return findById ( id );
    }

private Optional < ChannelInstance > findByName ( final String name ) { if ( name == null ) { return empty ( ) ; } final String id = this . manager . accessCall ( KEY_STORAGE , ChannelServiceAccess . class , channels -> { return channels . mapToId ( name ) ; } ) ; return findById ( id ) ; }

Find a channel by name

@param name
the channel name to look for
@return the optional channel entry, never returns {@code null} but my
return {@link Optional#empty()}.


private ChannelInstance findChannel ( final By by )
    {
        final Optional<ChannelInstance> channel;
        try ( Locked l = lock ( this.readLock ) )
        {
            channel = find ( by );
        }

        if ( !channel.isPresent () )
        {
            throw new ChannelNotFoundException ( by.toString () );
        }

        return channel.get ();
    }

private ChannelInstance findChannel ( final By by ) { final Optional < ChannelInstance > channel ; try ( Locked l = lock ( this . readLock ) ) { channel = find ( by ) ; } if ( ! channel . isPresent ( ) ) { throw new ChannelNotFoundException ( by . toString ( ) ) ; } return channel . get ( ) ; }

Find a channel

@param by
the search criteria
@return the found channel, never returns {@code null}
@throws ChannelNotFoundException
if there was no channel found


private void updateDeployGroupCache ( final ChannelServiceAccess model )
    {
        // this will simply rebuild the complete map

        // clear first
        this.deployKeysMap.clear ();

        // fill afterwards
        for ( final Map.Entry<String, Set<String>> entry : model.getDeployGroupMap ().entrySet () )
        {
            final String channelId = entry.getKey ();
            final List<DeployGroup> groups = entry.getValue ().stream ().map ( groupId -> model.getDeployGroup ( groupId ) ).collect ( Collectors.toList () );
            this.deployKeysMap.putAll ( channelId, groups );
        }
    }

Update the channel to deploy group cache map

@param model
the model to fill the cache from


@Override
    public List<DeployGroup> listGroups ( final int position, final int count )
    {
        return this.manager.accessCall ( KEY_STORAGE, ChannelServiceAccess.class, model -> {
            return split ( model.getDeployGroups (), position, count );
        } );
    }

@ Override public List < DeployGroup > listGroups ( final int position , final int count ) { return this . manager . accessCall ( KEY_STORAGE , ChannelServiceAccess . class , model -> { return split ( model . getDeployGroups ( ) , position , count ) ; } ) ; }


public static long copy ( final InputStream in, final OutputStream out ) throws IOException
    {
        Objects.requireNonNull ( in );
        Objects.requireNonNull ( out );

        final byte[] buffer = new byte[COPY_BUFFER_SIZE];
        long result = 0;

        int rc;
        while ( ( rc = in.read ( buffer ) ) >= 0 )
        {
            result += rc;
            out.write ( buffer, 0, rc );
        }

        return result;
    }

public static long copy ( final InputStream in , final OutputStream out ) throws IOException { Objects . requireNonNull ( in ) ; Objects . requireNonNull ( out ) ; final byte [ ] buffer = new byte [ COPY_BUFFER_SIZE ] ; long result = 0 ; int rc ; while ( ( rc = in . read ( buffer ) ) >= 0 ) { result += rc ; out . write ( buffer , 0 , rc ) ; } return result ; }

Copy the remaining content of one stream to the other

@param in
the input stream
@param out
the output stream
@return the number of bytes copied
@throws IOException
if any I/O error occurs


public static Node.Nodes parse(ParserController pc,
                                   String path,
				   JspReader reader,
				   Node parent,
				   boolean isTagFile,
				   boolean directivesOnly,
				   URL jarFileUrl,
				   String pageEnc,
				   String jspConfigPageEnc,
                                   boolean isDefaultPageEncoding,
                                   boolean hasBom)
		throws JasperException {

	Parser parser = new Parser(pc, reader, isTagFile, directivesOnly,
                                   jarFileUrl, hasBom);

	Node.Root root = new Node.Root(reader.mark(), parent, false);
	root.setPageEncoding(pageEnc);
	root.setJspConfigPageEncoding(jspConfigPageEnc);
	root.setIsDefaultPageEncoding(isDefaultPageEncoding);
        root.setHasBom(hasBom);

        if (hasBom) {
            // Consume (remove) BOM, so it won't appear in page output
            char bomChar = (char) reader.nextChar();
            if (bomChar != 0xFEFF) {
                parser.err.jspError(
                        reader.mark(),
                        "jsp.error.invalidBom",
                        Integer.toHexString(bomChar).toUpperCase());
            }
        }

	if (directivesOnly) {
	    parser.parseTagFileDirectives(root);
	    return new Node.Nodes(root);
	}

	// For the Top level page, add inlcude-prelude and include-coda
	PageInfo pageInfo = pc.getCompiler().getPageInfo();
	if (parent == null) {
	    parser.addInclude(root, pageInfo.getIncludePrelude());
	}
	while (reader.hasMoreInput()) {
	    parser.parseElements(root);
	}
	if (parent == null) {
	    parser.addInclude(root, pageInfo.getIncludeCoda());
	    parser.pageInfo.setRootPath(path);
	}

	Node.Nodes page = new Node.Nodes(root);
	return page;
    }

The main entry for Parser

@param pc The ParseController, use for getting other objects in compiler
and for parsing included pages
@param reader To read the page
@param parent The parent node to this page, null for top level page
@return list of nodes representing the parsed page


public static Attributes parseAttributes(ParserController pc,
					     JspReader reader)
		throws JasperException {
	Parser tmpParser = new Parser(pc, reader, false, false, null, false);
	return tmpParser.parseAttributes();
    }

public static Attributes parseAttributes ( ParserController pc , JspReader reader ) throws JasperException { Parser tmpParser = new Parser ( pc , reader , false , false , null , false ) ; return tmpParser . parseAttributes ( ) ; }

Parse Attributes for a reader, provided for external use

Parse Attributes for a reader provided for external use


private String parseQuoted(String tx) {
	StringBuilder buf = new StringBuilder();
	int size = tx.length();
	int i = 0;
	while (i < size) {
	    char ch = tx.charAt(i);
	    if (ch == '&') {
		if (i+5 < size && tx.charAt(i+1) == 'a'
		        && tx.charAt(i+2) == 'p' && tx.charAt(i+3) == 'o'
		        && tx.charAt(i+4) == 's' && tx.charAt(i+5) == ';') {
		    buf.append('\'');
		    i += 6;
		} else if (i+5 < size && tx.charAt(i+1) == 'q'
			   && tx.charAt(i+2) == 'u' && tx.charAt(i+3) == 'o'
			   && tx.charAt(i+4) == 't' && tx.charAt(i+5) == ';') {
		    buf.append('"');
		    i += 6;
		} else {
		    buf.append(ch);
		    ++i;
		}
	    } else if (ch == '\\' && i+1 < size) {
		ch = tx.charAt(i+1);
		if (ch == '\\' || ch == '\"' || ch == '\'' || ch == '>') {
		    buf.append(ch);
		    i += 2;
		} else {
		    buf.append('\\');
		    ++i;
		}
	    } else {
		buf.append(ch);
		++i;
	    }
	}
	return buf.toString();
    }

private String parseQuoted ( String tx ) { StringBuilder buf = new StringBuilder ( ) ; int size = tx . length ( ) ; int i = 0 ; while ( i < size ) { char ch = tx . charAt ( i ) ; if ( ch == ' ' ) { if ( i + 5 < size && tx . charAt ( i + 1 ) == ' ' && tx . charAt ( i + 2 ) == ' ' && tx . charAt ( i + 3 ) == ' ' && tx . charAt ( i + 4 ) == ' ' && tx . charAt ( i + 5 ) == ' ' ) { buf . append ( ' ' ) ; i += 6 ; } else if ( i + 5 < size && tx . charAt ( i + 1 ) == ' ' && tx . charAt ( i + 2 ) == ' ' && tx . charAt ( i + 3 ) == ' ' && tx . charAt ( i + 4 ) == ' ' && tx . charAt ( i + 5 ) == ' ' ) { buf . append ( ' ' ) ; i += 6 ; } else { buf . append ( ch ) ; ++ i ; } } else if ( ch == ' ' && i + 1 < size ) { ch = tx . charAt ( i + 1 ) ; if ( ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { buf . append ( ch ) ; i += 2 ; } else { buf . append ( ' ' ) ; ++ i ; } } else { buf . append ( ch ) ; ++ i ; } } return buf . toString ( ) ; }


private void addInclude(Node parent, List files) throws JasperException {
        if( files != null ) {
            Iterator iter = files.iterator();
            while (iter.hasNext()) {
                String file = (String) iter.next();
                AttributesImpl attrs = new AttributesImpl();
                attrs.addAttribute("", "file", "file", "CDATA", file);

                // Create a dummy Include directive node
                Node includeNode = new Node.IncludeDirective(attrs,
                    reader.mark(), parent);
                processIncludeDirective(file, includeNode);
            }
        }
    }

Add a list of files.  This is used for implementing include-prelude
and include-coda of jsp-config element in web.xml

Add a list of files . This is used for implementing include - prelude and include - coda of jsp - config element in web . xml


private boolean parseJspAttributeAndBody( Node parent, String tag,
        String bodyType )
        throws JasperException
    {
        boolean result = false;

        if( reader.matchesOptionalSpacesFollowedBy( "<jsp:attribute" ) ) {
            // May be an EmptyBody, depending on whether
            // There's a "<jsp:body" before the ETag

            // First, parse <jsp:attribute> elements:
            parseNamedAttributes( parent );

            result = true;
        }

        if( reader.matchesOptionalSpacesFollowedBy( "<jsp:body" ) ) {
            // ActionBody
            parseJspBody( parent, bodyType );
            reader.skipSpaces();
            if( !reader.matchesETag( tag ) ) {
                err.jspError(reader.mark(), "jsp.error.unterminated",
                    "<" + tag );
            }

            result = true;
        }
        else if( result && !reader.matchesETag( tag ) ) {
            // If we have <jsp:attribute> but something other than
            // <jsp:body> or the end tag, translation error.
            err.jspError(reader.mark(), "jsp.error.jspbody.required",
                "<" + tag );
        }

        return result;
    }

Attempts to parse 'JspAttributeAndBody' production.  Returns true if
it matched, or false if not.  Assumes EmptyBody is okay as well.

JspAttributeAndBody ::=
( '>' # S? ( '<jsp:attribute' NamedAttributes )?
'<jsp:body'
( JspBodyBody | <TRANSLATION_ERROR> )
S? ETag
)

Attempts to parse JspAttributeAndBody production . Returns true if it matched or false if not . Assumes EmptyBody is okay as well .


public void addAttribute(String name, String value) {

        if (attributes == null)
            attributes = new HashMap<String, String>();
        attributes.put(name, value);

    }

public void addAttribute ( String name , String value ) { if ( attributes == null ) attributes = new HashMap < String , String > ( ) ; attributes . put ( name , value ) ; }

Add an attribute to this node, replacing any existing attribute
with the same name.

@param name The attribute name to add
@param value The new attribute value

Add an attribute to this node replacing any existing attribute with the same name .


public void addChild(TreeNode node) {

        if (children == null)
            children = new ArrayList<TreeNode>();
        children.add(node);

    }

public void addChild ( TreeNode node ) { if ( children == null ) children = new ArrayList < TreeNode > ( ) ; children . add ( node ) ; }

Add a new child node to this node.

@param node The new child node


public Iterator<String> findAttributes() {

        Set<String> attrs;
        if (attributes == null)
            attrs = Collections.emptySet();
        else
            attrs = attributes.keySet();
        return attrs.iterator();

    }

public Iterator < String > findAttributes ( ) { Set < String > attrs ; if ( attributes == null ) attrs = Collections . emptySet ( ) ; else attrs = attributes . keySet ( ) ; return attrs . iterator ( ) ; }

Return an Iterator of the attribute names of this node.  If there are
no attributes, an empty Iterator is returned.

Return an Iterator of the attribute names of this node . If there are no attributes an empty Iterator is returned .


public Iterator<TreeNode> findChildren() {

        List<TreeNode> nodes;
        if (children == null)
            nodes = Collections.emptyList();
        else
            nodes = children;
        return nodes.iterator();
    }

public Iterator < TreeNode > findChildren ( ) { List < TreeNode > nodes ; if ( children == null ) nodes = Collections . emptyList ( ) ; else nodes = children ; return nodes . iterator ( ) ; }

Return an Iterator of all children of this node.  If there are no
children, an empty Iterator is returned.

Return an Iterator of all children of this node . If there are no children an empty Iterator is returned .


public Iterator<TreeNode> findChildren(String name) {

        List<TreeNode> results;
        if (children == null)
            results = Collections.emptyList();
        else {
            results = new ArrayList<TreeNode>();
            for (TreeNode item: children) {
                if (name.equals(item.getName()))
                    results.add(item);
            }
        }
        return results.iterator();
    }

public Iterator < TreeNode > findChildren ( String name ) { List < TreeNode > results ; if ( children == null ) results = Collections . emptyList ( ) ; else { results = new ArrayList < TreeNode > ( ) ; for ( TreeNode item : children ) { if ( name . equals ( item . getName ( ) ) ) results . add ( item ) ; } } return results . iterator ( ) ; }

Return an Iterator over all children of this node that have the
specified name.  If there are no such children, an empty Iterator
is returned.

@param name Name used to select children

Return an Iterator over all children of this node that have the specified name . If there are no such children an empty Iterator is returned .


public MavenCoordinates toBase ()
    {
        if ( this.classifier == null && this.extension == null )
        {
            return this;
        }

        return new MavenCoordinates ( this.groupId, this.artifactId, this.version );
    }

public MavenCoordinates toBase ( ) { if ( this . classifier == null && this . extension == null ) { return this ; } return new MavenCoordinates ( this . groupId , this . artifactId , this . version ) ; }

Create a new instance without classifier and extension


private String findAlias(String varName) {

	if (aliases == null)
	    return varName;

	String alias = aliases.get(varName);
	if (alias == null) {
	    return varName;
	}
	return alias;
    }

private String findAlias ( String varName ) { if ( aliases == null ) return varName ; String alias = aliases . get ( varName ) ; if ( alias == null ) { return varName ; } return alias ; }

Checks to see if the given variable name is used as an alias, and if so,
returns the variable name for which it is used as an alias.

@param varName The variable name to check
@return The variable name for which varName is used as an alias, or
varName if it is not being used as an alias

Checks to see if the given variable name is used as an alias and if so returns the variable name for which it is used as an alias .


public static void setThread() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        data.set(baos);
        streams.set(new PrintStream(baos));
    }

public static void setThread ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; data . set ( baos ) ; streams . set ( new PrintStream ( baos ) ) ; }


public static String unsetThread() {
        ByteArrayOutputStream baos =
            (ByteArrayOutputStream) data.get();
        if (baos == null) {
            return null;
        }
        streams.set(null);
        data.set(null);
        return baos.toString();
    }

public static String unsetThread ( ) { ByteArrayOutputStream baos = ( ByteArrayOutputStream ) data . get ( ) ; if ( baos == null ) { return null ; } streams . set ( null ) ; data . set ( null ) ; return baos . toString ( ) ; }

Stop capturing thread's output and return captured data as a String.

Stop capturing thread s output and return captured data as a String .


protected PrintStream findStream() {
        PrintStream ps = (PrintStream) streams.get();
        if (ps == null) {
            ps = wrapped;
        }
        return ps;
    }

protected PrintStream findStream ( ) { PrintStream ps = ( PrintStream ) streams . get ( ) ; if ( ps == null ) { ps = wrapped ; } return ps ; }

Find PrintStream to which the output must be written to.

Find PrintStream to which the output must be written to .


protected static void writeOptional ( final StringWriter writer, final String fieldName, final String value )
    {
        if ( value != null )
        {
            write ( writer, fieldName, value );
        }
    }

protected static void writeOptional ( final StringWriter writer , final String fieldName , final String value ) { if ( value != null ) { write ( writer , fieldName , value ) ; } }

Write field only when the value is set

@param writer
the writer to use
@param fieldName
the name of field
@param value
the value


protected static void write ( final StringWriter writer, final String fieldName, final String value )
    {
        writer.write ( fieldName + ": " + value + "\n" );
    }

protected
static
void
write
(
final
StringWriter
writer
,
final
String
fieldName
,
final
String
value
)
{
writer
.
write
(
fieldName
+
": "
+
value
+
"\n"
)
;
}

Write a field

@param writer
the writer to use
@param fieldName
the field name
@param value
the value, should not be null since this would
cause the string <q>null</q> in the file.


public static Element addElement ( final Element parent, final String name )
    {
        final Element ele = parent.getOwnerDocument ().createElement ( name );
        parent.appendChild ( ele );
        return ele;
    }

public static Element addElement ( final Element parent , final String name ) { final Element ele = parent . getOwnerDocument ( ) . createElement ( name ) ; parent . appendChild ( ele ) ; return ele ; }

Create a new element and add it as the last child

@param parent
the parent of the new element
@param name
the name of the element
@return the new element


public static Element addElementFirst ( final Element parent, final String name )
    {
        final Element ele = parent.getOwnerDocument ().createElement ( name );
        parent.insertBefore ( ele, null );
        return ele;
    }

public static Element addElementFirst ( final Element parent , final String name ) { final Element ele = parent . getOwnerDocument ( ) . createElement ( name ) ; parent . insertBefore ( ele , null ) ; return ele ; }

Create a new element and add it as the first child

@param parent
the parent to which to add the element
@param name
the name of the element
@return the new element


public void writeOut(Writer out) throws IOException {
	if (writer == null) {
	    out.write(cb, 0, nextChar);
	    // Flush not called as the writer passed could be a BodyContent and
	    // it doesn't allow to flush.
	}
    }

Write the contents of this BodyJspWriter into a Writer.
Subclasses are likely to do interesting things with the
implementation so some things are extra efficient.

@param out The writer into which to place the contents of this body
evaluation

Write the contents of this BodyJspWriter into a Writer . Subclasses are likely to do interesting things with the implementation so some things are extra efficient .


void setWriter(Writer writer) {
	this.writer = writer;
	if (writer != null) {
	    // According to the spec, the JspWriter returned by
	    // JspContext.pushBody(java.io.Writer writer) must behave as
	    // though it were unbuffered. This means that its getBufferSize()
	    // must always return 0. The implementation of
	    // JspWriter.getBufferSize() returns the value of JspWriter's
	    // 'bufferSize' field, which is inherited by this class.
	    // Therefore, we simply save the current 'bufferSize' (so we can
	    // later restore it should this BodyContentImpl ever be reused by
	    // a call to PageContext.pushBody()) before setting it to 0.
	    if (bufferSize != 0) {
		bufferSizeSave = bufferSize;
		bufferSize = 0;
	    }
	} else {
	    bufferSize = bufferSizeSave;
	    clearBody();
	}
    }

Sets the writer to which all output is written.

Sets the writer to which all output is written .


private void reAllocBuff(int len) {

        if (bufferSize + len <= cb.length) {
            bufferSize = cb.length;
            return;
        }

        if (len < cb.length) {
            len = cb.length;
        }

        bufferSize = cb.length + len;
        char[] tmp = new char[bufferSize];

	System.arraycopy(cb, 0, tmp, 0, cb.length);
	cb = tmp;
	tmp = null;

    }

private void reAllocBuff ( int len ) { if ( bufferSize + len <= cb . length ) { bufferSize = cb . length ; return ; } if ( len < cb . length ) { len = cb . length ; } bufferSize = cb . length + len ; char [ ] tmp = new char [ bufferSize ] ; System . arraycopy ( cb , 0 , tmp , 0 , cb . length ) ; cb = tmp ; tmp = null ; }

Reallocates buffer since the spec requires it to be unbounded.

Reallocates buffer since the spec requires it to be unbounded .


public static void map(Compiler compiler, Node.Nodes page)
		throws JasperException {

	ELFunctionMapper map = new ELFunctionMapper();
	map.ds = new StringBuilder();
	map.ss = new StringBuilder();

	page.visit(map.new ELFunctionVisitor());

	// Append the declarations to the root node
	String ds = map.ds.toString();
	if (ds.length() > 0) {
	    Node root = page.getRoot();
	    new Node.Declaration(map.ss.toString(), null, root);
	    new Node.Declaration("static {\n" + ds + "}\n", null, root);
	}
    }

Creates the functions mappers for all EL expressions in the JSP page.

@param compiler Current compiler, mainly for accessing error dispatcher.
@param page The current compilation unit.

Creates the functions mappers for all EL expressions in the JSP page .


private static State getSameParent ( final State parent, final MetaKey key )
    {
        State current = parent;
        while ( current != null )
        {
            if ( current.key.equals ( key ) )
            {
                return current;
            }

            current = current.parent;
        }
        return null;
    }

private static State getSameParent ( final State parent , final MetaKey key ) { State current = parent ; while ( current != null ) { if ( current . key . equals ( key ) ) { return current ; } current = current . parent ; } return null ; }

Traverse up from the provided parent and find the first which uses the
same key

@param parent
the first parent candidate
@param key
the key to look for
@return the first parent (which may be the input parameter), which uses
the same key


public StorageRegistration registerModel ( final long lockPriority, final MetaKey key, final StorageModelProvider<?, ?> storageProvider ) throws ModelInitializationException
    {
        this.modelLock.writeLock ().lock ();
        try
        {
            testClosed ();

            if ( this.modelKeyMap.containsKey ( key ) )
            {
                throw new IllegalArgumentException ( String.format ( "A provider for '%s' is already registered", key ) );
            }

            try
            {
                storageProvider.start ( this.context );
            }
            catch ( final Exception e )
            {
                throw new ModelInitializationException ( "Failed to start model provider: " + key, e );
            }

            final long id = this.counter++;

            final Entry entry = new Entry ( id, lockPriority, key, storageProvider );

            this.modelIdMap.put ( id, entry );
            this.modelKeyMap.put ( key, entry );

            return new StorageRegistration () {

                @Override
                public void unregister ()
                {
                    unregisterModel ( id );
                }
            };
        }
        finally
        {
            this.modelLock.writeLock ().unlock ();
        }
    }

Register a new model with the storage manager

@param lockPriority
the priority of the lock, lower numbers must be locked before
higher numbers
@param key
the model key
@param storageProvider
the storage provider
@return a handle for unregistering the model
@throws ModelInitializationException
if the {@link StorageModelProvider#start(StorageContext)}
method fails


public boolean stream ( final MetaKey key, final IOConsumer<InputStream> consumer ) throws IOException
    {
        return streamFrom ( this.dataPath, key, consumer );
    }

public boolean stream ( final MetaKey key , final IOConsumer < InputStream > consumer ) throws IOException { return streamFrom ( this . dataPath , key , consumer ) ; }


@RequestMapping ( "/{id}/monitor" )
    public ModelAndView monitor ( @PathVariable ( "id" ) final String id)
    {
        final JobHandle job = this.manager.getJob ( id );

        if ( job != null )
        {
            logger.debug ( "Job: {} - {}", job.getId (), job.getState () );
        }
        else
        {
            logger.debug ( "No job: {}", id );
        }

        final Map<String, Object> model = new HashMap<> ( 1 );
        model.put ( "job", job );
        return new ModelAndView ( "monitor", model );
    }

@
RequestMapping
(
"/{id}/monitor"
)
public
ModelAndView
monitor
(
@
PathVariable
(
"id"
)
final
String
id
)
{
final
JobHandle
job
=
this
.
manager
.
getJob
(
id
)
;
if
(
job
!=
)
{
logger
.
debug
(
"Job: {} - {}"
,
job
.
getId
(
)
,
job
.
getState
(
)
)
;
}
else
{
logger
.
debug
(
"No job: {}"
,
id
)
;
}
final
Map
<
String
,
Object
>
model
=
new
HashMap
<>
(
1
)
;
model
.
put
(
"job"
,
job
)
;
return
new
ModelAndView
(
"monitor"
,
model
)
;
}

Monitor the job, only produces an HTML fragment of the current job state

@param id
the job id
@return the view

Monitor the job only produces an HTML fragment of the current job state


protected boolean isAuthenticated ( final By by, final HttpServletRequest request )
    {
        final String[] authToks = parseAuthorization ( request );

        if ( authToks == null )
        {
            return false;
        }

        // we don't enforce the "deploy" user name anymore

        final String deployKey = authToks[1];

        logger.debug ( "Deploy key: '{}'", deployKey );

        final ChannelService service = getService ( request );
        if ( service == null )
        {
            logger.info ( "Called 'isAuthenticated' without service" );
            return false;
        }

        return service.getChannelDeployKeyStrings ( by ).orElse ( Collections.emptySet () ).contains ( deployKey );
    }

Simply test if the request is authenticated against the channels deploy
keys

@param by
the channel locator
@param request
the request
@return true if the request could be authenticated against
the channels deploy keys, false otherwise


public void finish () throws IOException
    {
        if ( !this.finished )
        {
            this.finished = true;
            writeEnd ();
        }
        try
        {
            this.out.close ();
        }
        catch ( final XMLStreamException e )
        {
            throw new IOException ( e );
        }
    }

public void finish ( ) throws IOException { if ( ! this . finished ) { this . finished = true ; writeEnd ( ) ; } try { this . out . close ( ) ; } catch ( final XMLStreamException e ) { throw new IOException ( e ) ; } }

Complete the document but don't close the underlying writer

@throws IOException
if there is an IO error

Complete the document but don t close the underlying writer


public static Gson makeGson ( final boolean pretty )
    {
        final GsonBuilder gb = new GsonBuilder ();

        if ( pretty )
        {
            gb.setPrettyPrinting ();
        }

        gb.registerTypeAdapter ( Node.class, new NodeAdapter () );
        gb.registerTypeAdapter ( byte[].class, new ByteArrayAdapter () );

        return gb.create ();
    }

public static Gson makeGson ( final boolean pretty ) { final GsonBuilder gb = new GsonBuilder ( ) ; if ( pretty ) { gb . setPrettyPrinting ( ) ; } gb . registerTypeAdapter ( Node . class , new NodeAdapter ( ) ) ; gb . registerTypeAdapter ( byte [ ] . class , new ByteArrayAdapter ( ) ) ; return gb . create ( ) ; }

Make an appropriate Gson parser to processing ChannelData instances

@param pretty
if the gson output should be "pretty printed"
@return the new gson instance


public boolean encodeForLZMA2() {
        // LZMA2 uses RangeEncoderToBuffer so IOExceptions aren't possible.
        try {
            if (!lz.isStarted() && !encodeInit())
                return false;

            while (uncompressedSize <= LZMA2_UNCOMPRESSED_LIMIT
                    && rc.getPendingSize() <= LZMA2_COMPRESSED_LIMIT)
                if (!encodeSymbol())
                    return false;
        } catch (IOException e) {
            throw new Error();
        }

        return true;
    }

Compresses for LZMA2.

@return      true if the LZMA2 chunk became full, false otherwise


public static Map<MetaKey, String> union ( final Map<MetaKey, String> providedMetaData, final Map<MetaKey, String> extractedMetaData )
    {
        final int size1 = providedMetaData != null ? providedMetaData.size () : 0;
        final int size2 = extractedMetaData != null ? extractedMetaData.size () : 0;

        if ( size1 + size2 == 0 )
        {
            return Collections.emptyMap ();
        }

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

        if ( extractedMetaData != null )
        {
            result.putAll ( extractedMetaData );
        }

        // provided will override
        if ( providedMetaData != null )
        {
            result.putAll ( providedMetaData );
        }

        return Collections.unmodifiableMap ( result );
    }

public
static
Map
<
MetaKey
,
String
>
union
(
final
Map
<
MetaKey
,
String
>
providedMetaData
,
final
Map
<
MetaKey
,
String
>
extractedMetaData
)
{
final
int
size1
=
providedMetaData
!=
providedMetaData
.
size
(
)
:
0
;
final
int
size2
=
extractedMetaData
!=
extractedMetaData
.
size
(
)
:
0
;
if
(
size1
+
size2
==
0
)
{
return
Collections
.
emptyMap
(
)
;
}
final
Map
<
MetaKey
,
String
>
result
=
new
HashMap
<>
(
size1
+
size2
)
;
if
(
extractedMetaData
!=
)
{
result
.
putAll
(
extractedMetaData
)
;
}
// provided will override
if
(
providedMetaData
!=
)
{
result
.
putAll
(
providedMetaData
)
;
}
return
Collections
.
unmodifiableMap
(
result
)
;
}

Return an unmodifiable map of provided and extracted meta data

@param providedMetaData
the provided meta data, or code {@code null}
@param extractedMetaData
the extracted meta data, or code {@code null}
@return the union of provided and extracted meta data, never returns
{@code null}


public static Throwable getThrowable(ServletRequest request) {
	Throwable error = (Throwable) request.getAttribute(SERVLET_EXCEPTION);
	if (error == null) {
	    error = (Throwable) request.getAttribute(JSP_EXCEPTION);
	    if (error != null) {
		/*
		 * The only place that sets JSP_EXCEPTION is
		 * PageContextImpl.handlePageException(). It really should set
		 * SERVLET_EXCEPTION, but that would interfere with the
		 * ErrorReportValve. Therefore, if JSP_EXCEPTION is set, we
		 * need to set SERVLET_EXCEPTION.
		 */
		request.setAttribute(SERVLET_EXCEPTION, error);
	    }
	}

	return error;
    }

Returns the value of the javax.servlet.error.exception request
attribute value, if present, otherwise the value of the
javax.servlet.jsp.jspException request attribute value.

This method is called at the beginning of the generated servlet code
for a JSP error page, when the "exception" implicit scripting language
variable is initialized.

Returns the value of the javax . servlet . error . exception request attribute value if present otherwise the value of the javax . servlet . jsp . jspException request attribute value .


private String isCheckSum ( final Coordinates c )
    {
        final String cext = c.getExtension ();

        if ( cext == null )
        {
            return null;
        }

        for ( final String ext : this.options.getChecksumExtensions () )
        {
            if ( cext.endsWith ( "." + ext ) )
            {
                return ext;
            }
        }

        return null;
    }

private String isCheckSum ( final Coordinates c ) { final String cext = c . getExtension ( ) ; if ( cext == null ) { return null ; } for ( final String ext : this . options . getChecksumExtensions ( ) ) { if ( cext . endsWith ( "." + ext ) ) { return ext ; } } return null ; }

Check if the uploaded artifact is actually a checksum file

@param c
the extracted coordinates
@return {@code true} if the upload is definitely a checksum file,
{@code false} otherwise


public void finish() throws IOException {
        if (!finished) {
            if (exception != null)
                throw exception;

            try {
                if (expectedUncompressedSize != -1
                        && expectedUncompressedSize != currentUncompressedSize)
                    throw new XZIOException("Expected uncompressed size ("
                            + expectedUncompressedSize + ") doesn't equal "
                            + "the number of bytes written to the stream ("
                            + currentUncompressedSize + ")");

                lz.setFinishing();
                lzma.encodeForLZMA1();

                if (useEndMarker)
                    lzma.encodeLZMA1EndMarker();

                rc.finish();
            } catch (IOException e) {
                exception = e;
                throw e;
            }

            finished = true;

            lzma.putArraysToCache(arrayCache);
            lzma = null;
            lz = null;
        }
    }

Finishes the stream without closing the underlying OutputStream.

Finishes the stream without closing the underlying OutputStream .


public Exception getException() {

        Throwable t = JspRuntimeLibrary.getThrowable(request);

        // Only wrap if needed
        if((t != null) && (! (t instanceof Exception))) {
            t = new JspException(t);
        }

        return (Exception) t;
    }

public
Exception
getException
(
)
{
Throwable
t
=
JspRuntimeLibrary
.
getThrowable
(
request
)
;
// Only wrap if needed
if
(
(
t
!=
)
&&
(
!
(
t
instanceof
Exception
)
)
)
{
t
=
new
JspException
(
t
)
;
}
return
(
Exception
)
t
;
}

Returns the exception associated with this page context, if any.

Added wrapping for Throwables to avoid ClassCastException
(see Bugzilla 31171 for details).

@return The Exception associated with this page context, if any.

Returns the exception associated with this page context if any .


public static Object evaluateExpression(final String expression,
					    final Class expectedType,
					    final PageContext pageContext,
					    final ProtectedFunctionMapper functionMap)
	throws ELException
    {
	Object retValue;
        if (SecurityUtil.isPackageProtectionEnabled()){
            try {
                retValue = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<Object>(){

                    public Object run() throws Exception{
                        ELContextImpl elContext =
                            (ELContextImpl) pageContext.getELContext();
                        elContext.setFunctionMapper(functionMap);
                        ExpressionFactory expFactory = getExpressionFactory(pageContext);
                        ValueExpression expr =
                             expFactory.createValueExpression(
                                                   elContext,
                                                   expression,
                                                   expectedType);
                        return expr.getValue(elContext);
                    }
                });
            } catch (PrivilegedActionException ex) {
                Exception realEx = ex.getException();
		if (realEx instanceof ELException) {
		    throw (ELException) realEx;
		} else {
		    throw new ELException(realEx);
		}
            }
        } else {
            ELContextImpl elContext = (ELContextImpl)pageContext.getELContext();
            elContext.setFunctionMapper(functionMap);
            ExpressionFactory expFactory = getExpressionFactory(pageContext);
            ValueExpression expr = expFactory.createValueExpression(
                                           elContext,
                                           expression,
                                           expectedType);
            retValue = expr.getValue(elContext);
        }
	return retValue;
    }

public static Object evaluateExpression ( final String expression , final Class expectedType , final PageContext pageContext , final ProtectedFunctionMapper functionMap ) throws ELException { Object retValue ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { try { retValue = AccessController . doPrivileged ( new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws Exception { ELContextImpl elContext = ( ELContextImpl ) pageContext . getELContext ( ) ; elContext . setFunctionMapper ( functionMap ) ; ExpressionFactory expFactory = getExpressionFactory ( pageContext ) ; ValueExpression expr = expFactory . createValueExpression ( elContext , expression , expectedType ) ; return expr . getValue ( elContext ) ; } } ) ; } catch ( PrivilegedActionException ex ) { Exception realEx = ex . getException ( ) ; if ( realEx instanceof ELException ) { throw ( ELException ) realEx ; } else { throw new ELException ( realEx ) ; } } } else { ELContextImpl elContext = ( ELContextImpl ) pageContext . getELContext ( ) ; elContext . setFunctionMapper ( functionMap ) ; ExpressionFactory expFactory = getExpressionFactory ( pageContext ) ; ValueExpression expr = expFactory . createValueExpression ( elContext , expression , expectedType ) ; retValue = expr . getValue ( elContext ) ; } return retValue ; }

Evaluates an EL expression

@param expression The expression to be evaluated
@param expectedType The expected resulting type
@param pageContext The page context
@param functionMap Maps prefix and name to Method
@return The result of the evaluation


protected String makePrefixFromOsgiProperties ()
    {
        final String port = System.getProperty ( "org.osgi.service.http.port" );
        if ( port == null )
        {
            return null;
        }

        final StringBuilder sb = new StringBuilder ();
        sb.append ( "http://" ).append ( discoverHostname () );
        if ( !"80".equals ( port ) )
        {
            sb.append ( ':' ).append ( port );
        }
        return sb.toString ();
    }

protected String makePrefixFromOsgiProperties ( ) { final String port = System . getProperty ( "org.osgi.service.http.port" ) ; if ( port == null ) { return null ; } final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "http://" ) . append ( discoverHostname ( ) ) ; if ( ! "80" . equals ( port ) ) { sb . append ( ' ' ) . append ( port ) ; } return sb . toString ( ) ; }

Make the prefix by guessing the port from the OSGi settings


public static boolean isXml ( final Path path ) throws IOException
    {
        final XmlToolsFactory xml = Activator.getXmlToolsFactory ();
        final XMLInputFactory xin = xml.newXMLInputFactory ();

        try ( InputStream stream = new BufferedInputStream ( Files.newInputStream ( path ) ) )
        {
            try
            {
                final XMLStreamReader reader = xin.createXMLStreamReader ( stream );
                reader.next ();
                return true;
            }
            catch ( final XMLStreamException e )
            {
                return false;
            }
        }
    }

public static boolean isXml ( final Path path ) throws IOException { final XmlToolsFactory xml = Activator . getXmlToolsFactory ( ) ; final XMLInputFactory xin = xml . newXMLInputFactory ( ) ; try ( InputStream stream = new BufferedInputStream ( Files . newInputStream ( path ) ) ) { try { final XMLStreamReader reader = xin . createXMLStreamReader ( stream ) ; reader . next ( ) ; return true ; } catch ( final XMLStreamException e ) { return false ; } } }

Test if this file is an XML file

@param path
the path to check
@return true if this is an XML file
@throws IOException
if the probing fails


public static TagInfo parseTagFileDirectives(ParserController pc,
						 String name,
						 String path,
						 TagLibraryInfo tagLibInfo)
                        throws JasperException {

        ErrorDispatcher err = pc.getCompiler().getErrorDispatcher();

        Node.Nodes page = null;
        try {
            page = pc.parseTagFileDirectives(path);
        } catch (FileNotFoundException e) {
            err.jspError("jsp.error.file.not.found", path);
        } catch (IOException e) {
            err.jspError("jsp.error.file.not.found", path);
        }

        TagFileDirectiveVisitor tagFileVisitor
            = new TagFileDirectiveVisitor(pc.getCompiler(), tagLibInfo, name,
                                          path);
        page.visit(tagFileVisitor);
        tagFileVisitor.postCheck();

        return tagFileVisitor.getTagInfo();
    }

public static TagInfo parseTagFileDirectives ( ParserController pc , String name , String path , TagLibraryInfo tagLibInfo ) throws JasperException { ErrorDispatcher err = pc . getCompiler ( ) . getErrorDispatcher ( ) ; Node . Nodes page = null ; try { page = pc . parseTagFileDirectives ( path ) ; } catch ( FileNotFoundException e ) { err . jspError ( "jsp.error.file.not.found" , path ) ; } catch ( IOException e ) { err . jspError ( "jsp.error.file.not.found" , path ) ; } TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor ( pc . getCompiler ( ) , tagLibInfo , name , path ) ; page . visit ( tagFileVisitor ) ; tagFileVisitor . postCheck ( ) ; return tagFileVisitor . getTagInfo ( ) ; }

Parses the tag file, and collects information on the directives included
in it.  The method is used to obtain the info on the tag file, when the
handler that it represents is referenced.  The tag file is not compiled
here.

@param pc the current ParserController used in this compilation
@param name the tag name as specified in the TLD
@param tagfile the path for the tagfile
@param tagLibInfo the TagLibraryInfo object associated with this TagInfo
@return a TagInfo object assembled from the directives in the tag file.

Parses the tag file and collects information on the directives included in it . The method is used to obtain the info on the tag file when the handler that it represents is referenced . The tag file is not compiled here .


private Class loadTagFile(Compiler compiler,
                              String tagFilePath, TagInfo tagInfo,
                              PageInfo parentPageInfo)
        throws JasperException {

        JspCompilationContext ctxt = compiler.getCompilationContext();
        JspRuntimeContext rctxt = ctxt.getRuntimeContext();

        synchronized(rctxt) {
            JspServletWrapper wrapper =
                (JspServletWrapper) rctxt.getWrapper(tagFilePath);
            if (wrapper == null) {
                wrapper = new JspServletWrapper(ctxt.getServletContext(),
                                                ctxt.getOptions(),
                                                tagFilePath,
                                                tagInfo,
                                                ctxt.getRuntimeContext(),
                                                (URL) ctxt.getTagFileJarUrls().get(tagFilePath));
                    rctxt.addWrapper(tagFilePath,wrapper);

		// Use same classloader and classpath for compiling tag files
		wrapper.getJspEngineContext().setClassLoader(
				(URLClassLoader) ctxt.getClassLoader());
		wrapper.getJspEngineContext().setClassPath(ctxt.getClassPath());
            }
            else {
                // Make sure that JspCompilationContext gets the latest TagInfo
                // for the tag file.  TagInfo instance was created the last
                // time the tag file was scanned for directives, and the tag
                // file may have been modified since then.
                wrapper.getJspEngineContext().setTagInfo(tagInfo);
            }

            Class tagClazz;
            int tripCount = wrapper.incTripCount();
            try {
                if (tripCount > 0) {
                    // When tripCount is greater than zero, a circular
                    // dependency exists.  The circularily dependant tag
                    // file is compiled in prototype mode, to avoid infinite
                    // recursion.

                    JspServletWrapper tempWrapper
                        = new JspServletWrapper(ctxt.getServletContext(),
                                                ctxt.getOptions(),
                                                tagFilePath,
                                                tagInfo,
                                                ctxt.getRuntimeContext(),
                                                (URL) ctxt.getTagFileJarUrls().get(tagFilePath));
                    tagClazz = tempWrapper.loadTagFilePrototype();
                    tempVector.add(
                               tempWrapper.getJspEngineContext().getCompiler());
                } else {
                    tagClazz = wrapper.loadTagFile();
                }
            } finally {
                wrapper.decTripCount();
            }

            // Add the dependants for this tag file to its parent's
            // dependant list.  The only reliable dependency information
            // can only be obtained from the tag instance.
            try {
                Object tagIns = tagClazz.newInstance();
                if (tagIns instanceof JspSourceDependent) {
                    for (String dependant:
                            ((JspSourceDependent)tagIns).getDependants()) {
                        parentPageInfo.addDependant(dependant);
                    }
                }
            } catch (Exception e) {
                // ignore errors
            }

            return tagClazz;
        }
    }


public void removeProtoTypeFiles(String classFileName) {
        Iterator<Compiler> iter = tempVector.iterator();
        while (iter.hasNext()) {
            Compiler c = iter.next();
            if (classFileName == null) {
                c.removeGeneratedClassFiles();
            } else if (classFileName.equals(
                        c.getCompilationContext().getClassFileName())) {
                c.removeGeneratedClassFiles();
                tempVector.remove(c);
                return;
            }
        }
    }

public void removeProtoTypeFiles ( String classFileName ) { Iterator < Compiler > iter = tempVector . iterator ( ) ; while ( iter . hasNext ( ) ) { Compiler c = iter . next ( ) ; if ( classFileName == null ) { c . removeGeneratedClassFiles ( ) ; } else if ( classFileName . equals ( c . getCompilationContext ( ) . getClassFileName ( ) ) ) { c . removeGeneratedClassFiles ( ) ; tempVector . remove ( c ) ; return ; } } }

Removed the java and class files for the tag prototype
generated from the current compilation.
@param classFileName If non-null, remove only the class file with
with this name.

Removed the java and class files for the tag prototype generated from the current compilation .


public static void main(String arg[]) {
        if (arg.length == 0) {
           System.out.println(Localizer.getMessage("jspc.usage"));
        } else {
            JspC jspc = new JspC();
            try {
                jspc.setArgs(arg);
                if (jspc.helpNeeded) {
                    System.out.println(Localizer.getMessage("jspc.usage"));
                } else {
                    jspc.execute();
                }
            } catch (JasperException je) {
                System.err.println(je);
                //System.err.println(je.getMessage());
                if (jspc.getDieLevel() != NO_DIE_LEVEL) {
                    System.exit(jspc.getDieLevel());
                }
            }
        }
    }

public static void main ( String arg [ ] ) { if ( arg . length == 0 ) { System . out . println ( Localizer . getMessage ( "jspc.usage" ) ) ; } else { JspC jspc = new JspC ( ) ; try { jspc . setArgs ( arg ) ; if ( jspc . helpNeeded ) { System . out . println ( Localizer . getMessage ( "jspc.usage" ) ) ; } else { jspc . execute ( ) ; } } catch ( JasperException je ) { System . err . println ( je ) ; //System.err.println(je.getMessage()); if ( jspc . getDieLevel ( ) != NO_DIE_LEVEL ) { System . exit ( jspc . getDieLevel ( ) ) ; } } } }


public void setUriroot( String s ) {
        uriRoot = s;
        if (s != null) {
            try {
                uriRoot=new File( s ).getCanonicalPath();
            } catch( Exception ex ) {
                uriRoot=s;
            }
        }
    }

public void setUriroot ( String s ) { uriRoot = s ; if ( s != null ) { try { uriRoot = new File ( s ) . getCanonicalPath ( ) ; } catch ( Exception ex ) { uriRoot = s ; } } }

Base dir for the webapp. Used to generate class names and resolve
includes

Base dir for the webapp . Used to generate class names and resolve includes


public void scanFiles( File base ) throws JasperException {
        Stack<String> dirs = new Stack<String>();
        dirs.push(base.toString());
        if (extensions == null) {
            extensions = new ArrayList<String>();
            extensions.add("jsp");
            extensions.add("jspx");
        }
        while (!dirs.isEmpty()) {
            String s = dirs.pop();
            File f = new File(s);
            if (f.exists() && f.isDirectory()) {
                String[] files = f.list();
                String ext;
                for (int i = 0; (files != null) && i < files.length; i++) {
                    File f2 = new File(s, files[i]);
                    if (f2.isDirectory()) {
                        dirs.push(f2.getPath());
                    } else {
                        String path = f2.getPath();
                        String uri = path.substring(uriRoot.length());
                        ext = files[i].substring(files[i].lastIndexOf('.') +1);
                        if (extensions.contains(ext) ||
                                jspConfig.isJspPage(uri)) {
                            pages.add(path);
                        }
                    }
                }
            }
        }
    }

public void scanFiles ( File base ) throws JasperException { Stack < String > dirs = new Stack < String > ( ) ; dirs . push ( base . toString ( ) ) ; if ( extensions == null ) { extensions = new ArrayList < String > ( ) ; extensions . add ( "jsp" ) ; extensions . add ( "jspx" ) ; } while ( ! dirs . isEmpty ( ) ) { String s = dirs . pop ( ) ; File f = new File ( s ) ; if ( f . exists ( ) && f . isDirectory ( ) ) { String [ ] files = f . list ( ) ; String ext ; for ( int i = 0 ; ( files != null ) && i < files . length ; i ++ ) { File f2 = new File ( s , files [ i ] ) ; if ( f2 . isDirectory ( ) ) { dirs . push ( f2 . getPath ( ) ) ; } else { String path = f2 . getPath ( ) ; String uri = path . substring ( uriRoot . length ( ) ) ; ext = files [ i ] . substring ( files [ i ] . lastIndexOf ( ' ' ) + 1 ) ; if ( extensions . contains ( ext ) || jspConfig . isJspPage ( uri ) ) { pages . add ( path ) ; } } } } } }

Locate all jsp files in the webapp. Used if no explicit
jsps are specified.

Locate all jsp files in the webapp . Used if no explicit jsps are specified .


private void locateUriRoot( File f ) {
        String tUriBase = uriBase;
        if (tUriBase == null) {
            tUriBase = "/";
        }
        try {
            if (f.exists()) {
                f = new File(f.getCanonicalPath());
                while (f != null) {
                    File g = new File(f, "WEB-INF");
                    if (g.exists() && g.isDirectory()) {
                        uriRoot = f.getCanonicalPath();
                        uriBase = tUriBase;
			if (log.isLoggable(Level.INFO)) {
                            log.info(
                                Localizer.getMessage("jspc.implicit.uriRoot",
                                                     uriRoot));
			}
                        break;
                    }
                    if (f.exists() && f.isDirectory()) {
                        tUriBase = "/" + f.getName() + "/" + tUriBase;
                    }

                    String fParent = f.getParent();
                    if (fParent == null) {
                        break;
                    } else {
                        f = new File(fParent);
                    }

                    // If there is no acceptible candidate, uriRoot will
                    // remain null to indicate to the CompilerContext to
                    // use the current working/user dir.
                }

                if (uriRoot != null) {
                    File froot = new File(uriRoot);
                    uriRoot = froot.getCanonicalPath();
                }
            }
        } catch (IOException ioe) {
            // since this is an optional default and a null value
            // for uriRoot has a non-error meaning, we can just
            // pass straight through
        }
    }

Find the WEB-INF dir by looking up in the directory tree.
This is used if no explicit docbase is set, but only files.
XXX Maybe we should require the docbase.

Find the WEB - INF dir by looking up in the directory tree . This is used if no explicit docbase is set but only files . XXX Maybe we should require the docbase .


private ClassLoader initSystemClassLoader() throws IOException {

        String sysClassPath = getSystemClassPath();
        if (sysClassPath == null) {
            return null;
        }

        ArrayList<URL> urls = new ArrayList<URL>();
        StringTokenizer tokenizer = new StringTokenizer(sysClassPath,
                                                        File.pathSeparator);
        while (tokenizer.hasMoreTokens()) {
            urls.add(new File(tokenizer.nextToken()).toURL());
        }

        if (urls.size() == 0) {
            return null;
        }

        URL urlsArray[] = new URL[urls.size()];
        urls.toArray(urlsArray);

        return new URLClassLoader(urlsArray, this.getClass().getClassLoader());
    }

private ClassLoader initSystemClassLoader ( ) throws IOException { String sysClassPath = getSystemClassPath ( ) ; if ( sysClassPath == null ) { return null ; } ArrayList < URL > urls = new ArrayList < URL > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( sysClassPath , File . pathSeparator ) ; while ( tokenizer . hasMoreTokens ( ) ) { urls . add ( new File ( tokenizer . nextToken ( ) ) . toURL ( ) ) ; } if ( urls . size ( ) == 0 ) { return null ; } URL urlsArray [ ] = new URL [ urls . size ( ) ] ; urls . toArray ( urlsArray ) ; return new URLClassLoader ( urlsArray , this . getClass ( ) . getClassLoader ( ) ) ; }


private int movePos() {
        int avail = movePos(4, 4);

        if (avail != 0) {
            if (++lzPos == Integer.MAX_VALUE) {
                int normalizationOffset = Integer.MAX_VALUE - cyclicSize;
                hash.normalize(normalizationOffset);
                normalize(chain, cyclicSize, normalizationOffset);
                lzPos -= normalizationOffset;
            }

            if (++cyclicPos == cyclicSize)
                cyclicPos = 0;
        }

        return avail;
    }

private int movePos ( ) { int avail = movePos ( 4 , 4 ) ; if ( avail != 0 ) { if ( ++ lzPos == Integer . MAX_VALUE ) { int normalizationOffset = Integer . MAX_VALUE - cyclicSize ; hash . normalize ( normalizationOffset ) ; normalize ( chain , cyclicSize , normalizationOffset ) ; lzPos -= normalizationOffset ; } if ( ++ cyclicPos == cyclicSize ) cyclicPos = 0 ; } return avail ; }

Moves to the next byte, checks that there is enough available space,
and possibly normalizes the hash tables and the hash chain.

@return      number of bytes available, including the current byte

Moves to the next byte checks that there is enough available space and possibly normalizes the hash tables and the hash chain .


boolean matches(String string) throws JasperException {
	Mark mark = mark();
	int ch = 0;
	int i = 0;
	do {
	    ch = nextChar();
	    if (((char) ch) != string.charAt(i++)) {
		reset(mark);
		return false;
	    }
	} while (i < string.length());
	return true;
    }

boolean matches ( String string ) throws JasperException { Mark mark = mark ( ) ; int ch = 0 ; int i = 0 ; do { ch = nextChar ( ) ; if ( ( ( char ) ch ) != string . charAt ( i ++ ) ) { reset ( mark ) ; return false ; } } while ( i < string . length ( ) ) ; return true ; }

search the stream for a match to a string
@param string The string to match
@return true is one is found, the current position
in stream is positioned after the search string,
false otherwise, position in stream unchanged.


boolean matchesOptionalSpacesFollowedBy( String s )
	throws JasperException
    {
        Mark mark = mark();

        skipSpaces();
        boolean result = matches( s );
        if( !result ) {
            reset( mark );
        }

        return result;
    }

boolean matchesOptionalSpacesFollowedBy ( String s ) throws JasperException { Mark mark = mark ( ) ; skipSpaces ( ) ; boolean result = matches ( s ) ; if ( ! result ) { reset ( mark ) ; } return result ; }

Looks ahead to see if there are optional spaces followed by
the given String.  If so, true is returned and those spaces and
characters are skipped.  If not, false is returned and the
position is restored to where we were before.

Looks ahead to see if there are optional spaces followed by the given String . If so true is returned and those spaces and characters are skipped . If not false is returned and the position is restored to where we were before .


Mark skipUntil(String limit) throws JasperException {
        Mark ret = null;
        int limlen = limit.length();
        int ch;

    skip:
        for (ret = mark(), ch = nextChar() ; ch != -1 ;
                 ret = mark(), ch = nextChar()) {
            if (ch == limit.charAt(0)) {
                Mark restart = mark();
                for (int i = 1 ; i < limlen ; i++) {
                    if (peekChar() == limit.charAt(i))
                        nextChar();
                    else {
                        reset(restart);
                        continue skip;
                    }
                }
                return ret;
            }
        }
        return null;
    }

Mark skipUntil ( String limit ) throws JasperException { Mark ret = null ; int limlen = limit . length ( ) ; int ch ; skip : for ( ret = mark ( ) , ch = nextChar ( ) ; ch != - 1 ; ret = mark ( ) , ch = nextChar ( ) ) { if ( ch == limit . charAt ( 0 ) ) { Mark restart = mark ( ) ; for ( int i = 1 ; i < limlen ; i ++ ) { if ( peekChar ( ) == limit . charAt ( i ) ) nextChar ( ) ; else { reset ( restart ) ; continue skip ; } } return ret ; } } return null ; }

Skip until the given string is matched in the stream.
When returned, the context is positioned past the end of the match.

@param s The String to match.
@return A non-null Mark instance (positioned immediately
before the search string) if found, null
otherwise.

Skip until the given string is matched in the stream . When returned the context is positioned past the end of the match .


Mark skipUntilIgnoreEsc(String limit) throws JasperException {
	Mark ret = null;
	int limlen = limit.length();
	int ch;
	int prev = 'x';	// Doesn't matter

    skip:
	for (ret = mark(), ch = nextChar() ; ch != -1 ;
	         ret = mark(), prev = ch, ch = nextChar()) {
	    if (ch == '\\' && prev == '\\') {
		ch = 0;		// Double \ is not an escape char anymore
	    }
	    else if (ch == limit.charAt(0) && prev != '\\') {
		for (int i = 1 ; i < limlen ; i++) {
		    if (peekChar() == limit.charAt(i))
			nextChar();
		    else
			continue skip;
		}
		return ret;
	    }
	}
	return null;
    }

Skip until the given string is matched in the stream, but ignoring
chars initially escaped by a '\'.
When returned, the context is positioned past the end of the match.

@param s The String to match.
@return A non-null Mark instance (positioned immediately
before the search string) if found, null
otherwise.

Skip until the given string is matched in the stream but ignoring chars initially escaped by a \ . When returned the context is positioned past the end of the match .


Mark skipUntilETag(String tag) throws JasperException {
	Mark ret = skipUntil("</" + tag);
	if (ret != null) {
	    skipSpaces();
	    if (nextChar() != '>')
		ret = null;
	}
	return ret;
    }

Mark skipUntilETag ( String tag ) throws JasperException { Mark ret = skipUntil ( "</" + tag ) ; if ( ret != null ) { skipSpaces ( ) ; if ( nextChar ( ) != ' ' ) ret = null ; } return ret ; }

Skip until the given end tag is matched in the stream.
When returned, the context is positioned past the end of the tag.

@param tag The name of the tag whose ETag (</tag>) to match.
@return A non-null Mark instance (positioned immediately
before the ETag) if found, null otherwise.

Skip until the given end tag is matched in the stream . When returned the context is positioned past the end of the tag .


String parseToken(boolean quoted) throws JasperException {
	StringBuilder stringBuffer = new StringBuilder();
	skipSpaces();
	stringBuffer.setLength(0);

        if (!hasMoreInput()) {
            return "";
        }

	int ch = peekChar();

	if (quoted) {
	    if (ch == '"' || ch == '\'') {

		char endQuote = ch == '"' ? '"' : '\'';
		// Consume the open quote:
		ch = nextChar();
		for (ch = nextChar(); ch != -1 && ch != endQuote;
		         ch = nextChar()) {
		    if (ch == '\\')
			ch = nextChar();
		    stringBuffer.append((char) ch);
		}
		// Check end of quote, skip closing quote:
		if (ch == -1) {
		    err.jspError(mark(), "jsp.error.quotes.unterminated");
		}
	    } else {
		err.jspError(mark(), "jsp.error.attr.quoted");
	    }
	} else {
	    if (!isDelimiter()) {
		// Read value until delimiter is found:
		do {
		    ch = nextChar();
		    // Take care of the quoting here.
		    if (ch == '\\') {
			if (peekChar() == '"' || peekChar() == '\'' ||
			       peekChar() == '>' || peekChar() == '%')
			    ch = nextChar();
		    }
		    stringBuffer.append((char) ch);
		} while (!isDelimiter());
	    }
	}

	return stringBuffer.toString();
    }

Parse a space delimited token.
If quoted the token will consume all characters up to a matching quote,
otherwise, it consumes up to the first delimiter character.

@param quoted If true accept quoted strings.

Parse a space delimited token . If quoted the token will consume all characters up to a matching quote otherwise it consumes up to the first delimiter character .


private boolean popFile() throws JasperException {

	// Is stack created ? (will happen if the Jsp file we're looking at is
	// missing.
	if (current == null || currFileId < 0) {
	    return false;
	}

	// Restore parser state:
	String fName = getFile(currFileId);
	currFileId = unregisterSourceFile(fName);
	if (currFileId < -1) {
	    err.jspError("jsp.error.file.not.registered", fName);
	}

	Mark previous = current.popStream();
	if (previous != null) {
	    master = current.baseDir;
	    current = previous;
	    return true;
	}
	// Note that although the current file is undefined here, "current"
	// is not set to null just for convience, for it maybe used to
	// set the current (undefined) position.
	return false;
    }

Pop a file from the file stack.  The field "current" is retored
to the value to point to the previous files, if any, and is set
to null otherwise.
@return true is there is a previous file on the stck.
false otherwise.

Pop a file from the file stack . The field current is retored to the value to point to the previous files if any and is set to null otherwise .


public Coordinates makeUnclassified ()
    {
        if ( this.classifier == null )
        {
            return this;
        }

        return new Coordinates ( this.groupId, this.artifactId, this.version, this.qualifiedVersion, null, this.extension );
    }

public Coordinates makeUnclassified ( ) { if ( this . classifier == null ) { return this ; } return new Coordinates ( this . groupId , this . artifactId , this . version , this . qualifiedVersion , null , this . extension ) ; }

Create an unclassified version of ourself

@return either a new instance without a classifier, or the same instance
if it already is without a classifier


public static List<AspectInformation> filterIds ( final List<AspectInformation> list, final Predicate<String> predicate )
    {
        if ( list == null )
        {
            return null;
        }

        return list.stream ().filter ( ( i ) -> predicate.test ( i.getFactoryId () ) ).collect ( Collectors.toList () );
    }

public static List < AspectInformation > filterIds ( final List < AspectInformation > list , final Predicate < String > predicate ) { if ( list == null ) { return null ; } return list . stream ( ) . filter ( ( i ) - > predicate . test ( i . getFactoryId ( ) ) ) . collect ( Collectors . toList ( ) ) ; }

Filter the provided aspect lists by a predicate on the ID

@param list
the list to filter
@param predicate
the ID predicate
@return the filtered list, returns only null when the list
was null


public String[] getMissingIds ( final List<AspectInformation> assignedAspects )
    {
        final Set<AspectInformation> required = new HashSet<> ();

        addRequired ( required, this, assignedAspects );

        return required.stream ().map ( AspectInformation::getFactoryId ).toArray ( size -> new String[size] );
    }

public String [ ] getMissingIds ( final List < AspectInformation > assignedAspects ) { final Set < AspectInformation > required = new HashSet <> ( ) ; addRequired ( required , this , assignedAspects ) ; return required . stream ( ) . map ( AspectInformation :: getFactoryId ) . toArray ( size -> new String [ size ] ) ; }

Get all aspect ids which are currently missing but required by this
aspect

@param assignedAspects
the aspects which are considered assigned
@return A possibly empty, array of all missing but required aspects.
Never returns null


public static void setSchemaResourcePrefix(String prefix) {

        if (prefix != null && prefix.startsWith("file:")) {
            schemaResourcePrefix = uencode(prefix);
            isSchemaResourcePrefixFileUrl = true;
        } else {
            schemaResourcePrefix = prefix;
            isSchemaResourcePrefixFileUrl = false;
        }

        for (int i=0; i<CACHED_SCHEMA_RESOURCE_PATHS.length; i++) {
            String path = DEFAULT_SCHEMA_RESOURCE_PATHS[i];
            int index = path.lastIndexOf('/');
            if (index != -1) {
                CACHED_SCHEMA_RESOURCE_PATHS[i] =
                    schemaResourcePrefix + path.substring(index+1);
            }
        }
    }

public static void setSchemaResourcePrefix ( String prefix ) { if ( prefix != null && prefix . startsWith ( "file:" ) ) { schemaResourcePrefix = uencode ( prefix ) ; isSchemaResourcePrefixFileUrl = true ; } else { schemaResourcePrefix = prefix ; isSchemaResourcePrefixFileUrl = false ; } for ( int i = 0 ; i < CACHED_SCHEMA_RESOURCE_PATHS . length ; i ++ ) { String path = DEFAULT_SCHEMA_RESOURCE_PATHS [ i ] ; int index = path . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { CACHED_SCHEMA_RESOURCE_PATHS [ i ] = schemaResourcePrefix + path . substring ( index + 1 ) ; } } }

Sets the path prefix URL for .xsd resources

Sets the path prefix URL for . xsd resources


public static void setDtdResourcePrefix(String prefix) {

        if (prefix != null && prefix.startsWith("file:")) {
            dtdResourcePrefix = uencode(prefix);
            isDtdResourcePrefixFileUrl = true;
        } else {
            dtdResourcePrefix = prefix;
            isDtdResourcePrefixFileUrl = false;
        }

        for (int i=0; i<CACHED_DTD_RESOURCE_PATHS.length; i++) {
            String path = DEFAULT_DTD_RESOURCE_PATHS[i];
            int index = path.lastIndexOf('/');
            if (index != -1) {
                CACHED_DTD_RESOURCE_PATHS[i] =
                    dtdResourcePrefix + path.substring(index+1);
            }
        }
    }

public static void setDtdResourcePrefix ( String prefix ) { if ( prefix != null && prefix . startsWith ( "file:" ) ) { dtdResourcePrefix = uencode ( prefix ) ; isDtdResourcePrefixFileUrl = true ; } else { dtdResourcePrefix = prefix ; isDtdResourcePrefixFileUrl = false ; } for ( int i = 0 ; i < CACHED_DTD_RESOURCE_PATHS . length ; i ++ ) { String path = DEFAULT_DTD_RESOURCE_PATHS [ i ] ; int index = path . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { CACHED_DTD_RESOURCE_PATHS [ i ] = dtdResourcePrefix + path . substring ( index + 1 ) ; } } }

Sets the path prefix URL for .dtd resources

Sets the path prefix URL for . dtd resources


private static String uencode(String prefix) {
        if (prefix != null && prefix.startsWith("file:")) {
            StringTokenizer tokens = new StringTokenizer(prefix, "/\\:", true);
            StringBuilder stringBuilder = new StringBuilder();
            while (tokens.hasMoreElements()) {
                String token = tokens.nextToken();
                if ("/".equals(token) || "\\".equals(token) || ":".equals(token)) {
                    stringBuilder.append(token);
                } else {
                    try {
                        stringBuilder.append(URLEncoder.encode(token, "UTF-8"));
                    } catch(java.io.UnsupportedEncodingException ex) {
                    }
                }
            }

            return stringBuilder.toString();
        } else {
            return prefix;
        }
    }

private static String uencode ( String prefix ) { if ( prefix != null && prefix . startsWith ( "file:" ) ) { StringTokenizer tokens = new StringTokenizer ( prefix , "/\\:" , true ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; while ( tokens . hasMoreElements ( ) ) { String token = tokens . nextToken ( ) ; if ( "/" . equals ( token ) || "\\" . equals ( token ) || ":" . equals ( token ) ) { stringBuilder . append ( token ) ; } else { try { stringBuilder . append ( URLEncoder . encode ( token , "UTF-8" ) ) ; } catch ( java . io . UnsupportedEncodingException ex ) { } } } return stringBuilder . toString ( ) ; } else { return prefix ; } }