Input: Prepares the request buffer . [CODESPLIT] @ Override protected Buffer buffer ( final boolean fullRequest ) { // INITIALIZATION // host port if ( header ( HEADER_HOST ) == null ) { setHostHeader ( ) ; } // form Buffer formBuffer = formBuffer ( ) ; // query string String queryString = queryString ( ) ; // user-agent if ( header ( "User-Agent" ) == null ) { header ( "User-Agent" , Defaults . userAgent ) ; } // POST method requires Content-Type to be set if ( method . equals ( "POST" ) && ( contentLength ( ) == null ) ) { contentLength ( 0 ) ; } // BUILD OUT Buffer request = new Buffer ( ) ; request . append ( method ) . append ( SPACE ) . append ( path ) ; if ( query != null && ! query . isEmpty ( ) ) { request . append ( ' ' ) ; request . append ( queryString ) ; } request . append ( SPACE ) . append ( httpVersion ) . append ( CRLF ) ; populateHeaderAndBody ( request , formBuffer , fullRequest ) ; return request ; }


Input: Syntax sugar . [CODESPLIT] public < R > R sendAndReceive ( final Function < HttpResponse , R > responseHandler ) { return responseHandler . apply ( send ( ) ) ; }


Input: Creates new { @link Session } with or without custom { @link Properties } . [CODESPLIT] protected Session createSession ( Properties properties ) { if ( properties == null ) { properties = System . getProperties ( ) ; } this . session = Session . getInstance ( properties ) ; return session ; }


Input: Copies properties from given set . If { @link Session } is already created exception will be thrown . [CODESPLIT] public T set ( final Properties properties ) throws MailException { checkSessionNotSet ( ) ; this . properties . putAll ( properties ) ; return _this ( ) ; }


Input: Sets property for the { @link Session } . If { @link Session } is already created an exception will be thrown . [CODESPLIT] public T set ( final String name , final String value ) { checkSessionNotSet ( ) ; properties . setProperty ( name , value ) ; return _this ( ) ; }


Input: Add new error message to the { [CODESPLIT] public void addError ( final String message ) { if ( config . collectErrors ) { if ( errors == null ) { errors = new ArrayList <> ( ) ; } errors . add ( message ) ; } }


Input: Removes the range between start and end from the Handler list that begins with the given element . [CODESPLIT] static Handler removeRange ( final Handler firstHandler , final Label start , final Label end ) { if ( firstHandler == null ) { return null ; } else { firstHandler . nextHandler = removeRange ( firstHandler . nextHandler , start , end ) ; } int handlerStart = firstHandler . startPc . bytecodeOffset ; int handlerEnd = firstHandler . endPc . bytecodeOffset ; int rangeStart = start . bytecodeOffset ; int rangeEnd = end == null ? Integer . MAX_VALUE : end . bytecodeOffset ; // Return early if [handlerStart,handlerEnd[ and [rangeStart,rangeEnd[ don't intersect. if ( rangeStart >= handlerEnd || rangeEnd <= handlerStart ) { return firstHandler ; } if ( rangeStart <= handlerStart ) { if ( rangeEnd >= handlerEnd ) { // If [handlerStart,handlerEnd[ is included in [rangeStart,rangeEnd[, remove firstHandler. return firstHandler . nextHandler ; } else { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [rangeEnd,handlerEnd[ return new Handler ( firstHandler , end , firstHandler . endPc ) ; } } else if ( rangeEnd >= handlerEnd ) { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [handlerStart,rangeStart[ return new Handler ( firstHandler , firstHandler . startPc , start ) ; } else { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = //     [handlerStart,rangeStart[ + [rangeEnd,handerEnd[ firstHandler . nextHandler = new Handler ( firstHandler , end , firstHandler . endPc ) ; return new Handler ( firstHandler , firstHandler . startPc , start ) ; } }


Input: Returns the number of elements of the Handler list that begins with the given element . [CODESPLIT] static int getExceptionTableLength ( final Handler firstHandler ) { int length = 0 ; Handler handler = firstHandler ; while ( handler != null ) { length ++ ; handler = handler . nextHandler ; } return length ; }


Input: Puts the JVMS exception_table corresponding to the Handler list that begins with the given element . <i > This includes the exception_table_length field . < / i > [CODESPLIT] static void putExceptionTable ( final Handler firstHandler , final ByteVector output ) { output . putShort ( getExceptionTableLength ( firstHandler ) ) ; Handler handler = firstHandler ; while ( handler != null ) { output . putShort ( handler . startPc . bytecodeOffset ) . putShort ( handler . endPc . bytecodeOffset ) . putShort ( handler . handlerPc . bytecodeOffset ) . putShort ( handler . catchType ) ; handler = handler . nextHandler ; } }


Input: Collects all interceptors . [CODESPLIT] protected void collectActionInterceptors ( ) { final Collection < ? extends ActionInterceptor > interceptorValues = interceptorsManager . getAllInterceptors ( ) ; interceptors = new ArrayList <> ( ) ; interceptors . addAll ( interceptorValues ) ; interceptors . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


Input: Collects all filters . [CODESPLIT] protected void collectActionFilters ( ) { final Collection < ? extends ActionFilter > filterValues = filtersManager . getAllFilters ( ) ; filters = new ArrayList <> ( ) ; filters . addAll ( filterValues ) ; filters . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


Input: Collects all action results . [CODESPLIT] protected void collectActionResults ( ) { final Collection < ActionResult > resultsValues = resultsManager . getAllActionResults ( ) ; results = new ArrayList <> ( ) ; results . addAll ( resultsValues ) ; results . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }


Input: Collects all action runtime configurations . [CODESPLIT] protected void collectActionRuntimes ( ) { actions = actionsManager . getAllActionRuntimes ( ) ; actions . sort ( Comparator . comparing ( ActionRuntime :: getActionPath ) ) ; }


Input: Resolves nested property name to the very last indexed property . If forced <code > null< / code > or non - existing properties will be created . [CODESPLIT] protected void resolveNestedProperties ( final BeanProperty bp ) { String name = bp . name ; int dotNdx ; while ( ( dotNdx = indexOfDot ( name ) ) != - 1 ) { bp . last = false ; bp . setName ( name . substring ( 0 , dotNdx ) ) ; bp . updateBean ( getIndexProperty ( bp ) ) ; name = name . substring ( dotNdx + 1 ) ; } bp . last = true ; bp . setName ( name ) ; }


Input: ---------------------------------------------------------------- simple property [CODESPLIT] @ Override public boolean hasSimpleProperty ( final Object bean , final String property ) { return hasSimpleProperty ( new BeanProperty ( this , bean , property ) ) ; }


Input: Sets a value of simple property . [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) protected void setSimpleProperty ( final BeanProperty bp , final Object value ) { Setter setter = bp . getSetter ( isDeclared ) ; // try: setter if ( setter != null ) { invokeSetter ( setter , bp , value ) ; return ; } // try: put("property", value) if ( bp . isMap ( ) ) { ( ( Map ) bp . bean ) . put ( bp . name , value ) ; return ; } if ( isSilent ) { return ; } throw new BeanException ( "Simple property not found: " + bp . name , bp ) ; }


Input: ---------------------------------------------------------------- indexed property [CODESPLIT] protected boolean hasIndexProperty ( final BeanProperty bp ) { if ( bp . bean == null ) { return false ; } String indexString = extractIndex ( bp ) ; if ( indexString == null ) { return hasSimpleProperty ( bp ) ; } Object resultBean = getSimpleProperty ( bp ) ; if ( resultBean == null ) { return false ; } // try: property[index] if ( resultBean . getClass ( ) . isArray ( ) ) { int index = parseInt ( indexString , bp ) ; return ( index >= 0 ) && ( index < Array . getLength ( resultBean ) ) ; } // try: list.get(index) if ( resultBean instanceof List ) { int index = parseInt ( indexString , bp ) ; return ( index >= 0 ) && ( index < ( ( List ) resultBean ) . size ( ) ) ; } if ( resultBean instanceof Map ) { return ( ( Map ) resultBean ) . containsKey ( indexString ) ; } // failed return false ; }


Input: Get non - nested property value : either simple or indexed property . If forced missing bean will be created if possible . [CODESPLIT] protected Object getIndexProperty ( final BeanProperty bp ) { bp . indexString = extractIndex ( bp ) ; Object value = _getIndexProperty ( bp ) ; bp . indexString = null ; return value ; }


Input: Sets indexed or regular properties ( no nested! ) . [CODESPLIT] protected void setIndexProperty ( final BeanProperty bp , final Object value ) { bp . indexString = extractIndex ( bp ) ; _setIndexProperty ( bp , value ) ; bp . indexString = null ; }


Input: ---------------------------------------------------------------- SET [CODESPLIT] @ Override public void setProperty ( final Object bean , final String name , final Object value ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! isSilent ) { resolveNestedProperties ( beanProperty ) ; setIndexProperty ( beanProperty , value ) ; } else { try { resolveNestedProperties ( beanProperty ) ; setIndexProperty ( beanProperty , value ) ; } catch ( Exception ignore ) { } } }


Input: Returns value of bean s property . [CODESPLIT] @ Override public < T > T getProperty ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! isSilent ) { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } else { try { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } catch ( Exception ignore ) { return null ; } } }


Input: ---------------------------------------------------------------- HAS [CODESPLIT] @ Override public boolean hasProperty ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! resolveExistingNestedProperties ( beanProperty ) ) { return false ; } return hasIndexProperty ( beanProperty ) ; }


Input: ---------------------------------------------------------------- type [CODESPLIT] @ Override public Class < ? > getPropertyType ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! resolveExistingNestedProperties ( beanProperty ) ) { return null ; } hasIndexProperty ( beanProperty ) ; return extractType ( beanProperty ) ; }


Input: Extract the first name of this reference . [CODESPLIT] @ Override public String extractThisReference ( final String propertyName ) { int ndx = StringUtil . indexOfChars ( propertyName , INDEX_CHARS ) ; if ( ndx == - 1 ) { return propertyName ; } return propertyName . substring ( 0 , ndx ) ; }


Input: Returns buffered writer . Buffer will be created if not already used . [CODESPLIT] @ Override public PrintWriter getWriter ( ) { if ( writer == null ) { writer = new FastCharArrayWriter ( ) ; printWriter = new PrintWriter ( writer ) ; } return printWriter ; }


Input: Resets the builder so it can be used again . Not everything is reset : object references and column alias type is not . [CODESPLIT] protected void resetSoft ( ) { columnCount = 0 ; paramCount = 0 ; hintCount = 0 ; if ( tableRefs != null ) { tableRefs . clear ( ) ; } //		objectRefs = null; if ( columnData != null ) { columnData . clear ( ) ; } if ( parameters != null ) { parameters . clear ( ) ; } if ( hints != null ) { hints . clear ( ) ; } //columnAliasType = defaultColumnAliasType; }


Input: Saves object reference . [CODESPLIT] public void setObjectReference ( final String name , final Object object ) { if ( objectRefs == null ) { objectRefs = new HashMap <> ( ) ; } objectRefs . put ( name , object ) ; }


Input: Returns object reference . [CODESPLIT] public Object getObjectReference ( final String name ) { if ( objectRefs == null ) { return null ; } return objectRefs . get ( name ) ; }


Input: Lookups for object reference and throws an exception if reference doesn t exist . [CODESPLIT] public Object lookupObject ( final String ref ) { Object value = getObjectReference ( ref ) ; if ( value == null ) { throw new DbSqlBuilderException ( "Invalid object reference: " + ref ) ; } return value ; }


Input: Returns entity descriptor for provided table reference . [CODESPLIT] public DbEntityDescriptor getTableDescriptor ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . desc ; }


