Search in sources :

Example 6 with IndexInvalidException

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

the class PartitionedRegion method createIndex.

public Index createIndex(boolean remotelyOriginated, IndexType indexType, String indexName, String indexedExpression, String fromClause, String imports, boolean loadEntries, boolean sendMessage) throws ForceReattemptException, IndexCreationException, IndexNameConflictException, IndexExistsException {
    // Check if its remote request and this vm is an accessor.
    if (remotelyOriginated && dataStore == null) {
        // data store where as it should have.
        if (getLocalMaxMemory() != 0) {
            throw new IndexCreationException(LocalizedStrings.PartitionedRegion_DATA_STORE_ON_THIS_VM_IS_NULL_AND_THE_LOCAL_MAX_MEMORY_IS_NOT_ZERO_THE_DATA_POLICY_IS_0_AND_THE_LOCALMAXMEMEORY_IS_1.toLocalizedString(getDataPolicy(), (long) getLocalMaxMemory()));
        }
        // Not have to do anything since the region is just an Accessor and
        // does not store any data.
        logger.info(LocalizedMessage.create(LocalizedStrings.PartitionedRegion_THIS_IS_AN_ACCESSOR_VM_AND_DOESNT_CONTAIN_DATA));
        return null;
    }
    // Create indexManager.
    if (this.indexManager == null) {
        this.indexManager = IndexUtils.getIndexManager(this, true);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Started creating index with Index Name :{} On PartitionedRegion {}, Indexfrom caluse={}, Remote Request: {}", indexName, this.getFullPath(), fromClause, remotelyOriginated);
    }
    IndexTask indexTask = new IndexTask(remotelyOriginated, indexType, indexName, indexedExpression, fromClause, imports, loadEntries);
    FutureTask<Index> indexFutureTask = new FutureTask<Index>(indexTask);
    // This will return either the Index FutureTask or Index itself, based
    // on whether the index creation is in process or completed.
    Object ind = this.indexes.putIfAbsent(indexTask, indexFutureTask);
    // Check if its instance of Index, in that the case throw index exists exception.
    if (ind instanceof Index) {
        if (remotelyOriginated) {
            return (Index) ind;
        }
        throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
    }
    FutureTask<Index> oldIndexFutureTask = (FutureTask<Index>) ind;
    Index index = null;
    boolean interrupted = false;
    try {
        if (oldIndexFutureTask == null) {
            // Index doesn't exist, create index.
            indexFutureTask.run();
            index = indexFutureTask.get();
            if (index != null) {
                this.indexes.put(indexTask, index);
                PartitionedIndex prIndex = (PartitionedIndex) index;
                indexManager.addIndex(indexName, index);
                // Send create request to other PR nodes.
                if (!remotelyOriginated && sendMessage) {
                    logger.info(LocalizedMessage.create(LocalizedStrings.PartitionedRegion_CREATED_INDEX_LOCALLY_SENDING_INDEX_CREATION_MESSAGE_TO_ALL_MEMBERS_AND_WILL_BE_WAITING_FOR_RESPONSE_0, prIndex));
                    HashSet<IndexCreationData> singleIndexDefinition = new HashSet<IndexCreationData>();
                    IndexCreationData icd = new IndexCreationData(indexName);
                    icd.setIndexData(indexType, fromClause, indexedExpression, imports, loadEntries);
                    singleIndexDefinition.add(icd);
                    IndexCreationMsg.IndexCreationResponse response = null;
                    try {
                        response = (IndexCreationMsg.IndexCreationResponse) IndexCreationMsg.send(null, PartitionedRegion.this, singleIndexDefinition);
                        if (response != null) {
                            IndexCreationMsg.IndexCreationResult result = response.waitForResult();
                            Map<String, Integer> indexBucketsMap = result.getIndexBucketsMap();
                            if (indexBucketsMap != null && indexBucketsMap.size() > 0) {
                                prIndex.setRemoteBucketesIndexed(indexBucketsMap.values().iterator().next());
                            }
                        }
                    } catch (UnsupportedOperationException ignore) {
                        // if remote nodes are of older versions indexes will not be created there, so remove
                        // index on this node as well.
                        this.indexes.remove(index);
                        indexManager.removeIndex(index);
                        throw new IndexCreationException(LocalizedStrings.PartitionedRegion_INDEX_CREATION_FAILED_ROLLING_UPGRADE.toLocalizedString());
                    }
                }
            }
        } else {
            // Some other thread is trying to create the same index.
            // Wait for index to be initialized from other thread.
            index = oldIndexFutureTask.get();
            if (remotelyOriginated) {
                return index;
            }
            throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
        }
    } catch (InterruptedException ignore) {
        interrupted = true;
    } catch (ExecutionException ee) {
        if (!remotelyOriginated) {
            Throwable cause = ee.getCause();
            if (cause instanceof IndexNameConflictException) {
                throw (IndexNameConflictException) cause;
            } else if (cause instanceof IndexExistsException) {
                throw (IndexExistsException) cause;
            }
            throw new IndexInvalidException(ee);
        }
    } finally {
        // If the index is not successfully created, remove IndexTask from the map.
        if (index == null) {
            ind = this.indexes.get(indexTask);
            if (index != null && !(index instanceof Index)) {
                this.indexes.remove(indexTask);
            }
        }
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Completed creating index with Index Name :{} On PartitionedRegion {}, Remote Request: {}", indexName, this.getFullPath(), remotelyOriginated);
    }
    return index;
}
Also used : IndexExistsException(org.apache.geode.cache.query.IndexExistsException) Index(org.apache.geode.cache.query.Index) PartitionedIndex(org.apache.geode.cache.query.internal.index.PartitionedIndex) AbstractIndex(org.apache.geode.cache.query.internal.index.AbstractIndex) IndexCreationData(org.apache.geode.cache.query.internal.index.IndexCreationData) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PartitionedIndex(org.apache.geode.cache.query.internal.index.PartitionedIndex) FutureTask(java.util.concurrent.FutureTask) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) IndexCreationException(org.apache.geode.cache.query.IndexCreationException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) IndexCreationMsg(org.apache.geode.internal.cache.partitioned.IndexCreationMsg) ExecutionException(java.util.concurrent.ExecutionException) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) HashSet(java.util.HashSet)

