Input: Convert a possibly relative resource path into a context - relative resource path that starts with a / . [CODESPLIT] public static String getContextRelativePath ( ServletRequest request , String relativePath ) { if ( relativePath . startsWith ( "/" ) ) return ( relativePath ) ; if ( ! ( request instanceof HttpServletRequest ) ) return ( relativePath ) ; HttpServletRequest hrequest = ( HttpServletRequest ) request ; String uri = ( String ) request . getAttribute ( "javax.servlet.include.servlet_path" ) ; if ( uri != null ) { String pathInfo = ( String ) request . getAttribute ( "javax.servlet.include.path_info" ) ; if ( pathInfo == null ) { if ( uri . lastIndexOf ( ' ' ) >= 0 ) { uri = uri . substring ( 0 , uri . lastIndexOf ( ' ' ) ) ; } } } else { // STARTJR: fix improper handling of jsp:include uri = hrequest . getServletPath ( ) ; String pathInfo = hrequest . getPathInfo ( ) ; if ( pathInfo != null ) { uri = uri + pathInfo ; } if ( uri . lastIndexOf ( ' ' ) >= 0 ) { uri = uri . substring ( 0 , uri . lastIndexOf ( ' ' ) ) ; } // ENDJR } return uri + ' ' + relativePath ; }


Input: Perform a RequestDispatcher . include () operation with optional flushing of the response beforehand . [CODESPLIT] public static void include ( ServletRequest request , ServletResponse response , String relativePath , JspWriter out , boolean flush ) throws IOException , ServletException { if ( flush && ! ( out instanceof BodyContent ) ) out . flush ( ) ; // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not.  Whether Catalina *should* take that into account // is a spec issue currently under review.  In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath ( request , relativePath ) ; RequestDispatcher rd = request . getRequestDispatcher ( resourcePath ) ; rd . include ( request , new ServletResponseWrapperInclude ( response , out ) ) ; }


Input: Adds the given tag handler to this tag handler pool unless this tag handler pool has already reached its capacity in which case the tag handler s release () method is called . [CODESPLIT] public void reuse ( Tag handler ) { PerThreadData ptd = perThread . get ( ) ; if ( ptd . current < ( ptd . handlers . length - 1 ) ) { ptd . handlers [ ++ ptd . current ] = handler ; } else { handler . release ( ) ; } }


Input: Calls the release () method of all tag handlers in this tag handler pool . [CODESPLIT] public void release ( ) { Enumeration < PerThreadData > enumeration = perThreadDataVector . elements ( ) ; while ( enumeration . hasMoreElements ( ) ) { PerThreadData ptd = enumeration . nextElement ( ) ; if ( ptd . handlers != null ) { for ( int i = ptd . current ; i >= 0 ; i -- ) { if ( ptd . handlers [ i ] != null ) { ptd . handlers [ i ] . release ( ) ; } } } } }


Input: Check if the uploaded artifact is actually a checksum file [CODESPLIT] 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 ; }


Input: private final static Logger logger = LoggerFactory . getLogger ( VirtualizerImpl . class ) ; [CODESPLIT] @ Override public void virtualize ( final Context context ) { try { processVirtualize ( context ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }


Input: Finishes the stream without closing the underlying OutputStream . [CODESPLIT] 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 ; } }


Input: Returns the exception associated with this page context if any . [CODESPLIT] 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 ; }


Input: Evaluates an EL expression [CODESPLIT] 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 ; }


Input: Make the prefix by guessing the port from the OSGi settings [CODESPLIT] 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 ( ) ; }


Input: Test if this file is an XML file [CODESPLIT] 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 ; } } }


Input: 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 . [CODESPLIT] 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 ( ) ; }


Input: Compiles and loads a tagfile . [CODESPLIT] 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 ; } }


Input: Implements a phase of the translation that compiles ( if necessary ) the tag files used in a JSP files . The directives in the tag files are assumed to have been proccessed and encapsulated as TagFileInfo in the CustomTag nodes . [CODESPLIT] public void loadTagFiles ( Compiler compiler , Node . Nodes page ) throws JasperException { tempVector = new ArrayList < Compiler > ( ) ; page . visit ( new TagFileLoaderVisitor ( compiler ) ) ; }


Input: Removed the java and class files for the tag prototype generated from the current compilation . [CODESPLIT] 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 ; } } }


Input: END GlassFish 750 [CODESPLIT] 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 ( ) ) ; } } } }


Input: Base dir for the webapp . Used to generate class names and resolve includes [CODESPLIT] public void setUriroot ( String s ) { uriRoot = s ; if ( s != null ) { try { uriRoot = new File ( s ) . getCanonicalPath ( ) ; } catch ( Exception ex ) { uriRoot = s ; } } }


Input: / * Parses comma - separated list of JSP files to be processed . [CODESPLIT] public void setJspFiles ( String jspFiles ) { StringTokenizer tok = new StringTokenizer ( jspFiles , " ," ) ; while ( tok . hasMoreTokens ( ) ) { pages . add ( tok . nextToken ( ) ) ; } }


Input: Gets the list of JSP compilation errors caught during the most recent invocation of this instance s <code > execute< / code > method when failOnError has been set to FALSE . [CODESPLIT] public List < JasperException > getJSPCompilationErrors ( ) { ArrayList < JasperException > ret = null ; Collection < JasperException > c = jspErrors . values ( ) ; if ( c != null ) { ret = new ArrayList < JasperException > ( ) ; Iterator < JasperException > it = c . iterator ( ) ; while ( it . hasNext ( ) ) { ret . add ( it . next ( ) ) ; } } return ret ; }


Input: Include the generated web . xml inside the webapp s web . xml . [CODESPLIT] protected void mergeIntoWebXml ( ) throws IOException { File webappBase = new File ( uriRoot ) ; File webXml = new File ( webappBase , "WEB-INF/web.xml" ) ; File webXml2 = new File ( webappBase , "WEB-INF/web2.xml" ) ; String insertStartMarker = Localizer . getMessage ( "jspc.webinc.insertStart" ) ; String insertEndMarker = Localizer . getMessage ( "jspc.webinc.insertEnd" ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( webXml ) , "UTF-8" ) ) ; BufferedReader fragmentReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( webxmlFile ) , "UTF-8" ) ) ; PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( new FileOutputStream ( webXml2 ) , "UTF-8" ) ) ; // Insert the <servlet> and <servlet-mapping> declarations int pos = - 1 ; String line = null ; while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { break ; } // Skip anything previously generated by JSPC if ( line . indexOf ( insertStartMarker ) >= 0 ) { while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { return ; } if ( line . indexOf ( insertEndMarker ) >= 0 ) { line = reader . readLine ( ) ; if ( line == null ) { return ; } break ; } } } for ( int i = 0 ; i < insertBefore . length ; i ++ ) { pos = line . indexOf ( insertBefore [ i ] ) ; if ( pos >= 0 ) break ; } if ( pos >= 0 ) { writer . println ( line . substring ( 0 , pos ) ) ; break ; } else { writer . println ( line ) ; } } writer . println ( insertStartMarker ) ; while ( true ) { String line2 = fragmentReader . readLine ( ) ; if ( line2 == null ) { writer . println ( ) ; break ; } writer . println ( line2 ) ; } writer . println ( insertEndMarker ) ; writer . println ( ) ; for ( int i = 0 ; i < pos ; i ++ ) { writer . print ( " " ) ; } if ( line != null ) { writer . println ( line . substring ( pos ) ) ; } while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { break ; } writer . println ( line ) ; } writer . close ( ) ; reader . close ( ) ; fragmentReader . close ( ) ; FileInputStream fis = new FileInputStream ( webXml2 ) ; FileOutputStream fos = new FileOutputStream ( webXml ) ; byte buf [ ] = new byte [ 512 ] ; try { while ( true ) { int n = fis . read ( buf ) ; if ( n < 0 ) { break ; } fos . write ( buf , 0 , n ) ; } } finally { if ( fis != null ) { fis . close ( ) ; } if ( fos != null ) { fos . close ( ) ; } } webXml2 . delete ( ) ; ( new File ( webxmlFile ) ) . delete ( ) ; }


Input: Locate all jsp files in the webapp . Used if no explicit jsps are specified . [CODESPLIT] 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 ) ; } } } } } }


Input: ==================== Private utility methods ==================== [CODESPLIT] private String nextArg ( ) { if ( ( argPos >= args . length ) || ( fullstop = SWITCH_FULL_STOP . equals ( args [ argPos ] ) ) ) { return null ; } else { return args [ argPos ++ ] ; } }


Input:
Initializes the classloader as / if needed for the given compilation context . [CODESPLIT] private void initClassLoader ( JspCompilationContext clctxt ) throws IOException { classPath = getClassPath ( ) ; ClassLoader jspcLoader = getClass ( ) . getClassLoader ( ) ; // Turn the classPath into URLs ArrayList < URL > urls = new ArrayList < URL > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( classPath , File . pathSeparator ) ; while ( tokenizer . hasMoreTokens ( ) ) { String path = tokenizer . nextToken ( ) ; try { File libFile = new File ( path ) ; urls . add ( libFile . toURL ( ) ) ; } catch ( IOException ioe ) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException ( ioe . toString ( ) ) ; } } File webappBase = new File ( uriRoot ) ; if ( webappBase . exists ( ) ) { File classes = new File ( webappBase , "/WEB-INF/classes" ) ; try { if ( classes . exists ( ) ) { classPath = classPath + File . pathSeparator + classes . getCanonicalPath ( ) ; urls . add ( classes . getCanonicalFile ( ) . toURL ( ) ) ; } } catch ( IOException ioe ) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException ( ioe . toString ( ) ) ; } File lib = new File ( webappBase , "/WEB-INF/lib" ) ; if ( lib . exists ( ) && lib . isDirectory ( ) ) { String [ ] libs = lib . list ( ) ; for ( int i = 0 ; i < libs . length ; i ++ ) { if ( libs [ i ] . length ( ) < 5 ) continue ; String ext = libs [ i ] . substring ( libs [ i ] . length ( ) - 4 ) ; if ( ! ".jar" . equalsIgnoreCase ( ext ) ) { if ( ".tld" . equalsIgnoreCase ( ext ) ) { log . warning ( "TLD files should not be placed in /WEB-INF/lib" ) ; } continue ; } try { File libFile = new File ( lib , libs [ i ] ) ; classPath = classPath + File . pathSeparator + libFile . getCanonicalPath ( ) ; urls . add ( libFile . getCanonicalFile ( ) . toURL ( ) ) ; } catch ( IOException ioe ) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException ( ioe . toString ( ) ) ; } } } } // What is this ?? urls . add ( new File ( clctxt . getRealPath ( "/" ) ) . getCanonicalFile ( ) . toURL ( ) ) ; URL urlsA [ ] = new URL [ urls . size ( ) ] ; urls . toArray ( urlsA ) ; /* SJSAS 6327357
        loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
         */ // START SJSAS 6327357 ClassLoader sysClassLoader = initSystemClassLoader ( ) ; if ( sysClassLoader != null ) { loader = new URLClassLoader ( urlsA , sysClassLoader ) ; } else { loader = new URLClassLoader ( urlsA , this . getClass ( ) . getClassLoader ( ) ) ; } // END SJSAS 6327357 }


Input: 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 . [CODESPLIT] 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 } }


