Search in sources :

Example 6 with PdxInstanceFactory

use of org.apache.geode.pdx.PdxInstanceFactory in project geode by apache.

the class PdxQueryDUnitTest method testVersionedClientServerQuery.

/**
   * Tests client-server query on PdxInstance.
   */
@Test
public void testVersionedClientServerQuery() throws CacheException {
    final Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    VM vm2 = host.getVM(2);
    VM vm3 = host.getVM(3);
    final int numberOfEntries = 10;
    final String[] queryStr = new String[] { // 0
    "SELECT DISTINCT ID FROM " + regName, // 1
    "SELECT * FROM " + regName, // 2
    "SELECT pkid FROM " + regName, // 3
    "SELECT * FROM " + regName + " WHERE ID > 5", // 4
    "SELECT p FROM " + regName + " p, p.positions pos WHERE p.pkid != 'vmware'", "SELECT entry.value FROM " + this.regName + ".entries entry WHERE entry.value.ID > 0", "SELECT entry.value FROM  " + this.regName + ".entries entry WHERE entry.key = 'key-1'", "SELECT e.value FROM " + this.regName + ".entrySet e where  e.value.pkid >= '0'", "SELECT * FROM " + this.regName + ".values p WHERE p.pkid in SET('1', '2','3')", "SELECT * FROM " + this.regName + " pf where pf.position1.secId > '2'", "SELECT * FROM " + this.regName + " p where p.position3[1].portfolioId = 2", "SELECT * FROM " + this.regName + " p, p.positions.values AS pos WHERE pos.secId != '1'", "SELECT key, positions FROM " + this.regName + ".entrySet, value.positions.values " + "positions WHERE positions.mktValue >= 25.00", "SELECT * FROM " + this.regName + " portfolio1, " + this.regName + " portfolio2 WHERE " + "portfolio1.status = portfolio2.status", "SELECT portfolio1.ID, portfolio2.status FROM " + this.regName + " portfolio1, " + this.regName + " portfolio2  WHERE portfolio1.status = portfolio2.status", "SELECT * FROM " + this.regName + " portfolio1, portfolio1.positions.values positions1, " + this.regName + " portfolio2,  portfolio2.positions.values positions2 WHERE " + "positions1.secId = positions1.secId ", "SELECT * FROM " + this.regName + " portfolio, portfolio.positions.values positions WHERE " + "portfolio.Pk IN SET ('1', '2') AND positions.secId = '1'", "SELECT DISTINCT pf1, pf2 FROM " + this.regName + "  pf1, pf1.collectionHolderMap.values coll1," + " pf1.positions.values posit1, " + this.regName + "  pf2, pf2.collectionHolderMap.values " + " coll2, pf2.positions.values posit2 WHERE pf1.ID = pf2.ID" };
    // Start server1
    vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {

        public void run2() throws CacheException {
            configAndStartBridgeServer();
            Region region = getRootRegion().getSubregion(regionName);
        }
    });
    // Start server2
    vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {

        public void run2() throws CacheException {
            configAndStartBridgeServer();
            Region region = getRootRegion().getSubregion(regionName);
        }
    });
    // Client pool.
    final int port0 = vm0.invoke(() -> PdxQueryDUnitTest.getCacheServerPort());
    final int port1 = vm1.invoke(() -> PdxQueryDUnitTest.getCacheServerPort());
    final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
    // Create client pool.
    final String poolName = "testClientServerQueryPool";
    createPool(vm2, poolName, new String[] { host0 }, new int[] { port0 }, true);
    createPool(vm3, poolName, new String[] { host0 }, new int[] { port1 }, true);
    // Create client region
    vm3.invoke(new CacheSerializableRunnable("Create region") {

        public void run2() throws CacheException {
            // Load client/server region.
            AttributesFactory factory = new AttributesFactory();
            factory.setScope(Scope.LOCAL);
            ClientServerTestCase.configureConnectionPool(factory, host0, port1, -1, true, -1, -1, null);
            Region region = createRegion(regionName, rootRegionName, factory.create());
            try {
                // Load TestObject
                for (int i = 0; i < numberOfEntries; i++) {
                    PortfolioPdxVersion portfolioPdxVersion = new PortfolioPdxVersion(new Integer(i), new Integer(i));
                    PdxInstanceFactory pdxFactory = PdxInstanceFactoryImpl.newCreator("PortfolioPdxVersion", false);
                    PdxInstance pdxInstance = portfolioPdxVersion.createPdxInstance(pdxFactory);
                    region.put("key-" + i, pdxInstance);
                }
            } catch (Exception ex) {
                fail("Failed to load the class.");
            }
            // Execute query:
            QueryService remoteQueryService = null;
            QueryService localQueryService = null;
            SelectResults[][] rs = new SelectResults[1][2];
            try {
                remoteQueryService = (PoolManager.find(poolName)).getQueryService();
                localQueryService = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < queryStr.length; i++) {
                try {
                    logger.info("### Executing Query on server:" + queryStr[i]);
                    Query query = remoteQueryService.newQuery(queryStr[i]);
                    rs[0][0] = (SelectResults) query.execute();
                    logger.info("### Executing Query locally:" + queryStr[i]);
                    query = localQueryService.newQuery(queryStr[i]);
                    rs[0][1] = (SelectResults) query.execute();
                    logger.info("### Remote Query rs size: " + (rs[0][0]).size() + "Local Query rs size: " + (rs[0][1]).size());
                    // Compare local and remote query results.
                    if (!CacheUtils.compareResultsOfWithAndWithoutIndex(rs)) {
                        fail("Local and Remote Query Results are not matching for query :" + queryStr[i]);
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing " + queryStr[i], e);
                }
            }
        }
    });
    this.closeClient(vm2);
    this.closeClient(vm3);
    this.closeClient(vm1);
    this.closeClient(vm0);
}
Also used : PdxInstanceFactory(org.apache.geode.pdx.PdxInstanceFactory) Query(org.apache.geode.cache.query.Query) CacheException(org.apache.geode.cache.CacheException) Host(org.apache.geode.test.dunit.Host) CacheException(org.apache.geode.cache.CacheException) AttributesFactory(org.apache.geode.cache.AttributesFactory) PartitionAttributesFactory(org.apache.geode.cache.PartitionAttributesFactory) SelectResults(org.apache.geode.cache.query.SelectResults) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) PdxInstance(org.apache.geode.pdx.PdxInstance) QueryService(org.apache.geode.cache.query.QueryService) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) Test(org.junit.Test)

