signature:
public class Generator { /** * 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 . */
private void generateSetJspContext ( TagInfo tagInfo ) { } }

implementation:
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 ( "}" ) ;


signature:
public class Generator { /** * 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 . */
public void generateSetDynamicAttribute ( ) { } }

implementation:
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 ( "}" ) ;


signature:
public class Generator { /** * 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 . */
private void generatePageScopedVariables ( JasperTagInfo tagInfo ) { } }

implementation:
// " 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);" ) ; }


signature:
public class Generator { /** * Generates the getter method for the given attribute name . */
private String toGetterMethod ( String attrName ) { } }

implementation: char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return "get" + new String ( attrChars ) + "()" ;


signature:
public class Generator { /** * Generates the setter method name for the given attribute name . */
private String toSetterMethodName ( String attrName ) { } }

implementation: char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return "set" + new String ( attrChars ) ;


signature:
public class TransferServiceImpl { /** * Read in a map of properties
 * @ param stream
 * input stream
 * @ return the map of properties
 * @ throws IOException
 * if anything goes wrong reading the file */
private Map < MetaKey , String > readProperties ( final InputStream stream ) throws IOException { } }

implementation:
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 ) ; }


signature:
public class TransferServiceImpl { /** * Export the content of a channel
 * @ param by
 * the channel to export
 * @ param stream
 * the stream to write the export file to
 * @ throws IOException
 * if the export cannot be performed */
private void exportChannel ( final By by , final OutputStream stream ) throws IOException { } }

implementation:
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


signature:
public class Header { /** * Make an array of header entries with given charset
 * < strong > Note : < / strong > Further updates on this instance will not update
 * the returned array . This is actually a copy of the current state .
 * @ param charset the charset of choice
 * @ return a new array of all header entries , unsorted */
public HeaderEntry [ ] makeEntries ( Charset charset ) { } }

implementation: 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 ] ) ;


signature:
public class Validator { /** * Validate XML view against the TagLibraryValidator classes of all
 * imported tag libraries . */
private static void validateXmlView ( PageData xmlView , Compiler compiler ) throws JasperException { } }

implementation:
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 ( ) ) ; }


signature:
public class TagHandlerPool { /** * Gets the next available tag handler from this tag handler pool ,
 * instantiating one if this tag handler pool is empty .
 * @ param handlerClass Tag handler class
 * @ return Reused or newly instantiated tag handler
 * @ throws JspException if a tag handler cannot be instantiated */
public < T extends JspTag > JspTag get ( Class < T > handlerClass ) throws JspException { } }

implementation:
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 ;


signature:
public class TagHandlerPool { /** * 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 .
 * @ param handler JspTag handler to add to this tag handler pool */
public void reuse ( JspTag handler ) { } }

implementation:
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 ) ; }


signature:
public class TagHandlerPool { /** * Calls the release ( ) method of all available tag handlers in this tag
 * handler pool . */
public synchronized void release ( ) { } }

implementation: for ( int i = current ; i >= 0 ; i -- ) { if ( handlers [ i ] instanceof Tag ) { ( ( Tag ) handlers [ i ] ) . release ( ) ; } if ( resourceInjector != null ) { resourceInjector . preDestroy ( handlers [ i ] ) ; } }


signature:
public class ELParser { /** * Parse an EL expression
 * @ param expression The input expression string of the form
 * ( ( Char * | ( ( ' $ { ' | ' # { ' ) Char * ' } ' ) ) +
 * @ return Parsed EL expression in ELNode . Nodes */
public static ELNode . Nodes parse ( String expression ) { } }

implementation: 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 ;


signature:
public class ELParser { /** * Parse an EL expression string ' $ { . . . } or # { . . . } '
 * @ return An ELNode . Nodes representing the EL expression
 * TODO : Currently only parsed into functions and text strings . This
 * should be rewritten for a full parser . */
private ELNode . Nodes parseEL ( ) { } }

implementation:
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 ;


signature:
public class ELParser { /** * Skip until an EL expression ( ' $ { ' or ' # { ' ) is reached , allowing escape
 * sequences ' \ \ ' , ' \ $ ' , and ' \ # ' .
 * @ return The text string up to the EL expression */
private String skipUntilEL ( ) { } }

implementation:
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 ( ) ;


signature:
public class ELParser { /** * Parse a string in single or double quotes , allowing for escape sequences
 * ' \ \ ' , and ( ' \ " ' , or " \ ' " ) */
private Token parseQuotedChars ( char quote ) { } }

implementation:
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 ( ) ) ;


signature:
public class JspConfig { /** * Select the property group that has more restrictive url - pattern .
 * In case of tie , select the first . */
private JspPropertyGroup selectProperty ( JspPropertyGroup prev , JspPropertyGroup curr ) { } }

implementation:
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 ;


signature:
public class JspConfig { /** * Find a property that best matches the supplied resource .
 * @ param uri the resource supplied .
 * @ return a JspProperty indicating the best match , or some default . */
public JspProperty findJspProperty ( String uri ) throws JasperException { } }

implementation:
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 ) ;


signature:
public class JspConfig { /** * To find out if an uri matches an url pattern in jsp config . If so ,
 * then the uri is a JSP page . This is used primarily for jspc . */
public boolean isJspPage ( String uri ) throws JasperException { } }

implementation:
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 ;


signature:
public class ServletWriter { /** * Print a standard comment for echo outputed chunk .
 * @ param start The starting position of the JSP chunk being processed .
 * @ param stop The ending position of the JSP chunk being processed . */
public void printComment ( Mark start , Mark stop , char [ ] chars ) { } }

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


signature:
public class ServletWriter { /** * Prints the current indention , followed by the given string */
public void printin ( String s ) { } }

implementation: writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . print ( s ) ;


signature:
public class ServletWriter { /** * Prints the current indention , and then the string , and a ' \ n ' . */
public void printil ( String s ) { } }

implementation: javaLine ++ ; writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . println ( s ) ;


signature:
public class ServletWriter { /** * Prints the given string .
 * If the string spans multiple lines , the line count will be adjusted
 * accordingly . */
public void printMultiLn ( String s ) { } }

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


signature:
public class JspUtil { /** * 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 ' % ' .
 * @ param token The token to be checked
 * return whether the token is a runtime expression or not . */
public static boolean isExpression ( String token , boolean isXml ) { } }

implementation: 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 ; }


signature:
public class JspUtil { /** * Takes a potential expression and converts it into XML form */
public static String getExprInXml ( String expression ) { } }

implementation: 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 ) ;


signature:
public class JspUtil { /** * Checks to see if the given scope is valid .
 * @ param scope The scope to be checked
 * @ param n The Node containing the ' scope ' attribute whose value is to be
 * checked
 * @ param err error dispatcher
 * @ throws JasperException if scope is not null and different from
 * & quot ; page & quot ; , & quot ; request & quot ; , & quot ; session & quot ; , and
 * & quot ; application & quot ; */
public static void checkScope ( String scope , Node n , ErrorDispatcher err ) throws JasperException { } }

