idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
26,600
public ServiceCacheBuilder < T > threadFactory ( ThreadFactory threadFactory ) { this . threadFactory = threadFactory ; this . executorService = null ; return this ; }
Optional thread factory to use for the cache s internal thread
26,601
public ServiceCacheBuilder < T > executorService ( ExecutorService executorService ) { this . executorService = new CloseableExecutorService ( executorService ) ; this . threadFactory = null ; return this ; }
Optional executor getGroup to use for the cache s background thread
26,602
private boolean isTransactional ( SqlAction [ ] sqlActions , XianTransaction transaction ) { int count = 0 ; for ( SqlAction sqlAction : sqlActions ) { if ( ! ( sqlAction instanceof ISelect ) ) { count ++ ; } } return count > 1 || transaction . isBegun ( ) ; }
judge whether we need to begin the transaction . If there are more than one non - query sql actions in this dao unit a new transaction will be begun . if a transaction is already begun a nested transaction will be begun . Else no transaction will be begun .
26,603
public ListenerContainer < NodeCacheListener > getListenable ( ) { Preconditions . checkState ( state . get ( ) != State . CLOSED , "Closed" ) ; return listeners ; }
Return the cache listenable
26,604
public static List < String > split ( String path ) { PathUtils . validatePath ( path ) ; return PATH_SPLITTER . splitToList ( path ) ; }
Given a full path return the the individual parts without slashes . The root path will return an empty list .
26,605
public static void deleteChildren ( ZooKeeper zookeeper , String path , boolean deleteSelf ) throws InterruptedException , KeeperException { PathUtils . validatePath ( path ) ; List < String > children = zookeeper . getChildren ( path , null ) ; for ( String child : children ) { String fullPath = makePath ( path , child ) ; deleteChildren ( zookeeper , fullPath , true ) ; } if ( deleteSelf ) { try { zookeeper . delete ( path , - 1 ) ; } catch ( KeeperException . NotEmptyException e ) { deleteChildren ( zookeeper , path , true ) ; } catch ( KeeperException . NoNodeException e ) { } } }
Recursively deletes children of a node .
26,606
public static List < String > getSortedChildren ( ZooKeeper zookeeper , String path ) throws InterruptedException , KeeperException { List < String > children = zookeeper . getChildren ( path , false ) ; List < String > sortedList = Lists . newArrayList ( children ) ; Collections . sort ( sortedList ) ; return sortedList ; }
Return the children of the given path sorted by sequence number
26,607
public static String makePath ( String parent , String child ) { StringBuilder path = new StringBuilder ( ) ; joinPath ( path , parent , child ) ; return path . toString ( ) ; }
Given a parent path and a child node create a combined full path
26,608
public static String makePath ( String parent , String firstChild , String ... restChildren ) { StringBuilder path = new StringBuilder ( ) ; joinPath ( path , parent , firstChild ) ; if ( restChildren == null ) { return path . toString ( ) ; } else { for ( String child : restChildren ) { joinPath ( path , "" , child ) ; } return path . toString ( ) ; } }
Given a parent path and a list of children nodes create a combined full path
26,609
public static void lookupHostname ( ErrorReporter errorReporter ) { String myHostName = getProperty ( PROPERTY_LOGSTASH_GELF_HOSTNAME , "unknown" ) ; String myFQDNHostName = getProperty ( PROPERTY_LOGSTASH_GELF_FQDN_HOSTNAME , "unknown" ) ; String myAddress = "" ; if ( ! Boolean . parseBoolean ( getProperty ( PROPERTY_LOGSTASH_GELF_SKIP_HOSTNAME_RESOLUTION , "false" ) ) ) { try { String resolutionOrder = getProperty ( PROPERTY_LOGSTASH_GELF_HOSTNAME_RESOLUTION_ORDER , RESOLUTION_ORDER_NETWORK_LOCALHOST_FALLBACK ) ; InetAddress inetAddress = null ; if ( resolutionOrder . equals ( RESOLUTION_ORDER_NETWORK_LOCALHOST_FALLBACK ) ) { inetAddress = getInetAddressWithHostname ( ) ; } if ( resolutionOrder . equals ( RESOLUTION_ORDER_LOCALHOST_NETWORK_FALLBACK ) ) { if ( isQualified ( InetAddress . getLocalHost ( ) ) ) { inetAddress = InetAddress . getLocalHost ( ) ; } else { inetAddress = getInetAddressWithHostname ( ) ; } } if ( inetAddress == null ) { inetAddress = InetAddress . getLocalHost ( ) ; } myHostName = getHostname ( inetAddress , false ) ; myFQDNHostName = getHostname ( inetAddress , true ) ; myAddress = inetAddress . getHostAddress ( ) ; } catch ( IOException e ) { errorReporter . reportError ( "Cannot resolve hostname" , e ) ; } } FQDN_HOSTNAME = myFQDNHostName ; HOSTNAME = myHostName ; ADDRESS = myAddress ; }
Triggers the hostname lookup .
26,610
public String registerScope ( FullHttpRequest req ) throws OAuthException { String contentType = ( req . headers ( ) != null ) ? req . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) : null ; if ( contentType != null && contentType . contains ( ResponseBuilder . APPLICATION_JSON ) ) { try { Scope scope = InputValidator . validate ( req . content ( ) . toString ( CharsetUtil . UTF_8 ) , Scope . class ) ; if ( scope . valid ( ) ) { if ( ! Scope . validScopeName ( scope . getScope ( ) ) ) { LOG . error ( "scope name is not valid" ) ; throw new OAuthException ( SCOPE_NAME_INVALID_ERROR , HttpResponseStatus . BAD_REQUEST ) ; } LOG . info ( ">>>>>>>>>>>>>>> scope = " + scope ) ; Scope foundScope = DBManagerFactory . getInstance ( ) . findScope ( scope . getScope ( ) ) . blockingGet ( ) ; if ( foundScope != null ) { LOG . error ( "scope already exists" ) ; throw new OAuthException ( SCOPE_ALREADY_EXISTS , HttpResponseStatus . BAD_REQUEST ) ; } else { DBManagerFactory . getInstance ( ) . storeScope ( scope ) . blockingGet ( ) ; } } else { LOG . error ( "scope is not valid" ) ; throw new OAuthException ( MANDATORY_FIELDS_ERROR , HttpResponseStatus . BAD_REQUEST ) ; } } catch ( Throwable e ) { LOG . error ( "cannot handle scope request" , e ) ; throw new OAuthException ( e , null , HttpResponseStatus . BAD_REQUEST ) ; } } else { throw new OAuthException ( ResponseBuilder . UNSUPPORTED_MEDIA_TYPE , HttpResponseStatus . BAD_REQUEST ) ; } return SCOPE_STORED_OK_MESSAGE ; }
Register an oauth scope . If the scope already exists returns an error .
26,611
public String getScopes ( HttpRequest req ) throws OAuthException { QueryStringDecoder dec = new QueryStringDecoder ( req . uri ( ) ) ; Map < String , List < String > > queryParams = dec . parameters ( ) ; if ( queryParams . containsKey ( "client_id" ) ) { return getScopes ( queryParams . get ( "client_id" ) . get ( 0 ) ) ; } List < Scope > scopes = DBManagerFactory . getInstance ( ) . getAllScopes ( ) . blockingGet ( ) ; String jsonString ; try { jsonString = JSON . toJSONString ( scopes ) ; } catch ( Exception e ) { LOG . error ( "cannot load scopes" , e ) ; throw new OAuthException ( e , null , HttpResponseStatus . BAD_REQUEST ) ; } return jsonString ; }
Returns either all scopes or scopes for a specific client_id passed as query parameter .
26,612
public Maybe < String > getValidScope ( String scope , String clientId ) { return DBManagerFactory . getInstance ( ) . findClientCredentials ( clientId ) . map ( creds -> getValidScopeByScope ( scope , creds . getScope ( ) ) ) ; }
Checks whether a scope is valid for a given client id .
26,613
public boolean scopeAllowed ( String scope , String allowedScopes ) { String [ ] allScopes = allowedScopes . split ( SPACE ) ; List < String > allowedList = Arrays . asList ( allScopes ) ; String [ ] scopes = scope . split ( SPACE ) ; int allowedCount = 0 ; for ( String s : scopes ) { if ( allowedList . contains ( s ) ) { allowedCount ++ ; } } return ( allowedCount == scopes . length ) ; }
Checks whether a scope is contained in allowed scopes .
26,614
public int getExpiresIn ( String tokenGrantType , String scope ) { int expiresIn = Integer . MAX_VALUE ; List < Scope > scopes = loadScopes ( scope ) ; boolean ccGrantType = TokenRequest . CLIENT_CREDENTIALS . equals ( tokenGrantType ) ; if ( TokenRequest . CLIENT_CREDENTIALS . equals ( tokenGrantType ) ) { for ( Scope s : scopes ) { if ( s . getCcExpiresIn ( ) < expiresIn ) { expiresIn = s . getCcExpiresIn ( ) ; } } } else if ( TokenRequest . PASSWORD . equals ( tokenGrantType ) ) { for ( Scope s : scopes ) { if ( s . getPassExpiresIn ( ) < expiresIn ) { expiresIn = s . getPassExpiresIn ( ) ; } } } else { for ( Scope s : scopes ) { if ( s . getRefreshExpiresIn ( ) < expiresIn ) { expiresIn = s . getRefreshExpiresIn ( ) ; } } } if ( scopes . size ( ) == 0 || expiresIn == Integer . MAX_VALUE ) { expiresIn = ( ccGrantType ) ? OAuthConfig . DEFAULT_CC_EXPIRES_IN : OAuthConfig . DEFAULT_PASSWORD_EXPIRES_IN ; } return expiresIn ; }
Returns value for expires_in by given scope and token type .
26,615
public String updateScope ( FullHttpRequest req , String scopeName ) throws OAuthException { String contentType = ( req . headers ( ) != null ) ? req . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) : null ; if ( contentType != null && contentType . contains ( ResponseBuilder . APPLICATION_JSON ) ) { try { Scope scope = InputValidator . validate ( req . content ( ) . toString ( CharsetUtil . UTF_8 ) , Scope . class ) ; if ( scope . validForUpdate ( ) ) { Scope foundScope = DBManagerFactory . getInstance ( ) . findScope ( scopeName ) . blockingGet ( ) ; if ( foundScope == null ) { LOG . error ( "scope does not exist" ) ; throw new OAuthException ( SCOPE_NOT_EXIST , HttpResponseStatus . BAD_REQUEST ) ; } else { setScopeEmptyValues ( scope , foundScope ) ; DBManagerFactory . getInstance ( ) . storeScope ( scope ) ; } } else { LOG . error ( "scope is not valid" ) ; throw new OAuthException ( MANDATORY_SCOPE_ERROR , HttpResponseStatus . BAD_REQUEST ) ; } } catch ( Exception e ) { LOG . error ( "cannot handle scope request" , e ) ; throw new OAuthException ( e , null , HttpResponseStatus . BAD_REQUEST ) ; } } else { throw new OAuthException ( ResponseBuilder . UNSUPPORTED_MEDIA_TYPE , HttpResponseStatus . BAD_REQUEST ) ; } return SCOPE_UPDATED_OK_MESSAGE ; }
Updates a scope . If the scope does not exists returns an error .
26,616
public String deleteScope ( String scopeName ) throws OAuthException { String responseMsg ; Scope foundScope = DBManagerFactory . getInstance ( ) . findScope ( scopeName ) . blockingGet ( ) ; if ( foundScope == null ) { LOG . error ( "scope does not exist" ) ; throw new OAuthException ( SCOPE_NOT_EXIST , HttpResponseStatus . BAD_REQUEST ) ; } else { List < ApplicationInfo > registeredApps = getClientAppsByScope ( scopeName ) ; if ( registeredApps . size ( ) > 0 ) { responseMsg = SCOPE_USED_BY_APP_MESSAGE ; } else { boolean ok = DBManagerFactory . getInstance ( ) . deleteScope ( scopeName ) . blockingGet ( ) ; if ( ok ) { responseMsg = SCOPE_DELETED_OK_MESSAGE ; } else { responseMsg = SCOPE_DELETED_NOK_MESSAGE ; } } } return responseMsg ; }
Deletes a scope . If the scope does not exists returns an error .
26,617
private void handleException ( final Throwable e ) { if ( errorListeners . size ( ) == 0 ) { LOG . error ( "" , e ) ; } else { errorListeners . forEach ( new Function < UnhandledErrorListener , Void > ( ) { public Void apply ( UnhandledErrorListener listener ) { try { listener . unhandledError ( "" , e ) ; } catch ( Exception e ) { ThreadUtils . checkInterrupted ( e ) ; LOG . error ( "Exception handling exception" , e ) ; } return null ; } } ) ; } }
Send an exception to any listeners or else log the error if there are none .
26,618
public static Single < Boolean > exists ( String key , Object member ) { return exists ( CacheService . CACHE_CONFIG_BEAN , key , member ) ; }
check whether the element exists in the set
26,619
public static Single < Long > addAll ( CacheConfigBean cacheConfigBean , String key , Set members ) { return SingleRxXian . call ( CacheService . CACHE_SERVICE , "cacheSetAdd" , new JSONObject ( ) { { put ( "cacheConfig" , cacheConfigBean ) ; put ( "key" , key ) ; put ( "members" , members ) ; } } ) . map ( unitResponseObject -> { unitResponseObject . throwExceptionIfNotSuccess ( ) ; if ( unitResponseObject . getData ( ) == null ) return 0L ; return unitResponseObject . dataToLong ( ) ; } ) ; }
add all the given elements into the set
26,620
public static Single < Long > removes ( String key , Set members ) { return removes ( CacheService . CACHE_CONFIG_BEAN , key , members ) ; }
remove the given elements from the cache set
26,621
public void start ( ) throws Exception { log . debug ( "Starting" ) ; if ( ! started . compareAndSet ( false , true ) ) { IllegalStateException ise = new IllegalStateException ( "Already started" ) ; throw ise ; } state . start ( ) ; }
Must be called after construction
26,622
public OperationTrace startAdvancedTracer ( String name ) { return new OperationTrace ( name , tracer . get ( ) , state . getSessionId ( ) ) ; }
Start a new advanced tracer with more metrics being recorded
26,623
public void start ( ) throws Exception { try { reRegisterServices ( ) ; } catch ( KeeperException e ) { log . error ( "Could not register instances - will try again later" , e ) ; } client . getConnectionStateListenable ( ) . addListener ( connectionStateListener ) ; }
The discovery must be started before use
26,624
public List < String > queryForNames ( ) throws Exception { List < String > names = client . getChildren ( ) . forPath ( basePath ) ; return ImmutableList . copyOf ( names ) ; }
Return the names of all known services
26,625
public Collection < ServiceInstance < T > > queryForInstances ( String name ) throws Exception { return queryForInstances ( name , null ) ; }
Return all known instances for the given group
26,626
public ServiceInstance < T > queryForInstance ( String name , String id ) throws Exception { String path = pathForInstance ( name , id ) ; try { byte [ ] bytes = client . getData ( ) . forPath ( path ) ; return serializer . deserialize ( bytes ) ; } catch ( KeeperException . NoNodeException ignore ) { } return null ; }
Return a group instance POJO
26,627
public String processPattern ( String newPattern ) throws IllegalArgumentException { int idx = 0 ; int offnum = - 1 ; StringBuffer outpat = new StringBuffer ( ) ; offsets = new int [ BUFSIZE ] ; arguments = new String [ BUFSIZE ] ; maxOffset = - 1 ; while ( true ) { int ridx = - 1 ; int lidx = newPattern . indexOf ( ldel , idx ) ; if ( lidx >= 0 ) { ridx = newPattern . indexOf ( rdel , lidx + ldel . length ( ) ) ; } else { break ; } if ( ++ offnum >= BUFSIZE ) { throw new IllegalArgumentException ( "TooManyArguments" ) ; } if ( ridx < 0 ) { if ( exactmatch ) { throw new IllegalArgumentException ( "UnmatchedBraces" ) ; } else { break ; } } outpat . append ( newPattern . substring ( idx , lidx ) ) ; offsets [ offnum ] = outpat . length ( ) ; arguments [ offnum ] = newPattern . substring ( lidx + ldel . length ( ) , ridx ) ; idx = ridx + rdel . length ( ) ; maxOffset ++ ; } outpat . append ( newPattern . substring ( idx ) ) ; return outpat . toString ( ) ; }
Scans the pattern and prepares internal variables .
26,628
private String formatObject ( Object obj ) { if ( obj == null ) { return null ; } if ( obj instanceof Number ) { return NumberFormat . getInstance ( locale ) . format ( obj ) ; } else if ( obj instanceof Date ) { return DateFormat . getDateTimeInstance ( DateFormat . SHORT , DateFormat . SHORT , locale ) . format ( obj ) ; } else if ( obj instanceof String ) { return ( String ) obj ; } return obj . toString ( ) ; }
Formats object .
26,629
public StringBuffer format ( Object pat , StringBuffer result , FieldPosition fpos ) { String pattern = processPattern ( ( String ) pat ) ; int lastOffset = 0 ; for ( int i = 0 ; i <= maxOffset ; ++ i ) { int offidx = offsets [ i ] ; result . append ( pattern . substring ( lastOffset , offsets [ i ] ) ) ; lastOffset = offidx ; String key = arguments [ i ] ; String obj ; if ( key . length ( ) > 0 ) { obj = formatObject ( processKey ( key ) ) ; } else { result . append ( this . ldel ) ; result . append ( this . rdel ) ; continue ; } if ( obj == null ) { String lessgreedy = ldel + key ; int fromright = lessgreedy . lastIndexOf ( ldel ) ; if ( fromright > 0 ) { String newkey = lessgreedy . substring ( fromright + ldel . length ( ) ) ; String newsubst = formatObject ( processKey ( newkey ) ) ; if ( newsubst != null ) { obj = lessgreedy . substring ( 0 , fromright ) + newsubst ; } } } if ( obj == null ) { if ( throwex ) { throw new IllegalArgumentException ( "ObjectForKey" ) ; } else { obj = ldel + key + rdel ; } } result . append ( obj ) ; } result . append ( pattern . substring ( lastOffset , pattern . length ( ) ) ) ; return result ; }
Formats the parsed string by inserting table s values .
26,630
private BaseLocalTransaction createLocalTransaction ( String transId ) { BaseLocalTransaction baseLocalTransaction ; try { baseLocalTransaction = localTransactionConstructor . newInstance ( transId , this ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } BaseLocalTransaction . addLocalTransaction ( baseLocalTransaction ) ; return baseLocalTransaction ; }
create a new local transaction . All transactions are produced by connections .
26,631
public static < T > List < T > toList ( Object array , Class < T > clazz ) { List < T > list = new ArrayList < > ( ) ; for ( Object o : toObjectArray ( array ) ) { list . add ( Reflection . toType ( o , clazz ) ) ; } return list ; }
Convert the given array to list
26,632
@ SuppressWarnings ( "unchecked" ) public static < T > T [ ] toArray ( List list , Class < T > tClass ) { Object arrayObject = Array . newInstance ( tClass , list . size ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Array . set ( arrayObject , i , list . get ( i ) ) ; } return ( T [ ] ) arrayObject ; }
convert list to an array .
26,633
public static < T > T [ ] concat ( T [ ] first , T [ ] second ) { T [ ] result = Arrays . copyOf ( first , first . length + second . length ) ; System . arraycopy ( second , 0 , result , first . length , second . length ) ; return result ; }
concat 2 array to a new array .
26,634
public static Single < Boolean > exists ( CacheConfigBean cacheConfigBean , String cacheKey ) { return SingleRxXian . call ( CacheService . CACHE_SERVICE , "cacheListExists" , new JSONObject ( ) { { put ( "cacheConfig" , cacheConfigBean ) ; put ( "key" , cacheKey ) ; } } ) . map ( UnitResponse :: dataToBoolean ) ; }
check whether the list exists
26,635
public static Single < Long > length ( CacheConfigBean cacheConfigBean , String cacheKey ) { return SingleRxXian . call ( CacheService . CACHE_SERVICE , "cacheListLength" , new JSONObject ( ) { { put ( "cacheConfig" , cacheConfigBean ) ; put ( "key" , cacheKey ) ; } } ) . map ( unitResponse -> { long length = Objects . requireNonNull ( unitResponse . dataToLong ( ) ) ; return length > 0 ? length : 0 ; } ) ; }
query the length of the cached list
26,636
public static Single < Boolean > isEmpty ( CacheConfigBean cacheConfigBean , String cacheKey ) { return length ( cacheConfigBean , cacheKey ) . map ( length -> length == 0 ) ; }
check whether the cached list is empty or not .
26,637
public static Single < Boolean > addFirst ( String cacheKey , Object value ) { return addFirst ( CacheService . CACHE_CONFIG_BEAN , cacheKey , value ) ; }
add element to the list s header
26,638
public static Single < Long > remove ( String cacheKey , Object value ) { return remove ( CacheService . CACHE_CONFIG_BEAN , cacheKey , value ) ; }
remove the given element
26,639
public static Completable clear ( CacheConfigBean cacheConfigBean , String cacheKey ) { return SingleRxXian . call ( CacheService . CACHE_SERVICE , "cacheListClear" , new JSONObject ( ) { { put ( "cacheConfig" , cacheConfigBean ) ; put ( "key" , cacheKey ) ; } } ) . toCompletable ( ) ; }
clear the specified cached list .
26,640
public static Single < Boolean > delete ( CacheConfigBean cacheConfigBean , String cacheKey ) { return CacheObjectUtil . remove ( cacheConfigBean , cacheKey ) ; }
delete the cached list
26,641
public void close ( ) { isOpen . set ( false ) ; Iterator < Future < ? > > iterator = futures . iterator ( ) ; while ( iterator . hasNext ( ) ) { Future < ? > future = iterator . next ( ) ; iterator . remove ( ) ; if ( ! future . isDone ( ) && ! future . isCancelled ( ) && ! future . cancel ( true ) ) { log . warn ( "Could not cancel " + future ) ; } } if ( shutdownOnClose ) { executorService . shutdownNow ( ) ; } }
Closes any tasks currently in progress
26,642
public < V > Future < V > submit ( Callable < V > task ) { Preconditions . checkState ( isOpen . get ( ) , "CloseableExecutorService is closed" ) ; InternalFutureTask < V > futureTask = new InternalFutureTask < V > ( new FutureTask < V > ( task ) ) ; executorService . execute ( futureTask ) ; return futureTask ; }
Submits a value - returning task for execution and returns a Future representing the pending results of the task . Upon completion this task may be taken or polled .
26,643
public Future < ? > submit ( Runnable task ) { Preconditions . checkState ( isOpen . get ( ) , "CloseableExecutorService is closed" ) ; InternalFutureTask < Void > futureTask = new InternalFutureTask < Void > ( new FutureTask < Void > ( task , null ) ) ; executorService . execute ( futureTask ) ; return futureTask ; }
Submits a Runnable task for execution and returns a Future representing that task . Upon completion this task may be taken or polled .
26,644
private boolean checkAndRespond ( Request request ) { if ( ! URIBean . checkUri ( request . getUrl ( ) ) ) { ServerResponseBean responseBean = new ServerResponseBean ( ) ; responseBean . setMsgId ( request . getMsgId ( ) ) ; responseBean . setHttpContentType ( HttpContentType . APPLICATION_JSON ) ; responseBean . setResponseBody ( UnitResponse . createError ( Group . CODE_BAD_REQUEST , null , String . format ( "URI %s is illegal." , request . getUrl ( ) ) ) . toVoJSONString ( ) ) ; IServerResponder . singleton . response ( responseBean ) ; return false ; } return true ; }
Check the request and respond a bad request response if checking is not passed .
26,645
public Single < ClientCredentials > issueClientCredentials ( HttpRequest req ) throws OAuthException { Single < ClientCredentials > creds ; String contentType = req . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) ; if ( contentType != null && contentType . contains ( HttpHeaderValues . APPLICATION_JSON ) ) { ApplicationInfo appInfo ; FullHttpRequest fullHttpRequest = ( FullHttpRequest ) req ; appInfo = InputValidator . validate ( fullHttpRequest . content ( ) . toString ( CharsetUtil . UTF_8 ) , ApplicationInfo . class ) ; if ( appInfo . valid ( ) ) { String [ ] scopeList = appInfo . getScope ( ) . split ( SCOPE_SPLITTER ) ; creds = db . getAllScopes ( ) . flatMap ( allScopes -> { for ( String s : scopeList ) { if ( matchScope ( allScopes , s ) == null ) { throw new OAuthException ( ResponseBuilder . SCOPE_NOT_EXIST , HttpResponseStatus . BAD_REQUEST ) ; } } if ( ( appInfo . getId ( ) != null && appInfo . getId ( ) . length ( ) > 0 ) && ( appInfo . getSecret ( ) != null && appInfo . getSecret ( ) . length ( ) > 0 ) ) { if ( areClientCredentialsValid ( appInfo . getId ( ) , appInfo . getSecret ( ) ) ) { return db . findClientCredentials ( appInfo . getId ( ) ) . switchIfEmpty ( Single . just ( new ClientCredentials ( appInfo . getName ( ) , appInfo . getScope ( ) , appInfo . getDescription ( ) , appInfo . getRedirectUri ( ) , appInfo . getId ( ) , appInfo . getSecret ( ) , appInfo . getApplicationDetails ( ) ) ) ) . flatMap ( clientCredentials -> { return Single . error ( new OAuthException ( ResponseBuilder . ALREADY_REGISTERED_APP , HttpResponseStatus . BAD_REQUEST ) ) ; } ) ; } else { throw new OAuthException ( ResponseBuilder . INVALID_CLIENT_CREDENTIALS , HttpResponseStatus . BAD_REQUEST ) ; } } else { ClientCredentials clientCredentials = new ClientCredentials ( appInfo . getName ( ) , appInfo . getScope ( ) , appInfo . getDescription ( ) , appInfo . getRedirectUri ( ) , appInfo . getApplicationDetails ( ) ) ; return Single . just ( clientCredentials ) ; } } ) . flatMap ( credsTmp -> db . storeClientCredentials ( credsTmp ) . andThen ( Single . just ( credsTmp ) ) ) ; } else { return Single . error ( new OAuthException ( ResponseBuilder . NAME_OR_SCOPE_OR_URI_IS_NULL , HttpResponseStatus . BAD_REQUEST ) ) ; } } else { return Single . error ( new OAuthException ( ResponseBuilder . UNSUPPORTED_MEDIA_TYPE , HttpResponseStatus . BAD_REQUEST ) ) ; } return creds ; }
issue a new clientCredentials
26,646
protected UserDetails authenticateUser ( String username , String password , HttpRequest authRequest ) throws AuthenticationException { UserDetails userDetails ; IUserAuthentication ua ; if ( OAuthConfig . getUserAuthenticationClass ( ) != null ) { try { ua = OAuthConfig . getUserAuthenticationClass ( ) . newInstance ( ) ; userDetails = ua . authenticate ( username , password , authRequest ) ; } catch ( InstantiationException | IllegalAccessException e ) { LOG . error ( "cannot instantiate user authentication class" , e ) ; throw new AuthenticationException ( e . getMessage ( ) ) ; } } else { userDetails = new UserDetails ( "12345" , null ) ; } return userDetails ; }
todo not tested
26,647
public Maybe < ApplicationInfo > getApplicationInfo ( String clientId ) { return db . findClientCredentials ( clientId ) . map ( creds -> { ApplicationInfo appInfo = null ; if ( creds != null ) { appInfo = ApplicationInfo . loadFromClientCredentials ( creds ) ; } return appInfo ; } ) ; }
Get the full application info by application id
26,648
protected Single < Boolean > isValidClientCredentials ( String clientId , String clientSecret ) { return db . findClientCredentials ( clientId ) . map ( creds -> creds . getSecret ( ) . equals ( clientSecret ) ) . switchIfEmpty ( Single . just ( false ) ) ; }
check only that LOCAL_NODE_ID and clientSecret are valid NOT that the status is active
26,649
public boolean blockingUpdateClientApp ( HttpRequest req , String clientId ) throws OAuthException { String contentType = req . headers ( ) . get ( HttpHeaderNames . CONTENT_TYPE ) ; if ( contentType != null && contentType . contains ( ResponseBuilder . APPLICATION_JSON ) ) { if ( ! isExistingClient ( clientId ) . blockingGet ( ) ) { throw new OAuthException ( ResponseBuilder . INVALID_CLIENT_ID , HttpResponseStatus . BAD_REQUEST ) ; } ApplicationInfo appInfo ; try { FullHttpRequest fullHttpRequest = ( FullHttpRequest ) req ; appInfo = InputValidator . validate ( fullHttpRequest . content ( ) . toString ( CharsetUtil . UTF_8 ) , ApplicationInfo . class ) ; if ( appInfo . validForUpdate ( ) ) { if ( appInfo . getScope ( ) != null ) { String [ ] scopeList = appInfo . getScope ( ) . split ( " " ) ; for ( String s : scopeList ) { if ( db . findScope ( s ) . blockingGet ( ) == null ) { throw new OAuthException ( ResponseBuilder . SCOPE_NOT_EXIST , HttpResponseStatus . BAD_REQUEST ) ; } } } db . updateClientCredentials ( clientId , appInfo . getScope ( ) , appInfo . getDescription ( ) , appInfo . getStatus ( ) , appInfo . getApplicationDetails ( ) ) . blockingGet ( ) ; } else { throw new OAuthException ( ResponseBuilder . UPDATE_APP_MANDATORY_PARAM_MISSING , HttpResponseStatus . BAD_REQUEST ) ; } } catch ( Throwable e ) { LOG . error ( "cannot update client application" , e ) ; throw new OAuthException ( e , ResponseBuilder . CANNOT_UPDATE_APP , HttpResponseStatus . BAD_REQUEST ) ; } } else { throw new OAuthException ( ResponseBuilder . UNSUPPORTED_MEDIA_TYPE , HttpResponseStatus . BAD_REQUEST ) ; } return true ; }
blocking update client app
26,650
private static boolean writeIfNotEmpty ( OutputAccessor out , boolean hasFields , String field , Object value ) { if ( value == null ) { return hasFields ; } if ( value instanceof String ) { if ( GelfMessage . isEmpty ( ( String ) value ) ) { return hasFields ; } if ( hasFields ) { writeKeyValueSeparator ( out ) ; } writeMapEntry ( out , field , value ) ; return true ; } if ( hasFields ) { writeKeyValueSeparator ( out ) ; } writeMapEntry ( out , field , value ) ; return true ; }
Write a Value to JSON if the value is not empty .
26,651
static Object getAdditionalFieldValue ( String value , String fieldType ) { Object result = null ; if ( fieldType . equalsIgnoreCase ( FIELD_TYPE_DISCOVER ) ) { Result discoveredType = ValueDiscovery . discover ( value ) ; if ( discoveredType == Result . STRING ) { return value ; } if ( discoveredType == Result . LONG ) { try { return Long . parseLong ( value ) ; } catch ( NumberFormatException ex ) { return value ; } } try { return Double . parseDouble ( value ) ; } catch ( NumberFormatException ex ) { return value ; } } if ( fieldType . equalsIgnoreCase ( FIELD_TYPE_STRING ) ) { result = value ; } if ( fieldType . equals ( FIELD_TYPE_DOUBLE ) || fieldType . equalsIgnoreCase ( FIELD_TYPE_DOUBLE2 ) ) { try { result = Double . parseDouble ( value ) ; } catch ( NumberFormatException ex ) { if ( fieldType . equals ( FIELD_TYPE_DOUBLE ) ) { result = Double . valueOf ( 0 ) ; } } } if ( fieldType . equals ( FIELD_TYPE_LONG ) || fieldType . equalsIgnoreCase ( FIELD_TYPE_LONG2 ) ) { try { result = ( long ) Double . parseDouble ( value ) ; } catch ( NumberFormatException ex ) { if ( fieldType . equals ( FIELD_TYPE_LONG ) ) { result = Long . valueOf ( 0 ) ; } } } return result ; }
Get the field value as requested data type .
26,652
public void clean ( ) throws Exception { try { client . delete ( ) . forPath ( basePath ) ; } catch ( KeeperException . BadVersionException ignore ) { } catch ( KeeperException . NotEmptyException ignore ) { } }
Attempt to delete the lock node so that sequence numbers get reset
26,653
public synchronized void close ( ) { Preconditions . checkState ( state . compareAndSet ( State . STARTED , State . CLOSED ) , "Already closed or has not been started" ) ; client . getConnectionStateListenable ( ) . removeListener ( listener ) ; executorService . close ( ) ; ourTask . set ( null ) ; }
Shutdown this selector and remove yourself from the leadership group
26,654
public synchronized void interruptLeadership ( ) { Future < ? > task = ourTask . get ( ) ; if ( task != null ) { task . cancel ( true ) ; } }
Attempt to cancel and interrupt the current leadership if this instance has leadership
26,655
private static ExecutorService wrapExecutor ( final Executor executor ) { return new AbstractExecutorService ( ) { private volatile boolean isShutdown = false ; private volatile boolean isTerminated = false ; public void shutdown ( ) { isShutdown = true ; } public List < Runnable > shutdownNow ( ) { return Lists . newArrayList ( ) ; } public boolean isShutdown ( ) { return isShutdown ; } public boolean isTerminated ( ) { return isTerminated ; } public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { throw new UnsupportedOperationException ( ) ; } public void execute ( Runnable command ) { try { executor . execute ( command ) ; } finally { isShutdown = true ; isTerminated = true ; } } } ; }
temporary wrapper for deprecated constructor
26,656
@ SuppressWarnings ( "all" ) synchronized public static < T > Set < Class < ? extends T > > getNonAbstractSubClasses ( Class < T > parentClass , String ... packageNames ) { return getNonAbstractSubClassInfoSet ( parentClass , packageNames ) . stream ( ) . map ( classInfo -> { try { return ( Class < ? extends T > ) parentClass . getClassLoader ( ) . loadClass ( classInfo . getName ( ) ) ; } catch ( ClassNotFoundException e ) { SystemOutLogger . SINGLETON . error ( "Failed to load class " + classInfo . getName ( ) , e , "" ) ; System . exit ( Constant . SYSTEM_EXIT_CODE_FOR_SYS_INIT_ERROR ) ; return null ; } } ) . collect ( Collectors . toSet ( ) ) ; }
Scan classpath for all concrete subclasses of specified interface or class
26,657
public synchronized static < T > Set < T > getSubclassInstances ( Class < T > parentClass , String ... packageNames ) { return getNonAbstractSubClasses ( parentClass , packageNames ) . stream ( ) . filter ( subclass -> { if ( Reflection . canInitiate ( subclass ) ) { return true ; } else { System . out . println ( subclass + " can not be initiated, ignored." ) ; return false ; } } ) . map ( subclass -> { try { return subclass . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { e . printStackTrace ( ) ; return null ; } } ) . collect ( Collectors . toSet ( ) ) ; }
search and create new instances of concrete subclasses 1 for each . Note that we only initiate subclasses which are with default constructor those without default constructors we judge them as canInitiate = false .
26,658
public boolean enter ( long maxWait , TimeUnit unit ) throws Exception { long startMs = System . currentTimeMillis ( ) ; boolean hasMaxWait = ( unit != null ) ; long maxWaitMs = hasMaxWait ? TimeUnit . MILLISECONDS . convert ( maxWait , unit ) : Long . MAX_VALUE ; boolean readyPathExists = ( client . checkExists ( ) . usingWatcher ( watcher ) . forPath ( readyPath ) != null ) ; client . create ( ) . creatingParentContainersIfNeeded ( ) . withMode ( CreateMode . EPHEMERAL ) . forPath ( ourPath ) ; boolean result = ( readyPathExists || internalEnter ( startMs , hasMaxWait , maxWaitMs ) ) ; if ( connectionLost . get ( ) ) { throw new KeeperException . ConnectionLossException ( ) ; } return result ; }
Enter the barrier and block until all members have entered or the timeout has elapsed
26,659
public synchronized boolean leave ( long maxWait , TimeUnit unit ) throws Exception { long startMs = System . currentTimeMillis ( ) ; boolean hasMaxWait = ( unit != null ) ; long maxWaitMs = hasMaxWait ? TimeUnit . MILLISECONDS . convert ( maxWait , unit ) : Long . MAX_VALUE ; return internalLeave ( startMs , hasMaxWait , maxWaitMs ) ; }
Leave the barrier and block until all members have left or the timeout has elapsed
26,660
public static < T > ServiceDiscoveryBuilder < T > builder ( Class < T > payloadClass ) { return new ServiceDiscoveryBuilder < T > ( payloadClass ) ; }
Return a new builder .
26,661
public static Future < ? > execute ( final CuratorFramework client , final Runnable runAfterConnection ) throws Exception { final ExecutorService executor = ThreadUtils . newSingleThreadExecutor ( ThreadUtils . getProcessName ( runAfterConnection . getClass ( ) ) ) ; Runnable internalCall = new Runnable ( ) { public void run ( ) { try { client . blockUntilConnected ( ) ; runAfterConnection . run ( ) ; } catch ( Exception e ) { ThreadUtils . checkInterrupted ( e ) ; log . error ( "An error occurred blocking until a connection is available" , e ) ; } finally { executor . shutdown ( ) ; } } } ; return executor . submit ( internalCall ) ; }
Spawns a new new background thread that will block until a connection is available and then execute the runAfterConnection logic
26,662
public byte [ ] element ( ) throws Exception { byte [ ] bytes = internalElement ( false , null ) ; if ( bytes == null ) { throw new NoSuchElementException ( ) ; } return bytes ; }
Return the head of the queue without modifying the queue .
26,663
public byte [ ] remove ( ) throws Exception { byte [ ] bytes = internalElement ( true , null ) ; if ( bytes == null ) { throw new NoSuchElementException ( ) ; } return bytes ; }
Attempts to remove the head of the queue and return it .
26,664
public boolean offer ( byte [ ] data ) throws Exception { String thisPath = ZKPaths . makePath ( path , PREFIX ) ; client . create ( ) . creatingParentContainersIfNeeded ( ) . withMode ( CreateMode . PERSISTENT_SEQUENTIAL ) . forPath ( thisPath , data ) ; return true ; }
Inserts data into queue .
26,665
private Single < SingleInsertionResult > insert ( String preparedSql , Object [ ] sqlParams ) { return Single . fromCallable ( ( ) -> { PreparedStatement statement = connection0 . prepareStatement ( preparedSql , PreparedStatement . RETURN_GENERATED_KEYS ) ; for ( int i = 0 ; i < sqlParams . length ; i ++ ) { statement . setObject ( i + 1 , sqlParams [ i ] ) ; } statement . execute ( ) ; ResultSet rs = statement . getGeneratedKeys ( ) ; Integer count = statement . getUpdateCount ( ) ; Long id ; if ( rs . next ( ) ) { id = rs . getLong ( 1 ) ; } else { id = null ; } rs . close ( ) ; statement . close ( ) ; return new SingleInsertionResult ( ) . setCount ( count ) . setId ( id ) . setPreparedSql ( preparedSql ) ; } ) ; }
Async single record insertion
26,666
public void setAdditionalFields ( String additionalFields ) { fields = ( Map < String , String > ) JSON . parse ( additionalFields . replaceAll ( "'" , "\"" ) ) ; }
GelfMessageProvider interface .
26,667
protected void subAppend ( LoggingEvent event ) { GelfMessage gelf = GelfMessageFactory . makeMessage ( layout , event , this ) ; this . qw . write ( gelf . toJson ( ) ) ; this . qw . write ( Layout . LINE_SEP ) ; if ( this . immediateFlush ) { this . qw . flush ( ) ; } }
the important parts .
26,668
public static < Request > Input create ( Request requestBean ) { if ( requestBean == null ) throw new IllegalArgumentException ( "request bean should not be null!" ) ; Class requestClass = requestBean . getClass ( ) ; return create ( requestClass ) ; }
generate an input object from the bean .
26,669
public static < T > QueueBuilder < T > builder ( CuratorFramework client , QueueConsumer < T > consumer , QueueSerializer < T > serializer , String queuePath ) { return new QueueBuilder < T > ( client , consumer , serializer , queuePath ) ; }
Allocate a new builder
26,670
protected static ByteBuffer [ ] toUDPBuffers ( GelfMessage message , ThreadLocal < ByteBuffer > writeBuffers , ThreadLocal < ByteBuffer > tempBuffers ) { while ( true ) { try { return message . toUDPBuffers ( getBuffer ( writeBuffers ) , getBuffer ( tempBuffers ) ) ; } catch ( BufferOverflowException e ) { enlargeBuffer ( writeBuffers ) ; enlargeBuffer ( tempBuffers ) ; } } }
Create UDP buffers and apply auto - buffer - enlarging if necessary .
26,671
protected static ByteBuffer toTCPBuffer ( GelfMessage message , ThreadLocal < ByteBuffer > writeBuffers ) { while ( true ) { try { return message . toTCPBuffer ( getBuffer ( writeBuffers ) ) ; } catch ( BufferOverflowException e ) { enlargeBuffer ( writeBuffers ) ; } } }
Create TCP buffer and apply auto - buffer - enlarging if necessary .
26,672
public static < K , V > Xmap < K , V > create ( Map < K , V > map ) { Xmap < K , V > xmap = new Xmap < > ( ) ; xmap . putAll ( map ) ; return xmap ; }
Clone a Xmap with all entries in the parameter map .
26,673
public static Single < Boolean > exists ( String path ) { return SingleRxXian . call ( "cosService" , "cosCheckFileExists" , new JSONObject ( ) { { put ( "path" , path ) ; } } ) . map ( UnitResponse :: dataToBoolean ) ; }
check whether the cos file exists
26,674
public static void replaceUnit ( Unit newUnit ) { String group = newUnit . getGroup ( ) . getName ( ) , unitName = newUnit . getName ( ) ; readWriteLock . writeLock ( ) . lock ( ) ; try { List < Unit > unitList = unitMap . get ( group ) ; unitList . removeIf ( unitToRemove -> Objects . equals ( unitToRemove . getName ( ) , unitName ) ) ; unitList . add ( newUnit ) ; Map < Class < ? extends Unit > , Unit > tmp = new HashMap < > ( ) ; for ( Map . Entry < Class < ? extends Unit > , Unit > classUnitEntry : searchUnitByClass . entrySet ( ) ) { Unit unit = classUnitEntry . getValue ( ) ; if ( unit . getGroup ( ) . getName ( ) . equals ( group ) && unit . getName ( ) . equals ( unitName ) ) { tmp . put ( classUnitEntry . getKey ( ) , newUnit ) ; break ; } } searchUnitByClass . putAll ( tmp ) ; searchUnitMap . put ( Unit . fullName ( group , unitName ) , newUnit ) ; } finally { readWriteLock . writeLock ( ) . unlock ( ) ; } }
Dynamically change the unit collections . Currently we use this for aop .
26,675
public static Group getGroupByUnitClass ( Class < ? extends Unit > unitClass ) { readWriteLock . readLock ( ) . lock ( ) ; try { return searchGroupByUnitClass . get ( unitClass ) ; } finally { readWriteLock . readLock ( ) . unlock ( ) ; } }
return the cached group singleton of the given unit class .
26,676
public static Unit getUnitByUnitClass ( Class < ? extends Unit > unitClass ) { readWriteLock . readLock ( ) . lock ( ) ; try { return searchUnitByClass . get ( unitClass ) ; } finally { readWriteLock . readLock ( ) . unlock ( ) ; } }
return the cached unit singleton of the given unit class .
26,677
public void ensure ( CuratorZookeeperClient client ) throws Exception { Helper localHelper = helper . get ( ) ; localHelper . ensure ( client , path , makeLastNode ) ; }
First time synchronizes and makes sure all nodes in the path are created . Subsequent calls with this instance are NOPs .
26,678
public static String generateDigitsString ( int length ) { StringBuffer buf = new StringBuffer ( length ) ; SecureRandom rand = new SecureRandom ( ) ; for ( int i = 0 ; i < length ; i ++ ) { buf . append ( rand . nextInt ( digits . length ) ) ; } return buf . toString ( ) ; }
Generates random string that contains digits only .
26,679
public String getHost ( ) { String hostAndPort = hostAndPort ( ) ; int indexOfMaohao = hostAndPort . indexOf ( ":" ) ; if ( indexOfMaohao == - 1 ) { return hostAndPort ; } else { return hostAndPort . substring ( 0 , indexOfMaohao ) ; } }
parse database url and get the host .
26,680
public int getPort ( ) { String hostAndPort = hostAndPort ( ) ; int indexOfMaohao = hostAndPort . indexOf ( ":" ) ; if ( indexOfMaohao == - 1 ) { return 3306 ; } else { return Integer . parseInt ( hostAndPort . substring ( indexOfMaohao + 1 ) ) ; } }
parse the database url and get the port .
26,681
private String hostAndPort ( ) { int start = url . indexOf ( "://" ) + 3 ; int end = url . indexOf ( "/" , start ) ; return url . substring ( start , end ) ; }
parse the url and get the host and port string .
26,682
public String getDatabase ( ) { int indexSlash = url . indexOf ( "/" , url . indexOf ( "://" ) + 3 ) ; int questionMarkIndex = url . indexOf ( "?" ) ; if ( questionMarkIndex != - 1 ) { return url . substring ( indexSlash + 1 , questionMarkIndex ) ; } else { return url . substring ( indexSlash + 1 ) ; } }
parse the databse url and get he database name
26,683
public static boolean set ( String value ) { if ( StringUtil . isEmpty ( value ) ) { throw new IllegalArgumentException ( "Can not set an empty msgId. If you want to clear msgId of current context, use clear() instead." ) ; } if ( Objects . equals ( value , MsgIdHolder . get ( ) ) ) { return false ; } else { singleton . set0 ( value ) ; return true ; } }
Set the msg id of current context
26,684
public static Map formatMap ( Map conditionMap ) { Map formattedMap = new HashMap ( ) ; formattedMap . putAll ( conditionMap ) ; forSpecialValue ( formattedMap ) ; return formattedMap ; }
format query map
26,685
public GelfMessageBuilder withField ( String key , String value ) { this . additionalFields . put ( key , value ) ; return this ; }
Add an additional field .
26,686
public void release ( ) throws Exception { Thread currentThread = Thread . currentThread ( ) ; LockData lockData = threadData . get ( currentThread ) ; if ( lockData == null ) { throw new IllegalMonitorStateException ( "You do not own the lock: " + basePath ) ; } int newLockCount = lockData . lockCount . decrementAndGet ( ) ; if ( newLockCount > 0 ) { return ; } if ( newLockCount < 0 ) { throw new IllegalMonitorStateException ( "Lock count has gone negative for lock: " + basePath ) ; } try { internals . releaseLock ( lockData . lockPath ) ; } finally { threadData . remove ( currentThread ) ; } }
Perform one release of the mutex if the calling thread is the same thread that acquired it . If the thread had made multiple calls to acquire the mutex will still be held when this method returns .
26,687
public Collection < String > getParticipantNodes ( ) throws Exception { return LockInternals . getParticipantNodes ( internals . getClient ( ) , basePath , internals . getLockName ( ) , internals . getDriver ( ) ) ; }
Return a sorted list of all current nodes participating in the lock
26,688
public static < T > T validate ( InputStream input , final Class < T > clazz ) throws IOException { return JSON . parseObject ( input , clazz ) ; }
Validates an input and returns an instance of a given class constructed from the input .
26,689
public static String getStaticNodeId ( String nodeId ) { String application = NodeIdBean . parse ( nodeId ) . getApplication ( ) ; if ( nodeId_to_StaticFinalId_map . get ( nodeId ) == null ) { Instance < NodeStatus > instance = ApplicationDiscovery . singleton . instance ( nodeId ) ; if ( instance != null ) { LOG . debug ( "Instance with given nodeId is found online, then initialize its static node id and put it into the map." ) ; onEvent ( nodeId ) ; } else { LOG . warn ( new IllegalArgumentException ( "Bad node id or the node is offline: " + nodeId ) ) ; } } return nodeId_to_StaticFinalId_map . get ( nodeId ) == null ? application + NodeIdBean . splitter + "null" : application + NodeIdBean . splitter + nodeId_to_StaticFinalId_map . get ( nodeId ) ; }
Lasy - create staticNodeId for the given node id .
26,690
public GelfMessage build ( ) { GelfMessage gelfMessage = new PoolingGelfMessage ( shortMessage , fullMessage , javaTimestamp , level , poolHolder ) ; gelfMessage . addFields ( additionalFields ) ; gelfMessage . setMaximumMessageSize ( maximumMessageSize ) ; gelfMessage . setVersion ( version ) ; gelfMessage . setHost ( host ) ; gelfMessage . setJavaTimestamp ( javaTimestamp ) ; gelfMessage . setFacility ( facility ) ; gelfMessage . setAdditionalFieldTypes ( additionalFieldTypes ) ; return gelfMessage ; }
Build a new Gelf message based on the builder settings .
26,691
public static < T > Set < Class < ? extends T > > getNonAbstractSubclasses ( Class < T > clazz ) { return ClassGraphUtil . getNonAbstractSubClasses ( clazz ) ; }
scan and get the concrete subclasses . Note 1 . we only scan for the default package . 2 . This method is too expensive it is advised to cache the result .
26,692
public static < T > List < T > getWithAnnotatedClass ( Class annotationClass , String packages ) { return new ArrayList < T > ( ) { { addAll ( ClassGraphUtil . getWithAnnotatedClass ( annotationClass , packages ) ) ; } } ; }
Scan and get classes under certain annotation and initiate them . Note that we only scan for the default package .
26,693
public static Class getPrimitiveType ( Class type ) { if ( type == int . class || type == Integer . class ) { return int . class ; } else if ( type == long . class || type == Long . class ) { return long . class ; } else if ( type == short . class || type == Short . class ) { return short . class ; } else if ( type == double . class || type == Double . class ) { return double . class ; } else if ( type == float . class || type == Float . class ) { return float . class ; } else if ( type == char . class || type == Character . class ) { return char . class ; } else if ( type == byte . class || type == Byte . class ) { return byte . class ; } else if ( type == boolean . class || type == Boolean . class ) { return boolean . class ; } throw new IllegalArgumentException ( "Type '" + type + "' can not be converted to primitive type." ) ; }
getPrimitiveType of the given class
26,694
@ SuppressWarnings ( "unchecked" ) private static < T > T cast ( Object obj , Class < T > clazz ) { if ( obj == null ) { return null ; } if ( clazz == null ) { throw new IllegalArgumentException ( "parameter 'Class<T> clazz' is not allowed to be null." ) ; } if ( clazz . isEnum ( ) && obj instanceof String ) { Class < Enum > enumClazz = ( Class < Enum > ) clazz ; return ( T ) Enum . valueOf ( enumClazz , obj . toString ( ) ) ; } if ( clazz . isPrimitive ( ) ) { if ( clazz == Integer . TYPE ) { clazz = ( Class < T > ) Integer . class ; } else if ( clazz == Long . TYPE ) { clazz = ( Class < T > ) Long . class ; } else if ( clazz == Short . TYPE ) { clazz = ( Class < T > ) Short . class ; } else if ( clazz == Double . TYPE ) { clazz = ( Class < T > ) Double . class ; } else if ( clazz == Float . TYPE ) { clazz = ( Class < T > ) Float . class ; } else if ( clazz == Character . TYPE ) { clazz = ( Class < T > ) Character . class ; } else if ( clazz == Byte . TYPE ) { clazz = ( Class < T > ) Byte . class ; } else if ( clazz == Boolean . TYPE ) { clazz = ( Class < T > ) Boolean . class ; } } return clazz . cast ( obj ) ; }
make a forced class casting .
26,695
@ SuppressWarnings ( "all" ) public static < T > Set < T > toTypedSet ( Object data , Class < T > type ) { Set < T > setResult = new HashSet < > ( ) ; if ( data == null ) { return setResult ; } if ( data instanceof Collection ) { Collection collection = ( Collection ) data ; for ( Object o : collection ) { setResult . add ( Reflection . toType ( o , type ) ) ; } return setResult ; } if ( data . getClass ( ) . isArray ( ) ) { for ( Object o : ArrayUtil . toObjectArray ( data ) ) { setResult . add ( Reflection . toType ( o , type ) ) ; } return setResult ; } setResult . add ( Reflection . toType ( data , type ) ) ; return setResult ; }
Adapt the data object to the given typed hash set it is safe to make a cast even if the given data is not a set or the element is not the given type .
26,696
private static List < Field > getAllFieldsRec ( Class clazz , List < Field > fieldList ) { Class superClazz = clazz . getSuperclass ( ) ; if ( superClazz != null ) { getAllFieldsRec ( superClazz , fieldList ) ; } fieldList . addAll ( ArrayUtil . toList ( clazz . getDeclaredFields ( ) , Field . class ) ) ; return fieldList ; }
recursive method .
26,697
public void start ( ) { Preconditions . checkState ( state . compareAndSet ( State . LATENT , State . STARTED ) , "Cannot be started more than once" ) ; service . submit ( new Callable < Object > ( ) { public Object call ( ) throws Exception { processEvents ( ) ; return null ; } } ) ; }
Start the manager
26,698
public synchronized boolean addStateChange ( ConnectionState newConnectionState ) { if ( state . get ( ) != State . STARTED ) { return false ; } ConnectionState previousState = currentConnectionState ; if ( previousState == newConnectionState ) { return false ; } currentConnectionState = newConnectionState ; ConnectionState localState = newConnectionState ; boolean isNegativeMessage = ( ( newConnectionState == ConnectionState . LOST ) || ( newConnectionState == ConnectionState . SUSPENDED ) || ( newConnectionState == ConnectionState . READ_ONLY ) ) ; if ( ! isNegativeMessage && initialConnectMessageSent . compareAndSet ( false , true ) ) { localState = ConnectionState . CONNECTED ; } postState ( localState ) ; return true ; }
Post a state change . If the manager is already in that state the change is ignored . Otherwise the change is queued for listeners .
26,699
public long getSessionId ( ) { long sessionId = 0 ; try { ZooKeeper zk = zooKeeper . getZooKeeper ( ) ; if ( zk != null ) { sessionId = zk . getSessionId ( ) ; } } catch ( Exception e ) { } return sessionId ; }
Return the current session id