Search in sources :

Example 6 with StructImpl

use of org.apache.geode.cache.query.internal.StructImpl in project geode by apache.

the class DataCommandFunction method select_SelectResults.

private void select_SelectResults(SelectResults selectResults, Object principal, List<SelectResultRow> list, AtomicInteger nestedObjectCount) throws GfJsonException {
    for (Object object : selectResults) {
        // Post processing
        object = securityService.postProcess(principal, null, null, object, false);
        if (object instanceof Struct) {
            StructImpl impl = (StructImpl) object;
            GfJsonObject jsonStruct = getJSONForStruct(impl, nestedObjectCount);
            if (logger.isDebugEnabled()) {
                logger.debug("SelectResults : Adding select json string : {}", jsonStruct);
            }
            list.add(new SelectResultRow(DataCommandResult.ROW_TYPE_STRUCT_RESULT, jsonStruct.toString()));
        } else if (JsonUtil.isPrimitiveOrWrapper(object.getClass())) {
            if (logger.isDebugEnabled()) {
                logger.debug("SelectResults : Adding select primitive : {}", object);
            }
            list.add(new SelectResultRow(DataCommandResult.ROW_TYPE_PRIMITIVE, object));
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("SelectResults : Bean Results class is {}", object.getClass());
            }
            String str = toJson(object);
            GfJsonObject jsonBean;
            try {
                jsonBean = new GfJsonObject(str);
            } catch (GfJsonException e) {
                logger.error(e.getMessage(), e);
                jsonBean = new GfJsonObject();
                try {
                    jsonBean.put("msg", e.getMessage());
                } catch (GfJsonException e1) {
                    logger.warn("Ignored GfJsonException:", e1);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("SelectResults : Adding bean json string : {}", jsonBean);
            }
            list.add(new SelectResultRow(DataCommandResult.ROW_TYPE_BEAN, jsonBean.toString()));
        }
    }
}
Also used : StructImpl(org.apache.geode.cache.query.internal.StructImpl) GfJsonObject(org.apache.geode.management.internal.cli.json.GfJsonObject) SelectResultRow(org.apache.geode.management.internal.cli.domain.DataCommandResult.SelectResultRow) GfJsonException(org.apache.geode.management.internal.cli.json.GfJsonException) GfJsonObject(org.apache.geode.management.internal.cli.json.GfJsonObject) Struct(org.apache.geode.cache.query.Struct)

Example 7 with StructImpl

use of org.apache.geode.cache.query.internal.StructImpl in project geode by apache.

the class SelectStarQueryDUnitTest method testSelectStarQueryForPdxObjects.

