Search in sources :

Example 86 with ClientCache

use of org.apache.geode.cache.client.ClientCache in project geode by apache.

the class CacheServerTestUtil method createClientCache.

public static void createClientCache(Pool poolAttr, String regionName, Properties dsProperties) throws Exception {
    ClientCacheFactory ccf = new ClientCacheFactory(dsProperties);
    if (poolAttr != null) {
        ccf.setPoolFreeConnectionTimeout(poolAttr.getFreeConnectionTimeout()).setPoolLoadConditioningInterval(poolAttr.getLoadConditioningInterval()).setPoolSocketBufferSize(poolAttr.getSocketBufferSize()).setPoolMinConnections(poolAttr.getMinConnections()).setPoolMaxConnections(poolAttr.getMaxConnections()).setPoolIdleTimeout(poolAttr.getIdleTimeout()).setPoolPingInterval(poolAttr.getPingInterval()).setPoolStatisticInterval(poolAttr.getStatisticInterval()).setPoolRetryAttempts(poolAttr.getRetryAttempts()).setPoolThreadLocalConnections(poolAttr.getThreadLocalConnections()).setPoolReadTimeout(poolAttr.getReadTimeout()).setPoolSubscriptionEnabled(poolAttr.getSubscriptionEnabled()).setPoolPRSingleHopEnabled(poolAttr.getPRSingleHopEnabled()).setPoolSubscriptionRedundancy(poolAttr.getSubscriptionRedundancy()).setPoolSubscriptionMessageTrackingTimeout(poolAttr.getSubscriptionMessageTrackingTimeout()).setPoolSubscriptionAckInterval(poolAttr.getSubscriptionAckInterval()).setPoolServerGroup(poolAttr.getServerGroup()).setPoolMultiuserAuthentication(poolAttr.getMultiuserAuthentication());
        for (InetSocketAddress locator : poolAttr.getLocators()) {
            ccf.addPoolLocator(locator.getHostName(), locator.getPort());
        }
        for (InetSocketAddress server : poolAttr.getServers()) {
            ccf.addPoolServer(server.getHostName(), server.getPort());
        }
    }
    new CacheServerTestUtil().createClientCache(dsProperties, ccf);
    ClientCache cc = (ClientCache) cache;
    cc.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);
    pool = (PoolImpl) ((GemFireCacheImpl) cc).getDefaultPool();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) ClientCache(org.apache.geode.cache.client.ClientCache) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory)

Example 87 with ClientCache

use of org.apache.geode.cache.client.ClientCache in project geode by apache.

the class LuceneQueriesClientDUnitTest method postSetUp.

@Override
public void postSetUp() throws Exception {
    super.postSetUp();
    SerializableCallableIF<Integer> launchServer = () -> {
        final Cache cache = getCache();
        final CacheServer server = cache.addCacheServer();
        server.setPort(0);
        server.start();
        return server.getPort();
    };
    final int port1 = dataStore1.invoke(launchServer);
    final int port2 = dataStore2.invoke(launchServer);
    accessor.invoke(() -> {
        ClientCacheFactory clientCacheFactory = new ClientCacheFactory();
        clientCacheFactory.addPoolServer("localhost", port1);
        clientCacheFactory.addPoolServer("localhost", port2);
        ClientCache clientCache = getClientCache(clientCacheFactory);
        clientCache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(REGION_NAME);
    });
}
Also used : CacheServer(org.apache.geode.cache.server.CacheServer) ClientCache(org.apache.geode.cache.client.ClientCache) Cache(org.apache.geode.cache.Cache) ClientCache(org.apache.geode.cache.client.ClientCache) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory)

Example 88 with ClientCache

use of org.apache.geode.cache.client.ClientCache in project geode by apache.

the class PartitionedRegionQueryDUnitTest method testOrderByOnPRWithReservedKeywords.

