Search in sources :

Example 46 with PdxInstance

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

the class RestAPIsAndInterOpsDUnitTest method verifyUpdatesInClientCache.

public void verifyUpdatesInClientCache() {
    ClientCache cache = GemFireCacheImpl.getInstance();
    assertNotNull(cache);
    Region<String, Object> region = cache.getRegion(PEOPLE_REGION_NAME);
    {
        Person expectedPerson = new Person(3L, "Nishka3", "Nilkanth3", "Patel3", DateTimeUtils.createDate(2009, Calendar.JULY, 31), Gender.FEMALE);
        Object value = region.get("3");
        if (value instanceof PdxInstance) {
            PdxInstance pi3 = (PdxInstance) value;
            Person actualPerson = (Person) pi3.getObject();
            assertEquals(actualPerson.getId(), expectedPerson.getId());
            assertEquals(actualPerson.getFirstName(), expectedPerson.getFirstName());
            assertEquals(actualPerson.getMiddleName(), expectedPerson.getMiddleName());
            assertEquals(actualPerson.getLastName(), expectedPerson.getLastName());
            assertEquals(actualPerson.getBirthDate(), expectedPerson.getBirthDate());
            assertEquals(actualPerson.getGender(), expectedPerson.getGender());
        } else if (value instanceof Person) {
            fail("VerifyUpdatesInClientCache, Get on key 3, Expected to get value of type PdxInstance ");
        }
    }
    // TODO: uncomment it once following issue encountered in put?op=CAS is fixed or document the
    // issue
    // CAS functionality is not working in following test case
    // step-1: Java client, Region.put("K", A);
    // Step-2: Rest CAS request for key "K" with data "@old" = A. CAS is failing as existing
    // PdxInstance in cache and
    // PdxInstance generated from JSON (CAS request) does not match as their value's type are
    // getting changed
    /*
     * //verify update on key "1" { Object obj = region.get("1"); if (obj instanceof PdxInstance) {
     * PdxInstance pi = (PdxInstance)obj; Person p1 = (Person)pi.getObject();
     * System.out.println("Nilkanth1 : verifyUpdatesInClientCache() : GET ON KEY=1" +
     * p1.toString()); }else {
     * System.out.println("Nilkanth1 : verifyUpdatesInClientCache() GET ON KEY=1  returned OBJECT: "
     * + obj.toString()); } }
     */
    // verify update on key "2"
    {
        Person expectedPerson = new Person(501L, "Barack", "Hussein", "Obama", DateTimeUtils.createDate(1961, Calendar.APRIL, 8), Gender.MALE);
        Object value = region.get("2");
        if (value instanceof PdxInstance) {
            PdxInstance pi3 = (PdxInstance) value;
            Person actualPerson = (Person) pi3.getObject();
            assertEquals(actualPerson.getId(), expectedPerson.getId());
            assertEquals(actualPerson.getFirstName(), expectedPerson.getFirstName());
            assertEquals(actualPerson.getMiddleName(), expectedPerson.getMiddleName());
            assertEquals(actualPerson.getLastName(), expectedPerson.getLastName());
            assertEquals(actualPerson.getBirthDate(), expectedPerson.getBirthDate());
            assertEquals(actualPerson.getGender(), expectedPerson.getGender());
        } else {
            fail("VerifyUpdatesInClientCache, Get on key 2, Expected to get value of type PdxInstance ");
        }
    }
    // verify Deleted key "13"
    {
        Object obj = region.get("13");
        assertEquals(obj, null);
        obj = region.get("14");
        assertEquals(obj, null);
        obj = region.get("15");
        assertEquals(obj, null);
        obj = region.get("16");
        assertEquals(obj, null);
    }
}
Also used : PdxInstance(org.apache.geode.pdx.PdxInstance) JSONObject(org.json.JSONObject) ClientCache(org.apache.geode.cache.client.ClientCache)

Example 47 with PdxInstance

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

the class DataSerializer method readObjectArray.

