io.vertx.core.shareddata.impl.ClusterSerializable Java Examples

The following examples show how to use io.vertx.core.shareddata.impl.ClusterSerializable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExtendedSessionUT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void extendeSessionShouldBeClusterSerializable() throws InterruptedException {
    Vertx vertx = Vertx.vertx();
    SharedDataSessionImpl delegate = new SharedDataSessionImpl(new PRNG(vertx), 3000, SessionStore.DEFAULT_SESSIONID_LENGTH);
    ExtendedSession extendedSession = ExtendedSession.adapt(delegate);
    assertThat(extendedSession).isInstanceOf(ClusterSerializable.class);
    long createdAt = extendedSession.createdAt();
    extendedSession.put("key1", "value");
    extendedSession.put("key2", 20);
    Thread.sleep(300);

    Buffer buffer = Buffer.buffer();
    ((ClusterSerializable) extendedSession).writeToBuffer(buffer);
    assertThat(buffer.length() > 0);

    ExtendedSession fromBuffer = ExtendedSession.adapt(
        new SharedDataSessionImpl(new PRNG(vertx), 0, SessionStore.DEFAULT_SESSIONID_LENGTH)
    );
    ((ClusterSerializable) fromBuffer).readFromBuffer(0, buffer);
    assertThat(fromBuffer.createdAt()).isEqualTo(createdAt);
    assertThat(fromBuffer.id()).isEqualTo(delegate.id());
    assertThat(fromBuffer.timeout()).isEqualTo(delegate.timeout());
    assertThat(fromBuffer.data()).isEqualTo(delegate.data());

}
 
Example #2
Source File: ExtendedSessionUT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void extendeSessionShouldBeClusterSerializable() throws InterruptedException {
    Vertx vertx = Vertx.vertx();
    SharedDataSessionImpl delegate = new SharedDataSessionImpl(new PRNG(vertx), 3000, SessionStore.DEFAULT_SESSIONID_LENGTH);
    ExtendedSession extendedSession = ExtendedSession.adapt(delegate);
    assertThat(extendedSession).isInstanceOf(ClusterSerializable.class);
    long createdAt = extendedSession.createdAt();
    extendedSession.put("key1", "value");
    extendedSession.put("key2", 20);
    Thread.sleep(300);

    Buffer buffer = Buffer.buffer();
    ((ClusterSerializable) extendedSession).writeToBuffer(buffer);
    assertThat(buffer.length() > 0);

    ExtendedSession fromBuffer = ExtendedSession.adapt(
        new SharedDataSessionImpl(new PRNG(vertx), 0, SessionStore.DEFAULT_SESSIONID_LENGTH)
    );
    ((ClusterSerializable) fromBuffer).readFromBuffer(0, buffer);
    assertThat(fromBuffer.createdAt()).isEqualTo(createdAt);
    assertThat(fromBuffer.id()).isEqualTo(delegate.id());
    assertThat(fromBuffer.timeout()).isEqualTo(delegate.timeout());
    assertThat(fromBuffer.data()).isEqualTo(delegate.data());

}
 
Example #3
Source File: DataConverter.java    From vertx-infinispan with Apache License 2.0 6 votes vote down vote up
public static byte[] toCachedObject(Object o) {
  if (o == null) {
    return null;
  }
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  if (o instanceof Serializable) {
    baos.write(0);
    writeSerializable(baos, (Serializable) o);
  } else if (o instanceof ClusterSerializable) {
    baos.write(1);
    writeClusterSerializable(baos, (ClusterSerializable) o);
  } else {
    throw new IllegalArgumentException("Cannot convert object of type: " + o.getClass());
  }
  return baos.toByteArray();
}
 
Example #4
Source File: UserHolder.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void writeToBuffer(Buffer buffer) {
  // try to get the user from the context otherwise fall back to any cached version
  final User user;

  synchronized (this) {
    user = context != null ? context.user() : this.user;
    // clear the context as this holder is not in a request anymore
    context = null;
  }

  if (user instanceof ClusterSerializable) {
    buffer.appendByte((byte)1);
    String className = user.getClass().getName();
    if (className == null) {
      throw new IllegalStateException("Cannot serialize " + user.getClass().getName());
    }
    byte[] bytes = className.getBytes(StandardCharsets.UTF_8);
    buffer.appendInt(bytes.length);
    buffer.appendBytes(bytes);
    ClusterSerializable cs = (ClusterSerializable)user;
    cs.writeToBuffer(buffer);
  } else {
    buffer.appendByte((byte)0);
  }
}
 