Input: START SJSAS 6327357 [CODESPLIT] 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 ( ) ) ; }


Input: / * Purges all compilation errors related to JSP fragments . [CODESPLIT] private void purgeJspFragmentErrors ( ) { Iterator < String > it = dependents . iterator ( ) ; if ( it != null ) { while ( it . hasNext ( ) ) { jspErrors . remove ( it . next ( ) ) ; } } }


Input: Moves to the next byte checks that there is enough available space and possibly normalizes the hash tables and the hash chain . [CODESPLIT] 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 ; }


Input: ------------------------------------- [CODESPLIT] public Expression parseExpression ( String expression , Class expectedType , FunctionMapper fMapper ) throws ELException { ExpressionFactory fac = ExpressionFactory . newInstance ( ) ; javax . el . ValueExpression expr ; ELContextImpl elContext = new ELContextImpl ( null ) ; javax . el . FunctionMapper fm = new FunctionMapperWrapper ( fMapper ) ; elContext . setFunctionMapper ( fm ) ; try { expr = fac . createValueExpression ( elContext , expression , expectedType ) ; } catch ( javax . el . ELException ex ) { throw new ELException ( ex ) ; } return new ExpressionImpl ( expr , pageContext ) ; }


Input: Sets the delta distance in bytes . The new distance must be in the range [ DISTANCE_MIN DISTANCE_MAX ] . [CODESPLIT] public void setDistance ( int distance ) throws UnsupportedOptionsException { if ( distance < DISTANCE_MIN || distance > DISTANCE_MAX ) throw new UnsupportedOptionsException ( "Delta distance must be in the range [" + DISTANCE_MIN + ", " + DISTANCE_MAX + "]: " + distance ) ; this . distance = distance ; }


Input: search the stream for a match to a string [CODESPLIT] 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 ; }


Input: 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 . [CODESPLIT] boolean matchesOptionalSpacesFollowedBy ( String s ) throws JasperException { Mark mark = mark ( ) ; skipSpaces ( ) ; boolean result = matches ( s ) ; if ( ! result ) { reset ( mark ) ; } return result ; }


Input: Skip until the given string is matched in the stream . When returned the context is positioned past the end of the match . [CODESPLIT] 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 ; }


Input: 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 . [CODESPLIT] Mark skipUntilIgnoreEsc ( String limit ) throws JasperException { Mark ret = null ; int limlen = limit . length ( ) ; int ch ; int prev = ' ' ; // 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 ; }


Input: Skip until the given end tag is matched in the stream . When returned the context is positioned past the end of the tag . [CODESPLIT] Mark skipUntilETag ( String tag ) throws JasperException { Mark ret = skipUntil ( "</" + tag ) ; if ( ret != null ) { skipSpaces ( ) ; if ( nextChar ( ) != ' ' ) ret = null ; } return ret ; }


Input: 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 . [CODESPLIT] 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 ( ) ; }


