Search in sources :

Example 1 with QueryInvocationTargetException

use of org.apache.geode.cache.query.QueryInvocationTargetException in project geode by apache.

the class AddFreeItemToOrders method execute.

public void execute(FunctionContext context) {
    Region region = null;
    List<Object> vals = new ArrayList<Object>();
    List<Object> keys = new ArrayList<Object>();
    List<Object> argsList = new ArrayList<Object>();
    Object[] argsArray = null;
    if (context.getArguments() instanceof Boolean) {
    } else if (context.getArguments() instanceof String) {
        String arg = (String) context.getArguments();
    } else if (context.getArguments() instanceof Vector) {
    } else if (context.getArguments() instanceof Object[]) {
        argsArray = (Object[]) context.getArguments();
        argsList = Arrays.asList(argsArray);
    } else {
        System.out.println("AddFreeItemToOrders : Invalid Arguments");
    }
    InternalCache cache = null;
    try {
        cache = (InternalCache) CacheFactory.getAnyInstance();
        cache.getCacheConfig().setPdxReadSerialized(true);
        region = cache.getRegion("orders");
    } catch (CacheClosedException ex) {
        vals.add("NoCacheFoundResult");
        context.getResultSender().lastResult(vals);
    }
    String oql = "SELECT DISTINCT entry.key FROM /orders.entries entry WHERE entry.value.totalPrice > $1";
    Object[] queryArgs = new Object[1];
    queryArgs[0] = argsList.get(0);
    final Query query = cache.getQueryService().newQuery(oql);
    SelectResults result = null;
    try {
        result = (SelectResults) query.execute(queryArgs);
        int resultSize = result.size();
        if (result instanceof Collection<?>)
            for (Object item : result) {
                keys.add(item);
            }
    } catch (FunctionDomainException e) {
        if (cache != null)
            cache.getLogger().info("Caught FunctionDomainException while executing function AddFreeItemToOrders: " + e.getMessage());
    } catch (TypeMismatchException e) {
        if (cache != null)
            cache.getLogger().info("Caught TypeMismatchException while executing function AddFreeItemToOrders: " + e.getMessage());
    } catch (NameResolutionException e) {
        if (cache != null)
            cache.getLogger().info("Caught NameResolutionException while executing function AddFreeItemToOrders: " + e.getMessage());
    } catch (QueryInvocationTargetException e) {
        if (cache != null)
            cache.getLogger().info("Caught QueryInvocationTargetException while executing function AddFreeItemToOrders" + e.getMessage());
    }
    // class has to be in classpath.
    try {
        Item it = (Item) (argsList.get(1));
        for (Object key : keys) {
            Object obj = region.get(key);
            if (obj instanceof PdxInstance) {
                PdxInstance pi = (PdxInstance) obj;
                Order receivedOrder = (Order) pi.getObject();
                receivedOrder.addItem(it);
                region.put(key, receivedOrder);
            }
        }
        context.getResultSender().lastResult("success");
    } catch (ClassCastException e) {
        context.getResultSender().lastResult("failure");
    } catch (Exception e) {
        context.getResultSender().lastResult("failure");
    }
}
Also used : Query(org.apache.geode.cache.query.Query) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) ArrayList(java.util.ArrayList) InternalCache(org.apache.geode.internal.cache.InternalCache) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) CacheClosedException(org.apache.geode.cache.CacheClosedException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) SelectResults(org.apache.geode.cache.query.SelectResults) PdxInstance(org.apache.geode.pdx.PdxInstance) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) Region(org.apache.geode.cache.Region) Collection(java.util.Collection) Vector(java.util.Vector)

Example 2 with QueryInvocationTargetException

use of org.apache.geode.cache.query.QueryInvocationTargetException in project geode by apache.

the class CompactRangeIndex method addToResultsFromEntries.

/*
   * 
   * @param lowerBoundKey the index key to match on for a lower bound on a ranged query, otherwise
   * the key to match on
   * 
   * @param upperBoundKey the index key to match on for an upper bound on a ranged query, otherwise
   * null
   * 
   * @param lowerBoundOperator the operator to use to determine a match against the lower bound
   * 
   * @param upperBoundOperator the operator to use to determine a match against the upper bound
   */
