Search in sources :

Example 1 with CacheWriter

use of org.apache.geode.cache.CacheWriter in project geode by apache.

the class RegionHelper method getRegionAttributes.

private static RegionAttributes getRegionAttributes(Cache cache, RegionConfiguration configuration) {
    // Create the requested attributes
    RegionAttributes baseRequestedAttributes = cache.getRegionAttributes(configuration.getRegionAttributesId());
    if (baseRequestedAttributes == null) {
        throw new IllegalArgumentException("No region attributes named " + configuration.getRegionAttributesId() + " are defined.");
    }
    AttributesFactory requestedFactory = new AttributesFactory(baseRequestedAttributes);
    // Set the expiration time and action if necessary
    int maxInactiveInterval = configuration.getMaxInactiveInterval();
    if (maxInactiveInterval != RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL) {
        requestedFactory.setStatisticsEnabled(true);
        if (configuration.getCustomExpiry() == null) {
            requestedFactory.setEntryIdleTimeout(new ExpirationAttributes(maxInactiveInterval, ExpirationAction.DESTROY));
        } else {
            requestedFactory.setCustomEntryIdleTimeout(configuration.getCustomExpiry());
        }
    }
    // Add the gateway delta region cache listener if necessary
    if (configuration.getEnableGatewayDeltaReplication()) {
        // Add the listener that forwards created/destroyed deltas to the gateway
        requestedFactory.addCacheListener(new GatewayDeltaForwarderCacheListener(cache));
    }
    // Add the debug cache listener if necessary
    if (configuration.getEnableDebugListener()) {
        requestedFactory.addCacheListener(new DebugCacheListener());
    }
    if (configuration.getSessionExpirationCacheListener()) {
        requestedFactory.addCacheListener(new SessionExpirationCacheListener());
    }
    // Add the cacheWriter if necessary
    if (configuration.getCacheWriterName() != null) {
        try {
            CacheWriter writer = (CacheWriter) Class.forName(configuration.getCacheWriterName()).newInstance();
            requestedFactory.setCacheWriter(writer);
        } catch (InstantiationException e) {
            throw new RuntimeException("Could not set a cacheWriter for the region", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Could not set a cacheWriter for the region", e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not set a cacheWriter for the region", e);
        }
    }
    return requestedFactory.create();
}
Also used : GatewayDeltaForwarderCacheListener(org.apache.geode.modules.gatewaydelta.GatewayDeltaForwarderCacheListener) RegionAttributes(org.apache.geode.cache.RegionAttributes) AttributesFactory(org.apache.geode.cache.AttributesFactory) SessionExpirationCacheListener(org.apache.geode.modules.session.catalina.callback.SessionExpirationCacheListener) CacheWriter(org.apache.geode.cache.CacheWriter) ExpirationAttributes(org.apache.geode.cache.ExpirationAttributes)

Example 2 with CacheWriter

use of org.apache.geode.cache.CacheWriter in project geode by apache.

the class RegionAttributesCreation method setCacheWriter.

public CacheWriter setCacheWriter(CacheWriter cacheWriter) {
    CacheWriter old = this.cacheWriter;
    this.cacheWriter = cacheWriter;
    setHasCacheWriter(true);
    return old;
}
Also used : CacheWriter(org.apache.geode.cache.CacheWriter)

Example 3 with CacheWriter

use of org.apache.geode.cache.CacheWriter in project geode by apache.

the class AbstractRegionMap method basicPut.

/*
   * returns null if the operation fails
   */
public RegionEntry basicPut(EntryEventImpl event, final long lastModified, final boolean ifNew, // only non-null if ifOld
final boolean ifOld, // only non-null if ifOld
Object expectedOldValue, boolean requireOldValue, final boolean overwriteDestroyed) throws CacheWriterException, TimeoutException {
    final LocalRegion owner = _getOwner();
    boolean clearOccured = false;
    if (owner == null) {
        // "fix" for bug 32440
        Assert.assertTrue(false, "The owner for RegionMap " + this + " is null for event " + event);
    }
    if (logger.isTraceEnabled(LogMarker.LRU_TOMBSTONE_COUNT) && !(owner instanceof HARegion)) {
        logger.trace(LogMarker.LRU_TOMBSTONE_COUNT, "ARM.basicPut called for {} expectedOldValue={} requireOldValue={} ifNew={} ifOld={} initialized={} overwriteDestroyed={}", event, expectedOldValue, requireOldValue, ifNew, ifOld, owner.isInitialized(), overwriteDestroyed);
    }
    RegionEntry result = null;
    long lastModifiedTime = 0;
    // copy into local var to prevent race condition with setter
    final CacheWriter cacheWriter = owner.basicGetWriter();
    final boolean cacheWrite = !event.isOriginRemote() && !event.isNetSearch() && event.isGenerateCallbacks() && (cacheWriter != null || owner.hasServerProxy() || owner.scope.isDistributed());
    /*
     * For performance reason, we try to minimize object creation and do as much work as we can
     * outside of synchronization, especially getting distribution advice.
     */
    final Set netWriteRecipients;
    if (cacheWrite) {
        if (cacheWriter == null && owner.scope.isDistributed()) {
            netWriteRecipients = ((DistributedRegion) owner).getCacheDistributionAdvisor().adviseNetWrite();
        } else {
            netWriteRecipients = null;
        }
    } else {
        netWriteRecipients = null;
    }
    // mbid: this has been added to maintain consistency between the disk region
    // and the region map after clear() has been called. This will set the
    // reference of the diskSegmentRegion as a ThreadLocal so that if the diskRegionSegment
    // is later changed by another thread, we can do the necessary.
    boolean uninitialized = !owner.isInitialized();
    boolean retrieveOldValueForDelta = event.getDeltaBytes() != null && event.getRawNewValue() == null;
    IndexManager oqlIndexManager = null;
    lockForCacheModification(owner, event);
    try {
        try {
            // Fix for Bug #44431. We do NOT want to update the region and wait
            // later for index INIT as region.clear() can cause inconsistency if
            // happened in parallel as it also does index INIT.
            oqlIndexManager = owner.getIndexManager();
            if (oqlIndexManager != null) {
                oqlIndexManager.waitForIndexInit();
            }
            // fix for bug #42169, replace must go to server if entry not on client
            boolean replaceOnClient = event.getOperation() == Operation.REPLACE && owner.getServerProxy() != null;
            // Rather than having two different blocks for synchronizing oldRe
            // and newRe, have only one block and synchronize re
            RegionEntry re = null;
            boolean eventRecorded = false;
            boolean onlyExisting = ifOld && !replaceOnClient;
            re = getOrCreateRegionEntry(owner, event, Token.REMOVED_PHASE1, null, onlyExisting, false);
            if (re == null) {
                return null;
            }
            while (true) {
                synchronized (re) {
                    // and change its state
                    if (re.isRemovedPhase2()) {
                        _getOwner().getCachePerfStats().incRetries();
                        _getMap().remove(event.getKey(), re);
                        re = getOrCreateRegionEntry(owner, event, Token.REMOVED_PHASE1, null, onlyExisting, false);
                        if (re == null) {
                            // this will happen when onlyExisting is true
                            return null;
                        }
                        continue;
                    } else {
                        @Released Object oldValueForDelta = null;
                        if (retrieveOldValueForDelta) {
                            // defer the lruUpdateCallback to prevent a deadlock (see bug 51121).
                            final boolean disabled = disableLruUpdateCallback();
                            try {
                                // Old value is faulted in from disk if not found in memory.
                                // OFFHEAP: if we are synced on oldRe no
                                oldValueForDelta = re.getValue(owner);
                            // issue since we can use ARE's ref
                            } finally {
                                if (disabled) {
                                    enableLruUpdateCallback();
                                }
                            }
                        }
                        try {
                            event.setRegionEntry(re);
                            // set old value in event
                            setOldValueInEvent(event, re, cacheWrite, requireOldValue);
                            if (!continueUpdate(re, event, ifOld, replaceOnClient)) {
                                return null;
                            }
                            // overwrite destroyed?
                            if (!continueOverwriteDestroyed(re, event, overwriteDestroyed, ifNew)) {
                                return null;
                            }
                            // check expectedOldValue
                            if (!satisfiesExpectedOldValue(event, re, expectedOldValue, replaceOnClient)) {
                                return null;
                            }
                            // invoke cacheWriter
                            invokeCacheWriter(re, event, cacheWrite, cacheWriter, netWriteRecipients, requireOldValue, expectedOldValue, replaceOnClient);
                            // notify index of an update
                            notifyIndex(re, true);
                            try {
                                try {
                                    if (// if there is a
                                    (cacheWrite && event.getOperation().isUpdate()) || // set
                                    !re.isRemoved() || replaceOnClient) {
                                        // update
                                        updateEntry(event, requireOldValue, oldValueForDelta, re);
                                    } else {
                                        // create
                                        createEntry(event, owner, re);
                                    }
                                    owner.recordEvent(event);
                                    eventRecorded = true;
                                } catch (RegionClearedException rce) {
                                    clearOccured = true;
                                    owner.recordEvent(event);
                                } catch (ConcurrentCacheModificationException ccme) {
                                    VersionTag tag = event.getVersionTag();
                                    if (tag != null && tag.isTimeStampUpdated()) {
                                        // Notify gateways of new time-stamp.
                                        owner.notifyTimestampsToGateways(event);
                                    }
                                    throw ccme;
                                }
                                if (uninitialized) {
                                    event.inhibitCacheListenerNotification(true);
                                }
                                updateLru(clearOccured, re, event);
                                lastModifiedTime = owner.basicPutPart2(event, re, !uninitialized, lastModifiedTime, clearOccured);
                            } finally {
                                notifyIndex(re, false);
                            }
                            result = re;
                            break;
                        } finally {
                            OffHeapHelper.release(oldValueForDelta);
                            if (re != null && !onlyExisting && !isOpComplete(re, event)) {
                                owner.cleanUpOnIncompleteOp(event, re);
                            } else if (re != null && owner.isUsedForPartitionedRegionBucket()) {
                                BucketRegion br = (BucketRegion) owner;
                                CachePerfStats stats = br.getPartitionedRegion().getCachePerfStats();
                            }
                        }
                    // try
                    }
                }
            // sync re
            }
        // end while
        } catch (DiskAccessException dae) {
            // Asif:Feel that it is safe to destroy the region here as there appears
            // to be no chance of deadlock during region destruction
            result = null;
            this._getOwner().handleDiskAccessException(dae);
            throw dae;
        } finally {
            if (oqlIndexManager != null) {
                oqlIndexManager.countDownIndexUpdaters();
            }
            if (result != null) {
                try {
                    // Note we do distribution after releasing all sync to avoid deadlock
                    final boolean invokeListeners = event.basicGetNewValue() != Token.TOMBSTONE;
                    owner.basicPutPart3(event, result, !uninitialized, lastModifiedTime, invokeListeners, ifNew, ifOld, expectedOldValue, requireOldValue);
                } finally {
                    // for any recipients
                    if (!clearOccured) {
                        try {
                            lruUpdateCallback();
                        } catch (DiskAccessException dae) {
                            // Asif:Feel that it is safe to destroy the region here as there appears
                            // to be no chance of deadlock during region destruction
                            result = null;
                            this._getOwner().handleDiskAccessException(dae);
                            throw dae;
                        }
                    }
                }
            // finally
            } else {
                resetThreadLocals();
            }
        }
    } finally {
        releaseCacheModificationLock(owner, event);
    }
    return result;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Released(org.apache.geode.internal.offheap.annotations.Released) ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) IndexManager(org.apache.geode.cache.query.internal.index.IndexManager) CacheWriter(org.apache.geode.cache.CacheWriter) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) DiskAccessException(org.apache.geode.cache.DiskAccessException) StoredObject(org.apache.geode.internal.offheap.StoredObject)

