Example usage for com.google.gson Gson getDelegateAdapter

List of usage examples for com.google.gson Gson getDelegateAdapter

Introduction

In this page you can find the example usage for com.google.gson Gson getDelegateAdapter.

Prototype

public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) 

Source Link

Document

This method is used to get an alternate type adapter for the specified type.

Usage

From source file:org.arl.fjage.remote.MessageAdapterFactory.java

License:BSD License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!Message.class.isAssignableFrom(rawType))
        return null;
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<Performative> perfDelegate = gson.getAdapter(TypeToken.get(Performative.class));
    final TypeAdapter<AgentID> aidDelegate = gson.getAdapter(TypeToken.get(AgentID.class));
    final TypeAdapter<GenericValue> gvDelegate = gson.getAdapter(TypeToken.get(GenericValue.class));
    final MessageAdapterFactory parent = this;
    return new TypeAdapter<T>() {

        @Override//from ww w. j  av  a2 s. com
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null)
                out.nullValue();
            else {
                out.beginObject();
                out.name("clazz").value(value.getClass().getName());
                out.name("data");
                if (value instanceof GenericMessage) {
                    GenericMessage msg = (GenericMessage) value;
                    out.beginObject();
                    out.name("msgID").value(msg.getMessageID());
                    out.name("inReplyTo").value(msg.getInReplyTo());
                    out.name("perf");
                    perfDelegate.write(out, msg.getPerformative());
                    out.name("recipient");
                    aidDelegate.write(out, msg.getRecipient());
                    out.name("sender");
                    aidDelegate.write(out, msg.getSender());
                    out.name("map");
                    delegate.write(out, value);
                    out.endObject();
                } else
                    delegate.write(out, value);
                out.endObject();
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            T rv = null;
            Class<?> cls = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("clazz")) {
                    String className = in.nextString();
                    try {
                        cls = classloader != null ? Class.forName(className, true, classloader)
                                : Class.forName(className);
                    } catch (Exception ex) {
                        // do nothing
                    }
                } else if (name.equals("data")) {
                    if (cls == null)
                        rv = delegate.read(in);
                    else if (cls.equals(GenericMessage.class)) {
                        GenericMessage msg = new GenericMessage();
                        in.beginObject();
                        while (in.hasNext()) {
                            String fname = in.nextName();
                            if (fname.equals("msgID"))
                                msg.setMessageID(in.nextString());
                            else if (fname.equals("inReplyTo"))
                                msg.setInReplyTo(in.nextString());
                            else if (fname.equals("perf"))
                                msg.setPerformative(perfDelegate.read(in));
                            else if (fname.equals("recipient"))
                                msg.setRecipient(aidDelegate.read(in));
                            else if (fname.equals("sender"))
                                msg.setSender(aidDelegate.read(in));
                            else if (fname.equals("map")) {
                                in.beginObject();
                                while (in.hasNext()) {
                                    String key = in.nextName();
                                    GenericValue value = gvDelegate.read(in);
                                    msg.put(key, value);
                                }
                                in.endObject();
                            } else
                                in.skipValue();
                        }
                        in.endObject();
                        rv = (T) msg;
                    } else {
                        TypeAdapter<?> delegate1 = gson.getDelegateAdapter(parent, TypeToken.get(cls));
                        rv = (T) delegate1.read(in);
                    }
                } else
                    in.skipValue();
            }
            in.endObject();
            return rv;
        }

    };
}

From source file:org.codice.admin.router.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }/*from  w w  w. j  a v a  2 s  . c om*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:org.immutables.mongo.bson4gson.GsonCodecs.java

License:Apache License

/**
 * Gson Factory which gives preference to existing adapters from {@code gson} instance. However,
 * if type is not supported it will query {@link CodecRegistry} to create one (if possible).
 *
 * <p>This allows supporting Bson types by Gson natively (eg. for {@link org.bson.types.ObjectId}).
 *
 * @param registry existing registry which will be used if type is unknown to {@code gson}.
 * @return factory which delegates to {@code registry} for unknown types.
 *///from ww  w  .  j  ava  2s  .  c om