Example #5
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private Object wrapIfNeeded(Object obj) {
    if (obj == null || obj instanceof Number || obj instanceof Character || obj instanceof String
        || obj instanceof Boolean || obj instanceof ClusterSerializable) {
        return obj;
    }
    return new SerializableHolder(obj);
}
 
Example #6
Source File: ConversionUtils.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
@Override
public void readData(ObjectDataInput objectDataInput) throws IOException {
  String className = objectDataInput.readUTF();
  int length = objectDataInput.readInt();
  byte[] bytes = new byte[length];
  objectDataInput.readFully(bytes);
  try {
    Class<?> clazz = loadClass(className);
    clusterSerializable = (ClusterSerializable) clazz.newInstance();
    clusterSerializable.readFromBuffer(0, Buffer.buffer(bytes));
  } catch (Exception e) {
    throw new IOException("Failed to load class " + className, e);
  }
}
 
Example #7
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private Object wrapIfNeeded(Object obj) {
    if (obj == null || obj instanceof Number || obj instanceof Character || obj instanceof String
        || obj instanceof Boolean || obj instanceof ClusterSerializable) {
        return obj;
    }
    return new SerializableHolder(obj);
}
 
Example #8
Source File: ConversionUtils.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T convertParam(T obj) {
  if (obj instanceof ClusterSerializable) {
    ClusterSerializable cobj = (ClusterSerializable) obj;
    return (T) (new DataSerializableHolder(cobj));
  } else {
    return obj;
  }
}
 
Example #9
Source File: BasicAuthHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void put(Session session, Handler<AsyncResult<Void>> resultHandler) {
  ClusterSerializable cs = (ClusterSerializable)session;
  Buffer buff = Buffer.buffer();
  cs.writeToBuffer(buff);
  sessions.put(session.id(), buff);
  vertx.runOnContext(v -> resultHandler.handle(Future.succeededFuture()));
}
 
Example #10
Source File: ClusterSerializationUtils.java    From vertx-ignite with Apache License 2.0 5 votes vote down vote up
private static ClusterSerializable unmarshal0(ClusterSerializableValue value) {
  try {
    Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(value.getClassName());
    ClusterSerializable obj = (ClusterSerializable) cls.getDeclaredConstructor().newInstance();
    obj.readFromBuffer(0, Buffer.buffer(value.getData()));
    return obj;
  } catch (Exception e) {
    throw new IllegalStateException("Failed to load class " + value.getClassName(), e);
  }
}
 
Example #11
Source File: DataConverter.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
private static void writeClusterSerializable(ByteArrayOutputStream baos, ClusterSerializable o) {
  Buffer buffer = Buffer.buffer();
  byte[] classNameBytes = o.getClass().getName().getBytes(StandardCharsets.UTF_8);
  buffer.appendInt(classNameBytes.length).appendBytes(classNameBytes);
  o.writeToBuffer(buffer);
  baos.write(buffer.getBytes(), 0, buffer.length());
}
 
Example #12
Source File: AtomixClusterManager.java    From atomix-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Vert.x compatible serializer.
 */
private Serializer createSerializer() {
  return Serializer.using(Namespace.builder()
      .setRegistrationRequired(false)
      .register(Namespaces.BASIC)
      .register(ServerID.class)
      .register(new ClusterSerializableSerializer<>(), ClusterSerializable.class)
      .build());
}
 
Example #13
Source File: UserHolder.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
  byte b = buffer.getByte(pos++);
  if (b == (byte)1) {
    int len = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + len);
    pos += len;
    String className = new String(bytes, StandardCharsets.UTF_8);
    try {
      Class<?> clazz = Utils.getClassLoader().loadClass(className);
      if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
        throw new ClassCastException(className + " is not ClusterSerializable");
      }
      ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
      pos = obj.readFromBuffer(pos, buffer);
      synchronized (this) {
        user = (User) obj;
        context = null;
      }
    } catch (Exception e) {
      throw new VertxException(e);
    }
  } else {
    synchronized (this) {
      user = null;
      context = null;
    }
  }
  return pos;
}
 
Example #14
Source File: ConversionUtils.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
public ClusterSerializable clusterSerializable() {
  return clusterSerializable;
}
 
Example #15
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 4 votes vote down vote up
@Override
public void writeToBuffer(Buffer buffer) {
    buffer.appendLong(createdAt);
    ((ClusterSerializable) delegate).writeToBuffer(buffer);
}
 
Example #16
Source File: ConversionUtils.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
private DataSerializableHolder(ClusterSerializable clusterSerializable) {
  this.clusterSerializable = clusterSerializable;
}
 