Input: Finds entity descriptor of a table that contains provided column reference . [CODESPLIT] public DbEntityDescriptor findTableDescriptorByColumnRef ( final String columnRef ) { for ( Map . Entry < String , TableRefData > entry : tableRefs . entrySet ( ) ) { DbEntityDescriptor ded = entry . getValue ( ) . desc ; if ( ded . findByPropertyName ( columnRef ) != null ) { return ded ; } } return null ; }


Input: Returns table alias for provided table reference . [CODESPLIT] public String getTableAlias ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . alias ; }


Input: Registers table reference for provided entity . [CODESPLIT] public void registerTableReference ( final String tableReference , final DbEntityDescriptor ded , final String tableAlias ) { if ( tableRefs == null ) { tableRefs = new HashMap <> ( ) ; } TableRefData t = new TableRefData ( ded , tableAlias ) ; if ( tableRefs . put ( tableReference , t ) != null ) { throw new DbSqlBuilderException ( "Duplicated table reference: " + tableReference ) ; } }


Input: Adds query parameter . [CODESPLIT] public void addParameter ( final String name , final Object value , final DbEntityColumnDescriptor dec ) { if ( parameters == null ) { parameters = new HashMap <> ( ) ; } parameters . put ( name , new ParameterValue ( value , dec ) ) ; }


Input: Lookups for entity name and throws exception if entity name not found . [CODESPLIT] protected DbEntityDescriptor lookupName ( final String entityName ) { DbEntityDescriptor ded = entityManager . lookupName ( entityName ) ; if ( ded == null ) { throw new DbSqlBuilderException ( "Entity name not registered: " + entityName ) ; } return ded ; }


Input: Lookups for table reference and throws an exception if table reference not found . [CODESPLIT] protected DbEntityDescriptor lookupTableRef ( final String tableRef ) { DbEntityDescriptor ded = getTableDescriptor ( tableRef ) ; if ( ded == null ) { throw new DbSqlBuilderException ( "Table reference not used in this query: " + tableRef ) ; } return ded ; }


Input: Defines parameter with name and its value . [CODESPLIT] protected void defineParameter ( final StringBuilder query , String name , final Object value ) { if ( name == null ) { name = getNextParameterName ( ) ; } query . append ( ' ' ) . append ( name ) ; addParameter ( name , value , null ) ; }


Input: Registers a hint . [CODESPLIT] public void registerHint ( final String hint ) { if ( hints == null ) { hints = new ArrayList <> ( hintCount ) ; } hints . add ( hint ) ; }


Input: Detects circular dependencies and pushes value as current type context . [CODESPLIT] @ Override public final boolean serialize ( final JsonContext jsonContext , final T value ) { if ( jsonContext . pushValue ( value ) ) { // prevent circular dependencies return false ; } serializeValue ( jsonContext , value ) ; jsonContext . popValue ( ) ; return true ; }


Input: ---------------------------------------------------------------- inject [CODESPLIT] @ Override public void inject ( final ActionRequest actionRequest , final Targets targets ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; instancesInjector . inject ( actionRequest , targets ) ; if ( injectAttributes ) { injectAttributes ( servletRequest , targets ) ; } if ( injectParameters ) { injectParameters ( servletRequest , targets ) ; injectUploadedFiles ( servletRequest , targets ) ; } actionPathMacroInjector . inject ( actionRequest , targets ) ; }


Input: Injects request attributes . [CODESPLIT] protected void injectAttributes ( final HttpServletRequest servletRequest , final Targets targets ) { final Enumeration < String > attributeNames = servletRequest . getAttributeNames ( ) ; while ( attributeNames . hasMoreElements ( ) ) { final String attrName = attributeNames . nextElement ( ) ; targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( attrName ) ; if ( name != null ) { final Object attrValue = servletRequest . getAttribute ( attrName ) ; target . writeValue ( name , attrValue , true ) ; } } ) ; } }


Input: Inject request parameters . [CODESPLIT] protected void injectParameters ( final HttpServletRequest servletRequest , final Targets targets ) { final boolean encode = encodeGetParams && servletRequest . getMethod ( ) . equals ( "GET" ) ; final Enumeration < String > paramNames = servletRequest . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { String [ ] paramValues = servletRequest . getParameterValues ( paramName ) ; paramValues = ServletUtil . prepareParameters ( paramValues , treatEmptyParamsAsNull , ignoreEmptyRequestParams ) ; if ( paramValues != null ) { if ( encode ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final String p = paramValues [ j ] ; if ( p != null ) { final String encoding = madvocEncoding . getEncoding ( ) ; paramValues [ j ] = StringUtil . convertCharset ( p , StringPool . ISO_8859_1 , encoding ) ; } } } final Object value = ( paramValues . length != 1 ? paramValues : paramValues [ 0 ] ) ; target . writeValue ( name , value , true ) ; } } } ) ; } }


Input: Inject uploaded files from multipart request parameters . [CODESPLIT] protected void injectUploadedFiles ( final HttpServletRequest servletRequest , final Targets targets ) { if ( ! ( servletRequest instanceof MultipartRequestWrapper ) ) { return ; } final MultipartRequestWrapper multipartRequest = ( MultipartRequestWrapper ) servletRequest ; if ( ! multipartRequest . isMultipart ( ) ) { return ; } final Enumeration < String > paramNames = multipartRequest . getFileParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { final FileUpload [ ] paramValues = multipartRequest . getFiles ( paramName ) ; if ( ignoreInvalidUploadFiles ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final FileUpload paramValue = paramValues [ j ] ; if ( ( ! paramValue . isValid ( ) ) || ( ! paramValue . isUploaded ( ) ) ) { paramValues [ j ] = null ; } } } final Object value = ( paramValues . length == 1 ? paramValues [ 0 ] : paramValues ) ; target . writeValue ( name , value , true ) ; } } ) ; } }


Input: ---------------------------------------------------------------- outject [CODESPLIT] @ Override public void outject ( final ActionRequest actionRequest , final Targets targets ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; targets . forEachTargetAndOut ( this , ( target , out ) -> { final Object value = target . readValue ( out ) ; servletRequest . setAttribute ( out . name ( ) , value ) ; } ) ; }


Input: Converts property name to column name . [CODESPLIT] public String convertPropertyNameToColumnName ( final String propertyName ) { StringBuilder tableName = new StringBuilder ( propertyName . length ( ) * 2 ) ; if ( splitCamelCase ) { String convertedTableName = Format . fromCamelCase ( propertyName , separatorChar ) ; tableName . append ( convertedTableName ) ; } else { tableName . append ( propertyName ) ; } if ( ! changeCase ) { return tableName . toString ( ) ; } return uppercase ? toUppercase ( tableName ) . toString ( ) : toLowercase ( tableName ) . toString ( ) ; }


Input: Converts column name to property name . [CODESPLIT] public String convertColumnNameToPropertyName ( final String columnName ) { StringBuilder propertyName = new StringBuilder ( columnName . length ( ) ) ; int len = columnName . length ( ) ; if ( splitCamelCase ) { boolean toUpper = false ; for ( int i = 0 ; i < len ; i ++ ) { char c = columnName . charAt ( i ) ; if ( c == separatorChar ) { toUpper = true ; continue ; } if ( toUpper ) { propertyName . append ( Character . toUpperCase ( c ) ) ; toUpper = false ; } else { propertyName . append ( Character . toLowerCase ( c ) ) ; } } return propertyName . toString ( ) ; } return columnName ; }


Input: Applies column naming strategy to given column name hint . Returns full column name . [CODESPLIT] public String applyToColumnName ( final String columnName ) { String propertyName = convertColumnNameToPropertyName ( columnName ) ; return convertPropertyNameToColumnName ( propertyName ) ; }