/**
   * Reads an array of <code>Object</code>s from a <code>DataInput</code>.
   *
   * @throws IOException A problem occurs while reading from <code>in</code>
   *
   * @see #writeObjectArray
   * @see #readObject
   */
public static Object[] readObjectArray(DataInput in) throws IOException, ClassNotFoundException {
    InternalDataSerializer.checkIn(in);
    int length = InternalDataSerializer.readArrayLength(in);
    if (length == -1) {
        return null;
    } else {
        Class<?> c = null;
        byte typeCode = in.readByte();
        String typeString = null;
        if (typeCode == DSCODE.CLASS) {
            typeString = readString(in);
        }
        InternalCache cache = GemFireCacheImpl.getInstance();
        boolean lookForPdxInstance = false;
        ClassNotFoundException cnfEx = null;
        if (typeCode == DSCODE.CLASS && cache != null && cache.getPdxReadSerializedByAnyGemFireServices()) {
            try {
                c = InternalDataSerializer.getCachedClass(typeString);
                lookForPdxInstance = true;
            } catch (ClassNotFoundException ignore) {
                c = Object.class;
                cnfEx = ignore;
            }
        } else {
            if (typeCode == DSCODE.CLASS) {
                c = InternalDataSerializer.getCachedClass(typeString);
            } else {
                c = InternalDataSerializer.decodePrimitiveClass(typeCode);
            }
        }
        Object o = null;
        if (length > 0) {
            o = readObject(in);
            if (lookForPdxInstance && o instanceof PdxInstance) {
                lookForPdxInstance = false;
                c = Object.class;
            }
        }
        Object[] array = (Object[]) Array.newInstance(c, length);
        if (length > 0) {
            array[0] = o;
        }
        for (int i = 1; i < length; i++) {
            o = readObject(in);
            if (lookForPdxInstance && o instanceof PdxInstance) {
                // create an Object[] and copy all the entries we already did into it
                lookForPdxInstance = false;
                c = Object.class;
                Object[] newArray = (Object[]) Array.newInstance(c, length);
                System.arraycopy(array, 0, newArray, 0, i);
                array = newArray;
            }
            array[i] = o;
        }
        if (lookForPdxInstance && cnfEx != null && length > 0) {
            // type is a pdx one.
            throw cnfEx;
        }
        if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
            logger.trace(LogMarker.SERIALIZER, "Read Object array of length {}", length);
        }
        return array;
    }
}
Also used : PdxInstance(org.apache.geode.pdx.PdxInstance) InternalCache(org.apache.geode.internal.cache.InternalCache) StoredObject(org.apache.geode.internal.offheap.StoredObject)

Example 48 with PdxInstance

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

the class CompiledOperation method evaluate.

public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    CompiledValue rcvr = getReceiver(context);
    Object result;
    Object evalRcvr;
    if (rcvr == null) {
        // must be intended as implicit iterator operation
        // see if it's an implicit operation name
        RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true);
        evalRcvr = rcvrItr.evaluate(context);
    /*
       * // evaluate on current iteration of collection if (rcvrItr != null) { result =
       * eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); }
       * 
       * // function call: no functions implemented except keywords in the grammar throw new
       * TypeMismatchException(LocalizedStrings.CompiledOperation_COULD_NOT_RESOLVE_METHOD_NAMED_0.
       * toLocalizedString(this.methodName));
       */
    } else {
        // if not null, then explicit receiver
        evalRcvr = rcvr.evaluate(context);
    }
    // short circuit null immediately
    if (evalRcvr == null) {
        return QueryService.UNDEFINED;
    }
    if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) {
        Region.Entry re = (Region.Entry) evalRcvr;
        if (re.isDestroyed()) {
            return QueryService.UNDEFINED;
        }
        try {
            evalRcvr = re.getValue();
        } catch (EntryDestroyedException ede) {
            // throw EntryDestroyedException if the value becomes null.
            return QueryService.UNDEFINED;
        }
    }
    // check if the receiver is the iterator, in which
    // case we resolve the method on the constraint rather
    // than the runtime type of the receiver
    Class resolveClass = null;
    // if (resolveClass == null)
    if (evalRcvr instanceof PdxInstance) {
        String className = ((PdxInstance) evalRcvr).getClassName();
        try {
            resolveClass = InternalDataSerializer.getCachedClass(className);
        } catch (ClassNotFoundException cnfe) {
            throw new QueryInvocationTargetException(cnfe);
        }
    } else if (evalRcvr instanceof PdxString) {
        resolveClass = String.class;
    } else {
        resolveClass = evalRcvr.getClass();
    }
    result = eval0(evalRcvr, resolveClass, context);
    // }
    // check for PR substitution
    // check for BucketRegion substitution
    PartitionedRegion pr = context.getPartitionedRegion();
    if (pr != null && (result instanceof Region)) {
        if (pr.getFullPath().equals(((Region) result).getFullPath())) {
            result = context.getBucketRegion();
        }
    }
    return result;
}
Also used : EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) PdxString(org.apache.geode.pdx.internal.PdxString) PdxString(org.apache.geode.pdx.internal.PdxString) PdxInstance(org.apache.geode.pdx.PdxInstance) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion)