Example #17
Source File: SharedDataSessionImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private int readDataFromBuffer(int pos, Buffer buffer) {
  try {
    int entries = buffer.getInt(pos);
    pos += 4;
    if (entries > 0) {
      final Map<String, Object> data = new ConcurrentHashMap<>(entries);

      for (int i = 0; i < entries; i++) {
        int keylen = buffer.getInt(pos);
        pos += 4;
        byte[] keyBytes = buffer.getBytes(pos, pos + keylen);
        pos += keylen;
        String key = new String(keyBytes, UTF8);
        byte type = buffer.getByte(pos++);
        Object val;
        switch (type) {
          case TYPE_LONG:
            val = buffer.getLong(pos);
            pos += 8;
            break;
          case TYPE_INT:
            val = buffer.getInt(pos);
            pos += 4;
            break;
          case TYPE_SHORT:
            val = buffer.getShort(pos);
            pos += 2;
            break;
          case TYPE_BYTE:
            val = buffer.getByte(pos);
            pos++;
            break;
          case TYPE_FLOAT:
            val = buffer.getFloat(pos);
            pos += 4;
            break;
          case TYPE_DOUBLE:
            val = buffer.getDouble(pos);
            pos += 8;
            break;
          case TYPE_CHAR:
            short s = buffer.getShort(pos);
            pos += 2;
            val = (char) s;
            break;
          case TYPE_BOOLEAN:
            byte b = buffer.getByte(pos);
            pos++;
            val = b == 1;
            break;
          case TYPE_STRING:
            int len = buffer.getInt(pos);
            pos += 4;
            byte[] bytes = buffer.getBytes(pos, pos + len);
            val = new String(bytes, UTF8);
            pos += len;
            break;
          case TYPE_BUFFER:
            len = buffer.getInt(pos);
            pos += 4;
            bytes = buffer.getBytes(pos, pos + len);
            val = Buffer.buffer(bytes);
            pos += len;
            break;
          case TYPE_BYTES:
            len = buffer.getInt(pos);
            pos += 4;
            val = buffer.getBytes(pos, pos + len);
            pos += len;
            break;
          case TYPE_CLUSTER_SERIALIZABLE:
            int classNameLen = buffer.getInt(pos);
            pos += 4;
            byte[] classNameBytes = buffer.getBytes(pos, pos + classNameLen);
            pos += classNameLen;
            String className = new String(classNameBytes, UTF8);
            Class<?> clazz = Utils.getClassLoader().loadClass(className);
            if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
              throw new ClassCastException(new String(classNameBytes) + " is not assignable from ClusterSerializable");
            }
            ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
            pos = obj.readFromBuffer(pos, buffer);
            val = obj;
            break;
          default:
            throw new IllegalStateException("Invalid serialized type: " + type);
        }
        data.put(key, val);
      }
      setData(data);
    }
    return pos;
  } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
    throw new VertxException(e);
  }
}
 
Example #18
Source File: ClusterSerializationUtils.java    From vertx-ignite with Apache License 2.0 4 votes vote down vote up
private static ClusterSerializableValue marshal0(ClusterSerializable obj) {
  Buffer buffer = Buffer.buffer();
  obj.writeToBuffer(buffer);
  return new ClusterSerializableValue(obj.getClass().getName(), buffer.getBytes());
}
 
Example #19
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 4 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
    createdAt = buffer.getLong(pos);
    return ((ClusterSerializable) delegate).readFromBuffer(pos + 8, buffer);
}
 
Example #20
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 4 votes vote down vote up
@Override
public void writeToBuffer(Buffer buffer) {
    buffer.appendLong(createdAt);
    ((ClusterSerializable) delegate).writeToBuffer(buffer);
}
 
Example #21
Source File: ExtendedSessionImpl.java    From vertx-vaadin with MIT License 4 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
    createdAt = buffer.getLong(pos);
    return ((ClusterSerializable) delegate).readFromBuffer(pos + 8, buffer);
}
 
Example #22
Source File: ClusterSerializationUtils.java    From vertx-ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Serializes and wraps to {@link ClusterSerializableValue} given object if it implements
 * {@link ClusterSerializable} interface, otherwise returns source value.
 *
 * @param obj Object.
 * @return {@link ClusterSerializableValue} instance as serialized form of passed object if it implements
 * {@link ClusterSerializable} interface, otherwise passed object itself.
 */
public static <T> T marshal(T obj) {
  if (obj instanceof ClusterSerializable) {
    return (T) marshal0((ClusterSerializable) obj);
  } else {
    return obj;
  }
}