Search in sources :

Example 1 with PdxInstance

use of org.apache.geode.pdx.PdxInstance in project geode by apache.

the class CompiledSelect method applyProjectionAndAddToResultSet.

// resultSet could be a set or a bag (we have set constructor, or there
// could be a distinct subquery)
// in future, it would be good to simplify this to always work with a bag
// (converting all sets to bags) until the end when we enforce distinct
// The number returned indicates the occurence of the data in the SelectResults
// Thus if the SelectResults is of type ResultsSet or StructSet
// then 1 will indicate that data was added to the results & that was the
// first occurence. For this 0 will indicate that the data was not added
// because it was a duplicate
// If the SelectResults is an instance ResultsBag or StructsBag , the number will
// indicate the occurence. Thus 1 will indicate it being added for first time
// Currently orderBy is present only for StructSet & ResultSet which are
// unique object holders. So the occurence for them can be either 0 or 1 only
private int applyProjectionAndAddToResultSet(ExecutionContext context, SelectResults resultSet, boolean ignoreOrderBy) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    List currrentRuntimeIters = context.getCurrentIterators();
    int occurence = 0;
    ObjectType elementType = resultSet.getCollectionType().getElementType();
    boolean isStruct = elementType != null && elementType.isStructType();
    // TODO: Optimize this condition in some clean way
    boolean isLinkedStructure = resultSet instanceof Ordered && ((Ordered) resultSet).dataPreordered();
    ArrayList evaluatedOrderByClause = null;
    OrderByComparator comparator = null;
    boolean applyOrderBy = false;
    if (this.orderByAttrs != null && !ignoreOrderBy) {
        // In case PR order-by will get applied on the coordinator node
        // on the cumulative results. Apply the order-by on PR only if
        // limit is specified.
        Integer limitValue = evaluateLimitValue(context, this.limit);
        if (context.getPartitionedRegion() != null && limitValue < 0) {
            applyOrderBy = false;
        }
        applyOrderBy = true;
    }
    if (this.orderByAttrs != null && !ignoreOrderBy) {
        comparator = (OrderByComparator) ((Ordered) resultSet).comparator();
    }
    if (projAttrs == null) {
        int len = currrentRuntimeIters.size();
        Object[] values = new Object[len];
        for (int i = 0; i < len; i++) {
            RuntimeIterator iter = (RuntimeIterator) currrentRuntimeIters.get(i);
            values[i] = iter.evaluate(context);
            // case of all Pdx objects in cache
            if (this.distinct && !((DefaultQuery) context.getQuery()).isRemoteQuery() && !context.getCache().getPdxReadSerialized() && (values[i] instanceof PdxInstance)) {
                values[i] = ((PdxInstance) values[i]).getObject();
            }
        }
        // Don't care about Order By for count(*).
        if (isCount() && !this.distinct) {
            // Counter is local to CompileSelect and not available in ResultSet
            // until
            // the end of evaluate call to this CompiledSelect object.
            this.countStartQueryResult++;
            occurence = 1;
        } else {
            // if order by is present
            if (applyOrderBy) {
                StructImpl structImpl;
                if (this.distinct) {
                    if (isStruct) {
                        if (values.length == 1 && values[0] instanceof StructImpl) {
                            structImpl = (StructImpl) values[0];
                            comparator.addEvaluatedSortCriteria(structImpl.getFieldValues(), context);
                            occurence = resultSet.add(structImpl) ? 1 : 0;
                        } else {
                            comparator.addEvaluatedSortCriteria(values, context);
                            occurence = ((StructFields) resultSet).addFieldValues(values) ? 1 : 0;
                        }
                    // TODO:Instead of a normal Map containing which holds
                    // StructImpl object
                    // use a THashObject with Object[] array hashing stragtegy as we
                    // are unnnecessarily
                    // creating objects of type Object[]
                    } else {
                        comparator.addEvaluatedSortCriteria(values[0], context);
                        occurence = resultSet.add(values[0]) ? 1 : 0;
                    }
                } else {
                    if (isStruct) {
                        if (values.length == 1 && values[0] instanceof StructImpl) {
                            structImpl = (StructImpl) values[0];
                            comparator.addEvaluatedSortCriteria(structImpl.getFieldValues(), context);
                            occurence = ((Bag) resultSet).addAndGetOccurence(structImpl.getFieldValues());
                        } else {
                            comparator.addEvaluatedSortCriteria(values, context);
                            occurence = ((Bag) resultSet).addAndGetOccurence(values);
                        }
                    } else {
                        comparator.addEvaluatedSortCriteria(values[0], context);
                        occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                    }
                }
            } else {
                if (isLinkedStructure) {
                    if (isStruct) {
                        StructImpl structImpl;
                        if (values.length == 1 && values[0] instanceof StructImpl) {
                            structImpl = (StructImpl) values[0];
                        } else {
                            structImpl = new StructImpl((StructTypeImpl) elementType, values);
                        }
                        if (this.distinct) {
                            occurence = resultSet.add(structImpl) ? 1 : 0;
                        } else {
                            occurence = ((Bag) resultSet).addAndGetOccurence(structImpl);
                        }
                    } else {
                        if (this.distinct) {
                            occurence = resultSet.add(values[0]) ? 1 : 0;
                        } else {
                            occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                        }
                    }
                } else {
                    if (this.distinct) {
                        if (isStruct) {
                            occurence = ((StructFields) resultSet).addFieldValues(values) ? 1 : 0;
                        } else {
                            occurence = resultSet.add(values[0]) ? 1 : 0;
                        }
                    } else {
                        if (isStruct) {
                            occurence = ((Bag) resultSet).addAndGetOccurence(values);
                        } else {
                            boolean add = true;
                            if (context.isCqQueryContext()) {
                                if (values[0] instanceof Region.Entry) {
                                    Region.Entry e = (Region.Entry) values[0];
                                    if (!e.isDestroyed()) {
                                        try {
                                            values[0] = new CqEntry(e.getKey(), e.getValue());
                                        } catch (EntryDestroyedException ignore) {
                                            // Even though isDestory() check is made, the entry could throw
                                            // EntryDestroyedException if the value becomes null.
                                            add = false;
                                        }
                                    } else {
                                        add = false;
                                    }
                                }
                            }
                            if (add) {
                                occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                            }
                        }
                    }
                }
            }
        }
    } else {
        // One or more projection attributes
        int projCount = projAttrs.size();
        Object[] values = new Object[projCount];
        for (int i = 0; i < projCount; i++) {
            Object[] projDef = (Object[]) projAttrs.get(i);
            values[i] = ((CompiledValue) projDef[1]).evaluate(context);
            // for remote queries
            if (!((DefaultQuery) context.getQuery()).isRemoteQuery()) {
                if (this.distinct && values[i] instanceof PdxInstance && !context.getCache().getPdxReadSerialized()) {
                    values[i] = ((PdxInstance) values[i]).getObject();
                } else if (values[i] instanceof PdxString) {
                    values[i] = ((PdxString) values[i]).toString();
                }
            }
        }
        // if order by is present
        if (applyOrderBy) {
            if (distinct) {
                if (isStruct) {
                    comparator.addEvaluatedSortCriteria(values, context);
                    // Occurence field is used to identify the corrcet number of
                    // iterations
                    // required to implement the limit based on the presence or absence
                    // of distinct clause
                    occurence = ((StructFields) resultSet).addFieldValues(values) ? 1 : 0;
                } else {
                    comparator.addEvaluatedSortCriteria(values[0], context);
                    occurence = resultSet.add(values[0]) ? 1 : 0;
                }
            } else {
                if (isStruct) {
                    comparator.addEvaluatedSortCriteria(values, context);
                    occurence = ((Bag) resultSet).addAndGetOccurence(values);
                } else {
                    comparator.addEvaluatedSortCriteria(values[0], context);
                    occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                }
            }
        } else {
            if (isLinkedStructure) {
                if (isStruct) {
                    StructImpl structImpl = new StructImpl((StructTypeImpl) elementType, values);
                    if (this.distinct) {
                        occurence = resultSet.add(structImpl) ? 1 : 0;
                    } else {
                        occurence = ((Bag) resultSet).addAndGetOccurence(structImpl);
                    }
                } else {
                    if (this.distinct) {
                        occurence = resultSet.add(values[0]) ? 1 : 0;
                    } else {
                        occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                    }
                }
            } else {
                if (this.distinct) {
                    if (isStruct) {
                        occurence = ((StructFields) resultSet).addFieldValues(values) ? 1 : 0;
                    } else {
                        occurence = resultSet.add(values[0]) ? 1 : 0;
                    }
                } else {
                    if (isStruct) {
                        occurence = ((Bag) resultSet).addAndGetOccurence(values);
                    } else {
                        occurence = ((Bag) resultSet).addAndGetOccurence(values[0]);
                    }
                }
            }
        }
    }
    return occurence;
}
Also used : EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) ArrayList(java.util.ArrayList) PdxString(org.apache.geode.pdx.internal.PdxString) ObjectType(org.apache.geode.cache.query.types.ObjectType) PdxInstance(org.apache.geode.pdx.PdxInstance) StructTypeImpl(org.apache.geode.cache.query.internal.types.StructTypeImpl) Region(org.apache.geode.cache.Region) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with PdxInstance

