idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
24,800 | public static boolean executeSql ( final String sql , final Connection connection , final boolean isDebug ) throws SQLException { if ( isDebug || LOGGER . isTraceEnabled ( ) ) { LOGGER . log ( Level . INFO , "Executing SQL [" + sql + "]" ) ; } final Statement statement = connection . createStatement ( ) ; final boolean isSuccess = ! statement . execute ( sql ) ; statement . close ( ) ; return isSuccess ; } | Executes the specified SQL with the specified connection . |
24,801 | public static boolean executeSql ( final String sql , final List < Object > paramList , final Connection connection , final boolean isDebug ) throws SQLException { if ( isDebug || LOGGER . isTraceEnabled ( ) ) { LOGGER . log ( Level . INFO , "Executing SQL [" + sql + "]" ) ; } final PreparedStatement preparedStatement = connection . prepareStatement ( sql ) ; for ( int i = 1 ; i <= paramList . size ( ) ; i ++ ) { preparedStatement . setObject ( i , paramList . get ( i - 1 ) ) ; } final boolean isSuccess = preparedStatement . execute ( ) ; preparedStatement . close ( ) ; return isSuccess ; } | Executes the specified SQL with the specified params and connection ... |
24,802 | protected String genHTML ( final HttpServletRequest request , final Map < String , Object > dataModel , final Template template ) throws Exception { final StringWriter stringWriter = new StringWriter ( ) ; template . setOutputEncoding ( "UTF-8" ) ; template . process ( dataModel , stringWriter ) ; final StringBuilder pageContentBuilder = new StringBuilder ( stringWriter . toString ( ) ) ; final long endimeMillis = System . currentTimeMillis ( ) ; final String dateString = DateFormatUtils . format ( endimeMillis , "yyyy/MM/dd HH:mm:ss" ) ; final long startTimeMillis = ( Long ) request . getAttribute ( Keys . HttpRequest . START_TIME_MILLIS ) ; final String msg = String . format ( "\n<!-- Generated by Latke (https://github.com/b3log/latke) in %1$dms, %2$s , endimeMillis - startTimeMillis , dateString ) ; pageContentBuilder . append ( msg ) ; return pageContentBuilder . toString ( ) ; } | Processes the specified FreeMarker template with the specified request data model . |
24,803 | public static Collection < Class < ? > > discover ( final String scanPath ) throws Exception { if ( StringUtils . isBlank ( scanPath ) ) { throw new IllegalStateException ( "Please specify the [scanPath]" ) ; } LOGGER . debug ( "scanPath[" + scanPath + "]" ) ; final Collection < Class < ? > > ret = new HashSet < > ( ) ; final String [ ] splitPaths = scanPath . split ( "," ) ; final String [ ] paths = ArrayUtils . concatenate ( splitPaths , BUILT_IN_COMPONENT_PKGS ) ; final Set < URL > urls = new LinkedHashSet < > ( ) ; for ( String path : paths ) { if ( ! AntPathMatcher . isPattern ( path ) ) { path = path . replaceAll ( "\\." , "/" ) + "/**/*.class" ; } urls . addAll ( ClassPathResolver . getResources ( path ) ) ; } for ( final URL url : urls ) { final DataInputStream classInputStream = new DataInputStream ( url . openStream ( ) ) ; final ClassFile classFile = new ClassFile ( classInputStream ) ; final String className = classFile . getName ( ) ; final AnnotationsAttribute annotationsAttribute = ( AnnotationsAttribute ) classFile . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( null == annotationsAttribute ) { LOGGER . log ( Level . TRACE , "The class [name={0}] is not a bean" , className ) ; continue ; } final ConstPool constPool = classFile . getConstPool ( ) ; final Annotation [ ] annotations = annotationsAttribute . getAnnotations ( ) ; boolean maybeBeanClass = false ; for ( final Annotation annotation : annotations ) { final String typeName = annotation . getTypeName ( ) ; if ( typeName . equals ( Singleton . class . getName ( ) ) ) { maybeBeanClass = true ; break ; } if ( typeName . equals ( RequestProcessor . class . getName ( ) ) || typeName . equals ( Service . class . getName ( ) ) || typeName . equals ( Repository . class . getName ( ) ) ) { final Annotation singletonAnnotation = new Annotation ( Singleton . class . getName ( ) , constPool ) ; annotationsAttribute . addAnnotation ( singletonAnnotation ) ; classFile . addAttribute ( annotationsAttribute ) ; classFile . setVersionToJava5 ( ) ; maybeBeanClass = true ; break ; } } if ( maybeBeanClass ) { Class < ? > clz = null ; try { clz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( final ClassNotFoundException e ) { LOGGER . log ( Level . ERROR , "Loads class [" + className + "] failed" , e ) ; } ret . add ( clz ) ; } } return ret ; } | Scans classpath to discover bean classes . |
24,804 | public static String signHmacSHA1 ( final String source , final String secret ) { try { final Mac mac = Mac . getInstance ( "HmacSHA1" ) ; mac . init ( new SecretKeySpec ( secret . getBytes ( "UTF-8" ) , "HmacSHA1" ) ) ; final byte [ ] signData = mac . doFinal ( source . getBytes ( "UTF-8" ) ) ; return new String ( Base64 . encodeBase64 ( signData ) , "UTF-8" ) ; } catch ( final Exception e ) { throw new RuntimeException ( "HMAC-SHA1 sign failed" , e ) ; } } | Signs the specified source string using the specified secret . |
24,805 | public static String encryptByAES ( final String content , final String key ) { try { final KeyGenerator kgen = KeyGenerator . getInstance ( "AES" ) ; final SecureRandom secureRandom = SecureRandom . getInstance ( "SHA1PRNG" ) ; secureRandom . setSeed ( key . getBytes ( ) ) ; kgen . init ( 128 , secureRandom ) ; final SecretKey secretKey = kgen . generateKey ( ) ; final byte [ ] enCodeFormat = secretKey . getEncoded ( ) ; final SecretKeySpec keySpec = new SecretKeySpec ( enCodeFormat , "AES" ) ; final Cipher cipher = Cipher . getInstance ( "AES" ) ; final byte [ ] byteContent = content . getBytes ( "UTF-8" ) ; cipher . init ( Cipher . ENCRYPT_MODE , keySpec ) ; final byte [ ] result = cipher . doFinal ( byteContent ) ; return Hex . encodeHexString ( result ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Encrypt failed" , e ) ; return null ; } } | Encrypts by AES . |
24,806 | public static String decryptByAES ( final String content , final String key ) { try { final byte [ ] data = Hex . decodeHex ( content . toCharArray ( ) ) ; final KeyGenerator kgen = KeyGenerator . getInstance ( "AES" ) ; final SecureRandom secureRandom = SecureRandom . getInstance ( "SHA1PRNG" ) ; secureRandom . setSeed ( key . getBytes ( ) ) ; kgen . init ( 128 , secureRandom ) ; final SecretKey secretKey = kgen . generateKey ( ) ; final byte [ ] enCodeFormat = secretKey . getEncoded ( ) ; final SecretKeySpec keySpec = new SecretKeySpec ( enCodeFormat , "AES" ) ; final Cipher cipher = Cipher . getInstance ( "AES" ) ; cipher . init ( Cipher . DECRYPT_MODE , keySpec ) ; final byte [ ] result = cipher . doFinal ( data ) ; return new String ( result , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Decrypt failed" ) ; return null ; } } | Decrypts by AES . |
24,807 | public static synchronized String genTimeMillisId ( ) { String ret ; ID_GEN_LOCK . lock ( ) ; try { ret = String . valueOf ( System . currentTimeMillis ( ) ) ; try { Thread . sleep ( ID_GEN_SLEEP_MILLIS ) ; } catch ( final InterruptedException e ) { throw new RuntimeException ( "Generates time millis id fail" ) ; } } finally { ID_GEN_LOCK . unlock ( ) ; } return ret ; } | Gets current date time string . |
24,808 | public static boolean hasLocale ( final Locale locale ) { try { ResourceBundle . getBundle ( Keys . LANGUAGE , locale ) ; return true ; } catch ( final MissingResourceException e ) { return false ; } } | Determines whether the server has the specified locale configuration or not . |
24,809 | public static void setLocale ( final HttpServletRequest request , final Locale locale ) { final HttpSession session = request . getSession ( false ) ; if ( null == session ) { LOGGER . warn ( "Ignores set locale caused by no session" ) ; return ; } session . setAttribute ( Keys . LOCALE , locale ) ; LOGGER . log ( Level . DEBUG , "Client[sessionId={0}] sets locale to [{1}]" , new Object [ ] { session . getId ( ) , locale . toString ( ) } ) ; } | Sets the specified locale into session of the specified request . |
24,810 | public static Locale getLocale ( ) { final Locale ret = LOCALE . get ( ) ; if ( null == ret ) { return Latkes . getLocale ( ) ; } return ret ; } | Gets locale . |
24,811 | public static String getCountry ( final String localeString ) { if ( localeString . length ( ) >= COUNTRY_END ) { return localeString . substring ( COUNTRY_START , COUNTRY_END ) ; } return "" ; } | Gets country from the specified locale string . |
24,812 | public static String getLanguage ( final String localeString ) { if ( localeString . length ( ) >= LANG_END ) { return localeString . substring ( LANG_START , LANG_END ) ; } return "" ; } | Gets language from the specified locale string . |
24,813 | private String createKeyDefinition ( final List < FieldDefinition > keyDefinitionList ) { final StringBuilder sql = new StringBuilder ( ) ; sql . append ( " PRIMARY KEY" ) ; boolean isFirst = true ; for ( FieldDefinition fieldDefinition : keyDefinitionList ) { if ( isFirst ) { sql . append ( "(" ) ; isFirst = false ; } else { sql . append ( "," ) ; } sql . append ( fieldDefinition . getName ( ) ) ; } sql . append ( ")" ) ; return sql . toString ( ) ; } | the keyDefinitionList tableSql . |
24,814 | public static String escape ( String string ) { char c ; String s = string . trim ( ) ; int length = s . length ( ) ; StringBuilder sb = new StringBuilder ( length ) ; for ( int i = 0 ; i < length ; i += 1 ) { c = s . charAt ( i ) ; if ( c < ' ' || c == '+' || c == '%' || c == '=' || c == ';' ) { sb . append ( '%' ) ; sb . append ( Character . forDigit ( ( char ) ( ( c >>> 4 ) & 0x0f ) , 16 ) ) ; sb . append ( Character . forDigit ( ( char ) ( c & 0x0f ) , 16 ) ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; } | Produce a copy of a string in which the characters + % = ; and control characters are replaced with %hh . This is a gentle form of URL encoding attempting to cause as little distortion to the string as possible . The characters = and ; are meta characters in cookies . By convention they are escaped using the URL - encoding . This is only a convention not a standard . Often cookies are expected to have encoded values . We encode = and ; because we must . We encode % and + because they are meta characters in URL encoding . |
24,815 | private < T > T getReference ( final Bean < T > bean ) { T ret = ( T ) beanReferences . get ( bean ) ; if ( null != ret ) { return ret ; } ret = bean . create ( ) ; if ( null != ret ) { beanReferences . put ( bean , ret ) ; return ret ; } throw new RuntimeException ( "Can't create reference for bean [" + bean + "]" ) ; } | Gets reference of the specified bean and creational context . |
24,816 | private < T > void destroyReference ( final Bean < T > bean , final T beanInstance ) { bean . destroy ( beanInstance ) ; } | Destroys the specified bean s instance . |
24,817 | public static void dispose ( ) { final JdbcTransaction jdbcTransaction = TX . get ( ) ; if ( null != jdbcTransaction && jdbcTransaction . getConnection ( ) != null ) { jdbcTransaction . dispose ( ) ; } final Connection connection = CONN . get ( ) ; if ( null != connection ) { try { connection . close ( ) ; } catch ( final SQLException e ) { throw new RuntimeException ( "Close connection failed" , e ) ; } finally { CONN . set ( null ) ; } } } | Disposes the resources . |
24,818 | private void update ( final String id , final JSONObject oldJsonObject , final JSONObject jsonObject , final List < Object > paramList , final StringBuilder sql ) throws JSONException { final JSONObject needUpdateJsonObject = getNeedUpdateJsonObject ( oldJsonObject , jsonObject ) ; if ( 0 == needUpdateJsonObject . length ( ) ) { LOGGER . log ( Level . TRACE , "Nothing to update [{0}] for repository [{1}]" , id , getName ( ) ) ; return ; } setUpdateProperties ( id , needUpdateJsonObject , paramList , sql ) ; } | Compares the specified old json object and new json object updates it if need . |
24,819 | private JSONObject getNeedUpdateJsonObject ( final JSONObject oldJsonObject , final JSONObject jsonObject ) throws JSONException { if ( null == oldJsonObject ) { return jsonObject ; } final JSONObject ret = new JSONObject ( ) ; final Iterator < String > keys = jsonObject . keys ( ) ; String key ; while ( keys . hasNext ( ) ) { key = keys . next ( ) ; if ( null == jsonObject . get ( key ) && null == oldJsonObject . get ( key ) ) { ret . put ( key , jsonObject . get ( key ) ) ; } else if ( ! jsonObject . optString ( key ) . equals ( oldJsonObject . optString ( key ) ) ) { ret . put ( key , jsonObject . get ( key ) ) ; } } return ret ; } | Compares the specified old json object and the new json object returns diff object for updating . |
24,820 | private void remove ( final String id , final StringBuilder sql ) { sql . append ( "DELETE FROM " ) . append ( getName ( ) ) . append ( " WHERE " ) . append ( JdbcRepositories . getDefaultKeyName ( ) ) . append ( " = '" ) . append ( id ) . append ( "'" ) ; } | Removes an record . |
24,821 | private Map < String , Object > buildSQLCount ( final int currentPageNum , final int pageSize , final int pageCount , final Query query , final StringBuilder sqlBuilder , final List < Object > paramList ) throws RepositoryException { final Map < String , Object > ret = new HashMap < > ( ) ; int pageCnt = pageCount ; int recordCnt = 0 ; final StringBuilder selectBuilder = new StringBuilder ( ) ; final StringBuilder whereBuilder = new StringBuilder ( ) ; final StringBuilder orderByBuilder = new StringBuilder ( ) ; buildSelect ( selectBuilder , query . getProjections ( ) ) ; buildWhere ( whereBuilder , paramList , query . getFilter ( ) ) ; buildOrderBy ( orderByBuilder , query . getSorts ( ) ) ; if ( - 1 == pageCount ) { final StringBuilder countBuilder = new StringBuilder ( "SELECT COUNT(" + JdbcRepositories . getDefaultKeyName ( ) + ") FROM " ) . append ( getName ( ) ) ; if ( StringUtils . isNotBlank ( whereBuilder . toString ( ) ) ) { countBuilder . append ( " WHERE " ) . append ( whereBuilder ) ; } recordCnt = ( int ) count ( countBuilder , paramList ) ; if ( 0 == recordCnt ) { ret . put ( Pagination . PAGINATION_PAGE_COUNT , 0 ) ; ret . put ( Pagination . PAGINATION_RECORD_COUNT , 0 ) ; return ret ; } pageCnt = ( int ) Math . ceil ( ( double ) recordCnt / ( double ) pageSize ) ; } ret . put ( Pagination . PAGINATION_PAGE_COUNT , pageCnt ) ; ret . put ( Pagination . PAGINATION_RECORD_COUNT , recordCnt ) ; final int start = ( currentPageNum - 1 ) * pageSize ; final int end = start + pageSize ; sqlBuilder . append ( JdbcFactory . getInstance ( ) . queryPage ( start , end , selectBuilder . toString ( ) , whereBuilder . toString ( ) , orderByBuilder . toString ( ) , getName ( ) ) ) ; return ret ; } | Builds query SQL and count result . |
24,822 | private void buildSelect ( final StringBuilder selectBuilder , final List < Projection > projections ) { selectBuilder . append ( "SELECT " ) ; if ( null == projections || projections . isEmpty ( ) ) { selectBuilder . append ( " * " ) ; return ; } selectBuilder . append ( projections . stream ( ) . map ( Projection :: getKey ) . collect ( Collectors . joining ( ", " ) ) ) ; } | Builds SELECT part with the specified select build and projections . |
24,823 | private void buildWhere ( final StringBuilder whereBuilder , final List < Object > paramList , final Filter filter ) throws RepositoryException { if ( null == filter ) { return ; } if ( filter instanceof PropertyFilter ) { processPropertyFilter ( whereBuilder , paramList , ( PropertyFilter ) filter ) ; } else { processCompositeFilter ( whereBuilder , paramList , ( CompositeFilter ) filter ) ; } } | Builds WHERE part with the specified where build param list and filter . |
24,824 | private void buildOrderBy ( final StringBuilder orderByBuilder , final Map < String , SortDirection > sorts ) { boolean isFirst = true ; String querySortDirection ; for ( final Map . Entry < String , SortDirection > sort : sorts . entrySet ( ) ) { if ( isFirst ) { orderByBuilder . append ( " ORDER BY " ) ; isFirst = false ; } else { orderByBuilder . append ( ", " ) ; } if ( sort . getValue ( ) . equals ( SortDirection . ASCENDING ) ) { querySortDirection = "ASC" ; } else { querySortDirection = "DESC" ; } orderByBuilder . append ( sort . getKey ( ) ) . append ( " " ) . append ( querySortDirection ) ; } } | Builds ORDER BY part with the specified order by build and sorts . |
24,825 | private Connection getConnection ( ) { final JdbcTransaction jdbcTransaction = TX . get ( ) ; if ( null != jdbcTransaction && jdbcTransaction . isActive ( ) ) { return jdbcTransaction . getConnection ( ) ; } Connection ret = CONN . get ( ) ; try { if ( null != ret && ! ret . isClosed ( ) ) { return ret ; } ret = Connections . getConnection ( ) ; } catch ( final SQLException e ) { LOGGER . log ( Level . ERROR , "Gets a connection failed" , e ) ; } CONN . set ( ret ) ; return ret ; } | getConnection . default using current JdbcTransaction s connection if null get a new one . |
24,826 | private void processPropertyFilter ( final StringBuilder whereBuilder , final List < Object > paramList , final PropertyFilter propertyFilter ) throws RepositoryException { String filterOperator ; switch ( propertyFilter . getOperator ( ) ) { case EQUAL : filterOperator = "=" ; break ; case GREATER_THAN : filterOperator = ">" ; break ; case GREATER_THAN_OR_EQUAL : filterOperator = ">=" ; break ; case LESS_THAN : filterOperator = "<" ; break ; case LESS_THAN_OR_EQUAL : filterOperator = "<=" ; break ; case NOT_EQUAL : filterOperator = "!=" ; break ; case IN : filterOperator = "IN" ; break ; case LIKE : filterOperator = "LIKE" ; break ; case NOT_LIKE : filterOperator = "NOT LIKE" ; break ; default : throw new RepositoryException ( "Unsupported filter operator [" + propertyFilter . getOperator ( ) + "]" ) ; } if ( FilterOperator . IN != propertyFilter . getOperator ( ) ) { whereBuilder . append ( propertyFilter . getKey ( ) ) . append ( " " ) . append ( filterOperator ) . append ( " ?" ) ; paramList . add ( propertyFilter . getValue ( ) ) ; } else { final Collection < Object > objects = ( Collection < Object > ) propertyFilter . getValue ( ) ; boolean isSubFist = true ; if ( objects != null && ! objects . isEmpty ( ) ) { whereBuilder . append ( propertyFilter . getKey ( ) ) . append ( " IN " ) ; final Iterator < Object > obs = objects . iterator ( ) ; while ( obs . hasNext ( ) ) { if ( isSubFist ) { whereBuilder . append ( "(" ) ; isSubFist = false ; } else { whereBuilder . append ( "," ) ; } whereBuilder . append ( "?" ) ; paramList . add ( obs . next ( ) ) ; if ( ! obs . hasNext ( ) ) { whereBuilder . append ( ") " ) ; } } } else { whereBuilder . append ( "1 != 1" ) ; } } } | Processes property filter . |
24,827 | private void processCompositeFilter ( final StringBuilder whereBuilder , final List < Object > paramList , final CompositeFilter compositeFilter ) throws RepositoryException { final List < Filter > subFilters = compositeFilter . getSubFilters ( ) ; if ( 2 > subFilters . size ( ) ) { throw new RepositoryException ( "At least two sub filters in a composite filter" ) ; } whereBuilder . append ( "(" ) ; final Iterator < Filter > iterator = subFilters . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Filter filter = iterator . next ( ) ; if ( filter instanceof PropertyFilter ) { processPropertyFilter ( whereBuilder , paramList , ( PropertyFilter ) filter ) ; } else { processCompositeFilter ( whereBuilder , paramList , ( CompositeFilter ) filter ) ; } if ( iterator . hasNext ( ) ) { switch ( compositeFilter . getOperator ( ) ) { case AND : whereBuilder . append ( " AND " ) ; break ; case OR : whereBuilder . append ( " OR " ) ; break ; default : throw new RepositoryException ( "Unsupported composite filter [operator=" + compositeFilter . getOperator ( ) + "]" ) ; } } } whereBuilder . append ( ")" ) ; } | Processes composite filter . |
24,828 | private static void toOracleClobEmpty ( final JSONObject jsonObject ) { final Iterator < String > keys = jsonObject . keys ( ) ; try { while ( keys . hasNext ( ) ) { final String name = keys . next ( ) ; final Object val = jsonObject . get ( name ) ; if ( val instanceof String ) { final String valStr = ( String ) val ; if ( StringUtils . isBlank ( valStr ) ) { jsonObject . put ( name , ORA_EMPTY_STR ) ; } } } } catch ( final JSONException e ) { LOGGER . log ( Level . ERROR , "Process oracle clob empty failed" , e ) ; } } | Process Oracle CLOB empty string . |
24,829 | public < T > Future < T > fireEventAsynchronously ( final Event < ? > event ) { final FutureTask < T > futureTask = new FutureTask < T > ( ( ) -> { synchronizedEventQueue . fireEvent ( event ) ; return null ; } ) ; Latkes . EXECUTOR_SERVICE . execute ( futureTask ) ; return futureTask ; } | Fire the specified event asynchronously . |
24,830 | public static void setRepositoriesWritable ( final boolean writable ) { for ( final Map . Entry < String , Repository > entry : REPOS_HOLDER . entrySet ( ) ) { final String repositoryName = entry . getKey ( ) ; final Repository repository = entry . getValue ( ) ; repository . setWritable ( writable ) ; LOGGER . log ( Level . INFO , "Sets repository[name={0}] writable[{1}]" , new Object [ ] { repositoryName , writable } ) ; } repositoryiesWritable = writable ; } | Sets all repositories whether is writable with the specified flag . |
24,831 | public static JSONArray getRepositoryNames ( ) { final JSONArray ret = new JSONArray ( ) ; if ( null == repositoriesDescription ) { LOGGER . log ( Level . INFO , "Not found repository description[repository.json] file under classpath" ) ; return ret ; } final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; ret . put ( repository . optString ( "name" ) ) ; } return ret ; } | Gets repository names . |
24,832 | public static JSONObject getRepositoryDef ( final String repositoryName ) { if ( StringUtils . isBlank ( repositoryName ) ) { return null ; } if ( null == repositoriesDescription ) { return null ; } final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; if ( repositoryName . equals ( repository . optString ( "name" ) ) ) { return repository ; } } throw new RuntimeException ( "Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json" ) ; } | Gets the repository definition of an repository specified by the given repository name . |
24,833 | private static void loadRepositoryDescription ( ) { LOGGER . log ( Level . INFO , "Loading repository description...." ) ; final InputStream inputStream = AbstractRepository . class . getResourceAsStream ( "/repository.json" ) ; if ( null == inputStream ) { LOGGER . log ( Level . INFO , "Not found repository description [repository.json] file under classpath" ) ; return ; } LOGGER . log ( Level . INFO , "Parsing repository description...." ) ; try { final String description = IOUtils . toString ( inputStream , "UTF-8" ) ; LOGGER . log ( Level . DEBUG , "{0}{1}" , new Object [ ] { Strings . LINE_SEPARATOR , description } ) ; repositoriesDescription = new JSONObject ( description ) ; final String tableNamePrefix = StringUtils . isNotBlank ( Latkes . getLocalProperty ( "jdbc.tablePrefix" ) ) ? Latkes . getLocalProperty ( "jdbc.tablePrefix" ) + "_" : "" ; final JSONArray repositories = repositoriesDescription . optJSONArray ( "repositories" ) ; for ( int i = 0 ; i < repositories . length ( ) ; i ++ ) { final JSONObject repository = repositories . optJSONObject ( i ) ; repository . put ( "name" , tableNamePrefix + repository . optString ( "name" ) ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Parses repository description failed" , e ) ; } finally { try { inputStream . close ( ) ; } catch ( final IOException e ) { LOGGER . log ( Level . ERROR , e . getMessage ( ) , e ) ; throw new RuntimeException ( e ) ; } } } | Loads repository description . |
24,834 | public void contextInitialized ( final ServletContextEvent servletContextEvent ) { servletContext = servletContextEvent . getServletContext ( ) ; Latkes . init ( ) ; LOGGER . info ( "Initializing the context...." ) ; Latkes . setLocale ( Locale . SIMPLIFIED_CHINESE ) ; LOGGER . log ( Level . INFO , "Default locale [{0}]" , Latkes . getLocale ( ) ) ; final String realPath = servletContext . getRealPath ( "/" ) ; LOGGER . log ( Level . INFO , "Server [realPath={0}, contextPath={1}]" , realPath , servletContext . getContextPath ( ) ) ; try { final Collection < Class < ? > > beanClasses = Discoverer . discover ( Latkes . getScanPath ( ) ) ; BeanManager . start ( beanClasses ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Initializes request processors failed" , e ) ; throw new IllegalStateException ( "Initializes request processors failed" ) ; } } | Initializes context locale and runtime environment . |
24,835 | private void resolveDependencies ( final Object reference ) { final Class < ? > superclass = reference . getClass ( ) . getSuperclass ( ) . getSuperclass ( ) ; resolveSuperclassFieldDependencies ( reference , superclass ) ; resolveCurrentclassFieldDependencies ( reference ) ; } | Resolves dependencies for the specified reference . |
24,836 | private T instantiateReference ( ) throws Exception { final T ret = proxyClass . newInstance ( ) ; ( ( ProxyObject ) ret ) . setHandler ( javassistMethodHandler ) ; LOGGER . log ( Level . TRACE , "Uses Javassist method handler for bean [class={0}]" , beanClass . getName ( ) ) ; return ret ; } | Constructs the bean object with dependencies resolved . |
24,837 | private void resolveCurrentclassFieldDependencies ( final Object reference ) { for ( final FieldInjectionPoint injectionPoint : fieldInjectionPoints ) { final Object injection = beanManager . getInjectableReference ( injectionPoint ) ; final Field field = injectionPoint . getAnnotated ( ) . getJavaMember ( ) ; try { final Field declaredField = proxyClass . getDeclaredField ( field . getName ( ) ) ; if ( declaredField . isAnnotationPresent ( Inject . class ) ) { try { declaredField . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } catch ( final NoSuchFieldException ex ) { try { field . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } } | Resolves current class field dependencies for the specified reference . |
24,838 | private void resolveSuperclassFieldDependencies ( final Object reference , final Class < ? > clazz ) { if ( clazz . equals ( Object . class ) ) { return ; } final Class < ? > superclass = clazz . getSuperclass ( ) ; resolveSuperclassFieldDependencies ( reference , superclass ) ; if ( Modifier . isAbstract ( clazz . getModifiers ( ) ) || Modifier . isInterface ( clazz . getModifiers ( ) ) ) { return ; } final Bean < ? > bean = beanManager . getBean ( clazz ) ; final Set < FieldInjectionPoint > injectionPoints = bean . fieldInjectionPoints ; for ( final FieldInjectionPoint injectionPoint : injectionPoints ) { final Object injection = beanManager . getInjectableReference ( injectionPoint ) ; final Field field = injectionPoint . getAnnotated ( ) . getJavaMember ( ) ; try { final Field declaredField = proxyClass . getDeclaredField ( field . getName ( ) ) ; if ( ! Reflections . matchInheritance ( declaredField , field ) ) { try { field . set ( reference , injection ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } } } catch ( final NoSuchFieldException ex ) { throw new RuntimeException ( ex ) ; } } } | Resolves super class field dependencies for the specified reference . |
24,839 | private void initFieldInjectionPoints ( ) { final Set < AnnotatedField < ? super T > > annotatedFields = annotatedType . getFields ( ) ; for ( final AnnotatedField < ? super T > annotatedField : annotatedFields ) { final FieldInjectionPoint fieldInjectionPoint = new FieldInjectionPoint ( this , annotatedField ) ; fieldInjectionPoints . add ( fieldInjectionPoint ) ; } } | Initializes field injection points . |
24,840 | public static String encode ( final String str ) { try { return URLEncoder . encode ( str , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Encodes str [" + str + "] failed" , e ) ; return str ; } } | Encodes the specified string . |
24,841 | public static String decode ( final String str ) { try { return URLDecoder . decode ( str , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Decodes str [" + str + "] failed" , e ) ; return str ; } } | Decodes the specified string . |
24,842 | public static List < FieldDefinition > getKeys ( final String repositoryName ) { final List < RepositoryDefinition > repositoryDefs = getRepositoryDefinitions ( ) ; for ( final RepositoryDefinition repositoryDefinition : repositoryDefs ) { if ( StringUtils . equals ( repositoryName , repositoryDefinition . getName ( ) ) ) { return repositoryDefinition . getKeys ( ) ; } } return null ; } | Gets keys of the repository specified by the given repository name . |
24,843 | public static List < RepositoryDefinition > getRepositoryDefinitions ( ) { if ( null == repositoryDefinitions ) { try { initRepositoryDefinitions ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Init repository definitions failed" , e ) ; } } return repositoryDefinitions ; } | Gets the repository definitions lazy load . |
24,844 | private static void initRepositoryDefinitions ( ) throws JSONException { final JSONObject jsonObject = Repositories . getRepositoriesDescription ( ) ; if ( null == jsonObject ) { LOGGER . warn ( "Loads repository description [repository.json] failed" ) ; return ; } repositoryDefinitions = new ArrayList < > ( ) ; final JSONArray repositoritArray = jsonObject . getJSONArray ( REPOSITORIES ) ; JSONObject repositoryObject ; JSONObject keyObject ; for ( int i = 0 ; i < repositoritArray . length ( ) ; i ++ ) { repositoryObject = repositoritArray . getJSONObject ( i ) ; final RepositoryDefinition repositoryDefinition = new RepositoryDefinition ( ) ; repositoryDefinitions . add ( repositoryDefinition ) ; repositoryDefinition . setName ( repositoryObject . getString ( NAME ) ) ; repositoryDefinition . setDescription ( repositoryObject . optString ( DESCRIPTION ) ) ; final List < FieldDefinition > keys = new ArrayList < > ( ) ; repositoryDefinition . setKeys ( keys ) ; final JSONArray keysJsonArray = repositoryObject . getJSONArray ( KEYS ) ; FieldDefinition definition ; for ( int j = 0 ; j < keysJsonArray . length ( ) ; j ++ ) { keyObject = keysJsonArray . getJSONObject ( j ) ; definition = fillFieldDefinitionData ( keyObject ) ; keys . add ( definition ) ; } repositoryDefinition . setCharset ( repositoryObject . optString ( CHARSET ) ) ; repositoryDefinition . setCollate ( repositoryObject . optString ( COLLATE ) ) ; } } | Initializes the repository definitions . |
24,845 | public static List < CreateTableResult > initAllTables ( ) { final List < CreateTableResult > ret = new ArrayList < > ( ) ; final List < RepositoryDefinition > repositoryDefs = getRepositoryDefinitions ( ) ; boolean isSuccess = false ; for ( final RepositoryDefinition repositoryDef : repositoryDefs ) { try { isSuccess = JdbcFactory . getInstance ( ) . createTable ( repositoryDef ) ; } catch ( final SQLException e ) { LOGGER . log ( Level . ERROR , "Creates table [" + repositoryDef . getName ( ) + "] error" , e ) ; } ret . add ( new CreateTableResult ( repositoryDef . getName ( ) , isSuccess ) ) ; } return ret ; } | Initializes all tables from repository . json . |
24,846 | public static Map < String , String > resolve ( final String uri , final String uriTemplate ) { final String [ ] parts = URLs . decode ( uri ) . split ( "/" ) ; final String [ ] templateParts = uriTemplate . split ( "/" ) ; if ( parts . length != templateParts . length ) { return null ; } final Map < String , String > ret = new HashMap < > ( ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { final String part = parts [ i ] ; final String templatePart = templateParts [ i ] ; if ( part . equals ( templatePart ) ) { continue ; } String name = StringUtils . substringBetween ( templatePart , "{" , "}" ) ; if ( StringUtils . isBlank ( name ) ) { return null ; } final String templatePartTmp = StringUtils . replace ( templatePart , "{" + name + "}" , "" ) ; final String arg = StringUtils . replace ( part , templatePartTmp , "" ) ; ret . put ( name , arg ) ; } return ret ; } | Resolves the specified URI with the specified URI template . |
24,847 | private void initAnnotatedFields ( ) { final Set < Field > hiddenFields = Reflections . getHiddenFields ( beanClass ) ; inject ( hiddenFields ) ; final Set < Field > inheritedFields = Reflections . getInheritedFields ( beanClass ) ; inject ( inheritedFields ) ; final Set < Field > ownFields = Reflections . getOwnFields ( beanClass ) ; inject ( ownFields ) ; } | Builds the annotated fields of this annotated type . |
24,848 | public static boolean isStatic ( final HttpServletRequest request ) { final boolean requestStaticResourceChecked = null == request . getAttribute ( Keys . HttpRequest . REQUEST_STATIC_RESOURCE_CHECKED ) ? false : ( Boolean ) request . getAttribute ( Keys . HttpRequest . REQUEST_STATIC_RESOURCE_CHECKED ) ; if ( requestStaticResourceChecked ) { return ( Boolean ) request . getAttribute ( Keys . HttpRequest . IS_REQUEST_STATIC_RESOURCE ) ; } if ( ! inited ) { init ( ) ; } request . setAttribute ( Keys . HttpRequest . REQUEST_STATIC_RESOURCE_CHECKED , true ) ; request . setAttribute ( Keys . HttpRequest . IS_REQUEST_STATIC_RESOURCE , false ) ; final String requestURI = request . getRequestURI ( ) ; for ( final String pattern : STATIC_RESOURCE_PATHS ) { if ( AntPathMatcher . match ( Latkes . getContextPath ( ) + pattern , requestURI ) ) { request . setAttribute ( Keys . HttpRequest . IS_REQUEST_STATIC_RESOURCE , true ) ; return true ; } } return false ; } | Determines whether the client requests a static resource with the specified request . |
24,849 | private static synchronized void init ( ) { LOGGER . trace ( "Reads static resources definition from [static-resources.xml]" ) ; final File staticResources = Latkes . getWebFile ( "/WEB-INF/static-resources.xml" ) ; if ( null == staticResources || ! staticResources . exists ( ) ) { throw new IllegalStateException ( "Not found static resources definition from [static-resources.xml]" ) ; } final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; try { final DocumentBuilder documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; final Document document = documentBuilder . parse ( staticResources ) ; final Element root = document . getDocumentElement ( ) ; root . normalize ( ) ; final StringBuilder logBuilder = new StringBuilder ( "Reading static files: [" ) . append ( Strings . LINE_SEPARATOR ) ; final NodeList includes = root . getElementsByTagName ( "include" ) ; for ( int i = 0 ; i < includes . getLength ( ) ; i ++ ) { final Element include = ( Element ) includes . item ( i ) ; String path = include . getAttribute ( "path" ) ; final URI uri = new URI ( "http" , "b3log.org" , path , null ) ; final String s = uri . toASCIIString ( ) ; path = StringUtils . substringAfter ( s , "b3log.org" ) ; STATIC_RESOURCE_PATHS . add ( path ) ; logBuilder . append ( " " ) . append ( "path pattern [" ) . append ( path ) . append ( "]" ) ; if ( i < includes . getLength ( ) - 1 ) { logBuilder . append ( "," ) ; } logBuilder . append ( Strings . LINE_SEPARATOR ) ; } logBuilder . append ( "]" ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . debug ( logBuilder . toString ( ) ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Reads [" + staticResources . getName ( ) + "] failed" , e ) ; throw new RuntimeException ( e ) ; } final StringBuilder logBuilder = new StringBuilder ( "Static files: [" ) . append ( Strings . LINE_SEPARATOR ) ; final Iterator < String > iterator = STATIC_RESOURCE_PATHS . iterator ( ) ; while ( iterator . hasNext ( ) ) { final String pattern = iterator . next ( ) ; logBuilder . append ( " " ) . append ( pattern ) ; if ( iterator . hasNext ( ) ) { logBuilder . append ( ',' ) ; } logBuilder . append ( Strings . LINE_SEPARATOR ) ; } logBuilder . append ( "], " ) . append ( '[' ) . append ( STATIC_RESOURCE_PATHS . size ( ) ) . append ( "] path patterns" ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( logBuilder . toString ( ) ) ; } inited = true ; } | Initializes the static resource path patterns . |
24,850 | public static void start ( final Collection < Class < ? > > classes ) { LOGGER . log ( Level . DEBUG , "Initializing Latke IoC container" ) ; final Configurator configurator = getInstance ( ) . getConfigurator ( ) ; if ( null != classes && ! classes . isEmpty ( ) ) { configurator . createBeans ( classes ) ; } LOGGER . log ( Level . DEBUG , "Initialized Latke IoC container" ) ; } | Starts the application with the specified bean class and bean modules . |
24,851 | public static void setLocalProperty ( final String key , final String value ) { if ( null == key ) { LOGGER . log ( Level . WARN , "local.props can not set null key" ) ; return ; } if ( null == value ) { LOGGER . log ( Level . WARN , "local.props can not set null value" ) ; return ; } localProps . setProperty ( key , value ) ; } | Sets local . props with the specified key and value . |
24,852 | public static void setLatkeProperty ( final String key , final String value ) { if ( null == key ) { LOGGER . log ( Level . WARN , "latke.props can not set null key" ) ; return ; } if ( null == value ) { LOGGER . log ( Level . WARN , "latke.props can not set null value" ) ; return ; } latkeProps . setProperty ( key , value ) ; } | Sets latke . props with the specified key and value . |
24,853 | private static void loadLocalProps ( ) { if ( null == localProps ) { localProps = new Properties ( ) ; } try { InputStream resourceAsStream ; final String localPropsEnv = System . getenv ( "LATKE_LOCAL_PROPS" ) ; if ( StringUtils . isNotBlank ( localPropsEnv ) ) { LOGGER . debug ( "Loading local.properties from env var [$LATKE_LOCAL_PROPS=" + localPropsEnv + "]" ) ; resourceAsStream = new FileInputStream ( localPropsEnv ) ; } else { LOGGER . debug ( "Loading local.properties from classpath [/local.properties]" ) ; resourceAsStream = Latkes . class . getResourceAsStream ( "/local.properties" ) ; } if ( null != resourceAsStream ) { localProps . load ( resourceAsStream ) ; LOGGER . debug ( "Loaded local.properties" ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . DEBUG , "Loads local.properties failed, ignored" ) ; } } | Loads the local . props . |
24,854 | private static void loadLatkeProps ( ) { if ( null == latkeProps ) { latkeProps = new Properties ( ) ; } try { InputStream resourceAsStream ; final String latkePropsEnv = System . getenv ( "LATKE_PROPS" ) ; if ( StringUtils . isNotBlank ( latkePropsEnv ) ) { LOGGER . debug ( "Loading latke.properties from env var [$LATKE_PROPS=" + latkePropsEnv + "]" ) ; resourceAsStream = new FileInputStream ( latkePropsEnv ) ; } else { LOGGER . debug ( "Loading latke.properties from classpath [/latke.properties]" ) ; resourceAsStream = Latkes . class . getResourceAsStream ( "/latke.properties" ) ; } if ( null != resourceAsStream ) { latkeProps . load ( resourceAsStream ) ; LOGGER . debug ( "Loaded latke.properties" ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Loads latke.properties failed" , e ) ; throw new RuntimeException ( "Loads latke.properties failed" ) ; } } | Loads the latke . props . |
24,855 | public static String getServerScheme ( ) { String ret = getLatkeProperty ( "serverScheme" ) ; if ( null == ret ) { final RequestContext requestContext = REQUEST_CONTEXT . get ( ) ; if ( null != requestContext ) { ret = requestContext . getRequest ( ) . getScheme ( ) ; } else { ret = "http" ; } } return ret ; } | Gets server scheme . |
24,856 | public static String getServerHost ( ) { String ret = getLatkeProperty ( "serverHost" ) ; if ( null == ret ) { final RequestContext requestContext = REQUEST_CONTEXT . get ( ) ; if ( null != requestContext ) { ret = requestContext . getRequest ( ) . getServerName ( ) ; } else { initPublicIP ( ) ; return PUBLIC_IP ; } } return ret ; } | Gets server host . |
24,857 | public synchronized static void initPublicIP ( ) { if ( StringUtils . isNotBlank ( PUBLIC_IP ) ) { return ; } try { final URL url = new URL ( "http://checkip.amazonaws.com" ) ; final HttpURLConnection urlConnection = ( HttpURLConnection ) url . openConnection ( ) ; urlConnection . setConnectTimeout ( 3000 ) ; urlConnection . setReadTimeout ( 3000 ) ; try ( final BufferedReader in = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) ) ) ) { PUBLIC_IP = in . readLine ( ) ; } urlConnection . disconnect ( ) ; return ; } catch ( final Exception e ) { try { PUBLIC_IP = InetAddress . getLocalHost ( ) . getHostAddress ( ) ; return ; } catch ( final Exception e2 ) { } } PUBLIC_IP = "127.0.0.1" ; } | Init public IP . |
24,858 | public static String getServerPort ( ) { String ret = getLatkeProperty ( "serverPort" ) ; if ( null == ret ) { final RequestContext requestContext = REQUEST_CONTEXT . get ( ) ; if ( null != requestContext ) { ret = requestContext . getRequest ( ) . getServerPort ( ) + "" ; } } return ret ; } | Gets server port . |
24,859 | public static String getServer ( ) { final StringBuilder serverBuilder = new StringBuilder ( getServerScheme ( ) ) . append ( "://" ) . append ( getServerHost ( ) ) ; final String port = getServerPort ( ) ; if ( StringUtils . isNotBlank ( port ) && ! "80" . equals ( port ) && ! "443" . equals ( port ) ) { serverBuilder . append ( ':' ) . append ( port ) ; } return serverBuilder . toString ( ) ; } | Gets server . |
24,860 | public static String getStaticServer ( ) { final StringBuilder staticServerBuilder = new StringBuilder ( getStaticServerScheme ( ) ) . append ( "://" ) . append ( getStaticServerHost ( ) ) ; final String port = getStaticServerPort ( ) ; if ( StringUtils . isNotBlank ( port ) && ! "80" . equals ( port ) && ! "443" . equals ( port ) ) { staticServerBuilder . append ( ':' ) . append ( port ) ; } return staticServerBuilder . toString ( ) ; } | Gets static server . |
24,861 | public static String getContextPath ( ) { if ( null != contextPath ) { return contextPath ; } final String contextPathConf = getLatkeProperty ( "contextPath" ) ; if ( null != contextPathConf ) { contextPath = contextPathConf ; return contextPath ; } final ServletContext servletContext = AbstractServletListener . getServletContext ( ) ; contextPath = servletContext . getContextPath ( ) ; return contextPath ; } | Gets context path . |
24,862 | public static String getStaticPath ( ) { if ( null == staticPath ) { staticPath = getLatkeProperty ( "staticPath" ) ; if ( null == staticPath ) { staticPath = getContextPath ( ) ; } } return staticPath ; } | Gets static path . |
24,863 | public static synchronized void init ( ) { if ( inited ) { return ; } inited = true ; LOGGER . log ( Level . TRACE , "Initializing Latke" ) ; loadLatkeProps ( ) ; loadLocalProps ( ) ; if ( null == runtimeMode ) { final String runtimeModeValue = getLatkeProperty ( "runtimeMode" ) ; if ( null != runtimeModeValue ) { runtimeMode = RuntimeMode . valueOf ( runtimeModeValue ) ; } else { LOGGER . log ( Level . TRACE , "Can't parse runtime mode in latke.properties, default to [PRODUCTION]" ) ; runtimeMode = RuntimeMode . PRODUCTION ; } } if ( Latkes . RuntimeMode . DEVELOPMENT == getRuntimeMode ( ) ) { LOGGER . warn ( "!!!!Runtime mode is [" + Latkes . RuntimeMode . DEVELOPMENT + "], please make sure configured it with [" + Latkes . RuntimeMode . PRODUCTION + "] in latke.properties if deployed on production environment!!!!" ) ; } else { LOGGER . log ( Level . DEBUG , "Runtime mode is [{0}]" , getRuntimeMode ( ) ) ; } final RuntimeDatabase runtimeDatabase = getRuntimeDatabase ( ) ; LOGGER . log ( Level . DEBUG , "Runtime database is [{0}]" , runtimeDatabase ) ; if ( RuntimeDatabase . H2 == runtimeDatabase ) { final String newTCPServer = getLocalProperty ( "newTCPServer" ) ; if ( "true" . equals ( newTCPServer ) ) { LOGGER . log ( Level . DEBUG , "Starting H2 TCP server" ) ; final String jdbcURL = getLocalProperty ( "jdbc.URL" ) ; if ( StringUtils . isBlank ( jdbcURL ) ) { throw new IllegalStateException ( "The jdbc.URL in local.properties is required" ) ; } final String [ ] parts = jdbcURL . split ( ":" ) ; if ( 5 != parts . length ) { throw new IllegalStateException ( "jdbc.URL should like [jdbc:h2:tcp://localhost:8250/~/] (the port part is required)" ) ; } String port = parts [ parts . length - 1 ] ; port = StringUtils . substringBefore ( port , "/" ) ; LOGGER . log ( Level . TRACE , "H2 TCP port [{0}]" , port ) ; try { h2 = org . h2 . tools . Server . createTcpServer ( new String [ ] { "-tcpPort" , port , "-tcpAllowOthers" } ) . start ( ) ; } catch ( final SQLException e ) { final String msg = "H2 TCP server create failed" ; LOGGER . log ( Level . ERROR , msg , e ) ; throw new IllegalStateException ( msg ) ; } LOGGER . log ( Level . DEBUG , "Started H2 TCP server" ) ; } } final RuntimeCache runtimeCache = getRuntimeCache ( ) ; LOGGER . log ( Level . INFO , "Runtime cache is [{0}]" , runtimeCache ) ; locale = new Locale ( "en_US" ) ; LOGGER . log ( Level . INFO , "Initialized Latke" ) ; } | Initializes Latke framework . |
24,864 | public static RuntimeCache getRuntimeCache ( ) { final String runtimeCache = getLocalProperty ( "runtimeCache" ) ; if ( null == runtimeCache ) { LOGGER . debug ( "Not found [runtimeCache] in local.properties, uses [LOCAL_LRU] as default" ) ; return RuntimeCache . LOCAL_LRU ; } return RuntimeCache . valueOf ( runtimeCache ) ; } | Gets the runtime cache . |
24,865 | public static RuntimeDatabase getRuntimeDatabase ( ) { final String runtimeDatabase = getLocalProperty ( "runtimeDatabase" ) ; if ( null == runtimeDatabase ) { throw new RuntimeException ( "Please configures runtime database in local.properties!" ) ; } final RuntimeDatabase ret = RuntimeDatabase . valueOf ( runtimeDatabase ) ; if ( null == ret ) { throw new RuntimeException ( "Please configures a valid runtime database in local.properties!" ) ; } return ret ; } | Gets the runtime database . |
24,866 | public static String getLocalProperty ( final String key ) { String ret = localProps . getProperty ( key ) ; if ( StringUtils . isBlank ( ret ) ) { return ret ; } ret = replaceEnvVars ( ret ) ; return ret ; } | Gets a property specified by the given key from file local . properties . |
24,867 | public static String getLatkeProperty ( final String key ) { String ret = latkeProps . getProperty ( key ) ; if ( StringUtils . isBlank ( ret ) ) { return ret ; } ret = replaceEnvVars ( ret ) ; return ret ; } | Gets a property specified by the given key from file latke . properties . |
24,868 | public static void shutdown ( ) { try { EXECUTOR_SERVICE . shutdown ( ) ; if ( RuntimeCache . REDIS == getRuntimeCache ( ) ) { RedisCache . shutdown ( ) ; } Connections . shutdownConnectionPool ( ) ; if ( RuntimeDatabase . H2 == getRuntimeDatabase ( ) ) { final String newTCPServer = getLocalProperty ( "newTCPServer" ) ; if ( "true" . equals ( newTCPServer ) ) { h2 . stop ( ) ; h2 . shutdown ( ) ; LOGGER . log ( Level . INFO , "Closed H2 TCP server" ) ; } } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Shutdowns Latke failed" , e ) ; } BeanManager . close ( ) ; final Enumeration < Driver > drivers = DriverManager . getDrivers ( ) ; while ( drivers . hasMoreElements ( ) ) { final Driver driver = drivers . nextElement ( ) ; try { DriverManager . deregisterDriver ( driver ) ; LOGGER . log ( Level . TRACE , "Unregistered JDBC driver [" + driver + "]" ) ; } catch ( final SQLException e ) { LOGGER . log ( Level . ERROR , "Unregister JDBC driver [" + driver + "] failed" , e ) ; } } } | Shutdowns Latke . |
24,869 | public static File getWebFile ( final String path ) { final ServletContext servletContext = AbstractServletListener . getServletContext ( ) ; File ret ; try { final URL resource = servletContext . getResource ( path ) ; if ( null == resource ) { return null ; } ret = FileUtils . toFile ( resource ) ; if ( null == ret ) { final File tempdir = ( File ) servletContext . getAttribute ( "javax.servlet.context.tempdir" ) ; ret = new File ( tempdir . getPath ( ) + path ) ; FileUtils . copyURLToFile ( resource , ret ) ; ret . deleteOnExit ( ) ; } return ret ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Reads file [path=" + path + "] failed" , e ) ; return null ; } } | Gets a file in web application with the specified path . |
24,870 | synchronized void fireEvent ( final Event < ? > event ) { final String eventType = event . getType ( ) ; List < Event < ? > > events = synchronizedEvents . get ( eventType ) ; if ( null == events ) { events = new ArrayList < > ( ) ; synchronizedEvents . put ( eventType , events ) ; } events . add ( event ) ; setChanged ( ) ; notifyListeners ( event ) ; } | Fires the specified event . |
24,871 | public < E extends Enum < E > > E getEnum ( Class < E > clazz , int index ) throws JSONException { E val = optEnum ( clazz , index ) ; if ( val == null ) { throw new JSONException ( "JSONArray[" + index + "] is not an enum of type " + JSONObject . quote ( clazz . getSimpleName ( ) ) + "." ) ; } return val ; } | Get the enum value associated with an index . |
24,872 | public float optFloat ( int index , float defaultValue ) { final Number val = this . optNumber ( index , null ) ; if ( val == null ) { return defaultValue ; } final float floatValue = val . floatValue ( ) ; return floatValue ; } | Get the optional float value associated with an index . The defaultValue is returned if there is no value for the index or if the value is not a number and cannot be converted to a number . |
24,873 | public int optInt ( int index , int defaultValue ) { final Number val = this . optNumber ( index , null ) ; if ( val == null ) { return defaultValue ; } return val . intValue ( ) ; } | Get the optional int value associated with an index . The defaultValue is returned if there is no value for the index or if the value is not a number and cannot be converted to a number . |
24,874 | public JSONArray optJSONArray ( int index ) { Object o = this . opt ( index ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } | Get the optional JSONArray associated with an index . |
24,875 | public JSONObject optJSONObject ( int index ) { Object o = this . opt ( index ) ; return o instanceof JSONObject ? ( JSONObject ) o : null ; } | Get the optional JSONObject associated with an index . Null is returned if the key is not found or null if the index has no value or if the value is not a JSONObject . |
24,876 | public long optLong ( int index , long defaultValue ) { final Number val = this . optNumber ( index , null ) ; if ( val == null ) { return defaultValue ; } return val . longValue ( ) ; } | Get the optional long value associated with an index . The defaultValue is returned if there is no value for the index or if the value is not a number and cannot be converted to a number . |
24,877 | public String optString ( int index , String defaultValue ) { Object object = this . opt ( index ) ; return JSONObject . NULL . equals ( object ) ? defaultValue : object . toString ( ) ; } | Get the optional string associated with an index . The defaultValue is returned if the key is not found . |
24,878 | public JSONArray put ( int index , float value ) throws JSONException { return this . put ( index , Float . valueOf ( value ) ) ; } | Put or replace a float value . If the index is greater than the length of the JSONArray then null elements will be added as necessary to pad it out . |
24,879 | public Writer write ( Writer writer , int indentFactor , int indent ) throws JSONException { try { boolean commanate = false ; int length = this . length ( ) ; writer . write ( '[' ) ; if ( length == 1 ) { try { JSONObject . writeValue ( writer , this . myArrayList . get ( 0 ) , indentFactor , indent ) ; } catch ( Exception e ) { throw new JSONException ( "Unable to write JSONArray value at index: 0" , e ) ; } } else if ( length != 0 ) { final int newindent = indent + indentFactor ; for ( int i = 0 ; i < length ; i += 1 ) { if ( commanate ) { writer . write ( ',' ) ; } if ( indentFactor > 0 ) { writer . write ( '\n' ) ; } JSONObject . indent ( writer , newindent ) ; try { JSONObject . writeValue ( writer , this . myArrayList . get ( i ) , indentFactor , newindent ) ; } catch ( Exception e ) { throw new JSONException ( "Unable to write JSONArray value at index: " + i , e ) ; } commanate = true ; } if ( indentFactor > 0 ) { writer . write ( '\n' ) ; } JSONObject . indent ( writer , indent ) ; } writer . write ( ']' ) ; return writer ; } catch ( IOException e ) { throw new JSONException ( e ) ; } } | Write the contents of the JSONArray as JSON text to a writer . |
24,880 | public static void shutdown ( ) { try { Connections . shutdown ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Shutdown redis connection pool failed" , e ) ; } } | Shutdowns redis cache . |
24,881 | public static Set < Class < ? extends Annotation > > getStereotypes ( final Class < ? > clazz ) { final Set < Class < ? extends Annotation > > ret = new HashSet < > ( ) ; final Set < Annotation > annotations = getAnnotations ( clazz . getAnnotations ( ) , Stereotype . class ) ; if ( annotations . isEmpty ( ) ) { return ret ; } for ( final Annotation annotation : annotations ) { ret . add ( annotation . annotationType ( ) ) ; } return ret ; } | Gets stereo types of the specified class . |
24,882 | private static Set < Annotation > getAnnotations ( final Annotation [ ] annotations , final Class < ? extends Annotation > neededAnnotationType ) { final Set < Annotation > ret = new HashSet < > ( ) ; for ( final Annotation annotation : annotations ) { annotation . annotationType ( ) . getAnnotations ( ) ; final Annotation [ ] metaAnnotations = annotation . annotationType ( ) . getAnnotations ( ) ; for ( final Annotation metaAnnotation : metaAnnotations ) { if ( metaAnnotation . annotationType ( ) . equals ( neededAnnotationType ) ) { ret . add ( annotation ) ; } } } return ret ; } | Gets annotations match the needed annotation type from the specified annotation . |
24,883 | public static String [ ] getMethodVariableNames ( final Class < ? > clazz , final String targetMethodName , final Class < ? > [ ] types ) { CtClass cc ; CtMethod cm = null ; try { if ( null == CLASS_POOL . find ( clazz . getName ( ) ) ) { CLASS_POOL . insertClassPath ( new ClassClassPath ( clazz ) ) ; } cc = CLASS_POOL . get ( clazz . getName ( ) ) ; final CtClass [ ] ptypes = new CtClass [ types . length ] ; for ( int i = 0 ; i < ptypes . length ; i ++ ) { ptypes [ i ] = CLASS_POOL . get ( types [ i ] . getName ( ) ) ; } cm = cc . getDeclaredMethod ( targetMethodName , ptypes ) ; } catch ( final NotFoundException e ) { LOGGER . log ( Level . ERROR , "Get method variable names failed" , e ) ; } if ( null == cm ) { return new String [ types . length ] ; } final MethodInfo methodInfo = cm . getMethodInfo ( ) ; final CodeAttribute codeAttribute = methodInfo . getCodeAttribute ( ) ; final LocalVariableAttribute attr = ( LocalVariableAttribute ) codeAttribute . getAttribute ( LocalVariableAttribute . tag ) ; String [ ] variableNames = new String [ 0 ] ; try { variableNames = new String [ cm . getParameterTypes ( ) . length ] ; } catch ( final NotFoundException e ) { LOGGER . log ( Level . ERROR , "Get method variable names failed" , e ) ; } int j = - 1 ; String variableName = null ; Boolean ifkill = false ; while ( ! "this" . equals ( variableName ) ) { j ++ ; variableName = attr . variableName ( j ) ; if ( j > 99 ) { LOGGER . log ( Level . WARN , "Maybe resolve to VariableNames error [class=" + clazz . getName ( ) + ", targetMethodName=" + targetMethodName + ']' ) ; ifkill = true ; break ; } } if ( ! ifkill ) { for ( int i = 0 ; i < variableNames . length ; i ++ ) { variableNames [ i ] = attr . variableName ( ++ j ) ; } } return variableNames ; } | Get method variable names of the specified class target method name and parameter types . |
24,884 | public JSONObject accumulate ( String key , Object value ) throws JSONException { testValidity ( value ) ; Object object = this . opt ( key ) ; if ( object == null ) { this . put ( key , value instanceof JSONArray ? new JSONArray ( ) . put ( value ) : value ) ; } else if ( object instanceof JSONArray ) { ( ( JSONArray ) object ) . put ( value ) ; } else { this . put ( key , new JSONArray ( ) . put ( object ) . put ( value ) ) ; } return this ; } | Accumulate values under a key . It is similar to the put method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values . If there is already a JSONArray then the new value is appended to it . In contrast the put method replaces the previous value . |
24,885 | public boolean getBoolean ( String key ) throws JSONException { Object object = this . get ( key ) ; if ( object . equals ( Boolean . FALSE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "false" ) ) ) { return false ; } else if ( object . equals ( Boolean . TRUE ) || ( object instanceof String && ( ( String ) object ) . equalsIgnoreCase ( "true" ) ) ) { return true ; } throw new JSONException ( "JSONObject[" + quote ( key ) + "] is not a Boolean." ) ; } | Get the boolean value associated with a key . |
24,886 | public JSONArray optJSONArray ( String key ) { Object o = this . opt ( key ) ; return o instanceof JSONArray ? ( JSONArray ) o : null ; } | Get an optional JSONArray associated with a key . It returns null if there is no such key or if its value is not a JSONArray . |
24,887 | private void populateMap ( Object bean ) { Class < ? > klass = bean . getClass ( ) ; boolean includeSuperClass = klass . getClassLoader ( ) != null ; Method [ ] methods = includeSuperClass ? klass . getMethods ( ) : klass . getDeclaredMethods ( ) ; for ( final Method method : methods ) { final int modifiers = method . getModifiers ( ) ; if ( Modifier . isPublic ( modifiers ) && ! Modifier . isStatic ( modifiers ) && method . getParameterTypes ( ) . length == 0 && ! method . isBridge ( ) && method . getReturnType ( ) != Void . TYPE && isValidMethodName ( method . getName ( ) ) ) { final String key = getKeyNameFromMethod ( method ) ; if ( key != null && ! key . isEmpty ( ) ) { try { final Object result = method . invoke ( bean ) ; if ( result != null ) { this . map . put ( key , wrap ( result ) ) ; if ( result instanceof Closeable ) { try { ( ( Closeable ) result ) . close ( ) ; } catch ( IOException ignore ) { } } } } catch ( IllegalAccessException ignore ) { } catch ( IllegalArgumentException ignore ) { } catch ( InvocationTargetException ignore ) { } } } } } | Populates the internal map of the JSONObject with the bean properties . The bean can not be recursive . |
24,888 | private static < A extends Annotation > A getAnnotation ( final Method m , final Class < A > annotationClass ) { if ( m == null || annotationClass == null ) { return null ; } if ( m . isAnnotationPresent ( annotationClass ) ) { return m . getAnnotation ( annotationClass ) ; } Class < ? > c = m . getDeclaringClass ( ) ; if ( c . getSuperclass ( ) == null ) { return null ; } for ( Class < ? > i : c . getInterfaces ( ) ) { try { Method im = i . getMethod ( m . getName ( ) , m . getParameterTypes ( ) ) ; return getAnnotation ( im , annotationClass ) ; } catch ( final SecurityException ex ) { continue ; } catch ( final NoSuchMethodException ex ) { continue ; } } try { return getAnnotation ( c . getSuperclass ( ) . getMethod ( m . getName ( ) , m . getParameterTypes ( ) ) , annotationClass ) ; } catch ( final SecurityException ex ) { return null ; } catch ( final NoSuchMethodException ex ) { return null ; } } | Searches the class hierarchy to see if the method or it s super implementations and interfaces has the annotation . |
24,889 | private static int getAnnotationDepth ( final Method m , final Class < ? extends Annotation > annotationClass ) { if ( m == null || annotationClass == null ) { return - 1 ; } if ( m . isAnnotationPresent ( annotationClass ) ) { return 1 ; } Class < ? > c = m . getDeclaringClass ( ) ; if ( c . getSuperclass ( ) == null ) { return - 1 ; } for ( Class < ? > i : c . getInterfaces ( ) ) { try { Method im = i . getMethod ( m . getName ( ) , m . getParameterTypes ( ) ) ; int d = getAnnotationDepth ( im , annotationClass ) ; if ( d > 0 ) { return d + 1 ; } } catch ( final SecurityException ex ) { continue ; } catch ( final NoSuchMethodException ex ) { continue ; } } try { int d = getAnnotationDepth ( c . getSuperclass ( ) . getMethod ( m . getName ( ) , m . getParameterTypes ( ) ) , annotationClass ) ; if ( d > 0 ) { return d + 1 ; } return - 1 ; } catch ( final SecurityException ex ) { return - 1 ; } catch ( final NoSuchMethodException ex ) { return - 1 ; } } | Searches the class hierarchy to see if the method or it s super implementations and interfaces has the annotation . Returns the depth of the annotation in the hierarchy . |
24,890 | protected static boolean isDecimalNotation ( final String val ) { return val . indexOf ( '.' ) > - 1 || val . indexOf ( 'e' ) > - 1 || val . indexOf ( 'E' ) > - 1 || "-0" . equals ( val ) ; } | Tests if the value should be tried as a decimal . It makes no test if there are actual digits . |
24,891 | protected static Number stringToNumber ( final String val ) throws NumberFormatException { char initial = val . charAt ( 0 ) ; if ( ( initial >= '0' && initial <= '9' ) || initial == '-' ) { if ( isDecimalNotation ( val ) ) { if ( val . length ( ) > 14 ) { return new BigDecimal ( val ) ; } final Double d = Double . valueOf ( val ) ; if ( d . isInfinite ( ) || d . isNaN ( ) ) { return new BigDecimal ( val ) ; } return d ; } BigInteger bi = new BigInteger ( val ) ; if ( bi . bitLength ( ) <= 31 ) { return Integer . valueOf ( bi . intValue ( ) ) ; } if ( bi . bitLength ( ) <= 63 ) { return Long . valueOf ( bi . longValue ( ) ) ; } return bi ; } throw new NumberFormatException ( "val [" + val + "] is not a valid number." ) ; } | Converts a string to a number using the narrowest possible type . Possible returns for this function are BigDecimal Double BigInteger Long and Integer . When a Double is returned it should always be a valid Double and not NaN or + - infinity . |
24,892 | public Writer write ( Writer writer , int indentFactor , int indent ) throws JSONException { try { boolean commanate = false ; final int length = this . length ( ) ; writer . write ( '{' ) ; if ( length == 1 ) { final Entry < String , ? > entry = this . entrySet ( ) . iterator ( ) . next ( ) ; final String key = entry . getKey ( ) ; writer . write ( quote ( key ) ) ; writer . write ( ':' ) ; if ( indentFactor > 0 ) { writer . write ( ' ' ) ; } try { writeValue ( writer , entry . getValue ( ) , indentFactor , indent ) ; } catch ( Exception e ) { throw new JSONException ( "Unable to write JSONObject value for key: " + key , e ) ; } } else if ( length != 0 ) { final int newindent = indent + indentFactor ; for ( final Entry < String , ? > entry : this . entrySet ( ) ) { if ( commanate ) { writer . write ( ',' ) ; } if ( indentFactor > 0 ) { writer . write ( '\n' ) ; } indent ( writer , newindent ) ; final String key = entry . getKey ( ) ; writer . write ( quote ( key ) ) ; writer . write ( ':' ) ; if ( indentFactor > 0 ) { writer . write ( ' ' ) ; } try { writeValue ( writer , entry . getValue ( ) , indentFactor , newindent ) ; } catch ( Exception e ) { throw new JSONException ( "Unable to write JSONObject value for key: " + key , e ) ; } commanate = true ; } if ( indentFactor > 0 ) { writer . write ( '\n' ) ; } indent ( writer , indent ) ; } writer . write ( '}' ) ; return writer ; } catch ( IOException exception ) { throw new JSONException ( exception ) ; } } | Write the contents of the JSONObject as JSON text to a writer . |
24,893 | public static boolean hasExpression ( final Template template , final String expression ) { final TemplateElement rootTreeNode = template . getRootTreeNode ( ) ; return hasExpression ( template , expression , rootTreeNode ) ; } | Determines whether exists a variable specified by the given expression in the specified template . |
24,894 | public static String exec ( final String cmd , final long timeout ) { final StringTokenizer st = new StringTokenizer ( cmd ) ; final String [ ] cmds = new String [ st . countTokens ( ) ] ; for ( int i = 0 ; st . hasMoreTokens ( ) ; i ++ ) { cmds [ i ] = st . nextToken ( ) ; } return exec ( cmds , timeout ) ; } | Executes the specified command with the specified timeout . |
24,895 | public static String exec ( final String [ ] cmds , final long timeout ) { try { final Process process = new ProcessBuilder ( cmds ) . redirectErrorStream ( true ) . start ( ) ; final StringWriter writer = new StringWriter ( ) ; new Thread ( ( ) -> { try { IOUtils . copy ( process . getInputStream ( ) , writer , "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Reads input stream failed: " + e . getMessage ( ) ) ; } } ) . start ( ) ; if ( ! process . waitFor ( timeout , TimeUnit . MILLISECONDS ) ) { LOGGER . log ( Level . WARN , "Executes commands [" + Arrays . toString ( cmds ) + "] timeout" ) ; process . destroy ( ) ; } return writer . toString ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Executes commands [" + Arrays . toString ( cmds ) + "] failed" , e ) ; return null ; } } | Executes the specified commands with the specified timeout . |
24,896 | public static synchronized Cache getCache ( final String cacheName ) { LOGGER . log ( Level . INFO , "Constructing cache [name={0}]...." , cacheName ) ; Cache ret = CACHES . get ( cacheName ) ; try { if ( null == ret ) { Class < Cache > cacheClass ; switch ( Latkes . getRuntimeCache ( ) ) { case LOCAL_LRU : cacheClass = ( Class < Cache > ) Class . forName ( "org.b3log.latke.cache.caffeine.CaffeineCache" ) ; break ; case REDIS : cacheClass = ( Class < Cache > ) Class . forName ( "org.b3log.latke.cache.redis.RedisCache" ) ; break ; case NONE : cacheClass = ( Class < Cache > ) Class . forName ( "org.b3log.latke.cache.NoneCache" ) ; break ; default : throw new RuntimeException ( "Latke runs in the hell.... Please set the environment correctly" ) ; } ret = cacheClass . newInstance ( ) ; ret . setName ( cacheName ) ; CACHES . put ( cacheName , ret ) ; } } catch ( final Exception e ) { throw new RuntimeException ( "Can not get cache: " + e . getMessage ( ) , e ) ; } LOGGER . log ( Level . INFO , "Constructed cache [name={0}, runtime={1}]" , cacheName , Latkes . getRuntimeCache ( ) ) ; return ret ; } | Gets a cache specified by the given cache name . |
24,897 | public static synchronized void clear ( ) { for ( final Map . Entry < String , Cache > entry : CACHES . entrySet ( ) ) { final Cache cache = entry . getValue ( ) ; cache . clear ( ) ; LOGGER . log ( Level . TRACE , "Cleared cache [name={0}]" , entry . getKey ( ) ) ; } } | Clears all caches . |
24,898 | public Map < String , Object > getDataModel ( ) { final AbstractResponseRenderer renderer = getRenderer ( ) ; if ( null == renderer ) { return null ; } return renderer . getRenderDataModel ( ) ; } | Gets the data model of renderer bound with this context . |
24,899 | public void sendRedirect ( final String location ) { try { response . sendRedirect ( location ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Sends redirect [" + location + "] failed: " + e . getMessage ( ) ) ; } } | Sends redirect to the specified location . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.