Input: / * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void comment ( char [ ] buf , int offset , int len ) throws SAXException { processChars ( ) ; // Flush char buffer and remove white spaces // ignore comments in the DTD if ( ! inDTD ) { startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; new Node . Comment ( new String ( buf , offset , len ) , startMark , current ) ; } }


Input: / * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void startCDATA ( ) throws SAXException { processChars ( ) ; // Flush char buffer and remove white spaces startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; }


Input: / * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void startDTD ( String name , String publicId , String systemId ) throws SAXException { if ( ! isValidating ) { fatalError ( ENABLE_DTD_VALIDATION_EXCEPTION ) ; } inDTD = true ; }


Input: / * Receives notification of the start of a Namespace mapping . [CODESPLIT] public void startPrefixMapping ( String prefix , String uri ) throws SAXException { if ( directivesOnly && ! ( JSP_URI . equals ( uri ) ) ) { return ; } try { addTaglibInfo ( prefix , uri ) ; } catch ( JasperException je ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.could.not.add.taglibraries" ) , locator , je ) ; } }


Input: / * Receives notification of the end of a Namespace mapping . [CODESPLIT] public void endPrefixMapping ( String prefix ) throws SAXException { if ( directivesOnly ) { String uri = pageInfo . getURI ( prefix ) ; if ( ! JSP_URI . equals ( uri ) ) { return ; } } pageInfo . popPrefixMapping ( prefix ) ; }


Input: Private utility methods [CODESPLIT] private Node parseStandardAction ( String qName , String localName , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { Node node = null ; if ( localName . equals ( ROOT_ACTION ) ) { if ( ! ( current instanceof Node . Root ) ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.nested_jsproot" ) , locator ) ; } node = new Node . JspRoot ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; if ( isTop ) { pageInfo . setHasJspRoot ( true ) ; } } else if ( localName . equals ( PAGE_DIRECTIVE_ACTION ) ) { if ( isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.istagfile" , localName ) , locator ) ; } node = new Node . PageDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( "import" ) ; // There can only be one 'import' attribute per page directive if ( imports != null ) { ( ( Node . PageDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( INCLUDE_DIRECTIVE_ACTION ) ) { node = new Node . IncludeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; processIncludeDirective ( nonTaglibAttrs . getValue ( "file" ) , node ) ; } else if ( localName . equals ( DECLARATION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Declaration ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SCRIPTLET_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Scriptlet ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( EXPRESSION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( "jsp.error.no.scriptlets" , localName ) , locator ) ; } node = new Node . Expression ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( USE_BEAN_ACTION ) ) { node = new Node . UseBean ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SET_PROPERTY_ACTION ) ) { node = new Node . SetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( GET_PROPERTY_ACTION ) ) { node = new Node . GetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INCLUDE_ACTION ) ) { node = new Node . IncludeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FORWARD_ACTION ) ) { node = new Node . ForwardAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAM_ACTION ) ) { node = new Node . ParamAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAMS_ACTION ) ) { node = new Node . ParamsAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PLUGIN_ACTION ) ) { node = new Node . PlugIn ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TEXT_ACTION ) ) { node = new Node . JspText ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( BODY_ACTION ) ) { node = new Node . JspBody ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ATTRIBUTE_ACTION ) ) { node = new Node . NamedAttribute ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( OUTPUT_ACTION ) ) { node = new Node . JspOutput ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TAG_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . TagDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( "import" ) ; // There can only be one 'import' attribute per tag directive if ( imports != null ) { ( ( Node . TagDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( ATTRIBUTE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . AttributeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( VARIABLE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . VariableDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INVOKE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . InvokeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( DOBODY_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.action.isnottagfile" , localName ) , locator ) ; } node = new Node . DoBodyAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ELEMENT_ACTION ) ) { node = new Node . JspElement ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FALLBACK_ACTION ) ) { node = new Node . FallBackAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.xml.badStandardAction" , localName ) , locator ) ; } return node ; }


Input: / * Checks if the XML element with the given tag name is a custom action and returns the corresponding Node object . [CODESPLIT] private Node parseCustomAction ( String qName , String localName , String uri , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo . getTaglib ( uri ) ; if ( tagLibInfo == null ) { return null ; } TagInfo tagInfo = tagLibInfo . getTag ( localName ) ; TagFileInfo tagFileInfo = tagLibInfo . getTagFile ( localName ) ; if ( tagInfo == null && tagFileInfo == null ) { throw new SAXException ( Localizer . getMessage ( "jsp.error.xml.bad_tag" , localName , uri ) ) ; } Class tagHandlerClass = null ; if ( tagInfo != null ) { String handlerClassName = tagInfo . getTagClassName ( ) ; try { tagHandlerClass = ctxt . getClassLoader ( ) . loadClass ( handlerClassName ) ; } catch ( Exception e ) { throw new SAXException ( Localizer . getMessage ( "jsp.error.loadclass.taghandler" , handlerClassName , qName ) , e ) ; } } String prefix = "" ; int colon = qName . indexOf ( ' ' ) ; if ( colon != - 1 ) { prefix = qName . substring ( 0 , colon ) ; } Node . CustomTag ret = null ; if ( tagInfo != null ) { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagInfo , tagHandlerClass ) ; } else { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagFileInfo ) ; } return ret ; }


Input:
/ * Adds the tag library associated with the given uri namespace to the translation unit that this parser is associated with . [CODESPLIT] private void addTaglibInfo ( String prefix , String uri ) throws JasperException { if ( uri . startsWith ( URN_JSPTAGDIR ) ) { // uri (of the form "urn:jsptagdir:path") references tag file dir String tagdir = uri . substring ( URN_JSPTAGDIR . length ( ) ) ; TagLibraryInfo taglibInfo = new ImplicitTagLibraryInfo ( ctxt , parserController , prefix , tagdir , err ) ; if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , taglibInfo ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { // uri references TLD file boolean isPlainUri = false ; if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } else { isPlainUri = true ; } // START GlassFish 750 ConcurrentHashMap < String , TagLibraryInfoImpl > taglibs = ctxt . getTaglibs ( ) ; TagLibraryInfoImpl taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { synchronized ( taglibs ) { taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { // END GlassFish 750             String [ ] location = ctxt . getTldLocation ( uri ) ; if ( location != null || ! isPlainUri ) { /*
                             * If the uri value is a plain uri, a translation
                             * error must not be generated if the uri is not
                             * found in the taglib map.
                             * Instead, any actions in the namespace defined
                             * by the uri value must be treated as
                             * uninterpreted.
                             */ taglibInfo = new TagLibraryInfoImpl ( ctxt , parserController , prefix , uri , location , err ) ; // START GlassFish 750 ctxt . addTaglib ( uri , taglibInfo ) ; pageInfo . addTaglib ( uri , taglibInfo ) ; // END GlassFish 750 } // START GlassFish 750 } } } // END GlassFish 750 if ( taglibInfo != null ) { if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , new TagLibraryInfoImpl ( prefix , uri , taglibInfo , pageInfo ) ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { pageInfo . pushPrefixMapping ( prefix , null ) ; } } }


Input: / * Ensures that the given body only contains nodes that are instances of TemplateText . [CODESPLIT] private void checkScriptingBody ( Node . ScriptingElement scriptingElem ) throws SAXException { Node . Nodes body = scriptingElem . getBody ( ) ; if ( body != null ) { int size = body . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node n = body . getNode ( i ) ; if ( ! ( n instanceof Node . TemplateText ) ) { String elemType = SCRIPTLET_ACTION ; if ( scriptingElem instanceof Node . Declaration ) elemType = DECLARATION_ACTION ; if ( scriptingElem instanceof Node . Expression ) elemType = EXPRESSION_ACTION ; String msg = Localizer . getMessage ( "jsp.error.parse.xml.scripting.invalid.body" , elemType ) ; throw new SAXException ( msg ) ; } } } }


Input: / * Parses the given file included via an include directive . [CODESPLIT] private void processIncludeDirective ( String fname , Node parent ) throws SAXException { if ( fname == null ) { return ; } try { parserController . parse ( fname , parent , null ) ; } catch ( FileNotFoundException fnfe ) { throw new SAXParseException ( Localizer . getMessage ( "jsp.error.file.not.found" , fname ) , locator , fnfe ) ; } catch ( Exception e ) { throw new SAXException ( e ) ; } }


Input: / * Checks an element s given URI qname and attributes to see if any of them hijack the jsp prefix that is bind it to a namespace other than http : // java . sun . com / JSP / Page . [CODESPLIT] private void checkPrefixes ( String uri , String qName , Attributes attrs ) { checkPrefix ( uri , qName ) ; int len = attrs . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { checkPrefix ( attrs . getURI ( i ) , attrs . getQName ( i ) ) ; } }


Input: / * Checks the given URI and qname to see if they hijack the jsp prefix which would be the case if qName contained the jsp prefix and uri was different from http : // java . sun . com / JSP / Page . [CODESPLIT] private void checkPrefix ( String uri , String qName ) { int index = qName . indexOf ( ' ' ) ; if ( index != - 1 ) { String prefix = qName . substring ( 0 , index ) ; pageInfo . addPrefix ( prefix ) ; if ( "jsp" . equals ( prefix ) && ! JSP_URI . equals ( uri ) ) { pageInfo . setIsJspPrefixHijacked ( true ) ; } } }


Input: / * Gets SAXParser . [CODESPLIT] private static SAXParser getSAXParser ( boolean validating , JspDocumentParser jspDocParser ) throws Exception { SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; // Preserve xmlns attributes factory . setFeature ( "http://xml.org/sax/features/namespace-prefixes" , true ) ; factory . setFeature ( "http://xml.org/sax/features/validation" , validating ) ; // Configure the parser SAXParser saxParser = factory . newSAXParser ( ) ; XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setProperty ( LEXICAL_HANDLER_PROPERTY , jspDocParser ) ; xmlReader . setErrorHandler ( jspDocParser ) ; return saxParser ; }


Input: Load the class with the specified name searching using the following algorithm until it finds and returns the class . If the class cannot be found returns <code > ClassNotFoundException< / code > . <ul > <li > Call <code > findLoadedClass ( String ) < / code > to check if the class has already been loaded . If it has the same <code > Class< / code > object is returned . < / li > <li > If the <code > delegate< / code > property is set to <code > true< / code > call the <code > loadClass () < / code > method of the parent class loader if any . < / li > <li > Call <code > findClass () < / code > to find this class in our locally defined repositories . < / li > <li > Call the <code > loadClass () < / code > method of our parent class loader if any . < / li > < / ul > If the class was found using the above steps and the <code > resolve< / code > flag is <code > true< / code > this method will then call <code > resolveClass ( Class ) < / code > on the resulting Class object . [CODESPLIT] public synchronized Class loadClass ( final String name , boolean resolve ) throws ClassNotFoundException { Class clazz = null ; // (0) Check our previously loaded class cache clazz = findLoadedClass ( name ) ; if ( clazz != null ) { if ( resolve ) resolveClass ( clazz ) ; return ( clazz ) ; } // (.5) Permission to access this class when using a SecurityManager if ( securityManager != null ) { int dot = name . lastIndexOf ( ' ' ) ; if ( dot >= 0 ) { try { // Do not call the security manager since by default, we grant that package. if ( ! "org.apache.jasper.runtime" . equalsIgnoreCase ( name . substring ( 0 , dot ) ) ) { securityManager . checkPackageAccess ( name . substring ( 0 , dot ) ) ; } } catch ( SecurityException se ) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name ; se . printStackTrace ( ) ; throw new ClassNotFoundException ( error ) ; } } } if ( ! name . startsWith ( Constants . JSP_PACKAGE_NAME ) ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent . loadClass ( name ) ; if ( resolve ) resolveClass ( clazz ) ; return clazz ; } return findClass ( name ) ; }


Input:
START OF IASRI 4709374 [CODESPLIT] public Class findClass ( String className ) throws ClassNotFoundException { // If the class file is in memory, use it byte [ ] cdata = this . bytecodes . get ( className ) ; String path = className . replace ( ' ' , ' ' ) + ".class" ; if ( cdata == null ) { // If the bytecode preprocessor is not enabled, use super.findClass // as usual. /* XXX
            if (!PreprocessorUtil.isPreprocessorEnabled()) {
                return super.findClass(className);
            }
*/ // read class data from file cdata = loadClassDataFromFile ( path ) ; if ( cdata == null ) { throw new ClassNotFoundException ( className ) ; } } // Preprocess the loaded byte code /* XXX
        if (PreprocessorUtil.isPreprocessorEnabled()) {
            cdata = PreprocessorUtil.processClass(path, cdata);
        }
*/ Class clazz = null ; if ( securityManager != null ) { ProtectionDomain pd = new ProtectionDomain ( codeSource , permissionCollection ) ; clazz = defineClass ( className , cdata , 0 , cdata . length , pd ) ; } else { clazz = defineClass ( className , cdata , 0 , cdata . length ) ; } return clazz ; }


Input: / * Load JSP class data from file . [CODESPLIT] private byte [ ] loadClassDataFromFile ( final String fileName ) { byte [ ] classBytes = null ; try { InputStream in = null ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { in = AccessController . doPrivileged ( new PrivilegedAction < InputStream > ( ) { public InputStream run ( ) { return getResourceAsStream ( fileName ) ; } } ) ; } else { in = getResourceAsStream ( fileName ) ; } if ( in == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte buf [ ] = new byte [ 1024 ] ; for ( int i = 0 ; ( i = in . read ( buf ) ) != - 1 ; ) { baos . write ( buf , 0 , i ) ; } in . close ( ) ; baos . close ( ) ; classBytes = baos . toByteArray ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return null ; } return classBytes ; }


Input: Call and wrap { @link Exception } s into a { @link RuntimeException } [CODESPLIT] public static < T > T wrapException ( final Callable < T > callable ) { try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }


Input: Call and wrap { @link Exception } s into an exception provided by the function . <p > If the function returns { @code null } a { @link RuntimeException } will be created instead . < / p > [CODESPLIT] public static < T > T wrapException ( final Callable < T > callable , final Function < Exception , RuntimeException > func ) { try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { RuntimeException t = func . apply ( e ) ; if ( t == null ) { t = new RuntimeException ( e ) ; } else { // fixing the stack trace to be a bit more precise t . setStackTrace ( Thread . currentThread ( ) . getStackTrace ( ) ) ; } throw t ; } }


Input: Parse the basic authentication header [CODESPLIT] public static String [ ] parseAuthorization ( final HttpServletRequest request ) { final String auth = request . getHeader ( "Authorization" ) ; logger . debug ( "Auth header: {}" , auth ) ; if ( auth == null || auth . isEmpty ( ) ) { return null ; } final String [ ] toks = auth . split ( "\\s" ) ; if ( toks . length < 2 ) { return null ; } if ( ! "Basic" . equalsIgnoreCase ( toks [ 0 ] ) ) { return null ; } final byte [ ] authData = Base64 . getDecoder ( ) . decode ( toks [ 1 ] ) ; final String authStr = StandardCharsets . ISO_8859_1 . decode ( ByteBuffer . wrap ( authData ) ) . toString ( ) ; logger . debug ( "Auth String: {}" , authStr ) ; final String [ ] authToks = authStr . split ( ":" , 2 ) ; logger . debug ( "Auth tokens: {}" , new Object [ ] { authToks } ) ; if ( authToks . length != 2 ) { return null ; } return authToks ; }


Input: Generated Servlet and Tag Handler implementations call this method to retrieve an instance of the ProtectedFunctionMapper . This is necessary since generated code does not have access to create instances of classes in this package . [CODESPLIT] public static ProtectedFunctionMapper getInstance ( ) { ProtectedFunctionMapper funcMapper ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { funcMapper = AccessController . doPrivileged ( new PrivilegedAction < ProtectedFunctionMapper > ( ) { public ProtectedFunctionMapper run ( ) { return new ProtectedFunctionMapper ( ) ; } } ) ; } else { funcMapper = new ProtectedFunctionMapper ( ) ; } funcMapper . fnmap = new java . util . HashMap < String , Method > ( ) ; return funcMapper ; }


Input: Stores a mapping from the given EL function prefix and name to the given Java method . [CODESPLIT] public void mapFunction ( String fnQName , final Class < ? > c , final String methodName , final Class < ? > [ ] args ) { java . lang . reflect . Method method ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { try { method = AccessController . doPrivileged ( new PrivilegedExceptionAction < Method > ( ) { public Method run ( ) throws Exception { return c . getDeclaredMethod ( methodName , args ) ; } } ) ; } catch ( PrivilegedActionException ex ) { throw new RuntimeException ( "Invalid function mapping - no such method: " + ex . getException ( ) . getMessage ( ) ) ; } } else { try { method = c . getDeclaredMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Invalid function mapping - no such method: " + e . getMessage ( ) ) ; } } this . fnmap . put ( fnQName , method ) ; }


Input: Creates an instance for this class and stores the Method for the given EL function prefix and name . This method is used for the case when there is only one function in the EL expression . [CODESPLIT] public static ProtectedFunctionMapper getMapForFunction ( String fnQName , final Class < ? > c , final String methodName , final Class < ? > [ ] args ) { java . lang . reflect . Method method ; ProtectedFunctionMapper funcMapper ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { funcMapper = AccessController . doPrivileged ( new PrivilegedAction < ProtectedFunctionMapper > ( ) { public ProtectedFunctionMapper run ( ) { return new ProtectedFunctionMapper ( ) ; } } ) ; try { method = AccessController . doPrivileged ( new PrivilegedExceptionAction < Method > ( ) { public Method run ( ) throws Exception { return c . getDeclaredMethod ( methodName , args ) ; } } ) ; } catch ( PrivilegedActionException ex ) { throw new RuntimeException ( "Invalid function mapping - no such method: " + ex . getException ( ) . getMessage ( ) ) ; } } else { funcMapper = new ProtectedFunctionMapper ( ) ; try { method = c . getDeclaredMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Invalid function mapping - no such method: " + e . getMessage ( ) ) ; } } funcMapper . theMethod = method ; return funcMapper ; }


Input: Resolves the specified local name and prefix into a Java . lang . Method . Returns null if the prefix and local name are not found . [CODESPLIT] public Method resolveFunction ( String prefix , String localName ) { if ( this . fnmap != null ) { return this . fnmap . get ( prefix + ":" + localName ) ; } return theMethod ; }


Input: Initializes the contents of the XMLString structure with the specified values . [CODESPLIT] public void setValues ( char [ ] ch , int offset , int length ) { this . ch = ch ; this . offset = offset ; this . length = length ; }


Input: Initializes the contents of the XMLString structure with copies of the given string structure . <p > <strong > Note : < / strong > This does not copy the character array ; only the reference to the array is copied . [CODESPLIT] public void setValues ( XMLString s ) { setValues ( s . ch , s . offset , s . length ) ; }


Input: interface extensions [CODESPLIT] @ Override public List < MenuEntry > getViews ( final HttpServletRequest request , final Object object ) { if ( ! ( object instanceof ChannelId ) ) { return null ; } final ChannelId channel = ( ChannelId ) object ; final List < MenuEntry > result = new LinkedList <> ( ) ; final Map < String , Object > model = new HashMap <> ( 1 ) ; model . put ( "channelId" , channel . getId ( ) ) ; result . add ( new MenuEntry ( "Help" , 100_000 , "Description" , 1_000 , LinkTarget . createFromController ( DescriptionController . class , "channelDescription" ) . expand ( model ) , Modifier . DEFAULT , "comment" ) ) ; return result ; }


Input: Resolves the specified variable within the given context . Returns null if the variable is not found . [CODESPLIT] public Object resolveVariable ( String pName ) throws javax . servlet . jsp . el . ELException { ELContext elContext = pageContext . getELContext ( ) ; ELResolver elResolver = elContext . getELResolver ( ) ; try { return elResolver . getValue ( elContext , null , pName ) ; } catch ( javax . el . ELException ex ) { throw new javax . servlet . jsp . el . ELException ( ) ; } }


Input: Parses a JSP page or tag file . This is invoked by the compiler . [CODESPLIT] public Node . Nodes parse ( String inFileName ) throws FileNotFoundException , JasperException , IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the  // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt . isTagFile ( ) ; directiveOnly = false ; return doParse ( inFileName , null , ctxt . getTagFileJarUrl ( ) ) ; }


Input: Processes an include directive with the given path . [CODESPLIT] public Node . Nodes parse ( String inFileName , Node parent , URL jarFileUrl ) throws FileNotFoundException , JasperException , IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse ( inFileName , parent , jarFileUrl ) ; }


Input: Extracts tag file directive information from the tag file with the given name . [CODESPLIT] public Node . Nodes parseTagFileDirectives ( String inFileName ) throws FileNotFoundException , JasperException , IOException { boolean isTagFileSave = isTagFile ; boolean directiveOnlySave = directiveOnly ; isTagFile = true ; directiveOnly = true ; Node . Nodes page = doParse ( inFileName , null , ( URL ) ctxt . getTagFileJarUrls ( ) . get ( inFileName ) ) ; directiveOnly = directiveOnlySave ; isTagFile = isTagFileSave ; return page ; }


Input: Parses the JSP page or tag file with the given path name . [CODESPLIT] private Node . Nodes doParse ( String inFileName , Node parent , URL jarFileUrl ) throws FileNotFoundException , JasperException , IOException { Node . Nodes parsedPage = null ; isEncodingSpecifiedInProlog = false ; isDefaultPageEncoding = false ; hasBom = false ; JarFile jarFile = getJarFile ( jarFileUrl ) ; String absFileName = resolveFileName ( inFileName ) ; String jspConfigPageEnc = getJspConfigPageEncoding ( absFileName ) ; // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding ( absFileName , jarFile , jspConfigPageEnc ) ; if ( parent != null ) { // Included resource, add to dependent list compiler . getPageInfo ( ) . addDependant ( absFileName ) ; } comparePageEncodings ( jspConfigPageEnc ) ; // Dispatch to the appropriate parser if ( isXml ) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser . parse ( this , absFileName , jarFile , parent , isTagFile , directiveOnly , sourceEnc , jspConfigPageEnc , isEncodingSpecifiedInProlog ) ; } else { // Standard syntax InputStreamReader inStreamReader = null ; try { inStreamReader = JspUtil . getReader ( absFileName , sourceEnc , jarFile , ctxt , err ) ; JspReader jspReader = new JspReader ( ctxt , absFileName , sourceEnc , inStreamReader , err ) ; parsedPage = Parser . parse ( this , absFileName , jspReader , parent , isTagFile , directiveOnly , jarFileUrl , sourceEnc , jspConfigPageEnc , isDefaultPageEncoding , hasBom ) ; } finally { if ( inStreamReader != null ) { try { inStreamReader . close ( ) ; } catch ( Exception any ) { } } } } if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( Throwable t ) { } } baseDirStack . pop ( ) ; return parsedPage ; }


Input:
/ * Ensures that the page encoding specified in the JSP config element ( with matching URL pattern ) if present matches the page encoding specified in the XML prolog of a JSP document ( XML syntax ) and the page encoding derived from the BOM . [CODESPLIT] private void comparePageEncodings ( String jspConfigPageEnc ) throws JasperException { if ( jspConfigPageEnc == null ) { return ; } if ( isXml && isEncodingSpecifiedInProlog ) { /*
             * Make sure the encoding specified in the XML prolog matches
             * that in the JSP config element, treating "UTF-16", "UTF-16BE",
             * and "UTF-16LE" as identical.
             */ if ( ! jspConfigPageEnc . equalsIgnoreCase ( sourceEnc ) && ( ! jspConfigPageEnc . toLowerCase ( ) . startsWith ( "utf-16" ) || ! sourceEnc . toLowerCase ( ) . startsWith ( "utf-16" ) ) ) { err . jspError ( "jsp.error.prolog_config_encoding_mismatch" , sourceEnc , jspConfigPageEnc ) ; } } if ( hasBom ) { /*
             * Make sure the encoding specified in the BOM matches
             * that in the JSP config element, treating "UTF-16", "UTF-16BE",
             * and "UTF-16LE" as identical.
             */ if ( ! jspConfigPageEnc . equalsIgnoreCase ( sourceEnc ) && ( ! jspConfigPageEnc . toLowerCase ( ) . startsWith ( "utf-16" ) || ! sourceEnc . toLowerCase ( ) . startsWith ( "utf-16" ) ) ) { err . jspError ( "jsp.error.bom_config_encoding_mismatch" , sourceEnc , jspConfigPageEnc ) ; } } }


Input: / * Checks to see if the given URI is matched by a URL pattern specified in a jsp - property - group in web . xml and if so returns the value of the <page - encoding > element . [CODESPLIT] private String getJspConfigPageEncoding ( String absFileName ) throws JasperException { JspConfig jspConfig = ctxt . getOptions ( ) . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( absFileName ) ; return jspProperty . getPageEncoding ( ) ; }


Input:
Determines the syntax ( standard or XML ) and page encoding properties for the given file and stores them in the isXml and sourceEnc instance variables respectively . [CODESPLIT] private void determineSyntaxAndEncoding ( String absFileName , JarFile jarFile , String jspConfigPageEnc ) throws JasperException , IOException { isXml = false ; /*
	 * 'true' if the syntax (XML or standard) of the file is given
	 * from external information: either via a JSP configuration element,
	 * the ".jspx" suffix, or the enclosing file (for included resources)
	 */ boolean isExternal = false ; /*
	 * Indicates whether we need to revert from temporary usage of
	 * "ISO-8859-1" back to "UTF-8"
	 */ boolean revert = false ; JspConfig jspConfig = ctxt . getOptions ( ) . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( absFileName ) ; if ( jspProperty . isXml ( ) != null ) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil . booleanValue ( jspProperty . isXml ( ) ) ; isExternal = true ; } else if ( absFileName . endsWith ( ".jspx" ) || absFileName . endsWith ( ".tagx" ) ) { isXml = true ; isExternal = true ; } if ( isExternal && ! isXml ) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc ; if ( sourceEnc != null ) { return ; } // We don't know the encoding sourceEnc = "ISO-8859-1" ; } else { // XML syntax or unknown, (auto)detect encoding ... Object [ ] ret = XMLEncodingDetector . getEncoding ( absFileName , jarFile , ctxt , err ) ; sourceEnc = ( String ) ret [ 0 ] ; if ( ( ( Boolean ) ret [ 1 ] ) . booleanValue ( ) ) { isEncodingSpecifiedInProlog = true ; } if ( ret [ 2 ] != null && ( ( Boolean ) ret [ 2 ] ) . booleanValue ( ) ) { hasBom = true ; } if ( ! isXml && sourceEnc . equalsIgnoreCase ( "utf-8" ) && ! hasBom ) { /*
		 * We don't know if we're dealing with XML or standard syntax.
		 * Therefore, we need to check to see if the page contains
		 * a <jsp:root> element.
		 *
                 * We need to be careful, because the page may be encoded in
                 * ISO-8859-1 (or something entirely different: UTF-8 was
                 * chosen as the default, for lack of better alternative),
                 * and may contain byte sequences that will cause a UTF-8
                 * converter to throw exceptions.
		 *
		 * It is safe to use a source encoding of ISO-8859-1 in this
		 * case, as there are no invalid byte sequences in ISO-8859-1,
		 * and the byte/character sequences we're looking for (i.e.,
		 * <jsp:root>) are identical in either encoding (both UTF-8
		 * and ISO-8859-1 are extensions of ASCII).
		 */ sourceEnc = "ISO-8859-1" ; revert = true ; } } if ( isXml ) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // ".jspx" suffix), so we're done. return ; } /*
	 * At this point, 'isExternal' or 'isXml' is FALSE.
	 * Search for jsp:root action, in order to determine if we're dealing
	 * with XML or standard syntax (unless we already know what we're
	 * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE).
	 * No check for XML prolog, since nothing prevents a page from
	 * outputting XML and still using JSP syntax (in this case, the
	 * XML prolog is treated as template text).
	 */ JspReader jspReader = null ; try { jspReader = new JspReader ( ctxt , absFileName , sourceEnc , jarFile , err ) ; } catch ( FileNotFoundException ex ) { throw new JasperException ( ex ) ; } jspReader . setSingleFile ( true ) ; Mark startMark = jspReader . mark ( ) ; if ( ! isExternal ) { jspReader . reset ( startMark ) ; if ( hasJspRoot ( jspReader ) ) { isXml = true ; if ( revert ) sourceEnc = "UTF-8" ; return ; } else { isXml = false ; } } /*
	 * At this point, we know we're dealing with JSP syntax.
	 * If an XML prolog is provided, it's treated as template text.
	 * Determine the page encoding from the page directive, unless it's
	 * specified via JSP config.
	 */ if ( ! hasBom ) { sourceEnc = jspConfigPageEnc ; } if ( sourceEnc == null ) { sourceEnc = getPageEncodingForJspSyntax ( jspReader , startMark ) ; if ( sourceEnc == null ) { // Default to "ISO-8859-1" per JSP spec sourceEnc = "ISO-8859-1" ; isDefaultPageEncoding = true ; } } }


Input:
/ * Determines page source encoding for page or tag file in JSP syntax by reading ( in this order ) the value of the pageEncoding page directive attribute or the charset value of the contentType page directive attribute . [CODESPLIT] private String getPageEncodingForJspSyntax ( JspReader jspReader , Mark startMark ) throws JasperException { String encoding = null ; String saveEncoding = null ; jspReader . reset ( startMark ) ; /*
	 * Determine page encoding from directive of the form <%@ page %>,
	 * <%@ tag %>, <jsp:directive.page > or <jsp:directive.tag >.
	 */ while ( true ) { if ( jspReader . skipUntil ( "<" ) == null ) { break ; } // If this is a comment, skip until its end if ( jspReader . matches ( "%--" ) ) { if ( jspReader . skipUntil ( "--%>" ) == null ) { // error will be caught in Parser break ; } continue ; } boolean isDirective = jspReader . matches ( "%@" ) ; if ( isDirective ) { jspReader . skipSpaces ( ) ; } else { isDirective = jspReader . matches ( "jsp:directive." ) ; } if ( ! isDirective ) { continue ; } // compare for "tag ", so we don't match "taglib" if ( jspReader . matches ( "tag " ) || jspReader . matches ( "page" ) ) { jspReader . skipSpaces ( ) ; Attributes attrs = Parser . parseAttributes ( this , jspReader ) ; encoding = getPageEncodingFromDirective ( attrs , "pageEncoding" ) ; if ( encoding != null ) { break ; } encoding = getPageEncodingFromDirective ( attrs , "contentType" ) ; if ( encoding != null ) { saveEncoding = encoding ; } } } if ( encoding == null ) { encoding = saveEncoding ; } return encoding ; }


Input: / * Scans the given attributes for the attribute with the given name which is either pageEncoding or contentType and returns the specified page encoding . [CODESPLIT] private String getPageEncodingFromDirective ( Attributes attrs , String attrName ) { String value = attrs . getValue ( attrName ) ; if ( attrName . equals ( "pageEncoding" ) ) { return value ; } // attrName = contentType String contentType = value ; String encoding = null ; if ( contentType != null ) { int loc = contentType . indexOf ( CHARSET ) ; if ( loc != - 1 ) { encoding = contentType . substring ( loc + CHARSET . length ( ) ) ; } } return encoding ; }


Input: / * Resolve the name of the file and update baseDirStack () to keep track of the current base directory for each included file . The root file is always an absolute path so no need to put an initial value in the baseDirStack . [CODESPLIT] private String resolveFileName ( String inFileName ) { String fileName = inFileName . replace ( ' ' , ' ' ) ; boolean isAbsolute = fileName . startsWith ( "/" ) ; fileName = isAbsolute ? fileName : baseDirStack . peek ( ) + fileName ; String baseDir = fileName . substring ( 0 , fileName . lastIndexOf ( "/" ) + 1 ) ; baseDirStack . push ( baseDir ) ; return fileName ; }


Input: / * Checks to see if the given page contains as its first element a <root > element whose prefix is bound to the JSP namespace as in : [CODESPLIT] private boolean hasJspRoot ( JspReader reader ) throws JasperException { // <prefix>:root must be the first element Mark start = null ; while ( ( start = reader . skipUntil ( "<" ) ) != null ) { int c = reader . nextChar ( ) ; if ( c != ' ' && c != ' ' ) break ; } if ( start == null ) { return false ; } Mark stop = reader . skipUntil ( ":root" ) ; if ( stop == null ) { return false ; } // call substring to get rid of leading '<' String prefix = reader . getText ( start , stop ) . substring ( 1 ) ; start = stop ; stop = reader . skipUntil ( ">" ) ; if ( stop == null ) { return false ; } // Determine namespace associated with <root> element's prefix String root = reader . getText ( start , stop ) ; String xmlnsDecl = "xmlns:" + prefix ; int index = root . indexOf ( xmlnsDecl ) ; if ( index == - 1 ) { return false ; } index += xmlnsDecl . length ( ) ; while ( index < root . length ( ) && Character . isWhitespace ( root . charAt ( index ) ) ) { index ++ ; } if ( index < root . length ( ) && root . charAt ( index ) == ' ' ) { index ++ ; while ( index < root . length ( ) && Character . isWhitespace ( root . charAt ( index ) ) ) { index ++ ; } if ( index < root . length ( ) && root . charAt ( index ++ ) == ' ' && root . regionMatches ( index , JSP_URI , 0 , JSP_URI . length ( ) ) ) { return true ; } } return false ; }


Input: Create a Compiler object . [CODESPLIT] public Compiler createCompiler ( boolean jspcMode ) throws JasperException { if ( jspCompiler != null ) { return jspCompiler ; } jspCompiler = new Compiler ( this , jsw , jspcMode ) ; return jspCompiler ; }


Input: Gets a resource as a stream relative to the meanings of this context s implementation . [CODESPLIT] public java . io . InputStream getResourceAsStream ( String res ) throws JasperException { return context . getResourceAsStream ( canonicalURI ( res ) ) ; }


Input: Gets the location of the TLD associated with the given taglib uri . [CODESPLIT] public String [ ] getTldLocation ( String uri ) throws JasperException { String [ ] location = getOptions ( ) . getTldScanner ( ) . getLocation ( uri ) ; return location ; }


Input: ==================== Removal ==================== [CODESPLIT] public void incrementRemoved ( ) { if ( removed > 1 ) { jspCompiler . removeGeneratedFiles ( ) ; if ( rctxt != null ) rctxt . removeWrapper ( jspUri ) ; } removed ++ ; }


Input: ==================== Compile and reload ==================== [CODESPLIT] public void compile ( ) throws JasperException , FileNotFoundException { createCompiler ( false ) ; if ( jspCompiler . isOutDated ( ) ) { try { jspCompiler . compile ( true ) ; jsw . setReload ( true ) ; jsw . setCompilationException ( null ) ; } catch ( JasperException ex ) { // Cache compilation exception jsw . setCompilationException ( ex ) ; throw ex ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; JasperException je = new JasperException ( Localizer . getMessage ( "jsp.error.unable.compile" ) , ex ) ; // Cache compilation exception jsw . setCompilationException ( je ) ; throw je ; } } }


Input: ==================== Manipulating the class ==================== [CODESPLIT] public Class load ( ) throws JasperException , ClassNotFoundException { try { String name = getFullClassName ( ) ; if ( options . getUsePrecompiled ( ) ) { servletClass = getClassLoader ( ) . loadClass ( name ) ; } else { servletClass = getJspLoader ( ) . loadClass ( name ) ; } } catch ( ClassNotFoundException cex ) { // Do not wrapper this in JasperException if use-precompiled is set, // because this is really a 404. if ( options . getUsePrecompiled ( ) ) { throw cex ; } throw new JasperException ( Localizer . getMessage ( "jsp.error.unable.load" ) , cex ) ; } catch ( Exception ex ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.unable.compile" ) , ex ) ; } removed = 0 ; return servletClass ; }


Input: Read a single character . This method will block until a character is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( ) throws IOException { int b0 = fInputStream . read ( ) ; if ( b0 > 0x80 ) { throw new IOException ( Localizer . getMessage ( "jsp.error.xml.invalidASCII" , Integer . toString ( b0 ) ) ) ; } return b0 ; }


Input: Read characters into a portion of an array . This method will block until some input is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( char ch [ ] , int offset , int length ) throws IOException { if ( length > fBuffer . length ) { length = fBuffer . length ; } int count = fInputStream . read ( fBuffer , 0 , length ) ; for ( int i = 0 ; i < count ; i ++ ) { int b0 = fBuffer [ i ] ; if ( b0 < 0 ) { throw new IOException ( Localizer . getMessage ( "jsp.error.xml.invalidASCII" , Integer . toString ( b0 ) ) ) ; } ch [ offset + i ] = ( char ) b0 ; } return count ; }


Input: Find the last modification timestamp of all channels [CODESPLIT] private Optional < Instant > calcLastMod ( ) { Instant globalLastMod = null ; for ( final ChannelInformation ci : this . channelService . list ( ) ) { final Optional < Instant > lastMod = ofNullable ( ci . getState ( ) . getModificationTimestamp ( ) ) ; if ( globalLastMod == null || lastMod . get ( ) . isAfter ( globalLastMod ) ) { globalLastMod = lastMod . get ( ) ; } } return Optional . ofNullable ( globalLastMod ) ; }


Input: We assume that the bootclassloader never uses the context classloader to find classes in itself . [CODESPLIT] ArrayList basicFindClassLoaders ( ) { Class [ ] stack = contextFinder . getClassContext ( ) ; ArrayList result = new ArrayList ( 1 ) ; ClassLoader previousLoader = null ; for ( int i = 1 ; i < stack . length ; i ++ ) { ClassLoader tmp = stack [ i ] . getClassLoader ( ) ; if ( checkClass ( stack [ i ] ) && tmp != null && tmp != this ) { if ( checkClassLoader ( tmp ) ) { if ( previousLoader != tmp ) { result . add ( tmp ) ; previousLoader = tmp ; } } // stop at the framework classloader or the first bundle classloader if ( Activator . getBundle ( stack [ i ] ) != null ) break ; } } return result ; }


Input: not be used as a delegate otherwise we endup in endless recursion . [CODESPLIT] private boolean checkClassLoader ( ClassLoader classloader ) { if ( classloader == null || classloader == getParent ( ) ) return false ; for ( ClassLoader parent = classloader . getParent ( ) ; parent != null ; parent = parent . getParent ( ) ) if ( parent == this ) return false ; return true ; }


Input: False is returned when a cycle is being detected [CODESPLIT] private boolean startLoading ( String name ) { Set classesAndResources = ( Set ) cycleDetector . get ( ) ; if ( classesAndResources != null && classesAndResources . contains ( name ) ) return false ; if ( classesAndResources == null ) { classesAndResources = new HashSet ( 3 ) ; cycleDetector . set ( classesAndResources ) ; } classesAndResources . add ( name ) ; return true ; }


Input: Reads the Stream Header into a buffer . This is a helper function for the constructors . [CODESPLIT] private static byte [ ] readStreamHeader ( InputStream in ) throws IOException { byte [ ] streamHeader = new byte [ DecoderUtil . STREAM_HEADER_SIZE ] ; new DataInputStream ( in ) . readFully ( streamHeader ) ; return streamHeader ; }


Input: Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will try to decompress <code > len< / code > bytes of uncompressed data . Less than <code > len< / code > bytes may be read only in the following situations : <ul > <li > The end of the compressed data was reached successfully . < / li > <li > An error is detected after at least one but less <code > len< / code > bytes have already been successfully decompressed . The next call with non - zero <code > len< / code > will immediately throw the pending exception . < / li > <li > An exception is thrown . < / li > < / ul > [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; int size = 0 ; try { while ( len > 0 ) { if ( blockDecoder == null ) { try { blockDecoder = new BlockInputStream ( in , check , verifyCheck , memoryLimit , - 1 , - 1 , arrayCache ) ; } catch ( IndexIndicatorException e ) { indexHash . validate ( in ) ; validateStreamFooter ( ) ; endReached = true ; return size > 0 ? size : - 1 ; } } int ret = blockDecoder . read ( buf , off , len ) ; if ( ret > 0 ) { size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { indexHash . add ( blockDecoder . getUnpaddedSize ( ) , blockDecoder . getUncompressedSize ( ) ) ; blockDecoder = null ; } } } catch ( IOException e ) { exception = e ; if ( size == 0 ) throw e ; } return size ; }


Input: Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; return blockDecoder == null ? 0 : blockDecoder . available ( ) ; }


Input: Closes the stream and optionally calls <code > in . close () < / code > . If the stream was already closed this does nothing . If <code > close ( false ) < / code > has been called a further call of <code > close ( true ) < / code > does nothing ( it doesn t call <code > in . close () < / code > ) . <p > If you don t want to close the underlying <code > InputStream< / code > there is usually no need to worry about closing this stream either ; it s fine to do nothing and let the garbage collector handle it . However if you are using { @link ArrayCache } <code > close ( false ) < / code > can be useful to put the allocated arrays back to the cache without closing the underlying <code > InputStream< / code > . <p > Note that if you successfully reach the end of the stream ( <code > read< / code > returns <code > - 1< / code > ) the arrays are automatically put back to the cache by that <code > read< / code > call . In this situation <code > close ( false ) < / code > is redundant ( but harmless ) . [CODESPLIT] public void close ( boolean closeInput ) throws IOException { if ( in != null ) { if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } try { if ( closeInput ) in . close ( ) ; } finally { in = null ; } } }


Input: Paginate from a full data set [CODESPLIT] public static < T > PaginationResult < T > paginate ( final Integer startPage , final int pageSize , final List < T > fullDataSet ) { return paginate ( startPage , pageSize , ( start , length ) -> { final int len = fullDataSet . size ( ) ; if ( start > len ) { return Collections . emptyList ( ) ; } return fullDataSet . subList ( start , Math . min ( start + length , len ) ) ; } ) ; }


Input: Calls { [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { return randomAccessFile . read ( buf , off , len ) ; }


Input: Convert a string to a MetaKey if possible [CODESPLIT] public static MetaKey fromString ( final String string ) { final int idx = string . indexOf ( ' ' ) ; if ( idx < 1 ) { // -1: none at all, 0: empty namespace return null ; } if ( idx + 1 >= string . length ( ) ) { // empty key segment return null ; } return new MetaKey ( string . substring ( 0 , idx ) , string . substring ( idx + 1 ) , true ) ; }


Input: Fill extra requirements the RPM file itself may have [CODESPLIT] private void fillRequirements ( ) throws IOException { this . requirements . add ( new Dependency ( "rpmlib(CompressedFileNames)" , "3.0.4-1" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; if ( ! this . options . getFileDigestAlgorithm ( ) . equals ( DigestAlgorithm . MD5 ) ) { this . requirements . add ( new Dependency ( "rpmlib(FileDigests)" , "4.6.0-1" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; } this . requirements . add ( new Dependency ( "rpmlib(PayloadFilesHavePrefix)" , "4.0-1" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; this . options . getPayloadCoding ( ) . createProvider ( ) . fillRequirements ( this . requirements :: add ) ; }


Input: Actually build the RPM file <p > <strong > Note : < / strong > this method may only be called once per instance < / p > [CODESPLIT] public void build ( ) throws IOException { if ( this . hasBuilt ) { throw new IllegalStateException ( "RPM file has already been built. Can only be built once." ) ; } this . hasBuilt = true ; fillProvides ( ) ; fillRequirements ( ) ; fillHeader ( ) ; final LeadBuilder leadBuilder = new LeadBuilder ( this . name , this . version ) ; leadBuilder . fillFlagsFromHeader ( this . header , createLeadArchitectureMapper ( ) , createLeadOperatingSystemMapper ( ) ) ; if ( this . headerCustomizer != null ) { this . headerCustomizer . accept ( this . header ) ; } try ( final RpmWriter writer = new RpmWriter ( this . targetFile , leadBuilder , this . header , this . options . getHeaderCharset ( ) , this . options . getOpenOptions ( ) ) ) { writer . addAllSignatureProcessors ( this . signatureProcessors ) ; writer . setPayload ( this . recorder ) ; } }


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 c = pageInfo . getTaglibs ( ) ; if ( c != null ) { Object [ ] objs = c . toArray ( ) ; if ( objs != null && objs . length > 0 ) { taglibs = new TagLibraryInfo [ objs . length ] ; for ( int i = 0 ; i < objs . length ; i ++ ) { taglibs [ i ] = ( TagLibraryInfo ) objs [ i ] ; } } } return taglibs ; }


Input: Checks to see if the given tag name maps to a tag file path and if so parses the corresponding tag file . [CODESPLIT] public TagFileInfo getTagFile ( String shortName ) { TagFileInfo tagFile = super . getTagFile ( shortName ) ; if ( tagFile == null ) { String path = tagFileMap . get ( shortName ) ; if ( path == null ) { return null ; } TagInfo tagInfo = null ; try { tagInfo = TagFileProcessor . parseTagFileDirectives ( pc , shortName , path , this ) ; } catch ( JasperException je ) { throw new RuntimeException ( je . toString ( ) ) ; } tagFile = new TagFileInfo ( shortName , path , tagInfo ) ; vec . add ( tagFile ) ; this . tagFiles = vec . toArray ( new TagFileInfo [ vec . size ( ) ] ) ; } return tagFile ; }


Input:
Parses the JSP version and tlib - version from the implicit . tld at the given path . [CODESPLIT] private void parseImplicitTld ( JspCompilationContext ctxt , String path ) throws JasperException { InputStream is = null ; TreeNode tld = null ; try { URL uri = ctxt . getResource ( path ) ; if ( uri == null ) { // no implicit.tld return ; } is = uri . openStream ( ) ; /* SJSAS 6384538
            tld = new ParserUtils().parseXMLDocument(IMPLICIT_TLD, is);
            */ // START SJSAS 6384538 tld = new ParserUtils ( ) . parseXMLDocument ( IMPLICIT_TLD , is , ctxt . getOptions ( ) . isValidationEnabled ( ) ) ; // END SJSAS 6384538 } catch ( Exception ex ) { throw new JasperException ( ex ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Throwable t ) { } } } this . jspversion = tld . findAttribute ( "version" ) ; Iterator list = tld . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode element = ( TreeNode ) list . next ( ) ; String tname = element . getName ( ) ; if ( "tlibversion" . equals ( tname ) || "tlib-version" . equals ( tname ) ) { 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 ) ) { err . jspError ( "jsp.error.implicitTld.additionalElements" , path , tname ) ; } } // JSP version in implicit.tld must be 2.0 or greater Double jspVersionDouble = Double . valueOf ( this . jspversion ) ; if ( Double . compare ( jspVersionDouble , Constants . JSP_VERSION_2_0 ) < 0 ) { err . jspError ( "jsp.error.implicitTld.jspVersion" , path , this . jspversion ) ; } }


Input: Get the digest of a closed file [CODESPLIT] public String getChecksum ( final String fileName , final String algorithm ) { if ( ! this . digests . contains ( algorithm ) ) { return null ; } final String result = this . checksums . get ( fileName + ":" + algorithm ) ; if ( result == null ) { throw new IllegalStateException ( String . format ( "Stream '%s' not closed." , fileName ) ) ; } return result ; }


Input: Get the size of a closed file [CODESPLIT] public long getSize ( final String fileName ) { final Long result = this . sizes . get ( fileName ) ; if ( result == null ) { throw new IllegalStateException ( String . format ( "Stream '%s' not closed or was not added" , fileName ) ) ; } return result ; }


Input: Validate the name of the channel [CODESPLIT] private static void validateChannelName ( final String name , final ValidationContext ctx ) { if ( name == null || name . isEmpty ( ) ) { return ; } final Matcher m = ChannelService . NAME_PATTERN . matcher ( name ) ; if ( ! m . matches ( ) ) { ctx . error ( "names" , String . format ( "The channel name '%s' must match the pattern '%s'" , name , ChannelService . NAME_PATTERN . pattern ( ) ) ) ; } }


Input: Seeks <code > n< / code > bytes forward in this stream . <p > This will not seek past the end of the file . If the current position is already at or past the end of the file this doesn t seek at all and returns <code > 0< / code > . Otherwise if skipping <code > n< / code > bytes would cause the position to exceed the stream size this will do equivalent of <code > seek ( length () ) < / code > and the return value will be adjusted accordingly . <p > If <code > n< / code > is negative the position isn t changed and the return value is <code > 0< / code > . It doesn t seek backward because it would conflict with the specification of { @link java . io . InputStream#skip ( long ) InputStream . skip } . [CODESPLIT] public long skip ( long n ) throws IOException { if ( n <= 0 ) return 0 ; long size = length ( ) ; long pos = position ( ) ; if ( pos >= size ) return 0 ; if ( size - pos < n ) n = size - pos ; seek ( pos + n ) ; return n ; }


Input: Gets how much memory the encoder will need with the given filter chain . This function simply calls <code > getEncoderMemoryUsage () < / code > for every filter in the array and returns the sum of the returned values . [CODESPLIT] public static int getEncoderMemoryUsage ( FilterOptions [ ] options ) { int m = 0 ; for ( int i = 0 ; i < options . length ; ++ i ) m += options [ i ] . getEncoderMemoryUsage ( ) ; return m ; }


Input: Gets how much memory the decoder will need with the given filter chain . This function simply calls <code > getDecoderMemoryUsage () < / code > for every filter in the array and returns the sum of the returned values . [CODESPLIT] public static int getDecoderMemoryUsage ( FilterOptions [ ] options ) { int m = 0 ; for ( int i = 0 ; i < options . length ; ++ i ) m += options [ i ] . getDecoderMemoryUsage ( ) ; return m ; }


Input: Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will try to decompress <code > len< / code > bytes of uncompressed data . Less than <code > len< / code > bytes may be read only in the following situations : <ul > <li > The end of the compressed data was reached successfully . < / li > <li > An error is detected after at least one but less than <code > len< / code > bytes have already been successfully decompressed . The next call with non - zero <code > len< / code > will immediately throw the pending exception . < / li > <li > An exception is thrown . < / li > < / ul > [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; int size = 0 ; try { if ( seekNeeded ) seek ( ) ; if ( endReached ) return - 1 ; while ( len > 0 ) { if ( blockDecoder == null ) { seek ( ) ; if ( endReached ) break ; } int ret = blockDecoder . read ( buf , off , len ) ; if ( ret > 0 ) { curPos += ret ; size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { blockDecoder = null ; } } } catch ( IOException e ) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if ( e instanceof EOFException ) e = new CorruptedInputException ( ) ; exception = e ; if ( size == 0 ) throw e ; } return size ; }


Input: Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; if ( endReached || seekNeeded || blockDecoder == null ) return 0 ; return blockDecoder . available ( ) ; }


Input: Seeks to the specified absolute uncompressed position in the stream . This only stores the new position so this function itself is always very fast . The actual seek is done when <code > read< / code > is called to read at least one byte . <p > Seeking past the end of the stream is possible . In that case <code > read< / code > will return <code > - 1< / code > to indicate the end of the stream . [CODESPLIT] public void seek ( long pos ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( pos < 0 ) throw new XZIOException ( "Negative seek position: " + pos ) ; seekPos = pos ; seekNeeded = true ; }


Input: Seeks to the beginning of the given XZ Block . [CODESPLIT] public void seekToBlock ( int blockNumber ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( blockNumber < 0 || blockNumber >= blockCount ) throw new XZIOException ( "Invalid XZ Block number: " + blockNumber ) ; // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos ( blockNumber ) ; seekNeeded = true ; }


Input: Does the actual seeking . This is also called when <code > read< / code > needs a new Block to decode . [CODESPLIT] private void seek ( ) throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if ( ! seekNeeded ) { if ( curBlockInfo . hasNext ( ) ) { curBlockInfo . setNext ( ) ; initBlockDecoder ( ) ; return ; } seekPos = curPos ; } seekNeeded = false ; // Check if we are seeking to or past the end of the file. if ( seekPos >= uncompressedSize ) { curPos = seekPos ; if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } endReached = true ; return ; } endReached = false ; // Locate the Block that contains the uncompressed target position. locateBlockByPos ( curBlockInfo , seekPos ) ; // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if ( ! ( curPos > curBlockInfo . uncompressedOffset && curPos <= seekPos ) ) { // Seek to the beginning of the Block. in . seek ( curBlockInfo . compressedOffset ) ; // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check . getInstance ( curBlockInfo . getCheckType ( ) ) ; // Create a new Block decoder. initBlockDecoder ( ) ; curPos = curBlockInfo . uncompressedOffset ; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if ( seekPos > curPos ) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos ; if ( blockDecoder . skip ( skipAmount ) != skipAmount ) throw new CorruptedInputException ( ) ; curPos = seekPos ; } }


Input: Locates the Block that contains the given uncompressed position . [CODESPLIT] private void locateBlockByPos ( BlockInfo info , long pos ) { if ( pos < 0 || pos >= uncompressedSize ) throw new IndexOutOfBoundsException ( "Invalid uncompressed position: " + pos ) ; // Locate the Stream that contains the target position. IndexDecoder index ; for ( int i = 0 ; ; ++ i ) { index = streams . get ( i ) ; if ( index . hasUncompressedOffset ( pos ) ) break ; } // Locate the Block from the Stream that contains the target position. index . locateBlock ( info , pos ) ; assert ( info . compressedOffset & 3 ) == 0 ; assert info . uncompressedSize > 0 ; assert pos >= info . uncompressedOffset ; assert pos < info . uncompressedOffset + info . uncompressedSize ; }


Input: Locates the given Block and stores information about it to <code > info< / code > . [CODESPLIT] private void locateBlockByNumber ( BlockInfo info , int blockNumber ) { // Validate. if ( blockNumber < 0 || blockNumber >= blockCount ) throw new IndexOutOfBoundsException ( "Invalid XZ Block number: " + blockNumber ) ; // Skip the search if info already points to the correct Block. if ( info . blockNumber == blockNumber ) return ; // Search the Stream that contains the given Block and then // search the Block from that Stream. for ( int i = 0 ; ; ++ i ) { IndexDecoder index = streams . get ( i ) ; if ( index . hasRecord ( blockNumber ) ) { index . setBlockInfo ( info , blockNumber ) ; return ; } } }


Input: Initializes a new BlockInputStream . This is a helper function for <code > seek () < / code > . [CODESPLIT] private void initBlockDecoder ( ) throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } blockDecoder = new BlockInputStream ( in , check , verifyCheck , memoryLimit , curBlockInfo . unpaddedSize , curBlockInfo . uncompressedSize , arrayCache ) ; } catch ( MemoryLimitException e ) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0 ; throw new MemoryLimitException ( e . getMemoryNeeded ( ) + indexMemoryUsage , memoryLimit + indexMemoryUsage ) ; } catch ( IndexIndicatorException e ) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException ( ) ; } }


Input: Generate codes for Collections The pseudo code is : [CODESPLIT] private void doCollection ( TagPluginContext ctxt ) { ctxt . generateImport ( "java.util.*" ) ; generateIterators ( ctxt ) ; String itemsV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "Object " + itemsV + "= " ) ; ctxt . generateAttribute ( "items" ) ; ctxt . generateJavaSource ( ";" ) ; String indexV = null , beginV = null , endV = null , stepV = null ; if ( hasBegin ) { beginV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "int " + beginV + " = " ) ; ctxt . generateAttribute ( "begin" ) ; ctxt . generateJavaSource ( ";" ) ; } if ( hasEnd ) { indexV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "int " + indexV + " = 0;" ) ; endV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "int " + endV + " = " ) ; ctxt . generateAttribute ( "end" ) ; ctxt . generateJavaSource ( ";" ) ; } if ( hasStep ) { stepV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "int " + stepV + " = " ) ; ctxt . generateAttribute ( "step" ) ; ctxt . generateJavaSource ( ";" ) ; } String iterV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "Iterator " + iterV + " = null;" ) ; // Object[] ctxt . generateJavaSource ( "if (" + itemsV + " instanceof Object[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((Object[])" + itemsV + ");" ) ; // boolean[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof boolean[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((boolean[])" + itemsV + ");" ) ; // byte[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof byte[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((byte[])" + itemsV + ");" ) ; // char[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof char[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((char[])" + itemsV + ");" ) ; // short[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof short[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((short[])" + itemsV + ");" ) ; // int[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof int[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((int[])" + itemsV + ");" ) ; // long[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof long[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((long[])" + itemsV + ");" ) ; // float[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof float[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((float[])" + itemsV + ");" ) ; // double[] ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof double[])" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((double[])" + itemsV + ");" ) ; // Collection ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof Collection)" ) ; ctxt . generateJavaSource ( iterV + "=((Collection)" + itemsV + ").iterator();" ) ; // Iterator ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof Iterator)" ) ; ctxt . generateJavaSource ( iterV + "=(Iterator)" + itemsV + ";" ) ; // Enumeration ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof Enumeration)" ) ; ctxt . generateJavaSource ( iterV + "=toIterator((Enumeration)" + itemsV + ");" ) ; // Map ctxt . generateJavaSource ( "else if (" + itemsV + " instanceof Map)" ) ; ctxt . generateJavaSource ( iterV + "=((Map)" + itemsV + ").entrySet().iterator();" ) ; if ( hasBegin ) { String tV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "for (int " + tV + "=" + beginV + ";" + tV + ">0 && " + iterV + ".hasNext(); " + tV + "--)" ) ; ctxt . generateJavaSource ( iterV + ".next();" ) ; } ctxt . generateJavaSource ( "while (" + iterV + ".hasNext()){" ) ; if ( hasVar ) { ctxt . generateJavaSource ( "_jspx_page_context.setAttribute(" ) ; ctxt . generateAttribute ( "var" ) ; ctxt . generateJavaSource ( ", " + iterV + ".next());" ) ; } ctxt . generateBody ( ) ; if ( hasStep ) { String tV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( "for (int " + tV + "=" + stepV + "-1;" + tV + ">0 && " + iterV + ".hasNext(); " + tV + "--)" ) ; ctxt . generateJavaSource ( iterV + ".next();" ) ; } if ( hasEnd ) { if ( hasStep ) { ctxt . generateJavaSource ( indexV + "+=" + stepV + ";" ) ; } else { ctxt . generateJavaSource ( indexV + "++;" ) ; } if ( hasBegin ) { ctxt . generateJavaSource ( "if(" + beginV + "+" + indexV + ">" + endV + ")" ) ; } else { ctxt . generateJavaSource ( "if(" + indexV + ">" + endV + ")" ) ; } ctxt . generateJavaSource ( "break;" ) ; } ctxt . generateJavaSource ( "}" ) ; // while }


Input: Generate iterators for data types supported in items [CODESPLIT] private void generateIterators ( TagPluginContext ctxt ) { // Object[] ctxt . generateDeclaration ( "ObjectArrayIterator" , "private Iterator toIterator(final Object[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return a[index++];}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // boolean[] ctxt . generateDeclaration ( "booleanArrayIterator" , "private Iterator toIterator(final boolean[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Boolean(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // byte[] ctxt . generateDeclaration ( "byteArrayIterator" , "private Iterator toIterator(final byte[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Byte(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // char[] ctxt . generateDeclaration ( "charArrayIterator" , "private Iterator toIterator(final char[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Character(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // short[] ctxt . generateDeclaration ( "shortArrayIterator" , "private Iterator toIterator(final short[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Short(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // int[] ctxt . generateDeclaration ( "intArrayIterator" , "private Iterator toIterator(final int[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Integer(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // long[] ctxt . generateDeclaration ( "longArrayIterator" , "private Iterator toIterator(final long[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Long(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // float[] ctxt . generateDeclaration ( "floatArrayIterator" , "private Iterator toIterator(final float[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Float(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // double[] ctxt . generateDeclaration ( "doubleArrayIterator" , "private Iterator toIterator(final double[] a){\n" + "  return (new Iterator() {\n" + "    int index=0;\n" + "    public boolean hasNext() {\n" + "      return index < a.length;}\n" + "    public Object next() {\n" + "      return new Double(a[index++]);}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; // Enumeration ctxt . generateDeclaration ( "enumIterator" , "private Iterator toIterator(final Enumeration e){\n" + "  return (new Iterator() {\n" + "    public boolean hasNext() {\n" + "      return e.hasMoreElements();}\n" + "    public Object next() {\n" + "      return e.nextElement();}\n" + "    public void remove() {}\n" + "  });\n" + "}" ) ; }


Input: Get a list of all relevant maven artifacts [CODESPLIT] protected static List < MavenVersionedArtifact > getMavenArtifacts ( final String channelId , final Supplier < Collection < ArtifactInformation > > artifactsSupplier , final String groupId , final String artifactId , final boolean snapshot , final Predicate < ComparableVersion > versionFilter ) { final List < MavenVersionedArtifact > arts = new ArrayList <> ( ) ; for ( final ArtifactInformation ai : artifactsSupplier . get ( ) ) { if ( ! isZip ( ai ) ) { // if is is anot a zip, then this is not for the unzip plugin continue ; } // fetch meta data final String mvnGroupId = ai . getMetaData ( ) . get ( MK_GROUP_ID ) ; final String mvnArtifactId = ai . getMetaData ( ) . get ( MK_ARTIFACT_ID ) ; final String classifier = ai . getMetaData ( ) . get ( MK_CLASSIFIER ) ; final String mvnVersion = ai . getMetaData ( ) . get ( MK_VERSION ) ; final String mvnSnapshotVersion = ai . getMetaData ( ) . get ( MK_SNAPSHOT_VERSION ) ; if ( mvnGroupId == null || mvnArtifactId == null || mvnVersion == null ) { // no GAV information continue ; } if ( classifier != null && ! classifier . isEmpty ( ) ) { // no classifiers right now continue ; } if ( ! mvnGroupId . equals ( groupId ) || ! mvnArtifactId . equals ( artifactId ) ) { // wrong group or artifact id continue ; } if ( ! snapshot && ( mvnSnapshotVersion != null || mvnVersion . endsWith ( "-SNAPSHOT" ) ) ) { // we are not looking for snapshots continue ; } final ComparableVersion v = parseVersion ( mvnVersion ) ; final ComparableVersion sv = parseVersion ( mvnSnapshotVersion ) ; if ( v == null ) { // unable to parse v continue ; } if ( versionFilter == null ) { // no filter, add it arts . add ( new MavenVersionedArtifact ( sv != null ? sv : v , channelId , ai ) ) ; } else if ( versionFilter . test ( v ) ) { // filter matched, add it arts . add ( new MavenVersionedArtifact ( sv != null ? sv : v , channelId , ai ) ) ; } else if ( sv != null && versionFilter . test ( sv ) ) { // we have a snapshot version and it matched, add it arts . add ( new MavenVersionedArtifact ( sv , channelId , ai ) ) ; } } return arts ; }


Input: Check if an artifact is a ZIP file <p > An artifact is a ZIP file if at least one of th following tests is true : <ul > <li > Its lower case name ends with <code > . zip< / code > < / li > <li > The meta data field <code > mvn : extension< / code > is set to <code > zip< / code > <li > The meta data field <code > mime : type< / code > is set to <code > application / zip< / code > < / ul > < / p > [CODESPLIT] protected static boolean isZip ( final ArtifactInformation artifact ) { if ( artifact . getName ( ) . toLowerCase ( ) . endsWith ( ".zip" ) ) { return true ; } final String mdExtension = artifact . getMetaData ( ) . get ( MK_MVN_EXTENSION ) ; if ( mdExtension != null && mdExtension . equalsIgnoreCase ( "zip" ) ) { return true ; } final String mdMime = artifact . getMetaData ( ) . get ( MK_MIME_TYPE ) ; if ( mdMime != null && mdMime . equalsIgnoreCase ( "application/zip" ) ) { return true ; } return false ; }


Input: Converts the opts array from backward indexes to forward indexes . Then it will be simple to get the next symbol from the array in later calls to <code > getNextSymbol () < / code > . [CODESPLIT] private int convertOpts ( ) { optEnd = optCur ; int optPrev = opts [ optCur ] . optPrev ; do { Optimum opt = opts [ optCur ] ; if ( opt . prev1IsLiteral ) { opts [ optPrev ] . optPrev = optCur ; opts [ optPrev ] . backPrev = - 1 ; optCur = optPrev -- ; if ( opt . hasPrev2 ) { opts [ optPrev ] . optPrev = optPrev + 1 ; opts [ optPrev ] . backPrev = opt . backPrev2 ; optCur = optPrev ; optPrev = opt . optPrev2 ; } } int temp = opts [ optPrev ] . optPrev ; opts [ optPrev ] . optPrev = optCur ; optCur = optPrev ; optPrev = temp ; } while ( optCur > 0 ) ; optCur = opts [ 0 ] . optPrev ; back = opts [ optCur ] . backPrev ; return optCur ; }


Input: Updates the state and reps for the current byte in the opts array . [CODESPLIT] private void updateOptStateAndReps ( ) { int optPrev = opts [ optCur ] . optPrev ; assert optPrev < optCur ; if ( opts [ optCur ] . prev1IsLiteral ) { -- optPrev ; if ( opts [ optCur ] . hasPrev2 ) { opts [ optCur ] . state . set ( opts [ opts [ optCur ] . optPrev2 ] . state ) ; if ( opts [ optCur ] . backPrev2 < REPS ) opts [ optCur ] . state . updateLongRep ( ) ; else opts [ optCur ] . state . updateMatch ( ) ; } else { opts [ optCur ] . state . set ( opts [ optPrev ] . state ) ; } opts [ optCur ] . state . updateLiteral ( ) ; } else { opts [ optCur ] . state . set ( opts [ optPrev ] . state ) ; } if ( optPrev == optCur - 1 ) { // Must be either a short rep or a literal. assert opts [ optCur ] . backPrev == 0 || opts [ optCur ] . backPrev == - 1 ; if ( opts [ optCur ] . backPrev == 0 ) opts [ optCur ] . state . updateShortRep ( ) ; else opts [ optCur ] . state . updateLiteral ( ) ; System . arraycopy ( opts [ optPrev ] . reps , 0 , opts [ optCur ] . reps , 0 , REPS ) ; } else { int back ; if ( opts [ optCur ] . prev1IsLiteral && opts [ optCur ] . hasPrev2 ) { optPrev = opts [ optCur ] . optPrev2 ; back = opts [ optCur ] . backPrev2 ; opts [ optCur ] . state . updateLongRep ( ) ; } else { back = opts [ optCur ] . backPrev ; if ( back < REPS ) opts [ optCur ] . state . updateLongRep ( ) ; else opts [ optCur ] . state . updateMatch ( ) ; } if ( back < REPS ) { opts [ optCur ] . reps [ 0 ] = opts [ optPrev ] . reps [ back ] ; int rep ; for ( rep = 1 ; rep <= back ; ++ rep ) opts [ optCur ] . reps [ rep ] = opts [ optPrev ] . reps [ rep - 1 ] ; for ( ; rep < REPS ; ++ rep ) opts [ optCur ] . reps [ rep ] = opts [ optPrev ] . reps [ rep ] ; } else { opts [ optCur ] . reps [ 0 ] = back - REPS ; System . arraycopy ( opts [ optPrev ] . reps , 0 , opts [ optCur ] . reps , 1 , REPS - 1 ) ; } } }


Input: Calculates prices of a literal a short rep and literal + rep0 . [CODESPLIT] private void calc1BytePrices ( int pos , int posState , int avail , int anyRepPrice ) { // This will be set to true if using a literal or a short rep. boolean nextIsByte = false ; int curByte = lz . getByte ( 0 ) ; int matchByte = lz . getByte ( opts [ optCur ] . reps [ 0 ] + 1 ) ; // Try a literal. int literalPrice = opts [ optCur ] . price + literalEncoder . getPrice ( curByte , matchByte , lz . getByte ( 1 ) , pos , opts [ optCur ] . state ) ; if ( literalPrice < opts [ optCur + 1 ] . price ) { opts [ optCur + 1 ] . set1 ( literalPrice , optCur , - 1 ) ; nextIsByte = true ; } // Try a short rep. if ( matchByte == curByte && ( opts [ optCur + 1 ] . optPrev == optCur || opts [ optCur + 1 ] . backPrev != 0 ) ) { int shortRepPrice = getShortRepPrice ( anyRepPrice , opts [ optCur ] . state , posState ) ; if ( shortRepPrice <= opts [ optCur + 1 ] . price ) { opts [ optCur + 1 ] . set1 ( shortRepPrice , optCur , 0 ) ; nextIsByte = true ; } } // If neither a literal nor a short rep was the cheapest choice, // try literal + long rep0. if ( ! nextIsByte && matchByte != curByte && avail > MATCH_LEN_MIN ) { int lenLimit = Math . min ( niceLen , avail - 1 ) ; int len = lz . getMatchLen ( 1 , opts [ optCur ] . reps [ 0 ] , lenLimit ) ; if ( len >= MATCH_LEN_MIN ) { nextState . set ( opts [ optCur ] . state ) ; nextState . updateLiteral ( ) ; int nextPosState = ( pos + 1 ) & posMask ; int price = literalPrice + getLongRepAndLenPrice ( 0 , len , nextState , nextPosState ) ; int i = optCur + 1 + len ; while ( optEnd < i ) opts [ ++ optEnd ] . reset ( ) ; if ( price < opts [ i ] . price ) opts [ i ] . set2 ( price , optCur , 0 ) ; } } }


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


Input: Calculates prices of a normal match and normal match + literal + rep0 . [CODESPLIT] private void calcNormalMatchPrices ( int pos , int posState , int avail , int anyMatchPrice , int startLen ) { // If the longest match is so long that it would not fit into // the opts array, shorten the matches. if ( matches . len [ matches . count - 1 ] > avail ) { matches . count = 0 ; while ( matches . len [ matches . count ] < avail ) ++ matches . count ; matches . len [ matches . count ++ ] = avail ; } if ( matches . len [ matches . count - 1 ] < startLen ) return ; while ( optEnd < optCur + matches . len [ matches . count - 1 ] ) opts [ ++ optEnd ] . reset ( ) ; int normalMatchPrice = getNormalMatchPrice ( anyMatchPrice , opts [ optCur ] . state ) ; int match = 0 ; while ( startLen > matches . len [ match ] ) ++ match ; for ( int len = startLen ; ; ++ len ) { int dist = matches . dist [ match ] ; // Calculate the price of a match of len bytes from the nearest // possible distance. int matchAndLenPrice = getMatchAndLenPrice ( normalMatchPrice , dist , len , posState ) ; if ( matchAndLenPrice < opts [ optCur + len ] . price ) opts [ optCur + len ] . set1 ( matchAndLenPrice , optCur , dist + REPS ) ; if ( len != matches . len [ match ] ) continue ; // Try match + literal + rep0. First get the length of the rep0. int len2Limit = Math . min ( niceLen , avail - len - 1 ) ; int len2 = lz . getMatchLen ( len + 1 , dist , len2Limit ) ; if ( len2 >= MATCH_LEN_MIN ) { nextState . set ( opts [ optCur ] . state ) ; nextState . updateMatch ( ) ; // Literal int curByte = lz . getByte ( len , 0 ) ; int matchByte = lz . getByte ( 0 ) ; // lz.getByte(len, len) int prevByte = lz . getByte ( len , 1 ) ; int price = matchAndLenPrice + literalEncoder . getPrice ( curByte , matchByte , prevByte , pos + len , nextState ) ; nextState . updateLiteral ( ) ; // Rep0 int nextPosState = ( pos + len + 1 ) & posMask ; price += getLongRepAndLenPrice ( 0 , len2 , nextState , nextPosState ) ; int i = optCur + len + 1 + len2 ; while ( optEnd < i ) opts [ ++ optEnd ] . reset ( ) ; if ( price < opts [ i ] . price ) opts [ i ] . set3 ( price , optCur , dist + REPS , len , 0 ) ; } if ( ++ match == matches . count ) break ; } }


Input: Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will block until <code > len< / code > bytes have been decompressed the end of the LZMA2 stream is reached or an exception is thrown . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; try { int size = 0 ; while ( len > 0 ) { if ( uncompressedSize == 0 ) { decodeChunkHeader ( ) ; if ( endReached ) return size == 0 ? - 1 : size ; } int copySizeMax = Math . min ( uncompressedSize , len ) ; if ( ! isLZMAChunk ) { lz . copyUncompressed ( in , copySizeMax ) ; } else { lz . setLimit ( copySizeMax ) ; lzma . decode ( ) ; } int copiedSize = lz . flush ( buf , off ) ; off += copiedSize ; len -= copiedSize ; size += copiedSize ; uncompressedSize -= copiedSize ; if ( uncompressedSize == 0 ) if ( ! rc . isFinished ( ) || lz . hasPending ( ) ) throw new CorruptedInputException ( ) ; } return size ; } catch ( IOException e ) { exception = e ; throw e ; } }


Input: Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . <p > In LZMA2InputStream the return value will be non - zero when the decompressor is in the middle of an LZMA2 chunk . The return value will then be the number of uncompressed bytes remaining from that chunk . The return value can also be non - zero in the middle of an uncompressed chunk but then the return value depends also on the <code > available () < / code > method of the underlying InputStream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; return isLZMAChunk ? uncompressedSize : Math . min ( uncompressedSize , in . available ( ) ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( final BundleContext bundleContext ) throws Exception { Activator . INSTANCE = this ; this . aspects = new ChannelAspectProcessor ( bundleContext ) ; this . recipes = new RecipeProcessor ( bundleContext ) ; this . generatorProcessor = new GeneratorProcessor ( bundleContext ) ; this . generatorProcessor . open ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void stop ( final BundleContext bundleContext ) throws Exception { this . aspects . close ( ) ; this . recipes . dispose ( ) ; this . generatorProcessor . close ( ) ; Activator . INSTANCE = null ; }


Input: Read a single character . This method will block until a character is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( ) throws IOException { // decode character int c = fSurrogate ; if ( fSurrogate == - 1 ) { // NOTE: We use the index into the buffer if there are remaining //       bytes from the last block read. -Ac int index = 0 ; // get first byte int b0 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b0 == - 1 ) { return - 1 ; } // UTF-8:   [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if ( b0 < 0x80 ) { c = ( char ) b0 ; } // UTF-8:   [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] else if ( ( b0 & 0xE0 ) == 0xC0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 2 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 2 , b1 ) ; } c = ( ( b0 << 6 ) & 0x07C0 ) | ( b1 & 0x003F ) ; } // UTF-8:   [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] else if ( ( b0 & 0xF0 ) == 0xE0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 3 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 3 , b1 ) ; } int b2 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b2 == - 1 ) { expectedByte ( 3 , 3 ) ; } if ( ( b2 & 0xC0 ) != 0x80 ) { invalidByte ( 3 , 3 , b2 ) ; } c = ( ( b0 << 12 ) & 0xF000 ) | ( ( b1 << 6 ) & 0x0FC0 ) | ( b2 & 0x003F ) ; } // UTF-8:   [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) //          [1101 11yy] [yyxx xxxx] (low surrogate) //          * uuuuu = wwww + 1 else if ( ( b0 & 0xF8 ) == 0xF0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 4 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 3 , b1 ) ; } int b2 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b2 == - 1 ) { expectedByte ( 3 , 4 ) ; } if ( ( b2 & 0xC0 ) != 0x80 ) { invalidByte ( 3 , 3 , b2 ) ; } int b3 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b3 == - 1 ) { expectedByte ( 4 , 4 ) ; } if ( ( b3 & 0xC0 ) != 0x80 ) { invalidByte ( 4 , 4 , b3 ) ; } int uuuuu = ( ( b0 << 2 ) & 0x001C ) | ( ( b1 >> 4 ) & 0x0003 ) ; if ( uuuuu > 0x10 ) { invalidSurrogate ( uuuuu ) ; } int wwww = uuuuu - 1 ; int hs = 0xD800 | ( ( wwww << 6 ) & 0x03C0 ) | ( ( b1 << 2 ) & 0x003C ) | ( ( b2 >> 4 ) & 0x0003 ) ; int ls = 0xDC00 | ( ( b2 << 6 ) & 0x03C0 ) | ( b3 & 0x003F ) ; c = hs ; fSurrogate = ls ; } // error else { invalidByte ( 1 , 1 , b0 ) ; } } // use surrogate else { fSurrogate = - 1 ; } // return character return c ; }


Input: Read characters into a portion of an array . This method will block until some input is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( char ch [ ] , int offset , int length ) throws IOException { // handle surrogate int out = offset ; if ( fSurrogate != - 1 ) { ch [ offset + 1 ] = ( char ) fSurrogate ; fSurrogate = - 1 ; length -- ; out ++ ; } // read bytes int count = 0 ; if ( fOffset == 0 ) { // adjust length to read if ( length > fBuffer . length ) { length = fBuffer . length ; } // perform read operation count = fInputStream . read ( fBuffer , 0 , length ) ; if ( count == - 1 ) { return - 1 ; } count += out - offset ; } // skip read; last character was in error // NOTE: Having an offset value other than zero means that there was //       an error in the last character read. In this case, we have //       skipped the read so we don't consume any bytes past the  //       error. By signalling the error on the next block read we //       allow the method to return the most valid characters that //       it can on the previous block read. -Ac else { count = fOffset ; fOffset = 0 ; } // convert bytes to characters final int total = count ; for ( int in = 0 ; in < total ; in ++ ) { int b0 = fBuffer [ in ] & 0x00FF ; // UTF-8:   [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if ( b0 < 0x80 ) { ch [ out ++ ] = ( char ) b0 ; continue ; } // UTF-8:   [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] if ( ( b0 & 0xE0 ) == 0xC0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 2 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 2 , b1 ) ; } int c = ( ( b0 << 6 ) & 0x07C0 ) | ( b1 & 0x003F ) ; ch [ out ++ ] = ( char ) c ; count -= 1 ; continue ; } // UTF-8:   [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] if ( ( b0 & 0xF0 ) == 0xE0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 3 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 3 , b1 ) ; } int b2 = - 1 ; if ( ++ in < total ) { b2 = fBuffer [ in ] & 0x00FF ; } else { b2 = fInputStream . read ( ) ; if ( b2 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } expectedByte ( 3 , 3 ) ; } count ++ ; } if ( ( b2 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } invalidByte ( 3 , 3 , b2 ) ; } int c = ( ( b0 << 12 ) & 0xF000 ) | ( ( b1 << 6 ) & 0x0FC0 ) | ( b2 & 0x003F ) ; ch [ out ++ ] = ( char ) c ; count -= 2 ; continue ; } // UTF-8:   [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) //          [1101 11yy] [yyxx xxxx] (low surrogate) //          * uuuuu = wwww + 1 if ( ( b0 & 0xF8 ) == 0xF0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 4 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 4 , b1 ) ; } int b2 = - 1 ; if ( ++ in < total ) { b2 = fBuffer [ in ] & 0x00FF ; } else { b2 = fInputStream . read ( ) ; if ( b2 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } expectedByte ( 3 , 4 ) ; } count ++ ; } if ( ( b2 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } invalidByte ( 3 , 4 , b2 ) ; } int b3 = - 1 ; if ( ++ in < total ) { b3 = fBuffer [ in ] & 0x00FF ; } else { b3 = fInputStream . read ( ) ; if ( b3 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } expectedByte ( 4 , 4 ) ; } count ++ ; } if ( ( b3 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fBuffer [ 3 ] = ( byte ) b3 ; fOffset = 4 ; return out - offset ; } invalidByte ( 4 , 4 , b2 ) ; } // decode bytes into surrogate characters int uuuuu = ( ( b0 << 2 ) & 0x001C ) | ( ( b1 >> 4 ) & 0x0003 ) ; if ( uuuuu > 0x10 ) { invalidSurrogate ( uuuuu ) ; } int wwww = uuuuu - 1 ; int zzzz = b1 & 0x000F ; int yyyyyy = b2 & 0x003F ; int xxxxxx = b3 & 0x003F ; int hs = 0xD800 | ( ( wwww << 6 ) & 0x03C0 ) | ( zzzz << 2 ) | ( yyyyyy >> 4 ) ; int ls = 0xDC00 | ( ( yyyyyy << 6 ) & 0x03C0 ) | xxxxxx ; // set characters ch [ out ++ ] = ( char ) hs ; ch [ out ++ ] = ( char ) ls ; count -= 2 ; continue ; } // error if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } invalidByte ( 1 , 1 , b0 ) ; } // return number of characters converted return count ; }


Input: Throws an exception for expected byte . [CODESPLIT] private void expectedByte ( int position , int count ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( "jsp.error.xml.expectedByte" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }


Input: Throws an exception for invalid byte . [CODESPLIT] private void invalidByte ( int position , int count , int c ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( "jsp.error.xml.invalidByte" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }