Пример #1
0
  @Test
  public void testGlobalSerializer_withOverrideJavaSerializable() {
    GlobalSerializerConfig globalSerializerConfig = new GlobalSerializerConfig();
    globalSerializerConfig.setOverrideJavaSerialization(true);
    final AtomicInteger writeCounter = new AtomicInteger();
    final AtomicInteger readCounter = new AtomicInteger();
    final JavaSerializer javaSerializer = new JavaSerializer(true, false);
    SerializationConfig serializationConfig =
        new SerializationConfig()
            .setGlobalSerializerConfig(
                globalSerializerConfig.setImplementation(
                    new StreamSerializer<Object>() {
                      @Override
                      public void write(ObjectDataOutput out, Object v) throws IOException {
                        writeCounter.incrementAndGet();
                        if (v instanceof Serializable) {
                          out.writeBoolean(true);
                          javaSerializer.write(out, v);
                        } else if (v instanceof DummyValue) {
                          out.writeBoolean(false);
                          out.writeUTF(((DummyValue) v).s);
                          out.writeInt(((DummyValue) v).k);
                        }
                      }

                      @Override
                      public Object read(ObjectDataInput in) throws IOException {
                        readCounter.incrementAndGet();
                        boolean java = in.readBoolean();
                        if (java) {
                          return javaSerializer.read(in);
                        }
                        return new DummyValue(in.readUTF(), in.readInt());
                      }

                      public int getTypeId() {
                        return 123;
                      }

                      public void destroy() {}
                    }));

    SerializationService ss1 =
        new DefaultSerializationServiceBuilder().setConfig(serializationConfig).build();
    DummyValue value = new DummyValue("test", 111);
    Data data1 = ss1.toData(value);
    Data data2 = ss1.toData(new Foo());
    Assert.assertNotNull(data1);
    Assert.assertNotNull(data2);
    assertEquals(2, writeCounter.get());

    SerializationService ss2 =
        new DefaultSerializationServiceBuilder().setConfig(serializationConfig).build();
    Object o1 = ss2.toObject(data1);
    Object o2 = ss2.toObject(data2);
    Assert.assertEquals(value, o1);
    Assert.assertNotNull(o2);
    assertEquals(2, readCounter.get());
  }
  @Test
  public void testCacheRecord_withBinaryInMemoryData() {
    CacheRecord cacheRecord = createRecord(InMemoryFormat.BINARY);

    Data cacheRecordData = service.toData(cacheRecord);
    service.toObject(cacheRecordData);
  }
  @Test
  public void testCacheRecord_withObjectInMemoryData() {
    CacheRecord cacheRecord = createRecord(InMemoryFormat.OBJECT);

    Data cacheRecordData = service.toData(cacheRecord);
    service.toObject(cacheRecordData);
  }
Пример #4
0
 @Test
 public void testDynamicProxySerialization_withContextClassLoader() {
   ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
   try {
     ClassLoader current = getClass().getClassLoader();
     DynamicProxyTestClassLoader cl = new DynamicProxyTestClassLoader(current);
     Thread.currentThread().setContextClassLoader(cl);
     SerializationService ss = new DefaultSerializationServiceBuilder().setClassLoader(cl).build();
     IObjectA oa =
         (IObjectA)
             Proxy.newProxyInstance(
                 current, new Class[] {IObjectA.class}, DummyInvocationHandler.INSTANCE);
     Data data = ss.toData(oa);
     Object o = ss.toObject(data);
     Assert.assertSame("context classloader is not used", cl, o.getClass().getClassLoader());
     try {
       IObjectA.class.cast(o);
       Assert.fail("the serialized object should not be castable");
     } catch (ClassCastException expected) {
       // expected
     }
   } finally {
     Thread.currentThread().setContextClassLoader(oldContextLoader);
   }
 }
 @Before
 public void setUp() {
   List<Data> dataList = new ArrayList<Data>();
   for (int i = 0; i < SIZE; i++) {
     dataList.add(serializationService.toData(i));
   }
   list = new UnmodifiableLazyList<Integer>(dataList, serializationService);
 }
Пример #6
0
  @Test
  public void testInternallySupportedClassExtended() {
    SerializationService ss = new DefaultSerializationServiceBuilder().build();
    TheClassThatExtendArrayList obj = new TheClassThatExtendArrayList();
    Data data = ss.toData(obj);
    Object obj2 = ss.toObject(data);

    assertEquals(obj2.getClass(), TheClassThatExtendArrayList.class);
  }
Пример #7
0
  /** issue #1265 */
  @Test
  public void testUnsharedJavaSerialization() {
    SerializationService ss =
        new DefaultSerializationServiceBuilder().setEnableSharedObject(false).build();
    Data data = ss.toData(new Foo());
    Foo foo = ss.toObject(data);

    Assert.assertFalse("Objects should not be identical!", foo == foo.getBar().getFoo());
  }