implementation: if ( scope != null && ! scope . equals ( "page" ) && ! scope . equals ( "request" ) && ! scope . equals ( "session" ) && ! scope . equals ( "application" ) ) { err . jspError ( n , "jsp.error.invalid.scope" , scope ) ; }


signature:
public class JspUtil { /** * 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 . */
public static void checkAttributes ( String typeOfTag , Node n , ValidAttribute [ ] validAttributes , ErrorDispatcher err ) throws JasperException { } }

implementation:
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 )


signature:
public class JspUtil { /** * Escape the 5 entities defined by XML . */
public static String escapeXml ( String s ) { } }

implementation: 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 ( ) ;


signature:
public class JspUtil { /** * 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 .
 * @ param s the string to be converted
 * @ return the boolean value associated with the string s */
public static boolean booleanValue ( String s ) { } }

implementation: boolean b = false ; if ( s != null ) { if ( s . equalsIgnoreCase ( "yes" ) ) { b = true ; } else { b = Boolean . valueOf ( s ) . booleanValue ( ) ; } } return b ;


signature:
public class JspUtil { /** * Returns the < tt > Class < / tt > object associated with the class or
 * interface with the given string name .
 * < p > The < tt > Class < / tt > object is determined by passing the given string
 * name to the < tt > Class . forName ( ) < / tt > method , unless the given string
 * name represents a primitive type , in which case it is converted to a
 * < tt > Class < / tt > object by appending " . class " to it ( e . g . , " int . class " ) . */
public static Class < ? > toClass ( String type , ClassLoader loader ) throws ClassNotFoundException { } }

implementation:
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 ( ) ;


signature:
public class JspUtil { /** * Produces a String representing a call to the EL interpreter .
 * @ param expression a String containing zero or more " $ { } " expressions
 * @ param expectedType the expected type of the interpreted result
 * @ param fnmapvar Variable pointing to a function map .
 * @ return a String representing a call to the EL interpreter . */
public static String interpreterCall ( boolean isTagFile , String expression , Class expectedType , String fnmapvar , String expectedDeferredType , String expectedReturnType , String [ ] expectedParamTypes ) { } }

implementation:
/* * 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 ( ) ;


signature:
public class JspUtil { /** * Validates the syntax of all EL expressions within the given string .
 * @ param where the approximate location of the expressions in the JSP page
 * @ param expressions a string containing an EL expressions
 * @ param err an error dispatcher to use */
public static void validateExpressions ( Mark where , String expressions , FunctionMapper functionMapper , ErrorDispatcher err ) throws JasperException { } }

implementation: 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 ( ) ) ; }


signature:
public class JspUtil { /** * Gets the fully - qualified class name of the tag handler corresponding to
 * the given tag file path .
 * @ param path Tag file path
 * @ param err Error dispatcher
 * @ return Fully - qualified class name of the tag handler corresponding to
 * the given tag file path */
public static String getTagHandlerClassName ( String path , ErrorDispatcher err ) throws JasperException { } }

implementation:
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 ;


signature:
public class JspUtil { /** * Converts the given path to a Java package or fully - qualified class name
 * @ param path Path to convert
 * @ return Java package corresponding to the given path */
public static final String makeJavaPackage ( String path ) { } }

implementation: 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 ( ) ;


signature:
public class JspUtil { /** * Splits a string into it ' s components .
 * @ param path String to split
 * @ param pat Pattern to split at
 * @ return the components of the path */
private static final String [ ] split ( String path , String pat ) { } }

implementation: 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 ;


signature:
public class JspUtil { /** * Converts the given identifier to a legal Java identifier
 * @ param identifier Identifier to convert
 * @ return Legal Java identifier corresponding to the given identifier */
public static final String makeJavaIdentifier ( String identifier ) { } }

implementation: 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 ( ) ;


signature:
public class JspUtil { /** * Mangle the specified character to create a legal Java class name . */
public static final String mangleChar ( char ch ) { } }

implementation: 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 ) ;


signature:
public class JspUtil { /** * Test whether the argument is a Java keyword */
public static boolean isJavaKeyword ( String key ) { } }

implementation: 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 ;


signature:
public class JspUtil { /** * 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 .
 * @ param name Identifier to convert
 * @ return Legal Java identifier corresponding to the given identifier */
public static final String makeXmlJavaIdentifier ( String name ) { } }

implementation: 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 ;


signature:
public class JspUtil { /** * 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 .
 * @ param c A instance of java . lang . Class
 * @ return The canonical name of c . */
public static String getCanonicalName ( Class c ) { } }

implementation: 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 ( ) ;


signature:
public class JspUtil { /** * 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. */
public static List < String > expandClassPath ( List < String > files ) { } }

implementation:
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 ;


signature:
public class Tokens { /** * Create a random token
 * This method uses the internal instance of of a { @ link SecureRandom }
 * generator to create a new token .
 * @ param length
 * the length of the token
 * @ return the newly created token , never returns < code > null < / code > */
public static String createToken ( final int length ) { } }

implementation: final byte [ ] data = new byte [ length ] ; random . nextBytes ( data ) ; return Strings . hex ( data ) ;


signature:
public class InstallableUnit { /** * Add property entry only of value is not null
 * @ param props
 * properties
 * @ param key
 * to add
 * @ param value
 * to add */
private static void addProperty ( final Map < String , String > props , final String key , final String value ) { } }

implementation: if ( value == null ) { return ; } props . put ( key , value ) ;


signature:
public class InstallableUnit { /** * Write a list of units inside a { @ code units } element
 * @ param xsw
 * the stream to write to
 * @ param ius
 * The units to write
 * @ throws XMLStreamException
 * if the underlying throws it */
public static void writeXml ( final XMLStreamWriter xsw , final List < InstallableUnit > ius ) throws XMLStreamException { } }

implementation: xsw . writeStartElement ( "units" ) ; xsw . writeAttribute ( "size" , Integer . toString ( ius . size ( ) ) ) ; for ( final InstallableUnit iu : ius ) { iu . writeXmlForUnit ( xsw ) ; } xsw . writeEndElement ( ) ;


signature:
public class InstallableUnit { /** * Write the unit as XML fragment
 * @ param xsw
 * the XMLStreamWriter to write to
 * @ throws XMLStreamException
 * if the underlying throws it */
public void writeXmlForUnit ( final XMLStreamWriter xsw ) throws XMLStreamException { } }

implementation:
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


signature:
public class JobWriteModel { /** * Get a job instance for updating it .
 * The fetched job will automatically be cloned and persisted .
 * @ param id
 * the id of the job
 * @ return the job instance entity or < code > null < / code > if none could be
 * found */
public JobInstanceEntity getJobForUpdate ( final String id ) { } }

implementation:
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 ;


signature:
public class Functions { /** * Convert a modifier value to a bootstrap type modifier
 * @ param prefix
 * an optional prefix to add
 * @ param modifier
 * the modifier to convert
 * @ return the bootstrap type string , optionally with a prefix attached ,
 * never < code > null < / code > */
public static String modifier ( final String prefix , final Modifier modifier ) { } }