Input: Parse utils - Is current character a token delimiter ? Delimiters are currently defined to be = &gt ; &lt ; and or any any space character as defined by <code > isSpace< / code > . [CODESPLIT] private boolean isDelimiter ( ) throws JasperException { if ( ! isSpace ( ) ) { int ch = peekChar ( ) ; // Look for a single-char work delimiter: if ( ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { return true ; } // Look for an end-of-comment or end-of-tag:		 if ( ch == ' ' ) { Mark mark = mark ( ) ; if ( ( ( ch = nextChar ( ) ) == ' ' ) || ( ( ch == ' ' ) && ( nextChar ( ) == ' ' ) ) ) { reset ( mark ) ; return true ; } else { reset ( mark ) ; return false ; } } return false ; } else { return true ; } }


Input: Register a new source file . This method is used to implement file inclusion . Each included file gets a unique identifier ( which is the index in the array of source files ) . [CODESPLIT] private int registerSourceFile ( String file ) { if ( sourceFiles . contains ( file ) ) return - 1 ; sourceFiles . add ( file ) ; this . size ++ ; return sourceFiles . size ( ) - 1 ; }


Input: Unregister the source file . This method is used to implement file inclusion . Each included file gets a uniq identifier ( which is the index in the array of source files ) . [CODESPLIT] private int unregisterSourceFile ( String file ) { if ( ! sourceFiles . contains ( file ) ) return - 1 ; sourceFiles . remove ( file ) ; this . size -- ; return sourceFiles . size ( ) - 1 ; }


Input: Push a file ( and its associated Stream ) on the file stack . THe current position in the current file is remembered . [CODESPLIT] private void pushFile ( String file , String encoding , InputStreamReader reader ) throws JasperException , FileNotFoundException { // Register the file String longName = file ; int fileid = registerSourceFile ( longName ) ; if ( fileid == - 1 ) { err . jspError ( "jsp.error.file.already.registered" , file ) ; } currFileId = fileid ; try { CharArrayWriter caw = new CharArrayWriter ( ) ; char buf [ ] = new char [ 1024 ] ; for ( int i = 0 ; ( i = reader . read ( buf ) ) != - 1 ; ) caw . write ( buf , 0 , i ) ; caw . close ( ) ; if ( current == null ) { current = new Mark ( this , caw . toCharArray ( ) , fileid , getFile ( fileid ) , master , encoding ) ; } else { current . pushStream ( caw . toCharArray ( ) , fileid , getFile ( fileid ) , longName , encoding ) ; } } catch ( Throwable ex ) { log . log ( Level . SEVERE , "Exception parsing file " , ex ) ; // Pop state being constructed: popFile ( ) ; err . jspError ( "jsp.error.file.cannot.read" , file ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( Exception any ) { } } } }


Input: 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 . [CODESPLIT] 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 ; }


Input: Create an unclassified version of ourself [CODESPLIT] public Coordinates makeUnclassified ( ) { if ( this . classifier == null ) { return this ; } return new Coordinates ( this . groupId , this . artifactId , this . version , this . qualifiedVersion , null , this . extension ) ; }


Input: Add custom binders assigned to the method <p > Custom binders assigned to the method will be added to the binding manager instance . < / p > [CODESPLIT] protected static void addMethodBinders ( final BindingManager manager , final Method method ) { final ControllerBinder [ ] binders = method . getAnnotationsByType ( ControllerBinder . class ) ; if ( binders == null ) { return ; } for ( final ControllerBinder binder : binders ) { try { final Binder binderImpl = binder . value ( ) . newInstance ( ) ; if ( binderImpl instanceof ControllerBinderParametersAware ) { ( ( ControllerBinderParametersAware ) binderImpl ) . setParameters ( binder . parameters ( ) ) ; } manager . addBinder ( binderImpl ) ; } catch ( InstantiationException | IllegalAccessException e ) { manager . addBinder ( new ErrorBinder ( e ) ) ; } } }


Input: Returns the given stratum as a String : a StratumSection followed by at least one FileSection and at least one LineSection . [CODESPLIT] public String getString ( ) { // check state and initialize buffer if ( fileNameList . size ( ) == 0 || lineData . size ( ) == 0 ) return null ; StringBuilder out = new StringBuilder ( ) ; // print StratumSection out . append ( "*S " + stratumName + "\n" ) ; // print FileSection out . append ( "*F\n" ) ; int bound = fileNameList . size ( ) ; for ( int i = 0 ; i < bound ; i ++ ) { if ( filePathList . get ( i ) != null ) { out . append ( "+ " + i + " " + fileNameList . get ( i ) + "\n" ) ; // Source paths must be relative, not absolute, so we // remove the leading "/", if one exists. String filePath = filePathList . get ( i ) ; if ( filePath . startsWith ( "/" ) ) { filePath = filePath . substring ( 1 ) ; } out . append ( filePath + "\n" ) ; } else { out . append ( i + " " + fileNameList . get ( i ) + "\n" ) ; } } // print LineSection out . append ( "*L\n" ) ; bound = lineData . size ( ) ; for ( int i = 0 ; i < bound ; i ++ ) { LineInfo li = lineData . get ( i ) ; out . append ( li . getString ( ) ) ; } return out . toString ( ) ; }


Input: Invoke CompilationResult#getProblems safely so that it works with 3 . 1 . 1 and more recent versions of the eclipse java compiler . See https : // jsp . dev . java . net / issues / show_bug . cgi?id = 13 [CODESPLIT] private static final IProblem [ ] safeGetProblems ( CompilationResult result ) { if ( ! USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM ) { try { return result . getProblems ( ) ; } catch ( NoSuchMethodError re ) { USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM = true ; } } try { if ( GET_PROBLEM_METH == null ) { GET_PROBLEM_METH = result . getClass ( ) . getDeclaredMethod ( "getProblems" , new Class [ ] { } ) ; } //an array of a particular type can be casted into an array of a super type. return ( IProblem [ ] ) GET_PROBLEM_METH . invoke ( result , null ) ; } catch ( Throwable e ) { if ( e instanceof RuntimeException ) { throw ( RuntimeException ) e ; } else { throw new RuntimeException ( e ) ; } } }


Input: Sets the compression options to the given preset . <p > The presets 0 - 3 are fast presets with medium compression . The presets 4 - 6 are fairly slow presets with high compression . The default preset ( <code > PRESET_DEFAULT< / code > ) is 6 . <p > The presets 7 - 9 are like the preset 6 but use bigger dictionaries and have higher compressor and decompressor memory requirements . Unless the uncompressed size of the file exceeds 8&nbsp ; MiB 16&nbsp ; MiB or 32&nbsp ; MiB it is waste of memory to use the presets 7 8 or 9 respectively . [CODESPLIT] public void setPreset ( int preset ) throws UnsupportedOptionsException { if ( preset < 0 || preset > 9 ) throw new UnsupportedOptionsException ( "Unsupported preset: " + preset ) ; lc = LC_DEFAULT ; lp = LP_DEFAULT ; pb = PB_DEFAULT ; dictSize = presetToDictSize [ preset ] ; if ( preset <= 3 ) { mode = MODE_FAST ; mf = MF_HC4 ; niceLen = preset <= 1 ? 128 : NICE_LEN_MAX ; depthLimit = presetToDepthLimit [ preset ] ; } else { mode = MODE_NORMAL ; mf = MF_BT4 ; niceLen = ( preset == 4 ) ? 16 : ( preset == 5 ) ? 32 : 64 ; depthLimit = 0 ; } }


Input: Sets the dictionary size in bytes . <p > The dictionary ( or history buffer ) holds the most recently seen uncompressed data . Bigger dictionary usually means better compression . However using a dictioanary bigger than the size of the uncompressed data is waste of memory . <p > Any value in the range [ DICT_SIZE_MIN DICT_SIZE_MAX ] is valid but sizes of 2^n and 2^n&nbsp ; + &nbsp ; 2^ ( n - 1 ) bytes are somewhat recommended . [CODESPLIT] public void setDictSize ( int dictSize ) throws UnsupportedOptionsException { if ( dictSize < DICT_SIZE_MIN ) throw new UnsupportedOptionsException ( "LZMA2 dictionary size must be at least 4 KiB: " + dictSize + " B" ) ; if ( dictSize > DICT_SIZE_MAX ) throw new UnsupportedOptionsException ( "LZMA2 dictionary size must not exceed " + ( DICT_SIZE_MAX >> 20 ) + " MiB: " + dictSize + " B" ) ; this . dictSize = dictSize ; }


Input: Sets the number of literal context bits and literal position bits . <p > The sum of <code > lc< / code > and <code > lp< / code > is limited to 4 . Trying to exceed it will throw an exception . This function lets you change both at the same time . [CODESPLIT] public void setLcLp ( int lc , int lp ) throws UnsupportedOptionsException { if ( lc < 0 || lp < 0 || lc > LC_LP_MAX || lp > LC_LP_MAX || lc + lp > LC_LP_MAX ) throw new UnsupportedOptionsException ( "lc + lp must not exceed " + LC_LP_MAX + ": " + lc + " + " + lp ) ; this . lc = lc ; this . lp = lp ; }


Input: Sets the number of position bits . <p > This affects what kind of alignment in the uncompressed data is assumed in general . The default ( 2 ) means four - byte alignment ( 2^<code > pb< / code > = 2^2 = 4 ) which is often a good choice when there s no better guess . <p > When the alignment is known setting the number of position bits accordingly may reduce the file size a little . For example with text files having one - byte alignment ( US - ASCII ISO - 8859 - * UTF - 8 ) using <code > setPb ( 0 ) < / code > can improve compression slightly . For UTF - 16 text <code > setPb ( 1 ) < / code > is a good choice . If the alignment is an odd number like 3 bytes <code > setPb ( 0 ) < / code > might be the best choice . <p > Even though the assumed alignment can be adjusted with <code > setPb< / code > and <code > setLp< / code > LZMA2 still slightly favors 16 - byte alignment . It might be worth taking into account when designing file formats that are likely to be often compressed with LZMA2 . [CODESPLIT] public void setPb ( int pb ) throws UnsupportedOptionsException { if ( pb < 0 || pb > PB_MAX ) throw new UnsupportedOptionsException ( "pb must not exceed " + PB_MAX + ": " + pb ) ; this . pb = pb ; }


Input: Sets the compression mode . <p > This specifies the method to analyze the data produced by a match finder . The default is <code > MODE_FAST< / code > for presets 0 - 3 and <code > MODE_NORMAL< / code > for presets 4 - 9 . <p > Usually <code > MODE_FAST< / code > is used with Hash Chain match finders and <code > MODE_NORMAL< / code > with Binary Tree match finders . This is also what the presets do . <p > The special mode <code > MODE_UNCOMPRESSED< / code > doesn t try to compress the data at all ( and doesn t use a match finder ) and will simply wrap it in uncompressed LZMA2 chunks . [CODESPLIT] public void setMode ( int mode ) throws UnsupportedOptionsException { if ( mode < MODE_UNCOMPRESSED || mode > MODE_NORMAL ) throw new UnsupportedOptionsException ( "Unsupported compression mode: " + mode ) ; this . mode = mode ; }


Input: Sets the nice length of matches . Once a match of at least <code > niceLen< / code > bytes is found the algorithm stops looking for better matches . Higher values tend to give better compression at the expense of speed . The default depends on the preset . [CODESPLIT] public void setNiceLen ( int niceLen ) throws UnsupportedOptionsException { if ( niceLen < NICE_LEN_MIN ) throw new UnsupportedOptionsException ( "Minimum nice length of matches is " + NICE_LEN_MIN + " bytes: " + niceLen ) ; if ( niceLen > NICE_LEN_MAX ) throw new UnsupportedOptionsException ( "Maximum nice length of matches is " + NICE_LEN_MAX + ": " + niceLen ) ; this . niceLen = niceLen ; }


Input: Sets the match finder type . <p > Match finder has a major effect on compression speed memory usage and compression ratio . Usually Hash Chain match finders are faster than Binary Tree match finders . The default depends on the preset : 0 - 3 use <code > MF_HC4< / code > and 4 - 9 use <code > MF_BT4< / code > . [CODESPLIT] public void setMatchFinder ( int mf ) throws UnsupportedOptionsException { if ( mf != MF_HC4 && mf != MF_BT4 ) throw new UnsupportedOptionsException ( "Unsupported match finder: " + mf ) ; this . mf = mf ; }


Input: Gets how much memory the LZMA2 decoder will need to decompress the data that was encoded with these options and stored in a . xz file . <p > The returned value may bigger than the value returned by a direct call to { [CODESPLIT] public int getDecoderMemoryUsage ( ) { // Round the dictionary size up to the next 2^n or 2^n + 2^(n-1). int d = dictSize - 1 ; d |= d >>> 2 ; d |= d >>> 3 ; d |= d >>> 4 ; d |= d >>> 8 ; d |= d >>> 16 ; return LZMA2InputStream . getMemoryUsage ( d + 1 ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Mark where , Exception e ) throws JasperException { dispatch ( where , e . getMessage ( ) , null , e ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( String errCode , String ... args ) throws JasperException { dispatch ( null , errCode , args , null ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Mark where , String errCode , String ... args ) throws JasperException { dispatch ( where , errCode , args , null ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Node n , String errCode , String ... args ) throws JasperException { dispatch ( n . getStart ( ) , errCode , args , null ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( String errCode , String arg , Exception e ) throws JasperException { dispatch ( null , errCode , new Object [ ] { arg } , e ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Node n , String errCode , String arg , Exception e ) throws JasperException { dispatch ( n . getStart ( ) , errCode , new Object [ ] { arg } , e ) ; }


Input: Creates and throws a new exception from the given JasperException by prepending the given location information ( containing file name line number and column number ) to the message of the given exception and copying the stacktrace of the given exception to the new exception . [CODESPLIT] public void throwException ( Mark where , JasperException je ) throws JasperException { if ( where == null ) { throw je ; } // Get file location String file = null ; if ( jspcMode ) { // Get the full URL of the resource that caused the error try { file = where . getURL ( ) . toString ( ) ; } catch ( MalformedURLException me ) { // Fallback to using context-relative path file = where . getFile ( ) ; } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where . getFile ( ) ; } JasperException newEx = new JasperException ( file + "(" + where . getLineNumber ( ) + "," + where . getColumnNumber ( ) + ")" + " " + je . getMessage ( ) , je . getCause ( ) ) ; newEx . setStackTrace ( je . getStackTrace ( ) ) ; throw newEx ; }


Input: / * Dispatches the given compilation error report and exception to the configured error handler . [CODESPLIT] public void javacError ( String errorReport , Exception e ) throws JasperException { errHandler . javacError ( errorReport , e ) ; }


Input: / * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] private void dispatch ( Mark where , String errCode , Object [ ] args , Exception e ) throws JasperException { String file = null ; String errMsg = null ; int line = - 1 ; int column = - 1 ; boolean hasLocation = false ; // Localize if ( errCode != null ) { errMsg = Localizer . getMessage ( errCode , args ) ; } else if ( e != null ) { // give a hint about what's wrong errMsg = e . getMessage ( ) ; } // Get error location if ( where != null ) { if ( jspcMode ) { // Get the full URL of the resource that caused the error try { file = where . getURL ( ) . toString ( ) ; } catch ( MalformedURLException me ) { // Fallback to using context-relative path file = where . getFile ( ) ; } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where . getFile ( ) ; } line = where . getLineNumber ( ) ; column = where . getColumnNumber ( ) ; hasLocation = true ; } // Get nested exception Exception nestedEx = e ; if ( ( e instanceof SAXException ) && ( ( ( SAXException ) e ) . getException ( ) != null ) ) { nestedEx = ( ( SAXException ) e ) . getException ( ) ; } if ( hasLocation ) { errHandler . jspError ( file , line , column , errMsg , nestedEx ) ; } else { errHandler . jspError ( errMsg , nestedEx ) ; } }


Input:
/ * Parses the given Java compilation error message which may contain one or more compilation errors into an array of JavacErrorDetail instances . [CODESPLIT] public static JavacErrorDetail [ ] parseJavacMessage ( Node . Nodes pageNodes , String errMsg , String fname ) throws IOException , JasperException { ArrayList < JavacErrorDetail > errors = new ArrayList < JavacErrorDetail > ( ) ; StringBuilder errMsgBuf = null ; int lineNum = - 1 ; JavacErrorDetail javacError = null ; BufferedReader reader = new BufferedReader ( new StringReader ( errMsg ) ) ; /*
         * Parse compilation errors. Each compilation error consists of a file
         * path and error line number, followed by a number of lines describing
         * the error.
         */ String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { /*
	     * Error line number is delimited by set of colons.
	     * Ignore colon following drive letter on Windows (fromIndex = 2).
	     * XXX Handle deprecation warnings that don't have line info
	     */ int beginColon = line . indexOf ( ' ' , 2 ) ; int endColon = line . indexOf ( ' ' , beginColon + 1 ) ; if ( ( beginColon >= 0 ) && ( endColon >= 0 ) ) { if ( javacError != null ) { // add previous error to error vector errors . add ( javacError ) ; } String lineNumStr = line . substring ( beginColon + 1 , endColon ) ; try { lineNum = Integer . parseInt ( lineNumStr ) ; } catch ( NumberFormatException e ) { // XXX } errMsgBuf = new StringBuilder ( ) ; javacError = createJavacError ( fname , pageNodes , errMsgBuf , lineNum ) ; } // Ignore messages preceding first error if ( errMsgBuf != null ) { errMsgBuf . append ( line ) ; errMsgBuf . append ( "\n" ) ; } } // Add last error to error vector if ( javacError != null ) { errors . add ( javacError ) ; } reader . close ( ) ; return errors . toArray ( new JavacErrorDetail [ 0 ] ) ; }


Input: Filter the provided aspect lists by a predicate on the ID [CODESPLIT] 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 ( ) ) ; }


Input: Get all aspect ids which are currently missing but required by this aspect [CODESPLIT] 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 ] ) ; }


Input: Sets the path prefix URL for . xsd resources [CODESPLIT] 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 ) ; } } }


Input: Sets the path prefix URL for . dtd resources [CODESPLIT] 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 ) ; } } }