private void addToResultsFromEntries(Object lowerBoundKey, Object upperBoundKey, int lowerBoundOperator, int upperBoundOperator, CloseableIterator<IndexStoreEntry> entriesIter, Collection result, CompiledValue iterOps, RuntimeIterator runtimeItr, ExecutionContext context, List projAttrib, SelectResults intermediateResults, boolean isIntersection, int limit) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    QueryObserver observer = QueryObserverHolder.getInstance();
    boolean limitApplied = false;
    if (entriesIter == null || (limitApplied = verifyLimit(result, limit))) {
        if (limitApplied) {
            if (observer != null) {
                observer.limitAppliedAtIndexLevel(this, limit, result);
            }
        }
        return;
    }
    Set seenKey = null;
    if (IndexManager.IS_TEST_EXPANSION) {
        seenKey = new HashSet();
    }
    while (entriesIter.hasNext()) {
        try {
            // Check if query execution on this thread is canceled.
            QueryMonitor.isQueryExecutionCanceled();
            if (IndexManager.testHook != null) {
                if (this.region.getCache().getLogger().fineEnabled()) {
                    this.region.getCache().getLogger().fine("IndexManager TestHook is set in addToResultsFromEntries.");
                }
                IndexManager.testHook.hook(11);
            }
            IndexStoreEntry indexEntry = null;
            try {
                indexEntry = entriesIter.next();
            } catch (NoSuchElementException ignore) {
                // Continue from while.
                continue;
            }
            Object value = indexEntry.getDeserializedValue();
            if (IndexManager.IS_TEST_EXPANSION) {
                Object rk = indexEntry.getDeserializedRegionKey();
                if (seenKey.contains(rk)) {
                    continue;
                }
                seenKey.add(rk);
                List expandedResults = expandValue(context, lowerBoundKey, upperBoundKey, lowerBoundOperator, upperBoundOperator, value);
                Iterator iterator = ((Collection) expandedResults).iterator();
                while (iterator.hasNext()) {
                    value = iterator.next();
                    if (value != null) {
                        boolean ok = true;
                        if (runtimeItr != null) {
                            runtimeItr.setCurrent(value);
                        }
                        if (ok && runtimeItr != null && iterOps != null) {
                            ok = QueryUtils.applyCondition(iterOps, context);
                        }
                        if (ok) {
                            if (context != null && context.isCqQueryContext()) {
                                result.add(new CqEntry(indexEntry.getDeserializedRegionKey(), value));
                            } else {
                                applyProjection(projAttrib, context, result, value, intermediateResults, isIntersection);
                            }
                            if (verifyLimit(result, limit)) {
                                observer.limitAppliedAtIndexLevel(this, limit, result);
                                return;
                            }
                        }
                    }
                }
            } else {
                if (value != null) {
                    boolean ok = true;
                    if (indexEntry.isUpdateInProgress() || TEST_ALWAYS_UPDATE_IN_PROGRESS) {
                        IndexInfo indexInfo = (IndexInfo) context.cacheGet(CompiledValue.INDEX_INFO);
                        if (runtimeItr == null) {
                            runtimeItr = getRuntimeIteratorForThisIndex(context, indexInfo);
                            if (runtimeItr == null) {
                                // could not match index with iterator
                                throw new QueryInvocationTargetException("Query alias's must be used consistently");
                            }
                        }
                        runtimeItr.setCurrent(value);
                        // Verify index key in region entry value.
                        ok = evaluateEntry((IndexInfo) indexInfo, context, null);
                    }
                    if (runtimeItr != null) {
                        runtimeItr.setCurrent(value);
                    }
                    if (ok && runtimeItr != null && iterOps != null) {
                        ok = QueryUtils.applyCondition(iterOps, context);
                    }
                    if (ok) {
                        if (context != null && context.isCqQueryContext()) {
                            result.add(new CqEntry(indexEntry.getDeserializedRegionKey(), value));
                        } else {
                            if (IndexManager.testHook != null) {
                                IndexManager.testHook.hook(200);
                            }
                            applyProjection(projAttrib, context, result, value, intermediateResults, isIntersection);
                        }
                        if (verifyLimit(result, limit)) {
                            observer.limitAppliedAtIndexLevel(this, limit, result);
                            return;
                        }
                    }
                }
            }
        } catch (ClassCastException | EntryDestroyedException ignore) {
        // ignore it
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) MemoryIndexStoreEntry(org.apache.geode.cache.query.internal.index.MemoryIndexStore.MemoryIndexStoreEntry) IndexStoreEntry(org.apache.geode.cache.query.internal.index.IndexStore.IndexStoreEntry) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) IndexInfo(org.apache.geode.cache.query.internal.IndexInfo) QueryObserver(org.apache.geode.cache.query.internal.QueryObserver) CqEntry(org.apache.geode.cache.query.internal.CqEntry) RuntimeIterator(org.apache.geode.cache.query.internal.RuntimeIterator) CloseableIterator(org.apache.geode.internal.cache.persistence.query.CloseableIterator) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) NoSuchElementException(java.util.NoSuchElementException) HashSet(java.util.HashSet)

Example 3 with QueryInvocationTargetException

use of org.apache.geode.cache.query.QueryInvocationTargetException in project geode by apache.

the class PartitionedIndex method verifyAndCreateMissingIndex.