@Test
public void testSelectStarQueryForPdxObjects() throws Exception {
    final Host host = Host.getHost(0);
    final VM server1 = host.getVM(0);
    final VM client = host.getVM(3);
    // create servers and regions
    final int port1 = startReplicatedCacheServer(server1);
    server1.invoke(new SerializableCallable("Set observer") {

        @Override
        public Object call() throws Exception {
            oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
            return null;
        }
    });
    // create client
    client.invoke(new SerializableCallable("Create client") {

        @Override
        public Object call() throws Exception {
            ClientCacheFactory cf = new ClientCacheFactory();
            cf.addPoolServer(getServerHostName(server1.getHost()), port1);
            ClientCache cache = getClientCache(cf);
            cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
            return null;
        }
    });
    // Update with serialized PortfolioPdx objects
    client.invoke(new SerializableCallable("Put objects") {

        @Override
        public Object call() throws Exception {
            Region r1 = getRootRegion(regName);
            for (int i = 0; i < 20; i++) {
                r1.put("key-" + i, new PortfolioPdx(i));
            }
            return null;
        }
    });
    // query remotely from client
    client.invoke(new SerializableCallable("Query") {

        @Override
        public Object call() throws Exception {
            getLogWriter().info("Querying remotely from client");
            QueryService localQS = null;
            QueryService remoteQS = null;
            try {
                localQS = ((ClientCache) getCache()).getLocalQueryService();
                remoteQS = ((ClientCache) getCache()).getQueryService();
            } catch (Exception e) {
                fail("Exception getting query service ", e);
            }
            SelectResults res = null;
            SelectResults[][] sr = new SelectResults[1][2];
            for (int i = 0; i < queries.length; i++) {
                try {
                    res = (SelectResults) localQS.newQuery(queries[i]).execute();
                    sr[0][0] = res;
                    res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
                    sr[0][1] = res;
                    CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
                } catch (Exception e) {
                    fail("Error executing query: " + queries[i], e);
                }
                assertEquals(resultSize[i], res.size());
                if (i == 3) {
                    int cnt = ((Integer) res.iterator().next());
                    assertEquals(20, cnt);
                } else {
                    for (Object rs : res) {
                        if (rs instanceof StructImpl) {
                            for (Object obj : ((StructImpl) rs).getFieldValues()) {
                                if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
                                } else {
                                    fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + obj.getClass());
                                }
                            }
                        } else if (rs instanceof PortfolioPdx) {
                        } else {
                            fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + rs.getClass());
                        }
                    }
                }
            }
            return null;
        }
    });
    // verify if objects iterated by query are serialized
    server1.invoke(new SerializableCallable("Get observer") {

        @Override
        public Object call() throws Exception {
            QueryObserver observer = QueryObserverHolder.getInstance();
            assertTrue(QueryObserverHolder.hasObserver());
            assertTrue(observer instanceof QueryResultTrackingObserver);
            QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
            assertTrue(resultObserver.isObjectSerialized());
            return null;
        }
    });
    // verify if objects returned by local server query are not serialized
    server1.invoke(new SerializableCallable("Query") {

        @Override
        public Object call() throws Exception {
            QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
            QueryService qs = null;
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                fail("Exception getting query service ", e);
            }
            SelectResults res = null;
            for (int i = 0; i < queries.length; i++) {
                try {
                    res = (SelectResults) qs.newQuery(queries[i]).execute();
                } catch (Exception e) {
                    fail("Error executing query: " + queries[i], e);
                }
                assertEquals(resultSize[i], res.size());
                if (i == 3) {
                    int cnt = ((Integer) res.iterator().next());
                    assertEquals(20, cnt);
                } else {
                    for (Object rs : res) {
                        if (rs instanceof StructImpl) {
                            for (Object obj : ((StructImpl) rs).getFieldValues()) {
                                if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
                                } else {
                                    fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + obj.getClass());
                                }
                            }
                        } else if (rs instanceof PortfolioPdx) {
                        } else {
                            fail("Result objects for remote client query: " + queries[i] + " should be instance of PortfolioPdx and not " + rs.getClass());
                        }
                    }
                }
            }
            observer = QueryObserverHolder.getInstance();
            assertTrue(QueryObserverHolder.hasObserver());
            assertTrue(observer instanceof QueryResultTrackingObserver);
            QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
            assertFalse(resultObserver.isObjectSerialized());
            QueryObserverHolder.setInstance(oldObserver);
            return null;
        }
    });
    // verify if Pdx instances are returned by local server query
    // if read-serialized is set true
    server1.invoke(new SerializableCallable("Query") {

        @Override
        public Object call() throws Exception {
            GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
            cache.setReadSerialized(true);
            QueryService qs = null;
            try {
                qs = getCache().getQueryService();
            } catch (Exception e) {
                fail("Exception getting query service ", e);
            }
            SelectResults res = null;
            for (int i = 0; i < queries.length; i++) {
                try {
                    res = (SelectResults) qs.newQuery(queries[i]).execute();
                } catch (Exception e) {
                    fail("Error executing query: " + queries[i], e);
                }
                assertEquals(resultSize[i], res.size());
                if (i == 3) {
                    int cnt = ((Integer) res.iterator().next());
                    assertEquals(20, cnt);
                } else {
                    for (Object rs : res) {
                        if (rs instanceof StructImpl) {
                            for (Object obj : ((StructImpl) rs).getFieldValues()) {
                                if (obj instanceof PdxInstance) {
                                } else {
                                    fail("Result objects for remote client query: " + queries[i] + " should be instance of PdxInstance and not " + obj.getClass());
                                }
                            }
                        } else if (rs instanceof PdxInstance) {
                        } else {
                            fail("Result objects for remote client query: " + queries[i] + " should be instance of PdxInstance and not " + rs.getClass());
                        }
                    }
                }
            }
            return null;
        }
    });
    closeCache(client);
    closeCache(server1);
}
Also used : PositionPdx(org.apache.geode.cache.query.data.PositionPdx) Host(org.apache.geode.test.dunit.Host) PortfolioPdx(org.apache.geode.cache.query.data.PortfolioPdx) ClientCache(org.apache.geode.cache.client.ClientCache) ClientCacheFactory(org.apache.geode.cache.client.ClientCacheFactory) QueryObserver(org.apache.geode.cache.query.internal.QueryObserver) SelectResults(org.apache.geode.cache.query.SelectResults) StructImpl(org.apache.geode.cache.query.internal.StructImpl) PdxInstance(org.apache.geode.pdx.PdxInstance) QueryService(org.apache.geode.cache.query.QueryService) VM(org.apache.geode.test.dunit.VM) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Region(org.apache.geode.cache.Region) GemFireCacheImpl(org.apache.geode.internal.cache.GemFireCacheImpl) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 8 with StructImpl