Example 7 with IndexInvalidException

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

the class ResourceManagerWithQueryMonitorDUnitTest method doCriticalMemoryHitWithIndexTest.

// test to verify what happens during index creation if memory threshold is hit
private void doCriticalMemoryHitWithIndexTest(final String regionName, boolean createPR, final int criticalThreshold, final boolean disabledQueryMonitorForLowMem, final int queryTimeout, final boolean hitCriticalThreshold, final String indexType) throws Exception {
    // create region on the server
    final Host host = Host.getHost(0);
    final VM server1 = host.getVM(0);
    final VM server2 = host.getVM(2);
    final VM client = host.getVM(1);
    final int numObjects = 200;
    try {
        final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2);
        startCacheServer(server1, port[0], criticalThreshold, disabledQueryMonitorForLowMem, queryTimeout, regionName, createPR, 0);
        startCacheServer(server2, port[1], criticalThreshold, true, -1, regionName, createPR, 0);
        startClient(client, server1, port[0], regionName);
        populateData(server1, regionName, numObjects);
        createCancelDuringGatherTestHook(server1);
        server1.invoke(new SerializableCallable("create index") {

            public Object call() {
                QueryService qs = null;
                try {
                    qs = getCache().getQueryService();
                    Index index = null;
                    if (indexType.equals("compact")) {
                        index = qs.createIndex("newIndex", "ID", "/" + regionName);
                    } else if (indexType.equals("hash")) {
                        index = qs.createHashIndex("newIndex", "ID", "/" + regionName);
                    }
                    assertNotNull(index);
                    assertTrue(((CancelDuringGatherHook) DefaultQuery.testHook).triggeredOOME);
                    if (hitCriticalThreshold && !disabledQueryMonitorForLowMem) {
                        throw new CacheException("Should have hit low memory") {
                        };
                    }
                    assertEquals(1, qs.getIndexes().size());
                } catch (Exception e) {
                    if (e instanceof IndexInvalidException) {
                        if (!hitCriticalThreshold || disabledQueryMonitorForLowMem) {
                            throw new CacheException("Should not have run into low memory exception") {
                            };
                        }
                    } else {
                        throw new CacheException(e) {
                        };
                    }
                }
                return 0;
            }
        });
    } finally {
        stopServer(server1);
        stopServer(server2);
    }
}
Also used : QueryService(org.apache.geode.cache.query.QueryService) CacheException(org.apache.geode.cache.CacheException) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Host(org.apache.geode.test.dunit.Host) Index(org.apache.geode.cache.query.Index) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) QueryExecutionTimeoutException(org.apache.geode.cache.query.QueryExecutionTimeoutException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) CacheException(org.apache.geode.cache.CacheException) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) QueryException(org.apache.geode.cache.query.QueryException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException)