Input: END PWC 6386258 [CODESPLIT] 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 ; } }


Input: Parse the specified XML document and return a <code > TreeNode< / code > that corresponds to the root node of the document tree . [CODESPLIT] public TreeNode parseXMLDocument ( String uri , InputSource is ) throws JasperException { return parseXMLDocument ( uri , is , false ) ; }


Input:
Parse the specified XML document and return a <code > TreeNode< / code > that corresponds to the root node of the document tree . [CODESPLIT] public TreeNode parseXMLDocument ( String uri , InputSource is , boolean validate ) throws JasperException { Document document = null ; // Perform an XML parse of this document, via JAXP // START 6412405 ClassLoader currentLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( getClass ( ) . getClassLoader ( ) ) ; // END 6412405 try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; /* See CR 6399139
            factory.setFeature(
                "http://apache.org/xml/features/validation/dynamic",
                true);
            */ DocumentBuilder builder = factory . newDocumentBuilder ( ) ; builder . setEntityResolver ( entityResolver ) ; builder . setErrorHandler ( errorHandler ) ; document = builder . parse ( is ) ; document . setDocumentURI ( uri ) ; if ( validate ) { Schema schema = getSchema ( document ) ; if ( schema != null ) { // Validate TLD against specified schema schema . newValidator ( ) . validate ( new DOMSource ( document ) ) ; } /* See CR 6399139
                else {
                    log.warning(Localizer.getMessage(
                        "jsp.warning.dtdValidationNotSupported"));
                }
                */ } } catch ( ParserConfigurationException ex ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.parse.xml" , uri ) , ex ) ; } catch ( SAXParseException ex ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.parse.xml.line" , uri , Integer . toString ( ex . getLineNumber ( ) ) , Integer . toString ( ex . getColumnNumber ( ) ) ) , ex ) ; } catch ( SAXException sx ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.parse.xml" , uri ) , sx ) ; } catch ( IOException io ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.parse.xml" , uri ) , io ) ; // START 6412405 } finally { Thread . currentThread ( ) . setContextClassLoader ( currentLoader ) ; } // END 6412405 // Convert the resulting document to a graph of TreeNodes return ( convert ( null , document . getDocumentElement ( ) ) ) ; }


Input: Create and return a TreeNode that corresponds to the specified Node including processing all of the attributes and children nodes . [CODESPLIT] protected TreeNode convert ( TreeNode parent , Node node ) { // Construct a new TreeNode for this node TreeNode treeNode = new TreeNode ( node . getNodeName ( ) , parent ) ; // Convert all attributes of this node NamedNodeMap attributes = node . getAttributes ( ) ; if ( attributes != null ) { int n = attributes . getLength ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node attribute = attributes . item ( i ) ; treeNode . addAttribute ( attribute . getNodeName ( ) , attribute . getNodeValue ( ) ) ; } } // Create and attach all children of this node NodeList children = node . getChildNodes ( ) ; if ( children != null ) { int n = children . getLength ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node child = children . item ( i ) ; if ( child instanceof Comment ) continue ; if ( child instanceof Text ) { String body = ( ( Text ) child ) . getData ( ) ; if ( body != null ) { body = body . trim ( ) ; if ( body . length ( ) > 0 ) treeNode . setBody ( body ) ; } } else { TreeNode treeChild = convert ( treeNode , child ) ; } } } // Return the completed TreeNode graph return ( treeNode ) ; }


Input: / * Gets the compiled schema referenced by the given XML document . [CODESPLIT] private static Schema getSchema ( Document document ) throws SAXException , JasperException { Schema schema = null ; Element root = document . getDocumentElement ( ) ; NamedNodeMap map = root . getAttributes ( ) ; for ( int i = 0 ; map != null && i < map . getLength ( ) ; i ++ ) { if ( SCHEMA_LOCATION_ATTR . equals ( map . item ( i ) . getLocalName ( ) ) ) { String schemaLocation = map . item ( i ) . getNodeValue ( ) ; if ( Constants . SCHEMA_LOCATION_JSP_20 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . TAGLIB_SCHEMA_PUBLIC_ID_20 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_JSP_21 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . TAGLIB_SCHEMA_PUBLIC_ID_21 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_WEBAPP_24 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . WEBAPP_SCHEMA_PUBLIC_ID_24 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_WEBAPP_25 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . WEBAPP_SCHEMA_PUBLIC_ID_25 ) ; break ; } else { throw new JasperException ( Localizer . getMessage ( "jsp.error.parse.unknownTldSchemaLocation" , document . getDocumentURI ( ) , map . item ( i ) . getNodeValue ( ) ) ) ; } } } return schema ; }


Input: / * Gets the compiled schema for the given schema public id . [CODESPLIT] private static Schema getSchema ( String schemaPublicId ) throws SAXException { Schema schema = schemaCache . get ( schemaPublicId ) ; if ( schema == null ) { synchronized ( schemaCache ) { schema = schemaCache . get ( schemaPublicId ) ; if ( schema == null ) { SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; schemaFactory . setResourceResolver ( new MyLSResourceResolver ( ) ) ; schemaFactory . setErrorHandler ( new MyErrorHandler ( ) ) ; String path = schemaPublicId ; if ( schemaResourcePrefix != null ) { int index = schemaPublicId . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { path = schemaPublicId . substring ( index + 1 ) ; } path = schemaResourcePrefix + path ; } InputStream input = null ; if ( isSchemaResourcePrefixFileUrl ) { try { File f = new File ( new URI ( path ) ) ; if ( f . exists ( ) ) { input = new FileInputStream ( f ) ; } } catch ( Exception e ) { throw new SAXException ( e ) ; } } else { input = ParserUtils . class . getResourceAsStream ( path ) ; } if ( input == null ) { throw new SAXException ( Localizer . getMessage ( "jsp.error.internal.filenotfound" , schemaPublicId ) ) ; } schema = schemaFactory . newSchema ( new StreamSource ( input ) ) ; schemaCache . put ( schemaPublicId , schema ) ; } } } return schema ; }


Input: Create a new BindingManager with default binders <p > This call creates a new BindingManager instance and add the following binders : < / p > <ul > <li > { @link MapBinder } < / li > <li > { @link BindingManagerBinder } < / li > < / ul > [CODESPLIT] public static final BindingManager create ( final Map < String , Object > data ) { final BindingManager result = new BindingManager ( ) ; result . addBinder ( new MapBinder ( data ) ) ; result . addBinder ( new BindingManagerBinder ( ) ) ; return result ; }


Input: Merge all errors of this binding into this result [CODESPLIT] private static void mergeErrors ( final BindingResult bindingResult , final BindingResult result ) { if ( bindingResult == null ) { return ; } result . addErrors ( bindingResult . getLocalErrors ( ) ) ; for ( final Map . Entry < String , BindingResult > child : bindingResult . getChildren ( ) . entrySet ( ) ) { mergeErrors ( child . getValue ( ) , result . getChildOrAdd ( child . getKey ( ) ) ) ; } }


Input: Add a new binder <p > If the binder has to be initialized then all methods annotated with { @link Initializer } will be called . < / p > [CODESPLIT] public void addBinder ( final Binder binder , final boolean initializeBinder ) { if ( initializeBinder ) { initializeBinder ( binder ) ; } this . binders . add ( binder ) ; }


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