implementation: 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 : "" ; }


signature:
public class Functions { /** * Get all meta data values which match namespace and key
 * @ param metadata
 * the map of meta data to filter
 * @ param namespace
 * an optional namespace filter
 * @ param key
 * an optional key filter
 * @ return the result set */
public static SortedSet < String > metadata ( final Map < MetaKey , String > metadata , String namespace , String key ) { } }

implementation: 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 ;


signature:
public class JspServlet { /** * Initializes this JspServlet . */
public void init ( ServletConfig config ) throws ServletException { } }

implementation:
super . init ( config ) ; this . config = config ; this . context = config . getServletContext ( ) ; // Initialize the JSP Runtime Context
options = new EmbeddedServletOptions ( config , context ) ; rctxt = new JspRuntimeContext ( context , options ) ; // START SJSWS 6232180
// Determine which HTTP methods to service ( " * " means all )
httpMethodsString = config . getInitParameter ( "httpMethods" ) ; if ( httpMethodsString != null && ! httpMethodsString . equals ( "*" ) ) { httpMethodsSet = new HashSet < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( httpMethodsString , ", \t\n\r\f" ) ; while ( tokenizer . hasMoreTokens ( ) ) { httpMethodsSet . add ( tokenizer . nextToken ( ) ) ; } } // END SJSWS 6232180
// START GlassFish 750
taglibs = new ConcurrentHashMap < String , TagLibraryInfo > ( ) ; context . setAttribute ( Constants . JSP_TAGLIBRARY_CACHE , taglibs ) ; tagFileJarUrls = new ConcurrentHashMap < String , URL > ( ) ; context . setAttribute ( Constants . JSP_TAGFILE_JAR_URLS_CACHE , tagFileJarUrls ) ; // END GlassFish 750
if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( Localizer . getMessage ( "jsp.message.scratch.dir.is" , options . getScratchDir ( ) . toString ( ) ) ) ; log . finest ( Localizer . getMessage ( "jsp.message.dont.modify.servlets" ) ) ; } this . jspProbeEmitter = ( JspProbeEmitter ) config . getServletContext ( ) . getAttribute ( "org.glassfish.jsp.monitor.probeEmitter" ) ;


signature:
public class JspServlet { /** * < p > Look for a < em > precompilation request < / em > as described in
 * Section 8.4.2 of the JSP 1.2 Specification . < strong > WARNING < / strong > -
 * we cannot use < code > request . getParameter ( ) < / code > for this , because
 * that will trigger parsing all of the request parameters , and not give
 * a servlet the opportunity to call
 * < code > request . setCharacterEncoding ( ) < / code > first . < / p >
 * @ param request The servlet requset we are processing
 * @ exception ServletException if an invalid parameter value for the
 * < code > jsp _ precompile < / code > parameter name is specified */
boolean preCompile ( HttpServletRequest request ) throws ServletException { } }

implementation:
String queryString = request . getQueryString ( ) ; if ( queryString == null ) { return ( false ) ; } int start = queryString . indexOf ( Constants . PRECOMPILE ) ; if ( start < 0 ) { return ( false ) ; } queryString = queryString . substring ( start + Constants . PRECOMPILE . length ( ) ) ; if ( queryString . length ( ) == 0 ) { return ( true ) ; // ? jsp _ precompile
} if ( queryString . startsWith ( "&" ) ) { return ( true ) ; // ? jsp _ precompile & foo = bar . . .
} if ( ! queryString . startsWith ( "=" ) ) { return ( false ) ; // part of some other name or value
} int limit = queryString . length ( ) ; int ampersand = queryString . indexOf ( "&" ) ; if ( ampersand > 0 ) { limit = ampersand ; } String value = queryString . substring ( 1 , limit ) ; if ( value . equals ( "true" ) ) { return ( true ) ; // ? jsp _ precompile = true
} else if ( value . equals ( "false" ) ) { // Spec says if jsp _ precompile = false , the request should not
// be delivered to the JSP page ; the easiest way to implement
// this is to set the flag to true , and precompile the page anyway .
// This still conforms to the spec , since it says the
// precompilation request can be ignored .
return ( true ) ; // ? jsp _ precompile = false
} else { throw new ServletException ( "Cannot have request parameter " + Constants . PRECOMPILE + " set to " + value ) ; }


signature:
public class JspServlet { /** * - - - - - Private Methods */
private void serviceJspFile ( HttpServletRequest request , HttpServletResponse response , String jspUri , Throwable exception , boolean precompile ) throws ServletException , IOException { } }

implementation:
JspServletWrapper wrapper = ( JspServletWrapper ) rctxt . getWrapper ( jspUri ) ; if ( wrapper == null ) { synchronized ( this ) { wrapper = ( JspServletWrapper ) rctxt . getWrapper ( jspUri ) ; if ( wrapper == null ) { // Check if the requested JSP page exists , to avoid
// creating unnecessary directories and files .
if ( null == context . getResource ( jspUri ) && ! options . getUsePrecompiled ( ) ) { String includeRequestUri = ( String ) request . getAttribute ( "javax.servlet.include.request_uri" ) ; if ( includeRequestUri != null ) { // Missing JSP resource has been the target of a
// RequestDispatcher . include ( ) .
// Throw an exception ( rather than returning a
// 404 response error code ) , because any call to
// response . sendError ( ) must be ignored by the
// servlet engine when issued from within an
// included resource ( as per the Servlet spec ) .
throw new FileNotFoundException ( JspUtil . escapeXml ( jspUri ) ) ; } response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; log . severe ( Localizer . getMessage ( "jsp.error.file.not.found" , context . getRealPath ( jspUri ) ) ) ; return ; } boolean isErrorPage = exception != null ; wrapper = new JspServletWrapper ( config , options , jspUri , isErrorPage , rctxt ) ; rctxt . addWrapper ( jspUri , wrapper ) ; } } } wrapper . service ( request , response , precompile ) ;


signature:
public class JspServlet { /** * STARTS S1AS */
private void incrementErrorCount ( String jspUri ) { } }

implementation:
countErrors . incrementAndGet ( ) ; // Fire the jspErrorEvent probe event
if ( jspProbeEmitter != null ) { jspProbeEmitter . jspErrorEvent ( jspUri ) ; }


signature:
public class DatabaseUserService { /** * Clean up timed out user registrations */
@ Override public void run ( ) throws Exception { } }

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


signature:
public class BinaryLocator { /** * Check if the { @ code p2 . repo : fragment - keys } field contains a matching key
 * @ param art
 * the artifact to check
 * @ param key
 * the required key value
 * @ return { @ code true } if the artifact has a matching key entry ,
 * { @ code false } otherwise */
private static boolean hasKey ( final ArtifactInformation art , final String key ) { } }