Example 8 with IndexInvalidException

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

the class IndexManager method createIndex.

// @todo need more specific list of exceptions
/**
   * Create an index that can be used when executing queries.
   * 
   * @param indexName the name of this index, used for statistics collection
   * @param indexType the type of index
   * @param origIndexedExpression the expression to index on, a function dependent on region entries
   *        individually.
   * @param origFromClause expression that evaluates to the collection(s) that will be queried over,
   *        must contain one and only one region path.
   * @return the newly created Index
   */
public Index createIndex(String indexName, IndexType indexType, String origIndexedExpression, String origFromClause, String imports, ExecutionContext externalContext, PartitionedIndex prIndex, boolean loadEntries) throws IndexNameConflictException, IndexExistsException, IndexInvalidException {
    if (QueryMonitor.isLowMemory()) {
        throw new IndexInvalidException(LocalizedStrings.IndexCreationMsg_CANCELED_DUE_TO_LOW_MEMORY.toLocalizedString());
    }
    boolean oldReadSerialized = DefaultQuery.getPdxReadSerialized();
    DefaultQuery.setPdxReadSerialized(this.region.getCache(), true);
    TXStateProxy tx = null;
    if (!((InternalCache) this.region.getCache()).isClient()) {
        tx = ((TXManagerImpl) this.region.getCache().getCacheTransactionManager()).internalSuspend();
    }
    try {
        // for now this is the only option
        String projectionAttributes = "*";
        if (getIndex(indexName) != null) {
            throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
        }
        IndexCreationHelper helper = null;
        boolean isCompactOrHash = false;
        // to recalculate the index key for the entry for comparisons during query.
        if (indexType == IndexType.HASH && isOverFlowRegion()) {
            indexType = IndexType.FUNCTIONAL;
        }
        if (indexType != IndexType.PRIMARY_KEY) {
            helper = new FunctionalIndexCreationHelper(origFromClause, origIndexedExpression, projectionAttributes, imports, (InternalCache) region.getCache(), externalContext, this);
            // Asif: For now support Map index as non compact .expand later
            // The limitation for compact range index also apply to hash index for now
            isCompactOrHash = shouldCreateCompactIndex((FunctionalIndexCreationHelper) helper);
        } else if (indexType == IndexType.PRIMARY_KEY) {
            helper = new PrimaryKeyIndexCreationHelper(origFromClause, origIndexedExpression, projectionAttributes, (InternalCache) region.getCache(), externalContext, this);
        } else {
            throw new AssertionError("Don't know how to set helper for " + indexType);
        }
        if (!isCompactOrHash && indexType != IndexType.PRIMARY_KEY) {
            if (indexType == IndexType.HASH) {
                if (!isIndexMaintenanceTypeSynchronous()) {
                    throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_HASH_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_ASYNC_MAINTENANCE.toLocalizedString());
                }
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_HASH_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_MULTIPLE_ITERATORS.toLocalizedString());
            }
            // Overflow is not supported with range index.
            if (isOverFlowRegion()) {
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_REGIONS_WHICH_OVERFLOW_TO_DISK_THE_REGION_INVOLVED_IS_0.toLocalizedString(region.getFullPath()));
            }
            // OffHeap is not supported with range index.
            if (isOffHeap()) {
                if (!isIndexMaintenanceTypeSynchronous()) {
                    throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_OFF_HEAP_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_ASYNC_MAINTENANCE_THE_REGION_IS_0.toLocalizedString(region.getFullPath()));
                }
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_OFF_HEAP_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_MULTIPLE_ITERATORS_THE_REGION_IS_0.toLocalizedString(region.getFullPath()));
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Started creating index with indexName: {} On region: {}", indexName, region.getFullPath());
        }
        if (IndexManager.testHook != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("IndexManager TestHook is set.");
            }
            if (((LocalRegion) this.region).isInitialized()) {
                testHook.hook(1);
            } else {
                testHook.hook(0);
            }
        }
        IndexTask indexTask = new IndexTask(indexName, indexType, origFromClause, origIndexedExpression, helper, isCompactOrHash, prIndex, loadEntries);
        FutureTask<Index> indexFutureTask = new FutureTask<Index>(indexTask);
        Object oldIndex = this.indexes.putIfAbsent(indexTask, indexFutureTask);
        Index index = null;
        boolean interrupted = false;
        try {
            if (oldIndex == null) {
                // Initialize index.
                indexFutureTask.run();
                // Set the index.
                index = (Index) indexFutureTask.get();
            } else {
                // Check if index creation is complete.
                if (!(oldIndex instanceof Index)) {
                    // Some other thread is creating the same index.
                    // Wait for index to be initialized from other thread.
                    ((Future) oldIndex).get();
                }
                // from this thread.
                if (getIndex(indexName) != null) {
                    throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
                } else {
                    throw new IndexExistsException(LocalizedStrings.IndexManager_SIMILAR_INDEX_EXISTS.toLocalizedString());
                }
            }
        } catch (InterruptedException ignored) {
            interrupted = true;
        } catch (ExecutionException ee) {
            Throwable c = ee.getCause();
            if (c instanceof IndexNameConflictException) {
                throw (IndexNameConflictException) c;
            } else if (c instanceof IndexExistsException) {
                throw (IndexExistsException) c;
            } else if (c instanceof IMQException) {
                throw new IndexInvalidException(c.getMessage());
            }
            throw new IndexInvalidException(ee);
        } finally {
            // the map.
            if (oldIndex == null && index == null) {
                Object ind = this.indexes.get(indexTask);
                if (ind != null && !(ind instanceof Index)) {
                    this.indexes.remove(indexTask);
                }
            }
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
        assert (index != null);
        if (logger.isDebugEnabled()) {
            logger.debug("Completed creating index with indexName: {} On region: {}", indexName, region.getFullPath());
        }
        return index;
    } finally {
        DefaultQuery.setPdxReadSerialized(this.region.getCache(), oldReadSerialized);
        if (tx != null) {
            ((TXManagerImpl) this.region.getCache().getCacheTransactionManager()).internalResume(tx);
        }
    }
}
Also used : IndexExistsException(org.apache.geode.cache.query.IndexExistsException) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) InternalCache(org.apache.geode.internal.cache.InternalCache) Index(org.apache.geode.cache.query.Index) LocalRegion(org.apache.geode.internal.cache.LocalRegion) FutureTask(java.util.concurrent.FutureTask) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) Future(java.util.concurrent.Future) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) ExecutionException(java.util.concurrent.ExecutionException)

