Search in sources :

Example 16 with CacheLoader

use of org.apache.geode.cache.CacheLoader 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)

Example 17 with CacheLoader

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

the class DistributedCacheTestCase method remoteDefineEntry.

/**
   * Defines an entry in the Region with the given name and scope. In 3.0 this method create a
   * subregion named <code>entryName</code> (with the appropriate attributes) that contains an entry
   * named <code>entryName</code>.
   *
   * @param regionName The name of a region that is a sub-region of the root region, or a global
   *        name
   * @param entryName Must be {@link java.io.Serializable}
   * @param doNetSearch Will the distributed region perform a netSearch when looking for objects? If
   *        <code>false</code> a {@link CacheException} will be thrown if an entry in the region is
   *        asked for and it not there.
   */
protected static void remoteDefineEntry(String regionName, String entryName, Scope scope, boolean doNetSearch) throws CacheException {
    Region root = getRootRegion();
    Region region = root.getSubregion(regionName);
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(scope);
    if (!doNetSearch) {
        factory.setCacheLoader(new CacheLoader() {

            public Object load(LoaderHelper helper) throws CacheLoaderException {
                String s = "Should not be loading \"" + helper.getKey() + "\" in \"" + helper.getRegion().getFullPath() + "\"";
                throw new CacheLoaderException(s);
            }

            public void close() {
            }
        });
    }
    Region sub = region.createSubregion(entryName, factory.create());
    sub.create(entryName, null);
    LogWriterUtils.getLogWriter().info("Defined Entry named '" + entryName + "' in region '" + sub.getFullPath() + "'");
}
Also used : LoaderHelper(org.apache.geode.cache.LoaderHelper) AttributesFactory(org.apache.geode.cache.AttributesFactory) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) Region(org.apache.geode.cache.Region) CacheLoader(org.apache.geode.cache.CacheLoader)

Example 18 with CacheLoader

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

the class RemoteTransactionDUnitTest method testPRTXGetOnLocalWithLoader.

@Test
public void testPRTXGetOnLocalWithLoader() {
    Host host = Host.getHost(0);
    VM accessor = host.getVM(0);
    VM datastore = host.getVM(1);
    initAccessorAndDataStore(accessor, datastore, 0);
    datastore.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            AttributesMutator am = getCache().getRegion(CUSTOMER).getAttributesMutator();
            am.setCacheLoader(new CacheLoader() {

                public Object load(LoaderHelper helper) throws CacheLoaderException {
                    return new Customer("sup dawg", "addr");
                }

                public void close() {
                }
            });
            CacheTransactionManager mgr = getGemfireCache().getTxManager();
            mgr.begin();
            Region cust = getCache().getRegion(CUSTOMER);
            CustId custId = new CustId(6);
            Customer s = (Customer) cust.get(custId);
            mgr.commit();
            Customer s2 = (Customer) cust.get(custId);
            Customer expectedCust = new Customer("sup dawg", "addr");
            assertEquals(s, expectedCust);
            assertEquals(s2, expectedCust);
            return null;
        }
    });
    accessor.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            return null;
        }
    });
}
Also used : LoaderHelper(org.apache.geode.cache.LoaderHelper) Customer(org.apache.geode.internal.cache.execute.data.Customer) CustId(org.apache.geode.internal.cache.execute.data.CustId) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Region(org.apache.geode.cache.Region) Host(org.apache.geode.test.dunit.Host) CacheLoader(org.apache.geode.cache.CacheLoader) NamingException(javax.naming.NamingException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) TransactionWriterException(org.apache.geode.cache.TransactionWriterException) CacheWriterException(org.apache.geode.cache.CacheWriterException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) TransactionDataRebalancedException(org.apache.geode.cache.TransactionDataRebalancedException) TransactionException(org.apache.geode.cache.TransactionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) UnsupportedOperationInTransactionException(org.apache.geode.cache.UnsupportedOperationInTransactionException) RollbackException(javax.transaction.RollbackException) TransactionDataNotColocatedException(org.apache.geode.cache.TransactionDataNotColocatedException) CommitConflictException(org.apache.geode.cache.CommitConflictException) AttributesMutator(org.apache.geode.cache.AttributesMutator) CacheTransactionManager(org.apache.geode.cache.CacheTransactionManager) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) TXExpiryJUnitTest(org.apache.geode.TXExpiryJUnitTest) Test(org.junit.Test)

Example 19 with CacheLoader

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

the class RemoteTransactionDUnitTest method testPRTXGetOnRemoteWithLoader.

