Exemplo n.º 1
0
    /** Creates a {@code GryoMapper}. */
    public GryoMapper create() {
      // consult the registry if provided and inject registry entries as custom classes.
      registries.forEach(
          registry -> {
            final List<Pair<Class, Object>> serializers = registry.find(GryoIo.class);
            serializers.forEach(
                p -> {
                  if (null == p.getValue1()) addCustom(p.getValue0());
                  else if (p.getValue1() instanceof Serializer)
                    addCustom(p.getValue0(), (Serializer) p.getValue1());
                  else if (p.getValue1() instanceof Function)
                    addCustom(p.getValue0(), (Function<Kryo, Serializer>) p.getValue1());
                  else
                    throw new IllegalStateException(
                        String.format(
                            "Unexpected value provided by the %s for %s - expects [null, %s implementation or Function<%s, %s>]",
                            IoRegistry.class.getSimpleName(),
                            p.getValue0().getClass().getSimpleName(),
                            Serializer.class.getName(),
                            Kryo.class.getSimpleName(),
                            Serializer.class.getSimpleName()));
                });
          });

      return new GryoMapper(this);
    }
  private void addCustomClasses(
      final Map<String, Object> config, final GryoMapper.Builder builder) {
    final List<String> classNameList = getClassNamesFromConfig(TOKEN_CUSTOM, config);

    classNameList
        .stream()
        .forEach(
            serializerDefinition -> {
              String className;
              Optional<String> serializerName;
              if (serializerDefinition.contains(";")) {
                final String[] split = serializerDefinition.split(";");
                if (split.length != 2)
                  throw new IllegalStateException(
                      String.format(
                          "Invalid format for serializer definition [%s] - expected <class>;<serializer-class>",
                          serializerDefinition));

                className = split[0];
                serializerName = Optional.of(split[1]);
              } else {
                serializerName = Optional.empty();
                className = serializerDefinition;
              }

              try {
                final Class clazz = Class.forName(className);
                final Serializer serializer;
                if (serializerName.isPresent()) {
                  final Class serializerClazz = Class.forName(serializerName.get());
                  serializer = (Serializer) serializerClazz.newInstance();
                  builder.addCustom(clazz, kryo -> serializer);
                } else builder.addCustom(clazz);
              } catch (Exception ex) {
                throw new IllegalStateException("Class could not be found", ex);
              }
            });
  }