Example 9 with IndexInvalidException

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

the class IndexManager method recreateAllIndexesForRegion.

/**
   * Recreates all indexes for this region. This operation blocks all updates on all indexes while
   * recreate is in progress. This is required as recreate does NOT lock region entries before index
   * update and hence might cause inconsistencies in index if concurrent region entry operations are
   * going on.
   * 
   */
private void recreateAllIndexesForRegion() {
    long start = 0;
    waitBeforeUpdate();
    try {
        // opCode is ignored for this operation
        Iterator iter = this.indexes.values().iterator();
        while (iter.hasNext()) {
            Object ind = iter.next();
            // the index is in create phase.
            if (ind instanceof FutureTask) {
                continue;
            }
            IndexProtocol index = (IndexProtocol) ind;
            if (index.getType() == IndexType.FUNCTIONAL || index.getType() == IndexType.HASH) {
                AbstractIndex aIndex = ((AbstractIndex) index);
                start = ((AbstractIndex) index).updateIndexUpdateStats();
                ((AbstractIndex) index).recreateIndexData();
                ((AbstractIndex) index).updateIndexUpdateStats(start);
            }
        }
    } catch (Exception e) {
        throw new IndexInvalidException(e);
    } finally {
        notifyAfterUpdate();
    }
}
Also used : FutureTask(java.util.concurrent.FutureTask) Iterator(java.util.Iterator) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) AmbiguousNameException(org.apache.geode.cache.query.AmbiguousNameException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) IndexMaintenanceException(org.apache.geode.cache.query.IndexMaintenanceException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) ExecutionException(java.util.concurrent.ExecutionException) QueryException(org.apache.geode.cache.query.QueryException) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) IndexExistsException(org.apache.geode.cache.query.IndexExistsException)