public static TypeAdapterFactory delegatingTypeAdapterFactory(final CodecRegistry registry) {
    Preconditions.checkNotNull(registry, "registry");
    return new TypeAdapterFactory() {
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            boolean hasAdapter;
            try {
                TypeAdapter<T> adapter = gson.getDelegateAdapter(this, type);
                hasAdapter = !isReflectiveTypeAdapter(adapter);
            } catch (IllegalArgumentException e) {
                hasAdapter = false;
            }

            if (hasAdapter) {
                return null;
            }

            try {
                @SuppressWarnings("unchecked")
                Codec<T> codec = (Codec<T>) registry.get(type.getRawType());
                return typeAdapterFromCodec(codec);
            } catch (CodecConfigurationException e1) {
                return null;
            }

        }
    };
}

From source file:org.lanternpowered.server.script.function.action.json.ActionTypeAdapterFactory.java

License:MIT License

@Override
protected JsonElement serialize(TypeToken<Action> type, Action value, Gson gson) throws IOException {
    if (value instanceof ConditionalAction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ConditionalAction.class))
                .toJsonTree((ConditionalAction) value);
    } else if (value instanceof EmptyAction) {
        return gson.getDelegateAdapter(this, TypeToken.get(EmptyAction.class)).toJsonTree((EmptyAction) value);
    } else if (value instanceof MultiAction) {
        return gson.getDelegateAdapter(this, TypeToken.get(MultiAction.class)).toJsonTree((MultiAction) value);
    } else if (value instanceof ScriptFunction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ScriptFunction.class))
                .toJsonTree((ScriptFunction) value);
    }/*  www .j  av a 2 s . c o m*/
    return super.serialize(type, value, gson);
}

From source file:org.lanternpowered.server.script.function.action.json.ActionTypeAdapterFactory.java

License:MIT License

@Override
protected Action deserialize(TypeToken<Action> type, JsonElement element, Gson gson) {
    final Class<? super Action> raw = type.getRawType();
    if (ScriptFunction.class.isAssignableFrom(raw)) {
        return LanternScriptGameRegistry.get().compile(element.getAsString(), Action.class).get();
    } else if (ConditionalAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(ConditionalAction.class)).fromJsonTree(element);
    } else if (EmptyAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(EmptyAction.class)).fromJsonTree(element);
    } else if (MultiAction.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(MultiAction.class)).fromJsonTree(element);
    } else if (raw == Action.class) {
        // The actual action type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonNull()) {
            return Action.empty();
        } else if (element.isJsonArray()) {
            return gson.getDelegateAdapter(this, TypeToken.get(MultiAction.class)).fromJsonTree(element);
        } else if (element.isJsonObject()) {
            final JsonObject obj = element.getAsJsonObject();
            if (obj.has(ConditionalActionJsonSerializer.ACTION)
                    && obj.has(ConditionalActionJsonSerializer.CONDITION)) {
                return gson.getDelegateAdapter(this, TypeToken.get(ConditionalAction.class))
                        .fromJsonTree(element);
            }//from w  w w. jav  a 2 s. co m
        } else {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, Action.class).get();
            }
        }
    }
    return super.deserialize(type, element, gson);
}

From source file:org.lanternpowered.server.script.function.condition.json.ConditionTypeAdapterFactory.java

License:MIT License

@Override
protected JsonElement serialize(TypeToken<Condition> type, Condition value, Gson gson) throws IOException {
    if (value instanceof AndCondition) {
        return gson.getDelegateAdapter(this, TypeToken.get(AndCondition.class))
                .toJsonTree((AndCondition) value);
    } else if (value instanceof OrCondition) {
        return gson.getDelegateAdapter(this, TypeToken.get(OrCondition.class)).toJsonTree((OrCondition) value);
    } else if (value instanceof ScriptFunction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ScriptFunction.class))
                .toJsonTree((ScriptFunction) value);
    }/*  w ww .  j a  va2  s  .  com*/
    return super.serialize(type, value, gson);
}

