use of org.apache.geode.cache.query.TypeMismatchException 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.TypeMismatchException in project geode by apache.
the class PartitionedRegion method doExecuteQuery.
/**
* If ForceReattemptException is thrown then the caller must loop and call us again.
*
* @throws ForceReattemptException if one of the buckets moved out from under us
*/
private Object doExecuteQuery(DefaultQuery query, Object[] parameters, Set buckets) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException, ForceReattemptException {
if (logger.isDebugEnabled()) {
logger.debug("Executing query :{}", query);
}
HashSet<Integer> allBuckets = new HashSet<Integer>();
if (buckets == null) {
// remote buckets
final Iterator remoteIter = getRegionAdvisor().getBucketSet().iterator();
try {
while (remoteIter.hasNext()) {
allBuckets.add((Integer) remoteIter.next());
}
} catch (NoSuchElementException ignore) {
}
} else {
// local buckets
Iterator localIter = null;
if (this.dataStore != null) {
localIter = buckets.iterator();
} else {
localIter = Collections.emptySet().iterator();
}
try {
while (localIter.hasNext()) {
allBuckets.add((Integer) localIter.next());
}
} catch (NoSuchElementException ignore) {
}
}
if (allBuckets.size() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("No bucket storage allocated. PR has no data yet.");
}
ResultsSet resSet = new ResultsSet();
resSet.setElementType(new ObjectTypeImpl(this.getValueConstraint() == null ? Object.class : this.getValueConstraint()));
return resSet;
}
CompiledSelect selectExpr = query.getSimpleSelect();
if (selectExpr == null) {
throw new IllegalArgumentException(LocalizedStrings.PartitionedRegion_QUERY_MUST_BE_A_SELECT_EXPRESSION_ONLY.toLocalizedString());
}
// this can return a BAG even if it's a DISTINCT select expression,
// since the expectation is that the duplicates will be removed at the end
SelectResults results = selectExpr.getEmptyResultSet(parameters, getCache(), query);
PartitionedRegionQueryEvaluator prqe = new PartitionedRegionQueryEvaluator(this.getSystem(), this, query, parameters, results, allBuckets);
for (; ; ) {
this.getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
results = prqe.queryBuckets(null);
break;
} catch (InterruptedException ignore) {
interrupted = true;
} catch (FunctionDomainException e) {
throw e;
} catch (TypeMismatchException e) {
throw e;
} catch (NameResolutionException e) {
throw e;
} catch (QueryInvocationTargetException e) {
throw e;
} catch (QueryException qe) {
throw new QueryInvocationTargetException(LocalizedStrings.PartitionedRegion_UNEXPECTED_QUERY_EXCEPTION_OCCURRED_DURING_QUERY_EXECUTION_0.toLocalizedString(qe.getMessage()), qe);
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
// for
// Drop Duplicates if this is a DISTINCT query
boolean allowsDuplicates = results.getCollectionType().allowsDuplicates();
// be exactly matching the limit
if (selectExpr.isDistinct()) {
// don't just convert to a ResultsSet (or StructSet), since
// the bags can convert themselves to a Set more efficiently
ObjectType elementType = results.getCollectionType().getElementType();
if (selectExpr.getOrderByAttrs() != null) {
// Set limit also, its not applied while building the final result set as order by is
// involved.
} else if (allowsDuplicates) {
results = new ResultsCollectionWrapper(elementType, results.asSet());
}
if (selectExpr.isCount() && (results.isEmpty() || selectExpr.isDistinct())) {
// Constructor with elementType not visible.
SelectResults resultCount = new ResultsBag(getCachePerfStats());
resultCount.setElementType(new ObjectTypeImpl(Integer.class));
((Bag) resultCount).addAndGetOccurence(results.size());
return resultCount;
}
}
return results;
}
use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.
the class RangeIndex method addSavedMappings.
public void addSavedMappings(RegionEntry entry) throws IMQException {
List nullSet = nullEntries.get();
List undefinedSet = undefinedEntries.get();
Map keysMap = keysToHashSetMap.get();
// Add nullEntries
if (nullSet != null && nullSet.size() > 0) {
this.internalIndexStats.incNumValues(-this.nullMappedEntries.getNumValues(entry) + nullSet.size());
this.nullMappedEntries.replace(entry, (nullSet.size() > 1) ? nullSet : nullSet.iterator().next());
} else {
this.internalIndexStats.incNumValues(-this.nullMappedEntries.getNumValues(entry));
this.nullMappedEntries.remove(entry);
}
// Add undefined entries
if (undefinedSet != null && undefinedSet.size() > 0) {
this.internalIndexStats.incNumValues(-this.undefinedMappedEntries.getNumValues(entry) + undefinedSet.size());
this.undefinedMappedEntries.replace(entry, (undefinedSet.size() > 1) ? undefinedSet : undefinedSet.iterator().next());
} else {
this.internalIndexStats.incNumValues(-this.undefinedMappedEntries.getNumValues(entry));
this.undefinedMappedEntries.remove(entry);
}
// Get existing keys from reverse map and remove new keys
// from this list and remove index entries for these old keys.
Object oldkeys = this.entryToValuesMap.remove(entry);
if (keysMap != null) {
Set keys = keysMap.keySet();
try {
if (oldkeys != null) {
if (oldkeys instanceof Collection) {
for (Object key : keys) {
((Collection) oldkeys).remove(TypeUtils.indexKeyFor(key));
}
} else {
for (Object key : keys) {
if (TypeUtils.indexKeyFor(key).equals(oldkeys)) {
oldkeys = null;
}
}
}
}
} catch (Exception ex) {
throw new IMQException(LocalizedStrings.RangeIndex_COULD_NOT_ADD_OBJECT_OF_TYPE_0.toLocalizedString(oldkeys.getClass().getName()), ex);
}
// Perform replace of new index entries in index.
if (keys.size() == 1) {
Object key = keys.iterator().next();
try {
Object newKey = TypeUtils.indexKeyFor(key);
boolean retry = false;
do {
retry = false;
RegionEntryToValuesMap rvMap = (RegionEntryToValuesMap) this.valueToEntriesMap.get(newKey);
if (rvMap == null) {
rvMap = new RegionEntryToValuesMap(true);
Object oldValue = this.valueToEntriesMap.putIfAbsent(newKey, rvMap);
if (oldValue != null) {
retry = true;
continue;
} else {
this.internalIndexStats.incNumKeys(1);
// TODO: non-atomic operation on volatile int
++valueToEntriesMapSize;
}
}
// and only remove it if current rvMap size is zero.
if (!retry) {
synchronized (rvMap) {
// If remove thread got the lock on rvMap first then we must retry.
if (rvMap != this.valueToEntriesMap.get(newKey)) {
retry = true;
} else {
// We got lock first so remove will wait and check the size of rvMap again
// before removing it.
Object newValues = keysMap.get(key);
Object oldValues = rvMap.get(entry);
rvMap.replace(entry, newValues);
// Update reverserMap (entry => values)
this.entryToValuesMap.add(entry, newKey);
// Calculate the difference in size.
int diff = calculateSizeDiff(oldValues, newValues);
this.internalIndexStats.incNumValues(diff);
}
}
}
} while (retry);
} catch (TypeMismatchException ex) {
throw new IMQException(LocalizedStrings.RangeIndex_COULD_NOT_ADD_OBJECT_OF_TYPE_0.toLocalizedString(key.getClass().getName()), ex);
}
} else {
for (Object key : keys) {
try {
Object newKey = TypeUtils.indexKeyFor(key);
boolean retry = false;
// Going in a retry loop until concurrent index update is successful.
do {
retry = false;
RegionEntryToValuesMap rvMap = (RegionEntryToValuesMap) this.valueToEntriesMap.get(newKey);
if (rvMap == null) {
rvMap = new RegionEntryToValuesMap(true);
Object oldValue = this.valueToEntriesMap.putIfAbsent(newKey, rvMap);
if (oldValue != null) {
retry = true;
continue;
} else {
this.internalIndexStats.incNumKeys(1);
// TODO: non-atomic operation on volatile int
++valueToEntriesMapSize;
}
}
// lock on it and only remove it if current rvMap size is zero.
if (!retry) {
synchronized (rvMap) {
// If remove thread got the lock on rvMap first then we must retry.
if (rvMap != this.valueToEntriesMap.get(newKey)) {
retry = true;
} else {
// We got lock first so remove will wait and check the size of
// rvMap again before removing it.
Object newValues = keysMap.get(key);
Object oldValues = rvMap.get(entry);
rvMap.replace(entry, newValues);
// Update reverserMap (entry => values)
this.entryToValuesMap.add(entry, newKey);
// Calculate the difference in size.
int diff = calculateSizeDiff(oldValues, newValues);
this.internalIndexStats.incNumValues(diff);
}
}
}
} while (retry);
} catch (TypeMismatchException ex) {
throw new IMQException(LocalizedStrings.RangeIndex_COULD_NOT_ADD_OBJECT_OF_TYPE_0.toLocalizedString(key.getClass().getName()), ex);
}
}
// for loop for keys
}
}
// Remove the remaining old keys.
if (oldkeys != null) {
removeOldMapping(entry, oldkeys);
}
}
use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.
the class CompiledIteratorDef method getRuntimeIterator.
public RuntimeIterator getRuntimeIterator(ExecutionContext context) throws TypeMismatchException, AmbiguousNameException, NameResolutionException {
RuntimeIterator rIter = null;
// check cached in context
rIter = (RuntimeIterator) context.cacheGet(this);
if (rIter != null) {
return rIter;
}
ObjectType type = this.elementType;
if (type.equals(TypeUtils.OBJECT_TYPE)) {
// check to see if there's a typecast for this collection
ObjectType typc = getCollectionElementTypeCast();
if (typc != null) {
type = typc;
} else {
// Does not determine type of nested query
if (!(this.collectionExpr instanceof CompiledSelect)) {
type = computeElementType(context);
}
}
}
rIter = new RuntimeIterator(this, type);
// generate from clause should take care of bucket region substitution if
// necessary and then set the definition.
String fromClause = genFromClause(context);
rIter.setDefinition(fromClause);
/*
* If the type of RunTimeIterator is still ObjectType & if the RuneTimeIterator is independent
* of any iterator of the scopes less than or equal to its own scope, we can evaluate the
* collection via RuntimeIterator. This will initialize the Collection of RuntimeIterator ,
* which is OK. The code in RuntimeIterator will be rectified such that the ElementType of that
* RuntimeIterator is taken from the collection
*/
if (type.equals(TypeUtils.OBJECT_TYPE) && !this.isDependentOnAnyIteratorOfScopeLessThanItsOwn(context)) {
// the collection
try {
rIter.evaluateCollection(context);
} catch (QueryExecutionTimeoutException qet) {
throw qet;
} catch (RegionNotFoundException re) {
throw re;
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Exception while getting runtime iterator.", e);
}
throw new TypeMismatchException(LocalizedStrings.CompiledIteratorDef_EXCEPTION_IN_EVALUATING_THE_COLLECTION_EXPRESSION_IN_GETRUNTIMEITERATOR_EVEN_THOUGH_THE_COLLECTION_IS_INDEPENDENT_OF_ANY_RUNTIMEITERATOR.toLocalizedString(), e);
}
}
// cache in context
context.cachePut(this, rIter);
return rIter;
}
use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.
the class CompiledJunction method auxIterateEvaluate.
/** invariant: the operand is known to be evaluated by iteration */
SelectResults auxIterateEvaluate(CompiledValue operand, ExecutionContext context, SelectResults intermediateResults) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
// signifies that the junction cannot be evaluated as a filter.
if (intermediateResults == null)
throw new RuntimeException(LocalizedStrings.CompiledJunction_INTERMEDIATERESULTS_CAN_NOT_BE_NULL.toLocalizedString());
if (// short circuit
intermediateResults.isEmpty())
return intermediateResults;
List currentIters = context.getCurrentIterators();
RuntimeIterator[] rIters = new RuntimeIterator[currentIters.size()];
currentIters.toArray(rIters);
ObjectType elementType = intermediateResults.getCollectionType().getElementType();
SelectResults resultSet;
if (elementType.isStructType()) {
resultSet = QueryUtils.createStructCollection(context, (StructTypeImpl) elementType);
} else {
resultSet = QueryUtils.createResultCollection(context, elementType);
}
QueryObserver observer = QueryObserverHolder.getInstance();
try {
observer.startIteration(intermediateResults, operand);
Iterator iResultsIter = intermediateResults.iterator();
while (iResultsIter.hasNext()) {
Object tuple = iResultsIter.next();
if (tuple instanceof Struct) {
Object[] values = ((Struct) tuple).getFieldValues();
for (int i = 0; i < values.length; i++) {
rIters[i].setCurrent(values[i]);
}
} else {
rIters[0].setCurrent(tuple);
}
Object result = null;
try {
result = operand.evaluate(context);
} finally {
observer.afterIterationEvaluation(result);
}
if (result instanceof Boolean) {
if (((Boolean) result).booleanValue())
resultSet.add(tuple);
} else if (result != null && result != QueryService.UNDEFINED)
throw new TypeMismatchException(LocalizedStrings.CompiledJunction_ANDOR_OPERANDS_MUST_BE_OF_TYPE_BOOLEAN_NOT_TYPE_0.toLocalizedString(result.getClass().getName()));
}
} finally {
observer.endIteration(resultSet);
}
return resultSet;
}
Aggregations