Input: This actively scans for available aspects and returns their information objects [CODESPLIT] public static Map < String , ChannelAspectInformation > scanAspectInformations ( final BundleContext context ) { Collection < ServiceReference < ChannelAspectFactory >> refs ; try { refs = context . getServiceReferences ( ChannelAspectFactory . class , null ) ; } catch ( final InvalidSyntaxException e ) { // this should never happen since we don't specific a filter return Collections . emptyMap ( ) ; } if ( refs == null ) { return Collections . emptyMap ( ) ; } final Map < String , ChannelAspectInformation > result = new HashMap <> ( refs . size ( ) ) ; for ( final ServiceReference < ChannelAspectFactory > ref : refs ) { final ChannelAspectInformation info = makeInformation ( ref ) ; result . put ( info . getFactoryId ( ) , info ) ; } return result ; }


Input: Generates an appropriate SMAP representing the current compilation context . ( JSR - 045 . ) [CODESPLIT] public void generateSmap ( Node . Nodes pageNodes ) throws IOException { classInfos = new ArrayList < ClassInfo > ( ) ; String className = ctxt . getFullClassName ( ) ; // Instantiate a SmapStratum for the main JSP page. SmapStratum s = new SmapStratum ( "JSP" ) ; classInfos . add ( new ClassInfo ( className , s ) ) ; // Map out Node.Nodes and putting LineInfo into SmapStratum evaluateNodes ( pageNodes , s , ctxt . getOptions ( ) . getMappedFile ( ) ) ; String classFileName = ctxt . getClassFileName ( ) ; for ( ClassInfo entry : classInfos ) { // Get SmapStratum s = entry . getSmapStratum ( ) ; s . optimizeLineSection ( ) ; // Set up our SMAP generator SmapGenerator g = new SmapGenerator ( ) ; g . setOutputFileName ( unqualify ( ctxt . getServletJavaFileName ( ) ) ) ; g . addStratum ( s , true ) ; String name = entry . getClassName ( ) ; // class name // Compute the class name and output file name for inner classes if ( ! className . equals ( name ) ) { classFileName = ctxt . getOutputDir ( ) + name . substring ( name . lastIndexOf ( ' ' ) + 1 ) + ".class" ; } entry . setClassFileName ( classFileName ) ; entry . setSmap ( g . getString ( ) ) ; if ( ctxt . getOptions ( ) . isSmapDumped ( ) ) { File outSmap = new File ( classFileName + ".smap" ) ; PrintWriter so = new PrintWriter ( new OutputStreamWriter ( new FileOutputStream ( outSmap ) , SMAP_ENCODING ) ) ; so . print ( g . getString ( ) ) ; so . close ( ) ; } } }


Input: Returns an unqualified version of the given file path . [CODESPLIT] private static String unqualify ( String path ) { path = path . replace ( ' ' , ' ' ) ; return path . substring ( path . lastIndexOf ( ' ' ) + 1 ) ; }


Input: Invoke tag plugin for the given custom tag if a plugin exists for the custom tag s tag handler . [CODESPLIT] private void invokePlugin ( Node . CustomTag n ) { TagPlugin tagPlugin = tagPlugins . get ( n . getTagHandlerClass ( ) . getName ( ) ) ; if ( tagPlugin == null ) { return ; } TagPluginContext tagPluginContext = new TagPluginContextImpl ( n , pageInfo ) ; n . setTagPluginContext ( tagPluginContext ) ; tagPlugin . doTag ( tagPluginContext ) ; }


Input: Gets { [CODESPLIT] private static < T > T getArray ( CacheMap < T > cache , int size ) { // putArray doesn't add small arrays to the cache and so it's // pointless to look for small arrays here. if ( size < CACHEABLE_SIZE_MIN ) return null ; // Try to find a stack that holds arrays of T[size]. CyclicStack < Reference < T > > stack ; synchronized ( cache ) { stack = cache . get ( size ) ; } if ( stack == null ) return null ; // Try to find a non-cleared Reference from the stack. T array ; do { Reference < T > r = stack . pop ( ) ; if ( r == null ) return null ; array = r . get ( ) ; } while ( array == null ) ; return array ; }


Input: Puts the { [CODESPLIT] private static < T > void putArray ( CacheMap < T > cache , T array , int size ) { // Small arrays aren't cached. if ( size < CACHEABLE_SIZE_MIN ) return ; CyclicStack < Reference < T > > stack ; synchronized ( cache ) { // Get a stack that holds arrays of T[size]. If no such stack // exists, allocate a new one. If the cache already had STACKS_MAX // number of stacks, the least recently used stack is removed by // cache.put (it calls removeEldestEntry). stack = cache . get ( size ) ; if ( stack == null ) { stack = new CyclicStack < Reference < T > > ( ) ; cache . put ( size , stack ) ; } } stack . push ( new SoftReference < T > ( array ) ) ; }


Input: Allocates a new byte array hopefully reusing an existing array from the cache . [CODESPLIT] public byte [ ] getByteArray ( int size , boolean fillWithZeros ) { byte [ ] array = getArray ( byteArrayCache , size ) ; if ( array == null ) array = new byte [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , ( byte ) 0x00 ) ; return array ; }


Input: This is like getByteArray but for int arrays . [CODESPLIT] public int [ ] getIntArray ( int size , boolean fillWithZeros ) { int [ ] array = getArray ( intArrayCache , size ) ; if ( array == null ) array = new int [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , 0 ) ; return array ; }


Input: Prepare an import with dependencies <p > This method does resolve even transient dependencies and also adds the sources if requested < / p > [CODESPLIT] public static AetherResult prepareDependencies ( final Path tmpDir , final ImportConfiguration cfg ) throws RepositoryException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) , cfg . isAllOptional ( ) ) ; // add all coordinates final CollectRequest cr = new CollectRequest ( ) ; cr . setRepositories ( ctx . getRepositories ( ) ) ; for ( final MavenCoordinates coords : cfg . getCoordinates ( ) ) { final Dependency dep = new Dependency ( new DefaultArtifact ( coords . toString ( ) ) , COMPILE ) ; cr . addDependency ( dep ) ; } final DependencyFilter filter = DependencyFilterUtils . classpathFilter ( COMPILE ) ; final DependencyRequest deps = new DependencyRequest ( cr , filter ) ; // resolve final DependencyResult dr = ctx . getSystem ( ) . resolveDependencies ( ctx . getSession ( ) , deps ) ; final List < ArtifactResult > arts = dr . getArtifactResults ( ) ; if ( ! cfg . isIncludeSources ( ) ) { // we are already done here return asResult ( arts , cfg , of ( dr ) ) ; } // resolve sources final List < ArtifactRequest > requests = extendRequests ( arts . stream ( ) . map ( ArtifactResult :: getRequest ) , ctx , cfg ) ; return asResult ( resolve ( ctx , requests ) , cfg , of ( dr ) ) ; }


Input: Prepare a plain import process <p > Prepare a simple import request with a specific list of coordinates < / p > [CODESPLIT] public static AetherResult preparePlain ( final Path tmpDir , final ImportConfiguration cfg ) throws ArtifactResolutionException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) , cfg . isAllOptional ( ) ) ; // extend final List < ArtifactRequest > requests = extendRequests ( cfg . getCoordinates ( ) . stream ( ) . map ( c -> { final DefaultArtifact artifact = new DefaultArtifact ( c . toString ( ) ) ; return makeRequest ( ctx . getRepositories ( ) , artifact ) ; } ) , ctx , cfg ) ; // process return asResult ( resolve ( ctx , requests ) , cfg , empty ( ) ) ; }


Input: Process the actual import request <p > This method takes the import configuration as is and simply tries to import it . Not manipulating the list of coordinates any more < / p > [CODESPLIT] public static Collection < ArtifactResult > processImport ( final Path tmpDir , final ImportConfiguration cfg ) throws ArtifactResolutionException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) ) ; final Collection < ArtifactRequest > requests = new LinkedList <> ( ) ; for ( final MavenCoordinates coords : cfg . getCoordinates ( ) ) { // main artifact final DefaultArtifact main = new DefaultArtifact ( coords . toString ( ) ) ; requests . add ( makeRequest ( ctx . getRepositories ( ) , main ) ) ; } // process return ctx . getSystem ( ) . resolveArtifacts ( ctx . getSession ( ) , requests ) ; }


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


Input: the following is a workaround until these problems are resolved . [CODESPLIT] private InputStream getResourceAsStream ( String uri ) throws JasperException { try { // see if file exists on the filesystem first String real = ctxt . getRealPath ( uri ) ; if ( real == null ) { return ctxt . getResourceAsStream ( uri ) ; } else { return new FileInputStream ( real ) ; } } catch ( FileNotFoundException ex ) { // if file not found on filesystem, get the resource through // the context return ctxt . getResourceAsStream ( uri ) ; } }


Input: Returns an array of TagLibraryInfo objects representing the entire set of tag libraries ( including this TagLibraryInfo ) imported by taglib directives in the translation unit that references this TagLibraryInfo . [CODESPLIT] public TagLibraryInfo [ ] getTagLibraryInfos ( ) { TagLibraryInfo [ ] taglibs = null ; Collection < TagLibraryInfo > c = pageInfo . getTaglibs ( ) ; if ( c != null && c . size ( ) > 0 ) { taglibs = c . toArray ( new TagLibraryInfo [ 0 ] ) ; } return taglibs ; }


Input: / * [CODESPLIT] private void parseTLD ( JspCompilationContext ctxt , String uri , InputStream in , URL jarFileUrl ) throws JasperException { List < TagInfo > tagVector = new ArrayList < TagInfo > ( ) ; List < TagFileInfo > tagFileVector = new ArrayList < TagFileInfo > ( ) ; HashMap < String , FunctionInfo > functionTable = new HashMap < String , FunctionInfo > ( ) ; // Create an iterator over the child elements of our <taglib> element ParserUtils pu = new ParserUtils ( ) ; TreeNode tld = pu . parseXMLDocument ( uri , in ) ; // Check to see if the <taglib> root element contains a 'version' // attribute, which was added in JSP 2.0 to replace the <jsp-version> // subelement this . jspversion = tld . findAttribute ( "version" ) ; // Process each child element of our <taglib> element Iterator list = tld . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode element = ( TreeNode ) list . next ( ) ; String tname = element . getName ( ) ; if ( "tlibversion" . equals ( tname ) // JSP 1.1 || "tlib-version" . equals ( tname ) ) { // JSP 1.2 this . tlibversion = element . getBody ( ) ; } else if ( "jspversion" . equals ( tname ) || "jsp-version" . equals ( tname ) ) { this . jspversion = element . getBody ( ) ; } else if ( "shortname" . equals ( tname ) || "short-name" . equals ( tname ) ) this . shortname = element . getBody ( ) ; else if ( "uri" . equals ( tname ) ) this . urn = element . getBody ( ) ; else if ( "info" . equals ( tname ) || "description" . equals ( tname ) ) this . info = element . getBody ( ) ; else if ( "validator" . equals ( tname ) ) this . tagLibraryValidator = createValidator ( element ) ; else if ( "tag" . equals ( tname ) ) tagVector . add ( createTagInfo ( element , jspversion ) ) ; else if ( "tag-file" . equals ( tname ) ) { TagFileInfo tagFileInfo = createTagFileInfo ( element , uri , jarFileUrl ) ; tagFileVector . add ( tagFileInfo ) ; } else if ( "function" . equals ( tname ) ) { // JSP2.0 FunctionInfo funcInfo = createFunctionInfo ( element ) ; String funcName = funcInfo . getName ( ) ; if ( functionTable . containsKey ( funcName ) ) { err . jspError ( "jsp.error.tld.fn.duplicate.name" , funcName , uri ) ; } functionTable . put ( funcName , funcInfo ) ; } else if ( "display-name" . equals ( tname ) || // Ignored elements "small-icon" . equals ( tname ) || "large-icon" . equals ( tname ) || "listener" . equals ( tname ) ) { ; } else if ( "taglib-extension" . equals ( tname ) ) { // Recognized but ignored } else { err . jspError ( "jsp.error.unknown.element.in.taglib" , tname ) ; } } if ( tlibversion == null ) { err . jspError ( "jsp.error.tld.mandatory.element.missing" , "tlib-version" ) ; } if ( jspversion == null ) { err . jspError ( "jsp.error.tld.mandatory.element.missing" , "jsp-version" ) ; } this . tags = tagVector . toArray ( new TagInfo [ 0 ] ) ; this . tagFiles = tagFileVector . toArray ( new TagFileInfo [ 0 ] ) ; this . functions = new FunctionInfo [ functionTable . size ( ) ] ; int i = 0 ; for ( FunctionInfo funcInfo : functionTable . values ( ) ) { this . functions [ i ++ ] = funcInfo ; } }


Input: / * @param uri The uri of the TLD @param ctxt The compilation context [CODESPLIT] private String [ ] generateTLDLocation ( String uri , JspCompilationContext ctxt ) throws JasperException { int uriType = TldScanner . uriType ( uri ) ; if ( uriType == TldScanner . ABS_URI ) { err . jspError ( "jsp.error.taglibDirective.absUriCannotBeResolved" , uri ) ; } else if ( uriType == TldScanner . NOROOT_REL_URI ) { uri = ctxt . resolveRelativeUri ( uri ) ; } String [ ] location = new String [ 2 ] ; location [ 0 ] = uri ; if ( location [ 0 ] . endsWith ( "jar" ) ) { URL url = null ; try { url = ctxt . getResource ( location [ 0 ] ) ; } catch ( Exception ex ) { err . jspError ( "jsp.error.tld.unable_to_get_jar" , location [ 0 ] , ex . toString ( ) ) ; } if ( url == null ) { err . jspError ( "jsp.error.tld.missing_jar" , location [ 0 ] ) ; } location [ 0 ] = url . toString ( ) ; location [ 1 ] = "META-INF/taglib.tld" ; } return location ; }


Input: / * Parses the tag file directives of the given TagFile and turns them into a TagInfo . [CODESPLIT] private TagFileInfo createTagFileInfo ( TreeNode elem , String uri , URL jarFileUrl ) throws JasperException { String name = null ; String path = null ; String description = null ; String displayName = null ; String icon = null ; boolean checkConflict = false ; Iterator list = elem . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode child = ( TreeNode ) list . next ( ) ; String tname = child . getName ( ) ; if ( "name" . equals ( tname ) ) { name = child . getBody ( ) ; } else if ( "path" . equals ( tname ) ) { path = child . getBody ( ) ; } else if ( "description" . equals ( tname ) ) { checkConflict = true ; description = child . getBody ( ) ; } else if ( "display-name" . equals ( tname ) ) { checkConflict = true ; displayName = child . getBody ( ) ; } else if ( "icon" . equals ( tname ) ) { checkConflict = true ; icon = child . getBody ( ) ; } else if ( "example" . equals ( tname ) ) { // Ignore <example> element: Bugzilla 33538 } else if ( "tag-extension" . equals ( tname ) ) { // Ignore <tag-extension> element: Bugzilla 33538 } else { err . jspError ( "jsp.error.unknown.element.in.tagfile" , tname ) ; } } if ( path . startsWith ( "/META-INF/tags" ) ) { // Tag file packaged in JAR // STARTJR: fix possible NPE if ( jarFileUrl != null ) { ctxt . getTagFileJarUrls ( ) . put ( path , jarFileUrl ) ; } // ENDJR: fix possible NPE } else if ( ! path . startsWith ( "/WEB-INF/tags" ) ) { err . jspError ( "jsp.error.tagfile.illegalPath" , path ) ; } JasperTagInfo tagInfo = ( JasperTagInfo ) TagFileProcessor . parseTagFileDirectives ( parserController , name , path , this ) ; if ( checkConflict ) { String tstring = tagInfo . getInfoString ( ) ; if ( tstring != null && ! "" . equals ( tstring ) ) { description = tstring ; } tstring = tagInfo . getDisplayName ( ) ; if ( tstring != null && ! "" . equals ( tstring ) ) { displayName = tstring ; } tstring = tagInfo . getSmallIcon ( ) ; if ( tstring != null && ! "" . equals ( tstring ) ) { icon = tstring ; } tagInfo = new JasperTagInfo ( tagInfo . getTagName ( ) , tagInfo . getTagClassName ( ) , tagInfo . getBodyContent ( ) , description , tagInfo . getTagLibrary ( ) , tagInfo . getTagExtraInfo ( ) , tagInfo . getAttributes ( ) , displayName , icon , tagInfo . getLargeIcon ( ) , tagInfo . getTagVariableInfos ( ) , tagInfo . getDynamicAttributesMapName ( ) ) ; } return new TagFileInfo ( name , path , tagInfo ) ; }


Input: Translation - time validation of the XML document associated with the JSP page . This is a convenience method on the associated TagLibraryValidator class . [CODESPLIT] public ValidationMessage [ ] validate ( PageData thePage ) { TagLibraryValidator tlv = getTagLibraryValidator ( ) ; if ( tlv == null ) return null ; String uri = getURI ( ) ; if ( uri . startsWith ( "/" ) ) { uri = URN_JSPTLD + uri ; } ValidationMessage [ ] messages = tlv . validate ( getPrefixString ( ) , uri , thePage ) ; tlv . release ( ) ; return messages ; }


Input: Sets this mark s state to a new stream . It will store the current stream in it s includeStack . [CODESPLIT] public void pushStream ( char [ ] inStream , int inFileid , String name , String inBaseDir , String inEncoding ) { // store current state in stack includeStack . push ( new IncludeState ( cursor , line , col , fileid , fileName , baseDir , encoding , stream ) ) ; // set new variables cursor = 0 ; line = 1 ; col = 1 ; fileid = inFileid ; fileName = name ; baseDir = inBaseDir ; encoding = inEncoding ; stream = inStream ; }


Input: / * Restores this mark s state to a previously stored stream . [CODESPLIT] public Mark popStream ( ) { // make sure we have something to pop if ( includeStack . size ( ) <= 0 ) { return null ; } // get previous state in stack IncludeState state = includeStack . pop ( ) ; // set new variables cursor = state . cursor ; line = state . line ; col = state . col ; fileid = state . fileid ; fileName = state . fileName ; baseDir = state . baseDir ; stream = state . stream ; return this ; }


Input: Autodetects the encoding of the XML document supplied by the given input stream . [CODESPLIT] public static Object [ ] getEncoding ( String fname , JarFile jarFile , JspCompilationContext ctxt , ErrorDispatcher err ) throws IOException , JasperException { InputStream inStream = JspUtil . getInputStream ( fname , jarFile , ctxt , err ) ; XMLEncodingDetector detector = new XMLEncodingDetector ( ) ; Object [ ] ret = detector . getEncoding ( inStream , err ) ; inStream . close ( ) ; return ret ; }


Input: org . apache . xerces . impl . XMLEntityManager . startEntity () [CODESPLIT] private void createInitialReader ( ) throws IOException , JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream ( stream ) ; // perform auto-detect of encoding if necessary if ( encoding == null ) { // read first four bytes and determine encoding final byte [ ] b4 = new byte [ 4 ] ; int count = 0 ; for ( ; count < 4 ; count ++ ) { b4 [ count ] = ( byte ) stream . read ( ) ; } if ( count == 4 ) { Object [ ] encodingDesc = getEncodingName ( b4 , count ) ; encoding = ( String ) ( encodingDesc [ 0 ] ) ; isBigEndian = ( Boolean ) ( encodingDesc [ 1 ] ) ; hasBom = ( Boolean ) ( encodingDesc [ 2 ] ) ; stream . reset ( ) ; // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if ( count > 2 && encoding . equals ( "UTF-8" ) ) { int b0 = b4 [ 0 ] & 0xFF ; int b1 = b4 [ 1 ] & 0xFF ; int b2 = b4 [ 2 ] & 0xFF ; if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { // ignore first three bytes... stream . skip ( 3 ) ; } } reader = createReader ( stream , encoding , isBigEndian ) ; } else { reader = createReader ( stream , encoding , isBigEndian ) ; } } }


Input:
Returns the IANA encoding name that is auto - detected from the bytes specified with the endian - ness of that encoding where appropriate . [CODESPLIT] private Object [ ] getEncodingName ( byte [ ] b4 , int count ) { if ( count < 2 ) { return new Object [ ] { "UTF-8" , null , null } ; } // UTF-16, with BOM int b0 = b4 [ 0 ] & 0xFF ; int b1 = b4 [ 1 ] & 0xFF ; if ( b0 == 0xFE && b1 == 0xFF ) { // UTF-16, big-endian, with a BOM return new Object [ ] { "UTF-16BE" , Boolean . TRUE , Boolean . TRUE } ; } /* SJSAS 6307968
        if (b0 == 0xFF && b1 == 0xFE) {
        */ // BEGIN SJSAS 6307968 if ( count == 2 && b0 == 0xFF && b1 == 0xFE ) { // END SJSAS 6307968 // UTF-16, little-endian, with a BOM return new Object [ ] { "UTF-16LE" , Boolean . FALSE , Boolean . TRUE } ; } // default to UTF-8 if we don't have enough bytes to make a // good determination of the encoding if ( count < 3 ) { return new Object [ ] { "UTF-8" , null , null } ; } // UTF-8 with a BOM int b2 = b4 [ 2 ] & 0xFF ; if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { return new Object [ ] { "UTF-8" , null , Boolean . TRUE } ; } // default to UTF-8 if we don't have enough bytes to make a // good determination of the encoding if ( count < 4 ) { return new Object [ ] { "UTF-8" , null , null } ; } // other encodings int b3 = b4 [ 3 ] & 0xFF ; if ( b0 == 0x00 && b1 == 0x00 && b2 == 0x00 && b3 == 0x3C ) { // UCS-4, big endian (1234) return new Object [ ] { "ISO-10646-UCS-4" , Boolean . TRUE , null } ; } if ( b0 == 0x3C && b1 == 0x00 && b2 == 0x00 && b3 == 0x00 ) { // UCS-4, little endian (4321) return new Object [ ] { "ISO-10646-UCS-4" , Boolean . FALSE , null } ; } if ( b0 == 0x00 && b1 == 0x00 && b2 == 0x3C && b3 == 0x00 ) { // UCS-4, unusual octet order (2143) // REVISIT: What should this be? return new Object [ ] { "ISO-10646-UCS-4" , null , null } ; } if ( b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x00 ) { // UCS-4, unusual octect order (3412) // REVISIT: What should this be? return new Object [ ] { "ISO-10646-UCS-4" , null , null } ; } if ( b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F ) { // UTF-16, big-endian, no BOM // (or could turn out to be UCS-2... // REVISIT: What should this be? return new Object [ ] { "UTF-16BE" , Boolean . TRUE , null } ; } if ( b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00 ) { // UTF-16, little-endian, no BOM // (or could turn out to be UCS-2... return new Object [ ] { "UTF-16LE" , Boolean . FALSE , null } ; } if ( b0 == 0x4C && b1 == 0x6F && b2 == 0xA7 && b3 == 0x94 ) { // EBCDIC // a la xerces1, return CP037 instead of EBCDIC here return new Object [ ] { "CP037" , null , null } ; } if ( b0 == 0x00 && b1 == 0x00 && b2 == 0xFE && b3 == 0xFF ) { // UTF-32, big-endian, with a BOM return new Object [ ] { "UTF-32BE" , Boolean . TRUE , Boolean . TRUE } ; } if ( b0 == 0xFF && b1 == 0xFE && b2 == 0x00 && b3 == 0x00 ) { // UTF-32, little-endian, with a BOM return new Object [ ] { "UTF-32LE" , Boolean . FALSE , Boolean . TRUE } ; } // BEGIN SJSAS 6307968 if ( b0 == 0xFF && b1 == 0xFE ) { // UTF-16, little-endian, with a BOM return new Object [ ] { "UTF-16LE" , Boolean . FALSE , Boolean . TRUE } ; } // END SJSAS 6307968 // default encoding return new Object [ ] { "UTF-8" , null , null } ; }


Input: org . apache . xerces . impl . XMLDocumentScannerImpl . dispatch [CODESPLIT] private void scanXMLDecl ( ) throws IOException , JasperException { if ( skipString ( "<?xml" ) ) { fMarkupDepth ++ ; // NOTE: special case where document starts with a PI //       whose name starts with "xml" (e.g. "xmlfoo") if ( XMLChar . isName ( peekChar ( ) ) ) { fStringBuffer . clear ( ) ; fStringBuffer . append ( "xml" ) ; while ( XMLChar . isName ( peekChar ( ) ) ) { fStringBuffer . append ( ( char ) scanChar ( ) ) ; } String target = fSymbolTable . addSymbol ( fStringBuffer . ch , fStringBuffer . offset , fStringBuffer . length ) ; scanPIData ( target , fString ) ; } // standard XML declaration else { scanXMLDeclOrTextDecl ( false ) ; } } }


Input: Scans an XML or text declaration . <p > <pre > [ 23 ] XMLDecl :: = &lt ; ?xml VersionInfo EncodingDecl? SDDecl? S? ? > [ 24 ] VersionInfo :: = S version Eq ( VersionNum | VersionNum ) [ 80 ] EncodingDecl :: = S encoding Eq ( EncName | EncName ) [ 81 ] EncName :: = [ A - Za - z ] ( [ A - Za - z0 - 9 . _ ] | - ) * [ 32 ] SDDecl :: = S standalone Eq (( ( yes | no ) ) | ( ( yes | no ) )) [CODESPLIT] private void scanXMLDeclOrTextDecl ( boolean scanningTextDecl ) throws IOException , JasperException { // scan decl scanXMLDeclOrTextDecl ( scanningTextDecl , fStrings ) ; fMarkupDepth -- ; // pseudo-attribute values String encodingPseudoAttr = fStrings [ 1 ] ; // set encoding on reader if ( encodingPseudoAttr != null ) { isEncodingSetInProlog = true ; encoding = encodingPseudoAttr ; } }


Input: Scans surrogates and append them to the specified buffer . <p > <strong > Note : < / strong > This assumes the current char has already been identified as a high surrogate . [CODESPLIT] private boolean scanSurrogates ( XMLStringBuffer buf ) throws IOException , JasperException { int high = scanChar ( ) ; int low = peekChar ( ) ; if ( ! XMLChar . isLowSurrogate ( low ) ) { err . jspError ( "jsp.error.xml.invalidCharInContent" , Integer . toString ( high , 16 ) ) ; return false ; } scanChar ( ) ; // convert surrogates to supplemental character int c = XMLChar . supplemental ( ( char ) high , ( char ) low ) ; // supplemental character must be a valid XML character if ( ! XMLChar . isValid ( c ) ) { err . jspError ( "jsp.error.xml.invalidCharInContent" , Integer . toString ( c , 16 ) ) ; return false ; } // fill in the buffer buf . append ( ( char ) high ) ; buf . append ( ( char ) low ) ; return true ; }


Input: Convenience function used in all XML scanners . [CODESPLIT] private void reportFatalError ( String msgId , String arg ) throws JasperException { err . jspError ( msgId , arg ) ; }


Input: Create a set of default repository links <p > This method calls { @link #fillRepoLinks ( ChannelInformation List String int String int LinkTarget ) } by using the baseName also as prefix and using a default { @code priorityOffset } of 10_000 < / p > [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final LinkTarget linkTemplate ) { fillRepoLinks ( channel , links , baseName , basePriority , baseName , 10_000 , linkTemplate ) ; }


Input: Create a set of default repository links [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final String prefix , final int priorityOffset , final LinkTarget linkTemplate ) { Objects . requireNonNull ( linkTemplate , "'linkTemplate' must not be null" ) ; fillRepoLinks ( channel , links , baseName , basePriority , prefix , priorityOffset , idOrName -> makeDefaultRepoLink ( linkTemplate , idOrName ) ) ; }


Input: Create a set of default repository links [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final String prefix , final int priorityOffset , final Function < String , LinkTarget > targetFunction ) { Objects . requireNonNull ( channel , "'channel' must not be null" ) ; Objects . requireNonNull ( links , "'links' must not be null" ) ; Objects . requireNonNull ( baseName , "'baseName' must not be null" ) ; Objects . requireNonNull ( prefix , "'prefix' must not be null" ) ; Objects . requireNonNull ( targetFunction , "'targetFunction' must not be null" ) ; links . add ( new MenuEntry ( baseName , basePriority , prefix + " (by ID)" , priorityOffset , targetFunction . apply ( channel . getId ( ) ) , Modifier . LINK , null ) ) ; int i = 1 ; for ( final String name : channel . getNames ( ) ) { final LinkTarget target = targetFunction . apply ( name ) ; if ( target != null ) { links . add ( new MenuEntry ( baseName , basePriority , String . format ( "%s (name: %s)" , prefix , name ) , priorityOffset + i , target , Modifier . LINK , null ) ) ; } i ++ ; } }


Input: Return the real path for the specified context - relative virtual path . [CODESPLIT] public String getRealPath ( String path ) { if ( ! myResourceBaseURL . getProtocol ( ) . equals ( "file" ) ) return ( null ) ; if ( ! path . startsWith ( "/" ) ) return ( null ) ; try { return ( getResource ( path ) . getFile ( ) . replace ( ' ' , File . separatorChar ) ) ; } catch ( Throwable t ) { return ( null ) ; } }


Input: Return a URL object of a resource that is mapped to the specified context - relative path . [CODESPLIT] public URL getResource ( String path ) throws MalformedURLException { if ( ! path . startsWith ( "/" ) ) throw new MalformedURLException ( "Path '" + path + "' does not start with '/'" ) ; URL url = new URL ( myResourceBaseURL , path . substring ( 1 ) ) ; InputStream is = null ; try { is = url . openStream ( ) ; } catch ( Throwable t ) { url = null ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Throwable t2 ) { // Ignore } } } return url ; }


Input: Return an InputStream allowing access to the resource at the specified context - relative path . [CODESPLIT] public InputStream getResourceAsStream ( String path ) { try { return ( getResource ( path ) . openStream ( ) ) ; } catch ( Throwable t ) { return ( null ) ; } }


Input: Return the set of resource paths for the directory at the specified context path . [CODESPLIT] public Set < String > getResourcePaths ( String path ) { Set < String > thePaths = new HashSet < String > ( ) ; if ( ! path . endsWith ( "/" ) ) path += "/" ; String basePath = getRealPath ( path ) ; if ( basePath == null ) return ( thePaths ) ; File theBaseDir = new File ( basePath ) ; if ( ! theBaseDir . exists ( ) || ! theBaseDir . isDirectory ( ) ) return ( thePaths ) ; String theFiles [ ] = theBaseDir . list ( ) ; for ( int i = 0 ; i < theFiles . length ; i ++ ) { File testFile = new File ( basePath + File . separator + theFiles [ i ] ) ; if ( testFile . isFile ( ) ) thePaths . add ( path + theFiles [ i ] ) ; else if ( testFile . isDirectory ( ) ) thePaths . add ( path + theFiles [ i ] + "/" ) ; } return ( thePaths ) ; }


Input: Log the specified message and exception . [CODESPLIT] public void log ( String message , Throwable exception ) { myLogWriter . println ( message ) ; exception . printStackTrace ( myLogWriter ) ; }


Input: / * Adds the servlet with the given name description class name init parameters and loadOnStartup to this servlet context . [CODESPLIT] public void addServlet ( String servletName , String description , String className , Map < String , String > initParameters , int loadOnStartup ) { // Do nothing return ; }


Input: Adds the filter with the given name description and class name to this servlet context . [CODESPLIT] public void addFilter ( String filterName , String description , String className , Map < String , String > initParameters ) { // Do nothing return ; }


Input: Updates the filter chain with a single filter . This is equivalent to passing a single - member FilterOptions array to <code > updateFilters ( FilterOptions [] ) < / code > . [CODESPLIT] public void updateFilters ( FilterOptions filterOptions ) throws XZIOException { FilterOptions [ ] opts = new FilterOptions [ 1 ] ; opts [ 0 ] = filterOptions ; updateFilters ( opts ) ; }


Input: Updates the filter chain with 1 - 4 filters . <p > Currently this cannot be used to update e . g . LZMA2 options in the middle of a XZ Block . Use <code > endBlock () < / code > to finish the current XZ Block before calling this function . The new filter chain will then be used for the next XZ Block . [CODESPLIT] public void updateFilters ( FilterOptions [ ] filterOptions ) throws XZIOException { if ( blockEncoder != null ) throw new UnsupportedOptionsException ( "Changing filter options " + "in the middle of a XZ Block not implemented" ) ; if ( filterOptions . length < 1 || filterOptions . length > 4 ) throw new UnsupportedOptionsException ( "XZ filter chain must be 1-4 filters" ) ; filtersSupportFlushing = true ; FilterEncoder [ ] newFilters = new FilterEncoder [ filterOptions . length ] ; for ( int i = 0 ; i < filterOptions . length ; ++ i ) { newFilters [ i ] = filterOptions [ i ] . getFilterEncoder ( ) ; filtersSupportFlushing &= newFilters [ i ] . supportsFlushing ( ) ; } RawCoder . validate ( newFilters ) ; filters = newFilters ; }


Input: Writes an array of bytes to be compressed . The compressors tend to do internal buffering and thus the written data won t be readable from the compressed output immediately . Use <code > flush () < / code > to force everything written so far to be written to the underlaying output stream but be aware that flushing reduces compression ratio . [CODESPLIT] public void write ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( "Stream finished or closed" ) ; try { if ( blockEncoder == null ) blockEncoder = new BlockOutputStream ( out , filters , check , arrayCache ) ; blockEncoder . write ( buf , off , len ) ; } catch ( IOException e ) { exception = e ; throw e ; } }


Input: Finishes the current XZ Block ( but not the whole XZ Stream ) . This doesn t flush the stream so it s possible that not all data will be decompressible from the output stream when this function returns . Call also <code > flush () < / code > if flushing is wanted in addition to finishing the current XZ Block . <p > If there is no unfinished Block open this function will do nothing . ( No empty XZ Block will be created . ) <p > This function can be useful for example to create random - accessible . xz files . <p > Starting a new XZ Block means that the encoder state is reset . Doing this very often will increase the size of the compressed file a lot ( more than plain <code > flush () < / code > would do ) . [CODESPLIT] public void endBlock ( ) throws IOException { if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( "Stream finished or closed" ) ; // NOTE: Once there is threading with multiple Blocks, it's possible // that this function will be more like a barrier that returns // before the last Block has been finished. if ( blockEncoder != null ) { try { blockEncoder . finish ( ) ; index . add ( blockEncoder . getUnpaddedSize ( ) , blockEncoder . getUncompressedSize ( ) ) ; blockEncoder = null ; } catch ( IOException e ) { exception = e ; throw e ; } } }


Input: Flushes the encoder and calls <code > out . flush () < / code > . All buffered pending data will then be decompressible from the output stream . <p > Calling this function very often may increase the compressed file size a lot . The filter chain options may affect the size increase too . For example with LZMA2 the HC4 match finder has smaller penalty with flushing than BT4 . <p > Some filters don t support flushing . If the filter chain has such a filter <code > flush () < / code > will call <code > endBlock () < / code > before flushing . [CODESPLIT] public void flush ( ) throws IOException { if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( "Stream finished or closed" ) ; try { if ( blockEncoder != null ) { if ( filtersSupportFlushing ) { // This will eventually call out.flush() so // no need to do it here again. blockEncoder . flush ( ) ; } else { endBlock ( ) ; out . flush ( ) ; } } else { out . flush ( ) ; } } catch ( IOException e ) { exception = e ; throw e ; } }


Input: Finishes compression without closing the underlying stream . No more data can be written to this stream after finishing ( calling <code > write< / code > with an empty buffer is OK ) . <p > Repeated calls to <code > finish () < / code > do nothing unless an exception was thrown by this stream earlier . In that case the same exception is thrown again . <p > After finishing the stream may be closed normally with <code > close () < / code > . If the stream will be closed anyway there usually is no need to call <code > finish () < / code > separately . [CODESPLIT] public void finish ( ) throws IOException { if ( ! finished ) { // This checks for pending exceptions so we don't need to // worry about it here. endBlock ( ) ; try { index . encode ( out ) ; encodeStreamFooter ( ) ; } catch ( IOException e ) { exception = e ; throw e ; } // Set it to true only if everything goes fine. Setting it earlier // would cause repeated calls to finish() do nothing instead of // throwing an exception to indicate an earlier error. finished = true ; } }


Input: Finishes compression and closes the underlying stream . The underlying stream <code > out< / code > is closed even if finishing fails . If both finishing and closing fail the exception thrown by <code > finish () < / code > is thrown and the exception from the failed <code > out . close () < / code > is lost . [CODESPLIT] public void close ( ) throws IOException { if ( out != null ) { // If finish() throws an exception, it stores the exception to // the variable "exception". So we can ignore the possible // exception here. try { finish ( ) ; } catch ( IOException e ) { } try { out . close ( ) ; } catch ( IOException e ) { // Remember the exception but only if there is no previous // pending exception. if ( exception == null ) exception = e ; } out = null ; } if ( exception != null ) throw exception ; }


Input: Gets the size of the LZ window buffer that needs to be allocated . [CODESPLIT] private static int getBufSize ( int dictSize , int extraSizeBefore , int extraSizeAfter , int matchLenMax ) { int keepSizeBefore = extraSizeBefore + dictSize ; int keepSizeAfter = extraSizeAfter + matchLenMax ; int reserveSize = Math . min ( dictSize / 2 + ( 256 << 10 ) , 512 << 20 ) ; return keepSizeBefore + keepSizeAfter + reserveSize ; }


Input: Gets approximate memory usage of the LZEncoder base structure and the match finder as kibibytes . [CODESPLIT] public static int getMemoryUsage ( int dictSize , int extraSizeBefore , int extraSizeAfter , int matchLenMax , int mf ) { // Buffer size + a little extra int m = getBufSize ( dictSize , extraSizeBefore , extraSizeAfter , matchLenMax ) / 1024 + 10 ; switch ( mf ) { case MF_HC4 : m += HC4 . getMemoryUsage ( dictSize ) ; break ; case MF_BT4 : m += BT4 . getMemoryUsage ( dictSize ) ; break ; default : throw new IllegalArgumentException ( ) ; } return m ; }


Input: Creates a new LZEncoder . <p > @param dictSize dictionary size [CODESPLIT] public static LZEncoder getInstance ( int dictSize , int extraSizeBefore , int extraSizeAfter , int niceLen , int matchLenMax , int mf , int depthLimit , ArrayCache arrayCache ) { switch ( mf ) { case MF_HC4 : return new HC4 ( dictSize , extraSizeBefore , extraSizeAfter , niceLen , matchLenMax , depthLimit , arrayCache ) ; case MF_BT4 : return new BT4 ( dictSize , extraSizeBefore , extraSizeAfter , niceLen , matchLenMax , depthLimit , arrayCache ) ; } throw new IllegalArgumentException ( ) ; }


Input: Sets a preset dictionary . If a preset dictionary is wanted this function must be called immediately after creating the LZEncoder before any data has been encoded . [CODESPLIT] public void setPresetDict ( int dictSize , byte [ ] presetDict ) { assert ! isStarted ( ) ; assert writePos == 0 ; if ( presetDict != null ) { // If the preset dictionary buffer is bigger than the dictionary // size, copy only the tail of the preset dictionary. int copySize = Math . min ( presetDict . length , dictSize ) ; int offset = presetDict . length - copySize ; System . arraycopy ( presetDict , offset , buf , 0 , copySize ) ; writePos += copySize ; skip ( copySize ) ; } }


Input: Moves data from the end of the buffer to the beginning discarding old data and making space for new input . [CODESPLIT] private void moveWindow ( ) { // Align the move to a multiple of 16 bytes. LZMA2 needs this // because it uses the lowest bits from readPos to get the // alignment of the uncompressed data. int moveOffset = ( readPos + 1 - keepSizeBefore ) & ~ 15 ; int moveSize = writePos - moveOffset ; System . arraycopy ( buf , moveOffset , buf , 0 , moveSize ) ; readPos -= moveOffset ; readLimit -= moveOffset ; writePos -= moveOffset ; }


Input: Copies new data into the LZEncoder s buffer . [CODESPLIT] public int fillWindow ( byte [ ] in , int off , int len ) { assert ! finishing ; // Move the sliding window if needed. if ( readPos >= bufSize - keepSizeAfter ) moveWindow ( ) ; // Try to fill the dictionary buffer. If it becomes full, // some of the input bytes may be left unused. if ( len > bufSize - writePos ) len = bufSize - writePos ; System . arraycopy ( in , off , buf , writePos , len ) ; writePos += len ; // Set the new readLimit but only if there's enough data to allow // encoding of at least one more byte. if ( writePos >= keepSizeAfter ) readLimit = writePos - keepSizeAfter ; processPendingBytes ( ) ; // Tell the caller how much input we actually copied into // the dictionary. return len ; }