implementation: if ( key == null ) { return false ; } final String keysString = art . getMetaData ( ) . get ( P2RepoConstants . KEY_FRAGMENT_KEYS ) ; if ( keysString == null ) { return false ; } final String [ ] keys = keysString . split ( P2RepoConstants . ENTRY_DELIMITER ) ; for ( final String actualKey : keys ) { if ( key . equals ( actualKey ) ) { return true ; } } return false ;


signature:
public class FileNames { /** * Get the last segment of a path , the filename
 * @ param name
 * the name to process
 * @ return the last segment , or { @ code null } if the input was { @ code null } */
public static String getBasename ( final String name ) { } }

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


signature:
public class XZInputStream { /** * Decompresses into an array of bytes .
 * If < code > len < / code > is zero , no bytes are read and < code > 0 < / code >
 * is returned . Otherwise this will try to decompress < code > len < / code >
 * bytes of uncompressed data . Less than < code > len < / code > bytes may
 * be read only in the following situations :
 * < ul >
 * < li > The end of the compressed data was reached successfully . < / li >
 * < li > An error is detected after at least one but less < code > len < / code >
 * bytes have already been successfully decompressed .
 * The next call with non - zero < code > len < / code > will immediately
 * throw the pending exception . < / li >
 * < li > An exception is thrown . < / li >
 * < / ul >
 * @ param buf target buffer for uncompressed data
 * @ param off start offset in < code > buf < / code >
 * @ param len maximum number of uncompressed bytes to read
 * @ return number of bytes read , or < code > - 1 < / code > to indicate
 * the end of the compressed stream
 * @ throws CorruptedInputException
 * @ throws UnsupportedOptionsException
 * @ throws MemoryLimitException
 * @ throws XZIOException if the stream has been closed
 * @ throws EOFException
 * compressed input is truncated or corrupt
 * @ throws IOException may be thrown by < code > in < / code > */
public int read ( byte [ ] buf , int off , int len ) throws IOException { } }