From source file:org.lanternpowered.server.script.function.condition.json.ConditionTypeAdapterFactory.java

License:MIT License

@Override
protected Condition deserialize(TypeToken<Condition> type, JsonElement element, Gson gson) {
    final Class<? super Condition> raw = type.getRawType();
    if (AndCondition.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(AndCondition.class)).fromJsonTree(element);
    } else if (OrCondition.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(OrCondition.class)).fromJsonTree(element);
    } else if (raw == Condition.class) {
        // The actual condition type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonArray()) {
            return gson.getAdapter(AndCondition.class).fromJsonTree(element);
        } else if (element.isJsonPrimitive()) {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, Condition.class).get();
            }/*from   w  w  w  .j a  va2 s  .  c  o m*/
        }
    }
    return super.deserialize(type, element, gson);
}

From source file:org.lanternpowered.server.script.function.value.json.DoubleValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected JsonElement serialize(TypeToken<DoubleValueProvider> type, DoubleValueProvider value, Gson gson)
        throws IOException {
    if (value instanceof DoubleValueProvider.Range) {
        return gson.getDelegateAdapter(this, TypeToken.get(DoubleValueProvider.Range.class))
                .toJsonTree((DoubleValueProvider.Range) value);
    } else if (value instanceof DoubleValueProvider.Constant) {
        return gson.getDelegateAdapter(this, TypeToken.get(DoubleValueProvider.Constant.class))
                .toJsonTree((DoubleValueProvider.Constant) value);
    } else if (value instanceof ScriptFunction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ScriptFunction.class))
                .toJsonTree((ScriptFunction) value);
    }//from   w  w w  .  j a  v a2  s  . co  m
    return super.serialize(type, value, gson);
}

From source file:org.lanternpowered.server.script.function.value.json.DoubleValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected DoubleValueProvider deserialize(TypeToken<DoubleValueProvider> type, JsonElement element, Gson gson) {
    final Class<? super DoubleValueProvider> raw = type.getRawType();
    if (FloatValueProvider.Constant.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(DoubleValueProvider.Constant.class))
                .fromJsonTree(element);/*from   w ww .  jav  a 2 s.  c o m*/
    } else if (FloatValueProvider.Range.class.isAssignableFrom(raw)) {
        return gson.getDelegateAdapter(this, TypeToken.get(DoubleValueProvider.Range.class))
                .fromJsonTree(element);
    } else if (raw == DoubleValueProvider.class) {
        // The actual condition type isn't provided, we will try
        // to assume the right type based in the json format
        if (element.isJsonPrimitive()) {
            final String value = element.getAsString();
            if (value.startsWith(SCRIPT_PREFIX)) {
                return LanternScriptGameRegistry.get().compile(value, DoubleValueProvider.class).get();
            }
            return gson.getDelegateAdapter(this, TypeToken.get(DoubleValueProvider.Constant.class))
                    .fromJsonTree(element);
        }
    }
    return super.deserialize(type, element, gson);
}

From source file:org.lanternpowered.server.script.function.value.json.FloatValueProviderTypeAdapterFactory.java

License:MIT License

@Override
protected JsonElement serialize(TypeToken<FloatValueProvider> type, FloatValueProvider value, Gson gson)
        throws IOException {
    if (value instanceof FloatValueProvider.Range) {
        return gson.getDelegateAdapter(this, TypeToken.get(FloatValueProvider.Range.class))
                .toJsonTree((FloatValueProvider.Range) value);
    } else if (value instanceof FloatValueProvider.Constant) {
        return gson.getDelegateAdapter(this, TypeToken.get(FloatValueProvider.Constant.class))
                .toJsonTree((FloatValueProvider.Constant) value);
    } else if (value instanceof ScriptFunction) {
        return gson.getDelegateAdapter(this, TypeToken.get(ScriptFunction.class))
                .toJsonTree((ScriptFunction) value);
    }//from   w  ww.  ja va 2  s  .  c o m
    return super.serialize(type, value, gson);
}