use of org.apache.geode.cache.query.CqClosedException in project geode by apache.
the class CqQueryDUnitTest method executeAndCloseAndExecuteIRMultipleTimes.
// helps test case where executeIR is called multiple times as well as after close
public void executeAndCloseAndExecuteIRMultipleTimes(VM vm, final String cqName, final String queryStr) {
vm.invoke(new CacheSerializableRunnable("Create CQ :" + cqName) {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Create CQ. ###" + cqName);
// Get CQ Service.
QueryService cqService = null;
try {
cqService = getCache().getQueryService();
} catch (Exception cqe) {
cqe.printStackTrace();
fail("Failed to getCQService.");
}
// Create CQ Attributes.
CqAttributesFactory cqf = new CqAttributesFactory();
CqListener[] cqListeners = { new CqQueryTestListener(LogWriterUtils.getLogWriter()) };
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
CqQuery cq1;
// Create CQ.
try {
cq1 = cqService.newCq(cqName, queryStr, cqa);
assertTrue("newCq() state mismatch", cq1.getState().isStopped());
} catch (Exception ex) {
AssertionError err = new AssertionError("Failed to create CQ " + cqName + " . ");
err.initCause(ex);
LogWriterUtils.getLogWriter().info("CqService is :" + cqService, err);
throw err;
}
try {
cq1.executeWithInitialResults();
try {
cq1.executeWithInitialResults();
} catch (IllegalStateException e) {
// expected
}
cq1.close();
try {
cq1.executeWithInitialResults();
} catch (CqClosedException e) {
// expected
return;
}
fail("should have received cqClosedException");
} catch (Exception e) {
fail("exception not expected here " + e);
}
}
});
}
use of org.apache.geode.cache.query.CqClosedException 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.CqClosedException in project geode by apache.
the class CqServiceImpl method stopCqs.
@Override
public synchronized void stopCqs(Collection<? extends InternalCqQuery> cqs) throws CqException {
final boolean isDebugEnabled = logger.isDebugEnabled();
if (isDebugEnabled) {
if (cqs == null) {
logger.debug("CqService.stopCqs cqs : null");
} else {
logger.debug("CqService.stopCqs cqs : ({} queries)", cqs.size());
}
}
if (cqs == null) {
return;
}
String cqName = null;
for (InternalCqQuery internalCqQuery : cqs) {
CqQuery cq = internalCqQuery;
if (!cq.isClosed() && cq.isRunning()) {
try {
cqName = cq.getName();
cq.stop();
} catch (QueryException | CqClosedException e) {
if (isDebugEnabled) {
logger.debug("Failed to stop the CQ, CqName : {} Error : {}", cqName, e.getMessage());
}
}
}
}
}
use of org.apache.geode.cache.query.CqClosedException in project geode by apache.
the class CqServiceImpl method stopCq.
/**
* Called directly on server side.
*/
@Override
public void stopCq(String cqName, ClientProxyMembershipID clientId) throws CqException {
String serverCqName = cqName;
if (clientId != null) {
serverCqName = this.constructServerCqName(cqName, clientId);
removeFromCacheForServerToConstructedCQName(cqName, clientId);
}
ServerCQImpl cQuery = null;
StringId errMsg = null;
Exception ex = null;
try {
HashMap<String, CqQueryImpl> cqMap = cqQueryMap;
if (!cqMap.containsKey(serverCqName)) {
/*
* gregp 052808: We should silently fail here instead of throwing error. This is to deal
* with races in recovery
*/
return;
}
cQuery = (ServerCQImpl) getCq(serverCqName);
} catch (CacheLoaderException e1) {
errMsg = LocalizedStrings.CqService_CQ_NOT_FOUND_IN_THE_CQ_META_REGION_CQNAME_0;
ex = e1;
} catch (TimeoutException e2) {
errMsg = LocalizedStrings.CqService_TIMEOUT_WHILE_TRYING_TO_GET_CQ_FROM_META_REGION_CQNAME_0;
ex = e2;
} finally {
if (ex != null) {
String s = errMsg.toLocalizedString(cqName);
if (logger.isDebugEnabled()) {
logger.debug(s);
}
throw new CqException(s, ex);
}
}
try {
if (!cQuery.isStopped()) {
cQuery.stop();
}
} catch (CqClosedException cce) {
throw new CqException(cce.getMessage());
} finally {
// If this CQ is stopped, disable caching event keys for this CQ.
// this.removeCQFromCaching(cQuery.getServerCqName());
this.removeFromMatchingCqMap(cQuery);
}
// Send stop message to peers.
cQuery.getCqBaseRegion().getFilterProfile().stopCq(cQuery);
}
use of org.apache.geode.cache.query.CqClosedException in project geode by apache.
the class ClientCQImpl method executeCqOnRedundantsAndPrimary.
/**
* This executes the CQ first on the redundant server and then on the primary server. This is
* required to keep the redundancy behavior in accordance with the HAQueue expectation (wherein
* the events are delivered only from the primary).
*
* @param executeWithInitialResults boolean
* @return Object SelectResults in case of executeWithInitialResults
*/
private Object executeCqOnRedundantsAndPrimary(boolean executeWithInitialResults) throws CqClosedException, RegionNotFoundException, CqException {
Object initialResults = null;
synchronized (this.cqState) {
if (this.isClosed()) {
throw new CqClosedException(LocalizedStrings.CqQueryImpl_CQ_IS_CLOSED_CQNAME_0.toLocalizedString(this.cqName));
}
if (this.isRunning()) {
throw new IllegalStateException(LocalizedStrings.CqQueryImpl_CQ_IS_IN_RUNNING_STATE_CQNAME_0.toLocalizedString(this.cqName));
}
if (logger.isDebugEnabled()) {
logger.debug("Performing Execute {} request for CQ. CqName: {}", ((executeWithInitialResults) ? "WithInitialResult" : ""), this.cqName);
}
this.cqBaseRegion = (LocalRegion) cqService.getCache().getRegion(this.regionName);
// If not server send the request to server.
if (!cqService.isServer()) {
// pool that initializes the CQ. Else its set using the Region proxy.
if (this.cqProxy == null) {
initConnectionProxy();
}
boolean success = false;
try {
if (this.proxyCache != null) {
if (this.proxyCache.isClosed()) {
throw new CacheClosedException("Cache is closed for this user.");
}
UserAttributes.userAttributes.set(this.proxyCache.getUserAttributes());
}
if (executeWithInitialResults) {
initialResults = cqProxy.createWithIR(this);
if (initialResults == null) {
String errMsg = "Failed to execute the CQ. CqName: " + this.cqName + ", Query String is: " + this.queryString;
throw new CqException(errMsg);
}
} else {
cqProxy.create(this);
}
success = true;
} catch (Exception ex) {
// Check for system shutdown.
if (this.shutdownInProgress()) {
throw new CqException("System shutdown in progress.");
}
if (ex.getCause() instanceof GemFireSecurityException) {
if (securityLogWriter.warningEnabled()) {
securityLogWriter.warning(LocalizedStrings.CqQueryImpl_EXCEPTION_WHILE_EXECUTING_CQ_EXCEPTION_0, ex, null);
}
throw new CqException(ex.getCause().getMessage(), ex.getCause());
} else if (ex instanceof CqException) {
throw (CqException) ex;
} else {
String errMsg = LocalizedStrings.CqQueryImpl_FAILED_TO_EXECUTE_THE_CQ_CQNAME_0_QUERY_STRING_IS_1_ERROR_FROM_LAST_SERVER_2.toLocalizedString(this.cqName, this.queryString, ex.getLocalizedMessage());
if (logger.isDebugEnabled()) {
logger.debug(errMsg, ex);
}
throw new CqException(errMsg, ex);
}
} finally {
if (!success && !this.shutdownInProgress()) {
try {
cqProxy.close(this);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Exception cleaning up failed cq", e);
}
UserAttributes.userAttributes.set(null);
}
}
UserAttributes.userAttributes.set(null);
}
}
this.cqState.setState(CqStateImpl.RUNNING);
}
// If client side, alert listeners that a cqs have been connected
if (!cqService.isServer()) {
connected = true;
CqListener[] cqListeners = getCqAttributes().getCqListeners();
for (int lCnt = 0; lCnt < cqListeners.length; lCnt++) {
if (cqListeners[lCnt] != null) {
if (cqListeners[lCnt] instanceof CqStatusListener) {
CqStatusListener listener = (CqStatusListener) cqListeners[lCnt];
listener.onCqConnected();
}
}
}
}
// Update CQ-base region for book keeping.
this.cqService.stats().incCqsActive();
this.cqService.stats().decCqsStopped();
return initialResults;
}
Aggregations