use of org.apache.geode.cache.query.QueryInvalidException in project geode by apache.
the class PutAllCSDUnitTest method testOneServer.
/**
* Tests putAll to one server.
*/
@Test
public void testOneServer() throws CacheException, InterruptedException {
final String title = "testOneServer:";
final Host host = Host.getHost(0);
VM server = host.getVM(0);
VM client1 = host.getVM(2);
VM client2 = host.getVM(3);
final String regionName = getUniqueName();
final String serverHost = NetworkUtils.getServerHostName(server.getHost());
// set <false, true> means <PR=false, notifyBySubscription=true> to enable registerInterest and
// CQ
final int serverPort = createBridgeServer(server, regionName, 0, false, 0, null);
createClient(client1, regionName, serverHost, new int[] { serverPort }, -1, -1, false, true, true);
createClient(client2, regionName, serverHost, new int[] { serverPort }, -1, -1, false, true, true);
server.invoke(new CacheSerializableRunnable(title + "server add listener") {
@Override
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
region.getAttributesMutator().addCacheListener(new MyListener(false));
}
});
client2.invoke(new CacheSerializableRunnable(title + "client2 registerInterest and add listener") {
@Override
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
region.getAttributesMutator().addCacheListener(new MyListener(false));
// registerInterest for ALL_KEYS
region.registerInterest("ALL_KEYS");
LogWriterUtils.getLogWriter().info("client2 registerInterest ALL_KEYS at " + region.getFullPath());
}
});
client1.invoke(new CacheSerializableRunnable(title + "client1 create local region and run putAll") {
@Override
public void run2() throws CacheException {
AttributesFactory factory2 = new AttributesFactory();
factory2.setScope(Scope.LOCAL);
factory2.addCacheListener(new MyListener(false));
createRegion("localsave", factory2.create());
Region region = doPutAll(regionName, "key-", numberOfEntries);
assertEquals(numberOfEntries, region.size());
}
});
AsyncInvocation async1 = client1.invokeAsync(new CacheSerializableRunnable(title + "client1 create CQ") {
@Override
public void run2() throws CacheException {
// create a CQ for key 10-20
Region localregion = getRootRegion().getSubregion("localsave");
CqAttributesFactory cqf1 = new CqAttributesFactory();
EOCQEventListener EOCQListener = new EOCQEventListener(localregion);
cqf1.addCqListener(EOCQListener);
CqAttributes cqa1 = cqf1.create();
String cqName1 = "EOInfoTracker";
String queryStr1 = "SELECT ALL * FROM /root/" + regionName + " ii WHERE ii.getTicker() >= '10' and ii.getTicker() < '20'";
LogWriterUtils.getLogWriter().info("Query String: " + queryStr1);
try {
QueryService cqService = getCache().getQueryService();
CqQuery EOTracker = cqService.newCq(cqName1, queryStr1, cqa1);
SelectResults rs1 = EOTracker.executeWithInitialResults();
List list1 = rs1.asList();
for (int i = 0; i < list1.size(); i++) {
Struct s = (Struct) list1.get(i);
TestObject o = (TestObject) s.get("value");
LogWriterUtils.getLogWriter().info("InitialResult:" + i + ":" + o);
localregion.put("key-" + i, o);
}
if (localregion.size() > 0) {
LogWriterUtils.getLogWriter().info("CQ is ready");
synchronized (lockObject) {
lockObject.notify();
}
}
waitTillNotify(lockObject2, 20000, (EOCQListener.num_creates == 5 && EOCQListener.num_updates == 5));
EOTracker.close();
} catch (CqClosedException e) {
Assert.fail("CQ", e);
} catch (RegionNotFoundException e) {
Assert.fail("CQ", e);
} catch (QueryInvalidException e) {
Assert.fail("CQ", e);
} catch (CqExistsException e) {
Assert.fail("CQ", e);
} catch (CqException e) {
Assert.fail("CQ", e);
}
}
});
server.invoke(new CacheSerializableRunnable(title + "verify Bridge Server") {
@Override
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
assertEquals(numberOfEntries, region.size());
for (int i = 0; i < numberOfEntries; i++) {
TestObject obj = (TestObject) region.getEntry("key-" + i).getValue();
assertEquals(i, obj.getPrice());
}
}
});
// verify CQ is ready
client1.invoke(new CacheSerializableRunnable(title + "verify CQ is ready") {
@Override
public void run2() throws CacheException {
Region localregion = getRootRegion().getSubregion("localsave");
waitTillNotify(lockObject, 10000, (localregion.size() > 0));
assertTrue(localregion.size() > 0);
}
});
// verify registerInterest result at client2
client2.invoke(new CacheSerializableRunnable(title + "verify client2") {
@Override
public void run2() throws CacheException {
final Region region = getRootRegion().getSubregion(regionName);
checkRegionSize(region, numberOfEntries);
for (int i = 0; i < numberOfEntries; i++) {
TestObject obj = (TestObject) region.getEntry("key-" + i).getValue();
assertEquals(i, obj.getPrice());
}
// then do update for key 10-20 to trigger CQ at server2
// destroy key 10-14 to simulate create/update mix case
region.removeAll(Arrays.asList("key-10", "key-11", "key-12", "key-13", "key-14"), "removeAllCallback");
assertEquals(null, region.get("key-10"));
assertEquals(null, region.get("key-11"));
assertEquals(null, region.get("key-12"));
assertEquals(null, region.get("key-13"));
assertEquals(null, region.get("key-14"));
}
});
// verify CQ result at client1
client1.invoke(new CacheSerializableRunnable(title + "Verify client1") {
@Override
public void run2() throws CacheException {
Region localregion = getRootRegion().getSubregion("localsave");
for (int i = 10; i < 15; i++) {
TestObject obj = null;
int cnt = 0;
while (cnt < 100) {
obj = (TestObject) localregion.get("key-" + i);
if (obj != null) {
// wait for the key to be destroyed
Wait.pause(100);
if (LogWriterUtils.getLogWriter().fineEnabled()) {
LogWriterUtils.getLogWriter().info("Waiting 100ms(" + cnt + ") for key-" + i + " to be destroyed");
}
cnt++;
} else {
break;
}
}
}
}
});
client2.invoke(new CacheSerializableRunnable(title + "verify client2") {
@Override
public void run2() throws CacheException {
final Region region = getRootRegion().getSubregion(regionName);
LinkedHashMap map = new LinkedHashMap();
for (int i = 10; i < 20; i++) {
map.put("key-" + i, new TestObject(i * 10));
}
region.putAll(map, "putAllCallback");
}
});
// verify CQ result at client1
client1.invoke(new CacheSerializableRunnable(title + "Verify client1") {
@Override
public void run2() throws CacheException {
Region localregion = getRootRegion().getSubregion("localsave");
for (int i = 10; i < 20; i++) {
TestObject obj = null;
int cnt = 0;
while (cnt < 100) {
obj = (TestObject) localregion.get("key-" + i);
if (obj == null || obj.getPrice() != i * 10) {
Wait.pause(100);
LogWriterUtils.getLogWriter().info("Waiting 100ms(" + cnt + ") for obj.getPrice() == i*10 at entry " + i);
cnt++;
} else {
break;
}
}
assertEquals(i * 10, obj.getPrice());
}
synchronized (lockObject2) {
lockObject2.notify();
}
}
});
ThreadUtils.join(async1, 30 * 1000);
// verify stats for client putAll into distributed region
// 1. verify client staus
/*
* server2.invoke(new CacheSerializableRunnable("server2 execute putAll") { public void run2()
* throws CacheException { try { DistributedSystemConfig config =
* AdminDistributedSystemFactory.defineDistributedSystem(system, null); AdminDistributedSystem
* ads = AdminDistributedSystemFactory.getDistributedSystem(config); ads.connect();
* DistributedMember distributedMember = system.getDistributedMember(); SystemMember member =
* ads.lookupSystemMember(distributedMember);
*
* StatisticResource[] resources = member.getStats(); for (int i=0; i<resources.length; i++) {
* System.out.println("GGG:"+resources[i].getType()); if
* (resources[i].getType().equals("CacheServerClientStats")) { Statistic[] stats =
* resources[i].getStatistics(); for (int j=0; i<stats.length; i++) { if
* (stats[j].getName().equals("putAll")) {
* System.out.println("GGG:"+stats[j].getName()+":"+stats[j].getValue()); } else if
* (stats[j].getName().equals("sendPutAllTime")) {
* System.out.println("GGG:"+stats[j].getName()+":"+stats[j].getValue()); } } } } } catch
* (AdminException e) { fail("Failed while creating AdminDS", e); } } });
*/
// Test Exception handling
// verify CQ is ready
client1.invoke(new CacheSerializableRunnable(title + "test exception handling") {
@Override
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
Map m = null;
boolean NPEthrowed = false;
try {
region.putAll(m, "putAllCallback");
fail("Should have thrown NullPointerException");
} catch (NullPointerException ex) {
NPEthrowed = true;
}
assertTrue(NPEthrowed);
region.localDestroyRegion();
boolean RDEthrowed = false;
try {
m = new HashMap();
for (int i = 1; i < 21; i++) {
m.put(new Integer(i), Integer.toString(i));
}
region.putAll(m, "putAllCallback");
fail("Should have thrown RegionDestroyedException");
} catch (RegionDestroyedException ex) {
RDEthrowed = true;
}
assertTrue(RDEthrowed);
try {
region.removeAll(Arrays.asList("key-10", "key-11"), "removeAllCallback");
fail("Should have thrown RegionDestroyedException");
} catch (RegionDestroyedException expected) {
}
}
});
// Stop server
stopBridgeServers(getCache());
}
use of org.apache.geode.cache.query.QueryInvalidException in project geode by apache.
the class CQJUnitTest method testValidateCQ.
/**
* Test to make sure CQs that have invalid syntax throw QueryInvalidException, and CQs that have
* unsupported CQ features throw UnsupportedOperationException
*/
@Test
public void testValidateCQ() throws Exception {
AttributesFactory attributesFactory = new AttributesFactory();
RegionAttributes regionAttributes = attributesFactory.create();
// The order by query computes dependency after compilation so the region has to be present
// for the query to progress further to throw UnsupportedOperationException
cache.createRegion("region", regionAttributes);
// default attributes
CqAttributes attrs = new CqAttributesFactory().create();
// valid CQ
this.qs.newCq("SELECT * FROM /region WHERE status = 'active'", attrs);
// invalid syntax
try {
this.qs.newCq("this query is garbage", attrs);
fail("should have thrown a QueryInvalidException");
} catch (QueryInvalidException e) {
// pass
}
String[] unsupportedCQs = new String[] { // not "just" a select statement
"(select * from /region where status = 'active').isEmpty", // cannot be DISTINCT
"select DISTINCT * from /region WHERE status = 'active'", // references more than one region
"select * from /region1 r1, /region2 r2 where r1 = r2", // where clause refers to a region
"select * from /region r where r.val = /region.size", // more than one iterator in FROM clause
"select * from /portfolios p1, p1.positions p2 where p2.id = 'IBM'", // first iterator in FROM clause is not just a region path
"select * from /region.entries e where e.value.id = 23", // has projections
"select id from /region where status = 'active'", // has ORDER BY
"select * from /region where status = 'active' ORDER BY id" };
for (int i = 0; i < unsupportedCQs.length; i++) {
try {
this.qs.newCq(unsupportedCQs[i], attrs);
fail("should have thrown UnsupportedOperationException for query #" + i);
} catch (UnsupportedOperationException e) {
// pass
}
}
}
use of org.apache.geode.cache.query.QueryInvalidException in project geode by apache.
the class QueryAccessController method runNamedQuery.
/**
* Run named parametrized Query with ID
*
* @param queryId id of the OQL string
* @param arguments query bind params required while executing query
* @return query result as a JSON document
*/
@RequestMapping(method = RequestMethod.POST, value = "/{query}", produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(value = "run parametrized query", notes = "run the specified named query passing in scalar values for query parameters in the GemFire cluster", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "Query successfully executed."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 400, message = "Query bind params specified as JSON document in the request body is invalid"), @ApiResponse(code = 500, message = "GemFire throws an error or exception") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'READ')")
public ResponseEntity<String> runNamedQuery(@PathVariable("query") String queryId, @RequestBody String arguments) {
logger.debug("Running named Query with ID ({})...", queryId);
queryId = decode(queryId);
if (arguments != null) {
// Its a compiled query.
// Convert arguments into Object[]
Object[] args = jsonToObjectArray(arguments);
Query compiledQuery = compiledQueries.get(queryId);
if (compiledQuery == null) {
// This is first time the query is seen by this server.
final String oql = getValue(PARAMETERIZED_QUERIES_REGION, queryId, false);
ValidationUtils.returnValueThrowOnNull(oql, new ResourceNotFoundException(String.format("No Query with ID (%1$s) was found!", queryId)));
try {
compiledQuery = getQueryService().newQuery(oql);
} catch (QueryInvalidException qie) {
throw new GemfireRestException("Syntax of the OQL queryString is invalid!", qie);
}
compiledQueries.putIfAbsent(queryId, (DefaultQuery) compiledQuery);
}
// and handle the Exceptions appropriately (500 Server Error)!
try {
Object queryResult = compiledQuery.execute(args);
return processQueryResponse(compiledQuery, args, queryResult);
} catch (FunctionDomainException fde) {
throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
} catch (TypeMismatchException tme) {
throw new GemfireRestException("Bind parameter is not of the expected type!", tme);
} catch (NameResolutionException nre) {
throw new GemfireRestException("Name in the query cannot be resolved!", nre);
} catch (IllegalArgumentException iae) {
throw new GemfireRestException(" The number of bound parameters does not match the number of placeholders!", iae);
} catch (IllegalStateException ise) {
throw new GemfireRestException("Query is not permitted on this type of region!", ise);
} catch (QueryExecutionTimeoutException qete) {
throw new GemfireRestException("Query execution time is exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!", qete);
} catch (QueryInvocationTargetException qite) {
throw new GemfireRestException("Data referenced in from clause is not available for querying!", qite);
} catch (QueryExecutionLowMemoryException qelme) {
throw new GemfireRestException("Query gets canceled due to low memory conditions and the resource manager critical heap percentage has been set!", qelme);
} catch (Exception e) {
throw new GemfireRestException("Error encountered while executing named query!", e);
}
} else {
throw new GemfireRestException(" Bind params either not specified or not processed properly by the server!");
}
}
use of org.apache.geode.cache.query.QueryInvalidException in project geode by apache.
the class IndexCreationJUnitTest method testIndexCreationWithImports.
@Test
public void testIndexCreationWithImports() throws Exception {
// Task ID ICM 16
QueryService qs;
qs = CacheUtils.getQueryService();
Index idx;
try {
idx = qs.createIndex("importsIndex", IndexType.FUNCTIONAL, "status", "/portfolios, (map<string,Position>)positions");
// can't find type
fail("Should have thrown a QueryInvalidException");
// Position
} catch (QueryInvalidException e) {
// pass
}
idx = qs.createIndex("importsIndex", IndexType.FUNCTIONAL, "status", "/portfolios, (map<string,Position>)positions", "import org.apache.geode.cache.\"query\".data.Position");
qs.removeIndex(idx);
idx = qs.createIndex("importsIndex2", IndexType.FUNCTIONAL, "status", "/portfolios, positions TYPE Position", "import org.apache.geode.cache.\"query\".data.Position");
}
use of org.apache.geode.cache.query.QueryInvalidException in project geode by apache.
the class OrderByComparatorJUnitTest method testSupportedOrderByForRR.
@Test
public void testSupportedOrderByForRR() throws Exception {
String[] unsupportedQueries = { "select distinct p.status from /portfolio1 p order by p.status, p.ID" };
Object[][] r = new Object[unsupportedQueries.length][2];
QueryService qs;
qs = CacheUtils.getQueryService();
Position.resetCounter();
// Create Regions
Region r1 = CacheUtils.createRegion("portfolio1", Portfolio.class);
for (int i = 0; i < 50; i++) {
r1.put(new Portfolio(i), new Portfolio(i));
}
for (int i = 0; i < unsupportedQueries.length; i++) {
Query q = null;
CacheUtils.getLogger().info("Executing query: " + unsupportedQueries[i]);
q = CacheUtils.getQueryService().newQuery(unsupportedQueries[i]);
try {
r[i][0] = q.execute();
} catch (QueryInvalidException qe) {
qe.printStackTrace();
fail(qe.toString());
}
}
}
Aggregations