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


Input: Get the length of a match at the given distance . [CODESPLIT] public int getMatchLen ( int dist , int lenLimit ) { int backPos = readPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ readPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }


Input: Get the length of a match at the given distance and forward offset . [CODESPLIT] public int getMatchLen ( int forward , int dist , int lenLimit ) { int curPos = readPos + forward ; int backPos = curPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ curPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }


Input: Verifies that the matches returned by the match finder are valid . This is meant to be used in an assert statement . This is totally useless for actual encoding since match finder s results should naturally always be valid if it isn t broken . [CODESPLIT] public boolean verifyMatches ( Matches matches ) { int lenLimit = Math . min ( getAvail ( ) , matchLenMax ) ; for ( int i = 0 ; i < matches . count ; ++ i ) if ( getMatchLen ( matches . dist [ i ] , lenLimit ) != matches . len [ i ] ) return false ; return true ; }


Input: Moves to the next byte checks if there is enough input available and returns the amount of input available . [CODESPLIT] int movePos ( int requiredForFlushing , int requiredForFinishing ) { assert requiredForFlushing >= requiredForFinishing ; ++ readPos ; int avail = writePos - readPos ; if ( avail < requiredForFlushing ) { if ( avail < requiredForFinishing || ! finishing ) { ++ pendingSize ; avail = 0 ; } } return avail ; }


Input: Package - level access [CODESPLIT] void recycle ( ) { flushed = false ; closed = false ; out = null ; byteOut = null ; releaseCharBuffer ( ) ; response = null ; }


Input: Flush the output buffer to the underlying character stream without flushing the stream itself . This method is non - private only so that it may be invoked by PrintStream . [CODESPLIT] protected final void flushBuffer ( ) throws IOException { if ( bufferSize == 0 ) return ; flushed = true ; ensureOpen ( ) ; if ( buf . pos == buf . offset ) return ; initOut ( ) ; out . write ( buf . buf , buf . offset , buf . pos - buf . offset ) ; buf . pos = buf . offset ; }


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


Input: Flush the stream . [CODESPLIT] public void flush ( ) throws IOException { flushBuffer ( ) ; if ( out != null ) { out . flush ( ) ; } // START 6426898 else { // Set the default character encoding if there isn't any present, // see CR 6699416 response . setCharacterEncoding ( response . getCharacterEncoding ( ) ) ; // Cause response headers to be sent response . flushBuffer ( ) ; } // END 6426898 }


Input: Close the stream . [CODESPLIT] public void close ( ) throws IOException { if ( response == null || closed ) // multiple calls to close is OK return ; flush ( ) ; if ( out != null ) out . close ( ) ; out = null ; byteOut = null ; closed = true ; }


Input: Attempt to write a String pre - encoded with the page encoding . [CODESPLIT] public void write ( boolean bytesOK , byte buf [ ] , String str ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 && bytesOK ) { initByteOut ( ) ; if ( implementsByteWriter ) { write ( buf , 0 , buf . length ) ; return ; } } write ( str ) ; }


Input: Write a single character . [CODESPLIT] public void write ( int c ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( c ) ; } else { if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; buf . buf [ buf . pos ++ ] = ( char ) c ; } }


Input:
Write a portion of an array of characters . [CODESPLIT] public void write ( char cbuf [ ] , int off , int len ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( cbuf , off , len ) ; return ; } if ( ( off < 0 ) || ( off > cbuf . length ) || ( len < 0 ) || ( ( off + len ) > cbuf . length ) || ( ( off + len ) < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } if ( len >= bufferSize ) { /* If the request length exceeds the size of the output buffer,
               flush the buffer and then write the data directly.  In this
               way buffered streams will cascade harmlessly. */ if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; initOut ( ) ; out . write ( cbuf , off , len ) ; return ; } int b = off , t = off + len ; while ( b < t ) { int d = min ( getRemaining ( ) , t - b ) ; System . arraycopy ( cbuf , b , buf . buf , buf . pos , d ) ; b += d ; buf . pos += d ; if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; } }


Input: Write a portion of a String . [CODESPLIT] public void write ( String s , int off , int len ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( s , off , len ) ; return ; } int b = off , t = off + len ; while ( b < t ) { int d = min ( getRemaining ( ) , t - b ) ; s . getChars ( b , b + d , buf . buf , buf . pos ) ; b += d ; buf . pos += d ; if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; } }


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


Input: Lock and return { @link AutoCloseable } instance for unlocking Use with a <tt > try - with - resources< / tt > construct : [CODESPLIT] public static Locked lock ( final Lock lock ) { lock . lock ( ) ; return new Locked ( ) { @ Override public void close ( ) { lock . unlock ( ) ; } } ; }


Input: / * Processes the given JSP parse error . [CODESPLIT] public void jspError ( String fname , int line , int column , String errMsg , Exception ex ) throws JasperException { throw new JasperException ( fname + "(" + line + "," + column + ")" + " " + errMsg , ex ) ; }


Input: / * Processes the given javac compilation errors . [CODESPLIT] public void javacError ( JavacErrorDetail [ ] details ) throws JasperException { if ( details == null ) { return ; } Object [ ] args = null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < details . length ; i ++ ) { if ( details [ i ] . getJspBeginLineNumber ( ) >= 0 ) { args = new Object [ ] { Integer . valueOf ( details [ i ] . getJspBeginLineNumber ( ) ) , details [ i ] . getJspFileName ( ) } ; buf . append ( Localizer . getMessage ( "jsp.error.single.line.number" , args ) ) ; buf . append ( "\n" ) ; } buf . append ( Localizer . getMessage ( "jsp.error.corresponding.servlet" ) ) ; buf . append ( details [ i ] . getErrorMessage ( ) ) ; buf . append ( "\n\n" ) ; } if ( buf . length ( ) == 0 ) { throw new JasperException ( Localizer . getMessage ( "jsp.error.nojdk" ) ) ; } throw new JasperException ( Localizer . getMessage ( "jsp.error.unable.compile" ) + "\n\n" + buf ) ; }


Input: Processes the given javac error report and exception . [CODESPLIT] public void javacError ( String errorReport , Exception exception ) throws JasperException { throw new JasperException ( Localizer . getMessage ( "jsp.error.unable.compile" ) , exception ) ; }


Input: Puts all allocated arrays back to the underlying ArrayCache that haven t already been put there with a call to { [CODESPLIT] public void reset ( ) { if ( byteArrays != null ) { // Put the arrays to the cache in reverse order: the array that // was allocated first is returned last. synchronized ( byteArrays ) { for ( int i = byteArrays . size ( ) - 1 ; i >= 0 ; -- i ) arrayCache . putArray ( byteArrays . get ( i ) ) ; byteArrays . clear ( ) ; } synchronized ( intArrays ) { for ( int i = intArrays . size ( ) - 1 ; i >= 0 ; -- i ) arrayCache . putArray ( intArrays . get ( i ) ) ; intArrays . clear ( ) ; } } }


Input: / * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode ) { String errMsg = errCode ; try { errMsg = bundle . getString ( errCode ) ; } catch ( MissingResourceException e ) { } return errMsg ; }


Input: / * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , String arg ) { return getMessage ( errCode , new Object [ ] { arg } ) ; }


Input: / * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , String arg1 , String arg2 ) { return getMessage ( errCode , new Object [ ] { arg1 , arg2 } ) ; }


Input: / * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , Object [ ] args ) { String errMsg = errCode ; try { errMsg = bundle . getString ( errCode ) ; if ( args != null ) { MessageFormat formatter = new MessageFormat ( errMsg ) ; errMsg = formatter . format ( args ) ; } } catch ( MissingResourceException e ) { } return errMsg ; }


Input: Make a key from the aggregator fields [CODESPLIT] public List < String > makeKey ( final Map < MetaKey , String > metaData , final boolean requireAll ) { final List < String > result = new ArrayList <> ( this . fields . size ( ) ) ; for ( final MetaKey field : this . fields ) { final String value = metaData . get ( field ) ; if ( requireAll && value == null ) { return null ; } result . add ( value ) ; } return result ; }