use of org.apache.geode.cache.query.internal.StructImpl in project geode by apache.

the class AbstractIndex method compareStructWithNonStruct.

/**
   * This method compares two objects in which one could be StructType and other ObjectType. Fur
   * conditions are possible, Object1 -> Struct Object2-> Struct Object1 -> Struct Object2-> Object
   * Object1 -> Object Object2-> Struct Object1 -> Object Object2-> Object
   *
   * @return true if valueInRegion's all objects are part of valueInIndex.
   */
private boolean compareStructWithNonStruct(Object valueInRegion, Object valueInIndex) {
    if (valueInRegion instanceof Struct && valueInIndex instanceof Struct) {
        Object[] regFields = ((StructImpl) valueInRegion).getFieldValues();
        List indFields = Arrays.asList(((StructImpl) valueInIndex).getFieldValues());
        for (Object regField : regFields) {
            if (!indFields.contains(regField)) {
                return false;
            }
        }
        return true;
    } else if (valueInRegion instanceof Struct) {
        Object[] fields = ((StructImpl) valueInRegion).getFieldValues();
        for (Object field : fields) {
            if (field.equals(valueInIndex)) {
                return true;
            }
        }
    } else if (valueInIndex instanceof Struct) {
        Object[] fields = ((StructImpl) valueInIndex).getFieldValues();
        for (Object field : fields) {
            if (field.equals(valueInRegion)) {
                return true;
            }
        }
    } else {
        return valueInRegion.equals(valueInIndex);
    }
    return false;
}
Also used : StructImpl(org.apache.geode.cache.query.internal.StructImpl) List(java.util.List) ArrayList(java.util.ArrayList) Struct(org.apache.geode.cache.query.Struct)

Example 9 with StructImpl

use of org.apache.geode.cache.query.internal.StructImpl in project geode by apache.

the class AbstractIndex method evaluateLastColl.

private List evaluateLastColl(Object value, ExecutionContext context, List itrs, int level) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    // A tuple is a value generated from RegionEntry value which could be a StructType (Multiple
    // Dependent Iterators) or ObjectType (Single Iterator) value.
    List tuples = new ArrayList(1);
    RuntimeIterator currItrator = (RuntimeIterator) itrs.get(level);
    currItrator.setCurrent(value);
    // If its last iterator then just evaluate final struct.
    if (itrs.size() - 1 == level) {
        if (itrs.size() > 1) {
            Object[] tuple = new Object[itrs.size()];
            for (int i = 0; i < itrs.size(); i++) {
                RuntimeIterator iter = (RuntimeIterator) itrs.get(i);
                tuple[i] = iter.evaluate(context);
            }
            // Its ok to pass type as null as we are only interested in values.
            tuples.add(new StructImpl(new StructTypeImpl(), tuple));
        } else {
            tuples.add(currItrator.evaluate(context));
        }
    } else {
        // Not the last iterator.
        RuntimeIterator nextItr = (RuntimeIterator) itrs.get(level + 1);
        Collection nextLevelValues = nextItr.evaluateCollection(context);
        // If value is null or INVALID then the evaluated collection would be Null.
        if (nextLevelValues != null) {
            for (Object nextLevelValue : nextLevelValues) {
                tuples.addAll(evaluateLastColl(nextLevelValue, context, itrs, level + 1));
            }
        }
    }
    return tuples;
}
Also used : StructImpl(org.apache.geode.cache.query.internal.StructImpl) ArrayList(java.util.ArrayList) StructTypeImpl(org.apache.geode.cache.query.internal.types.StructTypeImpl) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) RuntimeIterator(org.apache.geode.cache.query.internal.RuntimeIterator)

Example 10 with StructImpl

use of org.apache.geode.cache.query.internal.StructImpl in project geode by apache.

the class TypedJson method visitSpecialObjects.

