Input: Locates property field . Field is being searched also in all superclasses of current class . [CODESPLIT] protected FieldDescriptor findField ( final String fieldName ) { FieldDescriptor fieldDescriptor = classDescriptor . getFieldDescriptor ( fieldName , true ) ; if ( fieldDescriptor != null ) { return fieldDescriptor ; } // field descriptor not found in this class // try to locate it in the superclasses Class [ ] superclasses = classDescriptor . getAllSuperclasses ( ) ; for ( Class superclass : superclasses ) { ClassDescriptor classDescriptor = ClassIntrospector . get ( ) . lookup ( superclass ) ; fieldDescriptor = classDescriptor . getFieldDescriptor ( fieldName , true ) ; if ( fieldDescriptor != null ) { return fieldDescriptor ; } } // nothing found return null ; }


Input: Returns property type . Raw types are detected . [CODESPLIT] public Class getType ( ) { if ( type == null ) { if ( fieldDescriptor != null ) { type = fieldDescriptor . getRawType ( ) ; } else if ( readMethodDescriptor != null ) { type = getGetter ( true ) . getGetterRawType ( ) ; //type = readMethodDescriptor.getGetterRawType(); } else if ( writeMethodDescriptor != null ) { type = getSetter ( true ) . getSetterRawType ( ) ; //type = writeMethodDescriptor.getSetterRawType(); } } return type ; }


Input: Returns { [CODESPLIT] public Getter getGetter ( final boolean declared ) { if ( getters == null ) { getters = new Getter [ ] { createGetter ( false ) , createGetter ( true ) , } ; } return getters [ declared ? 1 : 0 ] ; }


Input: Creates a { [CODESPLIT] protected Getter createGetter ( final boolean declared ) { if ( readMethodDescriptor != null ) { if ( readMethodDescriptor . matchDeclared ( declared ) ) { return Getter . of ( readMethodDescriptor ) ; } } if ( fieldDescriptor != null ) { if ( fieldDescriptor . matchDeclared ( declared ) ) { return Getter . of ( fieldDescriptor ) ; } } return null ; }


Input: Returns { [CODESPLIT] public Setter getSetter ( final boolean declared ) { if ( setters == null ) { setters = new Setter [ ] { createSetter ( false ) , createSetter ( true ) , } ; } return setters [ declared ? 1 : 0 ] ; }


Input: Creates a { [CODESPLIT] protected Setter createSetter ( final boolean declared ) { if ( writeMethodDescriptor != null ) { if ( writeMethodDescriptor . matchDeclared ( declared ) ) { return Setter . of ( writeMethodDescriptor ) ; } } if ( fieldDescriptor != null ) { if ( fieldDescriptor . matchDeclared ( declared ) ) { return Setter . of ( fieldDescriptor ) ; } } return null ; }


Input: Resolves key type for given property descriptor . [CODESPLIT] public Class resolveKeyType ( final boolean declared ) { Class keyType = null ; Getter getter = getGetter ( declared ) ; if ( getter != null ) { keyType = getter . getGetterRawKeyComponentType ( ) ; } if ( keyType == null ) { FieldDescriptor fieldDescriptor = getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { keyType = fieldDescriptor . getRawKeyComponentType ( ) ; } } return keyType ; }


Input: Resolves component type for given property descriptor . [CODESPLIT] public Class resolveComponentType ( final boolean declared ) { Class componentType = null ; Getter getter = getGetter ( declared ) ; if ( getter != null ) { componentType = getter . getGetterRawComponentType ( ) ; } if ( componentType == null ) { FieldDescriptor fieldDescriptor = getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { componentType = fieldDescriptor . getRawComponentType ( ) ; } } return componentType ; }


Input: ---------------------------------------------------------------- util [CODESPLIT] protected String nosep ( final String in ) { if ( in . endsWith ( File . separator ) ) { return in . substring ( 0 , in . length ( ) - 1 ) ; } return in ; }


Input: Creates JSON result from given object . The object will be serialized to JSON . [CODESPLIT] public static JsonResult of ( final Object object ) { final String json = JsonSerializer . create ( ) . deep ( true ) . serialize ( object ) ; return new JsonResult ( json ) ; }


Input: Creates a JSON response from an exception . Response body will have information about the exception and response status will be set to 500 . [CODESPLIT] public static JsonResult of ( final Exception exception ) { final HashMap < String , Object > errorMap = new HashMap <> ( ) ; errorMap . put ( "message" , ExceptionUtil . message ( exception ) ) ; errorMap . put ( "error" , exception . getClass ( ) . getName ( ) ) ; errorMap . put ( "cause" , exception . getCause ( ) != null ? exception . getCause ( ) . getClass ( ) . getName ( ) : null ) ; final ArrayList < String > details = new ArrayList <> ( ) ; final StackTraceElement [ ] ste = ExceptionUtil . getStackTrace ( exception , null , null ) ; for ( StackTraceElement stackTraceElement : ste ) { details . add ( stackTraceElement . toString ( ) ) ; } errorMap . put ( "details" , details ) ; final String json = JsonSerializer . create ( ) . deep ( true ) . serialize ( errorMap ) ; return new JsonResult ( json ) . status ( HttpStatus . error500 ( ) . internalError ( ) ) ; }


Input: Resolves HTTP method name from method name . If method name or first camel - case word of a method equals to a HTTP method it will be used as that HTTP methods . [CODESPLIT] protected String resolveHttpMethodFromMethodName ( final String methodName ) { int i = 0 ; while ( i < methodName . length ( ) ) { if ( CharUtil . isUppercaseAlpha ( methodName . charAt ( i ) ) ) { break ; } i ++ ; } final String name = methodName . substring ( 0 , i ) . toUpperCase ( ) ; for ( final HttpMethod httpMethod : HttpMethod . values ( ) ) { if ( httpMethod . equalsName ( name ) ) { return httpMethod . name ( ) ; } } return null ; }


Input: Checks if two strings are equals or if they { [CODESPLIT] public static boolean equalsOrMatch ( final CharSequence string , final CharSequence pattern ) { if ( string . equals ( pattern ) ) { return true ; } return match ( string , pattern , 0 , 0 ) ; }


Input: Internal matching recursive function . [CODESPLIT] private static boolean match ( final CharSequence string , final CharSequence pattern , int sNdx , int pNdx ) { int pLen = pattern . length ( ) ; if ( pLen == 1 ) { if ( pattern . charAt ( 0 ) == ' ' ) { // speed-up return true ; } } int sLen = string . length ( ) ; boolean nextIsNotWildcard = false ; while ( true ) { // check if end of string and/or pattern occurred if ( ( sNdx >= sLen ) ) { // end of string still may have pending '*' in pattern while ( ( pNdx < pLen ) && ( pattern . charAt ( pNdx ) == ' ' ) ) { pNdx ++ ; } return pNdx >= pLen ; } if ( pNdx >= pLen ) { // end of pattern, but not end of the string return false ; } char p = pattern . charAt ( pNdx ) ; // pattern char // perform logic if ( ! nextIsNotWildcard ) { if ( p == ' ' ) { pNdx ++ ; nextIsNotWildcard = true ; continue ; } if ( p == ' ' ) { sNdx ++ ; pNdx ++ ; continue ; } if ( p == ' ' ) { char pNext = 0 ; // next pattern char if ( pNdx + 1 < pLen ) { pNext = pattern . charAt ( pNdx + 1 ) ; } if ( pNext == ' ' ) { // double '*' have the same effect as one '*' pNdx ++ ; continue ; } int i ; pNdx ++ ; // find recursively if there is any substring from the end of the // line that matches the rest of the pattern !!! for ( i = string . length ( ) ; i >= sNdx ; i -- ) { if ( match ( string , pattern , i , pNdx ) ) { return true ; } } return false ; } } else { nextIsNotWildcard = false ; } // check if pattern char and string char are equals if ( p != string . charAt ( sNdx ) ) { return false ; } // everything matches for now, continue sNdx ++ ; pNdx ++ ; } }


Input: Matches string to at least one pattern . Returns index of matched pattern or <code > - 1< / code > otherwise . [CODESPLIT] public static int matchOne ( final String src , final String ... patterns ) { for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( match ( src , patterns [ i ] ) ) { return i ; } } return - 1 ; }


Input: Matches path against pattern using * ? and ** wildcards . Both path and the pattern are tokenized on path separators ( both \ and / ) . ** represents deep tree wildcard as in Ant . [CODESPLIT] public static boolean matchPath ( final String path , final String pattern ) { String [ ] pathElements = StringUtil . splitc ( path , PATH_SEPARATORS ) ; String [ ] patternElements = StringUtil . splitc ( pattern , PATH_SEPARATORS ) ; return matchTokens ( pathElements , patternElements ) ; }


Input: Returns <code > true< / code > if class or resource name matches at least one package rule from the list . [CODESPLIT] protected boolean isMatchingRules ( final String name , final String ... rules ) { for ( String rule : rules ) { if ( Wildcard . equalsOrMatch ( name , rule ) ) { return true ; } } return false ; }


Input: Resolves loading rules . [CODESPLIT] protected Loading resolveLoading ( final boolean parentFirstStrategy , final String className ) { boolean withParent = true ; boolean withLoader = true ; if ( parentFirstStrategy ) { if ( isMatchingRules ( className , loaderOnlyRules ) ) { withParent = false ; } else if ( isMatchingRules ( className , parentOnlyRules ) ) { withLoader = false ; } } else { if ( isMatchingRules ( className , parentOnlyRules ) ) { withLoader = false ; } else if ( isMatchingRules ( className , loaderOnlyRules ) ) { withParent = false ; } } return new Loading ( withParent , withLoader ) ; }


Input: Resolves resources . [CODESPLIT] protected Loading resolveResourceLoading ( final boolean parentFirstStrategy , String resourceName ) { if ( matchResourcesAsPackages ) { resourceName = StringUtil . replaceChar ( resourceName , ' ' , ' ' ) ; } return resolveLoading ( parentFirstStrategy , resourceName ) ; }


Input: Loads class using parent - first or parent - last strategy . [CODESPLIT] @ Override protected synchronized Class < ? > loadClass ( final String className , final boolean resolve ) throws ClassNotFoundException { // check first if the class has already been loaded Class < ? > c = findLoadedClass ( className ) ; if ( c != null ) { if ( resolve ) { resolveClass ( c ) ; } return c ; } // class not loaded yet Loading loading = resolveLoading ( parentFirst , className ) ; if ( parentFirst ) { // PARENT FIRST if ( loading . withParent ) { try { c = parentClassLoader . loadClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } } if ( c == null ) { if ( loading . withLoader ) { c = this . findClass ( className ) ; } else { throw new ClassNotFoundException ( "Class not found: " + className ) ; } } } else { // THIS FIRST if ( loading . withLoader ) { try { c = this . findClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } } if ( c == null ) { if ( loading . withParent ) { c = parentClassLoader . loadClass ( className ) ; } else { throw new ClassNotFoundException ( "Class not found: " + className ) ; } } } if ( resolve ) { resolveClass ( c ) ; } return c ; }


Input: Returns a resource using parent - first or parent - last strategy . [CODESPLIT] @ Override public URL getResource ( final String resourceName ) { URL url = null ; Loading loading = resolveResourceLoading ( parentFirst , resourceName ) ; if ( parentFirst ) { // PARENT FIRST if ( loading . withParent ) { url = parentClassLoader . getResource ( resourceName ) ; } if ( url == null ) { if ( loading . withLoader ) { url = this . findResource ( resourceName ) ; } } } else { // THIS FIRST if ( loading . withLoader ) { url = this . findResource ( resourceName ) ; } if ( url == null ) { if ( loading . withParent ) { url = parentClassLoader . getResource ( resourceName ) ; } } } return url ; }


Input: Waits for gobbler to end . [CODESPLIT] public void waitFor ( ) { try { synchronized ( lock ) { if ( ! end ) { lock . wait ( ) ; } } } catch ( InterruptedException ignore ) { Thread . currentThread ( ) . interrupt ( ) ; } }


Input: Scans annotation and returns type of Madvoc annotations . [CODESPLIT] public Class < ? extends Annotation > detectAnnotationType ( final Annotation [ ] annotations ) { for ( final Annotation annotation : annotations ) { if ( annotation instanceof In ) { return annotation . annotationType ( ) ; } else if ( annotation instanceof Out ) { return annotation . annotationType ( ) ; } } return null ; }


Input: Inspects { [CODESPLIT] public ScopeData inspectMethodParameterScopes ( final String name , final Class type , final Annotation [ ] annotations ) { In in = null ; Out out = null ; for ( final Annotation annotation : annotations ) { if ( annotation instanceof In ) { in = ( In ) annotation ; } else if ( annotation instanceof Out ) { out = ( Out ) annotation ; } } final Class < ? extends MadvocScope > scope = resolveScopeClassFromAnnotations ( annotations ) ; int count = 0 ; InjectionPoint [ ] ins = null ; InjectionPoint [ ] outs = null ; if ( in != null ) { final InjectionPoint scopeDataIn = buildInjectionPoint ( in . value ( ) , name , type , scope ) ; if ( scopeDataIn != null ) { count ++ ; ins = new InjectionPoint [ ] { scopeDataIn } ; } } if ( out != null ) { final InjectionPoint scopeDataOut = buildInjectionPoint ( out . value ( ) , name , type , scope ) ; if ( scopeDataOut != null ) { count ++ ; outs = new InjectionPoint [ ] { scopeDataOut } ; } } if ( count == 0 ) { return NO_SCOPE_DATA ; } return new ScopeData ( this , ins , outs ) ; }


Input: Builds injection point . [CODESPLIT] protected InjectionPoint buildInjectionPoint ( final String annotationValue , final String propertyName , final Class propertyType , final Class < ? extends MadvocScope > scope ) { final String value = annotationValue . trim ( ) ; final String name , targetName ; if ( StringUtil . isNotBlank ( value ) ) { name = value ; targetName = propertyName ; } else { name = propertyName ; targetName = null ; } return new InjectionPoint ( propertyType , name , targetName , scopeResolver . defaultOrScopeType ( scope ) ) ; }


Input: Inspects { [CODESPLIT] public ScopeData inspectClassScopes ( final Class actionClass ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( actionClass ) ; PropertyDescriptor [ ] allProperties = cd . getAllPropertyDescriptors ( ) ; List < InjectionPoint > listIn = new ArrayList <> ( allProperties . length ) ; List < InjectionPoint > listOut = new ArrayList <> ( allProperties . length ) ; for ( PropertyDescriptor pd : allProperties ) { // collect annotations Class < ? extends MadvocScope > scope = null ; In in = null ; Out out = null ; if ( pd . getFieldDescriptor ( ) != null ) { Field field = pd . getFieldDescriptor ( ) . getField ( ) ; in = field . getAnnotation ( In . class ) ; out = field . getAnnotation ( Out . class ) ; scope = resolveScopeClassFromAnnotations ( field . getAnnotations ( ) ) ; } if ( pd . getWriteMethodDescriptor ( ) != null ) { Method method = pd . getWriteMethodDescriptor ( ) . getMethod ( ) ; if ( in == null ) { in = method . getAnnotation ( In . class ) ; } if ( out == null ) { out = method . getAnnotation ( Out . class ) ; } if ( scope == null ) { scope = resolveScopeClassFromAnnotations ( method . getAnnotations ( ) ) ; } } if ( pd . getReadMethodDescriptor ( ) != null ) { Method method = pd . getReadMethodDescriptor ( ) . getMethod ( ) ; if ( in == null ) { in = method . getAnnotation ( In . class ) ; } if ( out == null ) { out = method . getAnnotation ( Out . class ) ; } if ( scope == null ) { scope = resolveScopeClassFromAnnotations ( method . getAnnotations ( ) ) ; } } // inspect all final InjectionPoint ii = in == null ? null : buildInjectionPoint ( in . value ( ) , pd . getName ( ) , pd . getType ( ) , scope ) ; if ( ii != null ) { listIn . add ( ii ) ; } final InjectionPoint oi = out == null ? null : buildInjectionPoint ( out . value ( ) , pd . getName ( ) , pd . getType ( ) , scope ) ; if ( oi != null ) { listOut . add ( oi ) ; } } if ( ( listIn . isEmpty ( ) ) && ( listOut . isEmpty ( ) ) ) { return NO_SCOPE_DATA ; } InjectionPoint [ ] in = null ; InjectionPoint [ ] out = null ; if ( ! listIn . isEmpty ( ) ) { in = listIn . toArray ( new InjectionPoint [ 0 ] ) ; } if ( ! listOut . isEmpty ( ) ) { out = listOut . toArray ( new InjectionPoint [ 0 ] ) ; } return new ScopeData ( this , in , out ) ; }


Input: Visits a type . [CODESPLIT] public void visit ( ) { ClassDescriptor classDescriptor = ClassIntrospector . get ( ) . lookup ( type ) ; if ( classMetadataName != null ) { // process first 'meta' fields 'class' onProperty ( classMetadataName , null , false ) ; } PropertyDescriptor [ ] propertyDescriptors = classDescriptor . getAllPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { Getter getter = propertyDescriptor . getGetter ( declared ) ; if ( getter != null ) { String propertyName = propertyDescriptor . getName ( ) ; boolean isTransient = false ; // check for transient flag FieldDescriptor fieldDescriptor = propertyDescriptor . getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { isTransient = Modifier . isTransient ( fieldDescriptor . getField ( ) . getModifiers ( ) ) ; } onProperty ( propertyName , propertyDescriptor , isTransient ) ; } } }


Input: Invoked on each property . Properties are getting matched against the rules . If property passes all the rules it will be processed in { [CODESPLIT] protected void onProperty ( String propertyName , final PropertyDescriptor propertyDescriptor , final boolean isTransient ) { Class propertyType = propertyDescriptor == null ? null : propertyDescriptor . getType ( ) ; Path currentPath = jsonContext . path ; currentPath . push ( propertyName ) ; // change name for properties if ( propertyType != null ) { propertyName = typeData . resolveJsonName ( propertyName ) ; } // determine if name should be included/excluded boolean include = ! typeData . strict ; // + don't include transient fields if ( isTransient ) { include = false ; } // + all collections are not serialized by default include = jsonContext . matchIgnoredPropertyTypes ( propertyType , true , include ) ; // + annotations include = typeData . rules . apply ( propertyName , true , include ) ; // + path queries: excludes/includes include = jsonContext . matchPathToQueries ( include ) ; // done if ( ! include ) { currentPath . pop ( ) ; return ; } onSerializableProperty ( propertyName , propertyDescriptor ) ; currentPath . pop ( ) ; }


Input: Returns urls for the classloader [CODESPLIT] public static URL [ ] of ( ClassLoader classLoader , Class clazz ) { if ( clazz == null ) { clazz = ClassPathURLs . class ; } if ( classLoader == null ) { classLoader = clazz . getClassLoader ( ) ; } final Set < URL > urls = new LinkedHashSet <> ( ) ; while ( classLoader != null ) { if ( classLoader instanceof URLClassLoader ) { final URLClassLoader urlClassLoader = ( URLClassLoader ) classLoader ; return urlClassLoader . getURLs ( ) ; } final URL url = classModuleUrl ( classLoader , clazz ) ; if ( url != null ) { urls . add ( url ) ; } classLoader = classLoader . getParent ( ) ; } return urls . toArray ( new URL [ 0 ] ) ; }


Input: Sets new bean instance . [CODESPLIT] private void setBean ( final Object bean ) { this . bean = bean ; this . cd = ( bean == null ? null : introspector . lookup ( bean . getClass ( ) ) ) ; this . first = false ; this . updateProperty = true ; }


Input: Updates the bean . Detects special case of suppliers . [CODESPLIT] public void updateBean ( final Object bean ) { this . setBean ( bean ) ; if ( this . cd != null && this . cd . isSupplier ( ) ) { final Object newBean = ( ( Supplier ) this . bean ) . get ( ) ; setBean ( newBean ) ; } }


Input: Loads property descriptor if property was updated . [CODESPLIT] private void loadPropertyDescriptor ( ) { if ( updateProperty ) { if ( cd == null ) { propertyDescriptor = null ; } else { propertyDescriptor = cd . getPropertyDescriptor ( name , true ) ; } updateProperty = false ; } }


Input: Returns getter . [CODESPLIT] public Getter getGetter ( final boolean declared ) { loadPropertyDescriptor ( ) ; return propertyDescriptor != null ? propertyDescriptor . getGetter ( declared ) : null ; }


Input: Returns setter . [CODESPLIT] public Setter getSetter ( final boolean declared ) { loadPropertyDescriptor ( ) ; return propertyDescriptor != null ? propertyDescriptor . getSetter ( declared ) : null ; }


Input: Initializes the DbOom by connecting to the database . Database will be detected and DbOom will be configured to match it . [CODESPLIT] public DbOom connect ( ) { connectionProvider . init ( ) ; final DbDetector dbDetector = new DbDetector ( ) ; dbDetector . detectDatabaseAndConfigureDbOom ( connectionProvider , dbOomConfig ) ; return this ; }


Input: Adds an iterator to this composite . [CODESPLIT] public void add ( final Iterator < T > iterator ) { if ( allIterators . contains ( iterator ) ) { throw new IllegalArgumentException ( "Duplicate iterator" ) ; } allIterators . add ( iterator ) ; }


Input: Returns <code > true< / code > if next element is available . [CODESPLIT] @ Override public boolean hasNext ( ) { if ( currentIterator == - 1 ) { currentIterator = 0 ; } for ( int i = currentIterator ; i < allIterators . size ( ) ; i ++ ) { Iterator iterator = allIterators . get ( i ) ; if ( iterator . hasNext ( ) ) { currentIterator = i ; return true ; } } return false ; }


Input: Detects if there was a <code > null< / code > reading and returns <code > null< / code > if it was . Result set returns default value ( e . g . 0 ) for many getters therefore it detects if it was a null reading or it is a real value . [CODESPLIT] @ Override public < E > E readValue ( final ResultSet rs , final int index , final Class < E > destinationType , final int dbSqlType ) throws SQLException { T t = get ( rs , index , dbSqlType ) ; if ( ( t == null ) || ( rs . wasNull ( ) ) ) { return null ; } return prepareGetValue ( t , destinationType ) ; }


Input: Detects <code > null< / code > before storing the value into the database . [CODESPLIT] @ Override public void storeValue ( final PreparedStatement st , final int index , final Object value , final int dbSqlType ) throws SQLException { if ( value == null ) { st . setNull ( index , dbSqlType ) ; return ; } super . storeValue ( st , index , value , dbSqlType ) ; }


Input: Starts the Joy . Returns the { [CODESPLIT] public JoddJoyRuntime start ( final ServletContext servletContext ) { LoggerProvider loggerProvider = null ; if ( loggerProviderSupplier != null ) { loggerProvider = loggerProviderSupplier . get ( ) ; } if ( loggerProvider == null ) { loggerProvider = SimpleLogger . PROVIDER ; } LoggerFactory . setLoggerProvider ( loggerProvider ) ; log = LoggerFactory . getLogger ( JoddJoy . class ) ; printLogo ( ) ; log . info ( "Ah, Joy!" ) ; log . info ( "Logging using: " + loggerProvider . getClass ( ) . getSimpleName ( ) ) ; joyPropsConsumers . accept ( joyProps ) ; joyProxettaConsumers . accept ( joyProxetta ) ; joyDbConsumers . accept ( joyDb ) ; joyPetiteConsumers . accept ( joyPetite ) ; try { joyPaths . start ( ) ; joyProps . start ( ) ; joyProxetta . start ( ) ; joyScanner . start ( ) ; joyPetite . start ( ) ; joyPetite . getPetiteContainer ( ) . addBean ( appName + ".core" , this ) ; joyPetite . getPetiteContainer ( ) . addBean ( appName + ".scanner" , joyScanner ) ; joyDb . start ( ) ; joyMadvoc . setServletContext ( servletContext ) ; joyMadvoc . start ( ) ; runJoyInitBeans ( ) ; // cleanup things we will not use joyScanner . stop ( ) ; } catch ( Exception ex ) { if ( log != null ) { log . error ( ex . toString ( ) , ex ) ; } else { System . out . println ( ex . toString ( ) ) ; ex . printStackTrace ( ) ; } stop ( ) ; throw ex ; } joyPetite . printBeans ( 100 ) ; joyDb . printEntities ( 100 ) ; joyMadvoc . printRoutes ( 100 ) ; System . out . println ( Chalk256 . chalk ( ) . yellow ( ) . on ( "Joy" ) + " is up. Enjoy!" ) ; log . info ( "Joy is up. Enjoy!" ) ; if ( joyDb . isDatabaseEnabled ( ) ) { return new JoddJoyRuntime ( appName , joyPaths . getAppDir ( ) , joyProps . getProps ( ) , joyProxetta . getProxetta ( ) , joyPetite . getPetiteContainer ( ) , joyMadvoc . getWebApp ( ) , joyDb . isDatabaseEnabled ( ) , joyDb . getConnectionProvider ( ) , joyDb . getJtxManager ( ) ) ; } else { return new JoddJoyRuntime ( appName , joyPaths . getAppDir ( ) , joyProps . getProps ( ) , joyProxetta . getProxetta ( ) , joyPetite . getPetiteContainer ( ) , joyMadvoc . getWebApp ( ) ) ; } }


Input: Prints a logo . [CODESPLIT] private void printLogo ( ) { System . out . println ( Chalk256 . chalk ( ) . yellow ( ) . on ( Jodd . JODD ) ) ; }


Input: Stops the Joy . [CODESPLIT] public void stop ( ) { joyProps . stop ( ) ; try { joyDb . stop ( ) ; joyPetite . stop ( ) ; } catch ( Exception ignore ) { } if ( log != null ) { log . info ( "Joy is down. Bye, bye!" ) ; } }


Input: Creates new connection from current { @link jodd . http . HttpRequest request } . [CODESPLIT] @ Override public HttpConnection createHttpConnection ( final HttpRequest httpRequest ) throws IOException { final SocketHttpConnection httpConnection ; final boolean https = httpRequest . protocol ( ) . equalsIgnoreCase ( "https" ) ; if ( https ) { SSLSocket sslSocket = createSSLSocket ( httpRequest . host ( ) , httpRequest . port ( ) , httpRequest . connectionTimeout ( ) , httpRequest . trustAllCertificates ( ) , httpRequest . verifyHttpsHost ( ) ) ; httpConnection = new SocketHttpSecureConnection ( sslSocket ) ; } else { Socket socket = createSocket ( httpRequest . host ( ) , httpRequest . port ( ) , httpRequest . connectionTimeout ( ) ) ; httpConnection = new SocketHttpConnection ( socket ) ; } // prepare connection config httpConnection . setTimeout ( httpRequest . timeout ( ) ) ; try { // additional socket initialization httpConnection . init ( ) ; } catch ( Throwable throwable ) { // @wjw_add httpConnection . close ( ) ; throw new HttpException ( throwable ) ; } return httpConnection ; }


Input: Creates a socket using socket factory . [CODESPLIT] protected Socket createSocket ( final String host , final int port , final int connectionTimeout ) throws IOException { final SocketFactory socketFactory = getSocketFactory ( proxy , false , false , connectionTimeout ) ; if ( connectionTimeout < 0 ) { return socketFactory . createSocket ( host , port ) ; } else { // creates unconnected socket Socket socket = socketFactory . createSocket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , connectionTimeout ) ; return socket ; } }


Input: Creates a SSL socket . Enables default secure enabled protocols if specified . [CODESPLIT] protected SSLSocket createSSLSocket ( final String host , final int port , final int connectionTimeout , final boolean trustAll , final boolean verifyHttpsHost ) throws IOException { final SocketFactory socketFactory = getSocketFactory ( proxy , true , trustAll , connectionTimeout ) ; final Socket socket ; if ( connectionTimeout < 0 ) { socket = socketFactory . createSocket ( host , port ) ; } else { // creates unconnected socket // unfortunately, this does not work always //			sslSocket = (SSLSocket) socketFactory.createSocket(); //			sslSocket.connect(new InetSocketAddress(host, port), connectionTimeout); // // Note: SSLSocketFactory has several create() methods. // Those that take arguments all connect immediately // and have no options for specifying a connection timeout. // // So, we have to create a socket and connect it (with a // connection timeout), then have the SSLSocketFactory wrap // the already-connected socket. // socket = Sockets . connect ( host , port , connectionTimeout ) ; //sock.setSoTimeout(readTimeout); //socket.connect(new InetSocketAddress(host, port), connectionTimeout); // continue to wrap this plain socket with ssl socket... } // wrap plain socket in an SSL socket SSLSocket sslSocket ; if ( socket instanceof SSLSocket ) { sslSocket = ( SSLSocket ) socket ; } else { if ( socketFactory instanceof SSLSocketFactory ) { sslSocket = ( SSLSocket ) ( ( SSLSocketFactory ) socketFactory ) . createSocket ( socket , host , port , true ) ; } else { sslSocket = ( SSLSocket ) ( getDefaultSSLSocketFactory ( trustAll ) ) . createSocket ( socket , host , port , true ) ; } } // sslSocket is now ready if ( secureEnabledProtocols != null ) { final String [ ] values = StringUtil . splitc ( secureEnabledProtocols , ' ' ) ; StringUtil . trimAll ( values ) ; sslSocket . setEnabledProtocols ( values ) ; } // set SSL parameters to allow host name verifier if ( verifyHttpsHost ) { final SSLParameters sslParams = new SSLParameters ( ) ; sslParams . setEndpointIdentificationAlgorithm ( "HTTPS" ) ; sslSocket . setSSLParameters ( sslParams ) ; } return sslSocket ; }


Input: Returns default SSL socket factory allowing setting trust managers . [CODESPLIT] protected SSLSocketFactory getDefaultSSLSocketFactory ( final boolean trustAllCertificates ) throws IOException { if ( trustAllCertificates ) { try { SSLContext sc = SSLContext . getInstance ( sslProtocol ) ; sc . init ( null , TrustManagers . TRUST_ALL_CERTS , new java . security . SecureRandom ( ) ) ; return sc . getSocketFactory ( ) ; } catch ( NoSuchAlgorithmException | KeyManagementException e ) { throw new IOException ( e ) ; } } else { return ( SSLSocketFactory ) SSLSocketFactory . getDefault ( ) ; } }


Input: Returns socket factory based on proxy type and SSL requirements . [CODESPLIT] protected SocketFactory getSocketFactory ( final ProxyInfo proxy , final boolean ssl , final boolean trustAllCertificates , final int connectionTimeout ) throws IOException { switch ( proxy . getProxyType ( ) ) { case NONE : if ( ssl ) { return getDefaultSSLSocketFactory ( trustAllCertificates ) ; } else { return SocketFactory . getDefault ( ) ; } case HTTP : return new HTTPProxySocketFactory ( proxy , connectionTimeout ) ; case SOCKS4 : return new Socks4ProxySocketFactory ( proxy , connectionTimeout ) ; case SOCKS5 : return new Socks5ProxySocketFactory ( proxy , connectionTimeout ) ; default : return null ; } }


Input: Creates random string whose length is the number of characters specified . Characters are chosen from the set of characters specified . [CODESPLIT] public String random ( int count , final char [ ] chars ) { if ( count == 0 ) { return StringPool . EMPTY ; } final char [ ] result = new char [ count ] ; while ( count -- > 0 ) { result [ count ] = chars [ rnd . nextInt ( chars . length ) ] ; } return new String ( result ) ; }


Input: Creates random string whose length is the number of characters specified . Characters are chosen from the provided range . [CODESPLIT] public String random ( int count , final char start , final char end ) { if ( count == 0 ) { return StringPool . EMPTY ; } final char [ ] result = new char [ count ] ; final int len = end - start + 1 ; while ( count -- > 0 ) { result [ count ] = ( char ) ( rnd . nextInt ( len ) + start ) ; } return new String ( result ) ; }


Input: Creates random string whose length is the number of characters specified . Characters are chosen from the multiple sets defined by range pairs . All ranges must be in acceding order . [CODESPLIT] public String randomRanges ( int count , final char ... ranges ) { if ( count == 0 ) { return StringPool . EMPTY ; } int i = 0 ; int len = 0 ; final int [ ] lens = new int [ ranges . length ] ; while ( i < ranges . length ) { int gap = ranges [ i + 1 ] - ranges [ i ] + 1 ; len += gap ; lens [ i ] = len ; i += 2 ; } final char [ ] result = new char [ count ] ; while ( count -- > 0 ) { char c = 0 ; int r = rnd . nextInt ( len ) ; for ( i = 0 ; i < ranges . length ; i += 2 ) { if ( r < lens [ i ] ) { r += ranges [ i ] ; if ( i != 0 ) { r -= lens [ i - 2 ] ; } c = ( char ) r ; break ; } } result [ count ] = c ; } return new String ( result ) ; }


Input: Parses EML with provided EML content . [CODESPLIT] public ReceivedEmail parse ( final String emlContent , final String charset ) throws UnsupportedEncodingException , MessagingException { final byte [ ] bytes = emlContent . getBytes ( charset ) ; return parse ( bytes ) ; }


Input: Parses EML with provided EML content . [CODESPLIT] public ReceivedEmail parse ( final String emlContent ) throws MessagingException { try { return parse ( emlContent , JoddCore . encoding ) ; } catch ( final UnsupportedEncodingException ignore ) { return null ; } }


Input: Starts EML parsing with provided EML { @link File } . [CODESPLIT] public ReceivedEmail parse ( final File emlFile ) throws FileNotFoundException , MessagingException { final FileInputStream fileInputStream = new FileInputStream ( emlFile ) ; try { return parse ( fileInputStream ) ; } finally { StreamUtil . close ( fileInputStream ) ; } }


Input: Parses the EML content . If { @link Session } is not created default one will be used . [CODESPLIT] protected ReceivedEmail parse ( final InputStream emlContentInputStream ) throws MessagingException { if ( getSession ( ) == null ) { createSession ( getProperties ( ) ) ; } try { final MimeMessage message = new MimeMessage ( getSession ( ) , emlContentInputStream ) ; return new ReceivedEmail ( message , false , null ) ; } finally { StreamUtil . close ( emlContentInputStream ) ; } }


Input: Creates new type for JSON array objects . It returns a collection . Later the collection will be converted into the target type . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) protected Collection < Object > newArrayInstance ( final Class targetType ) { if ( targetType == null || targetType == List . class || targetType == Collection . class || targetType . isArray ( ) ) { return listSupplier . get ( ) ; } if ( targetType == Set . class ) { return new HashSet <> ( ) ; } try { return ( Collection < Object > ) targetType . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new JsonException ( e ) ; } }


Input: Creates new object or a <code > HashMap< / code > if type is not specified . [CODESPLIT] protected Object newObjectInstance ( final Class targetType ) { if ( targetType == null || targetType == Map . class ) { return mapSupplier . get ( ) ; } final ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( targetType ) ; final CtorDescriptor ctorDescriptor = cd . getDefaultCtorDescriptor ( true ) ; if ( ctorDescriptor == null ) { throw new JsonException ( "Default ctor not found for: " + targetType . getName ( ) ) ; } try { //			return ClassUtil.newInstance(targetType); return ctorDescriptor . getConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new JsonException ( e ) ; } }


Input: Injects value into the targets property . [CODESPLIT] protected void injectValueIntoObject ( final Object target , final PropertyDescriptor pd , final Object value ) { Object convertedValue = value ; if ( value != null ) { Class targetClass = pd . getType ( ) ; convertedValue = convertType ( value , targetClass ) ; } try { Setter setter = pd . getSetter ( true ) ; if ( setter != null ) { setter . invokeSetter ( target , convertedValue ) ; } } catch ( Exception ex ) { throw new JsonException ( ex ) ; } }


Input: Converts type of the given value . [CODESPLIT] protected Object convertType ( final Object value , final Class targetType ) { final Class valueClass = value . getClass ( ) ; if ( valueClass == targetType ) { return value ; } try { return TypeConverterManager . get ( ) . convertType ( value , targetType ) ; } catch ( Exception ex ) { if ( ! strictTypes ) { return null ; } throw new JsonException ( "Type conversion failed" , ex ) ; } }


Input: Visit an implementation of a service . [CODESPLIT] public void visitProvide ( final String service , final String ... providers ) { if ( mv != null ) { mv . visitProvide ( service , providers ) ; } }


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


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


Input: ---------------------------------------------------------------- header [CODESPLIT] @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { wd . init ( name , superName , suffix , reqProxyClassName ) ; // write destination class final int v = ProxettaAsmUtil . resolveJavaVersion ( version ) ; super . visit ( v , access , wd . thisReference , signature , wd . superName , interfaces ) ; }


Input: Creates default implementation of the type cache . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < A > TypeCache < A > createDefault ( ) { return ( TypeCache < A > ) Defaults . implementation . get ( ) ; }


Input: Add values to the map . [CODESPLIT] public T put ( final Class < ? > type , final T value ) { return map . put ( type , value ) ; }


Input: Returns existing value or add default supplied one . Use this method instead of { [CODESPLIT] public T get ( final Class < ? > key , final Supplier < T > valueSupplier ) { return map . computeIfAbsent ( key , aClass -> valueSupplier . get ( ) ) ; }


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


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


Input: Inspects types methods and return map of { [CODESPLIT] protected HashMap < String , MethodDescriptor [ ] > inspectMethods ( ) { boolean scanAccessible = classDescriptor . isScanAccessible ( ) ; if ( classDescriptor . isSystemClass ( ) ) { scanAccessible = false ; } final Class type = classDescriptor . getType ( ) ; final Method [ ] methods = scanAccessible ? ClassUtil . getAccessibleMethods ( type ) : ClassUtil . getSupportedMethods ( type ) ; final HashMap < String , MethodDescriptor [ ] > map = new HashMap <> ( methods . length ) ; for ( final Method method : methods ) { final String methodName = method . getName ( ) ; MethodDescriptor [ ] mds = map . get ( methodName ) ; if ( mds == null ) { mds = new MethodDescriptor [ 1 ] ; } else { mds = ArraysUtil . resize ( mds , mds . length + 1 ) ; } map . put ( methodName , mds ) ; mds [ mds . length - 1 ] = createMethodDescriptor ( method ) ; } return map ; }


Input: Returns a method that matches given name and parameter types . Returns <code > null< / code > if method is not found . [CODESPLIT] public MethodDescriptor getMethodDescriptor ( final String name , final Class [ ] paramTypes ) { final MethodDescriptor [ ] methodDescriptors = methodsMap . get ( name ) ; if ( methodDescriptors == null ) { return null ; } for ( MethodDescriptor methodDescriptor : methodDescriptors ) { final Method m = methodDescriptor . getMethod ( ) ; if ( ClassUtil . compareParameters ( m . getParameterTypes ( ) , paramTypes ) ) { return methodDescriptor ; } } return null ; }


Input: Returns method descriptor for given name . If more then one methods with the same name exists one method will be returned ( not determined which one ) . Returns <code > null< / code > if no method exist in this collection by given name . [CODESPLIT] public MethodDescriptor getMethodDescriptor ( final String name ) { final MethodDescriptor [ ] methodDescriptors = methodsMap . get ( name ) ; if ( methodDescriptors == null ) { return null ; } if ( methodDescriptors . length != 1 ) { throw new IllegalArgumentException ( "Method name not unique: " + name ) ; } return methodDescriptors [ 0 ] ; }


Input: Returns all methods . Cached . Lazy . [CODESPLIT] public MethodDescriptor [ ] getAllMethodDescriptors ( ) { if ( allMethods == null ) { final List < MethodDescriptor > allMethodsList = new ArrayList <> ( ) ; for ( MethodDescriptor [ ] methodDescriptors : methodsMap . values ( ) ) { Collections . addAll ( allMethodsList , methodDescriptors ) ; } final MethodDescriptor [ ] allMethods = allMethodsList . toArray ( new MethodDescriptor [ 0 ] ) ; Arrays . sort ( allMethods , Comparator . comparing ( md -> md . getMethod ( ) . getName ( ) ) ) ; this . allMethods = allMethods ; } return allMethods ; }


Input: Resolves IP address from a hostname . [CODESPLIT] public static String resolveIpAddress ( final String hostname ) { try { InetAddress netAddress ; if ( hostname == null || hostname . equalsIgnoreCase ( LOCAL_HOST ) ) { netAddress = InetAddress . getLocalHost ( ) ; } else { netAddress = Inet4Address . getByName ( hostname ) ; } return netAddress . getHostAddress ( ) ; } catch ( UnknownHostException ignore ) { return null ; } }


Input: Returns IP address as integer . [CODESPLIT] public static int getIpAsInt ( final String ipAddress ) { int ipIntValue = 0 ; String [ ] tokens = StringUtil . splitc ( ipAddress , ' ' ) ; for ( String token : tokens ) { if ( ipIntValue > 0 ) { ipIntValue <<= 8 ; } ipIntValue += Integer . parseInt ( token ) ; } return ipIntValue ; }


Input: Checks given string against IP address v4 format . [CODESPLIT] public static boolean validateAgaintIPAdressV4Format ( final String input ) { if ( input == null ) { return false ; } int hitDots = 0 ; char [ ] data = input . toCharArray ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { char c = data [ i ] ; int b = 0 ; do { if ( c < ' ' || c > ' ' ) { return false ; } b = ( b * 10 + c ) - 48 ; if ( ++ i >= data . length ) { break ; } c = data [ i ] ; } while ( c != ' ' ) ; if ( b > 255 ) { return false ; } hitDots ++ ; } return hitDots == 4 ; }


Input: Resolves host name from IP address bytes . [CODESPLIT] public static String resolveHostName ( final byte [ ] ip ) { try { InetAddress address = InetAddress . getByAddress ( ip ) ; return address . getHostName ( ) ; } catch ( UnknownHostException ignore ) { return null ; } }


Input: Downloads resource as byte array . [CODESPLIT] public static byte [ ] downloadBytes ( final String url ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ) { return StreamUtil . readBytes ( inputStream ) ; } }


Input: Downloads resource as String . [CODESPLIT] public static String downloadString ( final String url , final String encoding ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ) { return new String ( StreamUtil . readChars ( inputStream , encoding ) ) ; } }


Input: Downloads resource to a file potentially very efficiently . [CODESPLIT] public static void downloadFile ( final String url , final File file ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ; ReadableByteChannel rbc = Channels . newChannel ( inputStream ) ; FileChannel fileChannel = FileChannel . open ( file . toPath ( ) , StandardOpenOption . CREATE , StandardOpenOption . TRUNCATE_EXISTING , StandardOpenOption . WRITE ) ) { fileChannel . transferFrom ( rbc , 0 , Long . MAX_VALUE ) ; } }


Input: Wraps the response and parse it using Lagarto parser . It first calls { [CODESPLIT] @ Override public void doFilter ( final ServletRequest servletRequest , final ServletResponse servletResponse , final FilterChain filterChain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) servletRequest ; HttpServletResponse response = ( HttpServletResponse ) servletResponse ; String actionPath = DispatcherUtil . getServletPath ( request ) ; if ( processActionPath ( request , response , actionPath ) ) { return ; } if ( ! acceptActionPath ( request , actionPath ) ) { filterChain . doFilter ( servletRequest , servletResponse ) ; return ; } BufferResponseWrapper wrapper = new BufferResponseWrapper ( response ) ; filterChain . doFilter ( servletRequest , wrapper ) ; // reset servlet response content length AFTER the chain, since // servlet container may set it and we are changing the content. servletResponse . setContentLength ( - 1 ) ; char [ ] content = wrapper . getBufferContentAsChars ( ) ; if ( ( content != null ) && ( content . length != 0 ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Lagarto is about to parse: " + actionPath ) ; } try { content = parse ( content , request ) ; } catch ( Exception ex ) { log . error ( "Error parsing" , ex ) ; throw new ServletException ( ex ) ; } wrapper . writeContentToResponse ( content ) ; } }


Input: Accepts action path for further parsing . By default only <code > * . htm ( l ) < / code > requests are passed through and those without any extension . [CODESPLIT] protected boolean acceptActionPath ( final HttpServletRequest request , final String actionPath ) { String extension = FileNameUtil . getExtension ( actionPath ) ; if ( extension . length ( ) == 0 ) { return true ; } if ( extension . equals ( "html" ) || extension . equals ( "htm" ) ) { return true ; } return false ; }


Input: Sets the { [CODESPLIT] @ Override public void render ( final ActionRequest actionRequest , final Object resultValue ) { final Chain chainResult ; if ( resultValue == null ) { chainResult = Chain . to ( StringPool . EMPTY ) ; } else { if ( resultValue instanceof String ) { chainResult = Chain . to ( ( String ) resultValue ) ; } else { chainResult = ( Chain ) resultValue ; } } final String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; final String resultPath = resultMapper . resolveResultPathString ( resultBasePath , chainResult . path ( ) ) ; actionRequest . setNextActionPath ( resultPath ) ; }


Input: { [CODESPLIT] @ Override public Object intercept ( final ActionRequest actionRequest ) throws Exception { HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; // detect multipart request if ( ServletUtil . isMultipartRequest ( servletRequest ) ) { servletRequest = new MultipartRequestWrapper ( servletRequest , fileUploader . get ( ) , madvocEncoding . getEncoding ( ) ) ; actionRequest . bind ( servletRequest ) ; } // do it inject ( actionRequest ) ; final Object result = actionRequest . invoke ( ) ; outject ( actionRequest ) ; return result ; }


Input: Performs injection . [CODESPLIT] protected void inject ( final ActionRequest actionRequest ) { final Targets targets = actionRequest . getTargets ( ) ; final ServletContext servletContext = actionRequest . getHttpServletRequest ( ) . getServletContext ( ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( servletContext , targets ) ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( actionRequest , targets ) ) ; }


Input: Performs outjection . [CODESPLIT] protected void outject ( final ActionRequest actionRequest ) { final Targets targets = actionRequest . getTargets ( ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . outject ( actionRequest , targets ) ) ; }


Input: Creates a socket . [CODESPLIT] public static Socket connect ( final String hostname , final int port ) throws IOException { final Socket socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( hostname , port ) ) ; return socket ; }


Input: Creates a socket with a timeout . [CODESPLIT] public static Socket connect ( final String hostname , final int port , final int connectionTimeout ) throws IOException { final Socket socket = new Socket ( ) ; if ( connectionTimeout <= 0 ) { socket . connect ( new InetSocketAddress ( hostname , port ) ) ; } else { socket . connect ( new InetSocketAddress ( hostname , port ) , connectionTimeout ) ; } return socket ; }


Input: Prepares classname for loading respecting the arrays . Returns <code > null< / code > if class name is not an array . [CODESPLIT] public static String prepareArrayClassnameForLoading ( String className ) { int bracketCount = StringUtil . count ( className , ' ' ) ; if ( bracketCount == 0 ) { // not an array return null ; } String brackets = StringUtil . repeat ( ' ' , bracketCount ) ; int bracketIndex = className . indexOf ( ' ' ) ; className = className . substring ( 0 , bracketIndex ) ; int primitiveNdx = getPrimitiveClassNameIndex ( className ) ; if ( primitiveNdx >= 0 ) { className = String . valueOf ( PRIMITIVE_BYTECODE_NAME [ primitiveNdx ] ) ; return brackets + className ; } else { return brackets + ' ' + className + ' ' ; } }


Input: Detects if provided class name is a primitive type . Returns > = 0 number if so . [CODESPLIT] private static int getPrimitiveClassNameIndex ( final String className ) { int dotIndex = className . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { return - 1 ; } return Arrays . binarySearch ( PRIMITIVE_TYPE_NAMES , className ) ; }


Input: Loads class by name . [CODESPLIT] @ Override public Class loadClass ( final String className , final ClassLoader classLoader ) throws ClassNotFoundException { String arrayClassName = prepareArrayClassnameForLoading ( className ) ; if ( ( className . indexOf ( ' ' ) == - 1 ) && ( arrayClassName == null ) ) { // maybe a primitive int primitiveNdx = getPrimitiveClassNameIndex ( className ) ; if ( primitiveNdx >= 0 ) { return PRIMITIVE_TYPES [ primitiveNdx ] ; } } // try #1 - using provided class loader if ( classLoader != null ) { Class klass = loadClass ( className , arrayClassName , classLoader ) ; if ( klass != null ) { return klass ; } } // try #2 - using thread class loader ClassLoader currentThreadClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( ( currentThreadClassLoader != null ) && ( currentThreadClassLoader != classLoader ) ) { Class klass = loadClass ( className , arrayClassName , currentThreadClassLoader ) ; if ( klass != null ) { return klass ; } } // try #3 - using caller classloader, similar as Class.forName() //Class callerClass = ReflectUtil.getCallerClass(2); Class callerClass = ClassUtil . getCallerClass ( ) ; ClassLoader callerClassLoader = callerClass . getClassLoader ( ) ; if ( ( callerClassLoader != classLoader ) && ( callerClassLoader != currentThreadClassLoader ) ) { Class klass = loadClass ( className , arrayClassName , callerClassLoader ) ; if ( klass != null ) { return klass ; } } // try #4 - everything failed, try alternative array loader if ( arrayClassName != null ) { try { return loadArrayClassByComponentType ( className , classLoader ) ; } catch ( ClassNotFoundException ignore ) { } } throw new ClassNotFoundException ( "Class not found: " + className ) ; }


Input: Loads a class using provided class loader . If class is an array it will be first loaded using the <code > Class . forName< / code > ! We must use this since for JDK { [CODESPLIT] protected Class loadClass ( final String className , final String arrayClassName , final ClassLoader classLoader ) { if ( arrayClassName != null ) { try { if ( loadArrayClassByComponentTypes ) { return loadArrayClassByComponentType ( className , classLoader ) ; } else { return Class . forName ( arrayClassName , true , classLoader ) ; } } catch ( ClassNotFoundException ignore ) { } } try { return classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } return null ; }


Input: Loads array class using component type . [CODESPLIT] protected Class loadArrayClassByComponentType ( final String className , final ClassLoader classLoader ) throws ClassNotFoundException { int ndx = className . indexOf ( ' ' ) ; int multi = StringUtil . count ( className , ' ' ) ; String componentTypeName = className . substring ( 0 , ndx ) ; Class componentType = loadClass ( componentTypeName , classLoader ) ; if ( multi == 1 ) { return Array . newInstance ( componentType , 0 ) . getClass ( ) ; } int [ ] multiSizes ; if ( multi == 2 ) { multiSizes = new int [ ] { 0 , 0 } ; } else if ( multi == 3 ) { multiSizes = new int [ ] { 0 , 0 , 0 } ; } else { multiSizes = ( int [ ] ) Array . newInstance ( int . class , multi ) ; } return Array . newInstance ( componentType , multiSizes ) . getClass ( ) ; }


Input: Iterate all beans and invokes registered destroy methods . [CODESPLIT] @ Override public void shutdown ( ) { for ( final BeanData beanData : instances . values ( ) ) { beanData . callDestroyMethods ( ) ; } instances . clear ( ) ; }


Input: Creates binary search wrapper over an array . [CODESPLIT] public static < T extends Comparable > BinarySearch < T > forArray ( final T [ ] array ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { "unchecked" } ) protected int compare ( final int index , final T element ) { return array [ index ] . compareTo ( element ) ; } @ Override protected int getLastIndex ( ) { return array . length - 1 ; } } ; }


Input: Creates binary search wrapper over an array with given comparator . [CODESPLIT] public static < T > BinarySearch < T > forArray ( final T [ ] array , final Comparator < T > comparator ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { "unchecked" } ) protected int compare ( final int index , final T element ) { return comparator . compare ( array [ index ] , element ) ; } @ Override protected int getLastIndex ( ) { return array . length - 1 ; } } ; }


Input: Finds index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int find ( final E element , int low , int high ) { while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid , element ) ; if ( delta < 0 ) { low = mid + 1 ; } else if ( delta > 0 ) { high = mid - 1 ; } else { return mid ; } } // not found return - ( low + 1 ) ; }


Input: Defines excluded property names . [CODESPLIT] public T exclude ( final String ... excludes ) { for ( String ex : excludes ) { rules . exclude ( ex ) ; } return _this ( ) ; }


Input: Defines included property names . [CODESPLIT] public T include ( final String ... includes ) { for ( String in : includes ) { rules . include ( in ) ; } return _this ( ) ; }


Input: Defines included property names as public properties of given template class . Sets to black list mode . [CODESPLIT] public T includeAs ( final Class template ) { blacklist = false ; String [ ] properties = getAllBeanPropertyNames ( template , false ) ; include ( properties ) ; return _this ( ) ; }


Input: Starts the tag with the index of first < . Resets all tag data . [CODESPLIT] public void start ( final int startIndex ) { this . tagStartIndex = startIndex ; this . name = null ; this . idNdx = - 1 ; this . attributesCount = 0 ; this . tagLength = 0 ; this . modified = false ; this . type = TagType . START ; this . rawTag = false ; }


Input: ---------------------------------------------------------------- match [CODESPLIT] @ Override public boolean nameEquals ( final CharSequence charSequence ) { return caseSensitive ? CharSequenceUtil . equals ( name , charSequence ) : CharSequenceUtil . equalsIgnoreCase ( name , charSequence ) ; }


Input: ---------------------------------------------------------------- util [CODESPLIT] private void ensureLength ( ) { if ( attributesCount + 1 >= attrNames . length ) { attrNames = ArraysUtil . resize ( attrNames , attributesCount * 2 ) ; attrValues = ArraysUtil . resize ( attrValues , attributesCount * 2 ) ; } }


Input: ---------------------------------------------------------------- output [CODESPLIT] private void appendTo ( final Appendable out ) { try { out . append ( type . getStartString ( ) ) ; out . append ( name ) ; if ( attributesCount > 0 ) { for ( int i = 0 ; i < attributesCount ; i ++ ) { out . append ( ' ' ) ; out . append ( attrNames [ i ] ) ; final CharSequence value = attrValues [ i ] ; if ( value != null ) { out . append ( ' ' ) . append ( ' ' ) ; out . append ( HtmlEncoder . attributeDoubleQuoted ( value ) ) ; out . append ( ' ' ) ; } } } out . append ( type . getEndString ( ) ) ; } catch ( IOException ioex ) { throw new LagartoException ( ioex ) ; } }


Input: Registers component using its { @link #resolveBaseComponentName ( Class ) base name } . Previously defined component will be removed . [CODESPLIT] public void registerComponent ( final Class component ) { String name = resolveBaseComponentName ( component ) ; registerComponent ( name , component ) ; }


Input: Registers Madvoc component with given name . [CODESPLIT] public < T > void registerComponent ( final String name , final Class < T > component , final Consumer < T > consumer ) { log . debug ( ( ) -> "Madvoc WebApp component: [" + name + "] --> " + component . getName ( ) ) ; madpc . removeBean ( name ) ; madpc . registerPetiteBean ( component , name , null , null , false , consumer ) ; }


Input: Registers component instance using its { @link #resolveBaseComponentName ( Class ) base name } . Previously defined component will be removed . [CODESPLIT] public void registerComponentInstance ( final Object componentInstance ) { Class component = componentInstance . getClass ( ) ; String name = resolveBaseComponentName ( component ) ; registerComponentInstance ( name , componentInstance ) ; }


Input: Registers component instance and wires it with internal container . Warning : in this moment we can not guarantee that all other components are registered replaced or configuration is update ; therefore DO NOT USE injection unless you are absolutely sure it works . [CODESPLIT] public void registerComponentInstance ( final String name , final Object componentInstance ) { log . debug ( ( ) -> "Madvoc WebApp component: [" + name + "] --> " + componentInstance . getClass ( ) . getName ( ) ) ; madpc . removeBean ( name ) ; madpc . addBean ( name , componentInstance ) ; }


Input: Fires the Madvoc event . Warning : since event handlers may register more handlers we must collect first the list of components that matches the type and then to execute . [CODESPLIT] public void fireEvent ( final Class listenerType ) { final Set < String > existing = new HashSet <> ( ) ; while ( true ) { MutableInteger newCount = MutableInteger . of ( 0 ) ; madpc . forEachBeanType ( listenerType , name -> { if ( existing . add ( name ) ) { // name not found, fire! newCount . value ++ ; Object listener = lookupComponent ( name ) ; if ( listener != null ) { MadvocComponentLifecycle . invoke ( listener , listenerType ) ; } } } ) ; if ( newCount . value == 0 ) { break ; } } }


Input: Returns registered component or { [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public < T > T lookupComponent ( final Class < T > component ) { String name = resolveBaseComponentName ( component ) ; return ( T ) madpc . getBean ( name ) ; }


Input: Returns existing component . Throws an exception if component is not registered . [CODESPLIT] public < T > T requestComponent ( final Class < T > component ) { T existingComponent = lookupComponent ( component ) ; if ( existingComponent == null ) { throw new MadvocException ( "Madvoc component not found: " + component . getName ( ) ) ; } return existingComponent ; }


Input: Returns existing component . Throws an exception if component is not registered . [CODESPLIT] public < T > T requestComponent ( final String componentName ) { T existingComponent = ( T ) lookupComponent ( componentName ) ; if ( existingComponent == null ) { throw new MadvocException ( "Madvoc component not found: " + componentName ) ; } return existingComponent ; }


Input: Resolves the name of the last base non - abstract subclass for provided component . It iterates all subclasses up to the <code > Object< / cde > and declares the last non - abstract class as base component . Component name will be resolved from the founded base component . [CODESPLIT] private String resolveBaseComponentName ( Class component ) { Class lastComponent = component ; while ( true ) { Class superClass = component . getSuperclass ( ) ; if ( superClass . equals ( Object . class ) ) { break ; } component = superClass ; if ( ! Modifier . isAbstract ( component . getModifiers ( ) ) ) { lastComponent = component ; } } return madpc . resolveBeanName ( lastComponent ) ; }


Input: Prepares the query after initialization . Besides default work it checks if sql generator is used and if so generator hints and query parameters will be used for this query . Note regarding hints : since hints can be added manually generators hints will be ignored if there exists some manually set hints . [CODESPLIT] @ Override protected void prepareQuery ( ) { super . prepareQuery ( ) ; if ( sqlgen == null ) { return ; } if ( hints == null ) { String [ ] joinHints = sqlgen . getJoinHints ( ) ; if ( joinHints != null ) { withHints ( joinHints ) ; } } // insert parameters Map < String , ParameterValue > parameters = sqlgen . getQueryParameters ( ) ; if ( parameters == null ) { return ; } for ( Map . Entry < String , ParameterValue > entry : parameters . entrySet ( ) ) { String paramName = entry . getKey ( ) ; ParameterValue param = entry . getValue ( ) ; DbEntityColumnDescriptor dec = param . getColumnDescriptor ( ) ; if ( dec == null ) { setObject ( paramName , param . getValue ( ) ) ; } else { resolveColumnDbSqlType ( connection , dec ) ; setObject ( paramName , param . getValue ( ) , dec . getSqlTypeClass ( ) , dec . getDbSqlType ( ) ) ; } } }


Input: Resolves column db sql type and populates it in column descriptor if missing . [CODESPLIT] protected void resolveColumnDbSqlType ( final Connection connection , final DbEntityColumnDescriptor dec ) { if ( dec . dbSqlType != SqlType . DB_SQLTYPE_UNKNOWN ) { return ; } ResultSet rs = null ; DbEntityDescriptor ded = dec . getDbEntityDescriptor ( ) ; try { DatabaseMetaData dmd = connection . getMetaData ( ) ; rs = dmd . getColumns ( null , ded . getSchemaName ( ) , ded . getTableName ( ) , dec . getColumnName ( ) ) ; if ( rs . next ( ) ) { dec . dbSqlType = rs . getInt ( "DATA_TYPE" ) ; } else { dec . dbSqlType = SqlType . DB_SQLTYPE_NOT_AVAILABLE ; if ( log . isWarnEnabled ( ) ) { log . warn ( "Column SQL type not available: " + ded . toString ( ) + ' ' + dec . getColumnName ( ) ) ; } } } catch ( SQLException sex ) { dec . dbSqlType = SqlType . DB_SQLTYPE_NOT_AVAILABLE ; if ( log . isWarnEnabled ( ) ) { log . warn ( "Column SQL type not resolved: " + ded . toString ( ) + ' ' + dec . getColumnName ( ) , sex ) ; } } finally { DbUtil . close ( rs ) ; } }


Input: Pre - process SQL before using it . If string starts with a non - ascii char or it has no spaces it will be loaded from the query map . [CODESPLIT] protected String preprocessSql ( String sqlString ) { // detects callable statement if ( sqlString . charAt ( 0 ) == ' ' ) { return sqlString ; } // quickly detect if SQL string is a key if ( ! CharUtil . isAlpha ( sqlString . charAt ( 0 ) ) ) { sqlString = sqlString . substring ( 1 ) ; } else if ( sqlString . indexOf ( ' ' ) != - 1 ) { return sqlString ; } final String sqlFromMap = dbOom . queryMap ( ) . getQuery ( sqlString ) ; if ( sqlFromMap != null ) { sqlString = sqlFromMap . trim ( ) ; } return sqlString ; }


Input: Prepares a row ( array of rows mapped object ) using hints . Returns either single object or objects array . [CODESPLIT] protected Object resolveRowResults ( Object [ ] row ) { if ( hintResolver == null ) { hintResolver = new JoinHintResolver ( ) ; } row = hintResolver . join ( row , hints ) ; return row . length == 1 ? row [ 0 ] : row ; }


Input: Factory for result sets mapper . [CODESPLIT] protected ResultSetMapper createResultSetMapper ( final ResultSet resultSet ) { final Map < String , ColumnData > columnAliases = sqlgen != null ? sqlgen . getColumnData ( ) : null ; return new DefaultResultSetMapper ( dbOom , resultSet , columnAliases , cacheEntities , this ) ; }


Input: Finds generated key column of given type . [CODESPLIT] public < T > T findGeneratedKey ( final Class < T > type ) { return find ( new Class [ ] { type } , false , getGeneratedColumns ( ) ) ; }


Input: Populates entity with generated column values from executed query . [CODESPLIT] public void populateGeneratedKeys ( final Object entity ) { final String [ ] generatedColumns = getGeneratedColumnNames ( ) ; if ( generatedColumns == null ) { return ; } DbEntityDescriptor ded = dbOom . entityManager ( ) . lookupType ( entity . getClass ( ) ) ; // prepare key types Class [ ] keyTypes = new Class [ generatedColumns . length ] ; String [ ] properties = new String [ generatedColumns . length ] ; for ( int i = 0 ; i < generatedColumns . length ; i ++ ) { String column = generatedColumns [ i ] ; DbEntityColumnDescriptor decd = ded . findByColumnName ( column ) ; if ( decd != null ) { keyTypes [ i ] = decd . getPropertyType ( ) ; properties [ i ] = decd . getPropertyName ( ) ; } } final Object keyValues = findGeneratedColumns ( keyTypes ) ; if ( ! keyValues . getClass ( ) . isArray ( ) ) { BeanUtil . declared . setProperty ( entity , properties [ 0 ] , keyValues ) ; } else { for ( int i = 0 ; i < properties . length ; i ++ ) { BeanUtil . declared . setProperty ( entity , properties [ i ] , ( ( Object [ ] ) keyValues ) [ i ] ) ; } } }


Input: Acquires interceptor from Petite container . [CODESPLIT] @ Override protected < R extends ActionInterceptor > R createWrapper ( final Class < R > wrapperClass ) { return petiteContainer . createBean ( wrapperClass ) ; }


Input: Clears the current parameter values immediately . <p > In general parameter values remain in force for repeated use of a statement . Setting a parameter value automatically clears its previous value . However in some cases it is useful to immediately release the resources used by the current parameter values ; this can be done by calling the method <code > clearParameters< / code > . [CODESPLIT] public Q clearParameters ( ) { init ( ) ; if ( preparedStatement == null ) { return _this ( ) ; } try { preparedStatement . clearParameters ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- null [CODESPLIT] public Q setNull ( final int index , final int type ) { initPrepared ( ) ; try { preparedStatement . setNull ( index , type ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , "Failed to set null to parameter: " + index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- int [CODESPLIT] public Q setInteger ( final int index , final int value ) { initPrepared ( ) ; try { preparedStatement . setInt ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Integer [CODESPLIT] public Q setInteger ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . INTEGER ) ; } else { setInteger ( index , value . intValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Boolean [CODESPLIT] public Q setBoolean ( final int index , final Boolean value ) { if ( value == null ) { setNull ( index , Types . BOOLEAN ) ; } else { setBoolean ( index , value . booleanValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Long [CODESPLIT] public Q setLong ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . BIGINT ) ; } else { setLong ( index , value . longValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Byte [CODESPLIT] public Q setByte ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . SMALLINT ) ; } else { setByte ( index , value . byteValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- double [CODESPLIT] public Q setDouble ( final int index , final double value ) { initPrepared ( ) ; try { preparedStatement . setDouble ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Double [CODESPLIT] public Q setDouble ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . DOUBLE ) ; } else { setDouble ( index , value . doubleValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Float [CODESPLIT] public Q setFloat ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . FLOAT ) ; } else { setFloat ( index , value . floatValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Short [CODESPLIT] public Q setShort ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . SMALLINT ) ; } else { setShort ( index , value . shortValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- string [CODESPLIT] public Q setString ( final int index , final String value ) { initPrepared ( ) ; try { preparedStatement . setString ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- date [CODESPLIT] public Q setDate ( final int index , final Date value ) { initPrepared ( ) ; try { preparedStatement . setDate ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- time [CODESPLIT] public Q setTime ( final int index , final Time value ) { initPrepared ( ) ; try { preparedStatement . setTime ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- timestamp [CODESPLIT] public Q setTimestamp ( final int index , final Timestamp value ) { initPrepared ( ) ; try { preparedStatement . setTimestamp ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- big decimal [CODESPLIT] public Q setBigDecimal ( final int index , final BigDecimal value ) { initPrepared ( ) ; try { preparedStatement . setBigDecimal ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- big integer [CODESPLIT] public Q setBigInteger ( final int index , final BigInteger value ) { if ( value == null ) { setNull ( index , Types . NUMERIC ) ; } else { setLong ( index , value . longValue ( ) ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- URL [CODESPLIT] public Q setURL ( final int index , final URL value ) { initPrepared ( ) ; try { preparedStatement . setURL ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- BLOB [CODESPLIT] public Q setBlob ( final int index , final Blob value ) { initPrepared ( ) ; try { preparedStatement . setBlob ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- CLOB [CODESPLIT] public Q setClob ( final int index , final Clob value ) { initPrepared ( ) ; try { preparedStatement . setClob ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Array [CODESPLIT] public Q setArray ( final int index , final Array value ) { initPrepared ( ) ; try { preparedStatement . setArray ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- Ref [CODESPLIT] public Q setRef ( final int index , final Ref value ) { initPrepared ( ) ; try { preparedStatement . setRef ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: ---------------------------------------------------------------- ascii streams [CODESPLIT] public Q setAsciiStream ( final int index , final InputStream stream ) { initPrepared ( ) ; try { preparedStatement . setAsciiStream ( index , stream , stream . available ( ) ) ; } catch ( IOException | SQLException ioex ) { throwSetParamError ( index , ioex ) ; } return _this ( ) ; }


Input: Sets bean parameters from bean . Non - existing bean properties are ignored . [CODESPLIT] public Q setBean ( final String beanName , final Object bean ) { if ( bean == null ) { return _this ( ) ; } init ( ) ; final String beanNamePrefix = beanName + ' ' ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; if ( paramName . startsWith ( beanNamePrefix ) ) { final String propertyName = paramName . substring ( beanNamePrefix . length ( ) ) ; if ( BeanUtil . declared . hasRootProperty ( bean , propertyName ) ) { final Object value = BeanUtil . declared . getProperty ( bean , propertyName ) ; setObject ( paramName , value ) ; } } } ) ; return _this ( ) ; }


Input: Sets properties from the map . [CODESPLIT] public Q setMap ( final Map parameters ) { if ( parameters == null ) { return _this ( ) ; } init ( ) ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; setObject ( paramName , parameters . get ( paramName ) ) ; } ) ; return _this ( ) ; }


Input: Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] public Q setObject ( final int index , final Object object , final int targetSqlType ) { initPrepared ( ) ; try { preparedStatement . setObject ( index , object , targetSqlType ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] public Q setObject ( final String param , final Object object , final int targetSqlType ) { initPrepared ( ) ; final int [ ] positions = query . getNamedParameterIndices ( param ) ; try { for ( final int position : positions ) { preparedStatement . setObject ( position , object , targetSqlType ) ; } } catch ( SQLException sex ) { throwSetParamError ( param , sex ) ; } return _this ( ) ; }


Input: Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] void setObject ( final int index , final Object object , final int targetSqlType , final int scale ) { initPrepared ( ) ; try { preparedStatement . setObject ( index , object , targetSqlType , scale ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } }


Input: Sets object parameter in an advanced way . <p > First it checks if object is <code > null< / code > and invokes <code > setNull< / code > if so . If object is not <code > null< / code > it tries to resolve { [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public Q setObject ( final int index , final Object value , final Class < ? extends SqlType > sqlTypeClass , final int dbSqlType ) { init ( ) ; if ( value == null ) { setNull ( index , Types . NULL ) ; return _this ( ) ; } final SqlType sqlType ; if ( sqlTypeClass != null ) { sqlType = SqlTypeManager . get ( ) . lookupSqlType ( sqlTypeClass ) ; } else { sqlType = SqlTypeManager . get ( ) . lookup ( value . getClass ( ) ) ; } try { if ( ( sqlType != null ) && ( dbSqlType != SqlType . DB_SQLTYPE_NOT_AVAILABLE ) ) { sqlType . storeValue ( preparedStatement , index , value , dbSqlType ) ; } else { DbUtil . setPreparedStatementObject ( preparedStatement , index , value , dbSqlType ) ; } } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }


Input: Sets an array of objects parameters in given order . [CODESPLIT] public Q setObjects ( final Object ... objects ) { int index = 1 ; for ( final Object object : objects ) { setObject ( index ++ , object ) ; } return _this ( ) ; }


Input: Sets sql parameters from two arrays : names and values . [CODESPLIT] public Q setObjects ( final String [ ] names , final Object [ ] values ) { init ( ) ; if ( names . length != values . length ) { throw new DbSqlException ( this , "Different number of parameter names and values" ) ; } for ( int i = 0 ; i < names . length ; i ++ ) { setObject ( names [ i ] , values [ i ] ) ; } return _this ( ) ; }


Input: Sets batch parameters with given array of values . [CODESPLIT] public Q setBatch ( final String name , final int [ ] array , int startingIndex ) { init ( ) ; final int batchSize = query . getBatchParameterSize ( name ) ; for ( int i = 1 ; i <= batchSize ; i ++ ) { final String paramName = name + ' ' + i ; if ( startingIndex < array . length ) { setInteger ( paramName , array [ startingIndex ] ) ; } else { setNull ( paramName , Types . INTEGER ) ; } startingIndex ++ ; } return _this ( ) ; }


Input: Sets batch parameters with given array of values . [CODESPLIT] public Q setBatch ( final String name , final Object [ ] array , int startingIndex ) { init ( ) ; final int batchSize = query . getBatchParameterSize ( name ) ; for ( int i = 1 ; i <= batchSize ; i ++ ) { final String paramName = name + ' ' + i ; if ( startingIndex < array . length ) { setObject ( paramName , array [ startingIndex ] ) ; } else { setObject ( paramName , null ) ; } startingIndex ++ ; } return _this ( ) ; }


Input: Appends chunk to previous one and maintains the double - linked list of the previous chunk . Current surrounding connections of this chunk will be cut - off . [CODESPLIT] public void insertChunkAfter ( final SqlChunk previous ) { SqlChunk next = previous . nextChunk ; previous . nextChunk = this ; this . previousChunk = previous ; if ( next != null ) { next . previousChunk = this ; this . nextChunk = next ; } }


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


Input: Lookups for entity name and throws an exception if entity type is invalid . [CODESPLIT] protected DbEntityDescriptor lookupType ( final Class entity ) { final DbEntityDescriptor ded = dbEntityManager . lookupType ( entity ) ; if ( ded == null ) { throw new DbSqlBuilderException ( "Invalid or not-persistent entity: " + entity . getName ( ) ) ; } return ded ; }


Input: Finds a table that contains given column . [CODESPLIT] protected DbEntityDescriptor findColumnRef ( final String columnRef ) { DbEntityDescriptor ded = templateData . findTableDescriptorByColumnRef ( columnRef ) ; if ( ded == null ) { throw new DbSqlBuilderException ( "Invalid column reference: [" + columnRef + "]" ) ; } return ded ; }


Input: Resolves table name or alias that will be used in the query . [CODESPLIT] protected String resolveTable ( final String tableRef , final DbEntityDescriptor ded ) { String tableAlias = templateData . getTableAlias ( tableRef ) ; if ( tableAlias != null ) { return tableAlias ; } return ded . getTableNameForQuery ( ) ; }


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


Input: Resolves object to a class . [CODESPLIT] protected static Class resolveClass ( final Object object ) { Class type = object . getClass ( ) ; return type == Class . class ? ( Class ) object : type ; }


Input: Returns <code > true< / code > if a value is considered empty i . e . not existing . [CODESPLIT] protected boolean isEmptyColumnValue ( final DbEntityColumnDescriptor dec , final Object value ) { if ( value == null ) { return true ; } // special case for ID column if ( dec . isId ( ) && value instanceof Number ) { final double d = ( ( Number ) value ) . doubleValue ( ) ; if ( d == 0.0d ) { return true ; } } // special case for primitives if ( dec . getPropertyType ( ) . isPrimitive ( ) ) { if ( char . class == dec . getPropertyType ( ) ) { final Character c = ( ( Character ) value ) ; if ( ' ' == c . charValue ( ) ) { return true ; } } else { final double d = ( ( Number ) value ) . doubleValue ( ) ; if ( d == 0 ) { return true ; } } } // special case for strings if ( value instanceof CharSequence ) { if ( StringUtil . isBlank ( ( CharSequence ) value ) ) { return true ; } } return false ; }


Input: Appends missing space if the output doesn t end with whitespace . [CODESPLIT] protected void appendMissingSpace ( final StringBuilder out ) { int len = out . length ( ) ; if ( len == 0 ) { return ; } len -- ; if ( ! CharUtil . isWhitespace ( out . charAt ( len ) ) ) { out . append ( ' ' ) ; } }


Input: ---------------------------------------------------------------- valid [CODESPLIT] public boolean isValid ( final ValidationConstraintContext vcc , final Object value ) { return validate ( vcc . getTarget ( ) , value , fieldName ) ; }


Input: ---------------------------------------------------------------- get / free [CODESPLIT] @ Override public Connection getConnection ( ) { PooledConnection pconn ; try { pconn = cpds . getPooledConnection ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( "Invalid pooled connection" , sex ) ; } try { return pconn . getConnection ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( "Invalid pooled connection" , sex ) ; } }


Input: Get an enumeration of the parameter names for uploaded files [CODESPLIT] public Enumeration < String > getFileParameterNames ( ) { if ( mreq == null ) { return null ; } return Collections . enumeration ( mreq . getFileParameterNames ( ) ) ; }


Input: Get a { @link FileUpload } array for the given input field name . [CODESPLIT] public FileUpload [ ] getFiles ( final String fieldName ) { if ( mreq == null ) { return null ; } return mreq . getFiles ( fieldName ) ; }


Input: Compares value of two same instances . [CODESPLIT] @ Override public int compareTo ( final MutableLong other ) { return value < other . value ? - 1 : ( value == other . value ? 0 : 1 ) ; }


Input: Include page which path is relative to the current HTTP request . [CODESPLIT] public static boolean include ( final ServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = request . getRequestDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }


Input: Include named resource . [CODESPLIT] public static boolean includeNamed ( final HttpServletRequest request , final ServletResponse response , final String resource ) throws IOException , ServletException { return includeNamed ( request . getServletContext ( ) , request , response , resource ) ; }


Input: Include named resource . [CODESPLIT] public static boolean includeNamed ( final ServletContext context , final ServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getNamedDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }


Input: Include page which path relative to the root of the ServletContext . [CODESPLIT] public static boolean includeAbsolute ( final HttpServletRequest request , final HttpServletResponse response , final String page ) throws IOException , ServletException { return includeAbsolute ( request . getServletContext ( ) , request , response , page ) ; }


Input: Include page which path relative to the root of the ServletContext . [CODESPLIT] public static boolean includeAbsolute ( final ServletContext context , final ServletRequest request , final HttpServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getRequestDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }


Input: Forward to page path relative to the root of the ServletContext . [CODESPLIT] public static boolean forwardAbsolute ( final HttpServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { return forwardAbsolute ( request . getServletContext ( ) , request , response , page ) ; }


Input: Forward to page path relative to the root of the ServletContext . [CODESPLIT] public static boolean forwardAbsolute ( final ServletContext context , final ServletRequest request , final ServletResponse response , final String resource ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getRequestDispatcher ( resource ) ; if ( dispatcher != null ) { dispatcher . forward ( request , response ) ; return true ; } return false ; }


Input: Performs redirection ( 302 ) to specified url . [CODESPLIT] public static void redirect ( final HttpServletRequest request , final HttpServletResponse response , String url ) throws IOException { if ( url . startsWith ( StringPool . SLASH ) ) { url = ServletUtil . getContextPath ( request ) + url ; } response . sendRedirect ( response . encodeRedirectURL ( url ) ) ; }


Input: Performs permanent redirection ( 301 ) to specified url . [CODESPLIT] public static void redirectPermanent ( final HttpServletRequest request , final HttpServletResponse response , String url ) { if ( url . startsWith ( StringPool . SLASH ) ) { url = ServletUtil . getContextPath ( request ) + url ; } response . setStatus ( HttpServletResponse . SC_MOVED_PERMANENTLY ) ; response . setHeader ( "Location" , url ) ; }


Input: Returns full URL : uri + query string including the context path . [CODESPLIT] public static String getFullUrl ( final HttpServletRequest request ) { String url = request . getRequestURI ( ) ; String query = request . getQueryString ( ) ; if ( ( query != null ) && ( query . length ( ) != 0 ) ) { url += ' ' + query ; } return url ; }


Input: Returns url without context path convenient for request dispatcher . [CODESPLIT] public static String getUrl ( final HttpServletRequest request ) { String servletPath = request . getServletPath ( ) ; String query = request . getQueryString ( ) ; if ( ( query != null ) && ( query . length ( ) != 0 ) ) { servletPath += ' ' + query ; } return servletPath ; }


Input: Returns <code > true< / code > if current page is included . [CODESPLIT] public static boolean isPageIncluded ( final HttpServletRequest request , final HttpServletResponse response ) { return ( response . isCommitted ( ) || ( getIncludeServletPath ( request ) != null ) ) ; }


Input: Returns the base ( top - level ) uri . [CODESPLIT] public static String getBaseRequestUri ( final HttpServletRequest request ) { String result = getForwardRequestUri ( request ) ; if ( result == null ) { result = request . getRequestURI ( ) ; } return result ; }


Input: Get current request uri . [CODESPLIT] public static String getRequestUri ( final HttpServletRequest request ) { String result = getIncludeRequestUri ( request ) ; if ( result == null ) { result = request . getRequestURI ( ) ; } return result ; }


Input: Returns method parameter names . [CODESPLIT] public String [ ] resolveParamNames ( final Method actionClassMethod ) { MethodParameter [ ] methodParameters = Paramo . resolveParameters ( actionClassMethod ) ; String [ ] names = new String [ methodParameters . length ] ; for ( int i = 0 ; i < methodParameters . length ; i ++ ) { names [ i ] = methodParameters [ i ] . getName ( ) ; } return names ; }


Input: Builds { [CODESPLIT] public PathMacros buildActionPathMacros ( final String actionPath ) { if ( actionPath . isEmpty ( ) ) { return null ; } PathMacros pathMacros = createPathMacroInstance ( ) ; if ( ! pathMacros . init ( actionPath , actionsManager . getPathMacroSeparators ( ) ) ) { return null ; } return pathMacros ; }


Input: Creates new <code > PathMacro< / code > instance . [CODESPLIT] private PathMacros createPathMacroInstance ( ) { try { return ClassUtil . newInstance ( actionsManager . getPathMacroClass ( ) ) ; } catch ( Exception ex ) { throw new MadvocException ( ex ) ; } }


Input: Creates and initializes Petite container . It will be auto - magically configured by scanning the classpath . [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( "PETITE start  ----------" ) ; petiteContainer = createPetiteContainer ( ) ; if ( externalsCache ) { petiteContainer . setExternalsCache ( TypeCache . createDefault ( ) ) ; } log . info ( "Web application? " + isWebApplication ) ; if ( ! isWebApplication ) { // make session scope to act as singleton scope // if this is not a web application (and http session is not available). petiteContainer . registerScope ( SessionScope . class , new SingletonScope ( petiteContainer ) ) ; } // load parameters from properties files petiteContainer . defineParameters ( joyPropsSupplier . get ( ) . getProps ( ) ) ; // automagic configuration if ( autoConfiguration ) { final AutomagicPetiteConfigurator automagicPetiteConfigurator = new AutomagicPetiteConfigurator ( petiteContainer ) ; automagicPetiteConfigurator . registerAsConsumer ( joyScannerSupplier . get ( ) . getClassScanner ( ) ) ; } petiteContainerConsumers . accept ( this . petiteContainer ) ; log . info ( "PETITE OK!" ) ; }


Input: Stops Petite container . [CODESPLIT] @ Override public void stop ( ) { if ( log != null ) { log . info ( "PETITE stop" ) ; } if ( petiteContainer != null ) { petiteContainer . shutdown ( ) ; } petiteContainer = null ; }


Input: ---------------------------------------------------------------- print [CODESPLIT] public void printBeans ( final int width ) { final Print print = new Print ( ) ; print . line ( "Beans" , width ) ; final List < BeanDefinition > beanDefinitionList = new ArrayList <> ( ) ; final String appName = appNameSupplier . get ( ) ; final String prefix = appName + "." ; petiteContainer . forEachBean ( beanDefinitionList :: add ) ; beanDefinitionList . stream ( ) . sorted ( ( bd1 , bd2 ) -> { if ( bd1 . name ( ) . startsWith ( prefix ) ) { if ( bd2 . name ( ) . startsWith ( prefix ) ) { return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } return 1 ; } if ( bd2 . name ( ) . startsWith ( prefix ) ) { if ( bd1 . name ( ) . startsWith ( prefix ) ) { return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } return - 1 ; } return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } ) . forEach ( beanDefinition -> { print . out ( Chalk256 . chalk ( ) . yellow ( ) , scopeName ( beanDefinition ) , 10 ) ; print . space ( ) ; print . outLeftRightNewLine ( Chalk256 . chalk ( ) . green ( ) , beanDefinition . name ( ) , Chalk256 . chalk ( ) . blue ( ) , ClassUtil . getShortClassName ( beanDefinition . type ( ) , 2 ) , width - 10 - 1 ) ; } ) ; print . line ( width ) ; }


Input: Sets this CurrentFrame to the input stack map frame of the next current instruction i . e . the instruction just after the given one . It is assumed that the value of this object when this method is called is the stack map frame status just before the given instruction is executed . [CODESPLIT] @ Override void execute ( final int opcode , final int arg , final Symbol symbolArg , final SymbolTable symbolTable ) { super . execute ( opcode , arg , symbolArg , symbolTable ) ; Frame successor = new Frame ( null ) ; merge ( symbolTable , successor , 0 ) ; copyFrom ( successor ) ; }


Input: Defines filter for SUBJECT field . [CODESPLIT] public EmailFilter subject ( final String subject ) { final SearchTerm subjectTerm = new SubjectTerm ( subject ) ; concat ( subjectTerm ) ; return this ; }


Input: Defines filter for message id . [CODESPLIT] public EmailFilter messageId ( final String messageId ) { final SearchTerm msgIdTerm = new MessageIDTerm ( messageId ) ; concat ( msgIdTerm ) ; return this ; }


Input: Defines filter for FROM field . [CODESPLIT] public EmailFilter from ( final String fromAddress ) { final SearchTerm fromTerm = new FromStringTerm ( fromAddress ) ; concat ( fromTerm ) ; return this ; }


Input: Defines filter for TO field . [CODESPLIT] public EmailFilter to ( final String toAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . TO , toAddress ) ; concat ( toTerm ) ; return this ; }


Input: Defines filter for CC field . [CODESPLIT] public EmailFilter cc ( final String ccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . CC , ccAddress ) ; concat ( toTerm ) ; return this ; }


Input: Defines filter for BCC field . [CODESPLIT] public EmailFilter bcc ( final String bccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . BCC , bccAddress ) ; concat ( toTerm ) ; return this ; }


Input: Defines filter for many flags at once . [CODESPLIT] public EmailFilter flags ( final Flags flags , final boolean value ) { final SearchTerm flagTerm = new FlagTerm ( flags , value ) ; concat ( flagTerm ) ; return this ; }


Input: Defines filter for single flag . [CODESPLIT] public EmailFilter flag ( final Flag flag , final boolean value ) { final Flags flags = new Flags ( ) ; flags . add ( flag ) ; return flags ( flags , value ) ; }


Input: Defines filter for received date . [CODESPLIT] public EmailFilter receivedDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new ReceivedDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }


Input: Defines filter for sent date . [CODESPLIT] public EmailFilter sentDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new SentDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }


Input: Defines filter on a message body . All parts of the message that are of MIME type text / * are searched . [CODESPLIT] public EmailFilter text ( final String pattern ) { final SearchTerm term = new BodyTerm ( pattern ) ; concat ( term ) ; return this ; }


Input: Defines filter for { @link Header } . [CODESPLIT] public EmailFilter header ( final String headerName , final String pattern ) { final SearchTerm term = new HeaderTerm ( headerName , pattern ) ; concat ( term ) ; return this ; }


Input: Defines filter for message size . [CODESPLIT] public EmailFilter size ( final Operator comparison , final int size ) { final SearchTerm term = new SizeTerm ( comparison . value , size ) ; concat ( term ) ; return this ; }


Input: Defines AND group of filters . [CODESPLIT] public EmailFilter and ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new AndTerm ( searchTerms ) ) ; return this ; }


Input: Defines OR group of filters . [CODESPLIT] public EmailFilter or ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new OrTerm ( searchTerms ) ) ; return this ; }


Input: Appends single filter as NOT . [CODESPLIT] public EmailFilter not ( final EmailFilter emailFilter ) { final SearchTerm searchTerm = new NotTerm ( emailFilter . searchTerm ) ; concat ( searchTerm ) ; return this ; }


Input: Concatenates last search term with new one . [CODESPLIT] protected void concat ( SearchTerm searchTerm ) { if ( nextIsNot ) { searchTerm = new NotTerm ( searchTerm ) ; nextIsNot = false ; } if ( operatorAnd ) { and ( searchTerm ) ; } else { or ( searchTerm ) ; } }


Input: Sets { @link AndTerm } as searchTerm . [CODESPLIT] protected void and ( final SearchTerm searchTerm ) { if ( this . searchTerm == null ) { this . searchTerm = searchTerm ; return ; } this . searchTerm = new AndTerm ( this . searchTerm , searchTerm ) ; }


Input: Sets { @link OrTerm } searchTerm . [CODESPLIT] protected void or ( final SearchTerm searchTerm ) { if ( this . searchTerm == null ) { this . searchTerm = searchTerm ; return ; } this . searchTerm = new OrTerm ( this . searchTerm , searchTerm ) ; }


Input: Encode an array of binary bytes into a Base32 string . [CODESPLIT] public static String encode ( final byte [ ] bytes ) { StringBuilder base32 = new StringBuilder ( ( bytes . length * 8 + 4 ) / 5 ) ; int currByte , digit , i = 0 ; while ( i < bytes . length ) { // STEP 0; insert new 5 bits, leave 3 bits currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ currByte >> 3 ] ) ; digit = ( currByte & 7 ) << 2 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 3: insert 2 new bits, then 5 bits, leave 1 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 6 ) ] ) ; base32 . append ( CHARS [ ( currByte >> 1 ) & 31 ] ) ; digit = ( currByte & 1 ) << 4 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 1: insert 4 new bits, leave 4 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 4 ) ] ) ; digit = ( currByte & 15 ) << 1 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 4: insert 1 new bit, then 5 bits, leave 2 bits currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 7 ) ] ) ; base32 . append ( CHARS [ ( currByte >> 2 ) & 31 ] ) ; digit = ( currByte & 3 ) << 3 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 2: insert 3 new bits, then 5 bits, leave 0 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 5 ) ] ) ; base32 . append ( CHARS [ currByte & 31 ] ) ; } return base32 . toString ( ) ; }