use of org.apache.geode.pdx.PdxInstance in project geode by apache.

the class CompiledComparison method evaluate.

public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    Object left = _left.evaluate(context);
    Object right = _right.evaluate(context);
    if (context.isCqQueryContext() && left instanceof Region.Entry) {
        left = ((Region.Entry) left).getValue();
    }
    if (context.isCqQueryContext() && right instanceof Region.Entry) {
        right = ((Region.Entry) right).getValue();
    }
    if (left == null || right == null) {
        return TypeUtils.compare(left, right, _operator);
    }
    // only if it is of the same class as that of the object being compared
    if (!context.getCache().getPdxReadSerialized()) {
        if (left instanceof PdxInstance && !(right instanceof PdxInstance) && ((PdxInstance) left).getClassName().equals(right.getClass().getName())) {
            left = ((PdxInstance) left).getObject();
        } else if (right instanceof PdxInstance && !(left instanceof PdxInstance) && ((PdxInstance) right).getClassName().equals(left.getClass().getName())) {
            right = ((PdxInstance) right).getObject();
        }
    }
    if (left instanceof PdxString) {
        if (right instanceof String) {
            switch(_right.getType()) {
                case LITERAL:
                    right = ((CompiledLiteral) _right).getSavedPdxString();
                    break;
                case QUERY_PARAM:
                    right = ((CompiledBindArgument) _right).getSavedPdxString(context);
                    break;
                case FUNCTION:
                case PATH:
                    right = new PdxString((String) right);
            }
        }
    } else if (right instanceof PdxString) {
        switch(_left.getType()) {
            case LITERAL:
                left = ((CompiledLiteral) _left).getSavedPdxString();
                break;
            case QUERY_PARAM:
                left = ((CompiledBindArgument) _left).getSavedPdxString(context);
                break;
            case FUNCTION:
            case PATH:
                left = new PdxString((String) left);
        }
    }
    return TypeUtils.compare(left, right, _operator);
}
Also used : PdxInstance(org.apache.geode.pdx.PdxInstance) Region(org.apache.geode.cache.Region) PdxString(org.apache.geode.pdx.internal.PdxString) PdxString(org.apache.geode.pdx.internal.PdxString)

