idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
153,900
@ Override protected String getServiceName ( final String methodName ) { if ( methodName != null ) { int ndx = methodName . indexOf ( this . separator ) ; if ( ndx > 0 ) { return methodName . substring ( 0 , ndx ) ; } } return methodName ; }
Get the service name from the methodNode . JSON - RPC methods with the form Service . method will result in Service being returned in this case .
67
29
153,901
public void handle ( ResourceRequest request , ResourceResponse response ) throws IOException { logger . debug ( "Handing ResourceRequest {}" , request . getMethod ( ) ) ; response . setContentType ( contentType ) ; InputStream input = getRequestStream ( request ) ; OutputStream output = response . getPortletOutputStream ( ) ; handleRequest ( input , output ) ; // fix to not flush within handleRequest() but outside so http status code can be set output . flush ( ) ; }
Handles a portlet request .
104
7
153,902
public void handle ( HttpServletRequest request , HttpServletResponse response ) throws IOException { logger . debug ( "Handling HttpServletRequest {}" , request ) ; response . setContentType ( contentType ) ; OutputStream output = response . getOutputStream ( ) ; InputStream input = getRequestStream ( request ) ; int result = ErrorResolver . JsonError . PARSE_ERROR . code ; int contentLength = 0 ; ByteArrayOutputStream byteOutput = new ByteArrayOutputStream ( ) ; try { String acceptEncoding = request . getHeader ( ACCEPT_ENCODING ) ; result = handleRequest0 ( input , output , acceptEncoding , response , byteOutput ) ; contentLength = byteOutput . size ( ) ; } catch ( Throwable t ) { if ( StreamEndedException . class . isInstance ( t ) ) { logger . debug ( "Bad request: empty contents!" ) ; } else { logger . error ( t . getMessage ( ) , t ) ; } } int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider . INSTANCE . getHttpStatusCode ( result ) : httpStatusCodeProvider . getHttpStatusCode ( result ) ; response . setStatus ( httpStatusCode ) ; response . setContentLength ( contentLength ) ; byteOutput . writeTo ( output ) ; output . flush ( ) ; }
Handles a servlet request .
297
7
153,903
public void stop ( ) throws InterruptedException { if ( ! isStarted . get ( ) ) { throw new IllegalStateException ( "The StreamServer is not started" ) ; } stopServer ( ) ; stopClients ( ) ; closeSocket ( ) ; try { waitForServerToTerminate ( ) ; isStarted . set ( false ) ; stopServer ( ) ; } catch ( InterruptedException e ) { logger . error ( "InterruptedException while waiting for termination" , e ) ; throw e ; } }
Stops the server thread .
111
6
153,904
private void closeQuietly ( Closeable c ) { if ( c != null ) { try { c . close ( ) ; } catch ( Throwable t ) { logger . warn ( "Error closing, ignoring" , t ) ; } } }
Closes something quietly .
52
5
153,905
protected Class < ? > [ ] getHandlerInterfaces ( final String serviceName ) { if ( remoteInterface != null ) { return new Class < ? > [ ] { remoteInterface } ; } else if ( Proxy . isProxyClass ( handler . getClass ( ) ) ) { return handler . getClass ( ) . getInterfaces ( ) ; } else { return new Class < ? > [ ] { handler . getClass ( ) } ; } }
Returns the handler s class or interfaces . The variable serviceName is ignored in this class .
94
18
153,906
private ErrorObjectWithJsonError createResponseError ( String jsonRpc , Object id , JsonError errorObject ) { ObjectNode response = mapper . createObjectNode ( ) ; ObjectNode error = mapper . createObjectNode ( ) ; error . put ( ERROR_CODE , errorObject . code ) ; error . put ( ERROR_MESSAGE , errorObject . message ) ; if ( errorObject . data != null ) { error . set ( DATA , mapper . valueToTree ( errorObject . data ) ) ; } response . put ( JSONRPC , jsonRpc ) ; if ( Integer . class . isInstance ( id ) ) { response . put ( ID , Integer . class . cast ( id ) . intValue ( ) ) ; } else if ( Long . class . isInstance ( id ) ) { response . put ( ID , Long . class . cast ( id ) . longValue ( ) ) ; } else if ( Float . class . isInstance ( id ) ) { response . put ( ID , Float . class . cast ( id ) . floatValue ( ) ) ; } else if ( Double . class . isInstance ( id ) ) { response . put ( ID , Double . class . cast ( id ) . doubleValue ( ) ) ; } else if ( BigDecimal . class . isInstance ( id ) ) { response . put ( ID , BigDecimal . class . cast ( id ) ) ; } else { response . put ( ID , String . class . cast ( id ) ) ; } response . set ( ERROR , error ) ; return new ErrorObjectWithJsonError ( response , errorObject ) ; }
Convenience method for creating an error response .
350
10
153,907
private ObjectNode createResponseSuccess ( String jsonRpc , Object id , JsonNode result ) { ObjectNode response = mapper . createObjectNode ( ) ; response . put ( JSONRPC , jsonRpc ) ; if ( Integer . class . isInstance ( id ) ) { response . put ( ID , Integer . class . cast ( id ) . intValue ( ) ) ; } else if ( Long . class . isInstance ( id ) ) { response . put ( ID , Long . class . cast ( id ) . longValue ( ) ) ; } else if ( Float . class . isInstance ( id ) ) { response . put ( ID , Float . class . cast ( id ) . floatValue ( ) ) ; } else if ( Double . class . isInstance ( id ) ) { response . put ( ID , Double . class . cast ( id ) . doubleValue ( ) ) ; } else if ( BigDecimal . class . isInstance ( id ) ) { response . put ( ID , BigDecimal . class . cast ( id ) ) ; } else { response . put ( ID , String . class . cast ( id ) ) ; } response . set ( RESULT , result ) ; return response ; }
Creates a success response .
258
6
153,908
private void initRestTemplate ( ) { boolean isContainsConverter = false ; for ( HttpMessageConverter < ? > httpMessageConverter : this . restTemplate . getMessageConverters ( ) ) { if ( MappingJacksonRPC2HttpMessageConverter . class . isAssignableFrom ( httpMessageConverter . getClass ( ) ) ) { isContainsConverter = true ; break ; } } if ( ! isContainsConverter ) { final MappingJacksonRPC2HttpMessageConverter messageConverter = new MappingJacksonRPC2HttpMessageConverter ( ) ; messageConverter . setObjectMapper ( this . getObjectMapper ( ) ) ; final List < HttpMessageConverter < ? > > restMessageConverters = new ArrayList <> ( ) ; restMessageConverters . addAll ( this . restTemplate . getMessageConverters ( ) ) ; // Place JSON-RPC converter on the first place! restMessageConverters . add ( 0 , messageConverter ) ; this . restTemplate . setMessageConverters ( restMessageConverters ) ; } // use specific JSON-RPC error handler if it has not been changed to custom if ( restTemplate . getErrorHandler ( ) instanceof org . springframework . web . client . DefaultResponseErrorHandler ) { restTemplate . setErrorHandler ( JsonRpcResponseErrorHandler . INSTANCE ) ; } }
Check RestTemplate contains required converters
322
7
153,909
private HttpURLConnection prepareConnection ( Map < String , String > extraHeaders ) throws IOException { // create URLConnection HttpURLConnection connection = ( HttpURLConnection ) serviceUrl . openConnection ( connectionProxy ) ; connection . setConnectTimeout ( connectionTimeoutMillis ) ; connection . setReadTimeout ( readTimeoutMillis ) ; connection . setAllowUserInteraction ( false ) ; connection . setDefaultUseCaches ( false ) ; connection . setDoInput ( true ) ; connection . setDoOutput ( true ) ; connection . setUseCaches ( false ) ; connection . setInstanceFollowRedirects ( true ) ; connection . setRequestMethod ( "POST" ) ; setupSsl ( connection ) ; addHeaders ( extraHeaders , connection ) ; return connection ; }
Prepares a connection to the server .
167
8
153,910
public static Object createCompositeServiceProxy ( ClassLoader classLoader , Object [ ] services , boolean allowMultipleInheritance ) { return createCompositeServiceProxy ( classLoader , services , null , allowMultipleInheritance ) ; }
Creates a composite service using all of the given services .
51
12
153,911
public static Object createCompositeServiceProxy ( ClassLoader classLoader , Object [ ] services , Class < ? > [ ] serviceInterfaces , boolean allowMultipleInheritance ) { Set < Class < ? > > interfaces = collectInterfaces ( services , serviceInterfaces ) ; final Map < Class < ? > , Object > serviceClassToInstanceMapping = buildServiceMap ( services , allowMultipleInheritance , interfaces ) ; // now create the proxy return Proxy . newProxyInstance ( classLoader , interfaces . toArray ( new Class < ? > [ 0 ] ) , new InvocationHandler ( ) { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { Class < ? > clazz = method . getDeclaringClass ( ) ; if ( clazz == Object . class ) { return proxyObjectMethods ( method , proxy , args ) ; } return method . invoke ( serviceClassToInstanceMapping . get ( clazz ) , args ) ; } } ) ; }
Creates a composite service using all of the given services and implementing the given interfaces .
214
17
153,912
private void registerJsonProxyBean ( DefaultListableBeanFactory defaultListableBeanFactory , String className , String path ) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder . rootBeanDefinition ( JsonProxyFactoryBean . class ) . addPropertyValue ( "serviceUrl" , appendBasePath ( path ) ) . addPropertyValue ( "serviceInterface" , className ) ; if ( objectMapper != null ) { beanDefinitionBuilder . addPropertyValue ( "objectMapper" , objectMapper ) ; } if ( contentType != null ) { beanDefinitionBuilder . addPropertyValue ( "contentType" , contentType ) ; } defaultListableBeanFactory . registerBeanDefinition ( className + "-clientProxy" , beanDefinitionBuilder . getBeanDefinition ( ) ) ; }
Registers a new proxy bean with the bean factory .
174
11
153,913
private String appendBasePath ( String path ) { try { return new URL ( baseUrl , path ) . toString ( ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( format ( "Cannot combine URLs '%s' and '%s' to valid URL." , baseUrl , path ) , e ) ; } }
Appends the base path to the path found in the interface .
78
13
153,914
static Set < Method > findCandidateMethods ( Class < ? > [ ] classes , String name ) { StringBuilder sb = new StringBuilder ( ) ; for ( Class < ? > clazz : classes ) { sb . append ( clazz . getName ( ) ) . append ( "::" ) ; } String cacheKey = sb . append ( name ) . toString ( ) ; if ( methodCache . containsKey ( cacheKey ) ) { return methodCache . get ( cacheKey ) ; } Set < Method > methods = new HashSet <> ( ) ; for ( Class < ? > clazz : classes ) { for ( Method method : clazz . getMethods ( ) ) { if ( method . isAnnotationPresent ( JsonRpcMethod . class ) ) { JsonRpcMethod methodAnnotation = method . getAnnotation ( JsonRpcMethod . class ) ; if ( methodAnnotation . required ( ) ) { if ( methodAnnotation . value ( ) . equals ( name ) ) { methods . add ( method ) ; } } else if ( methodAnnotation . value ( ) . equals ( name ) || method . getName ( ) . equals ( name ) ) { methods . add ( method ) ; } } else if ( method . getName ( ) . equals ( name ) ) { methods . add ( method ) ; } } } methods = Collections . unmodifiableSet ( methods ) ; methodCache . put ( cacheKey , methods ) ; return methods ; }
Finds methods with the given name on the given class .
318
12
153,915
public static Object parseArguments ( Method method , Object [ ] arguments ) { JsonRpcParamsPassMode paramsPassMode = JsonRpcParamsPassMode . AUTO ; JsonRpcMethod jsonRpcMethod = getAnnotation ( method , JsonRpcMethod . class ) ; if ( jsonRpcMethod != null ) paramsPassMode = jsonRpcMethod . paramsPassMode ( ) ; Map < String , Object > namedParams = getNamedParameters ( method , arguments ) ; switch ( paramsPassMode ) { case ARRAY : if ( namedParams . size ( ) > 0 ) { Object [ ] parsed = new Object [ namedParams . size ( ) ] ; int i = 0 ; for ( Object value : namedParams . values ( ) ) { parsed [ i ++ ] = value ; } return parsed ; } else { return arguments != null ? arguments : new Object [ ] { } ; } case OBJECT : if ( namedParams . size ( ) > 0 ) { return namedParams ; } else { if ( arguments == null ) { return new Object [ ] { } ; } throw new IllegalArgumentException ( "OBJECT parameters pass mode is impossible without declaring JsonRpcParam annotations for all parameters on method " + method . getName ( ) ) ; } case AUTO : default : if ( namedParams . size ( ) > 0 ) { return namedParams ; } else { return arguments != null ? arguments : new Object [ ] { } ; } } }
Parses the given arguments for the given method optionally turning them into named parameters .
323
17
153,916
private void addHeaders ( HttpRequest request , Map < String , String > headers ) { for ( Map . Entry < String , String > key : headers . entrySet ( ) ) { request . addHeader ( key . getKey ( ) , key . getValue ( ) ) ; } }
Set the request headers .
62
5
153,917
private Object invokeAndReadResponse ( String methodName , Object argument , Type returnType , OutputStream output , InputStream input , String id ) throws Throwable { invoke ( methodName , argument , output , id ) ; return readResponse ( returnType , input , id ) ; }
Invokes the given method on the remote service passing the given arguments and reads a response .
58
18
153,918
private Object readResponse ( Type returnType , InputStream input , String id ) throws Throwable { ReadContext context = ReadContext . getReadContext ( input , mapper ) ; ObjectNode jsonObject = getValidResponse ( id , context ) ; notifyAnswerListener ( jsonObject ) ; handleErrorResponse ( jsonObject ) ; if ( hasResult ( jsonObject ) ) { if ( isReturnTypeInvalid ( returnType ) ) { return null ; } return constructResponseObject ( returnType , jsonObject ) ; } // no return type return null ; }
Reads a JSON - PRC response from the server . This blocks until a response is received . If an id is given responses that do not correspond are disregarded .
114
34
153,919
private ObjectNode internalCreateRequest ( String methodName , Object arguments , String id ) { final ObjectNode request = mapper . createObjectNode ( ) ; addId ( id , request ) ; addProtocolAndMethod ( methodName , request ) ; addParameters ( arguments , request ) ; addAdditionalHeaders ( request ) ; notifyBeforeRequestListener ( request ) ; return request ; }
Creates RPC request .
80
5
153,920
public void invokeNotification ( String methodName , Object argument , OutputStream output ) throws IOException { writeRequest ( methodName , argument , output , null ) ; output . flush ( ) ; }
Invokes the given method on the remote service passing the given argument without reading or expecting a return response .
41
21
153,921
private JsonEncoding getJsonEncoding ( MediaType contentType ) { if ( contentType != null && contentType . getCharset ( ) != null ) { Charset charset = contentType . getCharset ( ) ; for ( JsonEncoding encoding : JsonEncoding . values ( ) ) { if ( charset . name ( ) . equals ( encoding . getJavaName ( ) ) ) { return encoding ; } } } return JsonEncoding . UTF8 ; }
Determine the JSON encoding to use for the given content type .
108
14
153,922
private void registerServiceProxy ( DefaultListableBeanFactory defaultListableBeanFactory , String servicePath , String serviceBeanName ) { BeanDefinitionBuilder builder = BeanDefinitionBuilder . rootBeanDefinition ( JsonServiceExporter . class ) . addPropertyReference ( "service" , serviceBeanName ) ; BeanDefinition serviceBeanDefinition = findBeanDefinition ( defaultListableBeanFactory , serviceBeanName ) ; for ( Class < ? > currentInterface : getBeanInterfaces ( serviceBeanDefinition , defaultListableBeanFactory . getBeanClassLoader ( ) ) ) { if ( currentInterface . isAnnotationPresent ( JsonRpcService . class ) ) { String serviceInterface = currentInterface . getName ( ) ; logger . debug ( "Registering interface '{}' for JSON-RPC bean [{}]." , serviceInterface , serviceBeanName ) ; builder . addPropertyValue ( "serviceInterface" , serviceInterface ) ; break ; } } if ( objectMapper != null ) { builder . addPropertyValue ( "objectMapper" , objectMapper ) ; } if ( errorResolver != null ) { builder . addPropertyValue ( "errorResolver" , errorResolver ) ; } if ( invocationListener != null ) { builder . addPropertyValue ( "invocationListener" , invocationListener ) ; } if ( registerTraceInterceptor != null ) { builder . addPropertyValue ( "registerTraceInterceptor" , registerTraceInterceptor ) ; } if ( httpStatusCodeProvider != null ) { builder . addPropertyValue ( "httpStatusCodeProvider" , httpStatusCodeProvider ) ; } if ( convertedParameterTransformer != null ) { builder . addPropertyValue ( "convertedParameterTransformer" , convertedParameterTransformer ) ; } builder . addPropertyValue ( "backwardsCompatible" , backwardsCompatible ) ; builder . addPropertyValue ( "rethrowExceptions" , rethrowExceptions ) ; builder . addPropertyValue ( "allowExtraParams" , allowExtraParams ) ; builder . addPropertyValue ( "allowLessParams" , allowLessParams ) ; defaultListableBeanFactory . registerBeanDefinition ( servicePath , builder . getBeanDefinition ( ) ) ; }
Registers the new beans with the bean factory .
486
10
153,923
Optional < EntityDescriptor > referencingEntity ( AttributeDescriptor attribute ) { if ( ! Names . isEmpty ( attribute . referencedTable ( ) ) ) { // match by table name return entities . values ( ) . stream ( ) . filter ( entity -> entity . tableName ( ) . equalsIgnoreCase ( attribute . referencedTable ( ) ) ) . findFirst ( ) ; } else if ( ! Names . isEmpty ( attribute . referencedType ( ) ) ) { // match by type name Optional < TypeKind > primitiveType = Stream . of ( TypeKind . values ( ) ) . filter ( TypeKind :: isPrimitive ) . filter ( kind -> kind . toString ( ) . toLowerCase ( ) . equals ( attribute . referencedType ( ) ) ) . findFirst ( ) ; if ( ! primitiveType . isPresent ( ) ) { QualifiedName referencedType = new QualifiedName ( attribute . referencedType ( ) ) ; return entityByName ( referencedType ) ; } // else attribute is basic foreign key and not referring to an entity } else { TypeMirror referencedType = attribute . typeMirror ( ) ; if ( attribute . isIterable ( ) ) { referencedType = collectionElementType ( referencedType ) ; } TypeElement referencedElement = ( TypeElement ) types . asElement ( referencedType ) ; if ( referencedElement != null ) { String referencedName = referencedElement . getSimpleName ( ) . toString ( ) ; return entities . values ( ) . stream ( ) . filter ( entity -> match ( entity , referencedName ) ) . findFirst ( ) ; } } return Optional . empty ( ) ; }
Given a association attribute in an Entity find the Entity the attribute is referencing .
345
15
153,924
Optional < ? extends AttributeDescriptor > referencingAttribute ( AttributeDescriptor attribute , EntityDescriptor referenced ) { String referencedColumn = attribute . referencedColumn ( ) ; if ( Names . isEmpty ( referencedColumn ) ) { // using the id List < AttributeDescriptor > keys = referenced . attributes ( ) . stream ( ) . filter ( AttributeDescriptor :: isKey ) . collect ( Collectors . toList ( ) ) ; if ( keys . size ( ) == 1 ) { return Optional . of ( keys . get ( 0 ) ) ; } else { return keys . stream ( ) . filter ( other -> other . typeMirror ( ) . equals ( attribute . typeMirror ( ) ) ) . findFirst ( ) ; } } else { return referenced . attributes ( ) . stream ( ) . filter ( other -> other . name ( ) . equals ( referencedColumn ) ) . findFirst ( ) ; } }
Given an attribute in a given type finds the corresponding attribute that it is referencing in that referencing type .
199
20
153,925
Set < AttributeDescriptor > mappedAttributes ( EntityDescriptor entity , AttributeDescriptor attribute , EntityDescriptor referenced ) { String mappedBy = attribute . mappedBy ( ) ; if ( Names . isEmpty ( mappedBy ) ) { return referenced . attributes ( ) . stream ( ) . filter ( other -> other . cardinality ( ) != null ) . filter ( other -> referencingEntity ( other ) . isPresent ( ) ) . filter ( other -> referencingEntity ( other ) . orElseThrow ( IllegalStateException :: new ) == entity ) . collect ( Collectors . toSet ( ) ) ; } else { return referenced . attributes ( ) . stream ( ) . filter ( other -> other . name ( ) . equals ( mappedBy ) ) . collect ( Collectors . toSet ( ) ) ; } }
Given an association in an entity find the attributes it maps onto in the referenced entity .
174
17
153,926
protected void bindBlobLiteral ( int index , byte [ ] value ) { if ( blobLiterals == null ) { blobLiterals = new LinkedHashMap <> ( ) ; } blobLiterals . put ( index , value ) ; }
inlines a blob literal into the sql statement since it can t be used as bind parameter
54
18
153,927
public void createIndexes ( Connection connection , TableCreationMode mode ) { ArrayList < Type < ? > > sorted = sortTypes ( ) ; for ( Type < ? > type : sorted ) { createIndexes ( connection , mode , type ) ; } }
Creates all indexes in the model .
55
8
153,928
public String createTablesString ( TableCreationMode mode ) { ArrayList < Type < ? > > sorted = sortTypes ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( Type < ? > type : sorted ) { String sql = tableCreateStatement ( type , mode ) ; sb . append ( sql ) ; sb . append ( ";\n" ) ; } return sb . toString ( ) ; }
Convenience method to generated the create table statements as a string .
94
14
153,929
public void dropTables ( ) { try ( Connection connection = getConnection ( ) ; Statement statement = connection . createStatement ( ) ) { ArrayList < Type < ? > > reversed = sortTypes ( ) ; Collections . reverse ( reversed ) ; executeDropStatements ( statement , reversed ) ; } catch ( SQLException e ) { throw new TableModificationException ( e ) ; } }
Drop all tables in the schema . Note if the platform supports if exists that will be used in the statement if not and the table doesn t exist an exception will be thrown .
83
35
153,930
public void dropTable ( Type < ? > type ) { try ( Connection connection = getConnection ( ) ; Statement statement = connection . createStatement ( ) ) { executeDropStatements ( statement , Collections . < Type < ? > > singletonList ( type ) ) ; } catch ( SQLException e ) { throw new TableModificationException ( e ) ; } }
Drops a single table in the schema .
78
9
153,931
public < T > String tableCreateStatement ( Type < T > type , TableCreationMode mode ) { String tableName = type . getName ( ) ; QueryBuilder qb = createQueryBuilder ( ) ; qb . keyword ( CREATE ) ; if ( type . getTableCreateAttributes ( ) != null ) { for ( String attribute : type . getTableCreateAttributes ( ) ) { qb . append ( attribute , true ) ; } } qb . keyword ( TABLE ) ; if ( mode == TableCreationMode . CREATE_NOT_EXISTS ) { qb . keyword ( IF , NOT , EXISTS ) ; } qb . tableName ( tableName ) ; qb . openParenthesis ( ) ; int index = 0 ; // columns to define first Predicate < Attribute > filter = new Predicate < Attribute > ( ) { @ Override public boolean test ( Attribute value ) { if ( value . isVersion ( ) && ! platform . versionColumnDefinition ( ) . createColumn ( ) ) { return false ; } if ( platform . supportsInlineForeignKeyReference ( ) ) { return ! value . isForeignKey ( ) && ! value . isAssociation ( ) ; } else { return value . isForeignKey ( ) || ! value . isAssociation ( ) ; } } } ; Set < Attribute < T , ? > > attributes = type . getAttributes ( ) ; for ( Attribute attribute : attributes ) { if ( filter . test ( attribute ) ) { if ( index > 0 ) { qb . comma ( ) ; } createColumn ( qb , attribute ) ; index ++ ; } } // foreign keys for ( Attribute attribute : attributes ) { if ( attribute . isForeignKey ( ) ) { if ( index > 0 ) { qb . comma ( ) ; } createForeignKeyColumn ( qb , attribute , true , false ) ; index ++ ; } } // composite primary key if ( type . getKeyAttributes ( ) . size ( ) > 1 ) { if ( index > 0 ) { qb . comma ( ) ; } qb . keyword ( PRIMARY , KEY ) ; qb . openParenthesis ( ) ; qb . commaSeparated ( type . getKeyAttributes ( ) , new QueryBuilder . Appender < Attribute < T , ? > > ( ) { @ Override public void append ( QueryBuilder qb , Attribute < T , ? > value ) { qb . attribute ( value ) ; } } ) ; qb . closeParenthesis ( ) ; } qb . closeParenthesis ( ) ; return qb . toString ( ) ; }
Generates the create table for a specific type .
560
10
153,932
@ Override public T copy ( final T obj ) { try { return serializer . read ( serializer . serialize ( obj ) ) ; } catch ( ClassNotFoundException e ) { throw new SerializerException ( "Copying failed." , e ) ; } }
Returns a copy of the passed in instance by serializing and deserializing it .
57
17
153,933
@ Override public void registerXAResource ( String uniqueName , XAResource xaResource ) { Ehcache3XAResourceProducer xaResourceProducer = producers . get ( uniqueName ) ; if ( xaResourceProducer == null ) { xaResourceProducer = new Ehcache3XAResourceProducer ( ) ; xaResourceProducer . setUniqueName ( uniqueName ) ; // the initial xaResource must be added before init() can be called xaResourceProducer . addXAResource ( xaResource ) ; Ehcache3XAResourceProducer previous = producers . putIfAbsent ( uniqueName , xaResourceProducer ) ; if ( previous == null ) { xaResourceProducer . init ( ) ; } else { previous . addXAResource ( xaResource ) ; } } else { xaResourceProducer . addXAResource ( xaResource ) ; } }
Register an XAResource of a cache with BTM . The first time a XAResource is registered a new EhCacheXAResourceProducer is created to hold it .
207
39
153,934
@ Override public void unregisterXAResource ( String uniqueName , XAResource xaResource ) { Ehcache3XAResourceProducer xaResourceProducer = producers . get ( uniqueName ) ; if ( xaResourceProducer != null ) { boolean found = xaResourceProducer . removeXAResource ( xaResource ) ; if ( ! found ) { throw new IllegalStateException ( "no XAResource " + xaResource + " found in XAResourceProducer with name " + uniqueName ) ; } if ( xaResourceProducer . isEmpty ( ) ) { xaResourceProducer . close ( ) ; producers . remove ( uniqueName ) ; } } else { throw new IllegalStateException ( "no XAResourceProducer registered with name " + uniqueName ) ; } }
Unregister an XAResource of a cache from BTM .
182
14
153,935
public void compact ( ServerStoreProxy . ChainEntry entry ) { ChainBuilder builder = new ChainBuilder ( ) ; for ( PutOperation < K , V > operation : resolveAll ( entry ) . values ( ) ) { builder = builder . add ( codec . encode ( operation ) ) ; } Chain compacted = builder . build ( ) ; if ( compacted . length ( ) < entry . length ( ) ) { entry . replaceAtHead ( compacted ) ; } }
Compacts the given chain entry by resolving every key within .
98
12
153,936
protected Map < K , PutOperation < K , V > > resolveAll ( Chain chain ) { //absent hash-collisions this should always be a 1 entry map Map < K , PutOperation < K , V > > compacted = new HashMap <> ( 2 ) ; for ( Element element : chain ) { ByteBuffer payload = element . getPayload ( ) ; Operation < K , V > operation = codec . decode ( payload ) ; compacted . compute ( operation . getKey ( ) , ( k , v ) -> applyOperation ( k , v , operation ) ) ; } return compacted ; }
Resolves all keys within the given chain to their equivalent put operations .
129
14
153,937
public static long parse ( String configuredMemorySize ) throws IllegalArgumentException { MemorySize size = parseIncludingUnit ( configuredMemorySize ) ; return size . calculateMemorySizeInBytes ( ) ; }
Parse a String containing a human - readable memory size .
42
12
153,938
public boolean abandonLeadership ( String entityIdentifier , boolean healthyConnection ) { Hold hold = maintenanceHolds . remove ( entityIdentifier ) ; return ( hold != null ) && healthyConnection && silentlyUnlock ( hold , entityIdentifier ) ; }
Proactively abandon leadership before closing connection .
52
8
153,939
private boolean abandonFetchHolds ( String entityIdentifier , boolean healthyConnection ) { Hold hold = fetchHolds . remove ( entityIdentifier ) ; return ( hold != null ) && healthyConnection && silentlyUnlock ( hold , entityIdentifier ) ; }
Proactively abandon any READ holds before closing connection .
54
10
153,940
private void init ( ) { ServerSideServerStore serverStore = ehcacheStateService . getStore ( storeIdentifier ) ; ServerStoreBinding serverStoreBinding = new ServerStoreBinding ( storeIdentifier , serverStore ) ; CompletableFuture < Void > r1 = managementRegistry . register ( serverStoreBinding ) ; ServerSideConfiguration . Pool pool = ehcacheStateService . getDedicatedResourcePool ( storeIdentifier ) ; CompletableFuture < Void > allOf ; if ( pool != null ) { allOf = CompletableFuture . allOf ( r1 , managementRegistry . register ( new PoolBinding ( storeIdentifier , pool , PoolBinding . AllocationType . DEDICATED ) ) ) ; } else { allOf = r1 ; } allOf . thenRun ( ( ) -> { managementRegistry . refresh ( ) ; managementRegistry . pushServerEntityNotification ( serverStoreBinding , EHCACHE_SERVER_STORE_CREATED . name ( ) ) ; } ) ; }
the goal of the following code is to send the management metadata from the entity into the monitoring tree AFTER the entity creation
225
23
153,941
public ClusteringServiceConfigurationBuilder timeouts ( Builder < ? extends Timeouts > timeoutsBuilder ) { return new ClusteringServiceConfigurationBuilder ( this . connectionSource , timeoutsBuilder . build ( ) , this . autoCreate ) ; }
Adds timeouts . Read operations which time out return a result comparable to a cache miss . Write operations which time out won t do anything . Lifecycle operations which time out will fail with exception
51
38
153,942
@ Deprecated public ClusteringServiceConfigurationBuilder readOperationTimeout ( long duration , TimeUnit unit ) { Duration readTimeout = Duration . of ( duration , toChronoUnit ( unit ) ) ; return timeouts ( TimeoutsBuilder . timeouts ( ) . read ( readTimeout ) . build ( ) ) ; }
Adds a read operation timeout . Read operations which time out return a result comparable to a cache miss .
67
20
153,943
private void removeCache ( final String alias , final boolean removeFromConfig ) { statusTransitioner . checkAvailable ( ) ; final CacheHolder cacheHolder = caches . remove ( alias ) ; if ( cacheHolder != null ) { final InternalCache < ? , ? > ehcache = cacheHolder . retrieve ( cacheHolder . keyType , cacheHolder . valueType ) ; if ( ehcache != null ) { if ( removeFromConfig ) { configuration . removeCacheConfiguration ( alias ) ; } if ( ! statusTransitioner . isTransitioning ( ) ) { for ( CacheManagerListener listener : listeners ) { listener . cacheRemoved ( alias , ehcache ) ; } } ehcache . close ( ) ; closeEhcache ( alias , ehcache ) ; } LOGGER . info ( "Cache '{}' removed from {}." , alias , simpleName ) ; } }
Closes and removes a cache by alias from this cache manager .
188
13
153,944
private < K , V > CacheConfiguration < K , V > adjustConfigurationWithCacheManagerDefaults ( String alias , CacheConfiguration < K , V > config ) { ClassLoader cacheClassLoader = config . getClassLoader ( ) ; List < ServiceConfiguration < ? > > configurationList = new ArrayList <> ( ) ; configurationList . addAll ( config . getServiceConfigurations ( ) ) ; CacheLoaderWriterConfiguration loaderWriterConfiguration = findSingletonAmongst ( CacheLoaderWriterConfiguration . class , config . getServiceConfigurations ( ) ) ; if ( loaderWriterConfiguration == null ) { CacheLoaderWriterProvider loaderWriterProvider = serviceLocator . getService ( CacheLoaderWriterProvider . class ) ; ServiceConfiguration < CacheLoaderWriterProvider > preConfiguredCacheLoaderWriterConfig = loaderWriterProvider . getPreConfiguredCacheLoaderWriterConfig ( alias ) ; if ( preConfiguredCacheLoaderWriterConfig != null ) { configurationList . add ( preConfiguredCacheLoaderWriterConfig ) ; } if ( loaderWriterProvider . isLoaderJsrProvided ( alias ) ) { configurationList . add ( new CacheLoaderWriterConfiguration ( ) { } ) ; } } ServiceConfiguration < ? > [ ] serviceConfigurations = new ServiceConfiguration < ? > [ configurationList . size ( ) ] ; configurationList . toArray ( serviceConfigurations ) ; if ( cacheClassLoader == null ) { cacheClassLoader = cacheManagerClassLoader ; } if ( cacheClassLoader != config . getClassLoader ( ) ) { config = new BaseCacheConfiguration <> ( config . getKeyType ( ) , config . getValueType ( ) , config . getEvictionAdvisor ( ) , cacheClassLoader , config . getExpiryPolicy ( ) , config . getResourcePools ( ) , serviceConfigurations ) ; } else { config = new BaseCacheConfiguration <> ( config . getKeyType ( ) , config . getValueType ( ) , config . getEvictionAdvisor ( ) , config . getClassLoader ( ) , config . getExpiryPolicy ( ) , config . getResourcePools ( ) , serviceConfigurations ) ; } return config ; }
adjusts the config to reflect new classloader & serialization provider
450
13
153,945
boolean evict ( StoreEventSink < K , V > eventSink ) { evictionObserver . begin ( ) ; Random random = new Random ( ) ; @ SuppressWarnings ( "unchecked" ) Map . Entry < K , OnHeapValueHolder < V > > candidate = map . getEvictionCandidate ( random , SAMPLE_SIZE , EVICTION_PRIORITIZER , EVICTION_ADVISOR ) ; if ( candidate == null ) { // 2nd attempt without any advisor candidate = map . getEvictionCandidate ( random , SAMPLE_SIZE , EVICTION_PRIORITIZER , noAdvice ( ) ) ; } if ( candidate == null ) { return false ; } else { Map . Entry < K , OnHeapValueHolder < V > > evictionCandidate = candidate ; AtomicBoolean removed = new AtomicBoolean ( false ) ; map . computeIfPresent ( evictionCandidate . getKey ( ) , ( mappedKey , mappedValue ) -> { if ( mappedValue . equals ( evictionCandidate . getValue ( ) ) ) { removed . set ( true ) ; if ( ! ( evictionCandidate . getValue ( ) instanceof Fault ) ) { eventSink . evicted ( evictionCandidate . getKey ( ) , evictionCandidate . getValue ( ) ) ; invalidationListener . onInvalidation ( mappedKey , evictionCandidate . getValue ( ) ) ; } updateUsageInBytesIfRequired ( - mappedValue . size ( ) ) ; return null ; } return mappedValue ; } ) ; if ( removed . get ( ) ) { evictionObserver . end ( StoreOperationOutcomes . EvictionOutcome . SUCCESS ) ; return true ; } else { evictionObserver . end ( StoreOperationOutcomes . EvictionOutcome . FAILURE ) ; return false ; } } }
Try to evict a mapping .
400
6
153,946
@ Override public V getFailure ( K key , StoreAccessException e ) { try { return loaderWriter . load ( key ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheLoadingException ( e1 , e ) ; } finally { cleanup ( key , e ) ; } }
Get the value from the loader - writer .
63
9
153,947
@ Override public boolean containsKeyFailure ( K key , StoreAccessException e ) { cleanup ( key , e ) ; return false ; }
Return false . It doesn t matter if the key is present in the backend we consider it s not in the cache .
29
24
153,948
@ Override public void putFailure ( K key , V value , StoreAccessException e ) { try { loaderWriter . write ( key , value ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } finally { cleanup ( key , e ) ; } }
Write the value to the loader - write .
67
9
153,949
@ Override public void removeFailure ( K key , StoreAccessException e ) { try { loaderWriter . delete ( key ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } finally { cleanup ( key , e ) ; } }
Delete the key from the loader - writer .
62
9
153,950
@ Override public V putIfAbsentFailure ( K key , V value , StoreAccessException e ) { // FIXME: Should I care about useLoaderInAtomics? try { try { V loaded = loaderWriter . load ( key ) ; if ( loaded != null ) { return loaded ; } } catch ( Exception e1 ) { throw ExceptionFactory . newCacheLoadingException ( e1 , e ) ; } try { loaderWriter . write ( key , value ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } } finally { cleanup ( key , e ) ; } return null ; }
Write the value to the loader - writer if it doesn t already exist in it . Note that the load and write pair is not atomic . This atomicity if needed should be handled by the something else .
138
41
153,951
@ Override public boolean removeFailure ( K key , V value , StoreAccessException e ) { try { V loadedValue ; try { loadedValue = loaderWriter . load ( key ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheLoadingException ( e1 , e ) ; } if ( loadedValue == null ) { return false ; } if ( ! loadedValue . equals ( value ) ) { return false ; } try { loaderWriter . delete ( key ) ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } return true ; } finally { cleanup ( key , e ) ; } }
Delete the key from the loader - writer if it is found with a matching value . Note that the load and write pair is not atomic . This atomicity if needed should be handled by the something else .
140
41
153,952
@ SuppressWarnings ( "unchecked" ) @ Override public Map < K , V > getAllFailure ( Iterable < ? extends K > keys , StoreAccessException e ) { try { return loaderWriter . loadAll ( ( Iterable ) keys ) ; // FIXME: bad typing that we should fix } catch ( BulkCacheLoadingException e1 ) { throw e1 ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheLoadingException ( e1 , e ) ; } finally { cleanup ( keys , e ) ; } }
Get all entries for the provided keys . Entries not found by the loader - writer are expected to be an entry with the key and a null value .
117
31
153,953
@ Override public void putAllFailure ( Map < ? extends K , ? extends V > entries , StoreAccessException e ) { try { loaderWriter . writeAll ( entries . entrySet ( ) ) ; // FIXME: bad typing that we should fix } catch ( BulkCacheWritingException e1 ) { throw e1 ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } finally { cleanup ( entries . keySet ( ) , e ) ; } }
Write all entries to the loader - writer .
108
9
153,954
@ Override public void removeAllFailure ( Iterable < ? extends K > keys , StoreAccessException e ) { try { loaderWriter . deleteAll ( keys ) ; } catch ( BulkCacheWritingException e1 ) { throw e1 ; } catch ( Exception e1 ) { throw ExceptionFactory . newCacheWritingException ( e1 , e ) ; } finally { cleanup ( keys , e ) ; } }
Delete all keys from the loader - writer .
85
9
153,955
public void addPool ( String alias , int minSize , int maxSize ) { if ( alias == null ) { throw new NullPointerException ( "Pool alias cannot be null" ) ; } if ( poolConfigurations . containsKey ( alias ) ) { throw new IllegalArgumentException ( "A pool with the alias '" + alias + "' is already configured" ) ; } else { poolConfigurations . put ( alias , new PoolConfiguration ( minSize , maxSize ) ) ; } }
Adds a new pool with the provided minimum and maximum .
104
11
153,956
protected void cleanup ( StoreAccessException from ) { try { store . obliterate ( ) ; } catch ( StoreAccessException e ) { inconsistent ( from , e ) ; return ; } recovered ( from ) ; }
Clear all entries from the store .
44
7
153,957
protected void cleanup ( Iterable < ? extends K > keys , StoreAccessException from ) { try { store . obliterate ( keys ) ; } catch ( StoreAccessException e ) { inconsistent ( keys , from , e ) ; return ; } recovered ( keys , from ) ; }
Clean all keys from the store .
58
7
153,958
protected void recovered ( Iterable < ? extends K > keys , StoreAccessException from ) { LOGGER . info ( "Ehcache keys {} recovered from" , keys , from ) ; }
Called when the cache recovered from a failing store operation on a list of keys .
39
17
153,959
protected void inconsistent ( K key , StoreAccessException because , StoreAccessException ... cleanup ) { pacedErrorLog ( "Ehcache key {} in possible inconsistent state" , key , because ) ; }
Called when the cache failed to recover from a failing store operation on a key .
40
17
153,960
protected void inconsistent ( Iterable < ? extends K > keys , StoreAccessException because , StoreAccessException ... cleanup ) { pacedErrorLog ( "Ehcache keys {} in possible inconsistent state" , keys , because ) ; }
Called when the cache failed to recover from a failing store operation on a list of keys .
46
19
153,961
public ServerSideConfigurationBuilder resourcePool ( String name , long size , MemoryUnit unit , String serverResource ) { return resourcePool ( name , new Pool ( unit . toBytes ( size ) , serverResource ) ) ; }
Adds a resource pool with the given name and size and consuming the given server resource .
46
17
153,962
private synchronized void registerCacheEventListener ( EventListenerWrapper < K , V > wrapper ) { if ( aSyncListenersList . contains ( wrapper ) || syncListenersList . contains ( wrapper ) ) { throw new IllegalStateException ( "Cache Event Listener already registered: " + wrapper . getListener ( ) ) ; } if ( wrapper . isOrdered ( ) && orderedListenerCount ++ == 0 ) { storeEventSource . setEventOrdering ( true ) ; } switch ( wrapper . getFiringMode ( ) ) { case ASYNCHRONOUS : aSyncListenersList . add ( wrapper ) ; break ; case SYNCHRONOUS : syncListenersList . add ( wrapper ) ; break ; default : throw new AssertionError ( "Unhandled EventFiring value: " + wrapper . getFiringMode ( ) ) ; } if ( listenersCount ++ == 0 ) { storeEventSource . addEventListener ( eventListener ) ; } }
Synchronized to make sure listener addition is atomic in order to prevent having the same listener registered under multiple configurations
204
22
153,963
private synchronized boolean removeWrapperFromList ( EventListenerWrapper < K , V > wrapper , List < EventListenerWrapper < K , V > > listenersList ) { int index = listenersList . indexOf ( wrapper ) ; if ( index != - 1 ) { EventListenerWrapper < K , V > containedWrapper = listenersList . remove ( index ) ; if ( containedWrapper . isOrdered ( ) && -- orderedListenerCount == 0 ) { storeEventSource . setEventOrdering ( false ) ; } if ( -- listenersCount == 0 ) { storeEventSource . removeEventListener ( eventListener ) ; } return true ; } return false ; }
Synchronized to make sure listener removal is atomic
140
10
153,964
private void init ( ) { CompletableFuture . allOf ( managementRegistry . register ( generateClusterTierManagerBinding ( ) ) , // PoolBinding.ALL_SHARED is a marker so that we can send events not specifically related to 1 pool // this object is ignored from the stats and descriptors managementRegistry . register ( PoolBinding . ALL_SHARED ) ) . thenRun ( managementRegistry :: refresh ) ; }
the goal of the following code is to send the management metadata from the entity into the monitoring tre AFTER the entity creation
96
23
153,965
public boolean seen ( long msgId ) { boolean seen = nonContiguousMsgIds . contains ( msgId ) || msgId <= highestContiguousMsgId ; tryReconcile ( ) ; return seen ; }
Check wheather the given message id is already seen by track call .
46
14
153,966
private void reconcile ( ) { // If nonContiguousMsgIds is empty then nothing to reconcile. if ( nonContiguousMsgIds . isEmpty ( ) ) { return ; } // This happens when a passive is started after Active has moved on and // passive starts to see msgIDs starting from a number > 0. // Once the sync is completed, fast forward highestContiguousMsgId. // Post sync completion assuming platform will send all msgIds beyond highestContiguousMsgId. if ( highestContiguousMsgId == - 1L && isSyncCompleted ) { Long min = nonContiguousMsgIds . last ( ) ; LOGGER . info ( "Setting highestContiguousMsgId to {} from -1" , min ) ; highestContiguousMsgId = min ; nonContiguousMsgIds . removeIf ( msgId -> msgId <= min ) ; } for ( long msgId : nonContiguousMsgIds ) { if ( msgId <= highestContiguousMsgId ) { nonContiguousMsgIds . remove ( msgId ) ; } else if ( msgId > highestContiguousMsgId + 1 ) { break ; } else { // the order is important.. highestContiguousMsgId = msgId ; nonContiguousMsgIds . remove ( msgId ) ; } } }
Remove the contiguous seen msgIds from the nonContiguousMsgIds and update highestContiguousMsgId
273
22
153,967
private void tryReconcile ( ) { if ( ! this . reconciliationLock . tryLock ( ) ) { return ; } try { reconcile ( ) ; // Keep on warning after every reconcile if nonContiguousMsgIds reaches 500 (kept it a bit higher so that we won't get unnecessary warning due to high concurrency). if ( nonContiguousMsgIds . size ( ) > 500 ) { LOGGER . warn ( "Non - Contiguous Message ID has size : {}, with highestContiguousMsgId as : {}" , nonContiguousMsgIds . size ( ) , highestContiguousMsgId ) ; } } finally { this . reconciliationLock . unlock ( ) ; } }
Try to reconcile if the lock is available otherwise just return as other thread would have hold the lock and performing reconcile .
146
23
153,968
public DefaultResilienceStrategyConfiguration bind ( RecoveryStore < ? > store , CacheLoaderWriter < ? , ? > loaderWriter ) throws IllegalStateException { if ( getInstance ( ) == null ) { Object [ ] arguments = getArguments ( ) ; Object [ ] boundArguments = Arrays . copyOf ( arguments , arguments . length + 2 ) ; boundArguments [ arguments . length ] = store ; boundArguments [ arguments . length + 1 ] = loaderWriter ; return new BoundConfiguration ( getClazz ( ) , boundArguments ) ; } else { return this ; } }
Returns a configuration object bound to the given store and cache loader - writer .
125
15
153,969
public void setLastAccessTime ( long lastAccessTime ) { while ( true ) { long current = this . lastAccessTime ; if ( current >= lastAccessTime ) { break ; } if ( ACCESSTIME_UPDATER . compareAndSet ( this , current , lastAccessTime ) ) { break ; } } }
Set the last time this entry was accessed in milliseconds .
69
11
153,970
public PutOperation < K , V > applyOperation ( K key , PutOperation < K , V > existing , Operation < K , V > operation ) { final Result < K , V > newValue = operation . apply ( existing ) ; if ( newValue == null ) { return null ; } else { return newValue . asOperationExpiringAt ( Long . MAX_VALUE ) ; } }
Applies the given operation returning a result that never expires .
82
12
153,971
@ Override public Map < K , ValueHolder < V > > bulkCompute ( final Set < ? extends K > keys , final Function < Iterable < ? extends Map . Entry < ? extends K , ? extends V > > , Iterable < ? extends Map . Entry < ? extends K , ? extends V > > > remappingFunction ) throws StoreAccessException { Map < K , ValueHolder < V > > valueHolderMap = new HashMap <> ( ) ; if ( remappingFunction instanceof Ehcache . PutAllFunction ) { Ehcache . PutAllFunction < K , V > putAllFunction = ( Ehcache . PutAllFunction < K , V > ) remappingFunction ; Map < K , V > entriesToRemap = putAllFunction . getEntriesToRemap ( ) ; for ( Map . Entry < K , V > entry : entriesToRemap . entrySet ( ) ) { PutStatus putStatus = silentPut ( entry . getKey ( ) , entry . getValue ( ) ) ; if ( putStatus == PutStatus . PUT ) { putAllFunction . getActualPutCount ( ) . incrementAndGet ( ) ; valueHolderMap . put ( entry . getKey ( ) , new ClusteredValueHolder <> ( entry . getValue ( ) ) ) ; } } } else if ( remappingFunction instanceof Ehcache . RemoveAllFunction ) { Ehcache . RemoveAllFunction < K , V > removeAllFunction = ( Ehcache . RemoveAllFunction < K , V > ) remappingFunction ; for ( K key : keys ) { boolean removed = silentRemove ( key ) ; if ( removed ) { removeAllFunction . getActualRemoveCount ( ) . incrementAndGet ( ) ; } } } else { throw new UnsupportedOperationException ( "This bulkCompute method is not yet capable of handling generic computation functions" ) ; } return valueHolderMap ; }
The assumption is that this method will be invoked only by cache . putAll and cache . removeAll methods .
411
22
153,972
@ Override public V getFailure ( K key , StoreAccessException e ) { cleanup ( key , e ) ; return null ; }
Return null .
28
3
153,973
@ Override public V putIfAbsentFailure ( K key , V value , StoreAccessException e ) { cleanup ( key , e ) ; return null ; }
Do nothing and return null .
34
6
153,974
@ Override public Map < K , V > getAllFailure ( Iterable < ? extends K > keys , StoreAccessException e ) { cleanup ( keys , e ) ; HashMap < K , V > result = keys instanceof Collection < ? > ? new HashMap <> ( ( ( Collection < ? extends K > ) keys ) . size ( ) ) : new HashMap <> ( ) ; for ( K key : keys ) { result . put ( key , null ) ; } return result ; }
Do nothing and return a map of all the provided keys and null values .
106
15
153,975
public PooledExecutionServiceConfigurationBuilder defaultPool ( String alias , int minSize , int maxSize ) { PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder ( this ) ; other . defaultPool = new Pool ( alias , minSize , maxSize ) ; return other ; }
Adds a default pool configuration to the returned builder .
65
10
153,976
public PooledExecutionServiceConfigurationBuilder pool ( String alias , int minSize , int maxSize ) { PooledExecutionServiceConfigurationBuilder other = new PooledExecutionServiceConfigurationBuilder ( this ) ; other . pools . add ( new Pool ( alias , minSize , maxSize ) ) ; return other ; }
Adds a pool configuration to the returned builder .
66
9
153,977
private long calculateExpiryTime ( K key , PutOperation < K , V > existing , Operation < K , V > operation , Result < K , V > newValue ) { if ( operation . isExpiryAvailable ( ) ) { return operation . expirationTime ( ) ; } else { try { Duration duration ; if ( existing == null ) { duration = requireNonNull ( expiry . getExpiryForCreation ( key , newValue . getValue ( ) ) ) ; } else { duration = expiry . getExpiryForUpdate ( key , existing :: getValue , newValue . getValue ( ) ) ; if ( duration == null ) { return existing . expirationTime ( ) ; } } if ( duration . isNegative ( ) ) { duration = Duration . ZERO ; } else if ( isExpiryDurationInfinite ( duration ) ) { return Long . MAX_VALUE ; } return ExpiryUtils . getExpirationMillis ( operation . timeStamp ( ) , duration ) ; } catch ( Exception ex ) { LOG . error ( "Expiry computation caused an exception - Expiry duration will be 0 " , ex ) ; return Long . MIN_VALUE ; } } }
Calculates the expiration time of the new state based on this resolvers expiry policy .
259
20
153,978
public static boolean isAvailable ( ServiceProvider < Service > serviceProvider ) { return ENTITY_SERVICE_CLASS != null && serviceProvider . getService ( ENTITY_SERVICE_CLASS ) != null ; }
Check if clustering is active for this cache manager
44
10
153,979
public static int findBestCollectionSize ( Iterable < ? > iterable , int bestBet ) { return ( iterable instanceof Collection ? ( ( Collection < ? > ) iterable ) . size ( ) : bestBet ) ; }
Used to create a new collection with the correct size . Given an iterable will try to see it the iterable actually have a size and will return it . If the iterable has no known size we return the best bet .
49
46
153,980
public static DedicatedClusteredResourcePool clusteredDedicated ( String fromResource , long size , MemoryUnit unit ) { return new DedicatedClusteredResourcePoolImpl ( fromResource , size , unit ) ; }
Creates a new clustered resource pool using dedicated clustered resources .
46
12
153,981
public static < T > Optional < T > findStatisticOnDescendants ( Object context , String tag , String statName ) { @ SuppressWarnings ( "unchecked" ) Set < TreeNode > statResult = queryBuilder ( ) . descendants ( ) . filter ( context ( attributes ( Matchers . allOf ( hasAttribute ( "name" , statName ) , hasTag ( tag ) ) ) ) ) . build ( ) . execute ( Collections . singleton ( ContextManager . nodeFor ( context ) ) ) ; if ( statResult . size ( ) > 1 ) { throw new RuntimeException ( "One stat expected for " + statName + " but found " + statResult . size ( ) ) ; } if ( statResult . size ( ) == 1 ) { @ SuppressWarnings ( "unchecked" ) T result = ( T ) statResult . iterator ( ) . next ( ) . getContext ( ) . attributes ( ) . get ( "this" ) ; return Optional . ofNullable ( result ) ; } // No such stat in this context return Optional . empty ( ) ; }
Search for a statistic on the descendant of the context that matches the tag and statistic name .
235
18
153,982
@ Override public long getQueueSize ( ) { Batch snapshot = openBatch ; return executorQueue . size ( ) * batchSize + ( snapshot == null ? 0 : snapshot . size ( ) ) ; }
Gets the best estimate for items in the queue still awaiting processing . Since the value returned is a rough estimate it can sometimes be more than the number of items actually in the queue but not less .
46
40
153,983
@ Override public Result < K , V > apply ( final Result < K , V > previousOperation ) { if ( previousOperation == null ) { return this ; } else { return previousOperation ; } }
PutIfAbsent operation succeeds only when there is no previous operation for the same key .
43
18
153,984
public void setClip ( Rectangle2D clip ) { xMin = clip . getX ( ) ; xMax = xMin + clip . getWidth ( ) ; yMin = clip . getY ( ) ; yMax = yMin + clip . getHeight ( ) ; }
Sets the clip rectangle .
60
6
153,985
public static < T extends Comparable < ? super T > > void sort ( List < T > list ) { sort ( list , QuickSort . < T > naturalOrder ( ) ) ; // JAVA_8 replace with Comparator.naturalOrder() (and cleanup) }
Sorts the given list according to natural order .
58
10
153,986
public static < T > void sort ( List < T > list , Comparator < ? super T > comparator ) { if ( list instanceof RandomAccess ) { quicksort ( list , comparator ) ; } else { List < T > copy = new ArrayList <> ( list ) ; quicksort ( copy , comparator ) ; list . clear ( ) ; list . addAll ( copy ) ; } }
Sorts the given list using the given comparator .
88
11
153,987
public Rectangle getTextBounds ( ) { List < TextElement > texts = this . getText ( ) ; if ( ! texts . isEmpty ( ) ) { return Utils . bounds ( texts ) ; } else { return new Rectangle ( ) ; } }
Returns the minimum bounding box that contains all the TextElements on this Page
56
16
153,988
public static float [ ] filter ( float [ ] data , float alpha ) { float [ ] rv = new float [ data . length ] ; rv [ 0 ] = data [ 0 ] ; for ( int i = 1 ; i < data . length ; i ++ ) { rv [ i ] = rv [ i - 1 ] + alpha * ( data [ i ] - rv [ i - 1 ] ) ; } return rv ; }
Simple Low pass filter
95
4
153,989
public List < Table > extract ( Page page , List < Ruling > rulings ) { // split rulings into horizontal and vertical List < Ruling > horizontalR = new ArrayList <> ( ) , verticalR = new ArrayList <> ( ) ; for ( Ruling r : rulings ) { if ( r . horizontal ( ) ) { horizontalR . add ( r ) ; } else if ( r . vertical ( ) ) { verticalR . add ( r ) ; } } horizontalR = Ruling . collapseOrientedRulings ( horizontalR ) ; verticalR = Ruling . collapseOrientedRulings ( verticalR ) ; List < Cell > cells = findCells ( horizontalR , verticalR ) ; List < Rectangle > spreadsheetAreas = findSpreadsheetsFromCells ( cells ) ; List < Table > spreadsheets = new ArrayList <> ( ) ; for ( Rectangle area : spreadsheetAreas ) { List < Cell > overlappingCells = new ArrayList <> ( ) ; for ( Cell c : cells ) { if ( c . intersects ( area ) ) { c . setTextElements ( TextElement . mergeWords ( page . getText ( c ) ) ) ; overlappingCells . add ( c ) ; } } List < Ruling > horizontalOverlappingRulings = new ArrayList <> ( ) ; for ( Ruling hr : horizontalR ) { if ( area . intersectsLine ( hr ) ) { horizontalOverlappingRulings . add ( hr ) ; } } List < Ruling > verticalOverlappingRulings = new ArrayList <> ( ) ; for ( Ruling vr : verticalR ) { if ( area . intersectsLine ( vr ) ) { verticalOverlappingRulings . add ( vr ) ; } } TableWithRulingLines t = new TableWithRulingLines ( area , overlappingCells , horizontalOverlappingRulings , verticalOverlappingRulings , this ) ; spreadsheets . add ( t ) ; } Utils . sort ( spreadsheets , Rectangle . ILL_DEFINED_ORDER ) ; return spreadsheets ; }
Extract a list of Table from page using rulings as separators
462
13
153,990
public static < T extends Comparable < ? super T > > void sort ( List < T > list ) { if ( useQuickSort ) QuickSort . sort ( list ) ; else Collections . sort ( list ) ; }
Wrap Collections . sort so we can fallback to a non - stable quicksort if we re running on JDK7 +
46
27
153,991
public void normalize ( ) { double angle = this . getAngle ( ) ; if ( Utils . within ( angle , 0 , 1 ) || Utils . within ( angle , 180 , 1 ) ) { // almost horizontal this . setLine ( this . x1 , this . y1 , this . x2 , this . y1 ) ; } else if ( Utils . within ( angle , 90 , 1 ) || Utils . within ( angle , 270 , 1 ) ) { // almost vertical this . setLine ( this . x1 , this . y1 , this . x1 , this . y2 ) ; } // else { // System.out.println("oblique: " + this + " ("+ this.getAngle() + ")"); // } }
Normalize almost horizontal or almost vertical lines
166
8
153,992
private static OutputFormat whichOutputFormat ( CommandLine line ) throws ParseException { if ( ! line . hasOption ( ' ' ) ) { return OutputFormat . CSV ; } try { return OutputFormat . valueOf ( line . getOptionValue ( ' ' ) ) ; } catch ( IllegalArgumentException e ) { throw new ParseException ( String . format ( "format %s is illegal. Available formats: %s" , line . getOptionValue ( ' ' ) , Utils . join ( "," , OutputFormat . formatNames ( ) ) ) ) ; } }
CommandLine parsing methods
122
4
153,993
public static List < Float > parseFloatList ( String option ) throws ParseException { String [ ] f = option . split ( "," ) ; List < Float > rv = new ArrayList <> ( ) ; try { for ( int i = 0 ; i < f . length ; i ++ ) { rv . add ( Float . parseFloat ( f [ i ] ) ) ; } return rv ; } catch ( NumberFormatException e ) { throw new ParseException ( "Wrong number syntax" ) ; } }
utilities etc .
112
4
153,994
public TextChunk [ ] splitAt ( int i ) { if ( i < 1 || i >= this . getTextElements ( ) . size ( ) ) { throw new IllegalArgumentException ( ) ; } TextChunk [ ] rv = new TextChunk [ ] { new TextChunk ( this . getTextElements ( ) . subList ( 0 , i ) ) , new TextChunk ( this . getTextElements ( ) . subList ( i , this . getTextElements ( ) . size ( ) ) ) } ; return rv ; }
Splits a TextChunk in two at the position of the i - th TextElement
123
18
153,995
@ Override public void smoothScrollToPosition ( int position ) { int transformedPosition = transformInnerPositionIfNeed ( position ) ; super . smoothScrollToPosition ( transformedPosition ) ; Log . e ( "test" , "transformedPosition:" + transformedPosition ) ; }
Starts a smooth scroll to an adapter position . if position < adapter . getActualCount position will be transform to right position .
58
27
153,996
@ SuppressWarnings ( "unchecked" ) static < T , A extends BindingCollectionAdapter < T > > A createClass ( Class < ? extends BindingCollectionAdapter > adapterClass , ItemBinding < T > itemBinding ) { try { return ( A ) adapterClass . getConstructor ( ItemBinding . class ) . newInstance ( itemBinding ) ; } catch ( Exception e1 ) { throw new RuntimeException ( e1 ) ; } }
Constructs a binding adapter class from it s class name using reflection .
98
14
153,997
@ NonNull public DiffUtil . DiffResult calculateDiff ( @ NonNull final List < T > newItems ) { final ArrayList < T > frozenList ; synchronized ( LIST_LOCK ) { frozenList = new ArrayList <> ( list ) ; } return doCalculateDiff ( frozenList , newItems ) ; }
Calculates the list of update operations that can convert this list into the given one .
69
18
153,998
@ NonNull public final ItemBinding < T > bindExtra ( int variableId , Object value ) { if ( extraBindings == null ) { extraBindings = new SparseArray <> ( 1 ) ; } extraBindings . put ( variableId , value ) ; return this ; }
Bind an extra variable to the view with the given variable id . The same instance will be provided to all views the binding is bound to .
62
28
153,999
@ Nullable public final Object extraBinding ( int variableId ) { if ( extraBindings == null ) { return null ; } return extraBindings . get ( variableId ) ; }
Returns the current extra binding for the given variable id or null if one isn t present .
40
18