Example 7 with PdxInstanceFactory

use of org.apache.geode.pdx.PdxInstanceFactory in project geode by apache.

the class PdxQueryDUnitTest method testClientForFieldInOtherVersion.

/**
   * 2 servers(replicated) and 2 clients. client2 puts version1 and version2 objects on server1
   * client1 had registered interest to server2, hence gets the pdx objects for both versions Test
   * local query on client1 Test if client1 fetched pdxtypes from server
   * 
   * @throws CacheException
   */
@Test
public void testClientForFieldInOtherVersion() throws CacheException {
    final Host host = Host.getHost(0);
    final VM vm0 = host.getVM(0);
    final VM vm1 = host.getVM(1);
    final VM vm2 = host.getVM(2);
    final VM vm3 = host.getVM(3);
    final int numberOfEntries = 10;
    final String name = "/" + regionName;
    final String[] qs = { "select pdxStatus from " + name + " where pdxStatus = 'active'", "select status from " + name + " where id > 8 and id < 14" };
    // Start server1
    final int port1 = (Integer) vm0.invoke(new SerializableCallable("Create Server1") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    // Start server2
    final int port2 = (Integer) vm1.invoke(new SerializableCallable("Create Server2") {

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

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.setPoolSubscriptionEnabled(true);
            cf.addPoolServer(NetworkUtils.getServerHostName(vm1.getHost()), port2);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);
            region.registerInterest("ALL_KEYS");
            return null;
        }
    });
    // client2 loads both version objects on server1
    vm3.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(NetworkUtils.getServerHostName(vm0.getHost()), port1);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName);
            // Load version 1 objects
            for (int i = 0; i < numberOfEntries; i++) {
                PdxInstanceFactory pdxFactory = cache.createPdxInstanceFactory("PdxPortfolio");
                pdxFactory.writeString("pdxStatus", (i % 2 == 0 ? "active" : "inactive"));
                pdxFactory.writeInt("id", i);
                PdxInstance pdxInstance = pdxFactory.create();
                region.put("key-" + i, pdxInstance);
            }
            ;
            // Load version 2 objects
            for (int i = numberOfEntries; i < numberOfEntries * 2; i++) {
                PdxInstanceFactory pdxFactory = cache.createPdxInstanceFactory("PdxPortfolio");
                pdxFactory.writeString("status", i % 2 == 0 ? "active" : "inactive");
                pdxFactory.writeInt("id", i);
                PdxInstance pdxInstance = pdxFactory.create();
                region.put("key-" + i, pdxInstance);
            }
            return null;
        }
    });
    // query locally on client 1 which has registered interest
    vm2.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
            cache.setReadSerialized(true);
            QueryService localQueryService = null;
            // Execute query remotely
            try {
                localQueryService = ((ClientCache) getCache()).getLocalQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < qs.length; i++) {
                try {
                    SelectResults sr = (SelectResults) localQueryService.newQuery(qs[i]).execute();
                    assertEquals(5, sr.size());
                    if (i == 1) {
                        for (Object o : sr) {
                            if (o == null) {
                            } else if (o instanceof String) {
                            } else {
                                fail("Result should be either null or String and not " + o.getClass());
                            }
                        }
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing " + qs[i], e);
                }
            }
            // check if the types registered on server are fetched by the client
            TypeRegistration registration = GemFireCacheImpl.getForPdx("PDX registry is unavailable because the Cache has been closed.").getPdxRegistry().getTypeRegistration();
            Assert.assertTrue(registration instanceof ClientTypeRegistration);
            Map<Integer, PdxType> m = ((ClientTypeRegistration) registration).types();
            assertEquals(2, m.size());
            for (PdxType type : m.values()) {
                assertEquals("PdxPortfolio", type.getClassName());
            }
            return null;
        }
    });
    Invoke.invokeInEveryVM("Disconnecting from the Distributed system", () -> disconnectFromDS());
}
Also used : PdxInstanceFactory(org.apache.geode.pdx.PdxInstanceFactory) PdxType(org.apache.geode.pdx.internal.PdxType) PeerTypeRegistration(org.apache.geode.pdx.internal.PeerTypeRegistration) ClientTypeRegistration(org.apache.geode.pdx.internal.ClientTypeRegistration) TypeRegistration(org.apache.geode.pdx.internal.TypeRegistration) Host(org.apache.geode.test.dunit.Host) ClientCache(org.apache.geode.cache.client.ClientCache) CacheException(org.apache.geode.cache.CacheException) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) SelectResults(org.apache.geode.cache.query.SelectResults) PdxInstance(org.apache.geode.pdx.PdxInstance) 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) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) ClientTypeRegistration(org.apache.geode.pdx.internal.ClientTypeRegistration) Map(java.util.Map) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) Test(org.junit.Test)