@Test
public void testOrderByOnPRWithReservedKeywords() throws Exception {
    final Host host = Host.getHost(0);
    final VM server1 = host.getVM(0);
    final VM server2 = host.getVM(1);
    final VM client = host.getVM(2);
    final String regionName = "region1";
    final String[] queries = { "select distinct * from /" + regionName + " order by \"date\"", "select distinct \"date\" from /" + regionName + " order by \"date\"", "select distinct * from /" + regionName + " order by \"time\"", "select distinct \"time\" from /" + regionName + " order by \"time\"", "select distinct * from /" + regionName + " order by \"timestamp\"", "select distinct \"timestamp\" from /" + regionName + " order by \"timestamp\"", "select distinct \"date\" from /" + regionName + " order by \"date\".\"score\"", "select distinct * from /" + regionName + " order by nested.\"date\"", "select distinct * from /" + regionName + " order by nested.\"date\".nonKeyword", "select distinct * from /" + regionName + " order by nested.\"date\".\"date\"", "select distinct * from /" + regionName + " order by nested.\"date\".\"date\".score" };
    // Start server1
    final Integer port1 = (Integer) server1.invoke(new SerializableCallable("Create Server1") {

        @Override
        public Object call() throws Exception {
            String jsonCustomer = "{" + "\"firstName\": \"John\"," + "\"lastName\": \"Smith\"," + " \"age\": 25," + " \"date\":" + " \"" + new java.util.Date() + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"" + "}";
            String jsonCustomer1 = "{" + "\"firstName\": \"John1\"," + "\"lastName\": \"Smith1\"," + " \"age\": 25," + " \"date\":" + " \"" + new java.util.Date() + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"" + "}";
            String jsonCustomer2 = "{" + "\"firstName\": \"John2\"," + "\"lastName\": \"Smith2\"," + " \"age\": 25," + " \"date\":" + " \"" + new java.util.Date() + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"" + "}";
            String jsonCustomer3 = "{" + "\"firstName\": \"John3\"," + "\"lastName\": \"Smith3\"," + " \"age\": 25," + " \"date\":" + " \"" + new TestObject(1) + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"" + "}";
            String jsonCustomer4 = "{" + "\"firstName\": \"John4\"," + "\"lastName\": \"Smith4\"," + " \"age\": 25," + " \"date\":" + " \"" + new TestObject(1) + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"," + " \"nested\":" + " \"" + new NestedKeywordObject(1) + "\"" + "}";
            String jsonCustomer5 = "{" + "\"firstName\": \"John5\"," + "\"lastName\": \"Smith5\"," + " \"age\": 25," + " \"date\":" + " \"" + new TestObject(1) + "\"," + " \"time\":" + " \"" + new java.sql.Time(1000) + "\"," + " \"timestamp\":" + " \"" + new java.sql.Timestamp(1000) + "\"," + " \"nested\":" + " \"" + new NestedKeywordObject(new NestedKeywordObject(new TestObject(1))) + "\"" + "}";
            Region r1 = getCache().createRegionFactory(RegionShortcut.PARTITION).create(regionName);
            r1.put("jsondoc", JSONFormatter.fromJSON(jsonCustomer));
            r1.put("jsondoc1", JSONFormatter.fromJSON(jsonCustomer1));
            r1.put("jsondoc2", JSONFormatter.fromJSON(jsonCustomer2));
            r1.put("jsondoc3", JSONFormatter.fromJSON(jsonCustomer3));
            r1.put("jsondoc4", JSONFormatter.fromJSON(jsonCustomer4));
            r1.put("jsondoc5", JSONFormatter.fromJSON(jsonCustomer5));
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    // Start server2
    final Integer port2 = (Integer) server2.invoke(new SerializableCallable("Create Server2") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.PARTITION).create(regionName);
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    client.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(NetworkUtils.getServerHostName(server1.getHost()), port1);
            cf.addPoolServer(NetworkUtils.getServerHostName(server2.getHost()), port2);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);
            QueryService qs = null;
            SelectResults sr = null;
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < queries.length; i++) {
                try {
                    sr = (SelectResults) qs.newQuery(queries[i]).execute();
                    assertTrue("Size of resultset should be greater than 0 for query: " + queries[i], sr.size() > 0);
                } catch (Exception e) {
                    Assert.fail("Failed executing query ", e);
                }
            }
            return null;
        }
    });
    this.closeClient(server1);
    this.closeClient(server2);
    this.closeClient(client);
}
Also used : Host(org.apache.geode.test.dunit.Host) ClientCache(org.apache.geode.cache.client.ClientCache) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) CancellationException(java.util.concurrent.CancellationException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) RegionNotFoundException(org.apache.geode.cache.query.RegionNotFoundException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) IndexExistsException(org.apache.geode.cache.query.IndexExistsException) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Region(org.apache.geode.cache.Region) CacheServer(org.apache.geode.cache.server.CacheServer) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) Test(org.junit.Test)

Example 89 with ClientCache

use of org.apache.geode.cache.client.ClientCache in project geode by apache.