Пример #8
0
 @Test
 public void testArraySerialization() {
   SerializationService ss = new DefaultSerializationServiceBuilder().build();
   byte[] array = new byte[1024];
   new Random().nextBytes(array);
   Data data = ss.toData(array);
   byte[] deserialized = ss.toObject(data);
   assertArrayEquals(array, deserialized);
 }
Пример #9
0
  /** issue #1265 */
  @Test
  public void testSharedJavaSerialization() {
    SerializationService ss =
        new DefaultSerializationServiceBuilder().setEnableSharedObject(true).build();
    Data data = ss.toData(new Foo());
    Foo foo = (Foo) ss.toObject(data);

    assertTrue("Objects are not identical!", foo == foo.getBar().getFoo());
  }
 @Test
 public void testSerialize() {
   Data data = serializationService.toData(list);
   List<Integer> deserializedList = serializationService.toObject(data);
   int size = list.size();
   assertEquals(size, deserializedList.size());
   for (int i = 0; i < size; i++) {
     assertEquals(list.get(i), deserializedList.get(i));
   }
 }
Пример #11
0
 @Test
 public void testArrayListSerialization() {
   SerializationService ss = new DefaultSerializationServiceBuilder().build();
   ArrayList<Person> arrayList = new ArrayList<Person>();
   arrayList.add(new Person(35, 180, 100, "Orhan", null));
   arrayList.add(new Person(12, 120, 60, "Osman", null));
   Data data = ss.toData(arrayList);
   ArrayList deserialized = ss.toObject(data);
   assertTrue("Objects are not identical!", arrayList.equals(deserialized));
 }
Пример #12
0
  /**
   * Ensures that SerializationService correctly handles compressed Serializables, using a
   * test-specific object as a test case.
   */
  @Test
  public void testCompressionOnExternalizables() {
    SerializationService serializationService =
        new DefaultSerializationServiceBuilder().setEnableCompression(true).build();
    String test = "test";
    ExternalizableString ex = new ExternalizableString(test);
    Data data = serializationService.toData(ex);

    ExternalizableString actual = serializationService.toObject(data);
    assertEquals(test, actual.value);
  }
Пример #13
0
  @Test
  public void testResultType() {
    map.put("1", "a");
    Collection<String> entries = map.values(TruePredicate.INSTANCE);

    QueryResultCollection collection = assertInstanceOf(QueryResultCollection.class, entries);
    QueryResultRow row = (QueryResultRow) collection.getRows().iterator().next();
    // there should only be a value, no key
    assertNull(row.getKey());
    assertEquals(serializationService.toData("a"), row.getValue());
  }
Пример #14
0
  /**
   * Ensures that SerializationService correctly handles compressed Serializables, using a
   * Properties object as a test case.
   */
  @Test
  public void testCompressionOnSerializables() {
    SerializationService serializationService =
        new DefaultSerializationServiceBuilder().setEnableCompression(true).build();
    long key = 1, value = 5000;
    Properties properties = new Properties();
    properties.put(key, value);
    Data data = serializationService.toData(properties);

    Properties output = serializationService.toObject(data);
    assertEquals(value, output.get(key));
  }
Пример #15
0
  @Test
  public void testPartitionHash() {
    PartitioningStrategy partitionStrategy =
        new PartitioningStrategy() {
          @Override
          public Object getPartitionKey(Object key) {
            return key.hashCode();
          }
        };

    SerializationService ss = new DefaultSerializationServiceBuilder().build();

    String obj = String.valueOf(System.nanoTime());
    Data dataWithPartitionHash = ss.toData(obj, partitionStrategy);
    Data dataWithOutPartitionHash = ss.toData(obj);

    assertTrue(dataWithPartitionHash.hasPartitionHash());
    assertNotEquals(dataWithPartitionHash.hashCode(), dataWithPartitionHash.getPartitionHash());

    assertFalse(dataWithOutPartitionHash.hasPartitionHash());
    assertEquals(dataWithOutPartitionHash.hashCode(), dataWithOutPartitionHash.getPartitionHash());
  }
  @Test
  public void test_CacheReplicationOperation_serialization() throws Exception {
    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();

    try {
      CachingProvider provider =
          HazelcastServerCachingProvider.createCachingProvider(hazelcastInstance);
      CacheManager manager = provider.getCacheManager();

      CompleteConfiguration configuration = new MutableConfiguration();
      Cache cache1 = manager.createCache("cache1", configuration);
      Cache cache2 = manager.createCache("cache2", configuration);
      Cache cache3 = manager.createCache("cache3", configuration);

      for (int i = 0; i < 1000; i++) {
        cache1.put("key" + i, i);
        cache2.put("key" + i, i);
        cache3.put("key" + i, i);
      }

      HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance;

      Field original = HazelcastInstanceProxy.class.getDeclaredField("original");
      original.setAccessible(true);

      HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy);
      NodeEngineImpl nodeEngine = impl.node.nodeEngine;
      CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME);

      int partitionCount = nodeEngine.getPartitionService().getPartitionCount();

      for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
        CachePartitionSegment segment = cacheService.getSegment(partitionId);

        CacheReplicationOperation operation = new CacheReplicationOperation(segment, 1);
        Data serialized = service.toData(operation);
        try {
          service.toObject(serialized);
        } catch (Exception e) {
          throw new Exception("Partition: " + partitionId, e);
        }
      }

    } finally {
      factory.shutdownAll();
    }
  }