/**
   * Verify if the index is available of the buckets. If not create index on the bucket.
   */
public void verifyAndCreateMissingIndex(List buckets) throws QueryInvocationTargetException {
    PartitionedRegion pr = (PartitionedRegion) this.getRegion();
    PartitionedRegionDataStore prds = pr.getDataStore();
    for (Object bId : buckets) {
        // create index
        BucketRegion bukRegion = (BucketRegion) prds.getLocalBucketById((Integer) bId);
        if (bukRegion == null) {
            throw new QueryInvocationTargetException("Bucket not found for the id :" + bId);
        }
        IndexManager im = IndexUtils.getIndexManager(bukRegion, true);
        if (im != null && im.getIndex(indexName) == null) {
            try {
                if (pr.getCache().getLogger().fineEnabled()) {
                    pr.getCache().getLogger().fine("Verifying index presence on bucket region. " + " Found index " + this.indexName + " not present on the bucket region " + bukRegion.getFullPath() + ", index will be created on this region.");
                }
                ExecutionContext externalContext = new ExecutionContext(null, bukRegion.getCache());
                externalContext.setBucketRegion(pr, bukRegion);
                im.createIndex(this.indexName, this.type, this.originalIndexedExpression, this.fromClause, this.imports, externalContext, this, true);
            } catch (IndexExistsException iee) {
            // Index exists.
            } catch (IndexNameConflictException ince) {
            // ignore.
            }
        }
    }
}
Also used : ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) IndexExistsException(org.apache.geode.cache.query.IndexExistsException) BucketRegion(org.apache.geode.internal.cache.BucketRegion) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) PartitionedRegionDataStore(org.apache.geode.internal.cache.PartitionedRegionDataStore)

Example 4 with QueryInvocationTargetException

use of org.apache.geode.cache.query.QueryInvocationTargetException in project geode by apache.

the class HashIndex method addValueToResultSet.

private void addValueToResultSet(RegionEntry re, Collection result, CompiledValue iterOps, RuntimeIterator runtimeItr, ExecutionContext context, List projAttrib, SelectResults intermediateResults, boolean isIntersection, int limit, QueryObserver observer, long iteratorCreationTime) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    Object value = getTargetObject(re);
    if (value != null) {
        boolean ok = true;
        // we will reevaluate to be sure the value still matches the key
        if (re.isUpdateInProgress() || IndexManager.needsRecalculation(iteratorCreationTime, re.getLastModified())) {
            IndexInfo indexInfo = (IndexInfo) context.cacheGet(CompiledValue.INDEX_INFO);
            if (runtimeItr == null) {
                runtimeItr = getRuntimeIteratorForThisIndex(context, indexInfo);
                if (runtimeItr == null) {
                    // could not match index with iterator
                    throw new QueryInvocationTargetException("Query alias's must be used consistently");
                }
            }
            runtimeItr.setCurrent(value);
            // Verify index key in region entry value.
            ok = evaluateEntry(indexInfo, context, null);
        }
        if (runtimeItr != null) {
            runtimeItr.setCurrent(value);
        }
        if (ok && runtimeItr != null && iterOps != null) {
            ok = QueryUtils.applyCondition(iterOps, context);
        }
        if (ok) {
            if (context != null && context.isCqQueryContext()) {
                result.add(new CqEntry(re.getKey(), value));
            } else {
                applyProjection(projAttrib, context, result, value, intermediateResults, isIntersection);
            }
            if (limit != -1 && result.size() == limit) {
                observer.limitAppliedAtIndexLevel(this, limit, result);
                return;
            }
        }
    }
}
Also used : CqEntry(org.apache.geode.cache.query.internal.CqEntry) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) StoredObject(org.apache.geode.internal.offheap.StoredObject) IndexInfo(org.apache.geode.cache.query.internal.IndexInfo)

Example 5 with QueryInvocationTargetException

use of org.apache.geode.cache.query.QueryInvocationTargetException in project geode by apache.

the class PRQueryRegionClosedJUnitTest method testQueryingWithRegionClose.

/**
   * Tests the execution of query on a PartitionedRegion created on a single data store. <br>
   * 1. Creates a PR with redundancy=0 on a single VM. <br>
   * 2. Puts some test Objects in cache.<br>
   * 3. Create a Thread and fire queries on the data and verifies the result.<br>
   * 4. Create another Thread and call Region#close() on the PR region.<br>
   * 
   * 
   * @throws Exception
   */
