idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
22,300 | private String getIdFromFilename ( String filename ) { if ( ! StringUtils . hasText ( filename ) || filename . indexOf ( ' ' ) < 0 ) { return null ; } return filename . substring ( 0 , filename . lastIndexOf ( ' ' ) ) ; } | Extract the session id from the filename . | 60 | 9 |
22,301 | private boolean isSessionFilename ( String filename ) { if ( ! StringUtils . hasText ( filename ) ) { return false ; } String [ ] parts = filename . split ( "_" ) ; // Need at least 2 parts for a valid filename return ( parts . length >= 2 ) ; } | Check if the filename matches our session pattern . | 61 | 9 |
22,302 | public void sweepFile ( long now , Path p ) throws Exception { if ( p == null ) { return ; } long expiry = getExpiryFromFilename ( p . getFileName ( ) . toString ( ) ) ; // files with 0 expiry never expire if ( expiry > 0 && ( ( now - expiry ) >= ( 5 * TimeUnit . SECONDS . toMillis ( gracePeriodSec ) ) ) ) { Files . deleteIfExists ( p ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Sweep deleted " + p . getFileName ( ) ) ; } } } | Check to see if the expiry on the file is very old and delete the file if so . Old means that it expired at least 5 gracePeriods ago . | 138 | 34 |
22,303 | private void save ( OutputStream os , String id , SessionData data ) throws IOException { DataOutputStream out = new DataOutputStream ( os ) ; out . writeUTF ( id ) ; out . writeLong ( data . getCreationTime ( ) ) ; out . writeLong ( data . getAccessedTime ( ) ) ; out . writeLong ( data . getLastAccessedTime ( ) ) ; out . writeLong ( data . getExpiryTime ( ) ) ; out . writeLong ( data . getMaxInactiveInterval ( ) ) ; List < String > keys = new ArrayList <> ( data . getKeys ( ) ) ; out . writeInt ( keys . size ( ) ) ; ObjectOutputStream oos = new ObjectOutputStream ( out ) ; for ( String name : keys ) { oos . writeUTF ( name ) ; oos . writeObject ( data . getAttribute ( name ) ) ; } } | Save the session data . | 199 | 5 |
22,304 | private SessionData load ( InputStream is , String expectedId ) throws Exception { try { DataInputStream di = new DataInputStream ( is ) ; String id = di . readUTF ( ) ; // the actual id from inside the file long created = di . readLong ( ) ; long accessed = di . readLong ( ) ; long lastAccessed = di . readLong ( ) ; long expiry = di . readLong ( ) ; long maxIdle = di . readLong ( ) ; SessionData data = newSessionData ( id , created , accessed , lastAccessed , maxIdle ) ; data . setExpiryTime ( expiry ) ; data . setMaxInactiveInterval ( maxIdle ) ; // Attributes restoreAttributes ( di , di . readInt ( ) , data ) ; return data ; } catch ( Exception e ) { throw new UnreadableSessionDataException ( expectedId , e ) ; } } | Load session data from an input stream that contains session data . | 196 | 12 |
22,305 | private void restoreAttributes ( InputStream is , int size , SessionData data ) throws Exception { if ( size > 0 ) { // input stream should not be closed here Map < String , Object > attributes = new HashMap <> ( ) ; ObjectInputStream ois = new CustomObjectInputStream ( is ) ; for ( int i = 0 ; i < size ; i ++ ) { String key = ois . readUTF ( ) ; Object value = ois . readObject ( ) ; attributes . put ( key , value ) ; } data . putAllAttributes ( attributes ) ; } } | Load attributes from an input stream that contains session data . | 123 | 11 |
22,306 | private void parseMultipartParameters ( Map < String , List < FileItem > > fileItemListMap , RequestAdapter requestAdapter ) { String encoding = requestAdapter . getEncoding ( ) ; MultiValueMap < String , String > parameterMap = new LinkedMultiValueMap <> ( ) ; MultiValueMap < String , FileParameter > fileParameterMap = new LinkedMultiValueMap <> ( ) ; for ( Map . Entry < String , List < FileItem > > entry : fileItemListMap . entrySet ( ) ) { String fieldName = entry . getKey ( ) ; List < FileItem > fileItemList = entry . getValue ( ) ; if ( fileItemList != null && ! fileItemList . isEmpty ( ) ) { for ( FileItem fileItem : fileItemList ) { if ( fileItem . isFormField ( ) ) { String value = getString ( fileItem , encoding ) ; parameterMap . add ( fieldName , value ) ; } else { String fileName = fileItem . getName ( ) ; // Skip file uploads that don't have a file name - meaning that // no file was selected. if ( StringUtils . isEmpty ( fileName ) ) { continue ; } boolean valid = FilenameUtils . isValidFileExtension ( fileName , allowedFileExtensions , deniedFileExtensions ) ; if ( ! valid ) { continue ; } MemoryMultipartFileParameter fileParameter = new MemoryMultipartFileParameter ( fileItem ) ; fileParameterMap . add ( fieldName , fileParameter ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Found multipart file [" + fileParameter . getFileName ( ) + "] of size " + fileParameter . getFileSize ( ) + " bytes, stored " + fileParameter . getStorageDescription ( ) ) ; } } } } } if ( ! parameterMap . isEmpty ( ) ) { for ( Map . Entry < String , List < String > > entry : parameterMap . entrySet ( ) ) { String name = entry . getKey ( ) ; List < String > list = entry . getValue ( ) ; String [ ] values = list . toArray ( new String [ 0 ] ) ; requestAdapter . setParameter ( name , values ) ; } } if ( ! fileParameterMap . isEmpty ( ) ) { for ( Map . Entry < String , List < FileParameter > > entry : fileParameterMap . entrySet ( ) ) { String name = entry . getKey ( ) ; List < FileParameter > list = entry . getValue ( ) ; FileParameter [ ] values = list . toArray ( new FileParameter [ 0 ] ) ; requestAdapter . setFileParameter ( name , values ) ; } } } | Parse form fields and file items . | 584 | 8 |
22,307 | public Configuration createConfiguration ( ) throws IOException , TemplateException { Configuration config = newConfiguration ( ) ; Properties props = new Properties ( ) ; // Merge local properties if specified. if ( this . freemarkerSettings != null ) { props . putAll ( this . freemarkerSettings ) ; } // FreeMarker will only accept known keys in its setSettings and // setAllSharedVariables methods. if ( ! props . isEmpty ( ) ) { config . setSettings ( props ) ; } if ( this . freemarkerVariables != null && freemarkerVariables . size ( ) > 0 ) { config . setAllSharedVariables ( new SimpleHash ( this . freemarkerVariables , config . getObjectWrapper ( ) ) ) ; } if ( this . defaultEncoding != null ) { config . setDefaultEncoding ( this . defaultEncoding ) ; } // determine FreeMarker TemplateLoader if ( templateLoaders == null ) { if ( templateLoaderPaths != null && templateLoaderPaths . length > 0 ) { List < TemplateLoader > templateLoaderList = new ArrayList <> ( ) ; for ( String path : templateLoaderPaths ) { templateLoaderList . add ( getTemplateLoaderForPath ( path ) ) ; } setTemplateLoader ( templateLoaderList ) ; } } TemplateLoader templateLoader = getAggregateTemplateLoader ( templateLoaders ) ; if ( templateLoader != null ) { config . setTemplateLoader ( templateLoader ) ; } // determine CustomTrimDirectives if ( trimDirectives != null && trimDirectives . length > 0 ) { TrimDirectiveGroup group = new TrimDirectiveGroup ( trimDirectives ) ; for ( Map . Entry < String , Map < String , TrimDirective > > directives : group . entrySet ( ) ) { config . setSharedVariable ( directives . getKey ( ) , directives . getValue ( ) ) ; } } return config ; } | Prepare the FreeMarker Configuration and return it . | 414 | 11 |
22,308 | protected TemplateLoader getAggregateTemplateLoader ( TemplateLoader [ ] templateLoaders ) { int loaderCount = ( templateLoaders != null ? templateLoaders . length : 0 ) ; switch ( loaderCount ) { case 0 : if ( log . isDebugEnabled ( ) ) { log . debug ( "No FreeMarker TemplateLoaders specified; Can be used only inner template source" ) ; } return null ; case 1 : if ( log . isDebugEnabled ( ) ) { log . debug ( "One FreeMarker TemplateLoader registered: " + templateLoaders [ 0 ] ) ; } return templateLoaders [ 0 ] ; default : TemplateLoader loader = new MultiTemplateLoader ( templateLoaders ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Multiple FreeMarker TemplateLoader registered: " + loader ) ; } return loader ; } } | Return a TemplateLoader based on the given TemplateLoader list . If more than one TemplateLoader has been registered a FreeMarker MultiTemplateLoader needs to be created . | 183 | 33 |
22,309 | protected TemplateLoader getTemplateLoaderForPath ( String templateLoaderPath ) throws IOException { if ( templateLoaderPath . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { String basePackagePath = templateLoaderPath . substring ( ResourceUtils . CLASSPATH_URL_PREFIX . length ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to class path [" + basePackagePath + "]" ) ; } return new ClassTemplateLoader ( environment . getClassLoader ( ) , basePackagePath ) ; } else if ( templateLoaderPath . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { File file = new File ( templateLoaderPath . substring ( ResourceUtils . FILE_URL_PREFIX . length ( ) ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to file path [" + file . getAbsolutePath ( ) + "]" ) ; } return new FileTemplateLoader ( file ) ; } else { File file = new File ( environment . getBasePath ( ) , templateLoaderPath ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to file path [" + file . getAbsolutePath ( ) + "]" ) ; } return new FileTemplateLoader ( file ) ; } } | Determine a FreeMarker TemplateLoader for the given path . | 329 | 14 |
22,310 | public Options addOption ( Option opt ) { String key = opt . getKey ( ) ; // add it to the long option list if ( opt . hasLongName ( ) ) { longOpts . put ( opt . getLongName ( ) , opt ) ; } // if the option is required add it to the required list if ( opt . isRequired ( ) ) { if ( requiredOpts . contains ( key ) ) { requiredOpts . remove ( requiredOpts . indexOf ( key ) ) ; } requiredOpts . add ( key ) ; } shortOpts . put ( key , opt ) ; return this ; } | Adds an option instance . | 133 | 5 |
22,311 | public ItemRule newHeaderItemRule ( String headerName ) { ItemRule itemRule = new ItemRule ( ) ; itemRule . setName ( headerName ) ; addHeaderItemRule ( itemRule ) ; return itemRule ; } | Adds a new header rule with the specified name and returns it . | 48 | 13 |
22,312 | public void addHeaderItemRule ( ItemRule headerItemRule ) { if ( headerItemRuleMap == null ) { headerItemRuleMap = new ItemRuleMap ( ) ; } headerItemRuleMap . putItemRule ( headerItemRule ) ; } | Adds the header item rule . | 52 | 6 |
22,313 | public static HeaderActionRule newInstance ( String id , Boolean hidden ) { HeaderActionRule headerActionRule = new HeaderActionRule ( ) ; headerActionRule . setActionId ( id ) ; headerActionRule . setHidden ( hidden ) ; return headerActionRule ; } | Returns a new derived instance of HeaderActionRule . | 56 | 10 |
22,314 | protected Object getBean ( Token token ) { Object value ; if ( token . getAlternativeValue ( ) != null ) { if ( token . getDirectiveType ( ) == TokenDirectiveType . FIELD ) { Field field = ( Field ) token . getAlternativeValue ( ) ; if ( Modifier . isStatic ( field . getModifiers ( ) ) ) { value = ReflectionUtils . getField ( field , null ) ; } else { Class < ? > cls = field . getDeclaringClass ( ) ; Object target = activity . getBean ( cls ) ; value = ReflectionUtils . getField ( field , target ) ; } } else if ( token . getDirectiveType ( ) == TokenDirectiveType . METHOD ) { Method method = ( Method ) token . getAlternativeValue ( ) ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { value = ReflectionUtils . invokeMethod ( method , null ) ; } else { Class < ? > cls = method . getDeclaringClass ( ) ; Object target = activity . getBean ( cls ) ; value = ReflectionUtils . invokeMethod ( method , target ) ; } } else { Class < ? > cls = ( Class < ? > ) token . getAlternativeValue ( ) ; try { value = activity . getBean ( cls ) ; } catch ( RequiredTypeBeanNotFoundException | NoUniqueBeanException e ) { if ( token . getGetterName ( ) != null ) { try { value = BeanUtils . getProperty ( cls , token . getGetterName ( ) ) ; if ( value == null ) { value = token . getDefaultValue ( ) ; } return value ; } catch ( InvocationTargetException e2 ) { // ignore } } throw e ; } if ( value != null && token . getGetterName ( ) != null ) { value = getBeanProperty ( value , token . getGetterName ( ) ) ; } } } else { value = activity . getBean ( token . getName ( ) ) ; if ( value != null && token . getGetterName ( ) != null ) { value = getBeanProperty ( value , token . getGetterName ( ) ) ; } } if ( value == null ) { value = token . getDefaultValue ( ) ; } return value ; } | Returns the bean instance that matches the given token . | 512 | 10 |
22,315 | protected Object getBeanProperty ( final Object object , String propertyName ) { Object value ; try { value = BeanUtils . getProperty ( object , propertyName ) ; } catch ( InvocationTargetException e ) { // ignore value = null ; } return value ; } | Invoke bean s property . | 57 | 6 |
22,316 | protected Object getProperty ( Token token ) throws IOException { if ( token . getDirectiveType ( ) == TokenDirectiveType . CLASSPATH ) { Properties props = PropertiesLoaderUtils . loadProperties ( token . getValue ( ) , activity . getEnvironment ( ) . getClassLoader ( ) ) ; Object value = ( token . getGetterName ( ) != null ? props . get ( token . getGetterName ( ) ) : props ) ; return ( value != null ? value : token . getDefaultValue ( ) ) ; } else { Object value = activity . getActivityContext ( ) . getEnvironment ( ) . getProperty ( token . getName ( ) , activity ) ; if ( value != null && token . getGetterName ( ) != null ) { value = getBeanProperty ( value , token . getGetterName ( ) ) ; } return ( value != null ? value : token . getDefaultValue ( ) ) ; } } | Returns an Environment variable that matches the given token . | 205 | 10 |
22,317 | protected String getTemplate ( Token token ) { TemplateRenderer templateRenderer = activity . getActivityContext ( ) . getTemplateRenderer ( ) ; StringWriter writer = new StringWriter ( ) ; templateRenderer . render ( token . getName ( ) , activity , writer ) ; String result = writer . toString ( ) ; return ( result != null ? result : token . getDefaultValue ( ) ) ; } | Executes template returns the generated output . | 91 | 8 |
22,318 | public String stringify ( ) { if ( type == TokenType . TEXT ) { return defaultValue ; } StringBuilder sb = new StringBuilder ( ) ; if ( type == TokenType . BEAN ) { sb . append ( BEAN_SYMBOL ) ; sb . append ( START_BRACKET ) ; if ( name != null ) { sb . append ( name ) ; } if ( value != null ) { sb . append ( VALUE_SEPARATOR ) ; sb . append ( value ) ; } if ( getterName != null ) { sb . append ( GETTER_SEPARATOR ) ; sb . append ( getterName ) ; } } else if ( type == TokenType . TEMPLATE ) { sb . append ( TEMPLATE_SYMBOL ) ; sb . append ( START_BRACKET ) ; if ( name != null ) { sb . append ( name ) ; } } else if ( type == TokenType . PARAMETER ) { sb . append ( PARAMETER_SYMBOL ) ; sb . append ( START_BRACKET ) ; if ( name != null ) { sb . append ( name ) ; } } else if ( type == TokenType . ATTRIBUTE ) { sb . append ( ATTRIBUTE_SYMBOL ) ; sb . append ( START_BRACKET ) ; if ( name != null ) { sb . append ( name ) ; } if ( getterName != null ) { sb . append ( GETTER_SEPARATOR ) ; sb . append ( getterName ) ; } } else if ( type == TokenType . PROPERTY ) { sb . append ( PROPERTY_SYMBOL ) ; sb . append ( START_BRACKET ) ; if ( name != null ) { sb . append ( name ) ; } if ( value != null ) { sb . append ( VALUE_SEPARATOR ) ; sb . append ( value ) ; } if ( getterName != null ) { sb . append ( GETTER_SEPARATOR ) ; sb . append ( getterName ) ; } } else { throw new InvalidTokenException ( "Unknown token type: " + type , this ) ; } if ( defaultValue != null ) { sb . append ( VALUE_SEPARATOR ) ; sb . append ( defaultValue ) ; } sb . append ( END_BRACKET ) ; return sb . toString ( ) ; } | Convert a Token object into a string . | 547 | 9 |
22,319 | public static boolean isTokenSymbol ( char c ) { return ( c == BEAN_SYMBOL || c == TEMPLATE_SYMBOL || c == PARAMETER_SYMBOL || c == ATTRIBUTE_SYMBOL || c == PROPERTY_SYMBOL ) ; } | Returns whether a specified character is the token symbol . | 68 | 10 |
22,320 | public static TokenType resolveTypeAsSymbol ( char symbol ) { TokenType type ; if ( symbol == Token . BEAN_SYMBOL ) { type = TokenType . BEAN ; } else if ( symbol == Token . TEMPLATE_SYMBOL ) { type = TokenType . TEMPLATE ; } else if ( symbol == Token . PARAMETER_SYMBOL ) { type = TokenType . PARAMETER ; } else if ( symbol == Token . ATTRIBUTE_SYMBOL ) { type = TokenType . ATTRIBUTE ; } else if ( symbol == Token . PROPERTY_SYMBOL ) { type = TokenType . PROPERTY ; } else { throw new IllegalArgumentException ( "Unknown token symbol: " + symbol ) ; } return type ; } | Returns the token type for the specified character . | 175 | 9 |
22,321 | public void setTransformType ( TransformType transformType ) { this . transformType = transformType ; if ( contentType == null && transformType != null ) { if ( transformType == TransformType . TEXT ) { contentType = ContentType . TEXT_PLAIN . toString ( ) ; } else if ( transformType == TransformType . JSON ) { contentType = ContentType . TEXT_JSON . toString ( ) ; } else if ( transformType == TransformType . XML ) { contentType = ContentType . TEXT_XML . toString ( ) ; } } } | Sets the transform type . | 120 | 6 |
22,322 | public void setTemplateRule ( TemplateRule templateRule ) { this . templateRule = templateRule ; if ( templateRule != null ) { if ( this . transformType == null ) { setTransformType ( TransformType . TEXT ) ; } if ( templateRule . getEncoding ( ) != null && this . encoding == null ) { this . encoding = templateRule . getEncoding ( ) ; } } } | Sets the template rule . | 85 | 6 |
22,323 | public void setResultValue ( String actionId , Object resultValue ) { if ( actionId == null || ! actionId . contains ( ActivityContext . ID_SEPARATOR ) ) { this . actionId = actionId ; this . resultValue = resultValue ; } else { String [ ] ids = StringUtils . tokenize ( actionId , ActivityContext . ID_SEPARATOR , true ) ; if ( ids . length == 1 ) { this . actionId = null ; this . resultValue = resultValue ; } else if ( ids . length == 2 ) { ResultValueMap resultValueMap = new ResultValueMap ( ) ; resultValueMap . put ( ids [ 1 ] , resultValue ) ; this . actionId = ids [ 0 ] ; this . resultValue = resultValueMap ; } else { ResultValueMap resultValueMap = new ResultValueMap ( ) ; for ( int i = 1 ; i < ids . length - 1 ; i ++ ) { ResultValueMap resultValueMap2 = new ResultValueMap ( ) ; resultValueMap . put ( ids [ i ] , resultValueMap2 ) ; resultValueMap = resultValueMap2 ; } resultValueMap . put ( ids [ ids . length - 1 ] , resultValue ) ; this . actionId = actionId ; this . resultValue = resultValueMap ; } } } | Sets the result value of the action . | 294 | 9 |
22,324 | public static URL getResource ( String resource , ClassLoader classLoader ) throws IOException { URL url = null ; if ( classLoader != null ) { url = classLoader . getResource ( resource ) ; } if ( url == null ) { url = ClassLoader . getSystemResource ( resource ) ; } if ( url == null ) { throw new IOException ( "Could not find resource '" + resource + "'" ) ; } return url ; } | Returns the URL of the resource on the classpath . | 94 | 11 |
22,325 | public static Reader getReader ( final File file , String encoding ) throws IOException { InputStream stream ; try { stream = AccessController . doPrivileged ( new PrivilegedExceptionAction < InputStream > ( ) { @ Override public InputStream run ( ) throws IOException { return new FileInputStream ( file ) ; } } ) ; } catch ( PrivilegedActionException e ) { throw ( IOException ) e . getException ( ) ; } Reader reader ; if ( encoding != null ) { reader = new InputStreamReader ( stream , encoding ) ; } else { reader = new InputStreamReader ( stream ) ; } return reader ; } | Returns a Reader for reading the specified file . | 133 | 9 |
22,326 | public static Reader getReader ( final URL url , String encoding ) throws IOException { InputStream stream ; try { stream = AccessController . doPrivileged ( new PrivilegedExceptionAction < InputStream > ( ) { @ Override public InputStream run ( ) throws IOException { InputStream is = null ; if ( url != null ) { URLConnection connection = url . openConnection ( ) ; if ( connection != null ) { // Disable caches to get fresh data for reloading. connection . setUseCaches ( false ) ; is = connection . getInputStream ( ) ; } } return is ; } } ) ; } catch ( PrivilegedActionException e ) { throw ( IOException ) e . getException ( ) ; } Reader reader ; if ( encoding != null ) { reader = new InputStreamReader ( stream , encoding ) ; } else { reader = new InputStreamReader ( stream ) ; } return reader ; } | Returns a Reader for reading the specified url . | 191 | 9 |
22,327 | public static String read ( File file , String encoding ) throws IOException { Reader reader = getReader ( file , encoding ) ; String source ; try { source = read ( reader ) ; } finally { reader . close ( ) ; } return source ; } | Returns a string from the specified file . | 52 | 8 |
22,328 | public static String read ( URL url , String encoding ) throws IOException { Reader reader = getReader ( url , encoding ) ; String source ; try { source = read ( reader ) ; } finally { reader . close ( ) ; } return source ; } | Returns a string from the specified url . | 52 | 8 |
22,329 | public static String read ( Reader reader ) throws IOException { final char [ ] buffer = new char [ 1024 ] ; StringBuilder sb = new StringBuilder ( ) ; int len ; while ( ( len = reader . read ( buffer ) ) != - 1 ) { sb . append ( buffer , 0 , len ) ; } return sb . toString ( ) ; } | Returns a string from the specified Reader object . | 78 | 9 |
22,330 | private ViewDispatcher getViewDispatcher ( Activity activity ) throws ViewDispatcherException { if ( dispatchRule . getViewDispatcher ( ) != null ) { return dispatchRule . getViewDispatcher ( ) ; } try { String dispatcherName ; if ( dispatchRule . getDispatcherName ( ) != null ) { dispatcherName = dispatchRule . getDispatcherName ( ) ; } else { dispatcherName = activity . getSetting ( ViewDispatcher . VIEW_DISPATCHER_SETTING_NAME ) ; if ( dispatcherName == null ) { throw new IllegalArgumentException ( "The settings name '" + ViewDispatcher . VIEW_DISPATCHER_SETTING_NAME + "' has not been specified in the default response rule" ) ; } } ViewDispatcher viewDispatcher = cache . get ( dispatcherName ) ; if ( viewDispatcher == null ) { if ( dispatcherName . startsWith ( BeanRule . CLASS_DIRECTIVE_PREFIX ) ) { String dispatcherClassName = dispatcherName . substring ( BeanRule . CLASS_DIRECTIVE_PREFIX . length ( ) ) ; Class < ? > dispatcherClass = activity . getEnvironment ( ) . getClassLoader ( ) . loadClass ( dispatcherClassName ) ; viewDispatcher = ( ViewDispatcher ) activity . getBean ( dispatcherClass ) ; } else { viewDispatcher = activity . getBean ( dispatcherName ) ; } if ( viewDispatcher == null ) { throw new IllegalArgumentException ( "No bean named '" + dispatcherName + "' is defined" ) ; } if ( viewDispatcher . isSingleton ( ) ) { ViewDispatcher existing = cache . putIfAbsent ( dispatcherName , viewDispatcher ) ; if ( existing != null ) { viewDispatcher = existing ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Caching " + viewDispatcher ) ; } } } } return viewDispatcher ; } catch ( Exception e ) { throw new ViewDispatcherException ( "Unable to determine ViewDispatcher" , e ) ; } } | Determine the view dispatcher . | 470 | 7 |
22,331 | public static void fetchAttributes ( RequestAdapter requestAdapter , ProcessResult processResult ) { if ( processResult != null ) { for ( ContentResult contentResult : processResult ) { for ( ActionResult actionResult : contentResult ) { Object actionResultValue = actionResult . getResultValue ( ) ; if ( actionResultValue instanceof ProcessResult ) { fetchAttributes ( requestAdapter , ( ProcessResult ) actionResultValue ) ; } else { String actionId = actionResult . getActionId ( ) ; if ( actionId != null ) { requestAdapter . setAttribute ( actionId , actionResultValue ) ; } } } } } } | Stores an attribute in request . | 131 | 7 |
22,332 | public void excludePackage ( String ... packageNames ) { if ( packageNames == null ) { excludePackageNames = null ; } else { for ( String packageName : packageNames ) { if ( excludePackageNames == null ) { excludePackageNames = new HashSet <> ( ) ; } excludePackageNames . add ( packageName + PACKAGE_SEPARATOR_CHAR ) ; } } } | Adds packages that this ClassLoader should not handle . Any class whose fully - qualified name starts with the name registered here will be handled by the parent ClassLoader in the usual fashion . | 82 | 36 |
22,333 | public void excludeClass ( String ... classNames ) { if ( classNames == null ) { excludeClassNames = null ; } else { for ( String className : classNames ) { if ( ! isExcludePackage ( className ) ) { if ( excludeClassNames == null ) { excludeClassNames = new HashSet <> ( ) ; } excludeClassNames . add ( className ) ; } } } } | Adds classes that this ClassLoader should not handle . Any class whose fully - qualified name starts with the name registered here will be handled by the parent ClassLoader in the usual fashion . | 87 | 36 |
22,334 | public void open ( ) { if ( sqlSession == null ) { if ( executorType == null ) { executorType = ExecutorType . SIMPLE ; } sqlSession = sqlSessionFactory . openSession ( executorType , autoCommit ) ; if ( log . isDebugEnabled ( ) ) { ToStringBuilder tsb = new ToStringBuilder ( String . format ( "%s %s@%x" , ( arbitrarilyClosed ? "Reopened" : "Opened" ) , sqlSession . getClass ( ) . getSimpleName ( ) , sqlSession . hashCode ( ) ) ) ; tsb . append ( "executorType" , executorType ) ; tsb . append ( "autoCommit" , autoCommit ) ; log . debug ( tsb . toString ( ) ) ; } arbitrarilyClosed = false ; } } | Opens a new SqlSession and store its instance inside . Therefore whenever there is a request for a SqlSessionTxAdvice bean a new bean instance of the object must be created . | 183 | 39 |
22,335 | public void commit ( boolean force ) { if ( checkSession ( ) ) { return ; } if ( log . isDebugEnabled ( ) ) { ToStringBuilder tsb = new ToStringBuilder ( String . format ( "Committing transactional %s@%x" , sqlSession . getClass ( ) . getSimpleName ( ) , sqlSession . hashCode ( ) ) ) ; tsb . append ( "force" , force ) ; log . debug ( tsb . toString ( ) ) ; } sqlSession . commit ( force ) ; } | Flushes batch statements and commits database connection . | 116 | 9 |
22,336 | public void close ( boolean arbitrarily ) { if ( checkSession ( ) ) { return ; } arbitrarilyClosed = arbitrarily ; sqlSession . close ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Closed %s@%x" , sqlSession . getClass ( ) . getSimpleName ( ) , sqlSession . hashCode ( ) ) ) ; } sqlSession = null ; } | Closes the session arbitrarily . If the transaction advice does not finally close the session the session will automatically reopen whenever necessary . | 92 | 24 |
22,337 | public void ifExceptionThrow ( ) throws Exception { if ( nested == null || nested . isEmpty ( ) ) { return ; } if ( nested . size ( ) == 1 ) { Throwable th = nested . get ( 0 ) ; if ( th instanceof Error ) { throw ( Error ) th ; } if ( th instanceof Exception ) { throw ( Exception ) th ; } } throw this ; } | Throw a MultiException . If this multi exception is empty then no action is taken . If it contains a single exception that is thrown otherwise the this multi exception is thrown . | 84 | 34 |
22,338 | public void ifExceptionThrowRuntime ( ) throws Error { if ( nested == null || nested . isEmpty ( ) ) { return ; } if ( nested . size ( ) == 1 ) { Throwable th = nested . get ( 0 ) ; if ( th instanceof Error ) { throw ( Error ) th ; } else if ( th instanceof RuntimeException ) { throw ( RuntimeException ) th ; } else { throw new RuntimeException ( th ) ; } } throw new RuntimeException ( this ) ; } | Throw a Runtime exception . If this multi exception is empty then no action is taken . If it contains a single error or runtime exception that is thrown otherwise the this multi exception is thrown wrapped in a runtime exception . | 104 | 42 |
22,339 | public void printHelp ( Command command ) { if ( command . getDescriptor ( ) . getUsage ( ) != null ) { printUsage ( command . getDescriptor ( ) . getUsage ( ) ) ; } else { printUsage ( command ) ; } int leftWidth = printOptions ( command . getOptions ( ) ) ; printArguments ( command . getArgumentsList ( ) , leftWidth ) ; } | Print the help with the given Command object . | 89 | 9 |
22,340 | public void printUsage ( Command command ) { String commandName = command . getDescriptor ( ) . getName ( ) ; StringBuilder sb = new StringBuilder ( getSyntaxPrefix ( ) ) . append ( commandName ) . append ( " " ) ; // create a list for processed option groups Collection < OptionGroup > processedGroups = new ArrayList <> ( ) ; Collection < Option > optList = command . getOptions ( ) . getAllOptions ( ) ; if ( optList . size ( ) > 1 && getOptionComparator ( ) != null ) { List < Option > optList2 = new ArrayList <> ( optList ) ; optList2 . sort ( getOptionComparator ( ) ) ; optList = optList2 ; } for ( Iterator < Option > it = optList . iterator ( ) ; it . hasNext ( ) ; ) { // get the next Option Option option = it . next ( ) ; // check if the option is part of an OptionGroup OptionGroup group = command . getOptions ( ) . getOptionGroup ( option ) ; if ( group != null ) { // if the group has not already been processed if ( ! processedGroups . contains ( group ) ) { // add the group to the processed list processedGroups . add ( group ) ; // add the usage clause appendOptionGroup ( sb , group ) ; } // otherwise the option was displayed in the group // previously so ignore it. } // if the Option is not part of an OptionGroup else { appendOption ( sb , option , option . isRequired ( ) ) ; } if ( it . hasNext ( ) ) { sb . append ( " " ) ; } } for ( Arguments arguments : command . getArgumentsList ( ) ) { sb . append ( " " ) ; appendArguments ( sb , arguments ) ; } printWrapped ( getSyntaxPrefix ( ) . length ( ) + commandName . length ( ) + 1 , sb . toString ( ) ) ; } | Prints the usage statement for the specified command . | 431 | 10 |
22,341 | private void appendOptionGroup ( StringBuilder sb , OptionGroup group ) { if ( ! group . isRequired ( ) ) { sb . append ( OPTIONAL_BRACKET_OPEN ) ; } List < Option > optList = new ArrayList <> ( group . getOptions ( ) ) ; if ( optList . size ( ) > 1 && getOptionComparator ( ) != null ) { optList . sort ( getOptionComparator ( ) ) ; } // for each option in the OptionGroup for ( Iterator < Option > it = optList . iterator ( ) ; it . hasNext ( ) ; ) { // whether the option is required or not is handled at group level appendOption ( sb , it . next ( ) , true ) ; if ( it . hasNext ( ) ) { sb . append ( " | " ) ; } } if ( ! group . isRequired ( ) ) { sb . append ( OPTIONAL_BRACKET_CLOSE ) ; } } | Appends the usage clause for an OptionGroup to a StringBuilder . The clause is wrapped in square brackets if the group is required . The display of the options is handled by appendOption . | 213 | 38 |
22,342 | public ItemRule newArgumentItemRule ( String argumentName ) { ItemRule itemRule = new ItemRule ( ) ; itemRule . setName ( argumentName ) ; addArgumentItemRule ( itemRule ) ; return itemRule ; } | Adds a new argument rule with the specified name and returns it . | 50 | 13 |
22,343 | public void addArgumentItemRule ( ItemRule argumentItemRule ) { if ( argumentItemRuleMap == null ) { argumentItemRuleMap = new ItemRuleMap ( ) ; } argumentItemRuleMap . putItemRule ( argumentItemRule ) ; } | Adds the argument item rule . | 53 | 6 |
22,344 | public static BeanMethodActionRule newInstance ( String id , String beanId , String methodName , Boolean hidden ) throws IllegalRuleException { if ( methodName == null ) { throw new IllegalRuleException ( "The 'action' element requires an 'method' attribute" ) ; } BeanMethodActionRule beanMethodActionRule = new BeanMethodActionRule ( ) ; beanMethodActionRule . setActionId ( id ) ; beanMethodActionRule . setBeanId ( beanId ) ; beanMethodActionRule . setMethodName ( methodName ) ; beanMethodActionRule . setHidden ( hidden ) ; return beanMethodActionRule ; } | Returns a new instance of BeanActionRule . | 132 | 9 |
22,345 | public void setAll ( Map < String , String > params ) { for ( Map . Entry < String , String > entry : params . entrySet ( ) ) { setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } } | Set the given parameters under . | 54 | 6 |
22,346 | public Object getParameterWithoutCache ( String name ) { if ( activity . getRequestAdapter ( ) != null ) { String [ ] values = activity . getRequestAdapter ( ) . getParameterValues ( name ) ; if ( values != null ) { if ( values . length == 1 ) { return values [ 0 ] ; } else { return values ; } } } return null ; } | Returns the value of the request parameter from the request adapter without storing it in the cache . If the parameter does not exist returns null . | 79 | 27 |
22,347 | public Object getAttributeWithoutCache ( String name ) { if ( activity . getRequestAdapter ( ) != null ) { return activity . getRequestAdapter ( ) . getAttribute ( name ) ; } else { return null ; } } | Returns the value of the named attribute from the request adapter without storing it in the cache . If no attribute of the given name exists returns null . | 47 | 29 |
22,348 | public Object getActionResultWithoutCache ( String name ) { if ( activity . getProcessResult ( ) != null ) { return activity . getProcessResult ( ) . getResultValue ( name ) ; } else { return null ; } } | Returns the value of the named action s process result without storing it in the cache . If no process result of the given name exists returns null . | 49 | 29 |
22,349 | public Object getSessionAttributeWithoutCache ( String name ) { if ( activity . getSessionAdapter ( ) != null ) { return activity . getSessionAdapter ( ) . getAttribute ( name ) ; } else { return null ; } } | Returns the value of the named attribute from the session adapter without storing it in the cache . If no attribute of the given name exists returns null . | 48 | 29 |
22,350 | @ Override public Session get ( String id ) throws Exception { Session session ; Exception ex = null ; while ( true ) { session = doGet ( id ) ; if ( sessionDataStore == null ) { break ; // can't load any session data so just return null or the session object } if ( session == null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Session " + id + " not found locally, attempting to load" ) ; } // didn't get a session, try and create one and put in a placeholder for it PlaceHolderSession phs = new PlaceHolderSession ( new SessionData ( id , 0 , 0 , 0 , 0 ) ) ; Lock phsLock = phs . lock ( ) ; Session s = doPutIfAbsent ( id , phs ) ; if ( s == null ) { // My placeholder won, go ahead and load the full session data try { session = loadSession ( id ) ; if ( session == null ) { // session does not exist, remove the placeholder doDelete ( id ) ; phsLock . close ( ) ; break ; } try ( Lock ignored = session . lock ( ) ) { // swap it in instead of the placeholder boolean success = doReplace ( id , phs , session ) ; if ( ! success ) { // something has gone wrong, it should have been our placeholder doDelete ( id ) ; session = null ; log . warn ( "Replacement of placeholder for session " + id + " failed" ) ; phsLock . close ( ) ; break ; } else { // successfully swapped in the session session . setResident ( true ) ; session . updateInactivityTimer ( ) ; phsLock . close ( ) ; break ; } } } catch ( Exception e ) { ex = e ; // remember a problem happened loading the session doDelete ( id ) ; // remove the placeholder phsLock . close ( ) ; session = null ; break ; } } else { // my placeholder didn't win, check the session returned phsLock . close ( ) ; try ( Lock ignored = s . lock ( ) ) { // is it a placeholder? or is a non-resident session? In both cases, chuck it away and start again if ( ! s . isResident ( ) || s instanceof PlaceHolderSession ) { continue ; } session = s ; break ; } } } else { // check the session returned try ( Lock ignored = session . lock ( ) ) { // is it a placeholder? or is it passivated? In both cases, chuck it away and start again if ( ! session . isResident ( ) || session instanceof PlaceHolderSession ) { continue ; } // got the session break ; } } } if ( ex != null ) { throw ex ; } return session ; } | Get a session object . If the session object is not in this session store try getting the data for it from a SessionDataStore associated with the session manager . | 592 | 32 |
22,351 | private Session loadSession ( String id ) throws Exception { if ( sessionDataStore == null ) { return null ; // can't load it } try { SessionData data = sessionDataStore . load ( id ) ; if ( data == null ) { // session doesn't exist return null ; } return newSession ( data ) ; } catch ( UnreadableSessionDataException e ) { // can't load the session, delete it if ( isRemoveUnloadableSessions ( ) ) { sessionDataStore . delete ( id ) ; } throw e ; } } | Load the info for the session from the session data store . | 115 | 12 |
22,352 | @ Override public void put ( String id , Session session ) throws Exception { if ( id == null || session == null ) { throw new IllegalArgumentException ( "Put key=" + id + " session=" + ( session == null ? "null" : session . getId ( ) ) ) ; } try ( Lock ignored = session . lock ( ) ) { if ( ! session . isValid ( ) ) { return ; } if ( sessionDataStore == null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "No SessionDataStore, putting into SessionCache only id=" + id ) ; } session . setResident ( true ) ; if ( doPutIfAbsent ( id , session ) == null ) { // ensure it is in our map session . updateInactivityTimer ( ) ; } return ; } // don't do anything with the session until the last request for it has finished if ( ( session . getRequests ( ) <= 0 ) ) { // save the session if ( ! sessionDataStore . isPassivating ( ) ) { // if our backing datastore isn't the passivating kind, just save the session sessionDataStore . store ( id , session . getSessionData ( ) ) ; // if we evict on session exit, boot it from the cache if ( getEvictionPolicy ( ) == EVICT_ON_SESSION_EXIT ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Eviction on request exit id=" + id ) ; } doDelete ( session . getId ( ) ) ; session . setResident ( false ) ; } else { session . setResident ( true ) ; if ( doPutIfAbsent ( id , session ) == null ) { // ensure it is in our map session . updateInactivityTimer ( ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Non passivating SessionDataStore, session in SessionCache only id=" + id ) ; } } } else { // backing store supports passivation, call the listeners sessionHandler . willPassivate ( session ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Session passivating id=" + id ) ; } sessionDataStore . store ( id , session . getSessionData ( ) ) ; if ( getEvictionPolicy ( ) == EVICT_ON_SESSION_EXIT ) { // throw out the passivated session object from the map doDelete ( id ) ; session . setResident ( false ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Evicted on request exit id=" + id ) ; } } else { // reactivate the session sessionHandler . didActivate ( session ) ; session . setResident ( true ) ; if ( doPutIfAbsent ( id , session ) == null ) // ensure it is in our map session . updateInactivityTimer ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Session reactivated id=" + id ) ; } } } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Req count=" + session . getRequests ( ) + " for id=" + id ) ; } session . setResident ( true ) ; if ( doPutIfAbsent ( id , session ) == null ) { // ensure it is the map, but don't save it to the backing store until the last request exists session . updateInactivityTimer ( ) ; } } } } | Put the Session object back into the session store . | 753 | 10 |
22,353 | @ Override public boolean exists ( String id ) throws Exception { // try the object store first Session s = doGet ( id ) ; if ( s != null ) { try ( Lock ignored = s . lock ( ) ) { // wait for the lock and check the validity of the session return s . isValid ( ) ; } } // not there, so find out if session data exists for it return ( sessionDataStore != null && sessionDataStore . exists ( id ) ) ; } | Check to see if a session corresponding to the id exists . | 101 | 12 |
22,354 | @ Override public Session delete ( String id ) throws Exception { // get the session, if its not in memory, this will load it Session session = get ( id ) ; // Always delete it from the backing data store if ( sessionDataStore != null ) { boolean deleted = sessionDataStore . delete ( id ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Session " + id + " deleted in db: " + deleted ) ; } } // delete it from the session object store if ( session != null ) { session . stopInactivityTimer ( ) ; session . setResident ( false ) ; } return doDelete ( id ) ; } | Remove a session object from this store and from any backing store . | 141 | 13 |
22,355 | public void checkInactiveSession ( Session session ) { if ( session == null ) { return ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Checking for idle " + session . getId ( ) ) ; } try ( Lock ignored = session . lock ( ) ) { if ( getEvictionPolicy ( ) > 0 && session . isIdleLongerThan ( getEvictionPolicy ( ) ) && session . isValid ( ) && session . isResident ( ) && session . getRequests ( ) <= 0 ) { // Be careful with saveOnInactiveEviction - you may be able to re-animate a session that was // being managed on another node and has expired. try { if ( log . isDebugEnabled ( ) ) { log . debug ( "Evicting idle session " + session . getId ( ) ) ; } // save before evicting if ( isSaveOnInactiveEviction ( ) && sessionDataStore != null ) { if ( sessionDataStore . isPassivating ( ) ) { sessionHandler . willPassivate ( session ) ; } sessionDataStore . store ( session . getId ( ) , session . getSessionData ( ) ) ; } doDelete ( session . getId ( ) ) ; // detach from this cache session . setResident ( false ) ; } catch ( Exception e ) { log . warn ( "Passivation of idle session" + session . getId ( ) + " failed" , e ) ; session . updateInactivityTimer ( ) ; } } } } | Check a session for being inactive and thus being able to be evicted if eviction is enabled . | 329 | 19 |
22,356 | public PebbleEngine createPebbleEngine ( ) { PebbleEngine . Builder builder = new PebbleEngine . Builder ( ) ; builder . strictVariables ( strictVariables ) ; if ( defaultLocale != null ) { builder . defaultLocale ( defaultLocale ) ; } if ( templateLoaders == null ) { if ( templateLoaderPaths != null && templateLoaderPaths . length > 0 ) { List < Loader < ? > > templateLoaderList = new ArrayList <> ( ) ; for ( String path : templateLoaderPaths ) { templateLoaderList . add ( getTemplateLoaderForPath ( path ) ) ; } setTemplateLoader ( templateLoaderList ) ; } } Loader < ? > templateLoader = getAggregateTemplateLoader ( templateLoaders ) ; builder . loader ( templateLoader ) ; return builder . build ( ) ; } | Creates a PebbleEngine instance . | 179 | 7 |
22,357 | protected Loader < ? > getAggregateTemplateLoader ( Loader < ? > [ ] templateLoaders ) { int loaderCount = ( templateLoaders == null ) ? 0 : templateLoaders . length ; switch ( loaderCount ) { case 0 : // Register default template loaders. Loader < ? > stringLoader = new StringLoader ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Pebble Engine Template Loader not specified. Default Template Loader registered: " + stringLoader ) ; } return stringLoader ; case 1 : if ( log . isDebugEnabled ( ) ) { log . debug ( "One Pebble Engine Template Loader registered: " + templateLoaders [ 0 ] ) ; } return templateLoaders [ 0 ] ; default : List < Loader < ? > > defaultLoadingStrategies = new ArrayList <> ( ) ; Collections . addAll ( defaultLoadingStrategies , templateLoaders ) ; Loader < ? > delegatingLoader = new DelegatingLoader ( defaultLoadingStrategies ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Multiple Pebble Engine Template Loader registered: " + delegatingLoader ) ; } return delegatingLoader ; } } | Return a Template Loader based on the given Template Loader list . If more than one Template Loader has been registered a DelegatingLoader needs to be created . | 264 | 34 |
22,358 | protected Loader < ? > getTemplateLoaderForPath ( String templateLoaderPath ) { if ( templateLoaderPath . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { String basePackagePath = templateLoaderPath . substring ( ResourceUtils . CLASSPATH_URL_PREFIX . length ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to class path [" + basePackagePath + "]" ) ; } ClasspathLoader loader = new ClasspathLoader ( environment . getClassLoader ( ) ) ; loader . setPrefix ( basePackagePath ) ; return loader ; } else if ( templateLoaderPath . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { File file = new File ( templateLoaderPath . substring ( ResourceUtils . FILE_URL_PREFIX . length ( ) ) ) ; String prefix = file . getAbsolutePath ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to file path [" + prefix + "]" ) ; } FileLoader loader = new FileLoader ( ) ; loader . setPrefix ( prefix ) ; return loader ; } else { File file = new File ( environment . getBasePath ( ) , templateLoaderPath ) ; String prefix = file . getAbsolutePath ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Template loader path [" + templateLoaderPath + "] resolved to file path [" + prefix + "]" ) ; } FileLoader loader = new FileLoader ( ) ; loader . setPrefix ( prefix ) ; return loader ; } } | Determine a Pebble Engine Template Loader for the given path . | 379 | 14 |
22,359 | public String newSessionId ( long seedTerm ) { synchronized ( random ) { long r0 ; if ( weakRandom ) { r0 = hashCode ( ) ^ Runtime . getRuntime ( ) . freeMemory ( ) ^ random . nextInt ( ) ^ ( seedTerm << 32 ) ; } else { r0 = random . nextLong ( ) ; } if ( r0 < 0 ) { r0 = - r0 ; } long r1 ; if ( weakRandom ) { r1 = hashCode ( ) ^ Runtime . getRuntime ( ) . freeMemory ( ) ^ random . nextInt ( ) ^ ( seedTerm << 32 ) ; } else { r1 = random . nextLong ( ) ; } if ( r1 < 0 ) { r1 = - r1 ; } StringBuilder id = new StringBuilder ( ) ; if ( ! StringUtils . isEmpty ( groupName ) ) { id . append ( groupName ) ; } id . append ( Long . toString ( r0 , 36 ) ) ; id . append ( Long . toString ( r1 , 36 ) ) ; id . append ( counter . getAndIncrement ( ) ) ; return id . toString ( ) ; } } | Returns a new unique session id . | 254 | 7 |
22,360 | private void initRandom ( ) { try { random = new SecureRandom ( ) ; } catch ( Exception e ) { log . warn ( "Could not generate SecureRandom for session-id randomness" , e ) ; random = new Random ( ) ; weakRandom = true ; } } | Set up a random number generator for the sessionids . | 59 | 11 |
22,361 | public void write ( Parameters parameters ) throws IOException { if ( parameters != null ) { for ( Parameter pv : parameters . getParameterValueMap ( ) . values ( ) ) { if ( pv . isAssigned ( ) ) { write ( pv ) ; } } } } | Write a Parameters object to the character - output stream . | 61 | 11 |
22,362 | public void comment ( String message ) throws IOException { if ( message . indexOf ( NEW_LINE_CHAR ) != - 1 ) { String line ; int start = 0 ; while ( ( line = readLine ( message , start ) ) != null ) { writer . write ( COMMENT_LINE_START ) ; writer . write ( SPACE_CHAR ) ; writer . write ( line ) ; newLine ( ) ; start += line . length ( ) ; start = skipNewLineChar ( message , start ) ; if ( start == - 1 ) { break ; } } if ( start != - 1 ) { writer . write ( COMMENT_LINE_START ) ; newLine ( ) ; } } else { writer . write ( COMMENT_LINE_START ) ; writer . write ( SPACE_CHAR ) ; writer . write ( message ) ; newLine ( ) ; } } | Writes a comment to the character - output stream . | 186 | 11 |
22,363 | public static String stringify ( Parameters parameters , String indentString ) { if ( parameters == null ) { return null ; } try { Writer writer = new StringWriter ( ) ; AponWriter aponWriter = new AponWriter ( writer ) ; aponWriter . setIndentString ( indentString ) ; aponWriter . write ( parameters ) ; aponWriter . close ( ) ; return writer . toString ( ) ; } catch ( IOException e ) { return null ; } } | Converts a Parameters object to an APON formatted string . | 102 | 12 |
22,364 | public LinkedMultiValueMap < K , V > deepCopy ( ) { LinkedMultiValueMap < K , V > copy = new LinkedMultiValueMap <> ( this . size ( ) ) ; this . forEach ( ( key , value ) -> copy . put ( key , new LinkedList <> ( value ) ) ) ; return copy ; } | Create a deep copy of this Map . | 77 | 8 |
22,365 | protected void executeAdvice ( Executable action ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Action " + action ) ; } try { action . execute ( this ) ; } catch ( Exception e ) { setRaisedException ( e ) ; throw new ActionExecutionException ( "Failed to execute advice action " + action , e ) ; } } | Executes advice action . | 81 | 5 |
22,366 | @ SuppressWarnings ( "unchecked" ) public < T > T getAspectAdviceBean ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAspectAdviceBean ( aspectId ) : null ) ; } | Gets the aspect advice bean . | 63 | 7 |
22,367 | protected void putAspectAdviceBean ( String aspectId , Object adviceBean ) { if ( aspectAdviceResult == null ) { aspectAdviceResult = new AspectAdviceResult ( ) ; } aspectAdviceResult . putAspectAdviceBean ( aspectId , adviceBean ) ; } | Puts the aspect advice bean . | 67 | 7 |
22,368 | @ SuppressWarnings ( "unchecked" ) public < T > T getBeforeAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getBeforeAdviceResult ( aspectId ) : null ) ; } | Gets the before advice result . | 59 | 7 |
22,369 | @ SuppressWarnings ( "unchecked" ) public < T > T getAfterAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAfterAdviceResult ( aspectId ) : null ) ; } | Gets the after advice result . | 59 | 7 |
22,370 | @ SuppressWarnings ( "unchecked" ) public < T > T getAroundAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getAroundAdviceResult ( aspectId ) : null ) ; } | Gets the around advice result . | 59 | 7 |
22,371 | @ SuppressWarnings ( "unchecked" ) public < T > T getFinallyAdviceResult ( String aspectId ) { return ( aspectAdviceResult != null ? ( T ) aspectAdviceResult . getFinallyAdviceResult ( aspectId ) : null ) ; } | Gets the finally advice result . | 59 | 7 |
22,372 | protected void putAdviceResult ( AspectAdviceRule aspectAdviceRule , Object adviceActionResult ) { if ( aspectAdviceResult == null ) { aspectAdviceResult = new AspectAdviceResult ( ) ; } aspectAdviceResult . putAdviceResult ( aspectAdviceRule , adviceActionResult ) ; } | Puts the result of the advice . | 69 | 8 |
22,373 | private ActionList touchActionList ( ) { if ( contentList != null ) { if ( contentList . isExplicit ( ) || contentList . size ( ) != 1 ) { contentList = null ; } else { ActionList actionList = contentList . get ( 0 ) ; if ( actionList . isExplicit ( ) ) { contentList = null ; } } } ActionList actionList ; if ( contentList == null ) { contentList = new ContentList ( false ) ; actionList = new ActionList ( false ) ; contentList . add ( actionList ) ; } else { actionList = contentList . get ( 0 ) ; } return actionList ; } | Returns the action list . If not yet instantiated then create a new one . | 141 | 16 |
22,374 | public static void setStatus ( HttpStatus httpStatus , Translet translet ) { translet . getResponseAdapter ( ) . setStatus ( httpStatus . value ( ) ) ; } | Sets the status code . | 39 | 6 |
22,375 | private void outputString ( String s ) throws SAXException { handler . characters ( s . toCharArray ( ) , 0 , s . length ( ) ) ; } | Outputs a string . | 35 | 5 |
22,376 | protected InputStream getTemplateAsStream ( URL url ) throws IOException { URLConnection conn = url . openConnection ( ) ; return conn . getInputStream ( ) ; } | Gets the template as stream . | 36 | 7 |
22,377 | public static int search ( String str , String keyw ) { int strLen = str . length ( ) ; int keywLen = keyw . length ( ) ; int pos = 0 ; int cnt = 0 ; if ( keywLen == 0 ) { return 0 ; } while ( ( pos = str . indexOf ( keyw , pos ) ) != - 1 ) { pos += keywLen ; cnt ++ ; if ( pos >= strLen ) { break ; } } return cnt ; } | Returns the number of times the specified string was found in the target string or 0 if there is no specified string . | 107 | 23 |
22,378 | public static int searchIgnoreCase ( String str , String keyw ) { return search ( str . toLowerCase ( ) , keyw . toLowerCase ( ) ) ; } | Returns the number of times the specified string was found in the target string or 0 if there is no specified string . When searching for the specified string it is not case - sensitive . | 38 | 36 |
22,379 | public static int search ( CharSequence chars , char c ) { int count = 0 ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( chars . charAt ( i ) == c ) { count ++ ; } } return count ; } | Returns the number of times the specified character was found in the target string or 0 if there is no specified character . | 60 | 23 |
22,380 | public static int searchIgnoreCase ( CharSequence chars , char c ) { int count = 0 ; char cl = Character . toLowerCase ( c ) ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( Character . toLowerCase ( chars . charAt ( i ) ) == cl ) { count ++ ; } } return count ; } | Returns the number of times the specified character was found in the target string or 0 if there is no specified character . When searching for the specified character it is not case - sensitive . | 82 | 36 |
22,381 | public static String toLanguageTag ( Locale locale ) { return locale . getLanguage ( ) + ( hasText ( locale . getCountry ( ) ) ? "-" + locale . getCountry ( ) : EMPTY ) ; } | Determine the RFC 3066 compliant language tag as used for the HTTP Accept - Language header . | 47 | 20 |
22,382 | public static String convertToHumanFriendlyByteSize ( long size ) { if ( size < 1024 ) { return size + " B" ; } int z = ( 63 - Long . numberOfLeadingZeros ( size ) ) / 10 ; double d = ( double ) size / ( 1L << ( z * 10 ) ) ; String format = ( d % 1.0 == 0 ) ? "%.0f %sB" : "%.1f %sB" ; return String . format ( format , d , " KMGTPE" . charAt ( z ) ) ; } | Convert byte size into human friendly format . | 125 | 9 |
22,383 | @ SuppressWarnings ( "fallthrough" ) public static long convertToMachineFriendlyByteSize ( String size ) { double d ; try { d = Double . parseDouble ( size . replaceAll ( "[GMK]?[B]?$" , "" ) ) ; } catch ( NumberFormatException e ) { String msg = "Size must be specified as bytes (B), " + "kilobytes (KB), megabytes (MB), gigabytes (GB). " + "E.g. 1024, 1KB, 10M, 10MB, 100G, 100GB" ; throw new NumberFormatException ( msg + " " + e . getMessage ( ) ) ; } long l = Math . round ( d * 1024 * 1024 * 1024L ) ; int index = Math . max ( 0 , size . length ( ) - ( size . endsWith ( "B" ) ? 2 : 1 ) ) ; switch ( size . charAt ( index ) ) { default : l /= 1024 ; case ' ' : l /= 1024 ; case ' ' : l /= 1024 ; case ' ' : return l ; } } | Convert byte size into machine friendly format . | 240 | 9 |
22,384 | private void scan ( final String targetPath , final String basePackageName , final String relativePackageName , final WildcardMatcher matcher , final SaveHandler saveHandler ) { final File target = new File ( targetPath ) ; if ( ! target . exists ( ) ) { return ; } target . listFiles ( file -> { String fileName = file . getName ( ) ; if ( file . isDirectory ( ) ) { String relativePackageName2 ; if ( relativePackageName == null ) { relativePackageName2 = fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; } else { relativePackageName2 = relativePackageName + fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; } String basePath2 = targetPath + fileName + ResourceUtils . REGULAR_FILE_SEPARATOR ; scan ( basePath2 , basePackageName , relativePackageName2 , matcher , saveHandler ) ; } else if ( fileName . endsWith ( ClassUtils . CLASS_FILE_SUFFIX ) ) { String className ; if ( relativePackageName != null ) { className = basePackageName + relativePackageName + fileName . substring ( 0 , fileName . length ( ) - ClassUtils . CLASS_FILE_SUFFIX . length ( ) ) ; } else { className = basePackageName + fileName . substring ( 0 , fileName . length ( ) - ClassUtils . CLASS_FILE_SUFFIX . length ( ) ) ; } String relativePath = className . substring ( basePackageName . length ( ) ) ; if ( matcher . matches ( relativePath ) ) { String resourceName = targetPath + fileName ; Class < ? > targetClass = loadClass ( className ) ; saveHandler . save ( resourceName , targetClass ) ; } } return false ; } ) ; } | Recursive method used to find all classes in a given directory and sub dirs . | 399 | 17 |
22,385 | public static boolean isAssignableValue ( Class < ? > type , Object value ) { if ( value == null ) { return ! type . isPrimitive ( ) ; } Class < ? > valueType = value . getClass ( ) ; if ( type . isArray ( ) || valueType . isArray ( ) ) { if ( ( type . isArray ( ) && valueType . isArray ( ) ) ) { int len = Array . getLength ( value ) ; if ( len == 0 ) { return true ; } else { Object first = Array . get ( value , 0 ) ; return isAssignableValue ( type . getComponentType ( ) , first ) ; } } } else { if ( type . isInstance ( value ) ) { return true ; } if ( valueType . isPrimitive ( ) && ! type . isPrimitive ( ) && type . equals ( getPrimitiveWrapper ( valueType ) ) ) { return true ; } if ( type . isPrimitive ( ) && ! valueType . isPrimitive ( ) && valueType . equals ( getPrimitiveWrapper ( type ) ) ) { return true ; } } return false ; } | Determine if the given type is assignable from the given value assuming setting by reflection . Considers primitive wrapper classes as assignable to the corresponding primitive types . | 248 | 33 |
22,386 | public static Object toComponentTypeArray ( Object val , Class < ? > componentType ) { if ( val != null ) { int len = Array . getLength ( val ) ; Object arr = Array . newInstance ( componentType , len ) ; for ( int i = 0 ; i < len ; i ++ ) { Array . set ( arr , i , Array . get ( val , i ) ) ; } return arr ; } else { return null ; } } | Converts an array of objects to an array of the specified component type . | 96 | 15 |
22,387 | public void addActionResult ( ActionResult actionResult ) { ActionResult existActionResult = getActionResult ( actionResult . getActionId ( ) ) ; if ( existActionResult != null && existActionResult . getResultValue ( ) instanceof ResultValueMap && actionResult . getResultValue ( ) instanceof ResultValueMap ) { ResultValueMap resultValueMap = ( ResultValueMap ) existActionResult . getResultValue ( ) ; resultValueMap . putAll ( ( ResultValueMap ) actionResult . getResultValue ( ) ) ; } else { add ( actionResult ) ; } } | Adds the action result . | 125 | 5 |
22,388 | private void readParameters ( ) { ItemRuleMap parameterItemRuleMap = getRequestRule ( ) . getParameterItemRuleMap ( ) ; if ( parameterItemRuleMap != null && ! parameterItemRuleMap . isEmpty ( ) ) { ItemRuleList parameterItemRuleList = new ItemRuleList ( parameterItemRuleMap . values ( ) ) ; determineSimpleMode ( parameterItemRuleList ) ; if ( procedural ) { console . setStyle ( "GREEN" ) ; console . writeLine ( "Required parameters:" ) ; console . styleOff ( ) ; if ( ! simpleInputMode ) { for ( ItemRule itemRule : parameterItemRuleList ) { Token [ ] tokens = itemRule . getAllTokens ( ) ; if ( tokens == null ) { Token t = new Token ( TokenType . PARAMETER , itemRule . getName ( ) ) ; t . setDefaultValue ( itemRule . getDefaultValue ( ) ) ; tokens = new Token [ ] { t } ; } String mandatoryMarker = itemRule . isMandatory ( ) ? " * " : " " ; console . setStyle ( "YELLOW" ) ; console . write ( mandatoryMarker ) ; console . styleOff ( ) ; console . setStyle ( "bold" ) ; console . write ( itemRule . getName ( ) ) ; console . styleOff ( ) ; console . write ( ": " ) ; writeToken ( tokens ) ; console . writeLine ( ) ; } } } readRequiredParameters ( parameterItemRuleList ) ; } } | Read required input parameters . | 324 | 5 |
22,389 | private void readAttributes ( ) { ItemRuleMap attributeItemRuleMap = getRequestRule ( ) . getAttributeItemRuleMap ( ) ; if ( attributeItemRuleMap != null && ! attributeItemRuleMap . isEmpty ( ) ) { ItemRuleList attributeItemRuleList = new ItemRuleList ( attributeItemRuleMap . values ( ) ) ; determineSimpleMode ( attributeItemRuleList ) ; if ( procedural ) { console . setStyle ( "GREEN" ) ; console . writeLine ( "Required attributes:" ) ; console . styleOff ( ) ; if ( ! simpleInputMode ) { for ( ItemRule itemRule : attributeItemRuleList ) { Token [ ] tokens = itemRule . getAllTokens ( ) ; if ( tokens == null ) { Token t = new Token ( TokenType . PARAMETER , itemRule . getName ( ) ) ; t . setDefaultValue ( itemRule . getDefaultValue ( ) ) ; tokens = new Token [ ] { t } ; } String mandatoryMarker = itemRule . isMandatory ( ) ? " * " : " " ; console . setStyle ( "YELLOW" ) ; console . write ( mandatoryMarker ) ; console . styleOff ( ) ; console . setStyle ( "bold" ) ; console . write ( itemRule . getName ( ) ) ; console . styleOff ( ) ; console . write ( ": " ) ; writeToken ( tokens ) ; console . writeLine ( ) ; } } } readRequiredAttributes ( attributeItemRuleList ) ; } } | Read required input attributes . | 324 | 5 |
22,390 | private void destroySingletons ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Destroying singletons in " + this ) ; } int failedDestroyes = 0 ; for ( BeanRule beanRule : beanRuleRegistry . getIdBasedBeanRules ( ) ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } for ( Set < BeanRule > beanRuleSet : beanRuleRegistry . getTypeBasedBeanRules ( ) ) { for ( BeanRule beanRule : beanRuleSet ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } } for ( BeanRule beanRule : beanRuleRegistry . getConfigurableBeanRules ( ) ) { failedDestroyes += doDestroySingleton ( beanRule ) ; } if ( failedDestroyes > 0 ) { log . warn ( "Singletons has not been destroyed cleanly (Failure Count: " + failedDestroyes + ")" ) ; } else { log . debug ( "Destroyed all cached singletons in " + this ) ; } } | Destroy all cached singletons . | 229 | 7 |
22,391 | public static Response createTransformResponse ( TransformRule transformRule ) { TransformType transformType = transformRule . getTransformType ( ) ; Response transformResponse ; if ( transformType == TransformType . XSL ) { transformResponse = new XslTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . XML ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_XML . toString ( ) ) ; } transformResponse = new XmlTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . TEXT ) { transformResponse = new TextTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . JSON ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_PLAIN . toString ( ) ) ; } transformResponse = new JsonTransformResponse ( transformRule ) ; } else if ( transformType == TransformType . APON ) { if ( transformRule . getContentType ( ) == null ) { transformRule . setContentType ( ContentType . TEXT_PLAIN . toString ( ) ) ; } transformResponse = new AponTransformResponse ( transformRule ) ; } else { transformResponse = new NoneTransformResponse ( transformRule ) ; } return transformResponse ; } | Creates a new Transform object with specified TransformRule . | 289 | 11 |
22,392 | private void mem ( boolean gc , Console console ) { long total = Runtime . getRuntime ( ) . totalMemory ( ) ; long before = Runtime . getRuntime ( ) . freeMemory ( ) ; console . writeLine ( "%-24s %12s" , "Total memory" , StringUtils . convertToHumanFriendlyByteSize ( total ) ) ; console . writeLine ( "%-24s %12s" , "Used memory" , StringUtils . convertToHumanFriendlyByteSize ( total - before ) ) ; if ( gc ) { // Let the finalizer finish its work and remove objects from its queue System . gc ( ) ; // asynchronous garbage collector might already run System . gc ( ) ; // to make sure it does a full gc call it twice System . runFinalization ( ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { // do nothing } long after = Runtime . getRuntime ( ) . freeMemory ( ) ; console . writeLine ( "%-24s %12s" , "Free memory before GC" , StringUtils . convertToHumanFriendlyByteSize ( before ) ) ; console . writeLine ( "%-24s %12s" , "Free memory after GC" , StringUtils . convertToHumanFriendlyByteSize ( after ) ) ; console . writeLine ( "%-24s %12s" , "Memory gained with GC" , StringUtils . convertToHumanFriendlyByteSize ( after - before ) ) ; } else { console . writeLine ( "%-24s %12s" , "Free memory" , StringUtils . convertToHumanFriendlyByteSize ( before ) ) ; } } | Displays memory usage . | 366 | 5 |
22,393 | private void initMessageSource ( ) { if ( contextBeanRegistry . containsBean ( MESSAGE_SOURCE_BEAN_ID ) ) { messageSource = contextBeanRegistry . getBean ( MESSAGE_SOURCE_BEAN_ID , MessageSource . class ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Using MessageSource [" + messageSource + "]" ) ; } } else { // Use empty MessageSource to be able to accept getMessage calls. messageSource = new DelegatingMessageSource ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_ID + "': using default [" + messageSource + "]" ) ; } } } | Initialize the MessageSource . Use parent s if none defined in this context . | 178 | 16 |
22,394 | protected Locale resolveDefaultLocale ( Translet translet ) { Locale defaultLocale = getDefaultLocale ( ) ; if ( defaultLocale != null ) { translet . getRequestAdapter ( ) . setLocale ( defaultLocale ) ; return defaultLocale ; } else { return translet . getRequestAdapter ( ) . getLocale ( ) ; } } | Resolve the default locale for the given translet Called if can not find specified Locale . | 80 | 19 |
22,395 | protected TimeZone resolveDefaultTimeZone ( Translet translet ) { TimeZone defaultTimeZone = getDefaultTimeZone ( ) ; if ( defaultTimeZone != null ) { translet . getRequestAdapter ( ) . setTimeZone ( defaultTimeZone ) ; return defaultTimeZone ; } else { return translet . getRequestAdapter ( ) . getTimeZone ( ) ; } } | Resolve the default time zone for the given translet Called if can not find specified TimeZone . | 80 | 20 |
22,396 | public static Parameters parse ( String text ) throws AponParseException { Parameters parameters = new VariableParameters ( ) ; return parse ( text , parameters ) ; } | Converts an APON formatted string into a Parameters object . | 33 | 12 |
22,397 | public static < T extends Parameters > T parse ( String text , T parameters ) throws AponParseException { if ( text == null ) { throw new IllegalArgumentException ( "text must not be null" ) ; } if ( parameters == null ) { throw new IllegalArgumentException ( "parameters must not be null" ) ; } try { AponReader aponReader = new AponReader ( text ) ; aponReader . read ( parameters ) ; aponReader . close ( ) ; return parameters ; } catch ( AponParseException e ) { throw e ; } catch ( Exception e ) { throw new AponParseException ( "Failed to parse string with APON format" , e ) ; } } | Converts an APON formatted string into a given Parameters object . | 155 | 13 |
22,398 | public static Parameters parse ( File file , String encoding ) throws AponParseException { if ( file == null ) { throw new IllegalArgumentException ( "file must not be null" ) ; } Parameters parameters = new VariableParameters ( ) ; return parse ( file , encoding , parameters ) ; } | Converts to a Parameters object from a file . | 62 | 10 |
22,399 | public static Parameters parse ( Reader reader ) throws AponParseException { if ( reader == null ) { throw new IllegalArgumentException ( "reader must not be null" ) ; } AponReader aponReader = new AponReader ( reader ) ; return aponReader . read ( ) ; } | Converts to a Parameters object from a character - input stream . | 64 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.