List<Object> visitSpecialObjects(Writer w, Object object, boolean write) throws IOException {
    List<Object> elements = new ArrayList<Object>();
    Class clazz = object.getClass();
    if (clazz.isArray()) {
        if (write) {
            writeArray(w, object);
        } else {
            return getArrayChildren(object);
        }
    }
    if (clazz.isEnum()) {
        if (write) {
            writeEnum(w, object);
        } else {
            elements.add(object);
        }
        return elements;
    }
    if (object instanceof TypedJson) {
        this.writeTypedJson(w, (TypedJson) object);
        return elements;
    }
    if (object instanceof Collection) {
        Collection collection = (Collection) object;
        Iterator iter = collection.iterator();
        int i = 0;
        if (write)
            w.write('{');
        while (iter.hasNext() && i < queryCollectionsDepth) {
            Object item = iter.next();
            if (write) {
                writeKeyValue(w, i, item, item != null ? item.getClass() : null);
            } else {
                elements.add(item);
            }
            i++;
        }
        if (write)
            w.write('}');
        return elements;
    }
    if (object instanceof Map) {
        Map map = (Map) object;
        Iterator it = map.entrySet().iterator();
        int i = 0;
        if (write)
            w.write('{');
        while (it.hasNext() && i < queryCollectionsDepth) {
            Map.Entry e = (Map.Entry) it.next();
            Object value = e.getValue();
            if (write) {
                writeKeyValue(w, e.getKey(), value, value != null ? value.getClass() : null);
            } else {
                elements.add(value);
            }
            i++;
        }
        if (write)
            w.write('}');
        return elements;
    }
    if (object instanceof PdxInstance) {
        PdxInstance pdxInstance = (PdxInstance) object;
        if (write)
            w.write('{');
        for (String field : pdxInstance.getFieldNames()) {
            Object fieldValue = pdxInstance.getField(field);
            if (write) {
                writeKeyValue(w, field, fieldValue, fieldValue != null ? fieldValue.getClass() : null);
            } else {
                elements.add(fieldValue);
            }
        }
        if (write)
            w.write('}');
        return elements;
    }
    if (object instanceof Struct) {
        StructImpl impl = (StructImpl) object;
        String[] fields = impl.getFieldNames();
        Object[] values = impl.getFieldValues();
        if (write)
            w.write('{');
        for (int i = 0; i < fields.length; i++) {
            Object fieldValue = values[i];
            if (write) {
                writeKeyValue(w, fields[i], fieldValue, fieldValue != null ? fieldValue.getClass() : null);
            } else {
                elements.add(fieldValue);
            }
        }
        if (write)
            w.write('}');
        return elements;
    }
    if (object instanceof Region.Entry) {
        Region.Entry entry = (Region.Entry) object;
        Object key = entry.getKey();
        Object value = entry.getValue();
        if (write) {
            w.write('{');
            writeKeyValue(w, key, value, value != null ? value.getClass() : null);
            w.write('}');
        } else {
            elements.add(value);
        }
        return elements;
    }
    return elements;
}
Also used : ArrayList(java.util.ArrayList) Struct(org.apache.geode.cache.query.Struct) StructImpl(org.apache.geode.cache.query.internal.StructImpl) PdxInstance(org.apache.geode.pdx.PdxInstance) Iterator(java.util.Iterator) Collection(java.util.Collection) Region(org.apache.geode.cache.Region) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

StructImpl (org.apache.geode.cache.query.internal.StructImpl)17 Test (org.junit.Test)10 SelectResults (org.apache.geode.cache.query.SelectResults)8 Region (org.apache.geode.cache.Region)7 QueryService (org.apache.geode.cache.query.QueryService)7 ClientCache (org.apache.geode.cache.client.ClientCache)6 ClientCacheFactory (org.apache.geode.cache.client.ClientCacheFactory)6 PortfolioPdx (org.apache.geode.cache.query.data.PortfolioPdx)6 PositionPdx (org.apache.geode.cache.query.data.PositionPdx)6 Host (org.apache.geode.test.dunit.Host)6 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)6 VM (org.apache.geode.test.dunit.VM)6 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)6 Struct (org.apache.geode.cache.query.Struct)5 PdxInstance (org.apache.geode.pdx.PdxInstance)5 QueryObserver (org.apache.geode.cache.query.internal.QueryObserver)4 StructTypeImpl (org.apache.geode.cache.query.internal.types.StructTypeImpl)4 ArrayList (java.util.ArrayList)3 GemFireCacheImpl (org.apache.geode.internal.cache.GemFireCacheImpl)3 Collection (java.util.Collection)2