implementation: if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; int size = 0 ; try { while ( len > 0 ) { if ( xzIn == null ) { prepareNextStream ( ) ; if ( endReached ) return size == 0 ? - 1 : size ; } int ret = xzIn . read ( buf , off , len ) ; if ( ret > 0 ) { size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { xzIn = null ; } } } catch ( IOException e ) { exception = e ; if ( size == 0 ) throw e ; } return size ;


signature:
public class XZInputStream { /** * Returns the number of uncompressed bytes that can be read
 * without blocking . The value is returned with an assumption
 * that the compressed input data will be valid . If the compressed
 * data is corrupt , < code > CorruptedInputException < / code > may get
 * thrown before the number of bytes claimed to be available have
 * been read from this input stream .
 * @ return the number of uncompressed bytes that can be read
 * without blocking */
public int available ( ) throws IOException { } }

implementation: if ( in == null ) throw new XZIOException ( "Stream closed" ) ; if ( exception != null ) throw exception ; return xzIn == null ? 0 : xzIn . available ( ) ;


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

implementation: if ( in != null ) { if ( xzIn != null ) { xzIn . close ( false ) ; xzIn = null ; } try { if ( closeInput ) in . close ( ) ; } finally { in = null ; } }


signature:
public class DGagueIO { /** * Provides a way for the sub class to get a { @ link java . nio . ByteBuffer }
 * representation of a certain Rollup object .
 * @ param value
 * @ return */
@ Override protected ByteBuffer toByteBuffer ( Object value ) { } }

implementation: if ( ! ( value instanceof BluefloodGaugeRollup ) ) { throw new IllegalArgumentException ( "toByteBuffer(): expecting BluefloodGaugeRollup class but got " + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodGaugeRollup gaugeRollup = ( BluefloodGaugeRollup ) value ; return serDes . serialize ( gaugeRollup ) ;


signature:
public class BuildStore { /** * Consider 5 files getting merged in the buildstore . Assuming the flush rate to be 1 file / min , we need all the files together in order to construct 5 min rollup
 * How are we going to decide that a particular range has been totally filled up and ready to be rolled ?
 * One behaviour which we will start seeing in the buildstore is " higher " ranges starting to build up . This means the current range has almost filled up .
 * But there is still a possibility for backed up data , getting merged . So we provide RANGE _ BUFFER .
 * Basically , for every call to getEligibleData , it is going to return ( n - RANGE _ BUFFER ) ranges to get rolled up , and keep ( RANGE _ BUFFER ) in buildstore
 * Also , note that returning the range , will eventually remove them from buildstore , after all rollups are completed in RollupGenerator for that range . */
public static Map < Range , ConcurrentHashMap < Locator , Points > > getEligibleData ( ) { } }

implementation: if ( locatorToTimestampToPoint . size ( ) <= RANGE_BUFFER ) { log . debug ( "Range buffer still not exceeded. Returning null data to rollup generator" ) ; return null ; } else { Object [ ] sortedKeySet = locatorToTimestampToPoint . keySet ( ) . toArray ( ) ; Range cuttingPoint = ( Range ) sortedKeySet [ sortedKeySet . length - RANGE_BUFFER - 1 ] ; log . info ( "Found completed ranges up to the threshold range of {}" , cuttingPoint ) ; completedRangesReturned . mark ( ) ; return locatorToTimestampToPoint . headMap ( cuttingPoint , true ) ; }


signature:
public class MetadataCache { /** * Similar to { @ link # get ( Locator , String ) } , except this does not throw
 * any { @ link CacheException } . Instead , it may return null if the cache
 * does not contain the requested locator for the specified key .
 * @ param locator
 * @ param key
 * @ return */
public String safeGet ( Locator locator , String key ) { } }

implementation: String cacheValue = null ; try { cacheValue = get ( locator , key ) ; } catch ( CacheException ex ) { log . trace ( String . format ( "no cache value found for locator=%s, key=%s" , locator . toString ( ) , key ) ) ; } return cacheValue ;


signature:
public class MetadataCache { /** * returns true if updated . */
public boolean put ( Locator locator , String key , String value ) throws CacheException { } }

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


signature:
public class MetadataCache { /** * implements the CacheLoader interface . */
private String databaseLoad ( Locator locator , String key ) throws CacheException { } }

implementation:
try { CacheKey cacheKey = new CacheKey ( locator , key ) ; Map < String , String > metadata = io . getAllValues ( locator ) ; if ( metadata == null || metadata . isEmpty ( ) ) { cache . put ( cacheKey , NULL ) ; return NULL ; } int metadataRowSize = 0 ; // prepopulate all other metadata other than the key we called the method with
for ( Map . Entry < String , String > meta : metadata . entrySet ( ) ) { metadataRowSize += meta . getKey ( ) . getBytes ( ) . length + locator . toString ( ) . getBytes ( ) . length ; if ( meta . getValue ( ) != null ) metadataRowSize += meta . getValue ( ) . getBytes ( ) . length ; if ( meta . getKey ( ) . equals ( key ) ) continue ; CacheKey metaKey = new CacheKey ( locator , meta . getKey ( ) ) ; cache . put ( metaKey , meta . getValue ( ) ) ; } totalMetadataSize . update ( metadataRowSize ) ; String value = metadata . get ( key ) ; if ( value == null ) { cache . put ( cacheKey , NULL ) ; value = NULL ; } return value ; } catch ( IOException ex ) { throw new CacheException ( ex ) ; }


signature:
public class PreaggregateConversions { /** * type comparisions we use to determine how to serialize a number . */
public static Collection < IMetric > buildMetricsCollection ( AggregatedPayload payload ) { } }

implementation: Collection < IMetric > metrics = new ArrayList < IMetric > ( ) ; metrics . addAll ( PreaggregateConversions . convertCounters ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getFlushIntervalMillis ( ) , payload . getCounters ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertGauges ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getGauges ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertSets ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getSets ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertTimers ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getTimers ( ) ) ) ; return metrics ;


signature:
public class PreaggregateConversions { /** * resolve a number to a Long or double . */
public static Number resolveNumber ( Number n ) { } }

implementation:
if ( n instanceof LazilyParsedNumber ) { try { return n . longValue ( ) ; } catch ( NumberFormatException ex ) { return n . doubleValue ( ) ; } } else { // already resolved .
return n ; }


signature:
public class StringMetadataSerDes { /** * History : this used to support multiple types . */
public ByteBuffer serialize ( String str ) { } }

implementation: try { byte [ ] buf = new byte [ computeBufLength ( str ) ] ; CodedOutputStream out = CodedOutputStream . newInstance ( buf ) ; writeToOutputStream ( str , out ) ; return ByteBuffer . wrap ( buf ) ; } catch ( IOException e ) { throw new RuntimeException ( "Error serializing string metadata" , e ) ; }


signature:
public class StringMetadataSerDes { /** * writes object to CodedOutputStream . */
private static void writeToOutputStream ( Object obj , CodedOutputStream out ) throws IOException { } }

implementation: out . writeRawByte ( STRING ) ; out . writeStringNoTag ( ( String ) obj ) ;


signature:
public class ALocatorIO { /** * Insert a locator with key = shard long value calculated using Util . getShard ( )
 * @ param locator
 * @ throws IOException */
@ Override public void insertLocator ( Locator locator ) throws IOException { } }

implementation: Timer . Context timer = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { MutationBatch mutationBatch = AstyanaxIO . getKeyspace ( ) . prepareMutationBatch ( ) ; AstyanaxWriter . getInstance ( ) . insertLocator ( locator , mutationBatch ) ; mutationBatch . execute ( ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } finally { timer . stop ( ) ; }


signature:
public class ALocatorIO { /** * Returns the locators for a shard , i . e . those that should be rolled up , for a given shard .
 * ' Should ' means :
 * 1 ) A locator is capable of rollup .
 * 2 ) A locator has had new data in the past LOCATOR _ TTL seconds .
 * @ param shard Number of the shard you want the locators for . 0-127 inclusive .
 * @ return Collection of locators
 * @ throws IOException */
@ Override public Collection < Locator > getLocators ( long shard ) throws IOException { } }

implementation: Timer . Context ctx = Instrumentation . getReadTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { RowQuery < Long , Locator > query = AstyanaxIO . getKeyspace ( ) . prepareQuery ( CassandraModel . CF_METRICS_LOCATOR ) . getKey ( shard ) ; if ( LOG . isTraceEnabled ( ) ) LOG . trace ( "ALocatorIO.getLocators() executing: select * from \"" + CassandraModel . KEYSPACE + "\"." + CassandraModel . CF_METRICS_LOCATOR_NAME + " where key=" + Long . toString ( shard ) ) ; return query . execute ( ) . getResult ( ) . getColumnNames ( ) ; } catch ( NotFoundException e ) { Instrumentation . markNotFound ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; return Collections . emptySet ( ) ; } catch ( ConnectionException ex ) { Instrumentation . markReadError ( ex ) ; LOG . error ( "Connection exception during getLocators(" + Long . toString ( shard ) + ")" , ex ) ; throw new IOException ( "Error reading locators" , ex ) ; } finally { ctx . stop ( ) ; }


signature:
public class AbstractMetricsRW { /** * Gets the TTL for a particular locator , rollupType and granularity .
 * @ param locator
 * @ param rollupType
 * @ param granularity
 * @ return */
protected int getTtl ( Locator locator , RollupType rollupType , Granularity granularity ) { } }

implementation: return ( int ) TTL_PROVIDER . getTTL ( locator . getTenantId ( ) , granularity , rollupType ) . get ( ) . toSeconds ( ) ;


signature:
public class AbstractMetricsRW { /** * Converts the map of timestamp - > { @ link Rollup } to
 * { @ link Points } object
 * @ param timestampToRollupMap a map of timestamp to rollup
 * @ return */
protected < T extends Object > Points < T > convertToPoints ( final Map < Long , T > timestampToRollupMap ) { } }

implementation: Points points = new Points ( ) ; for ( Map . Entry < Long , T > value : timestampToRollupMap . entrySet ( ) ) { points . add ( createPoint ( value . getKey ( ) , value . getValue ( ) ) ) ; } return points ;


signature:
public class DLocatorIO { /** * Create all prepared statements use in this class for metrics _ locator */
private void createPreparedStatements ( ) { } }

implementation:
// create a generic select statement for retrieving from metrics _ locator
Select . Where select = QueryBuilder . select ( ) . all ( ) . from ( CassandraModel . CF_METRICS_LOCATOR_NAME ) . where ( eq ( KEY , bindMarker ( ) ) ) ; getValue = DatastaxIO . getSession ( ) . prepare ( select ) ; // create a generic insert statement for inserting into metrics _ locator
Insert insert = QueryBuilder . insertInto ( CassandraModel . CF_METRICS_LOCATOR_NAME ) . using ( ttl ( TenantTtlProvider . LOCATOR_TTL ) ) . value ( KEY , bindMarker ( ) ) . value ( COLUMN1 , bindMarker ( ) ) . value ( VALUE , bindMarker ( ) ) ; putValue = DatastaxIO . getSession ( ) . prepare ( insert ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_ONE ) ;


signature:
public class DLocatorIO { /** * Insert a locator with key = shard long value calculated using Util . getShard ( )
 * @ param locator
 * @ throws IOException */
@ Override public void insertLocator ( Locator locator ) throws IOException { } }

implementation:
Session session = DatastaxIO . getSession ( ) ; Timer . Context timer = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { // bound values and execute
BoundStatement bs = getBoundStatementForLocator ( locator ) ; session . execute ( bs ) ; } finally { timer . stop ( ) ; }


signature:
public class DLocatorIO { /** * package protect so other classes in this package can call it */
BoundStatement getBoundStatementForLocator ( Locator locator ) { } }

implementation:
// get shard this locator would belong to
long shard = ( long ) Util . getShard ( locator . toString ( ) ) ; return putValue . bind ( shard , locator . toString ( ) , "" ) ;


signature:
public class DLocatorIO { /** * Returns the locators for a shard , i . e . those that should be rolled up , for a given shard .
 * ' Should ' means :
 * 1 ) A locator is capable of rollup .
 * 2 ) A locator has had new data in the past LOCATOR _ TTL seconds .
 * @ param shard Number of the shard you want the locators for . 0-127 inclusive .
 * @ return Collection of locators
 * @ throws IOException */
@ Override public Collection < Locator > getLocators ( long shard ) throws IOException { } }

implementation:
Timer . Context ctx = Instrumentation . getReadTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; Session session = DatastaxIO . getSession ( ) ; Collection < Locator > locators = new ArrayList < Locator > ( ) ; try { // bind value
BoundStatement bs = getValue . bind ( shard ) ; List < Row > results = session . execute ( bs ) . all ( ) ; for ( Row row : results ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "Read metrics_locators with shard " + shard + ": " + row . getString ( KEY ) + row . getString ( COLUMN1 ) ) ; } locators . add ( Locator . createLocatorFromDbKey ( row . getString ( COLUMN1 ) ) ) ; } // return results
if ( locators . size ( ) == 0 ) { Instrumentation . markNotFound ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; return Collections . emptySet ( ) ; } else { return locators ; } } finally { ctx . stop ( ) ; }


signature:
public class Tracker { /** * This method is used to log delayed metrics , if tracking delayed metrics
 * is turned on for this Blueflood service .
 * @ param tenantid
 * @ param delayedMetrics */
public void trackDelayedMetricsTenant ( String tenantid , final List < Metric > delayedMetrics ) { } }

implementation:
if ( isTrackingDelayedMetrics ) { String logMessage = String . format ( "[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s" , tenantid ) ; log . info ( logMessage ) ; // log individual delayed metrics locator and collectionTime
double delayedMinutes ; long nowMillis = System . currentTimeMillis ( ) ; for ( Metric metric : delayedMetrics ) { delayedMinutes = ( double ) ( nowMillis - metric . getCollectionTime ( ) ) / 1000 / 60 ; logMessage = String . format ( "[TRACKER][DELAYED METRIC] %s has collectionTime %s which is delayed by %.2f minutes" , metric . getLocator ( ) . toString ( ) , dateFormatter . format ( new Date ( metric . getCollectionTime ( ) ) ) , delayedMinutes ) ; log . info ( logMessage ) ; } }


signature:
public class Tracker { /** * This method logs the delayed aggregated metrics for a particular tenant ,
 * if tracking delayed metric is turned on for this Blueflood service .
 * Aggregated metrics have one single timestamp for the group of metrics that
 * are sent in one request .
 * @ param tenantId the tenantId who ' s the sender of the metrics
 * @ param collectionTimeMs the collection timestamp ( ms ) in request payload
 * @ param delayTimeMs the delayed time ( ms )
 * @ param delayedMetricNames the list of delayed metrics in request payload */
public void trackDelayedAggregatedMetricsTenant ( String tenantId , long collectionTimeMs , long delayTimeMs , List < String > delayedMetricNames ) { } }

implementation:
if ( isTrackingDelayedMetrics ) { String logMessage = String . format ( "[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s" , tenantId ) ; log . info ( logMessage ) ; // log individual delayed metrics locator and collectionTime
double delayMin = delayTimeMs / 1000 / 60 ; logMessage = String . format ( "[TRACKER][DELAYED METRIC] %s have collectionTime %s which is delayed by %.2f minutes" , StringUtils . join ( delayedMetricNames , "," ) , dateFormatter . format ( new Date ( collectionTimeMs ) ) , delayMin ) ; log . info ( logMessage ) ; }


signature:
public class AbstractSerDes { /** * read out a type - specified number . */
protected Number getUnversionedDoubleOrLong ( CodedInputStream in ) throws IOException { } }

implementation: byte type = in . readRawByte ( ) ; if ( type == Constants . B_DOUBLE ) return in . readDouble ( ) ; else return in . readRawVarint64 ( ) ;


signature:
public class AbstractSerDes { /** * put out a number prefaced only by a type . */
protected void putUnversionedDoubleOrLong ( Number number , CodedOutputStream out ) throws IOException { } }

implementation: if ( number instanceof Double ) { out . writeRawByte ( Constants . B_DOUBLE ) ; out . writeDoubleNoTag ( number . doubleValue ( ) ) ; } else { out . writeRawByte ( Constants . B_I64 ) ; out . writeRawVarint64 ( number . longValue ( ) ) ; }


signature:
public class Configuration { /** * Convert the existing configuration values into a Map , including those specified in defaultProps .
 * @ return an unmodifiable Map */
public Map < Object , Object > getAllProperties ( ) { } }

implementation: Map < Object , Object > map = new HashMap < Object , Object > ( ) ; for ( Object key : defaultProps . keySet ( ) ) { map . put ( key , defaultProps . getProperty ( key . toString ( ) ) ) ; } for ( Object key : props . keySet ( ) ) { map . put ( key , props . getProperty ( key . toString ( ) ) ) ; } return Collections . unmodifiableMap ( map ) ;


signature:
public class CloudFilesPublisher { /** * idempotent other than when the month changes between two calls */
private void createContainer ( ) { } }

implementation: String containerName = CONTAINER_DATE_FORMAT . format ( new Date ( ) ) ; blobStore . createContainerInLocation ( null , containerName ) ; lastContainerCreated = containerName ;


signature:
public class DCounterIO { /** * Provides a way for the sub class to get a { @ link java . nio . ByteBuffer }
 * representation of a certain Rollup object .
 * @ param value
 * @ return */
@ Override protected ByteBuffer toByteBuffer ( Object value ) { } }

implementation: if ( ! ( value instanceof BluefloodCounterRollup ) ) { throw new IllegalArgumentException ( "toByteBuffer(): expecting BluefloodCounterRollup class but got " + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodCounterRollup counterRollup = ( BluefloodCounterRollup ) value ; return serDes . serialize ( counterRollup ) ;


signature:
public class DCounterIO { /** * Retrieves the { @ link BoundStatement } for a particular counter metric
 * @ param metric
 * @ param granularity
 * @ return */
@ Override protected BoundStatement getBoundStatementForMetric ( IMetric metric , Granularity granularity ) { } }

implementation: Object metricValue = metric . getMetricValue ( ) ; if ( ! ( metricValue instanceof BluefloodCounterRollup ) ) { throw new InvalidDataException ( String . format ( "getBoundStatementForMetric(locator=%s, granularity=%s): metric value %s is not type BluefloodCounterRollup" , metric . getLocator ( ) , granularity , metric . getMetricValue ( ) . getClass ( ) . getSimpleName ( ) ) ) ; } PreparedStatement statement = metricsCFPreparedStatements . preaggrGranToInsertStatement . get ( granularity ) ; return statement . bind ( metric . getLocator ( ) . toString ( ) , metric . getCollectionTime ( ) , serDes . serialize ( ( BluefloodCounterRollup ) metricValue ) , metric . getTtlInSeconds ( ) ) ;


signature:
public class ScheduleContext { /** * { @ inheritDoc } */
public void update ( long millis , int shard ) { } }

implementation:
// there are two update paths . for managed shards , we must guard the
// scheduled and running collections . but for unmanaged shards , we just
// let the update happen uncontested .
final Timer . Context dirtyTimerCtx = markSlotDirtyTimer . time ( ) ; try { if ( log . isTraceEnabled ( ) ) { log . trace ( "Updating {} to {}" , shard , millis ) ; } boolean isManaged = shardStateManager . contains ( shard ) ; for ( Granularity g : Granularity . rollupGranularities ( ) ) { ShardStateManager . SlotStateManager slotStateManager = shardStateManager . getSlotStateManager ( shard , g ) ; int slot = g . slot ( millis ) ; if ( isManaged ) { synchronized ( scheduledSlots ) { // put
SlotKey key = SlotKey . of ( g , slot , shard ) ; if ( scheduledSlots . remove ( key ) && log . isDebugEnabled ( ) ) { // don ' t worry about orderedScheduledSlots
log . debug ( "descheduled {}." , key ) ; } } } slotStateManager . createOrUpdateForSlotAndMillisecond ( slot , millis ) ; } } finally { dirtyTimerCtx . stop ( ) ; }


signature:
public class ScheduleContext { /** * only one thread should be calling in this puppy . */
void scheduleEligibleSlots ( long maxAgeMillis , long rollupDelayForMetricsWithShortDelay , long rollupWaitForMetricsWithLongDelay ) { } }

implementation:
long now = scheduleTime ; ArrayList < Integer > shardKeys = new ArrayList < Integer > ( shardStateManager . getManagedShards ( ) ) ; Collections . shuffle ( shardKeys ) ; for ( int shard : shardKeys ) { for ( Granularity g : Granularity . rollupGranularities ( ) ) { // sync on map since we do not want anything added to or taken from it while we iterate .
synchronized ( scheduledSlots ) { // read
synchronized ( runningSlots ) { // read
List < Integer > slotsToWorkOn = shardStateManager . getSlotStateManager ( shard , g ) . getSlotsEligibleForRollup ( now , maxAgeMillis , rollupDelayForMetricsWithShortDelay , rollupWaitForMetricsWithLongDelay ) ; if ( slotsToWorkOn . size ( ) == 0 ) { continue ; } if ( ! canWorkOnShard ( shard ) ) { continue ; } for ( Integer slot : slotsToWorkOn ) { SlotKey slotKey = SlotKey . of ( g , slot , shard ) ; if ( areChildKeysOrSelfKeyScheduledOrRunning ( slotKey ) ) { continue ; } SlotKey key = SlotKey . of ( g , slot , shard ) ; scheduledSlots . add ( key ) ; orderedScheduledSlots . add ( key ) ; recentlyScheduledShards . put ( shard , scheduleTime ) ; } } } } }


signature:
public class ScheduleContext { /** * Returns the next scheduled key . It has a few side effects :
 * 1 ) it resets update tracking for that slot
 * 2 ) it adds the key to the set of running rollups .
 * @ return */
@ VisibleForTesting SlotKey getNextScheduled ( ) { } }

implementation:
synchronized ( scheduledSlots ) { if ( scheduledSlots . size ( ) == 0 ) return null ; synchronized ( runningSlots ) { SlotKey key = orderedScheduledSlots . remove ( 0 ) ; int slot = key . getSlot ( ) ; Granularity gran = key . getGranularity ( ) ; int shard = key . getShard ( ) ; // notice how we change the state , but the timestamp remained
// the same . this is important . When the state is evaluated
// ( i . e . , in Reader . getShardState ( ) ) we need to realize that
// when timestamps are the same ( this will happen ) , that a
// remove always wins during the coalesce .
scheduledSlots . remove ( key ) ; if ( canWorkOnShard ( shard ) ) { UpdateStamp stamp = shardStateManager . getSlotStateManager ( shard , gran ) . getAndSetState ( slot , UpdateStamp . State . Running ) ; runningSlots . put ( key , stamp . getTimestamp ( ) ) ; return key ; } else { shardOwnershipChanged . mark ( ) ; return null ; } } }


signature:
public class ScheduleContext { /** * Take the given slot out of the running group , and put it back into the
 * scheduled group . If { @ code rescheduleImmediately } is true , the slot will
 * be the next slot returned by a call to { @ link # getNextScheduled ( ) } . If
 * { @ code rescheduleImmediately } is false , then the given slot will go to
 * the end of the line , as when it was first scheduled by
 * { @ link # scheduleEligibleSlots ( long , long , long ) } .
 * @ param key
 * @ param rescheduleImmediately */
void pushBackToScheduled ( SlotKey key , boolean rescheduleImmediately ) { } }

implementation:
synchronized ( scheduledSlots ) { synchronized ( runningSlots ) { int slot = key . getSlot ( ) ; Granularity gran = key . getGranularity ( ) ; int shard = key . getShard ( ) ; // no need to set dirty / clean here .
shardStateManager . getSlotStateManager ( shard , gran ) . getAndSetState ( slot , UpdateStamp . State . Active ) ; scheduledSlots . add ( key ) ; log . debug ( "pushBackToScheduled -> added to scheduledSlots: " + key + " size:" + scheduledSlots . size ( ) ) ; if ( rescheduleImmediately ) { orderedScheduledSlots . add ( 0 , key ) ; } else { orderedScheduledSlots . add ( key ) ; } } }


signature:
public class ScheduleContext { /** * Remove the given slot from the running group after it has been
 * successfully re - rolled .
 * @ param slotKey */
void clearFromRunning ( SlotKey slotKey ) { } }

implementation:
synchronized ( runningSlots ) { runningSlots . remove ( slotKey ) ; UpdateStamp stamp = shardStateManager . getUpdateStamp ( slotKey ) ; shardStateManager . setAllCoarserSlotsDirtyForSlot ( slotKey ) ; // When state gets set to " X " , before it got persisted , it might get scheduled for rollup
// again , if we get delayed metrics . To prevent this we temporarily set last rollup time with current
// time . This value wont get persisted .
long currentTimeInMillis = clock . now ( ) . getMillis ( ) ; stamp . setLastRollupTimestamp ( currentTimeInMillis ) ; log . debug ( "SlotKey {} is marked in memory with last rollup time as {}" , slotKey , currentTimeInMillis ) ; // Update the stamp to Rolled state if and only if the current state
// is running . If the current state is active , it means we received
// a delayed put which toggled the status to Active .
if ( stamp . getState ( ) == UpdateStamp . State . Running ) { stamp . setState ( UpdateStamp . State . Rolled ) ; // Note : Rollup state will be updated to the last ACTIVE
// timestamp which caused rollup process to kick in .
stamp . setDirty ( true ) ; } }


signature:
public class DBasicMetricsRW { /** * This method inserts a collection of { @ link com . rackspacecloud . blueflood . types . IMetric } objects
 * to the appropriate Cassandra column family . Effectively , this method is only called to write
 * the raw metrics received during Ingest requests . Another method , insertRollups , is used by
 * the Rollup processes to write rolled up metrics .
 * @ param metrics
 * @ throws IOException */
@ Override public void insertMetrics ( Collection < IMetric > metrics ) throws IOException { } }

implementation: Timer . Context ctx = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_FULL_NAME ) ; try { if ( isBatchIngestEnabled ) { insertMetricsInBatch ( metrics ) ; } else { insertMetricsIndividually ( metrics ) ; } } finally { ctx . stop ( ) ; }


signature:
public class DBasicMetricsRW { /** * Fetches { @ link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the
 * specified list of { @ link com . rackspacecloud . blueflood . types . Locator } and
 * { @ link com . rackspacecloud . blueflood . types . Range } from the specified column family
 * @ param locators
 * @ param range
 * @ param gran
 * @ return */
@ Override public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , Granularity gran ) { } }

implementation: Map < Locator , MetricData > metrics = new HashMap < Locator , MetricData > ( ) ; String columnFamily = CassandraModel . getBasicColumnFamilyName ( gran ) ; metrics . putAll ( super . getDatapointsForRange ( locators , range , columnFamily , gran ) ) ; return metrics ;


signature:
public class DBasicMetricsRW { /** * Return the appropriate IO object which interacts with the Cassandra database .
 * For Preaggregated Metrics , only rollup type is required .
 * For Basic Numeric Metrics , the granularity is required as metrics _ full is handled differently
 * than the other granularities .
 * @ param rollupType
 * @ param granularity
 * @ return */
@ Override public DAbstractMetricIO getIO ( String rollupType , Granularity granularity ) { } }

implementation: if ( granularity == Granularity . FULL ) return simpleNumberIO ; else return basicIO ;


signature:
public class DBasicMetricsRW { /** * Inserts a collection of metrics in a batch using an unlogged
 * { @ link BatchStatement }
 * @ param metrics
 * @ return */
private void insertMetricsInBatch ( Collection < IMetric > metrics ) throws IOException { } }

implementation:
BatchStatement batch = new BatchStatement ( BatchStatement . Type . UNLOGGED ) ; for ( IMetric metric : metrics ) { BoundStatement bound = simpleNumberIO . getBoundStatementForMetric ( metric ) ; batch . add ( bound ) ; Instrumentation . markFullResMetricWritten ( ) ; Locator locator = metric . getLocator ( ) ; if ( ! LocatorCache . getInstance ( ) . isLocatorCurrentInBatchLayer ( locator ) ) { LocatorCache . getInstance ( ) . setLocatorCurrentInBatchLayer ( locator ) ; batch . add ( locatorIO . getBoundStatementForLocator ( locator ) ) ; } // if we are recording delayed metrics , we may need to do an
// extra insert
if ( isRecordingDelayedMetrics ) { BoundStatement bs = getBoundStatementForMetricIfDelayed ( metric ) ; if ( bs != null ) { batch . add ( bs ) ; } } } LOG . trace ( String . format ( "insert batch statement size=%d" , batch . size ( ) ) ) ; try { DatastaxIO . getSession ( ) . execute ( batch ) ; } catch ( Exception ex ) { Instrumentation . markWriteError ( ) ; LOG . error ( String . format ( "error writing batch of %d metrics" , batch . size ( ) ) , ex ) ; }


signature:
public class Emitter { /** * Listens on the event .
 * @ param event event name .
 * @ param fn
 * @ return a reference to this object . */
public Emitter on ( String event , Listener fn ) { } }

implementation: ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; if ( callbacks == null ) { callbacks = new ConcurrentLinkedQueue < Listener > ( ) ; ConcurrentLinkedQueue < Listener > _callbacks = this . callbacks . putIfAbsent ( event , callbacks ) ; if ( _callbacks != null ) { callbacks = _callbacks ; } } callbacks . add ( fn ) ; return this ;


signature:
public class Emitter { /** * Adds a one time listener for the event .
 * @ param event an event name .
 * @ param fn
 * @ return a reference to this object . */
public Emitter once ( final String event , final Listener < T > fn ) { } }

implementation: Listener on = new Listener < T > ( ) { @ Override public void call ( T ... args ) { Emitter . this . off ( event , this ) ; fn . call ( args ) ; } } ; this . onceCallbacks . put ( fn , on ) ; this . on ( event , on ) ; return this ;


signature:
public class Emitter { /** * Removes all listeners of the specified event .
 * @ param event an event name .
 * @ return a reference to this object . */
public Emitter off ( String event ) { } }

implementation: ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . remove ( event ) ; if ( callbacks != null ) { for ( Listener fn : callbacks ) { this . onceCallbacks . remove ( fn ) ; } } return this ;


signature:
public class Emitter { /** * Executes each of listeners with the given args .
 * @ param event an event name .
 * @ param args
 * @ return a reference to this object . */
public Future emit ( String event , T ... args ) { } }

implementation: ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; if ( callbacks != null ) { callbacks = new ConcurrentLinkedQueue < Listener > ( callbacks ) ; for ( Listener fn : callbacks ) { fn . call ( args ) ; } } return null ;


signature:
public class Emitter { /** * Returns a list of listeners for the specified event .
 * @ param event an event name .
 * @ return a reference to this object . */
public List < Listener > listeners ( String event ) { } }

implementation: ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; return callbacks != null ? new ArrayList < Listener > ( callbacks ) : new ArrayList < Listener > ( ) ;


signature:
public class RollupFile { /** * Get the remote file name .
 * @ return The path to the remote file . */
public String getRemoteName ( ) { } }

implementation: Date time = new Date ( timestamp ) ; String formattedTime = new SimpleDateFormat ( "yyyyMMdd_" ) . format ( time ) ; return formattedTime + System . currentTimeMillis ( ) + "_" + Configuration . getInstance ( ) . getStringProperty ( CloudfilesConfig . CLOUDFILES_HOST_UNIQUE_IDENTIFIER ) ;


signature:
public class RollupFile { /** * Serialize a Rollup Event and append it to the file .
 * @ param rollup The rollup to append .
 * @ throws IOException */
public void append ( RollupEvent rollup ) throws IOException { } }

implementation: ensureOpen ( ) ; outputStream . write ( serializer . toBytes ( rollup ) ) ; outputStream . write ( '\n' ) ; outputStream . flush ( ) ;


signature:
public class RollupFile { /** * Parse the timestamp from a filename .
 * @ param fileName The file name to parse .
 * @ return The timestamp contained in the file name .
 * @ throws NumberFormatException */
private static long parseTimestamp ( String fileName ) throws NumberFormatException { } }

implementation: String numberPart = fileName . substring ( 0 , fileName . length ( ) - 5 ) ; return Long . parseLong ( numberPart ) ;