Example 10 with IndexInvalidException

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

the class FunctionalIndexCreationHelper method prepareFromClause.

/**
   * The function is modified to optimize the index creation code. If the 0th iterator of from
   * clause is not on Entries, then the 0th iterator is replaced with that of entries & the value
   * corresponding to original iterator is derived from the 0th iterator as additional projection
   * attribute. All the other iterators & index expression if were dependent on 0th iterator are
   * also appropriately modified such that they are correctly derived on the modified 0th iterator.
   * <p>
   * TODO: method is too complex for IDE to analyze -- refactor prepareFromClause
   */
private void prepareFromClause(IndexManager imgr) throws IndexInvalidException {
    if (this.imports != null) {
        this.compiler.compileImports(this.imports);
    }
    List list = this.compiler.compileFromClause(this.fromClause);
    if (list == null) {
        throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_INVALID_FROM_CLAUSE_0.toLocalizedString(this.fromClause));
    }
    int size = list.size();
    this.canonicalizedIteratorNames = new String[size];
    this.canonicalizedIteratorDefinitions = new String[size];
    StringBuilder tempBuff = new StringBuilder();
    boolean isFromClauseNull = true;
    try {
        PartitionedRegion pr = this.context.getPartitionedRegion();
        for (int i = 0; i < size; i++) {
            CompiledIteratorDef iterDef = (CompiledIteratorDef) list.get(i);
            iterDef.computeDependencies(this.context);
            RuntimeIterator rIter = iterDef.getRuntimeIterator(this.context);
            this.context.addToIndependentRuntimeItrMapForIndexCreation(iterDef);
            this.context.bindIterator(rIter);
            if (i != 0 && !iterDef.isDependentOnCurrentScope(this.context)) {
                throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_INVALID_FROM_CLAUSE_0_SUBSEQUENT_ITERATOR_EXPRESSIONS_IN_FROM_CLAUSE_MUST_BE_DEPENDENT_ON_PREVIOUS_ITERATORS.toLocalizedString(this.fromClause));
            }
            String definition = rIter.getDefinition();
            this.canonicalizedIteratorDefinitions[i] = definition;
            // Bind the Index_Internal_ID to the RuntimeIterator
            this.canonicalizedIteratorNames[i] = imgr.putCanonicalizedIteratorNameIfAbsent(definition);
            if (pr != null) {
                this.canonicalizedIteratorNames[i] = pr.getIndexManager().putCanonicalizedIteratorNameIfAbsent(definition);
            } else {
                this.canonicalizedIteratorNames[i] = imgr.putCanonicalizedIteratorNameIfAbsent(definition);
            }
            rIter.setIndexInternalID(this.canonicalizedIteratorNames[i]);
            tempBuff.append(definition).append(' ').append(this.canonicalizedIteratorNames[i]).append(", ");
            isFromClauseNull = false;
            CompiledIteratorDef newItr;
            if (i == 0) {
                CompiledValue cv = iterDef.getCollectionExpr();
                this.addnlProjType = rIter.getElementType();
                String name = iterDef.getName();
                if (isEmpty(name)) {
                    // In case the name of iterator is null or blank set it to index_internal_id
                    name = this.canonicalizedIteratorNames[i];
                }
                CompiledValue newCollExpr = new CompiledPath(new CompiledBindArgument(1), "entries");
                // TODO: What if cv is not an instance of CompiledRegion
                if (cv instanceof CompiledRegion) {
                    this.missingLink = new CompiledPath(new CompiledID(name), "value");
                    this.additionalProj = this.missingLink;
                } else if (cv instanceof CompiledOperation || cv instanceof CompiledPath || cv instanceof CompiledIndexOperation) {
                    CompiledValue prevCV;
                    List reconstruct = new ArrayList();
                    while (!(cv instanceof CompiledRegion)) {
                        prevCV = cv;
                        if (cv instanceof CompiledOperation) {
                            reconstruct.add(0, ((CompiledOperation) cv).getArguments());
                            reconstruct.add(0, ((CompiledOperation) cv).getMethodName());
                            cv = ((CompiledOperation) cv).getReceiver(this.context);
                        } else if (cv instanceof CompiledPath) {
                            reconstruct.add(0, ((CompiledPath) cv).getTailID());
                            cv = cv.getReceiver();
                        } else if (cv instanceof CompiledIndexOperation) {
                            reconstruct.add(0, ((CompiledIndexOperation) cv).getExpression());
                            cv = cv.getReceiver();
                        } else {
                            throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSEFROM_CLAUSE_IS_NEITHER_A_COMPILEDPATH_NOR_COMPILEDOPERATION.toLocalizedString());
                        }
                        reconstruct.add(0, prevCV.getType());
                    }
                    int firstTokenType = (Integer) reconstruct.get(0);
                    if (firstTokenType == CompiledValue.PATH) {
                        String tailID = (String) reconstruct.get(1);
                        if (tailID.equals("asList") || tailID.equals("asSet") || tailID.equals("values") || tailID.equals("toArray") || tailID.equals("getValues")) {
                            this.missingLink = new CompiledPath(new CompiledID(name), "value");
                        } else if (tailID.equals("keys") || tailID.equals("getKeys") || tailID.equals("keySet")) {
                            this.missingLink = new CompiledPath(new CompiledID(name), "key");
                            this.isFirstIteratorRegionKey = true;
                        } else if (tailID.equals("entries") || tailID.equals("getEntries") || tailID.equals("entrySet")) {
                            this.isFirstIteratorRegionEntry = true;
                        } else {
                            throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSEFROM_CLAUSE_DOES_NOT_EVALUATE_TO_VALID_COLLECTION.toLocalizedString());
                        }
                        remove(reconstruct, 2, 0);
                        int secondTokenType = reconstruct.size() > 1 ? (Integer) reconstruct.get(0) : -1;
                        if (!this.isFirstIteratorRegionEntry && secondTokenType == OQLLexerTokenTypes.TOK_LBRACK) {
                            // should be thrown as IndexOpn on set is not defined.
                            if (tailID.equals("values") || tailID.equals("getValues")) {
                                boolean returnEntryForRegionCollection = true;
                                this.additionalProj = new CompiledIndexOperation(new CompiledBindArgument(1), (CompiledValue) reconstruct.get(1), returnEntryForRegionCollection);
                                this.isFirstIteratorRegionEntry = true;
                            } else if (tailID.equals("toList") || tailID.equals("toArray")) {
                                // TODO: add support for toList and toArray
                                throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSETOLIST_TOARRAY_NOT_SUPPORTED.toLocalizedString());
                            } else {
                                throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSETOLIST_TOARRAY_NOT_SUPPORTED.toLocalizedString());
                            }
                            remove(reconstruct, 2, 0);
                        } else if (!this.isFirstIteratorRegionEntry && (secondTokenType == OQLLexerTokenTypes.METHOD_INV || secondTokenType == CompiledValue.PATH) && (tailID.equals("values") || tailID.equals("getValues") || tailID.equals("keySet") || tailID.equals("keys") || tailID.equals("getKeys"))) {
                            // Check if the second token name is toList or toArray or asSet.We need to remove
                            // those
                            String secTokName = (String) reconstruct.get(1);
                            if (secTokName.equals("asList") || secTokName.equals("asSet") || secTokName.equals("toArray")) {
                                remove(reconstruct, secondTokenType == OQLLexerTokenTypes.METHOD_INV ? 3 : 2, 0);
                            }
                        }
                    } else if (firstTokenType == OQLLexerTokenTypes.TOK_LBRACK) {
                        boolean returnEntryForRegionCollection = true;
                        this.additionalProj = new CompiledIndexOperation(new CompiledBindArgument(1), (CompiledValue) reconstruct.get(1), returnEntryForRegionCollection);
                        this.isFirstIteratorRegionEntry = true;
                    } else if (firstTokenType == OQLLexerTokenTypes.METHOD_INV) {
                        String methodName = (String) reconstruct.get(1);
                        if (methodName.equals("asList") || methodName.equals("asSet") || methodName.equals("values") || methodName.equals("toArray") || methodName.equals("getValues")) {
                            this.missingLink = new CompiledPath(new CompiledID(name), "value");
                        } else if (methodName.equals("keys") || methodName.equals("getKeys") || methodName.equals("keySet")) {
                            this.missingLink = new CompiledPath(new CompiledID(name), "key");
                            this.isFirstIteratorRegionKey = true;
                        } else if (methodName.equals("entries") || methodName.equals("getEntries") || methodName.equals("entrySet")) {
                            this.isFirstIteratorRegionEntry = true;
                            List args = (List) reconstruct.get(2);
                            if (args != null && args.size() == 1) {
                                Object obj = args.get(0);
                                if (obj instanceof CompiledBindArgument) {
                                    throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSEENTRIES_METHOD_CALLED_WITH_COMPILEDBINDARGUMENT.toLocalizedString());
                                }
                            }
                        }
                        remove(reconstruct, 3, 0);
                        int secondTokenType = reconstruct.size() > 1 ? (Integer) reconstruct.get(0) : -1;
                        if (!this.isFirstIteratorRegionEntry && secondTokenType == OQLLexerTokenTypes.TOK_LBRACK) {
                            if (methodName.equals("values") || methodName.equals("getValues")) {
                                boolean returnEntryForRegionCollection = true;
                                newCollExpr = new CompiledIndexOperation(new CompiledBindArgument(1), (CompiledValue) reconstruct.get(1), returnEntryForRegionCollection);
                            } else if (methodName.equals("toList") || methodName.equals("toArray")) {
                                // TODO: add support for toList and toArray
                                throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSETOLIST_TOARRAY_NOT_SUPPORTED_YET.toLocalizedString());
                            } else {
                                throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSETOLIST_TOARRAY_NOT_SUPPORTED_YET.toLocalizedString());
                            }
                            remove(reconstruct, 2, 0);
                        } else if (!this.isFirstIteratorRegionEntry && (secondTokenType == OQLLexerTokenTypes.METHOD_INV || secondTokenType == CompiledValue.PATH) && (methodName.equals("values") || methodName.equals("getValues") || methodName.equals("keys") || methodName.equals("getKeys") || methodName.equals("keySet"))) {
                            // Check if the second token name is toList or toArray or asSet.We need to remove
                            // those
                            String secTokName = (String) reconstruct.get(1);
                            if (secTokName.equals("asList") || secTokName.equals("asSet") || secTokName.equals("toArray")) {
                                remove(reconstruct, secondTokenType == OQLLexerTokenTypes.METHOD_INV ? 3 : 2, 0);
                            }
                        }
                    }
                    if (!this.isFirstIteratorRegionEntry) {
                        this.additionalProj = this.missingLink;
                        int len = reconstruct.size();
                        for (int j = 0; j < len; ++j) {
                            Object obj = reconstruct.get(j);
                            if (obj instanceof Integer) {
                                int tokenType = (Integer) obj;
                                if (tokenType == CompiledValue.PATH) {
                                    this.additionalProj = new CompiledPath(this.additionalProj, (String) reconstruct.get(++j));
                                } else if (tokenType == OQLLexerTokenTypes.TOK_LBRACK) {
                                    this.additionalProj = new CompiledIndexOperation(this.additionalProj, (CompiledValue) reconstruct.get(++j));
                                } else if (tokenType == OQLLexerTokenTypes.METHOD_INV) {
                                    this.additionalProj = new CompiledOperation(this.additionalProj, (String) reconstruct.get(++j), (List) reconstruct.get(++j));
                                }
                            }
                        }
                    }
                } else {
                    throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_FUNCTIONALINDEXCREATIONHELPERPREPAREFROMCLAUSEFROM_CLAUSE_IS_NEITHER_A_COMPILEDPATH_NOR_COMPILEDOPERATION.toLocalizedString());
                }
                if (!this.isFirstIteratorRegionEntry) {
                    newItr = new CompiledIteratorDef(name, null, newCollExpr);
                    this.indexInitIterators = new ArrayList();
                    this.indexInitIterators.add(newItr);
                }
            } else if (!this.isFirstIteratorRegionEntry) {
                newItr = iterDef;
                if (rIter.getDefinition().contains(this.canonicalizedIteratorNames[0])) {
                    newItr = (CompiledIteratorDef) getModifiedDependentCompiledValue(this.context, i, iterDef, true);
                }
                this.indexInitIterators.add(newItr);
            }
        }
    } catch (IndexInvalidException e) {
        throw e;
    } catch (Exception e) {
        throw new IndexInvalidException(e);
    }
    if (isFromClauseNull)
        throw new IndexInvalidException(LocalizedStrings.FunctionalIndexCreationHelper_INVALID_FROM_CLAUSE_0.toLocalizedString(this.fromClause));
    this.fromClause = tempBuff.substring(0, tempBuff.length() - 2);
    this.fromClauseIterators = list;
}
Also used : CompiledIteratorDef(org.apache.geode.cache.query.internal.CompiledIteratorDef) CompiledID(org.apache.geode.cache.query.internal.CompiledID) CompiledValue(org.apache.geode.cache.query.internal.CompiledValue) ArrayList(java.util.ArrayList) CompiledPath(org.apache.geode.cache.query.internal.CompiledPath) CompiledIndexOperation(org.apache.geode.cache.query.internal.CompiledIndexOperation) AmbiguousNameException(org.apache.geode.cache.query.AmbiguousNameException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) CompiledBindArgument(org.apache.geode.cache.query.internal.CompiledBindArgument) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) CompiledOperation(org.apache.geode.cache.query.internal.CompiledOperation) ArrayList(java.util.ArrayList) List(java.util.List) CompiledRegion(org.apache.geode.cache.query.internal.CompiledRegion) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) RuntimeIterator(org.apache.geode.cache.query.internal.RuntimeIterator)