the class ClientServerInvalidAndDestroyedEntryDUnitTest method doTestRegisterInterestRemovesOldEntry.

private void doTestRegisterInterestRemovesOldEntry(final String regionName, final boolean usePR) throws Exception {
    VM vm1 = Host.getHost(0).getVM(1);
    VM vm2 = Host.getHost(0).getVM(2);
    // here are the keys that will be used to validate behavior. Keys must be
    // colocated if using both a partitioned region in the server and transactions
    // in the client. All of these keys hash to bucket 0 in a two-bucket PR
    // except Object11 and IDoNotExist1
    final String key10 = "Object10";
    final String interestPattern = "Object.*";
    SerializableCallableIF createServer = getCreateServerCallable(regionName, usePR);
    int serverPort = (Integer) vm1.invoke(createServer);
    vm2.invoke(createServer);
    vm1.invoke(new SerializableRunnable("populate server") {

        public void run() {
            Region myRegion = getCache().getRegion(regionName);
            for (int i = 1; i <= 20; i++) {
                myRegion.put("Object" + i, "Value" + i);
            }
        }
    });
    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("creating client cache");
    ClientCache c = new ClientCacheFactory().addPoolServer("localhost", serverPort).set(LOG_LEVEL, LogWriterUtils.getDUnitLogLevel()).setPoolSubscriptionEnabled(true).create();
    Region myRegion = c.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);
    ;
    myRegion.registerInterestRegex(interestPattern);
    // make sure key1 is in the client because we're going to mess with it
    assertNotNull(myRegion.get(key10));
    // remove the entry for key1 on the servers and then simulate interest recovery
    // to show that the entry for key1 is no longer there in the client when recovery
    // finishes
    SerializableRunnable destroyKey10 = new SerializableRunnable("locally destroy " + key10 + " in the servers") {

        public void run() {
            Region myRegion = getCache().getRegion(regionName);
            EntryEventImpl event = ((LocalRegion) myRegion).generateEvictDestroyEvent(key10);
            event.setOperation(Operation.LOCAL_DESTROY);
            if (usePR) {
                BucketRegion bucket = ((PartitionedRegion) myRegion).getBucketRegion(key10);
                if (bucket != null) {
                    event.setRegion(bucket);
                    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("performing local destroy in " + bucket + " ccEnabled=" + bucket.concurrencyChecksEnabled + " rvv=" + bucket.getVersionVector());
                    // turn off cc so entry is removed
                    bucket.concurrencyChecksEnabled = false;
                    bucket.mapDestroy(event, false, false, null);
                    bucket.concurrencyChecksEnabled = true;
                }
            } else {
                // turn off cc so entry is
                ((LocalRegion) myRegion).concurrencyChecksEnabled = false;
                // removed
                ((LocalRegion) myRegion).mapDestroy(event, false, false, null);
                ((LocalRegion) myRegion).concurrencyChecksEnabled = true;
            }
        }
    };
    vm1.invoke(destroyKey10);
    vm2.invoke(destroyKey10);
    myRegion.getCache().getLogger().info("clearing keys of interest");
    ((LocalRegion) myRegion).clearKeysOfInterest(interestPattern, InterestType.REGULAR_EXPRESSION, InterestResultPolicy.KEYS_VALUES);
    myRegion.getCache().getLogger().info("done clearing keys of interest");
    assertTrue("expected region to be empty but it has " + myRegion.size() + " entries", myRegion.size() == 0);
    RegionEntry entry;
    entry = ((LocalRegion) myRegion).getRegionEntry(key10);
    // it should have been removed
    assertNull(entry);
    // now register interest. At the end, finishRegisterInterest should clear
    // out the entry for key1 because it was stored in image-state as a
    // destroyed RI entry in clearKeysOfInterest
    myRegion.registerInterestRegex(interestPattern);
    entry = ((LocalRegion) myRegion).getRegionEntry(key10);
    // it should not be there
    assertNull(entry);
}
Also used : SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) SerializableCallableIF(org.apache.geode.test.dunit.SerializableCallableIF) ClientCache(org.apache.geode.cache.client.ClientCache) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region)

Example 90 with ClientCache

use of org.apache.geode.cache.client.ClientCache in project geode by apache.

the class AcceptorImplDUnitTest method testAcceptorImplCloseCleansUpWithHangingConnection.