Example 4 with CacheWriter

use of org.apache.geode.cache.CacheWriter in project geode by apache.

the class RegionAlterFunction method alterRegion.

private <K, V> Region<?, ?> alterRegion(Cache cache, RegionFunctionArgs regionAlterArgs) {
    final String regionPathString = regionAlterArgs.getRegionPath();
    RegionPath regionPath = new RegionPath(regionPathString);
    AbstractRegion region = (AbstractRegion) cache.getRegion(regionPathString);
    if (region == null) {
        throw new IllegalArgumentException(CliStrings.format(CliStrings.ALTER_REGION__MSG__REGION_DOESNT_EXIST_0, new Object[] { regionPath }));
    }
    AttributesMutator mutator = region.getAttributesMutator();
    if (regionAlterArgs.isCloningEnabled() != null) {
        mutator.setCloningEnabled(regionAlterArgs.isCloningEnabled());
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - cloning");
        }
    }
    if (regionAlterArgs.getEvictionMax() != null) {
        mutator.getEvictionAttributesMutator().setMaximum(regionAlterArgs.getEvictionMax());
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - eviction attributes max");
        }
    }
    // Alter expiration attributes
    final RegionFunctionArgs.ExpirationAttrs newEntryExpirationIdleTime = regionAlterArgs.getEntryExpirationIdleTime();
    if (newEntryExpirationIdleTime != null) {
        mutator.setEntryIdleTimeout(parseExpirationAttributes(newEntryExpirationIdleTime, region.getEntryIdleTimeout()));
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - entry idle timeout");
        }
    }
    final RegionFunctionArgs.ExpirationAttrs newEntryExpirationTTL = regionAlterArgs.getEntryExpirationTTL();
    if (newEntryExpirationTTL != null) {
        mutator.setEntryTimeToLive(parseExpirationAttributes(newEntryExpirationTTL, region.getEntryTimeToLive()));
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - entry TTL");
        }
    }
    final RegionFunctionArgs.ExpirationAttrs newRegionExpirationIdleTime = regionAlterArgs.getRegionExpirationIdleTime();
    if (newRegionExpirationIdleTime != null) {
        mutator.setRegionIdleTimeout(parseExpirationAttributes(newRegionExpirationIdleTime, region.getRegionIdleTimeout()));
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - region idle timeout");
        }
    }
    final RegionFunctionArgs.ExpirationAttrs newRegionExpirationTTL = regionAlterArgs.getRegionExpirationTTL();
    if (newRegionExpirationTTL != null) {
        mutator.setRegionTimeToLive(parseExpirationAttributes(newRegionExpirationTTL, region.getRegionTimeToLive()));
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - region TTL");
        }
    }
    // Alter Gateway Sender Ids
    final Set<String> newGatewaySenderIds = regionAlterArgs.getGatewaySenderIds();
    if (newGatewaySenderIds != null) {
        // Remove old gateway sender ids that aren't in the new list
        Set<String> oldGatewaySenderIds = region.getGatewaySenderIds();
        if (!oldGatewaySenderIds.isEmpty()) {
            for (String gatewaySenderId : oldGatewaySenderIds) {
                if (!newGatewaySenderIds.contains(gatewaySenderId)) {
                    mutator.removeGatewaySenderId(gatewaySenderId);
                }
            }
        }
        // Add new gateway sender ids that don't already exist
        for (String gatewaySenderId : newGatewaySenderIds) {
            if (!oldGatewaySenderIds.contains(gatewaySenderId)) {
                mutator.addGatewaySenderId(gatewaySenderId);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - gateway sender IDs");
        }
    }
    // Alter Async Queue Ids
    final Set<String> newAsyncEventQueueIds = regionAlterArgs.getAsyncEventQueueIds();
    if (newAsyncEventQueueIds != null) {
        // Remove old async event queue ids that aren't in the new list
        Set<String> oldAsyncEventQueueIds = region.getAsyncEventQueueIds();
        if (!oldAsyncEventQueueIds.isEmpty()) {
            for (String asyncEventQueueId : oldAsyncEventQueueIds) {
                if (!newAsyncEventQueueIds.contains(asyncEventQueueId)) {
                    mutator.removeAsyncEventQueueId(asyncEventQueueId);
                }
            }
        }
        // Add new async event queue ids that don't already exist
        for (String asyncEventQueueId : newAsyncEventQueueIds) {
            if (!oldAsyncEventQueueIds.contains(asyncEventQueueId)) {
                mutator.addAsyncEventQueueId(asyncEventQueueId);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - async event queue IDs");
        }
    }
    // Alter Cache Listeners
    final Set<String> newCacheListenerNames = regionAlterArgs.getCacheListeners();
    if (newCacheListenerNames != null) {
        // Remove old cache listeners that aren't in the new list
        CacheListener[] oldCacheListeners = region.getCacheListeners();
        for (CacheListener oldCacheListener : oldCacheListeners) {
            if (!newCacheListenerNames.contains(oldCacheListener.getClass().getName())) {
                mutator.removeCacheListener(oldCacheListener);
            }
        }
        // Add new cache listeners that don't already exist
        for (String newCacheListenerName : newCacheListenerNames) {
            if (newCacheListenerName.isEmpty()) {
                continue;
            }
            boolean nameFound = false;
            for (CacheListener oldCacheListener : oldCacheListeners) {
                if (oldCacheListener.getClass().getName().equals(newCacheListenerName)) {
                    nameFound = true;
                    break;
                }
            }
            if (!nameFound) {
                Class<CacheListener<K, V>> cacheListenerKlass = forName(newCacheListenerName, CliStrings.ALTER_REGION__CACHELISTENER);
                mutator.addCacheListener(newInstance(cacheListenerKlass, CliStrings.ALTER_REGION__CACHELISTENER));
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - cache listeners");
        }
    }
    final String cacheLoader = regionAlterArgs.getCacheLoader();
    if (cacheLoader != null) {
        if (cacheLoader.isEmpty()) {
            mutator.setCacheLoader(null);
        } else {
            Class<CacheLoader<K, V>> cacheLoaderKlass = forName(cacheLoader, CliStrings.ALTER_REGION__CACHELOADER);
            mutator.setCacheLoader(newInstance(cacheLoaderKlass, CliStrings.ALTER_REGION__CACHELOADER));
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - cache loader");
        }
    }
    final String cacheWriter = regionAlterArgs.getCacheWriter();
    if (cacheWriter != null) {
        if (cacheWriter.isEmpty()) {
            mutator.setCacheWriter(null);
        } else {
            Class<CacheWriter<K, V>> cacheWriterKlass = forName(cacheWriter, CliStrings.ALTER_REGION__CACHEWRITER);
            mutator.setCacheWriter(newInstance(cacheWriterKlass, CliStrings.ALTER_REGION__CACHEWRITER));
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Region successfully altered - cache writer");
        }
    }
    return region;
}
Also used : AbstractRegion(org.apache.geode.internal.cache.AbstractRegion) CacheListener(org.apache.geode.cache.CacheListener) RegionPath(org.apache.geode.management.internal.cli.util.RegionPath) CacheWriter(org.apache.geode.cache.CacheWriter) CacheLoader(org.apache.geode.cache.CacheLoader) AttributesMutator(org.apache.geode.cache.AttributesMutator)

Example 5 with CacheWriter

use of org.apache.geode.cache.CacheWriter in project geode by apache.

the class RegionCreateFunction method createRegion.

public static <K, V> Region<?, ?> createRegion(Cache cache, RegionFunctionArgs regionCreateArgs) {
    Region<K, V> createdRegion = null;
    final String regionPath = regionCreateArgs.getRegionPath();
    final RegionShortcut regionShortcut = regionCreateArgs.getRegionShortcut();
    final String useAttributesFrom = regionCreateArgs.getUseAttributesFrom();
    // If a region path indicates a sub-region, check whether the parent region exists
    RegionPath regionPathData = new RegionPath(regionPath);
    String parentRegionPath = regionPathData.getParent();
    Region<?, ?> parentRegion = null;
    if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
        parentRegion = cache.getRegion(parentRegionPath);
        if (parentRegion == null) {
            throw new IllegalArgumentException(CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOESNOT_EXIST, new Object[] { regionPath }));
        }
        if (parentRegion.getAttributes().getPartitionAttributes() != null) {
            // For a PR, sub-regions are not supported.
            throw new CreateSubregionException(CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_A_PR_CANNOT_HAVE_SUBREGIONS, parentRegion.getFullPath()));
        }
    }
    // One of Region Shortcut OR Use Attributes From has to be given
    if (regionShortcut == null && useAttributesFrom == null) {
        throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_IS_REQUIRED);
    }
    boolean isPartitioned = false;
    RegionFactory<K, V> factory = null;
    RegionAttributes<K, V> regionAttributes = null;
    if (regionShortcut != null) {
        regionAttributes = cache.getRegionAttributes(regionShortcut.toString());
        if (logger.isDebugEnabled()) {
            logger.debug("Using shortcut {} for {} region attributes : {}", regionShortcut, regionPath, regionAttributes);
        }
        if (regionAttributes == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Shortcut {} doesn't have attributes in {}", regionShortcut, cache.listRegionAttributes());
            }
            throw new IllegalStateException(CliStrings.format(CliStrings.CREATE_REGION__MSG__COULDNOT_LOAD_REGION_ATTRIBUTES_FOR_SHORTCUT_0, regionShortcut));
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Using Manager's region attributes for {}", regionPath);
        }
        regionAttributes = regionCreateArgs.getRegionAttributes();
        if (logger.isDebugEnabled()) {
            logger.debug("Using Attributes : {}", regionAttributes);
        }
    }
    isPartitioned = regionAttributes.getPartitionAttributes() != null;
    factory = cache.createRegionFactory(regionAttributes);
    if (!isPartitioned && regionCreateArgs.hasPartitionAttributes()) {
        throw new IllegalArgumentException(CliStrings.format(CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION, regionCreateArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()));
    }
    if (isPartitioned) {
        PartitionAttributes<K, V> partitionAttributes = extractPartitionAttributes(cache, regionAttributes, regionCreateArgs);
        DataPolicy originalDataPolicy = regionAttributes.getDataPolicy();
        factory.setPartitionAttributes(partitionAttributes);
        // We have to do this because AttributesFactory.setPartitionAttributes()
        // checks RegionAttributes.hasDataPolicy() which is set only when the data
        // policy is set explicitly
        factory.setDataPolicy(originalDataPolicy);
    }
    // Set Constraints
    final String keyConstraint = regionCreateArgs.getKeyConstraint();
    final String valueConstraint = regionCreateArgs.getValueConstraint();
    if (keyConstraint != null && !keyConstraint.isEmpty()) {
        Class<K> keyConstraintClass = CliUtil.forName(keyConstraint, CliStrings.CREATE_REGION__KEYCONSTRAINT);
        factory.setKeyConstraint(keyConstraintClass);
    }
    if (valueConstraint != null && !valueConstraint.isEmpty()) {
        Class<V> valueConstraintClass = CliUtil.forName(valueConstraint, CliStrings.CREATE_REGION__VALUECONSTRAINT);
        factory.setValueConstraint(valueConstraintClass);
    }
    // Expiration attributes
    final RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime = regionCreateArgs.getEntryExpirationIdleTime();
    if (entryExpirationIdleTime != null) {
        factory.setEntryIdleTimeout(entryExpirationIdleTime.convertToExpirationAttributes());
    }
    final RegionFunctionArgs.ExpirationAttrs entryExpirationTTL = regionCreateArgs.getEntryExpirationTTL();
    if (entryExpirationTTL != null) {
        factory.setEntryTimeToLive(entryExpirationTTL.convertToExpirationAttributes());
    }
    final RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime = regionCreateArgs.getRegionExpirationIdleTime();
    if (regionExpirationIdleTime != null) {
        factory.setEntryIdleTimeout(regionExpirationIdleTime.convertToExpirationAttributes());
    }
    final RegionFunctionArgs.ExpirationAttrs regionExpirationTTL = regionCreateArgs.getRegionExpirationTTL();
    if (regionExpirationTTL != null) {
        factory.setEntryTimeToLive(regionExpirationTTL.convertToExpirationAttributes());
    }
    // Associate a Disk Store
    final String diskStore = regionCreateArgs.getDiskStore();
    if (diskStore != null && !diskStore.isEmpty()) {
        factory.setDiskStoreName(diskStore);
    }
    if (regionCreateArgs.isSetDiskSynchronous()) {
        factory.setDiskSynchronous(regionCreateArgs.isDiskSynchronous());
    }
    if (regionCreateArgs.isSetOffHeap()) {
        factory.setOffHeap(regionCreateArgs.isOffHeap());
    }
    // Set stats enabled
    if (regionCreateArgs.isSetStatisticsEnabled()) {
        factory.setStatisticsEnabled(regionCreateArgs.isStatisticsEnabled());
    }
    // Set conflation
    if (regionCreateArgs.isSetEnableAsyncConflation()) {
        factory.setEnableAsyncConflation(regionCreateArgs.isEnableAsyncConflation());
    }
    if (regionCreateArgs.isSetEnableSubscriptionConflation()) {
        factory.setEnableSubscriptionConflation(regionCreateArgs.isEnableSubscriptionConflation());
    }
    // Gateway Sender Ids
    final Set<String> gatewaySenderIds = regionCreateArgs.getGatewaySenderIds();
    if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
        for (String gatewaySenderId : gatewaySenderIds) {
            factory.addGatewaySenderId(gatewaySenderId);
        }
    }
    // Async Queue Ids
    final Set<String> asyncEventQueueIds = regionCreateArgs.getAsyncEventQueueIds();
    if (asyncEventQueueIds != null && !asyncEventQueueIds.isEmpty()) {
        for (String asyncEventQueueId : asyncEventQueueIds) {
            factory.addAsyncEventQueueId(asyncEventQueueId);
        }
    }
    // concurrency check enabled & concurrency level
    if (regionCreateArgs.isSetConcurrencyChecksEnabled()) {
        factory.setConcurrencyChecksEnabled(regionCreateArgs.isConcurrencyChecksEnabled());
    }
    if (regionCreateArgs.isSetConcurrencyLevel()) {
        factory.setConcurrencyLevel(regionCreateArgs.getConcurrencyLevel());
    }
    // cloning enabled for delta
    if (regionCreateArgs.isSetCloningEnabled()) {
        factory.setCloningEnabled(regionCreateArgs.isCloningEnabled());
    }
    // multicast enabled for replication
    if (regionCreateArgs.isSetMcastEnabled()) {
        factory.setMulticastEnabled(regionCreateArgs.isMcastEnabled());
    }
    // Set plugins
    final Set<String> cacheListeners = regionCreateArgs.getCacheListeners();
    if (cacheListeners != null && !cacheListeners.isEmpty()) {
        for (String cacheListener : cacheListeners) {
            Class<CacheListener<K, V>> cacheListenerKlass = CliUtil.forName(cacheListener, CliStrings.CREATE_REGION__CACHELISTENER);
            factory.addCacheListener(CliUtil.newInstance(cacheListenerKlass, CliStrings.CREATE_REGION__CACHELISTENER));
        }
    }
    // Compression provider
    if (regionCreateArgs.isSetCompressor()) {
        Class<Compressor> compressorKlass = CliUtil.forName(regionCreateArgs.getCompressor(), CliStrings.CREATE_REGION__COMPRESSOR);
        factory.setCompressor(CliUtil.newInstance(compressorKlass, CliStrings.CREATE_REGION__COMPRESSOR));
    }
    final String cacheLoader = regionCreateArgs.getCacheLoader();
    if (cacheLoader != null) {
        Class<CacheLoader<K, V>> cacheLoaderKlass = CliUtil.forName(cacheLoader, CliStrings.CREATE_REGION__CACHELOADER);
        factory.setCacheLoader(CliUtil.newInstance(cacheLoaderKlass, CliStrings.CREATE_REGION__CACHELOADER));
    }
    final String cacheWriter = regionCreateArgs.getCacheWriter();
    if (cacheWriter != null) {
        Class<CacheWriter<K, V>> cacheWriterKlass = CliUtil.forName(cacheWriter, CliStrings.CREATE_REGION__CACHEWRITER);
        factory.setCacheWriter(CliUtil.newInstance(cacheWriterKlass, CliStrings.CREATE_REGION__CACHEWRITER));
    }
    String regionName = regionPathData.getName();
    if (parentRegion != null) {
        createdRegion = factory.createSubregion(parentRegion, regionName);
    } else {
        createdRegion = factory.create(regionName);
    }
    return createdRegion;
}
Also used : RegionShortcut(org.apache.geode.cache.RegionShortcut) CacheListener(org.apache.geode.cache.CacheListener) CacheWriter(org.apache.geode.cache.CacheWriter) DataPolicy(org.apache.geode.cache.DataPolicy) Compressor(org.apache.geode.compression.Compressor) RegionPath(org.apache.geode.management.internal.cli.util.RegionPath) CreateSubregionException(org.apache.geode.management.internal.cli.exceptions.CreateSubregionException) CacheLoader(org.apache.geode.cache.CacheLoader)

Aggregations

CacheWriter (org.apache.geode.cache.CacheWriter)31 AttributesFactory (org.apache.geode.cache.AttributesFactory)16 CacheException (org.apache.geode.cache.CacheException)12 RegionAttributes (org.apache.geode.cache.RegionAttributes)9 CacheListener (org.apache.geode.cache.CacheListener)7 Test (org.junit.Test)7 Set (java.util.Set)6 CacheWriterException (org.apache.geode.cache.CacheWriterException)6 EntryEvent (org.apache.geode.cache.EntryEvent)6 TimeoutException (org.apache.geode.cache.TimeoutException)6 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)6 HashSet (java.util.HashSet)5 RegionEvent (org.apache.geode.cache.RegionEvent)5 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)5 CacheLoader (org.apache.geode.cache.CacheLoader)4 Region (org.apache.geode.cache.Region)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 AttributesMutator (org.apache.geode.cache.AttributesMutator)3 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)3