Aggregations

IndexInvalidException (org.apache.geode.cache.query.IndexInvalidException)11 IndexExistsException (org.apache.geode.cache.query.IndexExistsException)5 IndexNameConflictException (org.apache.geode.cache.query.IndexNameConflictException)5 NameResolutionException (org.apache.geode.cache.query.NameResolutionException)5 TypeMismatchException (org.apache.geode.cache.query.TypeMismatchException)5 List (java.util.List)4 AmbiguousNameException (org.apache.geode.cache.query.AmbiguousNameException)4 ExecutionException (java.util.concurrent.ExecutionException)3 FutureTask (java.util.concurrent.FutureTask)3 Index (org.apache.geode.cache.query.Index)3 CompiledBindArgument (org.apache.geode.cache.query.internal.CompiledBindArgument)3 CompiledIteratorDef (org.apache.geode.cache.query.internal.CompiledIteratorDef)3 CompiledValue (org.apache.geode.cache.query.internal.CompiledValue)3 ArrayList (java.util.ArrayList)2 MultiIndexCreationException (org.apache.geode.cache.query.MultiIndexCreationException)2 QueryException (org.apache.geode.cache.query.QueryException)2 QueryService (org.apache.geode.cache.query.QueryService)2 RegionNotFoundException (org.apache.geode.cache.query.RegionNotFoundException)2 CompiledIndexOperation (org.apache.geode.cache.query.internal.CompiledIndexOperation)2 CompiledOperation (org.apache.geode.cache.query.internal.CompiledOperation)2