/**
   * GEODE-2324. There was a bug where, due to an uncaught exception, `AcceptorImpl.close()` was
   * short-circuiting and failing to clean up properly.
   *
   * What this test does is start a Cache and hook the Acceptor to interrupt the thread before the
   * place where an InterruptedException could be thrown. It interrupts the thread, and checks that
   * the thread has terminated normally without short-circuiting. It doesn't check that every part
   * of the AcceptorImpl has shut down properly -- that seems both difficult to check (especially
   * since the fields are private) and implementation-dependent.
   */
@Test
public void testAcceptorImplCloseCleansUpWithHangingConnection() throws Exception {
    final String hostname = Host.getHost(0).getHostName();
    final VM clientVM = Host.getHost(0).getVM(0);
    Properties props = new Properties();
    props.setProperty(MCAST_PORT, "0");
    try (InternalCache cache = (InternalCache) new CacheFactory(props).create()) {
        RegionFactory<Object, Object> regionFactory = cache.createRegionFactory(RegionShortcut.PARTITION);
        SleepyCacheWriter<Object, Object> sleepyCacheWriter = new SleepyCacheWriter<>();
        regionFactory.setCacheWriter(sleepyCacheWriter);
        final CacheServer server = cache.addCacheServer();
        final int port = AvailablePortHelper.getRandomAvailableTCPPort();
        server.setPort(port);
        server.start();
        regionFactory.create("region1");
        assertTrue(cache.isServer());
        assertFalse(cache.isClosed());
        Awaitility.await("Acceptor is up and running").atMost(10, SECONDS).until(() -> getAcceptorImplFromCache(cache) != null);
        AcceptorImpl acceptorImpl = getAcceptorImplFromCache(cache);
        clientVM.invokeAsync(() -> {
            // System.setProperty("gemfire.PoolImpl.TRY_SERVERS_ONCE", "true");
            ClientCacheFactory clientCacheFactory = new ClientCacheFactory();
            clientCacheFactory.addPoolServer(hostname, port);
            clientCacheFactory.setPoolReadTimeout(5000);
            clientCacheFactory.setPoolRetryAttempts(1);
            clientCacheFactory.setPoolMaxConnections(1);
            clientCacheFactory.setPoolFreeConnectionTimeout(1000);
            ClientCache clientCache = clientCacheFactory.create();
            Region<Object, Object> clientRegion1 = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create("region1");
            clientRegion1.put("foo", "bar");
        });
        Awaitility.await("Cache writer starts").atMost(10, SECONDS).until(sleepyCacheWriter::isStarted);
        cache.close();
        Awaitility.await("Cache writer interrupted").atMost(10, SECONDS).until(sleepyCacheWriter::isInterrupted);
        sleepyCacheWriter.stopWaiting();
        Awaitility.await("Acceptor shuts down properly").atMost(10, SECONDS).until(() -> acceptorImpl.isShutdownProperly());
        // for debugging.
        ThreadUtils.dumpMyThreads();
        regionFactory.setCacheWriter(null);
    }
}
Also used : InternalCache(org.apache.geode.internal.cache.InternalCache) ClientCache(org.apache.geode.cache.client.ClientCache) Properties(java.util.Properties) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) VM(org.apache.geode.test.dunit.VM) CacheServer(org.apache.geode.cache.server.CacheServer) CacheFactory(org.apache.geode.cache.CacheFactory) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

ClientCache (org.apache.geode.cache.client.ClientCache)112 Test (org.junit.Test)74 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)73 ClientCacheFactory (org.apache.geode.cache.client.ClientCacheFactory)65 Region (org.apache.geode.cache.Region)64 VM (org.apache.geode.test.dunit.VM)43 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)42 Host (org.apache.geode.test.dunit.Host)40 SecurityTest (org.apache.geode.test.junit.categories.SecurityTest)31 QueryService (org.apache.geode.cache.query.QueryService)26 SelectResults (org.apache.geode.cache.query.SelectResults)25 SecurityTestUtil.createClientCache (org.apache.geode.security.SecurityTestUtil.createClientCache)25 SecurityTestUtil.createProxyRegion (org.apache.geode.security.SecurityTestUtil.createProxyRegion)23 CacheServer (org.apache.geode.cache.server.CacheServer)22 Cache (org.apache.geode.cache.Cache)20 CacheException (org.apache.geode.cache.CacheException)15 PortfolioPdx (org.apache.geode.cache.query.data.PortfolioPdx)13 IOException (java.io.IOException)12 Properties (java.util.Properties)12 IgnoredException (org.apache.geode.test.dunit.IgnoredException)12