Input: Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected boolean [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final boolean [ ] target = new boolean [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Boolean > booleanArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final boolean convertedValue = convertType ( element ) ; booleanArrayList . add ( Boolean . valueOf ( convertedValue ) ) ; } final boolean [ ] array = new boolean [ booleanArrayList . size ( ) ] ; for ( int i = 0 ; i < booleanArrayList . size ( ) ; i ++ ) { final Boolean b = booleanArrayList . get ( i ) ; array [ i ] = b . booleanValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }


Input: Stores value in database . Value is casted to sql type . [CODESPLIT] public void storeValue ( final PreparedStatement st , final int index , final Object value , final int dbSqlType ) throws SQLException { T t = TypeConverterManager . get ( ) . convertType ( value , sqlType ) ; set ( st , index , t , dbSqlType ) ; }


Input: Once when value is read from result set prepare it to match destination type . [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) protected < E > E prepareGetValue ( final T t , final Class < E > destinationType ) { if ( t == null ) { return null ; } if ( destinationType == null ) { return ( E ) t ; } return TypeConverterManager . get ( ) . convertType ( t , destinationType ) ; }


Input: Returns all action wrappers . Returns a copy in new set . [CODESPLIT] protected Set < T > getAll ( ) { final Set < T > set = new HashSet <> ( wrappers . size ( ) ) ; set . addAll ( wrappers . values ( ) ) ; return set ; }


Input: Resolves single wrapper . Creates new wrapper instance if not already registered . Does not expand the wrappers . [CODESPLIT] public T resolve ( final Class < ? extends T > wrapperClass ) { String wrapperClassName = wrapperClass . getName ( ) ; T wrapper = lookup ( wrapperClassName ) ; if ( wrapper == null ) { wrapper = createWrapper ( wrapperClass ) ; initializeWrapper ( wrapper ) ; wrappers . put ( wrapperClassName , wrapper ) ; } return wrapper ; }


Input: Resolves wrappers . Unregistered wrappers will be registered . Returned array may be different size than size of provided array due to { [CODESPLIT] public T [ ] resolveAll ( Class < ? extends T > [ ] wrapperClasses ) { if ( wrapperClasses == null ) { return null ; } wrapperClasses = expand ( wrapperClasses ) ; T [ ] result = createArray ( wrapperClasses . length ) ; for ( int i = 0 ; i < wrapperClasses . length ; i ++ ) { result [ i ] = resolve ( wrapperClasses [ i ] ) ; } return result ; }


Input: Replaces all { [CODESPLIT] protected Class < ? extends T > [ ] expand ( final Class < ? extends T > [ ] actionWrappers ) { if ( actionWrappers == null ) { return null ; } List < Class < ? extends T > > list = new ArrayList <> ( actionWrappers . length ) ; list . addAll ( Arrays . asList ( actionWrappers ) ) ; int i = 0 ; while ( i < list . size ( ) ) { Class < ? extends T > wrapperClass = list . get ( i ) ; if ( wrapperClass == null ) { continue ; } if ( ClassUtil . isTypeOf ( wrapperClass , BaseActionWrapperStack . class ) ) { BaseActionWrapperStack stack = ( BaseActionWrapperStack ) resolve ( wrapperClass ) ; list . remove ( i ) ; Class < ? extends T > [ ] stackWrappers = stack . getWrappers ( ) ; if ( stackWrappers != null ) { list . addAll ( i , Arrays . asList ( stackWrappers ) ) ; } i -- ; //continue; } i ++ ; } return list . toArray ( new Class [ 0 ] ) ; }


Input: Creates new wrapper . [CODESPLIT] protected < R extends T > R createWrapper ( final Class < R > wrapperClass ) { try { return ClassUtil . newInstance ( wrapperClass ) ; } catch ( Exception ex ) { throw new MadvocException ( "Invalid Madvoc wrapper: " + wrapperClass , ex ) ; } }


Input: Concatenates a filename to a base path using normal command line style rules . <p > The effect is equivalent to resultant directory after changing directory to the first argument followed by changing directory to the second argument . <p > The first argument is the base path the second is the path to concatenate . The returned path is always normalized via { @link #normalize ( String ) } thus <code > .. < / code > is handled . <p > If <code > pathToAdd< / code > is absolute ( has an absolute prefix ) then it will be normalized and returned . Otherwise the paths will be joined normalized and returned . <p > The output will be the same on both Unix and Windows except for the separator character . <pre > { @code / foo / + bar -- > / foo / bar / foo + bar -- > / foo / bar / foo + / bar -- > / bar / foo + C : / bar -- > C : / bar / foo + C : bar -- > C : bar ( * ) / foo / a / + .. / bar -- > foo / bar / foo / + .. / .. / bar -- > null / foo / + / bar -- > / bar / foo / .. + / bar -- > / bar / foo + bar / c . txt -- > / foo / bar / c . txt / foo / c . txt + bar -- > / foo / c . txt / bar ( ! ) } < / pre > ( * ) Note that the Windows relative drive prefix is unreliable when used with this method . ( ! ) Note that the first parameter must be a path . If it ends with a name then the name will be built into the concatenated path . If this might be a problem use { @link #getFullPath ( String ) } on the base path argument . [CODESPLIT] public static String concat ( final String basePath , final String fullFilenameToAdd ) { return doConcat ( basePath , fullFilenameToAdd , SYSTEM_SEPARATOR ) ; }


Input: Converts all separators to the system separator . [CODESPLIT] public static String separatorsToSystem ( final String path ) { if ( path == null ) { return null ; } if ( SYSTEM_SEPARATOR == WINDOWS_SEPARATOR ) { return separatorsToWindows ( path ) ; } else { return separatorsToUnix ( path ) ; } }


Input: Returns the index of the last directory separator character . <p > This method will handle a file in either Unix or Windows format . The position of the last forward or backslash is returned . <p > The output will be the same irrespective of the machine that the code is running on . [CODESPLIT] public static int indexOfLastSeparator ( final String filename ) { if ( filename == null ) { return - 1 ; } int lastUnixPos = filename . lastIndexOf ( UNIX_SEPARATOR ) ; int lastWindowsPos = filename . lastIndexOf ( WINDOWS_SEPARATOR ) ; return Math . max ( lastUnixPos , lastWindowsPos ) ; }


Input: Does the work of getting the path . [CODESPLIT] private static String doGetPath ( final String filename , final int separatorAdd ) { if ( filename == null ) { return null ; } int prefix = getPrefixLength ( filename ) ; if ( prefix < 0 ) { return null ; } int index = indexOfLastSeparator ( filename ) ; int endIndex = index + separatorAdd ; if ( prefix >= filename . length ( ) || index < 0 || prefix >= endIndex ) { return StringPool . EMPTY ; } return filename . substring ( prefix , endIndex ) ; }


Input: Splits filename into a array of four Strings containing prefix path basename and extension . Path will contain ending separator . [CODESPLIT] public static String [ ] split ( final String filename ) { String prefix = getPrefix ( filename ) ; if ( prefix == null ) { prefix = StringPool . EMPTY ; } int lastSeparatorIndex = indexOfLastSeparator ( filename ) ; int lastExtensionIndex = indexOfExtension ( filename ) ; String path ; String baseName ; String extension ; if ( lastSeparatorIndex == - 1 ) { path = StringPool . EMPTY ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } else { path = filename . substring ( prefix . length ( ) , lastSeparatorIndex + 1 ) ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) + path . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) + path . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } return new String [ ] { prefix , path , baseName , extension } ; }


Input: Resolve <code > ~< / code > in the path . [CODESPLIT] public static String resolveHome ( final String path ) { if ( path . length ( ) == 1 ) { if ( path . charAt ( 0 ) == ' ' ) { return SystemUtil . info ( ) . getHomeDir ( ) ; } return path ; } if ( path . length ( ) >= 2 ) { if ( ( path . charAt ( 0 ) == ' ' ) && ( path . charAt ( 1 ) == File . separatorChar ) ) { return SystemUtil . info ( ) . getHomeDir ( ) + path . substring ( 1 ) ; } } return path ; }


Input: Calculates relative path of target path on base path . [CODESPLIT] public static String relativePath ( final String targetPath , final String basePath ) { return new File ( basePath ) . toPath ( ) . relativize ( new File ( targetPath ) . toPath ( ) ) . toString ( ) ; }


Input: ---------------------------------------------------------------- visitor [CODESPLIT] @ Override public void visit ( final String name , final Object value ) { elements . put ( name , value ) ; }


Input: Registers additional Madvoc components after the registration of default components . [CODESPLIT] public WebApp registerComponent ( final Class < ? > madvocComponent ) { Objects . requireNonNull ( madvocComponent ) ; madvocComponents . add ( ClassConsumer . of ( madvocComponent ) ) ; return this ; }


Input: Registers Madvoc component <i > instance< / i > . Use with caution as injection of components registered after this will fail . [CODESPLIT] public WebApp registerComponent ( final Object madvocComponent ) { Objects . requireNonNull ( madvocComponent ) ; madvocComponentInstances . add ( madvocComponent ) ; return this ; }


Input: Configures the action configurations . [CODESPLIT] public < A extends ActionConfig > WebApp withActionConfig ( final Class < A > actionConfigType , final Consumer < A > actionConfigConsumer ) { withRegisteredComponent ( ActionConfigManager . class , acm -> acm . with ( actionConfigType , actionConfigConsumer ) ) ; return this ; }


Input: Configures a component . While the signature is the same as for { [CODESPLIT] public < T > WebApp withRegisteredComponent ( final Class < T > madvocComponent , final Consumer < T > componentConsumer ) { if ( componentConfigs == null ) { // component is already configured final T component = madvocContainer . lookupComponent ( madvocComponent ) ; if ( component == null ) { throw new MadvocException ( "Component not found: " + madvocComponent . getName ( ) ) ; } componentConsumer . accept ( component ) ; } else { componentConfigs . add ( madvocContainer -> { final T component = madvocContainer . lookupComponent ( madvocComponent ) ; if ( component == null ) { throw new MadvocException ( "Component not found: " + madvocComponent . getName ( ) ) ; } componentConsumer . accept ( component ) ; } ) ; } return this ; }


Input: Initializes and starts web application . [CODESPLIT] public WebApp start ( ) { log = LoggerFactory . getLogger ( WebApp . class ) ; log . debug ( "Initializing Madvoc WebApp" ) ; //// params & props for ( final Map < String , Object > params : paramsList ) { madvocContainer . defineParams ( params ) ; } for ( final Props props : propsList ) { madvocContainer . defineParams ( props ) ; } propsList = null ; //// components registerMadvocComponents ( ) ; madvocComponents . forEach ( madvocComponent -> madvocContainer . registerComponent ( madvocComponent . type ( ) , madvocComponent . consumer ( ) ) ) ; madvocComponents = null ; madvocComponentInstances . forEach ( madvocContainer :: registerComponentInstance ) ; madvocComponentInstances = null ; configureDefaults ( ) ; //// listeners madvocContainer . fireEvent ( Init . class ) ; //// component configuration componentConfigs . accept ( madvocContainer ) ; componentConfigs = null ; initialized ( ) ; madvocContainer . fireEvent ( Start . class ) ; if ( ! madvocRouterConsumers . isEmpty ( ) ) { final MadvocRouter madvocRouter = MadvocRouter . create ( ) ; madvocContainer . registerComponentInstance ( madvocRouter ) ; madvocRouterConsumers . accept ( madvocRouter ) ; } madvocRouterConsumers = null ; started ( ) ; madvocContainer . fireEvent ( Ready . class ) ; ready ( ) ; return this ; }


Input: Configure defaults . [CODESPLIT] protected void configureDefaults ( ) { final ActionConfigManager actionConfigManager = madvocContainer . lookupComponent ( ActionConfigManager . class ) ; actionConfigManager . registerAnnotation ( Action . class ) ; actionConfigManager . registerAnnotation ( RestAction . class ) ; }


Input: Registers default Madvoc components . [CODESPLIT] protected void registerMadvocComponents ( ) { if ( madvocContainer == null ) { throw new MadvocException ( "Madvoc WebApp not initialized." ) ; } log . debug ( "Registering Madvoc WebApp components" ) ; madvocContainer . registerComponent ( MadvocEncoding . class ) ; madvocContainer . registerComponentInstance ( new ServletContextProvider ( servletContext ) ) ; madvocContainer . registerComponent ( ActionConfigManager . class ) ; madvocContainer . registerComponent ( ActionMethodParamNameResolver . class ) ; madvocContainer . registerComponent ( ActionMethodParser . class ) ; madvocContainer . registerComponent ( ActionPathRewriter . class ) ; madvocContainer . registerComponent ( ActionsManager . class ) ; madvocContainer . registerComponent ( ContextInjectorComponent . class ) ; madvocContainer . registerComponent ( InterceptorsManager . class ) ; madvocContainer . registerComponent ( FiltersManager . class ) ; madvocContainer . registerComponent ( MadvocController . class ) ; madvocContainer . registerComponent ( RootPackages . class ) ; madvocContainer . registerComponent ( ResultsManager . class ) ; madvocContainer . registerComponent ( ResultMapper . class ) ; madvocContainer . registerComponent ( ScopeResolver . class ) ; madvocContainer . registerComponent ( ScopeDataInspector . class ) ; madvocContainer . registerComponent ( AsyncActionExecutor . class ) ; madvocContainer . registerComponent ( FileUploader . class ) ; }


Input: Specify excluded jars . [CODESPLIT] public ClassScanner excludeJars ( final String ... excludedJars ) { for ( final String excludedJar : excludedJars ) { rulesJars . exclude ( excludedJar ) ; } return this ; }


Input: Specify included jars . [CODESPLIT] public ClassScanner includeJars ( final String ... includedJars ) { for ( final String includedJar : includedJars ) { rulesJars . include ( includedJar ) ; } return this ; }


Input: Sets included set of names that will be considered during configuration . [CODESPLIT] public ClassScanner includeEntries ( final String ... includedEntries ) { for ( final String includedEntry : includedEntries ) { rulesEntries . include ( includedEntry ) ; } return this ; }


Input: Sets excluded names that narrows included set of packages . [CODESPLIT] public ClassScanner excludeEntries ( final String ... excludedEntries ) { for ( final String excludedEntry : excludedEntries ) { rulesEntries . exclude ( excludedEntry ) ; } return this ; }


Input: Returns <code > true< / code > if some JAR file has to be accepted . [CODESPLIT] protected boolean acceptJar ( final File jarFile ) { String path = jarFile . getAbsolutePath ( ) ; path = FileNameUtil . separatorsToUnix ( path ) ; return rulesJars . match ( path ) ; }


Input: Scans classes inside single JAR archive . Archive is scanned as a zip file . [CODESPLIT] protected void scanJarFile ( final File file ) { final ZipFile zipFile ; try { zipFile = new ZipFile ( file ) ; } catch ( IOException ioex ) { if ( ! ignoreException ) { throw new FindFileException ( "Invalid zip: " + file . getName ( ) , ioex ) ; } return ; } final Enumeration entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { final ZipEntry zipEntry = ( ZipEntry ) entries . nextElement ( ) ; final String zipEntryName = zipEntry . getName ( ) ; try { if ( StringUtil . endsWithIgnoreCase ( zipEntryName , CLASS_FILE_EXT ) ) { final String entryName = prepareEntryName ( zipEntryName , true ) ; final ClassPathEntry classPathEntry = new ClassPathEntry ( entryName , zipFile , zipEntry ) ; try { scanEntry ( classPathEntry ) ; } finally { classPathEntry . closeInputStream ( ) ; } } else if ( includeResources ) { final String entryName = prepareEntryName ( zipEntryName , false ) ; final ClassPathEntry classPathEntry = new ClassPathEntry ( entryName , zipFile , zipEntry ) ; try { scanEntry ( classPathEntry ) ; } finally { classPathEntry . closeInputStream ( ) ; } } } catch ( RuntimeException rex ) { if ( ! ignoreException ) { ZipUtil . close ( zipFile ) ; throw rex ; } } } ZipUtil . close ( zipFile ) ; }


Input: Scans single classpath directory . [CODESPLIT] protected void scanClassPath ( final File root ) { String rootPath = root . getAbsolutePath ( ) ; if ( ! rootPath . endsWith ( File . separator ) ) { rootPath += File . separatorChar ; } final FindFile ff = FindFile . create ( ) . includeDirs ( false ) . recursive ( true ) . searchPath ( rootPath ) ; File file ; while ( ( file = ff . nextFile ( ) ) != null ) { final String filePath = file . getAbsolutePath ( ) ; try { if ( StringUtil . endsWithIgnoreCase ( filePath , CLASS_FILE_EXT ) ) { scanClassFile ( filePath , rootPath , file , true ) ; } else if ( includeResources ) { scanClassFile ( filePath , rootPath , file , false ) ; } } catch ( RuntimeException rex ) { if ( ! ignoreException ) { throw rex ; } } } }


Input: Prepares resource and class names . For classes it strips . class from the end and converts all ( back ) slashes to dots . For resources it replaces all backslashes to slashes . [CODESPLIT] protected String prepareEntryName ( final String name , final boolean isClass ) { String entryName = name ; if ( isClass ) { entryName = name . substring ( 0 , name . length ( ) - 6 ) ; // 6 == ".class".length() entryName = StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; entryName = StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; } else { entryName = ' ' + StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; } return entryName ; }


Input: If entry name is { [CODESPLIT] protected void scanEntry ( final ClassPathEntry classPathEntry ) { if ( ! acceptEntry ( classPathEntry . name ( ) ) ) { return ; } try { onEntry ( classPathEntry ) ; } catch ( Exception ex ) { throw new FindFileException ( "Scan entry error: " + classPathEntry , ex ) ; } }


Input: Returns type signature bytes used for searching in class file . [CODESPLIT] public static byte [ ] bytecodeSignatureOfType ( final Class type ) { final String name = ' ' + type . getName ( ) . replace ( ' ' , ' ' ) + ' ' ; return name . getBytes ( ) ; }


Input: Scans URLs . If ( #ignoreExceptions } is set exceptions per one URL will be ignored and loops continues . [CODESPLIT] public ClassScanner scan ( final URL ... urls ) { for ( final URL url : urls ) { final File file = FileUtil . toContainerFile ( url ) ; if ( file == null ) { if ( ! ignoreException ) { throw new FindFileException ( "URL is not a valid file: " + url ) ; } } else { filesToScan . add ( file ) ; } } return this ; }


Input: Scans provided paths . [CODESPLIT] public ClassScanner scan ( final String ... paths ) { for ( final String path : paths ) { filesToScan . add ( new File ( path ) ) ; } return this ; }


Input: Starts with the scanner . [CODESPLIT] public void start ( ) { if ( detectEntriesMode ) { rulesEntries . detectMode ( ) ; } filesToScan . forEach ( file -> { final String path = file . getAbsolutePath ( ) ; if ( StringUtil . endsWithIgnoreCase ( path , JAR_FILE_EXT ) ) { if ( ! acceptJar ( file ) ) { return ; } scanJarFile ( file ) ; } else if ( file . isDirectory ( ) ) { scanClassPath ( file ) ; } } ) ; }


Input: Returns String characters in most performing way . If possible the inner <code > char [] < / code > will be returned . If not <code > toCharArray () < / code > will be called . Returns <code > null< / code > when argument is <code > null< / code > . [CODESPLIT] public static char [ ] getChars ( final String string ) { if ( string == null ) { return null ; } if ( ! HAS_UNSAFE || ! JoddCore . unsafeUsageEnabled ) { return string . toCharArray ( ) ; } return UnsafeInternal . unsafeGetChars ( string ) ; }


Input: { [CODESPLIT] @ Override public DbJtxTransaction requestTransaction ( final JtxTransactionMode mode , final Object scope ) { return ( DbJtxTransaction ) super . requestTransaction ( mode , scope ) ; }


Input: Builds new transaction instance . [CODESPLIT] @ Override protected JtxTransaction createNewTransaction ( final JtxTransactionMode tm , final Object scope , final boolean active ) { return new DbJtxTransaction ( this , tm , scope , active ) ; }


Input: Lookups the scope instance of given scope annotation . If instance does not exist it will be created cached and returned . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < S extends MadvocScope > S defaultOrScopeType ( final Class < S > scopeClass ) { if ( scopeClass == null ) { return ( S ) getOrInitScope ( RequestScope . class ) ; } return ( S ) getOrInitScope ( scopeClass ) ; }


Input: Performs search for the scope class and returns it s instance . [CODESPLIT] protected MadvocScope getOrInitScope ( final Class < ? extends MadvocScope > madvocScopeType ) { for ( final MadvocScope s : allScopes ) { if ( s . getClass ( ) . equals ( madvocScopeType ) ) { return s ; } } // new scope detected final MadvocScope newScope ; try { newScope = madpc . createBean ( madvocScopeType ) ; } catch ( Exception ex ) { throw new MadvocException ( "Unable to create scope: " + madvocScopeType , ex ) ; } allScopes . add ( newScope ) ; return newScope ; }


Input: Finds a given scope and consumes it . [CODESPLIT] public void forScope ( final Class < ? extends MadvocScope > scopeType , final Consumer < MadvocScope > madvocScopeConsumer ) { final MadvocScope scope = getOrInitScope ( scopeType ) ; madvocScopeConsumer . accept ( scope ) ; }


Input: Parses { @link Message } and extracts all data for the received message . [CODESPLIT] protected void parseMessage ( final Message msg , final boolean envelope ) throws MessagingException , IOException { // flags flags ( msg . getFlags ( ) ) ; // message number messageNumber ( msg . getMessageNumber ( ) ) ; if ( msg instanceof MimeMessage ) { messageId ( ( ( MimeMessage ) msg ) . getMessageID ( ) ) ; } // single from final Address [ ] addresses = msg . getFrom ( ) ; if ( addresses != null && addresses . length > 0 ) { from ( addresses [ 0 ] ) ; } // reply-to replyTo ( msg . getReplyTo ( ) ) ; // recipients to ( msg . getRecipients ( Message . RecipientType . TO ) ) ; cc ( msg . getRecipients ( Message . RecipientType . CC ) ) ; // no BCC because this will always be empty // subject subject ( msg . getSubject ( ) ) ; // dates receivedDate ( msg . getReceivedDate ( ) ) ; sentDate ( msg . getSentDate ( ) ) ; // headers headers ( msg . getAllHeaders ( ) ) ; // content if ( ! envelope ) { processPart ( msg ) ; } }


Input: Process part of the received message . All parts are simply added to the { @link ReceivedEmail } i . e . hierarchy is not saved . [CODESPLIT] protected void processPart ( final Part part ) throws MessagingException , IOException { final Object content = part . getContent ( ) ; if ( content instanceof String ) { addStringContent ( part , ( String ) content ) ; } else if ( content instanceof Multipart ) { processMultipart ( ( Multipart ) content ) ; } else if ( content instanceof InputStream ) { addAttachment ( part , ( InputStream ) content , attachmentStorage ) ; } else if ( content instanceof MimeMessage ) { final MimeMessage mimeMessage = ( MimeMessage ) content ; attachedMessage ( new ReceivedEmail ( mimeMessage , false , attachmentStorage ) ) ; } else { addAttachment ( part , part . getInputStream ( ) , attachmentStorage ) ; } }


Input: Process the { @link Multipart } . [CODESPLIT] private void processMultipart ( final Multipart mp ) throws MessagingException , IOException { final int count = mp . getCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final Part innerPart = mp . getBodyPart ( i ) ; processPart ( innerPart ) ; } }


Input: Adds String content as either { @link EmailAttachment } or as { @link EmailMessage } . [CODESPLIT] private void addStringContent ( final Part part , final String content ) throws MessagingException , UnsupportedEncodingException { final String contentType = part . getContentType ( ) ; final String encoding = EmailUtil . extractEncoding ( contentType , StringPool . US_ASCII ) ; final String disposition = part . getDisposition ( ) ; if ( disposition != null && disposition . equalsIgnoreCase ( Part . ATTACHMENT ) ) { addAttachment ( part , content . getBytes ( encoding ) ) ; } else { final String mimeType = EmailUtil . extractMimeType ( contentType ) ; message ( content , mimeType , encoding ) ; } }


Input: Returns the Content - ID of this { @link Part } . Returns { @code null } if none present . [CODESPLIT] protected static String parseContentId ( final Part part ) throws MessagingException { if ( part instanceof MimePart ) { final MimePart mp = ( MimePart ) part ; return mp . getContentID ( ) ; } else { return null ; } }


Input: Returns { @code true } if the { @link Part } is inline . [CODESPLIT] protected static boolean parseInline ( final Part part ) throws MessagingException { if ( part instanceof MimePart ) { final String dispositionId = part . getDisposition ( ) ; return dispositionId != null && dispositionId . equalsIgnoreCase ( "inline" ) ; } return false ; }


Input: Adds received attachment . [CODESPLIT] private ReceivedEmail addAttachment ( final Part part , final InputStream content , final File attachmentStorage ) throws MessagingException , IOException { final EmailAttachmentBuilder builder = addAttachmentInfo ( part ) ; builder . content ( content , part . getContentType ( ) ) ; if ( attachmentStorage != null ) { String name = messageId + "-" + ( this . attachments ( ) . size ( ) + 1 ) ; return storeAttachment ( builder . buildFileDataSource ( name , attachmentStorage ) ) ; } return storeAttachment ( builder . buildByteArrayDataSource ( ) ) ; }


Input: Adds received attachment . [CODESPLIT] private ReceivedEmail addAttachment ( final Part part , final byte [ ] content ) throws MessagingException { final EmailAttachmentBuilder builder = addAttachmentInfo ( part ) ; builder . content ( content , part . getContentType ( ) ) ; final EmailAttachment < ByteArrayDataSource > attachment = builder . buildByteArrayDataSource ( ) ; attachment . setSize ( content . length ) ; return storeAttachment ( attachment ) ; }


Input: Creates { @link EmailAttachmentBuilder } from { @link Part } and sets Content ID inline and name . [CODESPLIT] private static EmailAttachmentBuilder addAttachmentInfo ( final Part part ) throws MessagingException { final String fileName = EmailUtil . resolveFileName ( part ) ; final String contentId = parseContentId ( part ) ; final boolean isInline = parseInline ( part ) ; return new EmailAttachmentBuilder ( ) . name ( fileName ) . contentId ( contentId ) . inline ( isInline ) ; }


Input: Encodes a raw byte array into a BASE64 <code > char [] < / code > . [CODESPLIT] public static char [ ] encodeToChar ( final byte [ ] arr , final boolean lineSeparator ) { int len = arr != null ? arr . length : 0 ; if ( len == 0 ) { return new char [ 0 ] ; } int evenlen = ( len / 3 ) * 3 ; int cnt = ( ( len - 1 ) / 3 + 1 ) << 2 ; int destLen = cnt + ( lineSeparator ? ( cnt - 1 ) / 76 << 1 : 0 ) ; char [ ] dest = new char [ destLen ] ; for ( int s = 0 , d = 0 , cc = 0 ; s < evenlen ; ) { int i = ( arr [ s ++ ] & 0xff ) << 16 | ( arr [ s ++ ] & 0xff ) << 8 | ( arr [ s ++ ] & 0xff ) ; dest [ d ++ ] = CHARS [ ( i >>> 18 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ ( i >>> 12 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ i & 0x3f ] ; if ( lineSeparator && ( ++ cc == 19 ) && ( d < ( destLen - 2 ) ) ) { dest [ d ++ ] = ' ' ; dest [ d ++ ] = ' ' ; cc = 0 ; } } int left = len - evenlen ; // 0 - 2. if ( left > 0 ) { int i = ( ( arr [ evenlen ] & 0xff ) << 10 ) | ( left == 2 ? ( ( arr [ len - 1 ] & 0xff ) << 2 ) : 0 ) ; dest [ destLen - 4 ] = CHARS [ i >> 12 ] ; dest [ destLen - 3 ] = CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ destLen - 2 ] = left == 2 ? CHARS [ i & 0x3f ] : ' ' ; dest [ destLen - 1 ] = ' ' ; } return dest ; }


Input: Decodes a BASE64 encoded char array . [CODESPLIT] public static byte [ ] decode ( final char [ ] arr ) { int length = arr . length ; if ( length == 0 ) { return new byte [ 0 ] ; } int sndx = 0 , endx = length - 1 ; int pad = arr [ endx ] == ' ' ? ( arr [ endx - 1 ] == ' ' ? 2 : 1 ) : 0 ; int cnt = endx - sndx + 1 ; int sepCnt = length > 76 ? ( arr [ 76 ] == ' ' ? cnt / 78 : 0 ) << 1 : 0 ; int len = ( ( cnt - sepCnt ) * 6 >> 3 ) - pad ; byte [ ] dest = new byte [ len ] ; int d = 0 ; for ( int cc = 0 , eLen = ( len / 3 ) * 3 ; d < eLen ; ) { int i = INV [ arr [ sndx ++ ] ] << 18 | INV [ arr [ sndx ++ ] ] << 12 | INV [ arr [ sndx ++ ] ] << 6 | INV [ arr [ sndx ++ ] ] ; dest [ d ++ ] = ( byte ) ( i >> 16 ) ; dest [ d ++ ] = ( byte ) ( i >> 8 ) ; dest [ d ++ ] = ( byte ) i ; if ( sepCnt > 0 && ++ cc == 19 ) { sndx += 2 ; cc = 0 ; } } if ( d < len ) { int i = 0 ; for ( int j = 0 ; sndx <= endx - pad ; j ++ ) { i |= INV [ arr [ sndx ++ ] ] << ( 18 - j * 6 ) ; } for ( int r = 16 ; d < len ; r -= 8 ) { dest [ d ++ ] = ( byte ) ( i >> r ) ; } } return dest ; }


Input: Encodes a raw byte array into a BASE64 <code > char [] < / code > . [CODESPLIT] public static byte [ ] encodeToByte ( final byte [ ] arr , final boolean lineSep ) { int len = arr != null ? arr . length : 0 ; if ( len == 0 ) { return new byte [ 0 ] ; } int evenlen = ( len / 3 ) * 3 ; int cnt = ( ( len - 1 ) / 3 + 1 ) << 2 ; int destlen = cnt + ( lineSep ? ( cnt - 1 ) / 76 << 1 : 0 ) ; byte [ ] dest = new byte [ destlen ] ; for ( int s = 0 , d = 0 , cc = 0 ; s < evenlen ; ) { int i = ( arr [ s ++ ] & 0xff ) << 16 | ( arr [ s ++ ] & 0xff ) << 8 | ( arr [ s ++ ] & 0xff ) ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 18 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 12 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ i & 0x3f ] ; if ( lineSep && ++ cc == 19 && d < destlen - 2 ) { dest [ d ++ ] = ' ' ; dest [ d ++ ] = ' ' ; cc = 0 ; } } int left = len - evenlen ; if ( left > 0 ) { int i = ( ( arr [ evenlen ] & 0xff ) << 10 ) | ( left == 2 ? ( ( arr [ len - 1 ] & 0xff ) << 2 ) : 0 ) ; dest [ destlen - 4 ] = ( byte ) CHARS [ i >> 12 ] ; dest [ destlen - 3 ] = ( byte ) CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ destlen - 2 ] = left == 2 ? ( byte ) CHARS [ i & 0x3f ] : ( byte ) ' ' ; dest [ destlen - 1 ] = ' ' ; } return dest ; }


Input: ---------------------------------------------------------------- string [CODESPLIT] public static String encodeToString ( final String s ) { return new String ( encodeToChar ( StringUtil . getBytes ( s ) , false ) ) ; }


Input: Generates new CSRF token and puts it in the session . Returns generated token value . [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public static String prepareCsrfToken ( final HttpSession session , final int timeToLive ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( tokenSet == null ) { tokenSet = new HashSet <> ( ) ; session . setAttribute ( CSRF_TOKEN_SET , tokenSet ) ; } String value ; boolean unique ; do { value = RandomString . get ( ) . randomAlphaNumeric ( 32 ) ; assureSize ( tokenSet ) ; unique = tokenSet . add ( new Token ( value , timeToLive ) ) ; } while ( ! unique ) ; return value ; }


Input: Removes expired tokens if token set is full . [CODESPLIT] protected static void assureSize ( final Set < Token > tokenSet ) { if ( tokenSet . size ( ) < maxTokensPerSession ) { return ; } long validUntilMin = Long . MAX_VALUE ; Token tokenToRemove = null ; Iterator < Token > iterator = tokenSet . iterator ( ) ; while ( iterator . hasNext ( ) ) { Token token = iterator . next ( ) ; if ( token . isExpired ( ) ) { iterator . remove ( ) ; continue ; } if ( token . validUntil < validUntilMin ) { validUntilMin = token . validUntil ; tokenToRemove = token ; } } if ( ( tokenToRemove != null ) && ( tokenSet . size ( ) >= maxTokensPerSession ) ) { tokenSet . remove ( tokenToRemove ) ; } }


Input: Checks if { [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public static boolean checkCsrfToken ( final HttpServletRequest request , final String tokenName ) { String tokenValue = request . getParameter ( tokenName ) ; return checkCsrfToken ( request . getSession ( ) , tokenValue ) ; }


Input: Checks token value . C [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public static boolean checkCsrfToken ( final HttpSession session , final String tokenValue ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( ( tokenSet == null ) && ( tokenValue == null ) ) { return true ; } if ( ( tokenSet == null ) || ( tokenValue == null ) ) { return false ; } boolean found = false ; Iterator < Token > it = tokenSet . iterator ( ) ; while ( it . hasNext ( ) ) { Token t = it . next ( ) ; if ( t . isExpired ( ) ) { it . remove ( ) ; continue ; } if ( t . getValue ( ) . equals ( tokenValue ) ) { it . remove ( ) ; found = true ; } } return found ; }


Input: Creates <code > BeanCopy< / code > with given <code > Map< / code > as a source . [CODESPLIT] public static BeanCopy fromMap ( final Map source ) { BeanCopy beanCopy = new BeanCopy ( source ) ; beanCopy . isSourceMap = true ; return beanCopy ; }


Input: Defines source detects a map . [CODESPLIT] public static BeanCopy from ( final Object source ) { BeanCopy beanCopy = new BeanCopy ( source ) ; beanCopy . isSourceMap = source instanceof Map ; return beanCopy ; }


Input: Performs the copying . [CODESPLIT] public void copy ( ) { beanUtil = new BeanUtilBean ( ) . declared ( declared ) . forced ( forced ) . silent ( true ) ; visit ( ) ; }


Input: Copies single property to the destination . Exceptions are ignored so copying continues if destination does not have some of the sources properties . [CODESPLIT] @ Override protected boolean visitProperty ( String name , final Object value ) { if ( isTargetMap ) { name = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET ; } beanUtil . setProperty ( destination , name , value ) ; return true ; }


Input: Parses content using Lagarto and { [CODESPLIT] @ Override protected final char [ ] parse ( final char [ ] content , final HttpServletRequest request ) { LagartoParsingProcessor lpp = createParsingProcessor ( ) ; if ( lpp == null ) { return content ; } lpp . init ( content ) ; return lpp . parse ( request ) ; }


Input: Resolves and registers table references . [CODESPLIT] @ Override public void init ( final TemplateData templateData ) { super . init ( templateData ) ; if ( entity != null ) { ded = lookupType ( entity ) ; } else { Object object = templateData . getObjectReference ( entityName ) ; if ( object != null ) { ded = lookupType ( resolveClass ( object ) ) ; } else { ded = lookupName ( entityName ) ; } } String tableReference = this . tableReference ; if ( tableReference == null ) { tableReference = tableAlias ; } if ( tableReference == null ) { tableReference = entityName ; } if ( tableReference == null ) { tableReference = ded . getEntityName ( ) ; } templateData . registerTableReference ( tableReference , ded , tableAlias ) ; }


Input: Resolves and registers scope from a scope type . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < S extends Scope > S resolveScope ( final Class < S > scopeType ) { S scope = ( S ) scopes . get ( scopeType ) ; if ( scope == null ) { try { scope = newInternalInstance ( scopeType , ( PetiteContainer ) this ) ; } catch ( Exception ex ) { throw new PetiteException ( "Invalid Petite scope: " + scopeType . getName ( ) , ex ) ; } registerScope ( scopeType , scope ) ; scopes . put ( scopeType , scope ) ; } return scope ; }


Input: Creates new instance of given type . In the first try it tries to use constructor with a { [CODESPLIT] private < T > T newInternalInstance ( final Class < T > type , final PetiteContainer petiteContainer ) throws Exception { T t = null ; // first try ctor(PetiteContainer) try { Constructor < T > ctor = type . getConstructor ( PetiteContainer . class ) ; t = ctor . newInstance ( petiteContainer ) ; } catch ( NoSuchMethodException nsmex ) { // ignore } // if first try failed, try default ctor if ( t == null ) { return ClassUtil . newInstance ( type ) ; } return t ; }


Input: Registers new scope . It is not necessary to manually register scopes since they become registered on first scope resolving . However it is possible to pre - register some scopes or to <i > replace< / i > one scope type with another . Replacing may be important for testing purposes when using container - depended scopes . [CODESPLIT] public void registerScope ( final Class < ? extends Scope > scopeType , final Scope scope ) { scopes . put ( scopeType , scope ) ; }


Input: Lookups for { [CODESPLIT] public BeanDefinition lookupBeanDefinition ( final String name ) { BeanDefinition beanDefinition = beans . get ( name ) ; // try alt bean names if ( beanDefinition == null ) { if ( petiteConfig . isUseAltBeanNames ( ) ) { beanDefinition = beansAlt . get ( name ) ; } } return beanDefinition ; }


Input: Lookups for first founded { [CODESPLIT] protected BeanDefinition lookupBeanDefinitions ( final BeanReferences beanReferences ) { final int total = beanReferences . size ( ) ; for ( int i = 0 ; i < total ; i ++ ) { final String name = beanReferences . name ( i ) ; BeanDefinition beanDefinition = lookupBeanDefinition ( name ) ; if ( beanDefinition != null ) { return beanDefinition ; } } return null ; }


Input: Lookups for existing { [CODESPLIT] protected BeanDefinition lookupExistingBeanDefinition ( final String name ) { BeanDefinition beanDefinition = lookupBeanDefinition ( name ) ; if ( beanDefinition == null ) { throw new PetiteException ( "Bean not found: " + name ) ; } return beanDefinition ; }


Input: Creates { [CODESPLIT] protected < T > BeanDefinition createBeanDefinitionForRegistration ( final String name , final Class < T > type , final Scope scope , final WiringMode wiringMode , final Consumer < T > consumer ) { return new BeanDefinition <> ( name , type , scope , wiringMode , consumer ) ; }


Input: Creates { [CODESPLIT] protected < T > BeanDefinition createBeandDefinitionForExternalBeans ( final Class < T > type , final WiringMode wiringMode ) { final String name = resolveBeanName ( type ) ; return new BeanDefinition <> ( name , type , null , wiringMode , null ) ; }


Input: Registers a bean using provided class that is annotated . [CODESPLIT] public BeanDefinition registerPetiteBean ( final Class type ) { return registerPetiteBean ( type , null , null , null , false , null ) ; }


Input: Registers a bean using provided class that is annotated . [CODESPLIT] public < T > BeanDefinition < T > registerPetiteBean ( final Class < T > type , final Consumer < T > consumer ) { return registerPetiteBean ( type , null , null , null , false , consumer ) ; }


Input: Registers or defines a bean . [CODESPLIT] public < T > BeanDefinition < T > registerPetiteBean ( final Class < T > type , String name , Class < ? extends Scope > scopeType , WiringMode wiringMode , final boolean define , final Consumer < T > consumer ) { if ( name == null ) { name = resolveBeanName ( type ) ; } if ( wiringMode == null ) { wiringMode = annotationResolver . resolveBeanWiringMode ( type ) ; } if ( wiringMode == WiringMode . DEFAULT ) { wiringMode = petiteConfig . getDefaultWiringMode ( ) ; } if ( scopeType == null ) { scopeType = annotationResolver . resolveBeanScopeType ( type ) ; } if ( scopeType == null ) { scopeType = SingletonScope . class ; } // remove existing bean BeanDefinition existing = removeBean ( name ) ; if ( existing != null ) { if ( petiteConfig . getDetectDuplicatedBeanNames ( ) ) { throw new PetiteException ( "Duplicated bean name detected while registering class '" + type . getName ( ) + "'. Petite bean class '" + existing . type . getName ( ) + "' is already registered with the name: " + name ) ; } } // check if type is valid if ( type . isInterface ( ) ) { throw new PetiteException ( "PetiteBean can not be an interface: " + type . getName ( ) ) ; } // registration if ( log . isDebugEnabled ( ) ) { log . info ( "Petite bean: [" + name + "] --> " + type . getName ( ) + " @ " + scopeType . getSimpleName ( ) + ":" + wiringMode . toString ( ) ) ; } // register Scope scope = resolveScope ( scopeType ) ; BeanDefinition < T > beanDefinition = createBeanDefinitionForRegistration ( name , type , scope , wiringMode , consumer ) ; registerBean ( name , beanDefinition ) ; // providers ProviderDefinition [ ] providerDefinitions = petiteResolvers . resolveProviderDefinitions ( type , name ) ; if ( providerDefinitions != null ) { for ( ProviderDefinition providerDefinition : providerDefinitions ) { providers . put ( providerDefinition . name , providerDefinition ) ; } } // define if ( define ) { beanDefinition . ctor = petiteResolvers . resolveCtorInjectionPoint ( beanDefinition . type ( ) ) ; beanDefinition . properties = PropertyInjectionPoint . EMPTY ; beanDefinition . methods = MethodInjectionPoint . EMPTY ; beanDefinition . initMethods = InitMethodPoint . EMPTY ; beanDefinition . destroyMethods = DestroyMethodPoint . EMPTY ; } // return return beanDefinition ; }


Input: Registers bean definition by putting it in the beans map . If bean does not have petite name explicitly defined alternative bean names will be registered . [CODESPLIT] protected void registerBean ( final String name , final BeanDefinition beanDefinition ) { beans . put ( name , beanDefinition ) ; if ( ! petiteConfig . isUseAltBeanNames ( ) ) { return ; } Class type = beanDefinition . type ( ) ; if ( annotationResolver . beanHasAnnotationName ( type ) ) { return ; } Class [ ] interfaces = ClassUtil . resolveAllInterfaces ( type ) ; for ( Class anInterface : interfaces ) { String altName = annotationResolver . resolveBeanName ( anInterface , petiteConfig . getUseFullTypeNames ( ) ) ; if ( name . equals ( altName ) ) { continue ; } if ( beans . containsKey ( altName ) ) { continue ; } if ( beansAlt . containsKey ( altName ) ) { BeanDefinition existing = beansAlt . get ( altName ) ; if ( existing != null ) { beansAlt . put ( altName , null ) ; // store null as value to mark that alt name is duplicate } } else { beansAlt . put ( altName , beanDefinition ) ; } } }


Input: Removes all petite beans of provided type . Bean name is not resolved from a type! Instead all beans are iterated and only beans with equal types are removed . [CODESPLIT] public void removeBean ( final Class type ) { // collect bean names Set < String > beanNames = new HashSet <> ( ) ; for ( BeanDefinition def : beans . values ( ) ) { if ( def . type . equals ( type ) ) { beanNames . add ( def . name ) ; } } // remove collected bean names for ( String beanName : beanNames ) { removeBean ( beanName ) ; } }


Input: Removes bean and returns definition of removed bean . All resolvers references are deleted too . Returns bean definition of removed bean or <code > null< / code > . [CODESPLIT] public BeanDefinition removeBean ( final String name ) { BeanDefinition bd = beans . remove ( name ) ; if ( bd == null ) { return null ; } bd . scopeRemove ( ) ; return bd ; }


Input: Resolves bean names for give type . [CODESPLIT] protected String [ ] resolveBeanNamesForType ( final Class type ) { String [ ] beanNames = beanCollections . get ( type ) ; if ( beanNames != null ) { return beanNames ; } ArrayList < String > list = new ArrayList <> ( ) ; for ( Map . Entry < String , BeanDefinition > entry : beans . entrySet ( ) ) { BeanDefinition beanDefinition = entry . getValue ( ) ; if ( ClassUtil . isTypeOf ( beanDefinition . type , type ) ) { String beanName = entry . getKey ( ) ; list . add ( beanName ) ; } } if ( list . isEmpty ( ) ) { beanNames = StringPool . EMPTY_ARRAY ; } else { beanNames = list . toArray ( new String [ 0 ] ) ; } beanCollections . put ( type , beanNames ) ; return beanNames ; }


Input: Registers constructor injection point . [CODESPLIT] public void registerPetiteCtorInjectionPoint ( final String beanName , final Class [ ] paramTypes , final String [ ] references ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; Constructor constructor = null ; if ( paramTypes == null ) { CtorDescriptor [ ] ctors = cd . getAllCtorDescriptors ( ) ; if ( ctors != null && ctors . length > 0 ) { if ( ctors . length > 1 ) { throw new PetiteException ( ctors . length + " suitable constructor found as injection point for: " + beanDefinition . type . getName ( ) ) ; } constructor = ctors [ 0 ] . getConstructor ( ) ; } } else { CtorDescriptor ctorDescriptor = cd . getCtorDescriptor ( paramTypes , true ) ; if ( ctorDescriptor != null ) { constructor = ctorDescriptor . getConstructor ( ) ; } } if ( constructor == null ) { throw new PetiteException ( "Constructor not found: " + beanDefinition . type . getName ( ) ) ; } BeanReferences [ ] ref = referencesResolver . resolveReferenceFromValues ( constructor , references ) ; beanDefinition . ctor = new CtorInjectionPoint ( constructor , ref ) ; }


Input: Registers property injection point . [CODESPLIT] public void registerPetitePropertyInjectionPoint ( final String beanName , final String property , final String reference ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; PropertyDescriptor propertyDescriptor = cd . getPropertyDescriptor ( property , true ) ; if ( propertyDescriptor == null ) { throw new PetiteException ( "Property not found: " + beanDefinition . type . getName ( ) + ' ' + property ) ; } BeanReferences ref = referencesResolver . resolveReferenceFromValue ( propertyDescriptor , reference ) ; PropertyInjectionPoint pip = new PropertyInjectionPoint ( propertyDescriptor , ref ) ; beanDefinition . addPropertyInjectionPoint ( pip ) ; }


Input: Registers set injection point . [CODESPLIT] public void registerPetiteSetInjectionPoint ( final String beanName , final String property ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; PropertyDescriptor propertyDescriptor = cd . getPropertyDescriptor ( property , true ) ; if ( propertyDescriptor == null ) { throw new PetiteException ( "Property not found: " + beanDefinition . type . getName ( ) + ' ' + property ) ; } SetInjectionPoint sip = new SetInjectionPoint ( propertyDescriptor ) ; beanDefinition . addSetInjectionPoint ( sip ) ; }


Input: Registers method injection point . [CODESPLIT] public void registerPetiteMethodInjectionPoint ( final String beanName , final String methodName , final Class [ ] arguments , final String [ ] references ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; Method method = null ; if ( arguments == null ) { MethodDescriptor [ ] methods = cd . getAllMethodDescriptors ( methodName ) ; if ( methods != null && methods . length > 0 ) { if ( methods . length > 1 ) { throw new PetiteException ( methods . length + " suitable methods found as injection points for: " + beanDefinition . type . getName ( ) + ' ' + methodName ) ; } method = methods [ 0 ] . getMethod ( ) ; } } else { MethodDescriptor md = cd . getMethodDescriptor ( methodName , arguments , true ) ; if ( md != null ) { method = md . getMethod ( ) ; } } if ( method == null ) { throw new PetiteException ( "Method not found: " + beanDefinition . type . getName ( ) + ' ' + methodName ) ; } BeanReferences [ ] ref = referencesResolver . resolveReferenceFromValues ( method , references ) ; MethodInjectionPoint mip = new MethodInjectionPoint ( method , ref ) ; beanDefinition . addMethodInjectionPoint ( mip ) ; }


Input: Registers init method . [CODESPLIT] public void registerPetiteInitMethods ( final String beanName , final InitMethodInvocationStrategy invocationStrategy , String ... initMethodNames ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; if ( initMethodNames == null ) { initMethodNames = StringPool . EMPTY_ARRAY ; } int total = initMethodNames . length ; InitMethodPoint [ ] initMethodPoints = new InitMethodPoint [ total ] ; int i ; for ( i = 0 ; i < initMethodNames . length ; i ++ ) { MethodDescriptor md = cd . getMethodDescriptor ( initMethodNames [ i ] , ClassUtil . EMPTY_CLASS_ARRAY , true ) ; if ( md == null ) { throw new PetiteException ( "Init method not found: " + beanDefinition . type . getName ( ) + ' ' + initMethodNames [ i ] ) ; } initMethodPoints [ i ] = new InitMethodPoint ( md . getMethod ( ) , i , invocationStrategy ) ; } beanDefinition . addInitMethodPoints ( initMethodPoints ) ; }


Input: Registers destroy method . [CODESPLIT] public void registerPetiteDestroyMethods ( final String beanName , String ... destroyMethodNames ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; if ( destroyMethodNames == null ) { destroyMethodNames = StringPool . EMPTY_ARRAY ; } int total = destroyMethodNames . length ; DestroyMethodPoint [ ] destroyMethodPoints = new DestroyMethodPoint [ total ] ; int i ; for ( i = 0 ; i < destroyMethodNames . length ; i ++ ) { MethodDescriptor md = cd . getMethodDescriptor ( destroyMethodNames [ i ] , ClassUtil . EMPTY_CLASS_ARRAY , true ) ; if ( md == null ) { throw new PetiteException ( "Destroy method not found: " + beanDefinition . type . getName ( ) + ' ' + destroyMethodNames [ i ] ) ; } destroyMethodPoints [ i ] = new DestroyMethodPoint ( md . getMethod ( ) ) ; } beanDefinition . addDestroyMethodPoints ( destroyMethodPoints ) ; }


Input: Registers instance method provider . [CODESPLIT] public void registerPetiteProvider ( final String providerName , final String beanName , final String methodName , final Class [ ] arguments ) { BeanDefinition beanDefinition = lookupBeanDefinition ( beanName ) ; if ( beanDefinition == null ) { throw new PetiteException ( "Bean not found: " + beanName ) ; } Class beanType = beanDefinition . type ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanType ) ; MethodDescriptor md = cd . getMethodDescriptor ( methodName , arguments , true ) ; if ( md == null ) { throw new PetiteException ( "Provider method not found: " + methodName ) ; } ProviderDefinition providerDefinition = new ProviderDefinition ( providerName , beanName , md . getMethod ( ) ) ; providers . put ( providerName , providerDefinition ) ; }


Input: Registers static method provider . [CODESPLIT] public void registerPetiteProvider ( final String providerName , final Class type , final String staticMethodName , final Class [ ] arguments ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; MethodDescriptor md = cd . getMethodDescriptor ( staticMethodName , arguments , true ) ; if ( md == null ) { throw new PetiteException ( "Provider method not found: " + staticMethodName ) ; } ProviderDefinition providerDefinition = new ProviderDefinition ( providerName , md . getMethod ( ) ) ; providers . put ( providerName , providerDefinition ) ; }


Input: Iterates all beans . Iteration occurs over the { [CODESPLIT] public void forEachBean ( final Consumer < BeanDefinition > beanDefinitionConsumer ) { final Set < String > names = beanNames ( ) ; for ( String beanName : names ) { BeanDefinition beanDefinition = lookupBeanDefinition ( beanName ) ; if ( beanDefinition != null ) { beanDefinitionConsumer . accept ( beanDefinition ) ; } } }


Input: Iterates all beans that are of given type . [CODESPLIT] public void forEachBeanType ( final Class type , final Consumer < String > beanNameConsumer ) { forEachBean ( bd -> { if ( ClassUtil . isTypeOf ( bd . type , type ) ) { beanNameConsumer . accept ( bd . name ) ; } } ) ; }


Input: Defines many parameters at once . [CODESPLIT] public void defineParameters ( final Map < ? , ? > properties ) { for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { defineParameter ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } }


Input: Defines many parameters at once from { [CODESPLIT] public void defineParameters ( final Props props ) { Map < ? , ? > map = new HashMap <> ( ) ; props . extractProps ( map ) ; defineParameters ( map ) ; }


Input: Returns the value in the current classloader copy of this variable . If the variable has no value for the current classloader it is first initialized to the value returned by an invocation of the initialValue () method . [CODESPLIT] public synchronized T get ( ) { ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { T value = weakMap . get ( contextClassLoader ) ; if ( ( value == null ) && ! weakMap . containsKey ( contextClassLoader ) ) { value = initialValue ( ) ; weakMap . put ( contextClassLoader , value ) ; } return value ; } if ( ! initialized ) { value = initialValue ( ) ; initialized = true ; } return value ; }


Input: Sets the current classloaders s copy of this variable to the specified value . Most subclasses will have no need to override this method relying solely on the initialValue () method to set the values of classloader - locals . [CODESPLIT] public synchronized void set ( final T value ) { ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { weakMap . put ( contextClassLoader , value ) ; return ; } this . value = value ; this . initialized = true ; }


Input: { [CODESPLIT] @ Override public Float get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Float . valueOf ( rs . getFloat ( index ) ) ; }


Input: { [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Float value , final int dbSqlType ) throws SQLException { st . setFloat ( index , value . floatValue ( ) ) ; }


Input: { [CODESPLIT] @ Override public Date get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getDate ( index ) ; }


Input: { [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Date value , final int dbSqlType ) throws SQLException { st . setDate ( index , value ) ; }


Input: Measure action invocation time . [CODESPLIT] @ Override public Object intercept ( final ActionRequest actionRequest ) throws Exception { printBefore ( actionRequest ) ; long startTime = System . currentTimeMillis ( ) ; Object result = null ; try { result = actionRequest . invoke ( ) ; } catch ( Exception ex ) { result = "<exception>" ; throw ex ; } catch ( Throwable th ) { result = "<throwable>" ; throw new Exception ( th ) ; } finally { long executionTime = System . currentTimeMillis ( ) - startTime ; printAfter ( actionRequest , executionTime , result ) ; } return result ; }


Input: Prints out the message . User can override this method and modify the way the message is printed . [CODESPLIT] protected void printBefore ( final ActionRequest request ) { StringBuilder message = new StringBuilder ( prefixIn ) ; message . append ( request . getActionPath ( ) ) . append ( "   [" ) . append ( request . getActionRuntime ( ) . createActionString ( ) ) . append ( ' ' ) ; out ( message . toString ( ) ) ; }


Input: Prints out the message . User can override this method and modify the way the message is printed . [CODESPLIT] protected void printAfter ( final ActionRequest request , final long executionTime , final Object result ) { StringBuilder message = new StringBuilder ( prefixOut ) ; String resultString = StringUtil . toSafeString ( result ) ; if ( resultString . length ( ) > 70 ) { resultString = resultString . substring ( 0 , 70 ) ; resultString += "..." ; } message . append ( request . getActionPath ( ) ) . append ( "  (" ) . append ( resultString ) . append ( ") in " ) . append ( executionTime ) . append ( "ms." ) ; out ( message . toString ( ) ) ; }


Input: Resolves Java version from current version . [CODESPLIT] public static int resolveJavaVersion ( final int version ) { final int javaVersionNumber = SystemUtil . info ( ) . getJavaVersionNumber ( ) ; final int platformVersion = javaVersionNumber - 8 + 52 ; return version > platformVersion ? version : platformVersion ; }


Input: Pushes int value in an optimal way . [CODESPLIT] public static void pushInt ( final MethodVisitor mv , final int value ) { if ( value <= 5 ) { mv . visitInsn ( ICONST_0 + value ) ; } else if ( value <= Byte . MAX_VALUE ) { mv . visitIntInsn ( BIPUSH , value ) ; } else { mv . visitIntInsn ( SIPUSH , value ) ; } }


Input: Validates argument index . [CODESPLIT] public static void checkArgumentIndex ( final MethodInfo methodInfo , final int argIndex ) { if ( ( argIndex < 1 ) || ( argIndex > methodInfo . getArgumentsCount ( ) ) ) { throw new ProxettaException ( "Invalid argument index: " + argIndex ) ; } }


Input: Builds advice field name . [CODESPLIT] public static String adviceFieldName ( final String name , final int index ) { return ProxettaNames . fieldPrefix + name + ProxettaNames . fieldDivider + index ; }


Input: Builds advice method name . [CODESPLIT] public static String adviceMethodName ( final String name , final int index ) { return ProxettaNames . methodPrefix + name + ProxettaNames . methodDivider + index ; }


Input: ---------------------------------------------------------------- load [CODESPLIT] public static void loadMethodArgumentClass ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { TypeInfo argument = methodInfo . getArgument ( index ) ; loadClass ( mv , argument . getOpcode ( ) , argument . getRawName ( ) ) ; }


Input: Loads all method arguments before INVOKESPECIAL call . [CODESPLIT] public static void loadSpecialMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { mv . visitVarInsn ( ALOAD , 0 ) ; for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }


Input: Loads all method arguments before INVOKESTATIC call . [CODESPLIT] public static void loadStaticMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 0 ; i < methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }


Input: Loads all method arguments before INVOKEVIRTUAL call . [CODESPLIT] public static void loadVirtualMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }


Input: Loads one argument . Index is 1 - based . No conversion occurs . [CODESPLIT] public static void loadMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ILOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( LLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( FLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( DLOAD , offset ) ; break ; default : mv . visitVarInsn ( ALOAD , offset ) ; } }


Input: Stores one argument . Index is 1 - based . No conversion occurs . [CODESPLIT] public static void storeMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ISTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( LSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( FSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( DSTORE , offset ) ; break ; default : mv . visitVarInsn ( ASTORE , offset ) ; } }


Input: Returns <code > true< / code > if opcode is xSTORE . [CODESPLIT] public static boolean isStoreOpcode ( final int opcode ) { return ( opcode == ISTORE ) || ( opcode == LSTORE ) || ( opcode == FSTORE ) || ( opcode == DSTORE ) || ( opcode == ASTORE ) ; }


Input: Visits return opcodes . [CODESPLIT] public static void visitReturn ( final MethodVisitor mv , final MethodInfo methodInfo , final boolean isLast ) { switch ( methodInfo . getReturnType ( ) . getOpcode ( ) ) { case ' ' : if ( isLast ) { mv . visitInsn ( POP ) ; } mv . visitInsn ( RETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . byteValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . charValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . shortValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . intValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . booleanValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( LCONST_0 ) ; mv . visitInsn ( LRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . longValue ( mv ) ; } mv . visitInsn ( LRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( FCONST_0 ) ; mv . visitInsn ( FRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . floatValue ( mv ) ; } mv . visitInsn ( FRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( DCONST_0 ) ; mv . visitInsn ( DRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . doubleValue ( mv ) ; } mv . visitInsn ( DRETURN ) ; break ; default : mv . visitInsn ( ARETURN ) ; break ; } }


Input: Prepares return value . [CODESPLIT] public static void prepareReturnValue ( final MethodVisitor mv , final MethodInfo methodInfo , int varOffset ) { varOffset += methodInfo . getAllArgumentsSize ( ) ; switch ( methodInfo . getReturnType ( ) . getOpcode ( ) ) { case ' ' : mv . visitInsn ( ACONST_NULL ) ; break ; case ' ' : AsmUtil . valueOfByte ( mv ) ; break ; case ' ' : AsmUtil . valueOfCharacter ( mv ) ; break ; case ' ' : AsmUtil . valueOfShort ( mv ) ; break ; case ' ' : AsmUtil . valueOfInteger ( mv ) ; break ; case ' ' : AsmUtil . valueOfBoolean ( mv ) ; break ; case ' ' : AsmUtil . valueOfLong ( mv ) ; break ; case ' ' : AsmUtil . valueOfFloat ( mv ) ; break ; case ' ' : AsmUtil . valueOfDouble ( mv ) ; break ; } }


Input: Creates unique key for method signatures map . [CODESPLIT] public static String createMethodSignaturesKey ( final int access , final String methodName , final String description , final String className ) { return new StringBand ( 7 ) . append ( access ) . append ( COLON ) . append ( description ) . append ( StringPool . UNDERSCORE ) . append ( className ) . append ( StringPool . HASH ) . append ( methodName ) . toString ( ) ; }


Input: Visits non - array element value for annotation . Returns <code > true< / code > if value is successfully processed . [CODESPLIT] public static void visitElementValue ( final MethodVisitor mv , final Object elementValue , final boolean boxPrimitives ) { if ( elementValue instanceof String ) { // string mv . visitLdcInsn ( elementValue ) ; return ; } if ( elementValue instanceof Type ) { // class mv . visitLdcInsn ( elementValue ) ; return ; } if ( elementValue instanceof Class ) { mv . visitLdcInsn ( Type . getType ( ( Class ) elementValue ) ) ; return ; } // primitives if ( elementValue instanceof Integer ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfInteger ( mv ) ; } return ; } if ( elementValue instanceof Long ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfLong ( mv ) ; } return ; } if ( elementValue instanceof Short ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfShort ( mv ) ; } return ; } if ( elementValue instanceof Byte ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfByte ( mv ) ; } return ; } if ( elementValue instanceof Float ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfFloat ( mv ) ; } return ; } if ( elementValue instanceof Double ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfDouble ( mv ) ; } return ; } if ( elementValue instanceof Character ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfCharacter ( mv ) ; } return ; } if ( elementValue instanceof Boolean ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfBoolean ( mv ) ; } return ; } // enum Class elementValueClass = elementValue . getClass ( ) ; Class enumClass = ClassUtil . findEnum ( elementValueClass ) ; if ( enumClass != null ) { try { String typeRef = AsmUtil . typeToTyperef ( enumClass ) ; String typeSignature = AsmUtil . typeToSignature ( enumClass ) ; // invoke Method nameMethod = elementValue . getClass ( ) . getMethod ( "name" ) ; String name = ( String ) nameMethod . invoke ( elementValue ) ; mv . visitFieldInsn ( GETSTATIC , typeSignature , name , typeRef ) ; return ; } catch ( Exception ignore ) { } } throw new ProxettaException ( "Unsupported annotation type: " + elementValue . getClass ( ) ) ; }


Input: Creates new array . [CODESPLIT] public static void newArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitIntInsn ( NEWARRAY , T_INT ) ; return ; } if ( componentType == long . class ) { mv . visitIntInsn ( NEWARRAY , T_LONG ) ; return ; } if ( componentType == float . class ) { mv . visitIntInsn ( NEWARRAY , T_FLOAT ) ; return ; } if ( componentType == double . class ) { mv . visitIntInsn ( NEWARRAY , T_DOUBLE ) ; return ; } if ( componentType == byte . class ) { mv . visitIntInsn ( NEWARRAY , T_BYTE ) ; return ; } if ( componentType == short . class ) { mv . visitIntInsn ( NEWARRAY , T_SHORT ) ; return ; } if ( componentType == boolean . class ) { mv . visitIntInsn ( NEWARRAY , T_BOOLEAN ) ; return ; } if ( componentType == char . class ) { mv . visitIntInsn ( NEWARRAY , T_CHAR ) ; return ; } mv . visitTypeInsn ( ANEWARRAY , AsmUtil . typeToSignature ( componentType ) ) ; }


Input: Stores element on stack into an array . [CODESPLIT] public static void storeIntoArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitInsn ( IASTORE ) ; return ; } if ( componentType == long . class ) { mv . visitInsn ( LASTORE ) ; return ; } if ( componentType == float . class ) { mv . visitInsn ( FASTORE ) ; return ; } if ( componentType == double . class ) { mv . visitInsn ( DASTORE ) ; return ; } if ( componentType == byte . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == short . class ) { mv . visitInsn ( SASTORE ) ; return ; } if ( componentType == boolean . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == char . class ) { mv . visitInsn ( CASTORE ) ; return ; } mv . visitInsn ( AASTORE ) ; }


Input: ---------------------------------------------------------------- detect advice macros [CODESPLIT] public static boolean isInvokeMethod ( final String name , final String desc ) { if ( name . equals ( "invoke" ) ) { if ( desc . equals ( "()Ljava/lang/Object;" ) ) { return true ; } } return false ; }


Input: Lookups the decorator for given decorator path . Returns { [CODESPLIT] public char [ ] lookupDecoratorContent ( final String path ) { if ( contentMap != null ) { final char [ ] data = contentMap . get ( path ) ; if ( data != null ) { return data ; } final File file = filesMap . get ( path ) ; if ( file != null ) { try { return FileUtil . readChars ( file ) ; } catch ( IOException e ) { throw new DecoraException ( "Unable to read Decrator files" , e ) ; } } } return null ; }


Input: Resolves decorator path based on request and action path . If decorator is not found returns <code > null< / code > . By default applies decorator on all * . html pages . [CODESPLIT] public String resolveDecorator ( final HttpServletRequest request , final String actionPath ) { if ( actionPath . endsWith ( ".html" ) ) { return DEFAULT_DECORATOR ; } return null ; }


Input: TODO : should this always return lowercase or always uppercase? [CODESPLIT] public static String extractMimeType ( final String contentType ) { final int ndx = contentType . indexOf ( ' ' ) ; final String mime ; if ( ndx != - 1 ) { mime = contentType . substring ( 0 , ndx ) ; } else { mime = contentType ; } return mime ; }


Input: TODO : should this always return lowercase or always uppercase? [CODESPLIT] public static String extractEncoding ( final String contentType ) { int ndx = contentType . indexOf ( ' ' ) ; final String charset = ndx != - 1 ? contentType . substring ( ndx + 1 ) : StringPool . EMPTY ; String encoding = null ; ndx = charset . indexOf ( ATTR_CHARSET ) ; if ( ndx != - 1 ) { ndx += ATTR_CHARSET . length ( ) ; final int len = charset . length ( ) ; if ( charset . charAt ( ndx ) == ' ' ) { ndx ++ ; } final int start = ndx ; while ( ndx < len ) { final char c = charset . charAt ( ndx ) ; if ( ( c == ' ' ) || ( CharUtil . isWhitespace ( c ) ) || ( c == ' ' ) ) { break ; } ndx ++ ; } encoding = charset . substring ( start , ndx ) ; } return encoding ; }


Input: Extracts encoding from a given content type . [CODESPLIT] public static String extractEncoding ( final String contentType , String defaultEncoding ) { String encoding = extractEncoding ( contentType ) ; if ( encoding == null ) { if ( defaultEncoding == null ) { defaultEncoding = JoddCore . encoding ; } encoding = defaultEncoding ; } return encoding ; }


Input: Correctly resolves file name from the message part . Thanx to : Flavio Pompermaier [CODESPLIT] public static String resolveFileName ( final Part part ) throws MessagingException { if ( ! ( part instanceof MimeBodyPart ) ) { return part . getFileName ( ) ; } final String contentType = part . getContentType ( ) ; String ret ; try { ret = MimeUtility . decodeText ( part . getFileName ( ) ) ; } catch ( final Exception ex ) { // String[] contentId = part.getHeader("Content-ID"); // if (contentId != null && contentId.length > 0) { final String contentId = ( ( MimeBodyPart ) part ) . getContentID ( ) ; if ( contentId != null ) { ret = contentId + contentTypeForFileName ( contentType ) ; } else { ret = defaultFileName ( contentType ) ; } } return ret ; }


Input: Check whether flags is a empty flags [CODESPLIT] public static boolean isEmptyFlags ( Flags flags ) { if ( flags == null ) return true ; Flags . Flag [ ] systemFlags = flags . getSystemFlags ( ) ; if ( systemFlags != null && systemFlags . length > 0 ) { return false ; } String [ ] userFlags = flags . getUserFlags ( ) ; if ( userFlags != null && userFlags . length > 0 ) { return false ; } return true ; }


Input: Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected char [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final char [ ] target = new char [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Character > charArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final char convertedValue = convertType ( element ) ; charArrayList . add ( Character . valueOf ( convertedValue ) ) ; } final char [ ] array = new char [ charArrayList . size ( ) ] ; for ( int i = 0 ; i < charArrayList . size ( ) ; i ++ ) { final Character c = charArrayList . get ( i ) ; array [ i ] = c . charValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final CharSequence charSequence = ( CharSequence ) value ; final char [ ] result = new char [ charSequence . length ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = charSequence . charAt ( i ) ; } return result ; } // everything else: return convertToSingleElementArray ( value ) ; }


Input: Returns <code > true< / code > if a request is multi - part request . [CODESPLIT] public static boolean isMultipartRequest ( final HttpServletRequest request ) { String type = request . getHeader ( HEADER_CONTENT_TYPE ) ; return ( type != null ) && type . startsWith ( TYPE_MULTIPART_FORM_DATA ) ; }


Input: Decodes the Authorization header and retrieves the user s name from it . Returns <code > null< / code > if the header is not present . [CODESPLIT] public static String resolveAuthUsername ( final HttpServletRequest request ) { String header = request . getHeader ( HEADER_AUTHORIZATION ) ; if ( header == null ) { return null ; } if ( ! header . contains ( "Basic " ) ) { return null ; } final String encoded = header . substring ( header . indexOf ( ' ' ) + 1 ) ; final String decoded = new String ( Base64 . decode ( encoded ) ) ; return decoded . substring ( 0 , decoded . indexOf ( ' ' ) ) ; }


Input: Returns Bearer token . [CODESPLIT] public static String resolveAuthBearerToken ( final HttpServletRequest request ) { String header = request . getHeader ( HEADER_AUTHORIZATION ) ; if ( header == null ) { return null ; } int ndx = header . indexOf ( "Bearer " ) ; if ( ndx == - 1 ) { return null ; } return header . substring ( ndx + 7 ) . trim ( ) ; }


Input: Sends correct headers to require basic authentication for the given realm . [CODESPLIT] public static void requireAuthentication ( final HttpServletResponse resp , final String realm ) throws IOException { resp . setHeader ( WWW_AUTHENTICATE , "Basic realm=\"" + realm + ' ' ) ; resp . sendError ( HttpServletResponse . SC_UNAUTHORIZED ) ; }


Input: Prepares response for file download with provided mime type . [CODESPLIT] public static void prepareDownload ( final HttpServletResponse response , final File file , final String mimeType ) { if ( ! file . exists ( ) ) { throw new IllegalArgumentException ( "File not found: " + file ) ; } if ( file . length ( ) > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( "File too big: " + file ) ; } prepareResponse ( response , file . getAbsolutePath ( ) , mimeType , ( int ) file . length ( ) ) ; }


Input: Prepares response for various provided data . [CODESPLIT] public static void prepareResponse ( final HttpServletResponse response , final String fileName , String mimeType , final int fileSize ) { if ( ( mimeType == null ) && ( fileName != null ) ) { String extension = FileNameUtil . getExtension ( fileName ) ; mimeType = MimeTypes . getMimeType ( extension ) ; } if ( mimeType != null ) { response . setContentType ( mimeType ) ; } if ( fileSize >= 0 ) { response . setContentLength ( fileSize ) ; } // support internationalization // See https://tools.ietf.org/html/rfc6266#section-5 for more information. if ( fileName != null ) { String name = FileNameUtil . getName ( fileName ) ; String encodedFileName = URLCoder . encode ( name ) ; response . setHeader ( CONTENT_DISPOSITION , "attachment;filename=\"" + name + "\";filename*=utf8''" + encodedFileName ) ; } }


Input: Returns all cookies from client that matches provided name . [CODESPLIT] public static Cookie [ ] getAllCookies ( final HttpServletRequest request , final String cookieName ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) { return null ; } ArrayList < Cookie > list = new ArrayList <> ( cookies . length ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { list . add ( cookie ) ; } } if ( list . isEmpty ( ) ) { return null ; } return list . toArray ( new Cookie [ 0 ] ) ; }