Example 8 with PdxInstanceFactory

use of org.apache.geode.pdx.PdxInstanceFactory in project geode by apache.

the class PdxQueryDUnitTest method testPdxInstanceFieldInOtherVersion.

/**
   * Test to query a field that is not present in the Pdx object but is present in some other
   * version of the pdx instance
   * 
   * @throws CacheException
   */
@Test
public void testPdxInstanceFieldInOtherVersion() throws CacheException {
    final Host host = Host.getHost(0);
    final VM vm0 = host.getVM(0);
    final VM vm1 = host.getVM(1);
    final VM vm2 = host.getVM(2);
    final VM vm3 = host.getVM(3);
    final int numberOfEntries = 10;
    final String name = "/" + regionName;
    final String[] qs = { "select pdxStatus from " + name + " where pdxStatus = 'active'", "select pdxStatus from " + name + " where id > 8 and id < 14" };
    // Start server1
    final int port1 = (Integer) vm0.invoke(new SerializableCallable("Create Server1") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    // Start server2
    final int port2 = (Integer) vm1.invoke(new SerializableCallable("Create Server2") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    // client1 loads version 1 objects on server1
    vm2.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(NetworkUtils.getServerHostName(vm0.getHost()), port1);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName);
            // Load version 1 objects
            for (int i = 0; i < numberOfEntries; i++) {
                PdxInstanceFactory pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("PdxVersionedNewPortfolio", false);
                pdxInstanceFactory.writeInt("id", i);
                pdxInstanceFactory.writeString("pdxStatus", (i % 2 == 0 ? "active" : "inactive"));
                PdxInstance pdxInstance = pdxInstanceFactory.create();
                region.put("key-" + i, pdxInstance);
            }
            return null;
        }
    });
    // client 2 loads version 2 objects on server2
    vm3.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(NetworkUtils.getServerHostName(vm1.getHost()), port2);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName);
            // Load version 2 objects
            for (int i = numberOfEntries; i < numberOfEntries * 2; i++) {
                PdxInstanceFactory pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("PdxVersionedNewPortfolio", false);
                pdxInstanceFactory.writeInt("id", i);
                pdxInstanceFactory.writeString("status", (i % 2 == 0 ? "active" : "inactive"));
                PdxInstance pdxInstance = pdxInstanceFactory.create();
                region.put("key-" + i, pdxInstance);
            }
            return null;
        }
    });
    // query remotely from client 1 with version 1 in classpath
    vm2.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            QueryService remoteQueryService = null;
            // Execute query remotely
            try {
                remoteQueryService = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < qs.length; i++) {
                try {
                    SelectResults sr = (SelectResults) remoteQueryService.newQuery(qs[i]).execute();
                    assertEquals(5, sr.size());
                    if (i == 1) {
                        for (Object o : sr) {
                            if (o == null) {
                            } else if (o instanceof String) {
                            } else {
                                fail("Result should be either null or String and not " + o.getClass());
                            }
                        }
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing " + qs[i], e);
                }
            }
            return null;
        }
    });
    // query remotely from client 2 with version 2 in classpath
    vm3.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            QueryService remoteQueryService = null;
            // Execute query remotely
            try {
                remoteQueryService = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < qs.length; i++) {
                try {
                    SelectResults sr = (SelectResults) remoteQueryService.newQuery(qs[i]).execute();
                    assertEquals(5, sr.size());
                    if (i == 1) {
                        for (Object o : sr) {
                            if (o == null) {
                            } else if (o instanceof String) {
                            } else {
                                fail("Result should be either null or String and not " + o.getClass());
                            }
                        }
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing " + qs[i], e);
                }
            }
            return null;
        }
    });
    // query locally on server
    vm0.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
            cache.setReadSerialized(true);
            QueryService queryService = null;
            try {
                queryService = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < qs.length; i++) {
                try {
                    SelectResults sr = (SelectResults) queryService.newQuery(qs[i]).execute();
                    assertEquals(5, sr.size());
                    if (i == 1) {
                        for (Object o : sr) {
                            if (o == null) {
                            } else if (o instanceof String) {
                            } else {
                                fail("Result should be either null or String and not " + o.getClass());
                            }
                        }
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing " + qs[i], e);
                }
            }
            return null;
        }
    });
    // create index
    vm0.invoke(new SerializableCallable("Query") {

        @Override
        public Object call() throws Exception {
            QueryService qs = null;
            try {
                qs = getCache().getQueryService();
                qs.createIndex("status", "status", name);
            } catch (Exception e) {
                Assert.fail("Exception getting query service ", e);
            }
            return null;
        }
    });
    // query from client 1 with version 1 in classpath
    vm2.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            QueryService remoteQueryService = null;
            // Execute query remotely
            try {
                remoteQueryService = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            for (int i = 0; i < qs.length; i++) {
                try {
                    SelectResults sr = (SelectResults) remoteQueryService.newQuery(qs[i]).execute();
                    assertEquals(5, sr.size());
                } catch (Exception e) {
                    Assert.fail("Failed executing " + qs[i], e);
                }
            }
            return null;
        }
    });
    Invoke.invokeInEveryVM(DistributedTestCase.class, "disconnectFromDS");
}
Also used : PdxInstanceFactory(org.apache.geode.pdx.PdxInstanceFactory) Host(org.apache.geode.test.dunit.Host) ClientCache(org.apache.geode.cache.client.ClientCache) CacheException(org.apache.geode.cache.CacheException) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) SelectResults(org.apache.geode.cache.query.SelectResults) PdxInstance(org.apache.geode.pdx.PdxInstance) 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) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) Test(org.junit.Test)