Example 49 with PdxInstance

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

the class CompiledOperation method eval0.

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED", justification = "Does not matter if the methodDispatch that isn't stored in the map is used")
private Object eval0(Object receiver, Class resolutionType, ExecutionContext context) throws TypeMismatchException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException {
    if (receiver == null || receiver == QueryService.UNDEFINED)
        return QueryService.UNDEFINED;
    List args = new ArrayList();
    List argTypes = new ArrayList();
    Iterator i = this.args.iterator();
    while (i.hasNext()) {
        CompiledValue arg = (CompiledValue) i.next();
        Object o = arg.evaluate(context);
        // undefined arg produces undefines method result
        if (o == QueryService.UNDEFINED)
            return QueryService.UNDEFINED;
        args.add(o);
        // pass in null for the type if the runtime value is null
        if (o == null)
            argTypes.add(null);
        else
            // commented out because we currently always use the runtime type for args
            // else if (arg.getType() == Identifier)
            // {
            // CompiledValue resolved = context.resolve(((CompiledID)arg).getId());
            // if (resolved != null && resolved.getType() == ITERATOR)
            // argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint());
            // else
            // argTypes.add(o.getClass());
            // }
            // otherwise use the runtime type
            argTypes.add(o.getClass());
    }
    // see if in cache
    MethodDispatch methodDispatch;
    List key = Arrays.asList(new Object[] { resolutionType, this.methodName, argTypes });
    methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key);
    if (methodDispatch == null) {
        try {
            methodDispatch = new MethodDispatch(resolutionType, this.methodName, argTypes);
        } catch (NameResolutionException nre) {
            if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType) && (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS || DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) {
                return QueryService.UNDEFINED;
            } else {
                throw nre;
            }
        }
        // cache
        CompiledOperation.cache.putIfAbsent(key, methodDispatch);
    }
    if (receiver instanceof PdxInstance) {
        try {
            if (receiver instanceof PdxInstanceImpl) {
                receiver = ((PdxInstanceImpl) receiver).getCachedObject();
            } else {
                receiver = ((PdxInstance) receiver).getObject();
            }
        } catch (PdxSerializationException ex) {
            throw new QueryInvocationTargetException(ex);
        }
    } else if (receiver instanceof PdxString) {
        receiver = ((PdxString) receiver).toString();
    }
    return methodDispatch.invoke(receiver, args);
}
Also used : ArrayList(java.util.ArrayList) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) PdxString(org.apache.geode.pdx.internal.PdxString) PdxSerializationException(org.apache.geode.pdx.PdxSerializationException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) PdxInstance(org.apache.geode.pdx.PdxInstance) PdxInstanceImpl(org.apache.geode.pdx.internal.PdxInstanceImpl) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 50 with PdxInstance

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