@Test
public void testQueryingWithRegionClose() throws Exception {
    logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Test Started  ");
    logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: creating PR Region ");
    final Region region = PartitionedRegionTestHelper.createPartitionedRegion(regionName, localMaxMemory, redundancy);
    final Region localRegion = PartitionedRegionTestHelper.createLocalRegion(localRegionName);
    final StringBuffer errorBuf = new StringBuffer("");
    PortfolioData[] portfolios = new PortfolioData[100];
    try {
        for (int j = 0; j < 100; j++) {
            portfolios[j] = new PortfolioData(j);
        }
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: populating PortfolioData into the PR Datastore  ");
        populateData(region, portfolios);
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: populating PortfolioData into the PR Datastore  ");
        populateData(localRegion, portfolios);
        final String[] queryString = { "ID = 0 OR ID = 1", "ID > 4 AND ID < 9", "ID = 5", "ID < 5 ", "ID <= 5" };
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Creating a Thread which will fire queries on the datastore");
        Thread t1 = new Thread(new Runnable() {

            public void run() {
                final String expectedRegionDestroyedException = RegionDestroyedException.class.getName();
                logger.info("<ExpectedException action=add>" + expectedRegionDestroyedException + "</ExpectedException>");
                for (int i = 0; i < queryString.length; i++) {
                    try {
                        SelectResults resSetPR = region.query(queryString[i]);
                        SelectResults resSetLocal = localRegion.query(queryString[i]);
                        String failureString = PartitionedRegionTestHelper.compareResultSets(resSetPR, resSetLocal);
                        Thread.sleep(delayQuery);
                        if (failureString != null) {
                            errorBuf.append(failureString);
                            throw (new Exception(failureString));
                        }
                    } catch (InterruptedException ie) {
                        fail("interrupted");
                    } catch (RegionDestroyedException rde) {
                        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: RegionDestroyedException as Expected " + rde);
                    } catch (RegionNotFoundException rnfe) {
                        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: RegionNotFoundException as Expected " + rnfe);
                    } catch (QueryInvocationTargetException qite) {
                        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: QueryInvocationTargetException as Expected " + qite);
                    } catch (Exception qe) {
                        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Unexpected Exception " + qe);
                        encounteredException = true;
                        StringWriter sw = new StringWriter();
                        qe.printStackTrace(new PrintWriter(sw));
                        errorBuf.append(sw);
                    }
                }
                logger.info("<ExpectedException action=remove>" + expectedRegionDestroyedException + "</ExpectedException>");
            }
        });
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Creating a Thread which will call Region.destroyRegion() on the datastore ");
        Thread t2 = new Thread(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(2500);
                } catch (InterruptedException ie) {
                    fail("interrupted");
                }
                region.close();
                logger.info("PROperationWithQueryDUnitTest#getCacheSerializableRunnableForRegionClose: Region Closed on VM ");
            }
        });
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Initiating the  Threads");
        t1.start();
        t2.start();
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Waiting for the Threads to join ");
        t1.join(30000);
        assertFalse(t1.isAlive());
        t2.join(30000);
        assertFalse(t2.isAlive());
        logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: checking for any Unexpected Exception's occurred");
        assertFalse("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Exception occurred in Query-thread", encounteredException);
    } catch (Exception e) {
        e.printStackTrace();
        fail("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Test failed because of exception " + e);
    }
    logger.info("PRQueryRegionClosedJUnitTest#testQueryingWithRegionClose: Test Ended");
}
Also used : RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) RegionNotFoundException(org.apache.geode.cache.query.RegionNotFoundException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) RegionNotFoundException(org.apache.geode.cache.query.RegionNotFoundException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) SelectResults(org.apache.geode.cache.query.SelectResults) StringWriter(java.io.StringWriter) Region(org.apache.geode.cache.Region) PortfolioData(org.apache.geode.cache.query.data.PortfolioData) PrintWriter(java.io.PrintWriter) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

QueryInvocationTargetException (org.apache.geode.cache.query.QueryInvocationTargetException)42 Region (org.apache.geode.cache.Region)23 SelectResults (org.apache.geode.cache.query.SelectResults)22 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)21 QueryService (org.apache.geode.cache.query.QueryService)20 QueryException (org.apache.geode.cache.query.QueryException)16 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)16 Cache (org.apache.geode.cache.Cache)15 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)15 NameResolutionException (org.apache.geode.cache.query.NameResolutionException)15 TypeMismatchException (org.apache.geode.cache.query.TypeMismatchException)15 FunctionDomainException (org.apache.geode.cache.query.FunctionDomainException)14 Query (org.apache.geode.cache.query.Query)13 DefaultQuery (org.apache.geode.cache.query.internal.DefaultQuery)13 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)12 CancelException (org.apache.geode.CancelException)10 StructSetOrResultsSet (org.apache.geode.cache.query.functional.StructSetOrResultsSet)10 LocalRegion (org.apache.geode.internal.cache.LocalRegion)10 Host (org.apache.geode.test.dunit.Host)10 VM (org.apache.geode.test.dunit.VM)10