@Test
public void testPRTXGetOnRemoteWithLoader() {
    Host host = Host.getHost(0);
    VM accessor = host.getVM(0);
    VM datastore = host.getVM(1);
    initAccessorAndDataStore(accessor, datastore, 0);
    datastore.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            AttributesMutator am = getCache().getRegion(CUSTOMER).getAttributesMutator();
            am.setCacheLoader(new CacheLoader() {

                public Object load(LoaderHelper helper) throws CacheLoaderException {
                    return new Customer("sup dawg", "add");
                }

                public void close() {
                }
            });
            return null;
        }
    });
    accessor.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            CacheTransactionManager mgr = getGemfireCache().getTxManager();
            mgr.begin();
            Region cust = getCache().getRegion(CUSTOMER);
            Customer s = (Customer) cust.get(new CustId(8));
            assertEquals(new Customer("sup dawg", "add"), s);
            assertTrue(cust.containsKey(new CustId(8)));
            TXStateProxy tx = ((TXManagerImpl) mgr).internalSuspend();
            assertFalse(cust.containsKey(new CustId(8)));
            ((TXManagerImpl) mgr).internalResume(tx);
            mgr.commit();
            Customer s2 = (Customer) cust.get(new CustId(8));
            Customer ex = new Customer("sup dawg", "add");
            assertEquals(ex, s);
            assertEquals(ex, s2);
            return null;
        }
    });
}
Also used : Customer(org.apache.geode.internal.cache.execute.data.Customer) Host(org.apache.geode.test.dunit.Host) NamingException(javax.naming.NamingException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) TransactionWriterException(org.apache.geode.cache.TransactionWriterException) CacheWriterException(org.apache.geode.cache.CacheWriterException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) TransactionDataRebalancedException(org.apache.geode.cache.TransactionDataRebalancedException) TransactionException(org.apache.geode.cache.TransactionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) UnsupportedOperationInTransactionException(org.apache.geode.cache.UnsupportedOperationInTransactionException) RollbackException(javax.transaction.RollbackException) TransactionDataNotColocatedException(org.apache.geode.cache.TransactionDataNotColocatedException) CommitConflictException(org.apache.geode.cache.CommitConflictException) CacheTransactionManager(org.apache.geode.cache.CacheTransactionManager) LoaderHelper(org.apache.geode.cache.LoaderHelper) CustId(org.apache.geode.internal.cache.execute.data.CustId) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Region(org.apache.geode.cache.Region) CacheLoader(org.apache.geode.cache.CacheLoader) AttributesMutator(org.apache.geode.cache.AttributesMutator) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) TXExpiryJUnitTest(org.apache.geode.TXExpiryJUnitTest) Test(org.junit.Test)

Example 20 with CacheLoader

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

the class CacheAdvisorDUnitTest method testNetLoadAdvice.

@Test
public void testNetLoadAdvice() throws Exception {
    final String rgnName = getUniqueName();
    Set expected = new HashSet();
    for (int i = 0; i < vms.length; i++) {
        VM vm = vms[i];
        InternalDistributedMember id = ids[i];
        if (i % 2 == 1) {
            expected.add(id);
        }
        final int index = i;
        vm.invoke(new CacheSerializableRunnable("CacheAdvisorDUnitTest.testNetLoadAdvice") {

            public void run2() throws CacheException {
                AttributesFactory fac = new AttributesFactory();
                if (index % 2 == 1) {
                    fac.setCacheLoader(new CacheLoader() {

                        public Object load(LoaderHelper helper) throws CacheLoaderException {
                            return null;
                        }

                        public void close() {
                        }
                    });
                }
                createRegion(rgnName, fac.create());
            }
        });
    }
    RegionAttributes attrs = new AttributesFactory().create();
    DistributedRegion rgn = (DistributedRegion) createRegion(rgnName, attrs);
    assertEquals(expected, rgn.getCacheDistributionAdvisor().adviseNetLoad());
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) CacheException(org.apache.geode.cache.CacheException) RegionAttributes(org.apache.geode.cache.RegionAttributes) LoaderHelper(org.apache.geode.cache.LoaderHelper) AttributesFactory(org.apache.geode.cache.AttributesFactory) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) VM(org.apache.geode.test.dunit.VM) CacheLoader(org.apache.geode.cache.CacheLoader) HashSet(java.util.HashSet) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

CacheLoader (org.apache.geode.cache.CacheLoader)40 LoaderHelper (org.apache.geode.cache.LoaderHelper)32 Region (org.apache.geode.cache.Region)24 Test (org.junit.Test)24 AttributesFactory (org.apache.geode.cache.AttributesFactory)21 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)20 CacheException (org.apache.geode.cache.CacheException)18 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)17 VM (org.apache.geode.test.dunit.VM)16 Host (org.apache.geode.test.dunit.Host)13 CacheWriterException (org.apache.geode.cache.CacheWriterException)9 LocalRegion (org.apache.geode.internal.cache.LocalRegion)9 AttributesMutator (org.apache.geode.cache.AttributesMutator)8 RegionAttributes (org.apache.geode.cache.RegionAttributes)8 TimeoutException (org.apache.geode.cache.TimeoutException)7 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)7 FlakyTest (org.apache.geode.test.junit.categories.FlakyTest)7 HashSet (java.util.HashSet)6 Set (java.util.Set)6 Properties (java.util.Properties)5