the class InternalDataSerializer method basicWriteObject.

public static void basicWriteObject(Object o, DataOutput out, boolean ensurePdxCompatibility) throws IOException {
    checkOut(out);
    final boolean isDebugEnabled_SERIALIZER = logger.isTraceEnabled(LogMarker.SERIALIZER);
    if (isDebugEnabled_SERIALIZER) {
        logger.trace(LogMarker.SERIALIZER, "basicWriteObject: {}", o);
    }
    // Handle special objects first
    if (o == null) {
        out.writeByte(NULL);
    } else if (o instanceof DataSerializableFixedID) {
        checkPdxCompatible(o, ensurePdxCompatibility);
        DataSerializableFixedID dsfid = (DataSerializableFixedID) o;
        writeDSFID(dsfid, out);
    } else if (autoSerialized(o, out)) {
    // all done
    } else if (o instanceof DataSerializable.Replaceable) {
        // do this first to fix bug 31609
        // do this before DataSerializable
        Object replacement = ((DataSerializable.Replaceable) o).replace();
        basicWriteObject(replacement, out, ensurePdxCompatibility);
    } else if (o instanceof PdxSerializable) {
        writePdx(out, GemFireCacheImpl.getForPdx("PDX registry is unavailable because the Cache has been closed."), o, null);
    } else if (o instanceof DataSerializable) {
        if (isDebugEnabled_SERIALIZER) {
            logger.trace(LogMarker.SERIALIZER, "Writing DataSerializable: {}", o);
        }
        checkPdxCompatible(o, ensurePdxCompatibility);
        Class c = o.getClass();
        // Is "c" a user class registered with an Instantiator?
        int classId = InternalInstantiator.getClassId(c);
        if (classId != 0) {
            writeUserDataSerializableHeader(classId, out);
        } else {
            out.writeByte(DATA_SERIALIZABLE);
            DataSerializer.writeClass(c, out);
        }
        DataSerializable ds = (DataSerializable) o;
        invokeToData(ds, out);
    } else if (o instanceof Sendable) {
        if (!(o instanceof PdxInstance) || o instanceof PdxInstanceEnum) {
            checkPdxCompatible(o, ensurePdxCompatibility);
        }
        ((Sendable) o).sendTo(out);
    } else if (writeWellKnownObject(o, out, ensurePdxCompatibility)) {
    // Nothing more to do...
    } else {
        checkPdxCompatible(o, ensurePdxCompatibility);
        if (logger.isTraceEnabled(LogMarker.DUMP_SERIALIZED)) {
            logger.trace(LogMarker.DUMP_SERIALIZED, "DataSerializer Serializing an instance of {}", o.getClass().getName());
        }
        /*
       * If the (internally known) ThreadLocal named "DataSerializer.DISALLOW_JAVA_SERIALIZATION" is
       * set, then an exception will be thrown if we try to do standard Java Serialization. This is
       * used to catch Java serialization early for the case where the data is being sent to a
       * non-Java client
       */
        if (disallowJavaSerialization() && o instanceof Serializable) {
            throw new NotSerializableException(LocalizedStrings.DataSerializer_0_IS_NOT_DATASERIALIZABLE_AND_JAVA_SERIALIZATION_IS_DISALLOWED.toLocalizedString(o.getClass().getName()));
        }
        writeSerializableObject(o, out);
    }
}
Also used : PdxInstanceEnum(org.apache.geode.pdx.internal.PdxInstanceEnum) Serializable(java.io.Serializable) DataSerializable(org.apache.geode.DataSerializable) PdxSerializable(org.apache.geode.pdx.PdxSerializable) NotSerializableException(java.io.NotSerializableException) PdxInstance(org.apache.geode.pdx.PdxInstance) ObjectStreamClass(java.io.ObjectStreamClass) DataSerializable(org.apache.geode.DataSerializable) PdxSerializable(org.apache.geode.pdx.PdxSerializable)

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