Example 3 with PdxInstance

use of org.apache.geode.pdx.PdxInstance in project geode by apache.

the class PDXUtils method convertPDX.

public static Object convertPDX(Object obj, boolean isStruct, boolean getDomainObjectForPdx, boolean getDeserializedObject, boolean localResults, boolean[] objectChangedMarker, boolean isDistinct) {
    objectChangedMarker[0] = false;
    if (isStruct) {
        StructImpl simpl = (StructImpl) obj;
        if (getDomainObjectForPdx) {
            try {
                if (simpl.isHasPdx()) {
                    obj = simpl.getPdxFieldValues();
                    objectChangedMarker[0] = true;
                } else {
                    obj = simpl.getFieldValues();
                }
            } catch (Exception ex) {
                throw new CacheException("Unable to retrieve domain object from PdxInstance while building the ResultSet. " + ex.getMessage()) {
                };
            }
        } else {
            Object[] values = simpl.getFieldValues();
            if (getDeserializedObject) {
                for (int i = 0; i < values.length; i++) {
                    if (values[i] instanceof VMCachedDeserializable) {
                        values[i] = ((VMCachedDeserializable) values[i]).getDeserializedForReading();
                    }
                }
            }
            /* This is to convert PdxString to String */
            if (simpl.isHasPdx() && isDistinct && localResults) {
                for (int i = 0; i < values.length; i++) {
                    if (values[i] instanceof PdxString) {
                        values[i] = ((PdxString) values[i]).toString();
                    }
                }
            }
            obj = values;
        }
    } else {
        if (getDomainObjectForPdx) {
            if (obj instanceof PdxInstance) {
                try {
                    obj = ((PdxInstance) obj).getObject();
                    objectChangedMarker[0] = true;
                } catch (Exception ex) {
                    throw new CacheException("Unable to retrieve domain object from PdxInstance while building the ResultSet. " + ex.getMessage()) {
                    };
                }
            } else if (obj instanceof PdxString) {
                obj = ((PdxString) obj).toString();
            }
        } else if (isDistinct && localResults && obj instanceof PdxString) {
            /* This is to convert PdxString to String */
            obj = ((PdxString) obj).toString();
        }
        if (getDeserializedObject && obj instanceof VMCachedDeserializable) {
            obj = ((VMCachedDeserializable) obj).getDeserializedForReading();
            objectChangedMarker[0] = true;
        }
    }
    return obj;
}
Also used : StructImpl(org.apache.geode.cache.query.internal.StructImpl) PdxInstance(org.apache.geode.pdx.PdxInstance) CacheException(org.apache.geode.cache.CacheException) PdxString(org.apache.geode.pdx.internal.PdxString) VMCachedDeserializable(org.apache.geode.internal.cache.VMCachedDeserializable) CacheException(org.apache.geode.cache.CacheException)

