use of org.apache.geode.cache.query.QueryService in project geode by apache.
the class SelectStarQueryDUnitTest method testSelectStarQueryForPdxObjects.
@Test
public void testSelectStarQueryForPdxObjects() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
// create servers and regions
final int port1 = startReplicatedCacheServer(server1);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// Update with serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 0; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertTrue(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
// verify if Pdx instances are returned by local server query
// if read-serialized is set true
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
cache.setReadSerialized(true);
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PdxInstance) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PdxInstance and not " + obj.getClass());
}
}
} else if (rs instanceof PdxInstance) {
} else {
fail("Result objects for remote client query: " + queries[i] + " should be instance of PdxInstance and not " + rs.getClass());
}
}
}
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
use of org.apache.geode.cache.query.QueryService in project geode by apache.
the class ComparisonOperatorsJUnitTest method testCompareWithUNDEFINED.
@Test
public void testCompareWithUNDEFINED() throws Exception {
String var = "P2.secId";
QueryService qs = CacheUtils.getQueryService();
for (int i = 0; i < operators.length; i++) {
// comparison operators.
if (!operators[i].equals("=") && !operators[i].equals("!=") && !operators[i].equals("<>")) {
Query query = qs.newQuery("SELECT DISTINCT * FROM /Portfolios where " + var + operators[i] + " UNDEFINED");
Object result = query.execute();
if (result instanceof Collection) {
if (((Collection) result).size() != 0)
fail(this.getName() + " failed for operator " + operators[i]);
} else {
fail(this.getName() + " failed for operator " + operators[i]);
}
}
}
}
use of org.apache.geode.cache.query.QueryService in project geode by apache.
the class QueryUsingPoolDUnitTest method testRemoteStructQueries.
/**
* Tests remote struct query execution.
*/
@Test
public void testRemoteStructQueries() throws CacheException {
final String name = this.getName();
final String rootRegionName = "root";
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
final int numberOfEntries = 100;
// Start server
final int port = vm0.invoke("Create Bridge Server", () -> {
setupBridgeServerAndCreateData(name, numberOfEntries);
return getCacheServerPort();
});
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
final String regionName = "/" + rootRegionName + "/" + name;
// Create client pool.
final String poolName = "testRemoteStructQueries";
vm1.invoke("createPool", () -> createPool(poolName, host0, port));
// Execute client queries
vm1.invoke("Execute queries", () -> {
String queryString = null;
SelectResults results = null;
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception e) {
Assert.fail("Failed to get QueryService.", e);
}
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName;
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(numberOfEntries, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName + " where ticker = 'ibm'";
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(numberOfEntries, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName + " where ticker = 'IBM'";
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(0, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName + " where price > 49";
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(numberOfEntries / 2, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName + " where price = 50";
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(1, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
queryString = "import org.apache.geode.admin.QueryUsingPoolDUnitTest.TestObject; select distinct ticker, price from " + regionName + " where ticker = 'ibm' and price = 50";
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(1, results.size());
assertTrue(!results.getCollectionType().allowsDuplicates() && results.getCollectionType().getElementType().isStructType());
});
// Stop server
vm0.invoke("Stop CacheServer", () -> stopBridgeServer(getCache()));
}
use of org.apache.geode.cache.query.QueryService in project geode by apache.
the class QueryUsingPoolDUnitTest method testRemoteSortQueriesUsingIndex.
/**
* Tests remote full region query execution.
*/
@Test
public void testRemoteSortQueriesUsingIndex() throws CacheException {
final String name = this.getName();
final String rootRegionName = "root";
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
final int numberOfEntries = 100;
// Start server
vm0.invoke("Create Bridge Server", () -> {
createAndStartBridgeServer();
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
createRegion(name, factory.create());
Region region = getRootRegion().getSubregion(name);
for (int i = 0; i < numberOfEntries; i++) {
region.put("key-" + i, new TestObject(i, "ibm"));
}
// Create index
try {
QueryService qService = region.getCache().getQueryService();
qService.createIndex("idIndex", IndexType.FUNCTIONAL, "id", region.getFullPath());
} catch (Exception e) {
Assert.fail("Failed to create index.", e);
}
});
// Create client region
final int port = vm0.invoke("getCacheServerPort", () -> QueryUsingPoolDUnitTest.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
final String regionName = "/" + rootRegionName + "/" + name;
// Create client pool.
final String poolName = "testRemoteFullRegionQueries";
vm1.invoke("createPool", () -> createPool(poolName, host0, port));
// Execute client queries
vm1.invoke("Execute queries", () -> {
String queryString = null;
SelectResults results = null;
Comparator comparator = null;
Object[] resultsArray = null;
QueryService qService = null;
Integer v1 = 0;
Integer v2 = 0;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception e) {
Assert.fail("Failed to get QueryService.", e);
}
// order by value query
String[] qString = { "SELECT DISTINCT * FROM " + regionName + " WHERE id < 101 ORDER BY id", "SELECT DISTINCT id FROM " + regionName + " WHERE id < 101 ORDER BY id" };
for (int cnt = 0; cnt < qString.length; cnt++) {
queryString = qString[cnt];
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(numberOfEntries, results.size());
// All order-by query results are stored in a ResultsCollectionWrapper
// wrapping a list, so the assertion below is not correct even though
// it should be.
// assertTrue(!results.getCollectionType().allowsDuplicates());
assertTrue(results.getCollectionType().isOrdered());
comparator = new IdValueComparator();
resultsArray = results.toArray();
for (int i = 0; i < resultsArray.length; i++) {
if (i + 1 != resultsArray.length) {
// than the id of the next one to pass.
if (resultsArray[i] instanceof TestObject) {
v1 = ((TestObject) resultsArray[i]).getId();
v2 = ((TestObject) resultsArray[i + 1]).getId();
} else {
v1 = (Integer) resultsArray[i];
v2 = (Integer) resultsArray[i + 1];
}
assertTrue("The id for " + resultsArray[i] + " should be less than the id for " + resultsArray[i + 1], comparator.compare(v1, v2) == -1);
}
}
}
// order by struct query
String[] qString2 = { "SELECT DISTINCT id, ticker, price FROM " + regionName + " WHERE id < 101 ORDER BY id", "SELECT DISTINCT ticker, id FROM " + regionName + " WHERE id < 101 ORDER BY id", "SELECT DISTINCT id, ticker FROM " + regionName + " WHERE id < 101 ORDER BY id asc" };
for (int cnt = 0; cnt < qString2.length; cnt++) {
queryString = qString2[cnt];
try {
Query query = qService.newQuery(queryString);
results = (SelectResults) query.execute();
} catch (Exception e) {
Assert.fail("Failed executing " + queryString, e);
}
assertEquals(numberOfEntries, results.size());
// All order-by query results are stored in a ResultsCollectionWrapper
// wrapping a list, so the assertion below is not correct even though
// it should be.
// assertTrue(!results.getCollectionType().allowsDuplicates());
assertTrue(results.getCollectionType().isOrdered());
comparator = new StructIdComparator();
resultsArray = results.toArray();
for (int i = 0; i < resultsArray.length; i++) {
if (i + 1 != resultsArray.length) {
// The id of the current element in the result set must be less
// than the id of the next one to pass.
assertTrue("The id for " + resultsArray[i] + " should be less than the id for " + resultsArray[i + 1], comparator.compare(resultsArray[i], resultsArray[i + 1]) == -1);
}
}
}
});
// Stop server
vm0.invoke("Stop CacheServer", () -> stopBridgeServer(getCache()));
}
use of org.apache.geode.cache.query.QueryService in project geode by apache.
the class QueryUsingPoolDUnitTest method testClientServerQueriesWithParams.
/**
* Tests client-server query using parameters (compiled queries).
*/
@Test
public void testClientServerQueriesWithParams() throws CacheException {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
final int numberOfEntries = 100;
final Object[][] params = new Object[][] { // 0
{ "key-1" }, // 1
{ 101 }, // 2
{ 101 }, // 3
{ 101 }, // 4
{ 50, "ibm" }, // 5
{ 50, "ibm" } };
final int[] expectedResults = new int[] { // 0
1, // 1
100, // 2
100, // 3
1, // 4
1, // 5
50 };
// KIRK
assertNotNull(this.regionName);
// Start server
final int port = vm0.invoke("Create Bridge Server", () -> {
setupBridgeServerAndCreateData(regionName, numberOfEntries);
return getCacheServerPort();
});
// Create client region
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
// Create client pool.
final String poolName = "testClientServerQueriesWithParams";
vm1.invoke("createPool", () -> createPool(poolName, host0, port));
// Execute client queries
vm1.invoke(new CacheSerializableRunnable("Execute queries") {
public void run2() throws CacheException {
SelectResults results = null;
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception e) {
Assert.fail("Failed to get QueryService.", e);
}
executeQueriesForClientServerQueriesWithParams(results, qService, params, expectedResults);
}
});
final int useMaintainedCompiledQueries = queryString.length;
// Execute the same compiled queries multiple time
vm1.invoke("Execute queries", () -> {
SelectResults results = null;
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception e) {
Assert.fail("Failed to get QueryService.", e);
}
for (int x = 0; x < useMaintainedCompiledQueries; x++) {
executeQueriesForClientServerQueriesWithParams(results, qService, params, expectedResults);
}
});
// Validate maintained compiled queries.
// There should be only queryString.length compiled queries registered.
vm0.invoke("validate compiled query.", () -> {
long compiledQueryCount = CacheClientNotifier.getInstance().getStats().getCompiledQueryCount();
assertEquals(queryString.length, compiledQueryCount);
});
// Check to see if maintained compiled queries are used.
vm0.invoke("validate compiled query.", () -> {
long compiledQueryUsedCount = CacheClientNotifier.getInstance().getStats().getCompiledQueryUsedCount();
int numTimesUsed = (useMaintainedCompiledQueries + 1) * queryString.length;
assertEquals(numTimesUsed, compiledQueryUsedCount);
});
// Stop server
vm0.invoke("Stop CacheServer", () -> stopBridgeServer(getCache()));
}
Aggregations