Example 9 with PdxInstanceFactory

use of org.apache.geode.pdx.PdxInstanceFactory in project geode by apache.

the class PdxLocalQueryDUnitTest method testLocalPdxQueriesReadSerialized.

@Test
public void testLocalPdxQueriesReadSerialized() throws Exception {
    final Host host = Host.getHost(0);
    final VM server1 = host.getVM(0);
    final VM server2 = host.getVM(1);
    final int numberOfEntries = 10;
    final String name = "/" + regionName;
    final String[] queries = { "select * from " + name + " where position1 = $1", "select * from " + name + " where aDay = $1", "select * from " + name + " where status = 'inactive'", "select distinct * from " + name + " where status = 'inactive'", "select p from " + name + " p where p.status = 'inactive'", "select * from " + name + " p, p.positions.values v where v.secId = 'IBM'", "select * from " + name + " p where p.status = 'inactive' or p.ID > 0", "select * from " + name + " p where p.status = 'inactive' and p.ID >= 0", "select * from " + name + " p where p.status in set ('inactive', 'active')", "select * from " + name + " p where p.ID > 0 and p.ID < 10" };
    // Start server1
    server1.invoke(new SerializableCallable("Create Server1") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            for (int i = 0; i < numberOfEntries; i++) {
                PortfolioPdx p = new PortfolioPdx(i);
                r1.put("key-" + i, p);
            }
            return null;
        }
    });
    // Start server2
    server2.invoke(new SerializableCallable("Create Server2") {

        @Override
        public Object call() throws Exception {
            ((GemFireCacheImpl) getCache()).setReadSerialized(true);
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            QueryService qs = null;
            SelectResults sr = null;
            // Execute query locally
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            PositionPdx pos = new PositionPdx("IBM", 100);
            PdxInstanceFactory out = PdxInstanceFactoryImpl.newCreator("org.apache.geode.cache.query.data.PositionPdx", false);
            out.writeLong("avg20DaysVol", 0);
            out.writeString("bondRating", "");
            out.writeDouble("convRatio", 0);
            out.writeString("country", "");
            out.writeDouble("delta", 0);
            out.writeLong("industry", 0);
            out.writeLong("issuer", 0);
            out.writeDouble("mktValue", pos.getMktValue());
            out.writeDouble("qty", 0);
            out.writeString("secId", pos.secId);
            out.writeString("secIdIndexed", pos.secIdIndexed);
            out.writeString("secLinks", "");
            out.writeDouble("sharesOutstanding", pos.getSharesOutstanding());
            out.writeString("underlyer", "");
            out.writeLong("volatility", 0);
            out.writeInt("pid", pos.getPid());
            out.writeInt("portfolioId", 0);
            out.markIdentityField("secId");
            PdxInstance pi = out.create();
            PortfolioPdx.Day pDay = new PortfolioPdx(1).aDay;
            PdxInstanceEnum pdxEnum = new PdxInstanceEnum(pDay);
            for (int i = 0; i < queries.length; i++) {
                try {
                    if (i == 0) {
                        sr = (SelectResults) qs.newQuery(queries[i]).execute(new Object[] { pi });
                    } else if (i == 1) {
                        sr = (SelectResults) qs.newQuery(queries[i]).execute(new Object[] { pdxEnum });
                    } else {
                        sr = (SelectResults) qs.newQuery(queries[i]).execute();
                    }
                    assertTrue("Size of resultset should be greater than 0 for query: " + queries[i], sr.size() > 0);
                    for (Object result : sr) {
                        if (result instanceof Struct) {
                            Object[] r = ((Struct) result).getFieldValues();
                            for (int j = 0; j < r.length; j++) {
                                if (!(r[j] instanceof PdxInstance)) {
                                    fail("Result object should be a PdxInstance  and not an instance of " + r[j].getClass() + " for query: " + queries[i]);
                                }
                            }
                        } else if (!(result instanceof PdxInstance)) {
                            fail("Result object should be a PdxInstance  and not an instance of " + result.getClass() + " for query: " + queries[i]);
                        }
                    }
                } catch (Exception e) {
                    Assert.fail("Failed executing query " + queries[i], e);
                }
            }
            return null;
        }
    });
    this.closeClient(server1);
    this.closeClient(server2);
}
Also used : PdxInstanceFactory(org.apache.geode.pdx.PdxInstanceFactory) PositionPdx(org.apache.geode.cache.query.data.PositionPdx) Host(org.apache.geode.test.dunit.Host) PortfolioPdx(org.apache.geode.cache.query.data.PortfolioPdx) PdxString(org.apache.geode.pdx.internal.PdxString) CacheException(org.apache.geode.cache.CacheException) Struct(org.apache.geode.cache.query.Struct) PdxInstanceEnum(org.apache.geode.pdx.internal.PdxInstanceEnum) SelectResults(org.apache.geode.cache.query.SelectResults) PdxInstance(org.apache.geode.pdx.PdxInstance) 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) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 10 with PdxInstanceFactory