Example 4 with PdxInstance

use of org.apache.geode.pdx.PdxInstance in project geode by apache.

the class RestInterfaceJUnitTest method testRegionObjectWithDatePropertyAccessedWithRestApi.

@Test
public void testRegionObjectWithDatePropertyAccessedWithRestApi() throws Exception {
    String key = "1";
    Person jonDoe = createPerson("Jon", "Doe", createDate(1977, Calendar.OCTOBER, 31));
    assertTrue(getPeopleRegion().isEmpty());
    getPeopleRegion().put(key, jonDoe);
    assertFalse(getPeopleRegion().isEmpty());
    assertEquals(1, getPeopleRegion().size());
    assertTrue(getPeopleRegion().containsKey(key));
    Object jonDoeRef = getPeopleRegion().get(key);
    assertTrue(jonDoeRef instanceof PdxInstance);
    assertEquals(jonDoe.getClass().getName(), ((PdxInstance) jonDoeRef).getClassName());
    assertEquals(jonDoe.getFirstName(), ((PdxInstance) jonDoeRef).getField("firstName"));
    assertEquals(jonDoe.getLastName(), ((PdxInstance) jonDoeRef).getField("lastName"));
    assertEquals(jonDoe.getBirthDate(), ((PdxInstance) jonDoeRef).getField("birthDate"));
    RestTemplate restTemplate = createRestTemplate();
    Person jonDoeResource = restTemplate.getForObject(getRegionGetRestApiEndpoint(getPeopleRegion(), key), Person.class);
    assertNotNull(jonDoeResource);
    assertNotSame(jonDoe, jonDoeResource);
    assertEquals(jonDoe, jonDoeResource);
    /*
     * Object result = runQueryUsingApi(getPeopleRegion().getRegionService(),
     * String.format("SELECT * FROM %1$s", getPeopleRegion().getFullPath()));
     * 
     * System.out.printf("(OQL Query using API) Person is (%1$s)%n", result);
     */
    String url = getAdhocQueryRestApiEndpoint(String.format("SELECT * FROM %1$s", getPeopleRegion().getFullPath()));
    System.out.printf("URL (%1$s)%n", url);
    List<?> queryResults = restTemplate.getForObject(url, List.class);
    assertNotNull(queryResults);
    assertFalse(queryResults.isEmpty());
    assertEquals(1, queryResults.size());
    jonDoeResource = objectMapper.convertValue(queryResults.get(0), Person.class);
    assertNotNull(jonDoeResource);
    assertNotSame(jonDoe, jonDoeResource);
    assertEquals(jonDoe, jonDoeResource);
}
Also used : PdxInstance(org.apache.geode.pdx.PdxInstance) RestTemplate(org.springframework.web.client.RestTemplate) RestAPITest(org.apache.geode.test.junit.categories.RestAPITest) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 5 with PdxInstance

use of org.apache.geode.pdx.PdxInstance 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)

Aggregations

PdxInstance (org.apache.geode.pdx.PdxInstance)63 Test (org.junit.Test)33 Region (org.apache.geode.cache.Region)25 PdxInstanceFactory (org.apache.geode.pdx.PdxInstanceFactory)22 SelectResults (org.apache.geode.cache.query.SelectResults)18 Host (org.apache.geode.test.dunit.Host)18 VM (org.apache.geode.test.dunit.VM)18 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)18 QueryService (org.apache.geode.cache.query.QueryService)16 CacheException (org.apache.geode.cache.CacheException)14 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)13 ClientCache (org.apache.geode.cache.client.ClientCache)11 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)11 ClientCacheFactory (org.apache.geode.cache.client.ClientCacheFactory)10 GemFireCacheImpl (org.apache.geode.internal.cache.GemFireCacheImpl)10 PdxString (org.apache.geode.pdx.internal.PdxString)10 CacheServer (org.apache.geode.cache.server.CacheServer)8 Query (org.apache.geode.cache.query.Query)7 Collection (java.util.Collection)6 Struct (org.apache.geode.cache.query.Struct)6