Class GridCacheUtils

  • Direct Known Subclasses:
    CU

    public class GridCacheUtils
    extends Object
    Cache utility methods.
    • Constructor Detail

      • GridCacheUtils

        protected GridCacheUtils()
        Ensure singleton.
    • Method Detail

      • cheatCache

        @Deprecated
        public static boolean cheatCache​(int id)
        Deprecated.
        Quickly checks if passed in cache ID is a "cheat cache ID" set by -DCHEAT_CACHE=user_cache_name and resolved in static block above. FOR DEBUGGING AND TESTING PURPOSES!
        Parameters:
        id - Cache ID to check.
        Returns:
        True if this is cheat cache ID.
      • factory

        public static <K,​V> IgniteClosure<Integer,​IgnitePredicate<javax.cache.Cache.Entry<K,​V>>[]> factory()
        Entry predicate factory mostly used for deserialization.
        Type Parameters:
        K - Key type.
        V - Value type.
        Returns:
        Factory instance.
      • isNearEnabled

        public static boolean isNearEnabled​(GridCacheContext ctx)
        Checks if near cache is enabled for cache context.
        Parameters:
        ctx - Cache context to check.
        Returns:
        True if near cache is enabled, false otherwise.
      • isNearEnabled

        public static boolean isNearEnabled​(CacheConfiguration cfg)
        Checks if near cache is enabled for cache configuration.
        Parameters:
        cfg - Cache configuration to check.
        Returns:
        True if near cache is enabled, false otherwise.
      • oldest

        @Nullable
        public static @Nullable ClusterNode oldest​(Collection<ClusterNode> nodes)
        Parameters:
        nodes - Nodes.
        Returns:
        Oldest node for the given topology version.
      • empty

        public static <K,​V> IgnitePredicate<javax.cache.Cache.Entry<K,​V>>[] empty()
        Returns:
        Empty filter.
      • alwaysFalse0Arr

        public static CacheEntryPredicate[] alwaysFalse0Arr()
        Returns:
        Always false filter.
      • mapsReducer

        public static <K,​V> IgniteReducer<Map<K,​V>,​Map<K,​V>> mapsReducer​(int size)
        Gets reducer that aggregates maps into one.
        Type Parameters:
        K - Key type.
        V - Value type.
        Parameters:
        size - Predicted size of the resulting map to avoid resizings.
        Returns:
        Reducer.
      • collectionsReducer

        public static <T> IgniteReducer<Collection<T>,​Collection<T>> collectionsReducer​(int size)
        Gets reducer that aggregates collections.
        Type Parameters:
        T - Collection element type.
        Returns:
        Reducer.
      • objectsReducer

        public static <T> IgniteReducer<T,​Collection<T>> objectsReducer()
        Gets reducer that aggregates items into collection.
        Type Parameters:
        T - Items type.
        Returns:
        Reducer.
      • isLockTimeoutOrCancelled

        public static boolean isLockTimeoutOrCancelled​(Throwable t)
        Parameters:
        t - Exception to check.
        Returns:
        true if caused by lock timeout or cancellation.
      • skipValue

        public static Object skipValue​(Object val,
                                       boolean skip)
        Parameters:
        val - Value.
        skip - Skip value flag.
        Returns:
        Value.
      • txOnPrimary

        public static boolean txOnPrimary​(IgniteInternalTx tx)
        Parameters:
        tx - Transaction.
        Returns:
        True if transaction is on primary node.
      • txString

        public static String txString​(@Nullable
                                      @Nullable IgniteInternalTx tx)
        Parameters:
        tx - Transaction.
        Returns:
        String view of all safe-to-print transaction properties.
      • unwindEvicts

        public static void unwindEvicts​(GridCacheContext ctx)
        Parameters:
        ctx - Cache context.
      • nodeComparator

        public static Comparator<ClusterNode> nodeComparator​(boolean asc)
        Parameters:
        asc - True for ascending.
        Returns:
        Descending order comparator.
      • mask

        public static String mask​(String cacheName)
        Mask cache name in case it is null.
        Parameters:
        cacheName - Cache name.
        Returns:
        The same cache name or <default> in case the name is null.
      • unmask

        @Nullable
        public static @Nullable String unmask​(String cacheName)
        Unmask cache name.
        Parameters:
        cacheName - Cache name.
        Returns:
        Unmasked cache name, i.e. in case provided parameter was <default> then null will be returned.
      • replicationTopicSend

        public static String replicationTopicSend()
        Get topic to which replication requests are sent.
        Returns:
        Topic to which replication requests are sent.
      • replicationTopicReceive

        public static String replicationTopicReceive​(String cacheName)
        Get topic to which replication responses are sent.
        Parameters:
        cacheName - Cache name.
        Returns:
        Topic to which replication responses are sent.
      • checkAttributeMismatch

        public static void checkAttributeMismatch​(IgniteLogger log,
                                                  CacheConfiguration locCfg,
                                                  CacheConfiguration rmtCfg,
                                                  UUID rmtNodeId,
                                                  T2<String,​String> attr,
                                                  boolean fail)
                                           throws IgniteCheckedException
        Checks that local and remove configurations have the same value of given attribute.
        Parameters:
        log - Logger used to log warning message (used only if fail flag is not set).
        locCfg - Local configuration.
        rmtCfg - Remote configuration.
        rmtNodeId - Remote node.
        attr - Attribute name.
        fail - If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
        Throws:
        IgniteCheckedException - If attribute values are different and fail flag is true.
      • checkAttributeMismatch

        public static void checkAttributeMismatch​(IgniteLogger log,
                                                  String cfgName,
                                                  UUID rmtNodeId,
                                                  String attrName,
                                                  String attrMsg,
                                                  @Nullable
                                                  @Nullable Object locVal,
                                                  @Nullable
                                                  @Nullable Object rmtVal,
                                                  boolean fail)
                                           throws IgniteCheckedException
        Checks that cache configuration attribute has the same value in local and remote cache configurations.
        Parameters:
        log - Logger used to log warning message (used only if fail flag is not set).
        cfgName - Remote cache name.
        rmtNodeId - Remote node.
        attrName - Short attribute name for error message.
        attrMsg - Full attribute name for error message.
        locVal - Local value.
        rmtVal - Remote value.
        fail - If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
        Throws:
        IgniteCheckedException - If attribute values are different and fail flag is true.
      • validateCacheGroupsAttributesMismatch

        public static void validateCacheGroupsAttributesMismatch​(IgniteLogger log,
                                                                 CacheConfiguration cfg1,
                                                                 CacheConfiguration cfg2,
                                                                 String attrName,
                                                                 String attrMsg,
                                                                 Object val1,
                                                                 Object val2,
                                                                 boolean fail)
                                                          throws IgniteCheckedException
        Parameters:
        cfg1 - Existing configuration.
        cfg2 - Cache configuration to start.
        attrName - Short attribute name for error message.
        attrMsg - Full attribute name for error message.
        val1 - Attribute value in existing configuration.
        val2 - Attribute value in starting configuration.
        fail - If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
        Throws:
        IgniteCheckedException - If validation failed.
      • isUtilityCache

        public static boolean isUtilityCache​(String cacheName)
        Parameters:
        cacheName - Cache name.
        Returns:
        True if this is utility system cache.
      • isSystemCache

        public static boolean isSystemCache​(String cacheName)
        Parameters:
        cacheName - Cache name.
        Returns:
        True if system cache.
      • cacheId

        public static int cacheId​(String cacheName)
        Parameters:
        cacheName - Cache name.
        Returns:
        Cache ID.
      • cacheGroupId

        public static int cacheGroupId​(String cacheName,
                                       @Nullable
                                       @Nullable String grpName)
        Parameters:
        cacheName - Cache name.
        grpName - Group name.
        Returns:
        Group ID.
      • cacheGroupId

        public static int cacheGroupId​(CacheConfiguration<?,​?> ccfg)
        Parameters:
        ccfg - Cache configuration.
        Returns:
        Group ID.
      • cacheOrGroupName

        public static String cacheOrGroupName​(CacheConfiguration<?,​?> ccfg)
        Parameters:
        ccfg - Cache configuration.
        Returns:
        Group name if it is specified, otherwise cache name.
      • toExpireTime

        public static long toExpireTime​(long ttl)
        Convert TTL to expire time.
        Parameters:
        ttl - TTL.
        Returns:
        Expire time.
      • invalidate

        public static <K,​V> void invalidate​(IgniteCache<K,​V> cache,
                                                  K key)
        Invalidate entry in cache.
        Parameters:
        cache - Cache.
        key - Key.
      • toTtl

        public static long toTtl​(javax.cache.expiry.Duration duration)
        Parameters:
        duration - Duration.
        Returns:
        TTL.
      • ttlForLoad

        public static long ttlForLoad​(javax.cache.expiry.ExpiryPolicy plc)
        Get TTL for load operation.
        Parameters:
        plc - Expiry policy.
        Returns:
        TTL for load operation or TTL_ZERO in case of immediate expiration.
      • expireTimeInPast

        public static long expireTimeInPast()
        Returns:
        Expire time denoting a point in the past.
      • convertToCacheException

        @NotNull
        public static @NotNull RuntimeException convertToCacheException​(IgniteCheckedException e)
        Parameters:
        e - Ignite checked exception.
        Returns:
        CacheException runtime exception, never null.
      • value

        @Nullable
        public static <T> T value​(@Nullable
                                  @Nullable CacheObject cacheObj,
                                  GridCacheContext ctx,
                                  boolean cpy)
        Parameters:
        cacheObj - Cache object.
        ctx - Cache context.
        cpy - Copy flag.
        Returns:
        Cache object value.
      • cachePluginConfiguration

        public static <C extends CachePluginConfiguration> C cachePluginConfiguration​(CacheConfiguration cfg,
                                                                                      Class<C> cl)
        Parameters:
        cfg - Cache configuration.
        cl - Type of cache plugin configuration.
        Returns:
        Cache plugin configuration by type from cache configuration or null.
      • affinityNode

        public static boolean affinityNode​(ClusterNode node,
                                           IgnitePredicate<ClusterNode> filter)
        Parameters:
        node - Node.
        filter - Node filter.
        Returns:
        True if node is not client node and pass given filter.
      • baselineNode

        public static boolean baselineNode​(ClusterNode node,
                                           DiscoveryDataClusterState discoveryDataClusterState)
        Parameters:
        node - Node.
        discoveryDataClusterState - Discovery data cluster state.
        Returns:
        True if node is included in BaselineTopology.
      • convertInvalidPartitions

        public static Map<Integer,​int[]> convertInvalidPartitions​(Map<Integer,​Set<Integer>> partsMap)
        Parameters:
        partsMap - Cache ID to partition IDs collection map.
        Returns:
        Cache ID to partition ID array map.
      • isReservedCacheName

        public static boolean isReservedCacheName​(String name)
        Parameters:
        name - Cache name.
        Returns:
        True if it is a reserved cache name.
      • validateKeyConfigiration

        public static Map<String,​String> validateKeyConfigiration​(String groupName,
                                                                        String cacheName,
                                                                        CacheKeyConfiguration[] cacheKeyCfgs,
                                                                        IgniteLogger log,
                                                                        boolean fail)
                                                                 throws IgniteCheckedException
        Validate affinity key configurations. All fields are initialized and not empty (typeName and affKeyFieldName is defined). Definition for the type does not repeat.
        Parameters:
        groupName - Cache group name.
        cacheName - Cache name.
        cacheKeyCfgs - keyConfiguration to validate.
        log - Logger used to log warning message (used only if fail flag is not set).
        fail - If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
        Returns:
        Affinity key maps (typeName -> fieldName)
        Throws:
        IgniteCheckedException - In case the affinity key configurations is not valid.
      • validateKeyConfigiration

        public static void validateKeyConfigiration​(String groupName,
                                                    String cacheName,
                                                    UUID rmtNodeId,
                                                    CacheKeyConfiguration[] rmtCacheKeyCfgs,
                                                    CacheKeyConfiguration[] locCacheKeyCfgs,
                                                    IgniteLogger log,
                                                    boolean fail)
                                             throws IgniteCheckedException
        Validate and compare affinity key configurations.
        Parameters:
        groupName - Cache group name.
        cacheName - Cache name.
        rmtNodeId - Remote node.
        rmtCacheKeyCfgs - Exist affinity key configurations.
        locCacheKeyCfgs - New affinity key configurations.
        log - Logger used to log warning message (used only if fail flag is not set).
        fail - If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
        Throws:
        IgniteCheckedException - In case the affinity key configurations is not valid.
      • createBackupPostProcessingClosure

        @Nullable
        public static @Nullable GridCacheUtils.BackupPostProcessingClosure createBackupPostProcessingClosure​(AffinityTopologyVersion topVer,
                                                                                                             IgniteLogger log,
                                                                                                             GridCacheContext cctx,
                                                                                                             @Nullable
                                                                                                             @Nullable KeyCacheObject key,
                                                                                                             @Nullable
                                                                                                             @Nullable IgniteCacheExpiryPolicy expiryPlc,
                                                                                                             boolean readThrough,
                                                                                                             boolean skipVals)
        Creates closure that saves initial value to backup partition.

        Useful only when store with readThrough is used. In situation when get() on backup node returns successful result, it's expected that localPeek() will be successful as well. But it isn't true when primary node loaded value from local store, in this case backups will remain non-initialized.
        To meet that requirement the value requested from primary should be saved on backup during get().

        Parameters:
        topVer - Topology version.
        log - Logger.
        cctx - Cache context.
        key - Key.
        expiryPlc - Expiry policy.
        readThrough - Read through.
        skipVals - Skip values.
      • isPersistentCache

        public static boolean isPersistentCache​(CacheConfiguration ccfg,
                                                DataStorageConfiguration dsCfg)
        Checks if cache configuration belongs to persistent cache.
        Parameters:
        ccfg - Cache configuration.
        dsCfg - Data storage config.
      • findDataRegion

        @Nullable
        public static @Nullable DataRegionConfiguration findDataRegion​(DataStorageConfiguration dsCfg,
                                                                       String drName)
        Finds data region by name.
        Parameters:
        dsCfg - Data storage configuration.
        drName - Data region name.
        Returns:
        Found data region.
      • isInMemoryCluster

        public static boolean isInMemoryCluster​(Collection<ClusterNode> nodes,
                                                JdkMarshaller marshaller,
                                                ClassLoader clsLdr)
        Parameters:
        nodes - Nodes to check.
        marshaller - JdkMarshaller
        clsLdr - Class loader.
        Returns:
        true if cluster has only in-memory nodes.
      • extractDataStorage

        @Nullable
        public static @Nullable DataStorageConfiguration extractDataStorage​(ClusterNode node,
                                                                            JdkMarshaller marshaller,
                                                                            ClassLoader clsLdr)
        Extract and unmarshal data storage configuration from given node.
        Parameters:
        node - Source of data storage configuration.
        Returns:
        Data storage configuration for given node, or null if this node has not data storage configuration.
      • findDataRegionConfiguration

        @Nullable
        public static @Nullable DataRegionConfiguration findDataRegionConfiguration​(@Nullable
                                                                                    @Nullable DataStorageConfiguration dsCfg,
                                                                                    @Nullable
                                                                                    @Nullable String name)
        Finds and returns a data region configuration with the specified name.
        Parameters:
        dsCfg - Data storage configuration.
        name - Name of data region configuration to find.
        Returns:
        Data region configuration with the specified name or null if the given data storage configuration does not contain such data region. If the name of required data region is null, the default data region is returned.
      • findRemoteDataRegionConfiguration

        @Nullable
        public static @Nullable DataRegionConfiguration findRemoteDataRegionConfiguration​(ClusterNode node,
                                                                                          JdkMarshaller marshaller,
                                                                                          ClassLoader clsLdr,
                                                                                          @Nullable
                                                                                          @Nullable String name)
        Finds and returns a data region configuration with the specified name that is configured on remote node.
        Parameters:
        node - Remote node.
        marshaller - JDK marshaller that is used in order to extract data storage configuration.
        clsLdr - Classloader that is used in order to extract data storage configuration.
        name - Name of data region configuration to find.
        Returns:
        Data region configuration with the specified name or null if the given data storage configuration does not contain such data region. If the name of required data region is null, the default data region is returned.
      • isDefaultDataRegionPersistent

        public static boolean isDefaultDataRegionPersistent​(DataStorageConfiguration cfg)
        Returns:
        true if persistence is enabled for a default data region, false if not.
      • isPersistenceEnabled

        public static boolean isPersistenceEnabled​(IgniteConfiguration cfg)
        Returns:
        true if persistence is enabled for at least one data region, false if not.
      • isPersistenceEnabled

        public static boolean isPersistenceEnabled​(DataStorageConfiguration cfg)
        Returns:
        true if persistence is enabled for at least one data region, false if not.
      • isCdcEnabled

        public static boolean isCdcEnabled​(IgniteConfiguration cfg)
        Parameters:
        cfg - Ignite configuration.
        Returns:
        true if CDC enabled.
      • storeCacheConfig

        public static boolean storeCacheConfig​(GridCacheSharedContext<?,​?> cctx,
                                               CacheConfiguration<?,​?> cacheCfg)
        Checks whether given cache configuration should be persisted.
        Parameters:
        cacheCfg - Cache config.
        Returns:
        True if cache configuration should be persisted, false in other case.
      • encryptedPageSize

        public static int encryptedPageSize​(int pageSize,
                                            EncryptionSpi encSpi)
        Parameters:
        pageSize - Page size.
        encSpi - Encryption spi.
        Returns:
        Page size without encryption overhead.
      • firstPartitioned

        public static GridCacheContext<?,​?> firstPartitioned​(GridCacheSharedContext<?,​?> sctx,
                                                                   Iterable<Integer> cacheIds)
        Parameters:
        sctx - Shared context.
        cacheIds - Cache ids.
        Returns:
        First partitioned cache or null in case no partitioned cache ids are in list.
      • isCacheTemplateName

        public static boolean isCacheTemplateName​(String cacheName)
        Parameters:
        cacheName - Name of cache or cache template.
        Returns:
        true if cache name ends with asterisk (*), and therefire is a template name.
      • patchCacheConfiguration

        public static <K,​V> CacheConfiguration<K,​V> patchCacheConfiguration​(CacheConfiguration<K,​V> oldCfg,
                                                                                        Collection<QueryEntity> entities,
                                                                                        String sqlSchema,
                                                                                        boolean isSqlEscape,
                                                                                        int qryParallelism)
        Patch cache configuration with SchemaAddQueryEntityOperation.
        Parameters:
        oldCfg - Old cache config.
        entities - New query entities.
        sqlSchema - Sql schema name.
        isSqlEscape - Sql escape flag.
        qryParallelism - Query parallelism parameter.