Input:
Compile the jsp file into equivalent servlet in java source [CODESPLIT] private void generateJava ( ) throws Exception { long t1 , t2 , t3 , t4 ; t1 = t2 = t3 = t4 = 0 ; if ( log . isLoggable ( Level . FINE ) ) { t1 = System . currentTimeMillis ( ) ; } // Setup page info area pageInfo = new PageInfo ( new BeanRepository ( ctxt . getClassLoader ( ) , errDispatcher ) , ctxt . getJspFile ( ) ) ; JspConfig jspConfig = options . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( ctxt . getJspFile ( ) ) ; /*
         * If the current uri is matched by a pattern specified in
         * a jsp-property-group in web.xml, initialize pageInfo with
         * those properties.
         */ pageInfo . setELIgnored ( JspUtil . booleanValue ( jspProperty . isELIgnored ( ) ) ) ; pageInfo . setScriptingInvalid ( JspUtil . booleanValue ( jspProperty . isScriptingInvalid ( ) ) ) ; pageInfo . setTrimDirectiveWhitespaces ( JspUtil . booleanValue ( jspProperty . getTrimSpaces ( ) ) ) ; pageInfo . setDeferredSyntaxAllowedAsLiteral ( JspUtil . booleanValue ( jspProperty . getPoundAllowed ( ) ) ) ; pageInfo . setErrorOnUndeclaredNamespace ( JspUtil . booleanValue ( jspProperty . errorOnUndeclaredNamespace ( ) ) ) ; if ( jspProperty . getIncludePrelude ( ) != null ) { pageInfo . setIncludePrelude ( jspProperty . getIncludePrelude ( ) ) ; } if ( jspProperty . getIncludeCoda ( ) != null ) { pageInfo . setIncludeCoda ( jspProperty . getIncludeCoda ( ) ) ; } if ( options . isDefaultBufferNone ( ) && pageInfo . getBufferValue ( ) == null ) { // Set to unbuffered if not specified explicitly pageInfo . setBuffer ( 0 ) ; } String javaFileName = ctxt . getServletJavaFileName ( ) ; ServletWriter writer = null ; try { // Setup the ServletWriter Writer javaWriter = javaCompiler . getJavaWriter ( javaFileName , ctxt . getOptions ( ) . getJavaEncoding ( ) ) ; writer = new ServletWriter ( new PrintWriter ( javaWriter ) ) ; ctxt . setWriter ( writer ) ; // Reset the temporary variable counter for the generator. JspUtil . resetTemporaryVariableName ( ) ; // Parse the file ParserController parserCtl = new ParserController ( ctxt , this ) ; pageNodes = parserCtl . parse ( ctxt . getJspFile ( ) ) ; if ( ctxt . isPrototypeMode ( ) ) { // generate prototype .java file for the tag file Generator . generate ( writer , this , pageNodes ) ; writer . close ( ) ; writer = null ; return ; } // Validate and process attributes Validator . validate ( this , pageNodes ) ; if ( log . isLoggable ( Level . FINE ) ) { t2 = System . currentTimeMillis ( ) ; } // Collect page info Collector . collect ( this , pageNodes ) ; // Compile (if necessary) and load the tag files referenced in // this compilation unit. tfp = new TagFileProcessor ( ) ; tfp . loadTagFiles ( this , pageNodes ) ; if ( log . isLoggable ( Level . FINE ) ) { t3 = System . currentTimeMillis ( ) ; } // Determine which custom tag needs to declare which scripting vars ScriptingVariabler . set ( pageNodes , errDispatcher ) ; // Optimizations by Tag Plugins TagPluginManager tagPluginManager = options . getTagPluginManager ( ) ; tagPluginManager . apply ( pageNodes , errDispatcher , pageInfo ) ; // Optimization: concatenate contiguous template texts. TextOptimizer . concatenate ( this , pageNodes ) ; // Generate static function mapper codes. ELFunctionMapper . map ( this , pageNodes ) ; // generate servlet .java file Generator . generate ( writer , this , pageNodes ) ; writer . close ( ) ; writer = null ; // The writer is only used during the compile, dereference // it in the JspCompilationContext when done to allow it // to be GC'd and save memory. ctxt . setWriter ( null ) ; if ( log . isLoggable ( Level . FINE ) ) { t4 = System . currentTimeMillis ( ) ; log . fine ( "Generated " + javaFileName + " total=" + ( t4 - t1 ) + " generate=" + ( t4 - t3 ) + " validate=" + ( t2 - t1 ) ) ; } } catch ( Exception e ) { if ( writer != null ) { try { writer . close ( ) ; writer = null ; } catch ( Exception e1 ) { // do nothing } } // Remove the generated .java file javaCompiler . doJavaFile ( false ) ; throw e ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e2 ) { // do nothing } } } // JSR45 Support if ( ! options . isSmapSuppressed ( ) ) { smapUtil . generateSmap ( pageNodes ) ; } // If any proto type .java and .class files was generated, // the prototype .java may have been replaced by the current // compilation (if the tag file is self referencing), but the // .class file need to be removed, to make sure that javac would // generate .class again from the new .java file just generated. tfp . removeProtoTypeFiles ( ctxt . getClassFileName ( ) ) ; }


Input: Compile the servlet from . java file to . class file [CODESPLIT] private void generateClass ( ) throws FileNotFoundException , JasperException , Exception { long t1 = 0 ; if ( log . isLoggable ( Level . FINE ) ) { t1 = System . currentTimeMillis ( ) ; } String javaFileName = ctxt . getServletJavaFileName ( ) ; setJavaCompilerOptions ( ) ; // Start java compilation JavacErrorDetail [ ] javacErrors = javaCompiler . compile ( ctxt . getFullClassName ( ) , pageNodes ) ; if ( javacErrors != null ) { // If there are errors, always generate java files to disk. javaCompiler . doJavaFile ( true ) ; log . severe ( "Error compiling file: " + javaFileName ) ; errDispatcher . javacError ( javacErrors ) ; } if ( log . isLoggable ( Level . FINE ) ) { long t2 = System . currentTimeMillis ( ) ; log . fine ( "Compiled " + javaFileName + " " + ( t2 - t1 ) + "ms" ) ; } // Save or delete the generated Java files, depending on the // value of "keepgenerated" attribute javaCompiler . doJavaFile ( ctxt . keepGenerated ( ) ) ; // JSR45 Support if ( ! ctxt . isPrototypeMode ( ) && ! options . isSmapSuppressed ( ) ) { smapUtil . installSmap ( ) ; } // START CR 6373479 if ( jsw != null && jsw . getServletClassLastModifiedTime ( ) <= 0 ) { jsw . setServletClassLastModifiedTime ( javaCompiler . getClassLastModified ( ) ) ; } // END CR 6373479 if ( options . getSaveBytecode ( ) ) { javaCompiler . saveClassFile ( ctxt . getFullClassName ( ) , ctxt . getClassFileName ( ) ) ; } // On some systems, due to file caching, the time stamp for the updated // JSP file may actually be greater than that of the newly created byte // codes in the cache.  In such cases, adjust the cache time stamp to // JSP page time, to avoid unnecessary recompilations. ctxt . getRuntimeContext ( ) . adjustBytecodeTime ( ctxt . getFullClassName ( ) , jspModTime ) ; }


Input: Compile the jsp file from the current engine context . As an side - effect tag files that are referenced by this page are also compiled . [CODESPLIT] public void compile ( boolean compileClass ) throws FileNotFoundException , JasperException , Exception { try { // Create the output directory for the generated files // Always try and create the directory tree, in case the generated // directories were deleted after the server was started. ctxt . makeOutputDir ( ctxt . getOutputDir ( ) ) ; // If errDispatcher is nulled from a previous compilation of the // same page, instantiate one here. if ( errDispatcher == null ) { errDispatcher = new ErrorDispatcher ( jspcMode ) ; } generateJava ( ) ; if ( compileClass ) { generateClass ( ) ; } else { // If called from jspc to only compile to .java files, // make sure that .java files are written to disk. javaCompiler . doJavaFile ( ctxt . keepGenerated ( ) ) ; } } finally { if ( tfp != null ) { tfp . removeProtoTypeFiles ( null ) ; } javaCompiler . release ( ) ; // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null ; errDispatcher = null ; if ( ! jspcMode ) { pageInfo = null ; } pageNodes = null ; if ( ctxt . getWriter ( ) != null ) { ctxt . getWriter ( ) . close ( ) ; ctxt . setWriter ( null ) ; } } }


Input:
Determine if a compilation is necessary by checking the time stamp of the JSP page with that of the corresponding . class or . java file . If the page has dependencies the check is also extended to its dependeants and so on . This method can by overidden by a subclasses of Compiler . [CODESPLIT] public boolean isOutDated ( boolean checkClass ) { String jsp = ctxt . getJspFile ( ) ; if ( jsw != null && ( ctxt . getOptions ( ) . getModificationTestInterval ( ) > 0 ) ) { if ( jsw . getLastModificationTest ( ) + ( ctxt . getOptions ( ) . getModificationTestInterval ( ) * 1000 ) > System . currentTimeMillis ( ) ) { return false ; } else { jsw . setLastModificationTest ( System . currentTimeMillis ( ) ) ; } } long jspRealLastModified = 0 ; // START PWC 6468930 File targetFile ; if ( checkClass ) { targetFile = new File ( ctxt . getClassFileName ( ) ) ; } else { targetFile = new File ( ctxt . getServletJavaFileName ( ) ) ; } // Get the target file's last modified time. File.lastModified() // returns 0 if the file does not exist. long targetLastModified = targetFile . lastModified ( ) ; // Check cached class file if ( checkClass ) { JspRuntimeContext rtctxt = ctxt . getRuntimeContext ( ) ; String className = ctxt . getFullClassName ( ) ; long cachedTime = rtctxt . getBytecodeBirthTime ( className ) ; if ( cachedTime > targetLastModified ) { targetLastModified = cachedTime ; } else { // Remove from cache, since the bytecodes from the file is more // current, so that JasperLoader won't load the cached version rtctxt . setBytecode ( className , null ) ; } } if ( targetLastModified == 0L ) return true ; // Check if the jsp exists in the filesystem (instead of a jar // or a remote location). If yes, then do a File.lastModified() // to determine its last modified time. This is more performant  // (fewer stat calls) than the ctxt.getResource() followed by  // openConnection(). However, it only works for file system jsps. // If the file has indeed changed, then need to call URL.OpenConnection()  // so that the cache loads the latest jsp file if ( jsw != null ) { File jspFile = jsw . getJspFile ( ) ; if ( jspFile != null ) { jspRealLastModified = jspFile . lastModified ( ) ; } } if ( jspRealLastModified == 0 || targetLastModified < jspRealLastModified ) { // END PWC 6468930 try { URL jspUrl = ctxt . getResource ( jsp ) ; if ( jspUrl == null ) { ctxt . incrementRemoved ( ) ; return false ; } URLConnection uc = jspUrl . openConnection ( ) ; if ( uc instanceof JarURLConnection ) { jspRealLastModified = ( ( JarURLConnection ) uc ) . getJarEntry ( ) . getTime ( ) ; } else { jspRealLastModified = uc . getLastModified ( ) ; } uc . getInputStream ( ) . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return true ; } // START PWC 6468930 } // END PWC 6468930 /* PWC 6468930
        long targetLastModified = 0;
        File targetFile;

        if( checkClass ) {
            targetFile = new File(ctxt.getClassFileName());
        } else {
            targetFile = new File(ctxt.getServletJavaFileName());
        }

        if (!targetFile.exists()) {
            return true;
        }

        targetLastModified = targetFile.lastModified();
        */ if ( checkClass && jsw != null ) { jsw . setServletClassLastModifiedTime ( targetLastModified ) ; } if ( targetLastModified < jspRealLastModified ) { // Remember JSP mod time jspModTime = jspRealLastModified ; if ( log . isLoggable ( Level . FINE ) ) { log . fine ( "Compiler: outdated: " + targetFile + " " + targetLastModified ) ; } return true ; } // determine if source dependent files (e.g. includes using include // directives) have been changed. if ( jsw == null ) { return false ; } List < String > depends = jsw . getDependants ( ) ; if ( depends == null ) { return false ; } for ( String include : depends ) { try { URL includeUrl = ctxt . getResource ( include ) ; if ( includeUrl == null ) { return true ; } URLConnection includeUconn = includeUrl . openConnection ( ) ; long includeLastModified = 0 ; if ( includeUconn instanceof JarURLConnection ) { includeLastModified = ( ( JarURLConnection ) includeUconn ) . getJarEntry ( ) . getTime ( ) ; } else { includeLastModified = includeUconn . getLastModified ( ) ; } includeUconn . getInputStream ( ) . close ( ) ; if ( includeLastModified > targetLastModified ) { // START GlassFish 750 if ( include . endsWith ( ".tld" ) ) { ctxt . clearTaglibs ( ) ; ctxt . clearTagFileJarUrls ( ) ; } // END GlassFish 750 return true ; } } catch ( Exception e ) { e . printStackTrace ( ) ; return true ; } } return false ; }


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


Input: Get an instance of JavaCompiler . If Running with JDK 6 use a Jsr199JavaCompiler that supports JSR199 else if eclipse s JDT compiler is available use that . The default is to use javac from ant . [CODESPLIT] private void initJavaCompiler ( ) throws JasperException { boolean disablejsr199 = Boolean . TRUE . toString ( ) . equals ( System . getProperty ( "org.apache.jasper.compiler.disablejsr199" ) ) ; Double version = Double . valueOf ( System . getProperty ( "java.specification.version" ) ) ; if ( ! disablejsr199 && ( version >= 1.6 || getClassFor ( "javax.tools.Tool" ) != null ) ) { // JDK 6 or bundled with jsr199 compiler javaCompiler = new Jsr199JavaCompiler ( ) ; } else { Class c = getClassFor ( "org.eclipse.jdt.internal.compiler.Compiler" ) ; if ( c != null ) { c = getClassFor ( "org.apache.jasper.compiler.JDTJavaCompiler" ) ; if ( c != null ) { try { javaCompiler = ( JavaCompiler ) c . newInstance ( ) ; } catch ( Exception ex ) { } } } } if ( javaCompiler == null ) { Class c = getClassFor ( "org.apache.tools.ant.taskdefs.Javac" ) ; if ( c != null ) { c = getClassFor ( "org.apache.jasper.compiler.AntJavaCompiler" ) ; if ( c != null ) { try { javaCompiler = ( JavaCompiler ) c . newInstance ( ) ; } catch ( Exception ex ) { } } } } if ( javaCompiler == null ) { errDispatcher . jspError ( "jsp.error.nojavac" ) ; } javaCompiler . init ( ctxt , errDispatcher , jspcMode ) ; }


Input: Return true if the path refers to a jar file in WEB - INF and is a system jar . [CODESPLIT] private boolean systemJarInWebinf ( String path ) { if ( path . indexOf ( "/WEB-INF/" ) < 0 ) { return false ; } Boolean useMyFaces = ( Boolean ) ctxt . getServletContext ( ) . getAttribute ( "com.sun.faces.useMyFaces" ) ; if ( useMyFaces == null || ! useMyFaces ) { for ( String jar : systemJsfJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } } for ( String jar : systemJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } return false ; }


Input: Decode into an array of bytes . <p > This calls <code > in . read ( buf off len ) < / code > and defilters the returned data . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; int size ; try { size = in . read ( buf , off , len ) ; } catch ( IOException e ) { exception = e ; throw e ; } if ( size == - 1 ) return - 1 ; delta . decode ( buf , off , size ) ; return size ; }


Input: Calls <code > in . available () < / code > . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; return in . available ( ) ; }


Input: Single quote and escape a character [CODESPLIT] static String quote ( char c ) { StringBuilder b = new StringBuilder ( ) ; b . append ( ' ' ) ; if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else b . append ( c ) ; b . append ( ' ' ) ; return b . toString ( ) ; }


Input:
Generates declarations . This includes info of the page directive and scriptlet declarations . [CODESPLIT] private void generateDeclarations ( Node . Nodes page ) throws JasperException { class DeclarationVisitor extends Node . Visitor { private boolean getServletInfoGenerated = false ; /*
             * Generates getServletInfo() method that returns the value of the
             * page directive's 'info' attribute, if present.
             *
             * The Validator has already ensured that if the translation unit
             * contains more than one page directive with an 'info' attribute,
             * their values match.
             */ public void visit ( Node . PageDirective n ) throws JasperException { if ( getServletInfoGenerated ) { return ; } String info = n . getAttributeValue ( "info" ) ; if ( info == null ) return ; getServletInfoGenerated = true ; out . printil ( "public String getServletInfo() {" ) ; out . pushIndent ( ) ; out . printin ( "return " ) ; out . print ( quote ( info ) ) ; out . println ( ";" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; } public void visit ( Node . Declaration n ) throws JasperException { n . setBeginJavaLine ( out . getJavaLine ( ) ) ; out . printMultiLn ( n . getText ( ) ) ; out . println ( ) ; n . setEndJavaLine ( out . getJavaLine ( ) ) ; } // Custom Tags may contain declarations from tag plugins. public void visit ( Node . CustomTag n ) throws JasperException { if ( n . useTagPlugin ( ) ) { if ( n . getAtSTag ( ) != null ) { n . getAtSTag ( ) . visit ( this ) ; } visitBody ( n ) ; if ( n . getAtETag ( ) != null ) { n . getAtETag ( ) . visit ( this ) ; } } else { visitBody ( n ) ; } } } out . println ( ) ; page . visit ( new DeclarationVisitor ( ) ) ; }


Input:
Compiles list of tag handler pool names . [CODESPLIT] private void compileTagHandlerPoolList ( Node . Nodes page ) throws JasperException { class TagHandlerPoolVisitor extends Node . Visitor { private Set < String > names = new HashSet < String > ( ) ; /*
             * Constructor
             *
             * @param v Set of tag handler pool names to populate
             */ TagHandlerPoolVisitor ( Set < String > v ) { names = v ; } /*
             * Gets the name of the tag handler pool for the given custom tag
             * and adds it to the list of tag handler pool names unless it is
             * already contained in it.
             */ public void visit ( Node . CustomTag n ) throws JasperException { if ( ! n . implementsSimpleTag ( ) ) { String name = createTagHandlerPoolName ( n . getPrefix ( ) , n . getLocalName ( ) , n . getAttributes ( ) , n . hasEmptyBody ( ) ) ; n . setTagHandlerPoolName ( name ) ; if ( ! names . contains ( name ) ) { names . add ( name ) ; } } visitBody ( n ) ; } /*
             * Creates the name of the tag handler pool whose tag handlers may
             * be (re)used to service this action.
             *
             * @return The name of the tag handler pool
             */ private String createTagHandlerPoolName ( String prefix , String shortName , Attributes attrs , boolean hasEmptyBody ) { String poolName = null ; poolName = "_jspx_tagPool_" + prefix + "_" + shortName ; if ( attrs != null ) { String [ ] attrNames = new String [ attrs . getLength ( ) ] ; for ( int i = 0 ; i < attrNames . length ; i ++ ) { attrNames [ i ] = attrs . getQName ( i ) ; } Arrays . sort ( attrNames , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < attrNames . length ; i ++ ) { poolName = poolName + "_" + attrNames [ i ] ; } } if ( hasEmptyBody ) { poolName = poolName + "_nobody" ; } return JspUtil . makeXmlJavaIdentifier ( poolName ) ; } } page . visit ( new TagHandlerPoolVisitor ( tagHandlerPoolNames ) ) ; }


Input: Generates the _jspInit () method for instantiating the tag handler pools . For tag file _jspInit has to be invoked manually and the ServletConfig object explicitly passed . [CODESPLIT] private void generateTagHandlerInit ( ) { if ( ! isPoolingEnabled || tagHandlerPoolNames . isEmpty ( ) ) { return ; } if ( ctxt . isTagFile ( ) ) { out . printil ( "private void _jspInit(ServletConfig config) {" ) ; } else { out . printil ( "public void _jspInit() {" ) ; } out . pushIndent ( ) ; for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printin ( tagHandlerPoolName ) ; out . print ( " = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(" ) ; if ( ctxt . isTagFile ( ) ) { out . print ( "config" ) ; } else { out . print ( "getServletConfig()" ) ; } out . println ( ");" ) ; } out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; }


Input: Generates the _jspDestroy () method which is responsible for calling the release () method on every tag handler in any of the tag handler pools . [CODESPLIT] private void generateTagHandlerDestroy ( ) { if ( ! isPoolingEnabled || tagHandlerPoolNames . isEmpty ( ) ) { return ; } out . printil ( "public void _jspDestroy() {" ) ; out . pushIndent ( ) ; for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printin ( tagHandlerPoolName ) ; out . println ( ".release();" ) ; } out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; }


Input: Generate preamble package name ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreamblePackage ( String packageName ) throws JasperException { if ( ! "" . equals ( packageName ) && packageName != null ) { out . printil ( "package " + packageName + ";" ) ; out . println ( ) ; } }


Input: Generate preamble imports ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleImports ( ) throws JasperException { Iterator < String > iter = pageInfo . getImports ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { out . printin ( "import " ) ; out . print ( iter . next ( ) ) ; out . println ( ";" ) ; } out . println ( ) ; }


Input: Generation of static initializers in preamble . For example dependant list el function map prefix map . ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleStaticInitializers ( ) throws JasperException { out . printil ( "private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();" ) ; out . println ( ) ; // Static data for getDependants() out . printil ( "private static java.util.List<String> _jspx_dependants;" ) ; out . println ( ) ; List < String > dependants = pageInfo . getDependants ( ) ; Iterator < String > iter = dependants . iterator ( ) ; if ( ! dependants . isEmpty ( ) ) { out . printil ( "static {" ) ; out . pushIndent ( ) ; out . printin ( "_jspx_dependants = new java.util.ArrayList<String>(" ) ; out . print ( "" + dependants . size ( ) ) ; out . println ( ");" ) ; while ( iter . hasNext ( ) ) { out . printin ( "_jspx_dependants.add(\"" ) ; out . print ( iter . next ( ) ) ; out . println ( "\");" ) ; } out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; } // Codes to support genStringAsByteArray option // Generate a static variable for the initial response encoding if ( genBytes ) { // first get the respons encoding String contentType = pageInfo . getContentType ( ) ; String encoding = "ISO-8859-1" ; int i = contentType . indexOf ( "charset=" ) ; if ( i > 0 ) encoding = contentType . substring ( i + 8 ) ; // Make sure the encoding is supported // Assume that this can be determined at compile time try { "testing" . getBytes ( encoding ) ; out . printin ( "private static final String _jspx_encoding = " ) ; out . print ( quote ( encoding ) ) ; out . println ( ";" ) ; out . printil ( "private boolean _jspx_gen_bytes = true;" ) ; out . printil ( "private boolean _jspx_encoding_tested;" ) ; } catch ( java . io . UnsupportedEncodingException ex ) { genBytes = false ; } } }


Input: Declare tag handler pools ( tags of the same type and with the same attribute set share the same tag handler pool ) ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleClassVariableDeclarations ( String className ) throws JasperException { if ( isPoolingEnabled ) { if ( ! tagHandlerPoolNames . isEmpty ( ) ) { for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printil ( "private org.apache.jasper.runtime.TagHandlerPool " + tagHandlerPoolName + ";" ) ; } out . println ( ) ; } } out . printil ( "private org.glassfish.jsp.api.ResourceInjector " + "_jspx_resourceInjector;" ) ; out . println ( ) ; }


Input: Declare general - purpose methods ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleMethods ( ) throws JasperException { // Method used to get compile time file dependencies out . printil ( "public java.util.List<String> getDependants() {" ) ; out . pushIndent ( ) ; out . printil ( "return _jspx_dependants;" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; // Method to get bytes from String if ( genBytes ) { out . printil ( "private static byte[] _jspx_getBytes(String s) {" ) ; out . pushIndent ( ) ; out . printil ( "try {" ) ; out . pushIndent ( ) ; out . printil ( "return s.getBytes(_jspx_encoding);" ) ; out . popIndent ( ) ; out . printil ( "} catch (java.io.UnsupportedEncodingException ex) {" ) ; out . printil ( "}" ) ; out . printil ( "return null;" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; // Generate code to see if the response encoding has been set // differently from the encoding declared in the page directive. // Note that we only need to do the test once.  The assumption // is that the encoding cannot be changed once some data has been // written. out . printil ( "private boolean _jspx_same_encoding(String encoding) {" ) ; out . pushIndent ( ) ; out . printil ( "if (! _jspx_encoding_tested) {" ) ; out . pushIndent ( ) ; out . printil ( "_jspx_gen_bytes = _jspx_encoding.equals(encoding);" ) ; out . printil ( "_jspx_encoding_tested = true;" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . printil ( "return _jspx_gen_bytes;" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; } generateTagHandlerInit ( ) ; generateTagHandlerDestroy ( ) ; }


Input: Generates the beginning of the static portion of the servlet . [CODESPLIT] private void generatePreamble ( Node . Nodes page ) throws JasperException { String servletPackageName = ctxt . getServletPackageName ( ) ; String servletClassName = ctxt . getServletClassName ( ) ; String serviceMethodName = Constants . SERVICE_METHOD_NAME ; // First the package name: genPreamblePackage ( servletPackageName ) ; // Generate imports genPreambleImports ( ) ; // Generate class declaration out . printin ( "public final class " ) ; out . print ( servletClassName ) ; out . print ( " extends " ) ; out . println ( pageInfo . getExtends ( ) ) ; out . printin ( "    implements org.apache.jasper.runtime.JspSourceDependent" ) ; if ( ! pageInfo . isThreadSafe ( ) ) { out . println ( "," ) ; out . printin ( "                 SingleThreadModel" ) ; } out . println ( " {" ) ; out . pushIndent ( ) ; // Class body begins here generateDeclarations ( page ) ; // Static initializations here genPreambleStaticInitializers ( ) ; // Class variable declarations genPreambleClassVariableDeclarations ( servletClassName ) ; // Constructor //	generateConstructor(className); // Methods here genPreambleMethods ( ) ; // Now the service method out . printin ( "public void " ) ; out . print ( serviceMethodName ) ; out . println ( "(HttpServletRequest request, HttpServletResponse response)" ) ; out . println ( "        throws java.io.IOException, ServletException {" ) ; out . pushIndent ( ) ; out . println ( ) ; // Local variable declarations out . printil ( "PageContext pageContext = null;" ) ; if ( pageInfo . isSession ( ) ) out . printil ( "HttpSession session = null;" ) ; if ( pageInfo . isErrorPage ( ) ) { out . printil ( "Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);" ) ; out . printil ( "if (exception != null) {" ) ; out . pushIndent ( ) ; out . printil ( "response.setStatus((Integer)request.getAttribute(\"javax.servlet.error.status_code\"));" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; } out . printil ( "ServletContext application = null;" ) ; out . printil ( "ServletConfig config = null;" ) ; out . printil ( "JspWriter out = null;" ) ; out . printil ( "Object page = this;" ) ; out . printil ( "JspWriter _jspx_out = null;" ) ; out . printil ( "PageContext _jspx_page_context = null;" ) ; out . println ( ) ; out . printil ( "try {" ) ; out . pushIndent ( ) ; out . printin ( "response.setContentType(" ) ; out . print ( quote ( pageInfo . getContentType ( ) ) ) ; out . println ( ");" ) ; if ( ctxt . getOptions ( ) . isXpoweredBy ( ) ) { out . printil ( "response.setHeader(\"X-Powered-By\", \"" + Constants . JSP_NAME + "\");" ) ; } out . printil ( "pageContext = _jspxFactory.getPageContext(this, request, response," ) ; out . printin ( "\t\t\t" ) ; out . print ( quote ( pageInfo . getErrorPage ( ) ) ) ; out . print ( ", " + pageInfo . isSession ( ) ) ; out . print ( ", " + pageInfo . getBuffer ( ) ) ; out . print ( ", " + pageInfo . isAutoFlush ( ) ) ; out . println ( ");" ) ; out . printil ( "_jspx_page_context = pageContext;" ) ; out . printil ( "application = pageContext.getServletContext();" ) ; out . printil ( "config = pageContext.getServletConfig();" ) ; if ( pageInfo . isSession ( ) ) out . printil ( "session = pageContext.getSession();" ) ; out . printil ( "out = pageContext.getOut();" ) ; out . printil ( "_jspx_out = out;" ) ; out . printil ( "_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute(\"com.sun.appserv.jsp.resource.injector\");" ) ; out . println ( ) ; }


Input:
Generates an XML Prolog which includes an XML declaration and an XML doctype declaration . [CODESPLIT] private void generateXmlProlog ( Node . Nodes page ) { /*
         * An XML declaration is generated under the following conditions:
         *
         * - 'omit-xml-declaration' attribute of <jsp:output> action is set to
         *   "no" or "false"
         * - JSP document without a <jsp:root>
         */ String omitXmlDecl = pageInfo . getOmitXmlDecl ( ) ; if ( ( omitXmlDecl != null && ! JspUtil . booleanValue ( omitXmlDecl ) ) || ( omitXmlDecl == null && page . getRoot ( ) . isXmlSyntax ( ) && ! pageInfo . hasJspRoot ( ) && ! ctxt . isTagFile ( ) ) ) { String cType = pageInfo . getContentType ( ) ; String charSet = cType . substring ( cType . indexOf ( "charset=" ) + 8 ) ; out . printil ( "out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"" + charSet + "\\\"?>\\n\");" ) ; } /*
         * Output a DOCTYPE declaration if the doctype-root-element appears.
         * If doctype-public appears:
         *     <!DOCTYPE name PUBLIC "doctypePublic" "doctypeSystem">
         * else
         *     <!DOCTYPE name SYSTEM "doctypeSystem" >
         */ String doctypeName = pageInfo . getDoctypeName ( ) ; if ( doctypeName != null ) { String doctypePublic = pageInfo . getDoctypePublic ( ) ; String doctypeSystem = pageInfo . getDoctypeSystem ( ) ; out . printin ( "out.write(\"<!DOCTYPE " ) ; out . print ( doctypeName ) ; if ( doctypePublic == null ) { out . print ( " SYSTEM \\\"" ) ; } else { out . print ( " PUBLIC \\\"" ) ; out . print ( doctypePublic ) ; out . print ( "\\\" \\\"" ) ; } out . print ( doctypeSystem ) ; out . println ( "\\\">\\n\");" ) ; } }


Input: / * Generates the constructor . ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void generateConstructor ( String className ) { out . printil ( "public " + className + "() {" ) ; out . printil ( "}" ) ; out . println ( ) ; }


Input: Common part of postamble shared by both servlets and tag files . [CODESPLIT] private void genCommonPostamble ( ) { // Append any methods that were generated in the buffer. for ( int i = 0 ; i < methodsBuffered . size ( ) ; i ++ ) { GenBuffer methodBuffer = methodsBuffered . get ( i ) ; methodBuffer . adjustJavaLines ( out . getJavaLine ( ) - 1 ) ; out . printMultiLn ( methodBuffer . toString ( ) ) ; } // Append the helper class if ( fragmentHelperClass . isUsed ( ) ) { fragmentHelperClass . generatePostamble ( ) ; fragmentHelperClass . adjustJavaLines ( out . getJavaLine ( ) - 1 ) ; out . printMultiLn ( fragmentHelperClass . toString ( ) ) ; } // Append char array declarations if ( arrayBuffer != null ) { out . printMultiLn ( arrayBuffer . toString ( ) ) ; } // Close the class definition out . popIndent ( ) ; out . printil ( "}" ) ; }


Input: Generates the ending part of the static portion of the servlet . [CODESPLIT] private void generatePostamble ( Node . Nodes page ) { out . popIndent ( ) ; out . printil ( "} catch (Throwable t) {" ) ; out . pushIndent ( ) ; out . printil ( "if (!(t instanceof SkipPageException)){" ) ; out . pushIndent ( ) ; out . printil ( "out = _jspx_out;" ) ; out . printil ( "if (out != null && out.getBufferSize() != 0)" ) ; out . pushIndent ( ) ; out . printil ( "out.clearBuffer();" ) ; out . popIndent ( ) ; out . printil ( "if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);" ) ; out . printil ( "else throw new ServletException(t);" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . popIndent ( ) ; out . printil ( "} finally {" ) ; out . pushIndent ( ) ; out . printil ( "_jspxFactory.releasePageContext(_jspx_page_context);" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; // Close the service method out . popIndent ( ) ; out . printil ( "}" ) ; // Generated methods, helper classes, etc. genCommonPostamble ( ) ; }


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


Input:
/ * Generates tag handler preamble . [CODESPLIT] private void generateTagHandlerPreamble ( JasperTagInfo tagInfo , Node . Nodes tag ) throws JasperException { // Generate package declaration String className = tagInfo . getTagClassName ( ) ; int lastIndex = className . lastIndexOf ( ' ' ) ; if ( lastIndex != - 1 ) { String pkgName = className . substring ( 0 , lastIndex ) ; genPreamblePackage ( pkgName ) ; className = className . substring ( lastIndex + 1 ) ; } // Generate imports genPreambleImports ( ) ; // Generate class declaration out . printin ( "public final class " ) ; out . println ( className ) ; out . printil ( "    extends javax.servlet.jsp.tagext.SimpleTagSupport" ) ; out . printin ( "    implements org.apache.jasper.runtime.JspSourceDependent" ) ; if ( tagInfo . hasDynamicAttributes ( ) ) { out . println ( "," ) ; out . printin ( "               javax.servlet.jsp.tagext.DynamicAttributes" ) ; } out . println ( " {" ) ; out . println ( ) ; out . pushIndent ( ) ; /*
         * Class body begins here
         */ generateDeclarations ( tag ) ; // Static initializations here genPreambleStaticInitializers ( ) ; out . printil ( "private JspContext jspContext;" ) ; // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out . printil ( "private java.io.Writer _jspx_sout;" ) ; // Class variable declarations genPreambleClassVariableDeclarations ( tagInfo . getTagName ( ) ) ; generateSetJspContext ( tagInfo ) ; // Tag-handler specific declarations generateTagHandlerAttributes ( tagInfo ) ; if ( tagInfo . hasDynamicAttributes ( ) ) generateSetDynamicAttribute ( ) ; // Methods here genPreambleMethods ( ) ; // Now the doTag() method out . printil ( "public void doTag() throws JspException, java.io.IOException {" ) ; if ( ctxt . isPrototypeMode ( ) ) { out . printil ( "}" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; return ; } out . pushIndent ( ) ; /*
         * According to the spec, 'pageContext' must not be made available as
         * an implicit object in tag files.
         * Declare _jspx_page_context, so we can share the code generator with
         * JSPs.
         */ out . printil ( "PageContext _jspx_page_context = (PageContext)jspContext;" ) ; // Declare implicit objects.   out . printil ( "HttpServletRequest request = " + "(HttpServletRequest) _jspx_page_context.getRequest();" ) ; out . printil ( "HttpServletResponse response = " + "(HttpServletResponse) _jspx_page_context.getResponse();" ) ; out . printil ( "HttpSession session = _jspx_page_context.getSession();" ) ; out . printil ( "ServletContext application = _jspx_page_context.getServletContext();" ) ; out . printil ( "ServletConfig config = _jspx_page_context.getServletConfig();" ) ; out . printil ( "JspWriter out = jspContext.getOut();" ) ; if ( isPoolingEnabled && ! tagHandlerPoolNames . isEmpty ( ) ) { out . printil ( "_jspInit(config);" ) ; } generatePageScopedVariables ( tagInfo ) ; out . println ( ) ; out . printil ( "try {" ) ; out . pushIndent ( ) ; }


Input: Generates declarations for tag handler attributes and defines the getter and setter methods for each . [CODESPLIT] private void generateTagHandlerAttributes ( TagInfo tagInfo ) throws JasperException { if ( tagInfo . hasDynamicAttributes ( ) ) { out . printil ( "private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();" ) ; } // Declare attributes TagAttributeInfo [ ] attrInfos = tagInfo . getAttributes ( ) ; for ( int i = 0 ; i < attrInfos . length ; i ++ ) { out . printin ( "private " ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( "javax.servlet.jsp.tagext.JspFragment " ) ; } else { out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( " " ) ; } out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( ";" ) ; } out . println ( ) ; // Define attribute getter and setter methods for ( int i = 0 ; i < attrInfos . length ; i ++ ) { // getter method out . printin ( "public " ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( "javax.servlet.jsp.tagext.JspFragment " ) ; } else { out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( " " ) ; } out . print ( toGetterMethod ( attrInfos [ i ] . getName ( ) ) ) ; out . println ( " {" ) ; out . pushIndent ( ) ; out . printin ( "return this." ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( ";" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; // setter method out . printin ( "public void " ) ; out . print ( toSetterMethodName ( attrInfos [ i ] . getName ( ) ) ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( "(javax.servlet.jsp.tagext.JspFragment " ) ; } else { out . print ( "(" ) ; out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( " " ) ; } out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( ") {" ) ; out . pushIndent ( ) ; out . printin ( "this." ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . print ( " = " ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( ";" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; } }


Input: / * Generate setter for JspContext so we can create a wrapper and store both the original and the wrapper . We need the wrapper to mask the page context from the tag file and simulate a fresh page context . We need the original to do things like sync AT_BEGIN and AT_END scripting variables . [CODESPLIT] private void generateSetJspContext ( TagInfo tagInfo ) { boolean nestedSeen = false ; boolean atBeginSeen = false ; boolean atEndSeen = false ; // Determine if there are any aliases boolean aliasSeen = false ; TagVariableInfo [ ] tagVars = tagInfo . getTagVariableInfos ( ) ; for ( int i = 0 ; i < tagVars . length ; i ++ ) { if ( tagVars [ i ] . getNameFromAttribute ( ) != null && tagVars [ i ] . getNameGiven ( ) != null ) { aliasSeen = true ; break ; } } if ( aliasSeen ) { out . printil ( "public void setJspContext(JspContext ctx, java.util.Map aliasMap) {" ) ; } else { out . printil ( "public void setJspContext(JspContext ctx) {" ) ; } out . pushIndent ( ) ; out . printil ( "super.setJspContext(ctx);" ) ; out . printil ( "java.util.ArrayList<String> _jspx_nested = null;" ) ; out . printil ( "java.util.ArrayList<String> _jspx_at_begin = null;" ) ; out . printil ( "java.util.ArrayList<String> _jspx_at_end = null;" ) ; for ( int i = 0 ; i < tagVars . length ; i ++ ) { switch ( tagVars [ i ] . getScope ( ) ) { case VariableInfo . NESTED : if ( ! nestedSeen ) { out . printil ( "_jspx_nested = new java.util.ArrayList<String>();" ) ; nestedSeen = true ; } out . printin ( "_jspx_nested.add(" ) ; break ; case VariableInfo . AT_BEGIN : if ( ! atBeginSeen ) { out . printil ( "_jspx_at_begin = new java.util.ArrayList<String>();" ) ; atBeginSeen = true ; } out . printin ( "_jspx_at_begin.add(" ) ; break ; case VariableInfo . AT_END : if ( ! atEndSeen ) { out . printil ( "_jspx_at_end = new java.util.ArrayList<String>();" ) ; atEndSeen = true ; } out . printin ( "_jspx_at_end.add(" ) ; break ; } // switch out . print ( quote ( tagVars [ i ] . getNameGiven ( ) ) ) ; out . println ( ");" ) ; } if ( aliasSeen ) { out . printil ( "this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);" ) ; } else { out . printil ( "this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);" ) ; } out . popIndent ( ) ; out . printil ( "}" ) ; out . println ( ) ; out . printil ( "public JspContext getJspContext() {" ) ; out . pushIndent ( ) ; out . printil ( "return this.jspContext;" ) ; out . popIndent ( ) ; out . printil ( "}" ) ; }


Input:
/ * Generates implementation of javax . servlet . jsp . tagext . DynamicAttributes . setDynamicAttribute () method which saves each dynamic attribute that is passed in so that a scoped variable can later be created for it . [CODESPLIT] public void generateSetDynamicAttribute ( ) { out . printil ( "public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {" ) ; out . pushIndent ( ) ; /*
         * According to the spec, only dynamic attributes with no uri are to
         * be present in the Map; all other dynamic attributes are ignored.
         */ out . printil ( "if (uri == null)" ) ; out . pushIndent ( ) ; out . printil ( "_jspx_dynamic_attrs.put(localName, value);" ) ; out . popIndent ( ) ; out . popIndent ( ) ; out . printil ( "}" ) ; }


Input: / * Creates a page - scoped variable for each declared tag attribute . Also if the tag accepts dynamic attributes a page - scoped variable is made available for each dynamic attribute that was passed in . [CODESPLIT] private void generatePageScopedVariables ( JasperTagInfo tagInfo ) { // "normal" attributes TagAttributeInfo [ ] attrInfos = tagInfo . getAttributes ( ) ; for ( int i = 0 ; i < attrInfos . length ; i ++ ) { String attrName = attrInfos [ i ] . getName ( ) ; out . printil ( "if( " + toGetterMethod ( attrName ) + " != null ) {" ) ; out . pushIndent ( ) ; out . printin ( "_jspx_page_context.setAttribute(" ) ; out . print ( quote ( attrName ) ) ; out . print ( ", " ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( ");" ) ; if ( attrInfos [ i ] . isDeferredValue ( ) ) { // If the attribute is a deferred value, also set it to an EL // variable of the same name. out . printin ( "org.apache.jasper.runtime.PageContextImpl.setValueVariable(" ) ; out . print ( "_jspx_page_context, " ) ; out . print ( quote ( attrName ) ) ; out . print ( ", " ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( ");" ) ; } if ( attrInfos [ i ] . isDeferredMethod ( ) ) { // If the attribute is a deferred method, set a wrapped // ValueExpression to an EL variable of the same name. out . printin ( "org.apache.jasper.runtime.PageContextImpl.setMethodVariable(" ) ; out . print ( "_jspx_page_context, " ) ; out . print ( quote ( attrName ) ) ; out . print ( ", " ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( ");" ) ; } out . popIndent ( ) ; out . println ( "}" ) ; } // Expose the Map containing dynamic attributes as a page-scoped var if ( tagInfo . hasDynamicAttributes ( ) ) { out . printin ( "_jspx_page_context.setAttribute(\"" ) ; out . print ( tagInfo . getDynamicAttributesMapName ( ) ) ; out . print ( "\", _jspx_dynamic_attrs);" ) ; } }


Input: / * Generates the getter method for the given attribute name . [CODESPLIT] private String toGetterMethod ( String attrName ) { char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return "get" + new String ( attrChars ) + "()" ; }


Input: / * Generates the setter method name for the given attribute name . [CODESPLIT] private String toSetterMethodName ( String attrName ) { char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return "set" + new String ( attrChars ) ; }


Input: Read in a map of properties [CODESPLIT] private Map < MetaKey , String > readProperties ( final InputStream stream ) throws IOException { try { // wrap the input stream since we don't want the XML parser to close the stream while parsing final Document doc = this . xmlToolsFactory . newDocumentBuilder ( ) . parse ( new FilterInputStream ( stream ) { @ Override public void close ( ) { // do nothing } } ) ; final Element root = doc . getDocumentElement ( ) ; if ( ! "properties" . equals ( root . getNodeName ( ) ) ) { throw new IllegalStateException ( String . format ( "Root element must be of type '%s'" , "properties" ) ) ; } final Map < MetaKey , String > result = new HashMap <> ( ) ; for ( final Element ele : XmlHelper . iterElement ( root , "property" ) ) { final String namespace = ele . getAttribute ( "namespace" ) ; final String key = ele . getAttribute ( "key" ) ; final String value = ele . getTextContent ( ) ; if ( namespace . isEmpty ( ) || key . isEmpty ( ) ) { continue ; } result . put ( new MetaKey ( namespace , key ) , value ) ; } return result ; } catch ( final Exception e ) { throw new IOException ( "Failed to read properties" , e ) ; } }


Input: Export the content of a channel [CODESPLIT] private void exportChannel ( final By by , final OutputStream stream ) throws IOException { final ZipOutputStream zos = new ZipOutputStream ( stream ) ; initExportFile ( zos ) ; this . channelService . accessRun ( by , ReadableChannel . class , channel -> { putDataEntry ( zos , "names" , makeNames ( channel . getId ( ) ) ) ; putDataEntry ( zos , "description" , channel . getId ( ) . getDescription ( ) ) ; putDirEntry ( zos , "artifacts" ) ; putProperties ( zos , "properties.xml" , channel . getContext ( ) . getProvidedMetaData ( ) ) ; putAspects ( zos , channel . getContext ( ) . getAspectStates ( ) . keySet ( ) ) ; // the first run receives all artifacts and filters for the root elements putArtifacts ( zos , "artifacts/" , channel , channel . getArtifacts ( ) , true ) ; } ) ; this . channelService . accessRun ( by , TriggeredChannel . class , channel -> { putTriggers ( zos , channel ) ; } ) ; zos . finish ( ) ; // don't close stream, since there might be other channels following }


Input: Make an array of header entries with given charset <p > <strong > Note : < / strong > Further updates on this instance will not update the returned array . This is actually a copy of the current state . < / p > [CODESPLIT] public HeaderEntry [ ] makeEntries ( Charset charset ) { if ( charset == null ) { throw new IllegalArgumentException ( "'charset' cannot be null" ) ; } Header . charset = charset ; return this . entries . entrySet ( ) . stream ( ) . map ( Header :: makeEntry ) . toArray ( num -> new HeaderEntry [ num ] ) ; }


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


Input: Gets the next available tag handler from this tag handler pool instantiating one if this tag handler pool is empty . [CODESPLIT] public < T extends JspTag > JspTag get ( Class < T > handlerClass ) throws JspException { synchronized ( this ) { if ( current >= 0 ) { return handlers [ current -- ] ; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. JspTag tagHandler = null ; try { if ( resourceInjector != null ) { tagHandler = resourceInjector . createTagHandlerInstance ( handlerClass ) ; } else { tagHandler = handlerClass . newInstance ( ) ; } } catch ( Exception e ) { throw new JspException ( e . getMessage ( ) , e ) ; } return tagHandler ; }


Input: Adds the given tag handler to this tag handler pool unless this tag handler pool has already reached its capacity in which case the tag handler s release () method is called . [CODESPLIT] public void reuse ( JspTag handler ) { synchronized ( this ) { if ( current < ( handlers . length - 1 ) ) { handlers [ ++ current ] = handler ; return ; } } // There is no need for other threads to wait for us to release if ( handler instanceof Tag ) { ( ( Tag ) handler ) . release ( ) ; } if ( resourceInjector != null ) { resourceInjector . preDestroy ( handler ) ; } }


Input: Calls the release () method of all available tag handlers in this tag handler pool . [CODESPLIT] public synchronized void release ( ) { for ( int i = current ; i >= 0 ; i -- ) { if ( handlers [ i ] instanceof Tag ) { ( ( Tag ) handlers [ i ] ) . release ( ) ; } if ( resourceInjector != null ) { resourceInjector . preDestroy ( handlers [ i ] ) ; } } }


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


Input: Parse an EL expression string $ { ... } or # { ... } [CODESPLIT] private ELNode . Nodes parseEL ( ) { StringBuilder buf = new StringBuilder ( ) ; ELexpr = new ELNode . Nodes ( ) ; while ( hasNext ( ) ) { nextToken ( ) ; if ( curToken instanceof Char ) { if ( curToken . toChar ( ) == ' ' ) { break ; } buf . append ( curToken . toChar ( ) ) ; } else { // Output whatever is in buffer if ( buf . length ( ) > 0 ) { ELexpr . add ( new ELNode . ELText ( buf . toString ( ) ) ) ; } if ( ! parseFunction ( ) ) { ELexpr . add ( new ELNode . ELText ( curToken . toString ( ) ) ) ; } } } if ( buf . length ( ) > 0 ) { ELexpr . add ( new ELNode . ELText ( buf . toString ( ) ) ) ; } return ELexpr ; }


Input: Skip until an EL expression ( $ { or # { ) is reached allowing escape sequences \\ \ $ and \ # . [CODESPLIT] private String skipUntilEL ( ) { char prev = 0 ; StringBuilder buf = new StringBuilder ( ) ; while ( hasNextChar ( ) ) { char ch = nextChar ( ) ; if ( prev == ' ' ) { prev = 0 ; if ( ch == ' ' ) { buf . append ( ' ' ) ; if ( ! escapeBS ) prev = ' ' ; } else if ( ch == ' ' || ch == ' ' ) { buf . append ( ch ) ; } // else error! } else if ( prev == ' ' || prev == ' ' ) { if ( ch == ' ' ) { this . isDollarExpr = ( prev == ' ' ) ; prev = 0 ; break ; } buf . append ( prev ) ; if ( ch == ' ' || ch == ' ' || ch == ' ' ) { prev = ch ; } else { buf . append ( ch ) ; } } else if ( ch == ' ' || ch == ' ' || ch == ' ' ) { prev = ch ; } else { buf . append ( ch ) ; } } if ( prev != 0 ) { buf . append ( prev ) ; } return buf . toString ( ) ; }


Input: / * Parse a string in single or double quotes allowing for escape sequences \\ and ( \ or \ ) [CODESPLIT] private Token parseQuotedChars ( char quote ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( quote ) ; while ( hasNextChar ( ) ) { char ch = nextChar ( ) ; if ( ch == ' ' ) { ch = nextChar ( ) ; if ( ch == ' ' || ch == quote ) { buf . append ( ch ) ; } // else error! } else if ( ch == quote ) { buf . append ( ch ) ; break ; } else { buf . append ( ch ) ; } } return new QuotedString ( buf . toString ( ) ) ; }


Input: Select the property group that has more restrictive url - pattern . In case of tie select the first . [CODESPLIT] private JspPropertyGroup selectProperty ( JspPropertyGroup prev , JspPropertyGroup curr ) { if ( prev == null ) { return curr ; } if ( prev . getExtension ( ) == null ) { // exact match return prev ; } if ( curr . getExtension ( ) == null ) { // exact match return curr ; } String prevPath = prev . getPath ( ) ; String currPath = curr . getPath ( ) ; if ( prevPath == null && currPath == null ) { // Both specifies a *.ext, keep the first one return prev ; } if ( prevPath == null && currPath != null ) { return curr ; } if ( prevPath != null && currPath == null ) { return prev ; } if ( prevPath . length ( ) >= currPath . length ( ) ) { return prev ; } return curr ; }


Input: Find a property that best matches the supplied resource . [CODESPLIT] public JspProperty findJspProperty ( String uri ) throws JasperException { init ( ) ; // JSP Configuration settings do not apply to tag files	     if ( jspProperties == null || uri . endsWith ( ".tag" ) || uri . endsWith ( ".tagx" ) ) { return defaultJspProperty ; } String uriPath = null ; int index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriPath = uri . substring ( 0 , index + 1 ) ; } String uriExtension = null ; index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriExtension = uri . substring ( index + 1 ) ; } ArrayList < String > includePreludes = new ArrayList < String > ( ) ; ArrayList < String > includeCodas = new ArrayList < String > ( ) ; JspPropertyGroup isXmlMatch = null ; JspPropertyGroup elIgnoredMatch = null ; JspPropertyGroup scriptingInvalidMatch = null ; JspPropertyGroup trimSpacesMatch = null ; JspPropertyGroup poundAllowedMatch = null ; JspPropertyGroup pageEncodingMatch = null ; JspPropertyGroup defaultContentTypeMatch = null ; JspPropertyGroup bufferMatch = null ; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null ; for ( JspPropertyGroup jpg : jspProperties ) { JspProperty jp = jpg . getJspProperty ( ) ; // (arrays will be the same length) String extension = jpg . getExtension ( ) ; String path = jpg . getPath ( ) ; if ( extension == null ) { // exact match pattern: /a/foo.jsp if ( ! uri . equals ( path ) ) { // not matched; continue ; } } else { // Matching patterns *.ext or /p/* if ( path != null && uriPath != null && ! uriPath . startsWith ( path ) ) { // not matched continue ; } if ( ! extension . equals ( "*" ) && ! extension . equals ( uriExtension ) ) { // not matched continue ; } } // We have a match // Add include-preludes and include-codas if ( jp . getIncludePrelude ( ) != null ) { includePreludes . addAll ( jp . getIncludePrelude ( ) ) ; } if ( jp . getIncludeCoda ( ) != null ) { includeCodas . addAll ( jp . getIncludeCoda ( ) ) ; } // If there is a previous match for the same property, remember // the one that is more restrictive. if ( jp . isXml ( ) != null ) { isXmlMatch = selectProperty ( isXmlMatch , jpg ) ; } if ( jp . isELIgnored ( ) != null ) { elIgnoredMatch = selectProperty ( elIgnoredMatch , jpg ) ; } if ( jp . isScriptingInvalid ( ) != null ) { scriptingInvalidMatch = selectProperty ( scriptingInvalidMatch , jpg ) ; } if ( jp . getPageEncoding ( ) != null ) { pageEncodingMatch = selectProperty ( pageEncodingMatch , jpg ) ; } if ( jp . getTrimSpaces ( ) != null ) { trimSpacesMatch = selectProperty ( trimSpacesMatch , jpg ) ; } if ( jp . getPoundAllowed ( ) != null ) { poundAllowedMatch = selectProperty ( poundAllowedMatch , jpg ) ; } if ( jp . getDefaultContentType ( ) != null ) { defaultContentTypeMatch = selectProperty ( defaultContentTypeMatch , jpg ) ; } if ( jp . getBuffer ( ) != null ) { bufferMatch = selectProperty ( bufferMatch , jpg ) ; } if ( jp . errorOnUndeclaredNamespace ( ) != null ) { errorOnUndeclaredNamespaceMatch = selectProperty ( errorOnUndeclaredNamespaceMatch , jpg ) ; } } String isXml = defaultIsXml ; String isELIgnored = defaultIsELIgnored ; String isScriptingInvalid = defaultIsScriptingInvalid ; String trimSpaces = defaultTrimSpaces ; String poundAllowed = defaultPoundAllowed ; String pageEncoding = null ; String defaultContentType = null ; String buffer = null ; String errorOnUndeclaredNamespace = defaultErrorOnUndeclaredNamespace ; if ( isXmlMatch != null ) { isXml = isXmlMatch . getJspProperty ( ) . isXml ( ) ; } if ( elIgnoredMatch != null ) { isELIgnored = elIgnoredMatch . getJspProperty ( ) . isELIgnored ( ) ; } if ( scriptingInvalidMatch != null ) { isScriptingInvalid = scriptingInvalidMatch . getJspProperty ( ) . isScriptingInvalid ( ) ; } if ( trimSpacesMatch != null ) { trimSpaces = trimSpacesMatch . getJspProperty ( ) . getTrimSpaces ( ) ; } if ( poundAllowedMatch != null ) { poundAllowed = poundAllowedMatch . getJspProperty ( ) . getPoundAllowed ( ) ; } if ( pageEncodingMatch != null ) { pageEncoding = pageEncodingMatch . getJspProperty ( ) . getPageEncoding ( ) ; } if ( defaultContentTypeMatch != null ) { defaultContentType = defaultContentTypeMatch . getJspProperty ( ) . getDefaultContentType ( ) ; } if ( bufferMatch != null ) { buffer = bufferMatch . getJspProperty ( ) . getBuffer ( ) ; } if ( errorOnUndeclaredNamespaceMatch != null ) { errorOnUndeclaredNamespace = errorOnUndeclaredNamespaceMatch . getJspProperty ( ) . errorOnUndeclaredNamespace ( ) ; } return new JspProperty ( isXml , isELIgnored , isScriptingInvalid , trimSpaces , poundAllowed , pageEncoding , includePreludes , includeCodas , defaultContentType , buffer , errorOnUndeclaredNamespace ) ; }


Input: To find out if an uri matches an url pattern in jsp config . If so then the uri is a JSP page . This is used primarily for jspc . [CODESPLIT] public boolean isJspPage ( String uri ) throws JasperException { init ( ) ; if ( jspProperties == null ) { return false ; } String uriPath = null ; int index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriPath = uri . substring ( 0 , index + 1 ) ; } String uriExtension = null ; index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriExtension = uri . substring ( index + 1 ) ; } for ( JspPropertyGroup jpg : jspProperties ) { JspProperty jp = jpg . getJspProperty ( ) ; String extension = jpg . getExtension ( ) ; String path = jpg . getPath ( ) ; if ( extension == null ) { if ( uri . equals ( path ) ) { // There is an exact match return true ; } } else { if ( ( path == null || path . equals ( uriPath ) ) && ( extension . equals ( "*" ) || extension . equals ( uriExtension ) ) ) { // Matches *, *.ext, /p/*, or /p/*.ext return true ; } } } return false ; }


Input: Print a standard comment for echo outputed chunk . [CODESPLIT] public void printComment ( Mark start , Mark stop , char [ ] chars ) { if ( start != null && stop != null ) { println ( "// from=" + start ) ; println ( "//   to=" + stop ) ; } if ( chars != null ) for ( int i = 0 ; i < chars . length ; ) { printin ( ) ; print ( "// " ) ; while ( chars [ i ] != ' ' && i < chars . length ) writer . print ( chars [ i ++ ] ) ; } }


Input: Prints the current indention followed by the given string [CODESPLIT] public void printin ( String s ) { writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . print ( s ) ; }


Input: Prints the current indention and then the string and a \ n . [CODESPLIT] public void printil ( String s ) { javaLine ++ ; writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . println ( s ) ; }


Input: Prints the given string . [CODESPLIT] public void printMultiLn ( String s ) { int index = 0 ; // look for hidden newlines inside strings while ( ( index = s . indexOf ( ' ' , index ) ) > - 1 ) { javaLine ++ ; index ++ ; } writer . print ( s ) ; }


Input: Checks if the token is a runtime expression . In standard JSP syntax a runtime expression starts with <% and ends with % > . When the JSP document is in XML syntax a runtime expression starts with % = and ends with % . [CODESPLIT] public static boolean isExpression ( String token , boolean isXml ) { String openExpr ; String closeExpr ; if ( isXml ) { openExpr = OPEN_EXPR_XML ; closeExpr = CLOSE_EXPR_XML ; } else { openExpr = OPEN_EXPR ; closeExpr = CLOSE_EXPR ; } if ( token . startsWith ( openExpr ) && token . endsWith ( closeExpr ) ) { return true ; } else { return false ; } }


Input: Takes a potential expression and converts it into XML form [CODESPLIT] public static String getExprInXml ( String expression ) { String returnString ; int length = expression . length ( ) ; if ( expression . startsWith ( OPEN_EXPR ) && expression . endsWith ( CLOSE_EXPR ) ) { returnString = expression . substring ( 1 , length - 1 ) ; } else { returnString = expression ; } return escapeXml ( returnString ) ; }


Input: Checks to see if the given scope is valid . [CODESPLIT] public static void checkScope ( String scope , Node n , ErrorDispatcher err ) throws JasperException { if ( scope != null && ! scope . equals ( "page" ) && ! scope . equals ( "request" ) && ! scope . equals ( "session" ) && ! scope . equals ( "application" ) ) { err . jspError ( n , "jsp.error.invalid.scope" , scope ) ; } }


Input:
Checks if all mandatory attributes are present and if all attributes present have valid names . Checks attributes specified as XML - style attributes as well as attributes specified using the jsp : attribute standard action . [CODESPLIT] public static void checkAttributes ( String typeOfTag , Node n , ValidAttribute [ ] validAttributes , ErrorDispatcher err ) throws JasperException { Attributes attrs = n . getAttributes ( ) ; Mark start = n . getStart ( ) ; boolean valid = true ; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = ( attrs == null ) ? 0 : attrs . getLength ( ) ; ArrayList < String > temp = new ArrayList < String > ( tempLength ) ; for ( int i = 0 ; i < tempLength ; i ++ ) { String qName = attrs . getQName ( i ) ; if ( ( ! qName . equals ( "xmlns" ) ) && ( ! qName . startsWith ( "xmlns:" ) ) ) temp . add ( qName ) ; } // Add names of attributes specified using jsp:attribute Node . Nodes tagBody = n . getBody ( ) ; if ( tagBody != null ) { int numSubElements = tagBody . size ( ) ; for ( int i = 0 ; i < numSubElements ; i ++ ) { Node node = tagBody . getNode ( i ) ; if ( node instanceof Node . NamedAttribute ) { String attrName = node . getAttributeValue ( "name" ) ; temp . add ( attrName ) ; // Check if this value appear in the attribute of the node if ( n . getAttributeValue ( attrName ) != null ) { err . jspError ( n , "jsp.error.duplicate.name.jspattribute" , attrName ) ; } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break ; } } } /*
	 * First check to see if all the mandatory attributes are present.
	 * If so only then proceed to see if the other attributes are valid
	 * for the particular tag.
	 */ String missingAttribute = null ; for ( int i = 0 ; i < validAttributes . length ; i ++ ) { int attrPos ; if ( validAttributes [ i ] . mandatory ) { attrPos = temp . indexOf ( validAttributes [ i ] . name ) ; if ( attrPos != - 1 ) { temp . remove ( attrPos ) ; valid = true ; } else { valid = false ; missingAttribute = validAttributes [ i ] . name ; break ; } } } // If mandatory attribute is missing then the exception is thrown if ( ! valid ) err . jspError ( start , "jsp.error.mandatory.attribute" , typeOfTag , missingAttribute ) ; // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp . size ( ) ; if ( attrLeftLength == 0 ) return ; // Now check to see if the rest of the attributes are valid too. String attribute = null ; for ( int j = 0 ; j < attrLeftLength ; j ++ ) { valid = false ; attribute = temp . get ( j ) ; for ( int i = 0 ; i < validAttributes . length ; i ++ ) { if ( attribute . equals ( validAttributes [ i ] . name ) ) { valid = true ; break ; } } if ( ! valid ) err . jspError ( start , "jsp.error.invalid.attribute" , typeOfTag , attribute ) ; } // XXX *could* move EL-syntax validation here... (sb) }


Input: Escape the 5 entities defined by XML . [CODESPLIT] public static String escapeXml ( String s ) { if ( s == null ) return null ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' ) { sb . append ( "<" ) ; } else if ( c == ' ' ) { sb . append ( ">" ) ; } else if ( c == ' ' ) { sb . append ( "'" ) ; } else if ( c == ' ' ) { sb . append ( "&" ) ; } else if ( c == ' ' ) { sb . append ( """ ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }


Input: Convert a String value to boolean . Besides the standard conversions done by Boolean . valueOf ( s ) . booleanValue () the value yes ( ignore case ) is also converted to true . If s is null then false is returned . [CODESPLIT] public static boolean booleanValue ( String s ) { boolean b = false ; if ( s != null ) { if ( s . equalsIgnoreCase ( "yes" ) ) { b = true ; } else { b = Boolean . valueOf ( s ) . booleanValue ( ) ; } } return b ; }


Input: Returns the <tt > Class< / tt > object associated with the class or interface with the given string name . [CODESPLIT] public static Class < ? > toClass ( String type , ClassLoader loader ) throws ClassNotFoundException { Class < ? > c = null ; int i0 = type . indexOf ( ' ' ) ; int dims = 0 ; if ( i0 > 0 ) { // This is an array.  Count the dimensions for ( int i = 0 ; i < type . length ( ) ; i ++ ) { if ( type . charAt ( i ) == ' ' ) dims ++ ; } type = type . substring ( 0 , i0 ) ; } if ( "boolean" . equals ( type ) ) c = boolean . class ; else if ( "char" . equals ( type ) ) c = char . class ; else if ( "byte" . equals ( type ) ) c = byte . class ; else if ( "short" . equals ( type ) ) c = short . class ; else if ( "int" . equals ( type ) ) c = int . class ; else if ( "long" . equals ( type ) ) c = long . class ; else if ( "float" . equals ( type ) ) c = float . class ; else if ( "double" . equals ( type ) ) c = double . class ; else if ( type . indexOf ( ' ' ) < 0 ) c = loader . loadClass ( type ) ; if ( dims == 0 ) return c ; if ( dims == 1 ) return java . lang . reflect . Array . newInstance ( c , 1 ) . getClass ( ) ; // Array of more than i dimension return java . lang . reflect . Array . newInstance ( c , new int [ dims ] ) . getClass ( ) ; }


Input:
Produces a String representing a call to the EL interpreter . [CODESPLIT] public static String interpreterCall ( boolean isTagFile , String expression , Class expectedType , String fnmapvar , String expectedDeferredType , String expectedReturnType , String [ ] expectedParamTypes ) { /*
         * Determine which context object to use.
         */ String jspCtxt = null ; if ( isTagFile ) jspCtxt = "this.getJspContext()" ; else jspCtxt = "_jspx_page_context" ; if ( expectedType == javax . el . ValueExpression . class ) { if ( expectedDeferredType == null ) { expectedDeferredType = "java.lang.Object" ; } return "org.apache.jasper.runtime.PageContextImpl.getValueExpression" + "(" + Generator . quote ( expression ) + ", " + "(PageContext)" + jspCtxt + ", " + expectedDeferredType + ".class, " + fnmapvar + ")" ; } if ( expectedType == javax . el . MethodExpression . class ) { if ( expectedReturnType == null ) { expectedReturnType = "Void" ; } StringBuilder params = new StringBuilder ( ) ; if ( expectedParamTypes != null ) { for ( int i = 0 ; i < expectedParamTypes . length ; i ++ ) { if ( i > 0 ) { params . append ( ", " ) ; } params . append ( expectedParamTypes [ i ] + ".class" ) ; } } return "org.apache.jasper.runtime.PageContextImpl.getMethodExpression" + "(" + Generator . quote ( expression ) + ", " + "(PageContext)" + jspCtxt + ", " + fnmapvar + ", " + expectedReturnType + ".class, " + "new Class[] {" + params . toString ( ) + "})" ; } /*
         * Determine whether to use the expected type's textual name
	 * or, if it's a primitive, the name of its correspondent boxed
	 * type.
         */ String targetType = expectedType . getName ( ) ; String primitiveConverterMethod = null ; if ( expectedType . isPrimitive ( ) ) { if ( expectedType . equals ( Boolean . TYPE ) ) { targetType = Boolean . class . getName ( ) ; primitiveConverterMethod = "booleanValue" ; } else if ( expectedType . equals ( Byte . TYPE ) ) { targetType = Byte . class . getName ( ) ; primitiveConverterMethod = "byteValue" ; } else if ( expectedType . equals ( Character . TYPE ) ) { targetType = Character . class . getName ( ) ; primitiveConverterMethod = "charValue" ; } else if ( expectedType . equals ( Short . TYPE ) ) { targetType = Short . class . getName ( ) ; primitiveConverterMethod = "shortValue" ; } else if ( expectedType . equals ( Integer . TYPE ) ) { targetType = Integer . class . getName ( ) ; primitiveConverterMethod = "intValue" ; } else if ( expectedType . equals ( Long . TYPE ) ) { targetType = Long . class . getName ( ) ; primitiveConverterMethod = "longValue" ; } else if ( expectedType . equals ( Float . TYPE ) ) { targetType = Float . class . getName ( ) ; primitiveConverterMethod = "floatValue" ; } else if ( expectedType . equals ( Double . TYPE ) ) { targetType = Double . class . getName ( ) ; primitiveConverterMethod = "doubleValue" ; } } targetType = toJavaSourceType ( targetType ) ; StringBuilder call = new StringBuilder ( "(" + targetType + ") " + "org.apache.jasper.runtime.PageContextImpl.evaluateExpression" + "(" + Generator . quote ( expression ) + ", " + targetType + ".class, " + "(PageContext)" + jspCtxt + ", " + fnmapvar + ")" ) ; /*
         * Add the primitive converter method if we need to.
         */ if ( primitiveConverterMethod != null ) { call . insert ( 0 , "(" ) ; call . append ( ")." + primitiveConverterMethod + "()" ) ; } return call . toString ( ) ; }


Input: Validates the syntax of all EL expressions within the given string . [CODESPLIT] public static void validateExpressions ( Mark where , String expressions , FunctionMapper functionMapper , ErrorDispatcher err ) throws JasperException { try { ELContextImpl elContext = new ELContextImpl ( null ) ; elContext . setFunctionMapper ( functionMapper ) ; getExpressionFactory ( ) . createValueExpression ( elContext , expressions , Object . class ) ; } catch ( ELException e ) { err . jspError ( where , "jsp.error.invalid.expression" , expressions , e . toString ( ) ) ; } }


Input: Gets the fully - qualified class name of the tag handler corresponding to the given tag file path . [CODESPLIT] public static String getTagHandlerClassName ( String path , ErrorDispatcher err ) throws JasperException { String className = null ; int begin = 0 ; int index ; index = path . lastIndexOf ( ".tag" ) ; if ( index == - 1 ) { err . jspError ( "jsp.error.tagfile.badSuffix" , path ) ; } //It's tempting to remove the ".tag" suffix here, but we can't. //If we remove it, the fully-qualified class name of this tag //could conflict with the package name of other tags. //For instance, the tag file //    /WEB-INF/tags/foo.tag //would have fully-qualified class name //    org.apache.jsp.tag.web.foo //which would conflict with the package name of the tag file //    /WEB-INF/tags/foo/bar.tag index = path . indexOf ( WEB_INF_TAGS ) ; if ( index != - 1 ) { className = "org.apache.jsp.tag.web." ; begin = index + WEB_INF_TAGS . length ( ) ; } else { index = path . indexOf ( META_INF_TAGS ) ; if ( index != - 1 ) { className = "org.apache.jsp.tag.meta." ; begin = index + META_INF_TAGS . length ( ) ; } else { err . jspError ( "jsp.error.tagfile.illegalPath" , path ) ; } } className += makeJavaPackage ( path . substring ( begin ) ) ; return className ; }


Input: Converts the given path to a Java package or fully - qualified class name [CODESPLIT] public static final String makeJavaPackage ( String path ) { String classNameComponents [ ] = split ( path , "/" ) ; StringBuilder legalClassNames = new StringBuilder ( ) ; for ( int i = 0 ; i < classNameComponents . length ; i ++ ) { legalClassNames . append ( makeJavaIdentifier ( classNameComponents [ i ] ) ) ; if ( i < classNameComponents . length - 1 ) { legalClassNames . append ( ' ' ) ; } } return legalClassNames . toString ( ) ; }


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


Input: Converts the given identifier to a legal Java identifier [CODESPLIT] public static final String makeJavaIdentifier ( String identifier ) { StringBuilder modifiedIdentifier = new StringBuilder ( identifier . length ( ) ) ; if ( ! Character . isJavaIdentifierStart ( identifier . charAt ( 0 ) ) ) { modifiedIdentifier . append ( ' ' ) ; } for ( int i = 0 ; i < identifier . length ( ) ; i ++ ) { char ch = identifier . charAt ( i ) ; if ( Character . isJavaIdentifierPart ( ch ) && ch != ' ' ) { modifiedIdentifier . append ( ch ) ; } else if ( ch == ' ' ) { modifiedIdentifier . append ( ' ' ) ; } else { modifiedIdentifier . append ( mangleChar ( ch ) ) ; } } if ( isJavaKeyword ( modifiedIdentifier . toString ( ) ) ) { modifiedIdentifier . append ( ' ' ) ; } return modifiedIdentifier . toString ( ) ; }


Input: Mangle the specified character to create a legal Java class name . [CODESPLIT] public static final String mangleChar ( char ch ) { char [ ] result = new char [ 5 ] ; result [ 0 ] = ' ' ; result [ 1 ] = Character . forDigit ( ( ch >> 12 ) & 0xf , 16 ) ; result [ 2 ] = Character . forDigit ( ( ch >> 8 ) & 0xf , 16 ) ; result [ 3 ] = Character . forDigit ( ( ch >> 4 ) & 0xf , 16 ) ; result [ 4 ] = Character . forDigit ( ch & 0xf , 16 ) ; return new String ( result ) ; }


Input: Test whether the argument is a Java keyword [CODESPLIT] public static boolean isJavaKeyword ( String key ) { int i = 0 ; int j = javaKeywords . length ; while ( i < j ) { int k = ( i + j ) / 2 ; int result = javaKeywords [ k ] . compareTo ( key ) ; if ( result == 0 ) { return true ; } if ( result < 0 ) { i = k + 1 ; } else { j = k ; } } return false ; }


Input: Converts the given Xml name to a legal Java identifier . This is slightly more efficient than makeJavaIdentifier in that we only need to worry about . - and : in the string . We also assume that the resultant string is further concatenated with some prefix string so that we don t have to worry about it being a Java key word . [CODESPLIT] public static final String makeXmlJavaIdentifier ( String name ) { if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , "$1" ) ; if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , "$2" ) ; if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , "$3" ) ; return name ; }


Input: Compute the canonical name from a Class instance . Note that a simple replacment of $ with . of a binary name would not work as $ is a legal Java Identifier character . [CODESPLIT] public static String getCanonicalName ( Class c ) { String binaryName = c . getName ( ) ; c = c . getDeclaringClass ( ) ; if ( c == null ) { return binaryName ; } StringBuilder buf = new StringBuilder ( binaryName ) ; do { buf . setCharAt ( c . getName ( ) . length ( ) , ' ' ) ; c = c . getDeclaringClass ( ) ; } while ( c != null ) ; return buf . toString ( ) ; }


Input: Given a list of jar files their manifest attribute Class - path are scanned and jars specified there are added to the list . This is carried out recursively . Note : This is needed to work around the JDK bug 6725230 . [CODESPLIT] public static List < String > expandClassPath ( List < String > files ) { for ( int i = 0 ; i < files . size ( ) ; i ++ ) { String file = files . get ( i ) ; if ( ! file . endsWith ( ".jar" ) ) { continue ; } Manifest manifest = manifestMap . get ( file ) ; JarFile jarfile = null ; if ( manifest == null ) { try { jarfile = new JarFile ( file , false ) ; manifest = jarfile . getManifest ( ) ; if ( manifest == null ) { // mark jar file as known to contain no manifest manifestMap . put ( file , nullManifest ) ; continue ; } else if ( ! file . contains ( "/WEB-INF" ) ) { // Don't cache any jars bundled with the app. manifestMap . put ( file , manifest ) ; } } catch ( IOException ex ) { // Ignored continue ; } finally { try { if ( jarfile != null ) jarfile . close ( ) ; } catch ( IOException ex ) { // Ignored } } } else if ( manifest == nullManifest ) { continue ; } java . util . jar . Attributes attrs = manifest . getMainAttributes ( ) ; String cp = ( String ) attrs . getValue ( "Class-Path" ) ; if ( cp == null ) { continue ; } String [ ] paths = cp . split ( " " ) ; int lastIndex = file . lastIndexOf ( File . separatorChar ) ; String baseDir = "" ; if ( lastIndex > 0 ) { baseDir = file . substring ( 0 , lastIndex + 1 ) ; } for ( String path : paths ) { String p ; if ( path . startsWith ( File . separator ) ) { p = path ; } else { p = baseDir + path ; } if ( ! files . contains ( p ) ) { files . add ( p ) ; } } } return files ; }


Input: Create a random token <p > This method uses the internal instance of of a { @link SecureRandom } generator to create a new token . < / p > [CODESPLIT] public static String createToken ( final int length ) { final byte [ ] data = new byte [ length ] ; random . nextBytes ( data ) ; return Strings . hex ( data ) ; }


Input: Add property entry only of value is not null [CODESPLIT] private static void addProperty ( final Map < String , String > props , final String key , final String value ) { if ( value == null ) { return ; } props . put ( key , value ) ; }


Input: Write a list of units inside a { @code units } element [CODESPLIT] public static void writeXml ( final XMLStreamWriter xsw , final List < InstallableUnit > ius ) throws XMLStreamException { xsw . writeStartElement ( "units" ) ; xsw . writeAttribute ( "size" , Integer . toString ( ius . size ( ) ) ) ; for ( final InstallableUnit iu : ius ) { iu . writeXmlForUnit ( xsw ) ; } xsw . writeEndElement ( ) ; }


Input: Write the unit as XML fragment [CODESPLIT] public void writeXmlForUnit ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw . writeStartElement ( "unit" ) ; xsw . writeAttribute ( "id" , this . id ) ; xsw . writeAttribute ( "version" , "" + this . version ) ; xsw . writeAttribute ( "singleton" , Boolean . toString ( this . singleton ) ) ; { xsw . writeEmptyElement ( "update" ) ; xsw . writeAttribute ( "id" , this . id ) ; xsw . writeAttribute ( "range" , "[0.0.0," + this . version + ")" ) ; xsw . writeAttribute ( "severity" , "0" ) ; } { xsw . writeStartElement ( "properties" ) ; xsw . writeAttribute ( "size" , Integer . toString ( this . properties . size ( ) ) ) ; for ( final Map . Entry < String , String > entry : this . properties . entrySet ( ) ) { xsw . writeStartElement ( "property" ) ; xsw . writeAttribute ( "name" , entry . getKey ( ) ) ; if ( entry . getValue ( ) != null ) { xsw . writeAttribute ( "value" , entry . getValue ( ) ) ; } xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // properties } { xsw . writeStartElement ( "provides" ) ; xsw . writeAttribute ( "size" , Integer . toString ( this . provides . size ( ) ) ) ; for ( final Entry < String > entry : this . provides ) { xsw . writeStartElement ( "provided" ) ; xsw . writeAttribute ( "namespace" , entry . getNamespace ( ) ) ; xsw . writeAttribute ( "name" , entry . getKey ( ) ) ; xsw . writeAttribute ( "version" , entry . getValue ( ) ) ; xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // provides } { xsw . writeStartElement ( "requires" ) ; xsw . writeAttribute ( "size" , Integer . toString ( this . requires . size ( ) ) ) ; for ( final Entry < Requirement > entry : this . requires ) { xsw . writeStartElement ( "required" ) ; xsw . writeAttribute ( "namespace" , entry . getNamespace ( ) ) ; xsw . writeAttribute ( "name" , entry . getKey ( ) ) ; xsw . writeAttribute ( "range" , makeString ( entry . getValue ( ) . getRange ( ) ) ) ; if ( entry . getValue ( ) . isOptional ( ) ) { xsw . writeAttribute ( "optional" , "true" ) ; } if ( entry . getValue ( ) . getGreedy ( ) != null ) { xsw . writeAttribute ( "greedy" , "" + entry . getValue ( ) . getGreedy ( ) ) ; } final String filterString = entry . getValue ( ) . getFilter ( ) ; if ( filterString != null && ! filterString . isEmpty ( ) ) { xsw . writeStartElement ( "filter" ) ; xsw . writeCharacters ( entry . getValue ( ) . getFilter ( ) ) ; xsw . writeEndElement ( ) ; // filter } xsw . writeEndElement ( ) ; // required } xsw . writeEndElement ( ) ; // requires } { if ( this . filter != null && ! this . filter . isEmpty ( ) ) { xsw . writeStartElement ( "filter" ) ; xsw . writeCharacters ( this . filter ) ; xsw . writeEndElement ( ) ; // filter } } if ( ! this . artifacts . isEmpty ( ) ) { xsw . writeStartElement ( "artifacts" ) ; xsw . writeAttribute ( "size" , Integer . toString ( this . artifacts . size ( ) ) ) ; for ( final Artifact artifact : this . artifacts ) { xsw . writeEmptyElement ( "artifact" ) ; xsw . writeAttribute ( "classifier" , artifact . getClassifer ( ) ) ; xsw . writeAttribute ( "id" , artifact . getId ( ) ) ; xsw . writeAttribute ( "version" , "" + artifact . getVersion ( ) ) ; } xsw . writeEndElement ( ) ; // artifacts } { if ( this . touchpoints . isEmpty ( ) ) { xsw . writeEmptyElement ( "touchpoint" ) ; xsw . writeAttribute ( "id" , "null" ) ; xsw . writeAttribute ( "version" , "0.0.0" ) ; } else { for ( final Touchpoint tp : this . touchpoints ) { xsw . writeEmptyElement ( "touchpoint" ) ; xsw . writeAttribute ( "id" , tp . getId ( ) ) ; xsw . writeAttribute ( "version" , tp . getVersion ( ) ) ; if ( ! tp . getInstructions ( ) . isEmpty ( ) ) { xsw . writeStartElement ( "touchpointData" ) ; xsw . writeAttribute ( "size" , "1" ) ; xsw . writeStartElement ( "instructions" ) ; xsw . writeAttribute ( "size" , Integer . toString ( tp . getInstructions ( ) . size ( ) ) ) ; for ( final Map . Entry < String , String > entry : tp . getInstructions ( ) . entrySet ( ) ) { xsw . writeStartElement ( "instruction" ) ; xsw . writeAttribute ( "key" , entry . getKey ( ) ) ; xsw . writeCharacters ( entry . getValue ( ) ) ; xsw . writeEndElement ( ) ; // instruction } xsw . writeEndElement ( ) ; // instructions xsw . writeEndElement ( ) ; // touchpointData } } } } { xsw . writeStartElement ( "licenses" ) ; xsw . writeAttribute ( "size" , Integer . toString ( this . licenses . size ( ) ) ) ; for ( final License licenseEntry : this . licenses ) { xsw . writeStartElement ( "license" ) ; if ( licenseEntry . getUri ( ) != null ) { xsw . writeAttribute ( "url" , licenseEntry . getUri ( ) ) ; xsw . writeAttribute ( "uri" , licenseEntry . getUri ( ) ) ; } if ( licenseEntry . getText ( ) != null ) { xsw . writeCData ( licenseEntry . getText ( ) ) ; } xsw . writeEndElement ( ) ; // license } xsw . writeEndElement ( ) ; // licenses } if ( this . copyright != null || this . copyrightUrl != null ) { xsw . writeStartElement ( "copyright" ) ; if ( this . copyrightUrl != null ) { xsw . writeAttribute ( "url" , this . copyrightUrl ) ; xsw . writeAttribute ( "uri" , this . copyrightUrl ) ; } if ( this . copyright != null ) { xsw . writeCData ( this . copyright ) ; } xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // unit }


Input: Get a job instance for updating it . <p > The fetched job will automatically be cloned and persisted . < / p > [CODESPLIT] public JobInstanceEntity getJobForUpdate ( final String id ) { JobInstanceEntity job = this . cloneMap . get ( id ) ; if ( job != null ) { // this already is the cloned job return job ; } // fetch the job job = this . jobs . get ( id ) ; if ( job == null ) { return null ; } // make the clone final JobInstanceEntity clonedJob = new JobInstanceEntity ( job ) ; this . cloneMap . put ( id , clonedJob ) ; return clonedJob ; }


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


Input: Get all meta data values which match namespace and key [CODESPLIT] public static SortedSet < String > metadata ( final Map < MetaKey , String > metadata , String namespace , String key ) { final SortedSet < String > result = new TreeSet <> ( ) ; if ( namespace . isEmpty ( ) ) { namespace = null ; } if ( key . isEmpty ( ) ) { key = null ; } for ( final Map . Entry < MetaKey , String > entry : metadata . entrySet ( ) ) { if ( namespace != null && ! namespace . equals ( entry . getKey ( ) . getNamespace ( ) ) ) { continue ; } if ( key != null && ! key . equals ( entry . getKey ( ) . getKey ( ) ) ) { continue ; } result . add ( entry . getValue ( ) ) ; } return result ; }