idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
24,800 | 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 . | 98 | 6 |
24,801 | 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 . | 67 | 6 |
24,802 | 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 . | 66 | 6 |
24,803 | 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 . | 85 | 13 |
24,804 | 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 . | 70 | 8 |
24,805 | 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 . | 348 | 6 |
24,806 | 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 . | 163 | 9 |
24,807 | 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 . | 243 | 11 |
24,808 | 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 . | 98 | 12 |
24,809 | 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 . | 267 | 15 |
24,810 | 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 . | 682 | 8 |
24,811 | 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 . | 103 | 13 |
24,812 | 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 . | 93 | 12 |
24,813 | 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 . | 97 | 13 |
24,814 | 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 . | 245 | 7 |
24,815 | 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 . | 269 | 8 |
24,816 | 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 . | 87 | 5 |
24,817 | 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 . | 90 | 5 |
24,818 | 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 . | 202 | 4 |
24,819 | 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 . | 78 | 5 |
24,820 | 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 . | 112 | 4 |
24,821 | 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 . | 119 | 5 |
24,822 | 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 . | 98 | 5 |
24,823 | public static String getStaticPath ( ) { if ( null == staticPath ) { staticPath = getLatkeProperty ( "staticPath" ) ; if ( null == staticPath ) { staticPath = getContextPath ( ) ; } } return staticPath ; } | Gets static path . | 55 | 5 |
24,824 | 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 . | 715 | 6 |
24,825 | 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 . | 86 | 6 |
24,826 | 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 . | 99 | 6 |
24,827 | 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 . | 58 | 15 |
24,828 | 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 . | 60 | 16 |
24,829 | 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 ( ) ; // Manually unregister JDBC driver, which prevents Tomcat from complaining about memory leaks 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 . | 310 | 5 |
24,830 | 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 . | 193 | 12 |
24,831 | 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 . | 94 | 6 |
24,832 | public < E extends Enum < E > > E getEnum ( Class < E > clazz , int index ) throws JSONException { E val = optEnum ( clazz , index ) ; if ( val == null ) { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException 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 . | 136 | 9 |
24,833 | public float optFloat ( int index , float defaultValue ) { final Number val = this . optNumber ( index , null ) ; if ( val == null ) { return defaultValue ; } final float floatValue = val . floatValue ( ) ; // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { // return 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 . | 86 | 39 |
24,834 | 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 . | 48 | 39 |
24,835 | 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 . | 37 | 10 |
24,836 | 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 . | 37 | 37 |
24,837 | 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 . | 48 | 39 |
24,838 | 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 . | 45 | 21 |
24,839 | 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 . | 32 | 32 |
24,840 | 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 ( ' ' ) ; } 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 ( ' ' ) ; } 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 . | 313 | 14 |
24,841 | public static void shutdown ( ) { try { Connections . shutdown ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Shutdown redis connection pool failed" , e ) ; } } | Shutdowns redis cache . | 48 | 6 |
24,842 | 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 . | 116 | 9 |
24,843 | 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 . | 141 | 13 |
24,844 | 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 ) ; } // final int staticIndex = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; int j = - 1 ; String variableName = null ; Boolean ifkill = false ; while ( ! "this" . equals ( variableName ) ) { j ++ ; variableName = attr . variableName ( j ) ; // to prevent heap error when there being some unknown reasons to resolve the VariableNames 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 . | 538 | 15 |
24,845 | 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 . | 120 | 71 |
24,846 | 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 . | 129 | 9 |
24,847 | 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 . | 37 | 29 |
24,848 | private void populateMap ( Object bean ) { Class < ? > klass = bean . getClass ( ) ; // If klass is a System class then set includeSuperClass to false. 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 ) ) ; // we don't use the result anywhere outside of wrap // if it's a resource we should be sure to close it // after calling toString 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 . | 329 | 21 |
24,849 | private static < A extends Annotation > A getAnnotation ( final Method m , final Class < A > annotationClass ) { // if we have invalid data the result is null if ( m == null || annotationClass == null ) { return null ; } if ( m . isAnnotationPresent ( annotationClass ) ) { return m . getAnnotation ( annotationClass ) ; } // if we've already reached the Object class, return null; Class < ? > c = m . getDeclaringClass ( ) ; if ( c . getSuperclass ( ) == null ) { return null ; } // check directly implemented interfaces for the method being checked 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 . | 279 | 22 |
24,850 | private static int getAnnotationDepth ( final Method m , final Class < ? extends Annotation > annotationClass ) { // if we have invalid data the result is -1 if ( m == null || annotationClass == null ) { return - 1 ; } if ( m . isAnnotationPresent ( annotationClass ) ) { return 1 ; } // if we've already reached the Object class, return -1; Class < ? > c = m . getDeclaringClass ( ) ; if ( c . getSuperclass ( ) == null ) { return - 1 ; } // check directly implemented interfaces for the method being checked for ( Class < ? > i : c . getInterfaces ( ) ) { try { Method im = i . getMethod ( m . getName ( ) , m . getParameterTypes ( ) ) ; int d = getAnnotationDepth ( im , annotationClass ) ; if ( d > 0 ) { // since the annotation was on the interface, add 1 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 ) { // since the annotation was on the superclass, add 1 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 . | 334 | 32 |
24,851 | protected static boolean isDecimalNotation ( final String val ) { return val . indexOf ( ' ' ) > - 1 || val . indexOf ( ' ' ) > - 1 || val . indexOf ( ' ' ) > - 1 || "-0" . equals ( val ) ; } | Tests if the value should be tried as a decimal . It makes no test if there are actual digits . | 61 | 22 |
24,852 | protected static Number stringToNumber ( final String val ) throws NumberFormatException { char initial = val . charAt ( 0 ) ; if ( ( initial >= ' ' && initial <= ' ' ) || initial == ' ' ) { // decimal representation if ( isDecimalNotation ( val ) ) { // quick dirty way to see if we need a BigDecimal instead of a Double // this only handles some cases of overflow or underflow if ( val . length ( ) > 14 ) { return new BigDecimal ( val ) ; } final Double d = Double . valueOf ( val ) ; if ( d . isInfinite ( ) || d . isNaN ( ) ) { // if we can't parse it as a double, go up to BigDecimal // this is probably due to underflow like 4.32e-678 // or overflow like 4.65e5324. The size of the string is small // but can't be held in a Double. return new BigDecimal ( val ) ; } return d ; } // integer representation. // This will narrow any values to the smallest reasonable Object representation // (Integer, Long, or BigInteger) // string version // The compare string length method reduces GC, // but leads to smaller integers being placed in larger wrappers even though not // needed. i.e. 1,000,000,000 -> Long even though it's an Integer // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long //if(val.length()<=9){ // return Integer.valueOf(val); //} //if(val.length()<=18){ // return Long.valueOf(val); //} //return new BigInteger(val); // BigInteger version: We use a similar bitLenth compare as // BigInteger#intValueExact uses. Increases GC, but objects hold // only what they need. i.e. Less runtime overhead if the value is // long lived. Which is the better tradeoff? This is closer to what's // in stringToValue. 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 . | 528 | 51 |
24,853 | 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 ( ' ' ) ; } 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 ( ' ' ) ; } 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 . | 414 | 14 |
24,854 | 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 . | 47 | 17 |
24,855 | 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 . | 89 | 10 |
24,856 | 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 . | 241 | 10 |
24,857 | 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 . | 332 | 11 |
24,858 | 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 . | 79 | 5 |
24,859 | 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 . | 53 | 13 |
24,860 | 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 . | 63 | 8 |
24,861 | public String param ( final String name ) { try { return request . getParameter ( name ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Can't parse request parameter [uri=" + request . getRequestURI ( ) + ", method=" + request . getMethod ( ) + ", parameterName=" + name + "]: " + e . getMessage ( ) ) ; return null ; } } | Gets a parameter specified by the given name from request body form or query string . | 90 | 17 |
24,862 | public void sendError ( final int sc ) { try { response . sendError ( sc ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Sends error status code [" + sc + "] failed: " + e . getMessage ( ) ) ; } } | Sends the specified error status code . | 63 | 8 |
24,863 | public RequestContext renderJSONPretty ( final JSONObject json ) { final JsonRenderer jsonRenderer = new JsonRenderer ( ) ; jsonRenderer . setJSONObject ( json ) ; jsonRenderer . setPretty ( true ) ; this . renderer = jsonRenderer ; return this ; } | Pretty rends with the specified json object . | 70 | 9 |
24,864 | public RequestContext renderJSON ( final JSONObject json ) { final JsonRenderer jsonRenderer = new JsonRenderer ( ) ; jsonRenderer . setJSONObject ( json ) ; this . renderer = jsonRenderer ; return this ; } | Renders with the specified json object . | 58 | 8 |
24,865 | public RequestContext renderPretty ( ) { if ( renderer instanceof JsonRenderer ) { final JsonRenderer r = ( JsonRenderer ) renderer ; r . setPretty ( true ) ; } return this ; } | Pretty renders . | 52 | 3 |
24,866 | public void handle ( ) { try { for ( handleIndex ++ ; handleIndex < handlers . size ( ) ; handleIndex ++ ) { handlers . get ( handleIndex ) . handle ( this ) ; } } catch ( final Exception e ) { final String requestLog = Requests . getLog ( request ) ; LOGGER . log ( Level . ERROR , "Handler process failed: " + requestLog , e ) ; setRenderer ( new Http500Renderer ( e ) ) ; } } | Handles this context with handlers . | 105 | 7 |
24,867 | private static JSONObject parseRequestJSONObject ( final HttpServletRequest request , final HttpServletResponse response ) { response . setContentType ( "application/json" ) ; try { BufferedReader reader ; try { reader = request . getReader ( ) ; } catch ( final IllegalStateException illegalStateException ) { reader = new BufferedReader ( new InputStreamReader ( request . getInputStream ( ) ) ) ; } String tmp = IOUtils . toString ( reader ) ; if ( StringUtils . isBlank ( tmp ) ) { tmp = "{}" ; } else { if ( StringUtils . startsWithIgnoreCase ( tmp , "%7B%22" /* {" */ ) ) { tmp = URLs . decode ( tmp ) ; } } return new JSONObject ( tmp ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Parses request JSON object failed [" + e . getMessage ( ) + "], returns an empty json object" ) ; return new JSONObject ( ) ; } } | Gets the request json object with the specified request . | 226 | 11 |
24,868 | public static int getPage ( final HttpServletRequest request ) { int ret = 1 ; final String p = request . getParameter ( "p" ) ; if ( Strings . isNumeric ( p ) ) { try { ret = Integer . parseInt ( p ) ; } catch ( final Exception e ) { // ignored } } if ( 1 > ret ) { ret = 1 ; } return ret ; } | Gets the current page number from the query string p of the specified request . | 87 | 16 |
24,869 | public static List < Integer > paginate ( final int currentPageNum , final int pageSize , final int pageCount , final int windowSize ) { List < Integer > ret ; if ( pageCount < windowSize ) { ret = new ArrayList <> ( pageCount ) ; for ( int i = 0 ; i < pageCount ; i ++ ) { ret . add ( i , i + 1 ) ; } } else { ret = new ArrayList <> ( windowSize ) ; int first = currentPageNum + 1 - windowSize / 2 ; first = first < 1 ? 1 : first ; first = first + windowSize > pageCount ? pageCount - windowSize + 1 : first ; for ( int i = 0 ; i < windowSize ; i ++ ) { ret . add ( i , first + i ) ; } } return ret ; } | Paginates with the specified current page number page size page count and window size . | 178 | 17 |
24,870 | public List < AbstractPlugin > getPlugins ( ) { if ( pluginCache . isEmpty ( ) ) { LOGGER . info ( "Plugin cache miss, reload" ) ; load ( ) ; } final List < AbstractPlugin > ret = new ArrayList <> ( ) ; for ( final Map . Entry < String , HashSet < AbstractPlugin > > entry : pluginCache . entrySet ( ) ) { ret . addAll ( entry . getValue ( ) ) ; } return ret ; } | Gets all plugins . | 103 | 5 |
24,871 | public Set < AbstractPlugin > getPlugins ( final String viewName ) { if ( pluginCache . isEmpty ( ) ) { LOGGER . info ( "Plugin cache miss, reload" ) ; load ( ) ; } final Set < AbstractPlugin > ret = pluginCache . get ( viewName ) ; if ( null == ret ) { return Collections . emptySet ( ) ; } return ret ; } | Gets a plugin by the specified view name . | 83 | 10 |
24,872 | private void register ( final AbstractPlugin plugin , final Map < String , HashSet < AbstractPlugin > > holder ) { final String rendererId = plugin . getRendererId ( ) ; /* * the rendererId support multiple,using ';' to split. * and using Map to match the plugin is not flexible, a regular expression match pattern may be needed in futrue. */ final String [ ] redererIds = rendererId . split ( ";" ) ; for ( final String rid : redererIds ) { final HashSet < AbstractPlugin > set = holder . computeIfAbsent ( rid , k -> new HashSet <> ( ) ) ; set . add ( plugin ) ; } LOGGER . log ( Level . DEBUG , "Registered plugin[name={0}, version={1}] for rendererId[name={2}], [{3}] plugins totally" , plugin . getName ( ) , plugin . getVersion ( ) , rendererId , holder . size ( ) ) ; } | Registers the specified plugin into the specified holder . | 216 | 10 |
24,873 | private static void setPluginProps ( final String pluginDirName , final AbstractPlugin plugin , final Properties props ) throws Exception { final String author = props . getProperty ( Plugin . PLUGIN_AUTHOR ) ; final String name = props . getProperty ( Plugin . PLUGIN_NAME ) ; final String version = props . getProperty ( Plugin . PLUGIN_VERSION ) ; final String types = props . getProperty ( Plugin . PLUGIN_TYPES ) ; LOGGER . log ( Level . TRACE , "Plugin[name={0}, author={1}, version={2}, types={3}]" , name , author , version , types ) ; plugin . setAuthor ( author ) ; plugin . setName ( name ) ; plugin . setId ( name + "_" + version ) ; plugin . setVersion ( version ) ; plugin . setDir ( pluginDirName ) ; plugin . readLangs ( ) ; // try to find the setting config.json final File settingFile = Latkes . getWebFile ( "/plugins/" + pluginDirName + "/config.json" ) ; if ( null != settingFile && settingFile . exists ( ) ) { try { final String config = FileUtils . readFileToString ( settingFile ) ; final JSONObject jsonObject = new JSONObject ( config ) ; plugin . setSetting ( jsonObject ) ; } catch ( final IOException ie ) { LOGGER . log ( Level . ERROR , "reading the config of the plugin[" + name + "] failed" , ie ) ; } catch ( final JSONException e ) { LOGGER . log ( Level . ERROR , "convert the config of the plugin[" + name + "] to json failed" , e ) ; } } Arrays . stream ( types . split ( "," ) ) . map ( PluginType :: valueOf ) . forEach ( plugin :: addType ) ; } | Sets the specified plugin s properties from the specified properties file under the specified plugin directory . | 401 | 18 |
24,874 | private void registerEventListeners ( final Properties props , final URLClassLoader classLoader , final AbstractPlugin plugin ) throws Exception { final String eventListenerClasses = props . getProperty ( Plugin . PLUGIN_EVENT_LISTENER_CLASSES ) ; final String [ ] eventListenerClassArray = eventListenerClasses . split ( "," ) ; for ( final String eventListenerClassName : eventListenerClassArray ) { if ( StringUtils . isBlank ( eventListenerClassName ) ) { LOGGER . log ( Level . INFO , "No event listener to load for plugin[name={0}]" , plugin . getName ( ) ) ; return ; } LOGGER . log ( Level . DEBUG , "Loading event listener[className={0}]" , eventListenerClassName ) ; final Class < ? > eventListenerClass = classLoader . loadClass ( eventListenerClassName ) ; final AbstractEventListener < ? > eventListener = ( AbstractEventListener ) eventListenerClass . newInstance ( ) ; plugin . addEventListener ( eventListener ) ; LOGGER . log ( Level . DEBUG , "Registered event listener[class={0}, eventType={1}] for plugin[name={2}]" , eventListener . getClass ( ) , eventListener . getEventType ( ) , plugin . getName ( ) ) ; } } | Registers event listeners with the specified plugin properties class loader and plugin . | 284 | 14 |
24,875 | public Map < String , String > getAll ( final Locale locale ) { Map < String , String > ret = LANGS . get ( locale ) ; if ( null == ret ) { ret = new HashMap <> ( ) ; final ResourceBundle defaultLangBundle = ResourceBundle . getBundle ( Keys . LANGUAGE , Latkes . getLocale ( ) ) ; final Enumeration < String > defaultLangKeys = defaultLangBundle . getKeys ( ) ; while ( defaultLangKeys . hasMoreElements ( ) ) { final String key = defaultLangKeys . nextElement ( ) ; final String value = replaceVars ( defaultLangBundle . getString ( key ) ) ; ret . put ( key , value ) ; } final ResourceBundle langBundle = ResourceBundle . getBundle ( Keys . LANGUAGE , locale ) ; final Enumeration < String > langKeys = langBundle . getKeys ( ) ; while ( langKeys . hasMoreElements ( ) ) { final String key = langKeys . nextElement ( ) ; final String value = replaceVars ( langBundle . getString ( key ) ) ; ret . put ( key , value ) ; } LANGS . put ( locale , ret ) ; } return ret ; } | Gets all language properties as a map by the specified locale . | 281 | 13 |
24,876 | public String get ( final String key , final Locale locale ) { return get ( Keys . LANGUAGE , key , locale ) ; } | Gets a value with the specified key and locale . | 30 | 11 |
24,877 | private String replaceVars ( final String langValue ) { String ret = StringUtils . replace ( langValue , "${servePath}" , Latkes . getServePath ( ) ) ; ret = StringUtils . replace ( ret , "${staticServePath}" , Latkes . getStaticServePath ( ) ) ; return ret ; } | Replaces all variables of the specified language value . | 76 | 10 |
24,878 | public static String unescape ( String string ) { StringBuilder sb = new StringBuilder ( string . length ( ) ) ; for ( int i = 0 , length = string . length ( ) ; i < length ; i ++ ) { char c = string . charAt ( i ) ; if ( c == ' ' ) { final int semic = string . indexOf ( ' ' , i ) ; if ( semic > i ) { final String entity = string . substring ( i + 1 , semic ) ; sb . append ( XMLTokener . unescapeEntity ( entity ) ) ; // skip past the entity we just parsed. i += entity . length ( ) + 1 ; } else { // this shouldn't happen in most cases since the parser // errors on unclosed entries. sb . append ( c ) ; } } else { // not part of an entity sb . append ( c ) ; } } return sb . toString ( ) ; } | Removes XML escapes from the string . | 201 | 8 |
24,879 | public static String format ( final String xml ) { try { final DocumentBuilder db = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; final Document doc = db . parse ( new InputSource ( new StringReader ( xml ) ) ) ; final Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; final StreamResult result = new StreamResult ( new StringWriter ( ) ) ; final DOMSource source = new DOMSource ( doc ) ; transformer . transform ( source , result ) ; return result . getWriter ( ) . toString ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . WARN , "Formats pretty XML failed: " + e . getMessage ( ) ) ; return xml ; } } | Returns pretty print of the specified xml string . | 208 | 9 |
24,880 | private void initTemplateEngineCfg ( ) { configuration = new Configuration ( ) ; configuration . setDefaultEncoding ( "UTF-8" ) ; final ServletContext servletContext = AbstractServletListener . getServletContext ( ) ; configuration . setServletContextForTemplateLoading ( servletContext , "/plugins/" + dirName ) ; LOGGER . log ( Level . DEBUG , "Initialized template configuration" ) ; } | Initializes template engine configuration . | 90 | 6 |
24,881 | public String getLang ( final Locale locale , final String key ) { return langs . get ( locale . toString ( ) ) . getProperty ( key ) ; } | Gets language label with the specified locale and key . | 37 | 11 |
24,882 | public void plug ( final Map < String , Object > dataModel , final RequestContext context ) { String content = ( String ) dataModel . get ( Plugin . PLUGINS ) ; if ( null == content ) { dataModel . put ( Plugin . PLUGINS , "" ) ; } handleLangs ( dataModel ) ; fillDefault ( dataModel ) ; postPlug ( dataModel , context ) ; content = ( String ) dataModel . get ( Plugin . PLUGINS ) ; final StringBuilder contentBuilder = new StringBuilder ( content ) ; contentBuilder . append ( getViewContent ( dataModel ) ) ; final String pluginsContent = contentBuilder . toString ( ) ; dataModel . put ( Plugin . PLUGINS , pluginsContent ) ; LOGGER . log ( Level . DEBUG , "Plugin[name={0}] has been plugged" , getName ( ) ) ; } | Plugs with the specified data model and the args from request . | 185 | 13 |
24,883 | private void handleLangs ( final Map < String , Object > dataModel ) { final Locale locale = Latkes . getLocale ( ) ; final String language = locale . getLanguage ( ) ; final String country = locale . getCountry ( ) ; final String variant = locale . getVariant ( ) ; final StringBuilder keyBuilder = new StringBuilder ( language ) ; if ( StringUtils . isNotBlank ( country ) ) { keyBuilder . append ( "_" ) . append ( country ) ; } if ( StringUtils . isNotBlank ( variant ) ) { keyBuilder . append ( "_" ) . append ( variant ) ; } final String localKey = keyBuilder . toString ( ) ; final Properties props = langs . get ( localKey ) ; if ( null == props ) { return ; } final Set < Object > keySet = props . keySet ( ) ; for ( final Object key : keySet ) { dataModel . put ( ( String ) key , props . getProperty ( ( String ) key ) ) ; } } | Processes languages . Retrieves language labels with default locale then sets them into the specified data model . | 223 | 21 |
24,884 | private void fillDefault ( final Map < String , Object > dataModel ) { Keys . fillServer ( dataModel ) ; Keys . fillRuntime ( dataModel ) ; } | Fills default values into the specified data model . | 35 | 10 |
24,885 | private String getViewContent ( final Map < String , Object > dataModel ) { if ( null == configuration ) { initTemplateEngineCfg ( ) ; } try { final Template template = configuration . getTemplate ( "plugin.ftl" ) ; final StringWriter sw = new StringWriter ( ) ; template . process ( dataModel , sw ) ; return sw . toString ( ) ; } catch ( final Exception e ) { // This plugin has no view return "" ; } } | Gets view content of a plugin . The content is processed with the specified data model by template engine . | 100 | 21 |
24,886 | synchronized void addListener ( final AbstractEventListener < ? > listener ) { if ( null == listener ) { throw new NullPointerException ( ) ; } final String eventType = listener . getEventType ( ) ; if ( null == eventType ) { throw new NullPointerException ( ) ; } List < AbstractEventListener < ? > > listenerList = listeners . get ( eventType ) ; if ( null == listenerList ) { listenerList = new ArrayList <> ( ) ; listeners . put ( eventType , listenerList ) ; } listenerList . add ( listener ) ; } | Adds the specified listener to the set of listeners for this object provided that it is not the same as some listener already in the set . | 125 | 27 |
24,887 | public static < T > T [ ] concatenate ( final T [ ] first , final T [ ] ... rest ) { int totalLength = first . length ; for ( final T [ ] array : rest ) { totalLength += array . length ; } final T [ ] ret = Arrays . copyOf ( first , totalLength ) ; int offset = first . length ; for ( final T [ ] array : rest ) { System . arraycopy ( array , 0 , ret , offset , array . length ) ; offset += array . length ; } return ret ; } | Concatenates the specified arrays . | 118 | 8 |
24,888 | private static Set < URL > getResourcesFromRoot ( final String rootPath ) { final Set < URL > rets = new LinkedHashSet < URL > ( ) ; String path = rootPath ; if ( path . startsWith ( "/" ) ) { path = path . substring ( 1 ) ; } try { final Enumeration < URL > resources = Thread . currentThread ( ) . getContextClassLoader ( ) . getResources ( path ) ; URL url = null ; while ( resources . hasMoreElements ( ) ) { url = ( URL ) resources . nextElement ( ) ; rets . add ( url ) ; } } catch ( final IOException e ) { LOGGER . log ( Level . ERROR , "get the ROOT Rescources error" , e ) ; } return rets ; } | the URLS under Root path each of which we should scan from . | 172 | 14 |
24,889 | private static boolean isJarURL ( final URL rootDirResource ) { final String protocol = rootDirResource . getProtocol ( ) ; /** * Determine whether the given URL points to a resource in a jar file, that is, has protocol "jar", "zip", * "wsjar" or "code-source". * <p> * "zip" and "wsjar" are used by BEA WebLogic Server and IBM WebSphere, respectively, but can be treated like * jar files. The same applies to "code-source" URLs on Oracle OC4J, provided that the path contains a jar * separator. * * */ return "jar" . equals ( protocol ) || "zip" . equals ( protocol ) || "wsjar" . equals ( protocol ) || ( "code-source" . equals ( protocol ) && rootDirResource . getPath ( ) . contains ( JAR_URL_SEPARATOR ) ) ; } | check if the URL of the Rousource is a JAR resource . | 199 | 15 |
24,890 | private static Collection < ? extends URL > doFindPathMatchingJarResources ( final URL rootDirResource , final String subPattern ) { final Set < URL > result = new LinkedHashSet < URL > ( ) ; JarFile jarFile = null ; String jarFileUrl ; String rootEntryPath = null ; URLConnection con ; boolean newJarFile = false ; try { con = rootDirResource . openConnection ( ) ; if ( con instanceof JarURLConnection ) { final JarURLConnection jarCon = ( JarURLConnection ) con ; jarCon . setUseCaches ( false ) ; jarFile = jarCon . getJarFile ( ) ; jarFileUrl = jarCon . getJarFileURL ( ) . toExternalForm ( ) ; final JarEntry jarEntry = jarCon . getJarEntry ( ) ; rootEntryPath = jarEntry != null ? jarEntry . getName ( ) : "" ; } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the // protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" // prefix. final String urlFile = rootDirResource . getFile ( ) ; final int separatorIndex = urlFile . indexOf ( JAR_URL_SEPARATOR ) ; if ( separatorIndex != - 1 ) { jarFileUrl = urlFile . substring ( 0 , separatorIndex ) ; rootEntryPath = urlFile . substring ( separatorIndex + JAR_URL_SEPARATOR . length ( ) ) ; jarFile = getJarFile ( jarFileUrl ) ; } else { jarFile = new JarFile ( urlFile ) ; jarFileUrl = urlFile ; rootEntryPath = "" ; } newJarFile = true ; } } catch ( final IOException e ) { LOGGER . log ( Level . ERROR , "reslove jar File error" , e ) ; return result ; } try { if ( ! "" . equals ( rootEntryPath ) && ! rootEntryPath . endsWith ( "/" ) ) { // Root entry path must end with slash to allow for proper // matching. // The Sun JRE does not return a slash here, but BEA JRockit // does. rootEntryPath = rootEntryPath + "/" ; } for ( final Enumeration < JarEntry > entries = jarFile . entries ( ) ; entries . hasMoreElements ( ) ; ) { final JarEntry entry = ( JarEntry ) entries . nextElement ( ) ; final String entryPath = entry . getName ( ) ; String relativePath = null ; if ( entryPath . startsWith ( rootEntryPath ) ) { relativePath = entryPath . substring ( rootEntryPath . length ( ) ) ; if ( AntPathMatcher . match ( subPattern , relativePath ) ) { if ( relativePath . startsWith ( "/" ) ) { relativePath = relativePath . substring ( 1 ) ; } result . add ( new URL ( rootDirResource , relativePath ) ) ; } } } return result ; } catch ( final IOException e ) { LOGGER . log ( Level . ERROR , "parse the JarFile error" , e ) ; } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if ( newJarFile ) { try { jarFile . close ( ) ; } catch ( final IOException e ) { LOGGER . log ( Level . WARN , " occur error when closing jarFile" , e ) ; } } } return result ; } | scan the jar to get the URLS of the Classes . | 770 | 12 |
24,891 | private static Collection < ? extends URL > doFindPathMatchingFileResources ( final URL rootDirResource , final String subPattern ) { File rootFile = null ; final Set < URL > rets = new LinkedHashSet < URL > ( ) ; try { rootFile = new File ( rootDirResource . toURI ( ) ) ; } catch ( final URISyntaxException e ) { LOGGER . log ( Level . ERROR , "cat not resolve the rootFile" , e ) ; throw new RuntimeException ( "cat not resolve the rootFile" , e ) ; } String fullPattern = StringUtils . replace ( rootFile . getAbsolutePath ( ) , File . separator , "/" ) ; if ( ! subPattern . startsWith ( "/" ) ) { fullPattern += "/" ; } final String filePattern = fullPattern + StringUtils . replace ( subPattern , File . separator , "/" ) ; @ SuppressWarnings ( "unchecked" ) final Collection < File > files = FileUtils . listFiles ( rootFile , new IOFileFilter ( ) { @ Override public boolean accept ( final File dir , final String name ) { return true ; } @ Override public boolean accept ( final File file ) { if ( file . isDirectory ( ) ) { return false ; } if ( AntPathMatcher . match ( filePattern , StringUtils . replace ( file . getAbsolutePath ( ) , File . separator , "/" ) ) ) { return true ; } return false ; } } , TrueFileFilter . INSTANCE ) ; try { for ( File file : files ) { rets . add ( file . toURI ( ) . toURL ( ) ) ; } } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "convert file to URL error" , e ) ; throw new RuntimeException ( "convert file to URL error" , e ) ; } return rets ; } | scan the system file to get the URLS of the Classes . | 417 | 13 |
24,892 | public static RequestContext handle ( final HttpServletRequest request , final HttpServletResponse response ) { try { request . setCharacterEncoding ( "UTF-8" ) ; response . setCharacterEncoding ( "UTF-8" ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Sets request context character encoding failed" , e ) ; } final RequestContext ret = new RequestContext ( ) ; ret . setRequest ( request ) ; ret . setResponse ( response ) ; Latkes . REQUEST_CONTEXT . set ( ret ) ; for ( final Handler handler : HANDLERS ) { ret . addHandler ( handler ) ; } ret . handle ( ) ; result ( ret ) ; Latkes . REQUEST_CONTEXT . set ( null ) ; return ret ; } | Handle flow . | 175 | 3 |
24,893 | public static void result ( final RequestContext context ) { final HttpServletResponse response = context . getResponse ( ) ; if ( response . isCommitted ( ) ) { // Response sends redirect or error return ; } AbstractResponseRenderer renderer = context . getRenderer ( ) ; if ( null == renderer ) { renderer = new Http404Renderer ( ) ; } renderer . render ( context ) ; } | Do HTTP response . | 94 | 4 |
24,894 | public static Router delete ( final String uriTemplate , final ContextHandler handler ) { return route ( ) . delete ( uriTemplate , handler ) ; } | HTTP DELETE routing . | 32 | 6 |
24,895 | public static Router put ( final String uriTemplate , final ContextHandler handler ) { return route ( ) . put ( uriTemplate , handler ) ; } | HTTP PUT routing . | 32 | 5 |
24,896 | public static Router get ( final String uriTemplate , final ContextHandler handler ) { return route ( ) . get ( uriTemplate , handler ) ; } | HTTP GET routing . | 32 | 4 |
24,897 | public static Router post ( final String uriTemplate , final ContextHandler handler ) { return route ( ) . post ( uriTemplate , handler ) ; } | HTTP POST routing . | 32 | 4 |
24,898 | public static void mapping ( ) { for ( final Router router : routers ) { final ContextHandlerMeta contextHandlerMeta = router . toContextHandlerMeta ( ) ; RouteHandler . addContextHandlerMeta ( contextHandlerMeta ) ; } } | Performs mapping for all routers . | 48 | 7 |
24,899 | public void dispose ( ) { try { connection . close ( ) ; } catch ( final Exception e ) { LOGGER . log ( Level . ERROR , "Disposes transaction [" + getId ( ) + "] failed" , e ) ; } finally { isActive = false ; connection = null ; JdbcRepository . TX . set ( null ) ; } } | Disposes this transaction . | 77 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.