use of org.apache.geode.pdx.PdxInstanceFactory in project geode by apache.

the class PdxLocalQueryVersionedClassDUnitTest method testIsRemoteFlagForRemoteQueries.

/**
   * Testing the isRemote flag which could be inconsistent when bind queries are being executed in
   * multiple threads. Bug #49662 is caused because of this inconsistent behavior.
   * 
   * @throws Exception
   */
@Test
public void testIsRemoteFlagForRemoteQueries() throws Exception {
    final Host host = Host.getHost(0);
    final VM server = host.getVM(0);
    final VM client = host.getVM(1);
    final int numberOfEntries = 1000;
    final String name = "/" + regionName;
    final String query = "select distinct * from " + name + " where id > $1 and id < $2 and status = 'active'";
    // Start server
    final int port1 = (Integer) server.invoke(new SerializableCallable("Create Server") {

        @Override
        public Object call() throws Exception {
            Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
            CacheServer server = getCache().addCacheServer();
            int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
            server.setPort(port);
            server.start();
            return port;
        }
    });
    // Start client and put version1 objects on server
    // Server does not have version1 classes in classpath
    client.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(NetworkUtils.getServerHostName(server.getHost()), port1);
            ClientCache cache = getClientCache(cf);
            Region region = cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regionName);
            for (int i = 0; i < numberOfEntries; i++) {
                PdxInstanceFactory pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("PdxVersionedNewPortfolio", false);
                pdxInstanceFactory.writeInt("id", i);
                pdxInstanceFactory.writeString("status", (i % 2 == 0 ? "active" : "inactive"));
                PdxInstance pdxInstance = pdxInstanceFactory.create();
                region.put("key-" + i, pdxInstance);
            }
            return null;
        }
    });
    // Execute same query remotely from client using 2 threads
    // Since this is a bind query, the query object will be shared
    // between the 2 threads.
    AsyncInvocation a1 = client.invokeAsync(new SerializableCallable("Query from client") {

        @Override
        public Object call() throws Exception {
            QueryService qs = null;
            SelectResults sr = null;
            // Execute query remotely
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            try {
                for (int i = 0; i < 100; i++) {
                    sr = (SelectResults) qs.newQuery(query).execute(new Object[] { 1, 1000 });
                }
                Assert.assertTrue("Size of resultset should be greater than 0 for query: " + query, sr.size() > 0);
            } catch (Exception e) {
                Assert.fail("Failed executing query " + query, e);
            }
            return null;
        }
    });
    AsyncInvocation a2 = client.invokeAsync(new SerializableCallable("Query from client") {

        @Override
        public Object call() throws Exception {
            QueryService qs = null;
            SelectResults sr = null;
            // Execute query remotely
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                Assert.fail("Failed to get QueryService.", e);
            }
            try {
                for (int i = 0; i < 100; i++) {
                    sr = (SelectResults) qs.newQuery(query).execute(new Object[] { 997, 1000 });
                }
                Assert.assertTrue("Size of resultset should be greater than 0 for query: " + query, sr.size() > 0);
            } catch (Exception e) {
                Assert.fail("Failed executing query " + query, e);
            }
            return null;
        }
    });
    ThreadUtils.join(a1, 60 * 1000);
    ThreadUtils.join(a2, 60 * 1000);
    if (a1.exceptionOccurred()) {
        Assert.fail("Failed query execution " + a1.getException().getMessage());
    }
    if (a2.exceptionOccurred()) {
        Assert.fail("Failed query execution " + a2.getException());
    }
    this.closeClient(client);
    this.closeClient(server);
}
Also used : PdxInstanceFactory(org.apache.geode.pdx.PdxInstanceFactory) Host(org.apache.geode.test.dunit.Host) ClientCache(org.apache.geode.cache.client.ClientCache) AsyncInvocation(org.apache.geode.test.dunit.AsyncInvocation) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) SelectResults(org.apache.geode.cache.query.SelectResults) PdxInstance(org.apache.geode.pdx.PdxInstance) 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) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

PdxInstanceFactory (org.apache.geode.pdx.PdxInstanceFactory)23 PdxInstance (org.apache.geode.pdx.PdxInstance)22 Test (org.junit.Test)18 Region (org.apache.geode.cache.Region)13 Host (org.apache.geode.test.dunit.Host)12 VM (org.apache.geode.test.dunit.VM)12 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)12 CacheException (org.apache.geode.cache.CacheException)11 QueryService (org.apache.geode.cache.query.QueryService)11 SelectResults (org.apache.geode.cache.query.SelectResults)11 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)8 ClientCache (org.apache.geode.cache.client.ClientCache)7 ClientCacheFactory (org.apache.geode.cache.client.ClientCacheFactory)7 CacheServer (org.apache.geode.cache.server.CacheServer)7 GemFireCacheImpl (org.apache.geode.internal.cache.GemFireCacheImpl)6 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)6 Query (org.apache.geode.cache.query.Query)4 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)4 PdxString (org.apache.geode.pdx.internal.PdxString)4 Cache (org.apache.geode.cache.Cache)3