/** Encode Decode Tests */
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class MapMessageEncodeDecodeTest {

  private static final SerializationService serializationService =
      new DefaultSerializationServiceBuilder().build();

  private static final String NAME = "name";
  private static final Data DATA = serializationService.toData("The Test");
  private static final long THE_LONG = 0xFFFFl;

  private ClientProtocolBuffer byteBuffer;

  @Before
  public void setUp() {
    byteBuffer = new SafeBuffer(new byte[20]);
  }

  @Test
  public void shouldEncodeDecodeCorrectly_PUT() {
    final int calculatedSize =
        MapPutCodec.RequestParameters.calculateDataSize(NAME, DATA, DATA, THE_LONG, THE_LONG);
    ClientMessage cmEncode = MapPutCodec.encodeRequest(NAME, DATA, DATA, THE_LONG, THE_LONG);
    cmEncode
        .setVersion((short) 3)
        .addFlag(ClientMessage.BEGIN_AND_END_FLAGS)
        .setCorrelationId(Long.MAX_VALUE)
        .setPartitionId(77);

    assertTrue(calculatedSize > cmEncode.getFrameLength());
    byteBuffer = cmEncode.buffer();

    ClientMessage cmDecode = ClientMessage.createForDecode(byteBuffer, 0);
    MapPutCodec.RequestParameters decodeParams = MapPutCodec.decodeRequest(cmDecode);

    assertEquals(MapPutCodec.REQUEST_TYPE.id(), cmDecode.getMessageType());
    assertEquals(3, cmDecode.getVersion());
    assertEquals(ClientMessage.BEGIN_AND_END_FLAGS, cmDecode.getFlags());
    assertEquals(Long.MAX_VALUE, cmDecode.getCorrelationId());
    assertEquals(77, cmDecode.getPartitionId());

    assertEquals(NAME, decodeParams.name);
    assertEquals(DATA, decodeParams.key);
    assertEquals(DATA, decodeParams.value);
    assertEquals(THE_LONG, decodeParams.threadId);
    assertEquals(THE_LONG, decodeParams.ttl);
  }
}
Пример #18
0
 @Test
 public void testNonPublicDynamicProxySerialization_withClassLoaderMess() {
   ClassLoader current = getClass().getClassLoader();
   DynamicProxyTestClassLoader cl1 =
       new DynamicProxyTestClassLoader(current, IPrivateObjectB.class.getName());
   DynamicProxyTestClassLoader cl2 =
       new DynamicProxyTestClassLoader(cl1, IPrivateObjectC.class.getName());
   SerializationService ss = new DefaultSerializationServiceBuilder().setClassLoader(cl2).build();
   Object ocd =
       Proxy.newProxyInstance(
           current,
           new Class[] {IPrivateObjectB.class, IPrivateObjectC.class},
           DummyInvocationHandler.INSTANCE);
   Data data = ss.toData(ocd);
   try {
     ss.toObject(data);
     Assert.fail("the object should not be deserializable");
   } catch (IllegalAccessError expected) {
     // expected
   }
 }
Пример #19
0
  @Test
  public void testEmptyData() {
    SerializationConfig serializationConfig =
        new SerializationConfig()
            .addSerializerConfig(
                new SerializerConfig()
                    .setTypeClass(SingletonValue.class)
                    .setImplementation(
                        new StreamSerializer<SingletonValue>() {
                          @Override
                          public void write(ObjectDataOutput out, SingletonValue v)
                              throws IOException {}

                          @Override
                          public SingletonValue read(ObjectDataInput in) throws IOException {
                            return new SingletonValue();
                          }

                          @Override
                          public int getTypeId() {
                            return 123;
                          }

                          @Override
                          public void destroy() {}
                        }));

    SerializationService ss1 =
        new DefaultSerializationServiceBuilder().setConfig(serializationConfig).build();
    Data data = ss1.toData(new SingletonValue());
    Assert.assertNotNull(data);

    SerializationService ss2 =
        new DefaultSerializationServiceBuilder().setConfig(serializationConfig).build();
    Object o = ss2.toObject(data);
    Assert.assertEquals(new SingletonValue(), o);
  }
Пример #20
0
 protected Data toData(Object object, PartitioningStrategy partitioningStrategy) {
   return serializationService.toData(object, partitioningStrategy);
 }