Search in sources :

Example 1 with ReflectionException

use of com.badlogic.gdx.utils.reflect.ReflectionException in project libgdx by libgdx.

the class Json method readValue.

/** @param type May be null if the type is unknown.
	 * @param elementType May be null if the type is unknown.
	 * @return May be null. */
public <T> T readValue(Class<T> type, Class elementType, JsonValue jsonData) {
    if (jsonData == null)
        return null;
    if (jsonData.isObject()) {
        String className = typeName == null ? null : jsonData.getString(typeName, null);
        if (className != null) {
            type = getClass(className);
            if (type == null) {
                try {
                    type = (Class<T>) ClassReflection.forName(className);
                } catch (ReflectionException ex) {
                    throw new SerializationException(ex);
                }
            }
        }
        if (type == null) {
            if (defaultSerializer != null)
                return (T) defaultSerializer.read(this, jsonData, type);
            return (T) jsonData;
        }
        if (typeName != null && ClassReflection.isAssignableFrom(Collection.class, type)) {
            // JSON object wrapper to specify type.
            jsonData = jsonData.get("items");
        } else {
            Serializer serializer = classToSerializer.get(type);
            if (serializer != null)
                return (T) serializer.read(this, jsonData, type);
            if (type == String.class || type == Integer.class || type == Boolean.class || type == Float.class || type == Long.class || type == Double.class || type == Short.class || type == Byte.class || type == Character.class || ClassReflection.isAssignableFrom(Enum.class, type)) {
                return readValue("value", type, jsonData);
            }
            Object object = newInstance(type);
            if (object instanceof Serializable) {
                ((Serializable) object).read(this, jsonData);
                return (T) object;
            }
            // JSON object special cases.
            if (object instanceof ObjectMap) {
                ObjectMap result = (ObjectMap) object;
                for (JsonValue child = jsonData.child; child != null; child = child.next) result.put(child.name, readValue(elementType, null, child));
                return (T) result;
            }
            if (object instanceof ArrayMap) {
                ArrayMap result = (ArrayMap) object;
                for (JsonValue child = jsonData.child; child != null; child = child.next) result.put(child.name, readValue(elementType, null, child));
                return (T) result;
            }
            if (object instanceof Map) {
                Map result = (Map) object;
                for (JsonValue child = jsonData.child; child != null; child = child.next) {
                    if (child.name.equals(typeName)) {
                        continue;
                    }
                    result.put(child.name, readValue(elementType, null, child));
                }
                return (T) result;
            }
            readFields(object, jsonData);
            return (T) object;
        }
    }
    if (type != null) {
        Serializer serializer = classToSerializer.get(type);
        if (serializer != null)
            return (T) serializer.read(this, jsonData, type);
        if (ClassReflection.isAssignableFrom(Serializable.class, type)) {
            // A Serializable may be read as an array, string, etc, even though it will be written as an object.
            Object object = newInstance(type);
            ((Serializable) object).read(this, jsonData);
            return (T) object;
        }
    }
    if (jsonData.isArray()) {
        // JSON array special cases.
        if (type == null || type == Object.class)
            type = (Class<T>) Array.class;
        if (ClassReflection.isAssignableFrom(Array.class, type)) {
            Array result = type == Array.class ? new Array() : (Array) newInstance(type);
            for (JsonValue child = jsonData.child; child != null; child = child.next) result.add(readValue(elementType, null, child));
            return (T) result;
        }
        if (ClassReflection.isAssignableFrom(Queue.class, type)) {
            Queue result = type == Queue.class ? new Queue() : (Queue) newInstance(type);
            for (JsonValue child = jsonData.child; child != null; child = child.next) result.addLast(readValue(elementType, null, child));
            return (T) result;
        }
        if (ClassReflection.isAssignableFrom(Collection.class, type)) {
            Collection result = type.isInterface() ? new ArrayList() : (Collection) newInstance(type);
            for (JsonValue child = jsonData.child; child != null; child = child.next) result.add(readValue(elementType, null, child));
            return (T) result;
        }
        if (type.isArray()) {
            Class componentType = type.getComponentType();
            if (elementType == null)
                elementType = componentType;
            Object result = ArrayReflection.newInstance(componentType, jsonData.size);
            int i = 0;
            for (JsonValue child = jsonData.child; child != null; child = child.next) ArrayReflection.set(result, i++, readValue(elementType, null, child));
            return (T) result;
        }
        throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }
    if (jsonData.isNumber()) {
        try {
            if (type == null || type == float.class || type == Float.class)
                return (T) (Float) jsonData.asFloat();
            if (type == int.class || type == Integer.class)
                return (T) (Integer) jsonData.asInt();
            if (type == long.class || type == Long.class)
                return (T) (Long) jsonData.asLong();
            if (type == double.class || type == Double.class)
                return (T) (Double) jsonData.asDouble();
            if (type == String.class)
                return (T) jsonData.asString();
            if (type == short.class || type == Short.class)
                return (T) (Short) jsonData.asShort();
            if (type == byte.class || type == Byte.class)
                return (T) (Byte) jsonData.asByte();
        } catch (NumberFormatException ignored) {
        }
        jsonData = new JsonValue(jsonData.asString());
    }
    if (jsonData.isBoolean()) {
        try {
            if (type == null || type == boolean.class || type == Boolean.class)
                return (T) (Boolean) jsonData.asBoolean();
        } catch (NumberFormatException ignored) {
        }
        jsonData = new JsonValue(jsonData.asString());
    }
    if (jsonData.isString()) {
        String string = jsonData.asString();
        if (type == null || type == String.class)
            return (T) string;
        try {
            if (type == int.class || type == Integer.class)
                return (T) Integer.valueOf(string);
            if (type == float.class || type == Float.class)
                return (T) Float.valueOf(string);
            if (type == long.class || type == Long.class)
                return (T) Long.valueOf(string);
            if (type == double.class || type == Double.class)
                return (T) Double.valueOf(string);
            if (type == short.class || type == Short.class)
                return (T) Short.valueOf(string);
            if (type == byte.class || type == Byte.class)
                return (T) Byte.valueOf(string);
        } catch (NumberFormatException ignored) {
        }
        if (type == boolean.class || type == Boolean.class)
            return (T) Boolean.valueOf(string);
        if (type == char.class || type == Character.class)
            return (T) (Character) string.charAt(0);
        if (ClassReflection.isAssignableFrom(Enum.class, type)) {
            Enum[] constants = (Enum[]) type.getEnumConstants();
            for (int i = 0, n = constants.length; i < n; i++) {
                Enum e = constants[i];
                if (string.equals(convertToString(e)))
                    return (T) e;
            }
        }
        if (type == CharSequence.class)
            return (T) string;
        throw new SerializationException("Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ReflectionException

use of com.badlogic.gdx.utils.reflect.ReflectionException in project libgdx by libgdx.

the class Skin method getJsonLoader.

protected Json getJsonLoader(final FileHandle skinFile) {
    final Skin skin = this;
    final Json json = new Json() {

        public <T> T readValue(Class<T> type, Class elementType, JsonValue jsonData) {
            // If the JSON is a string but the type is not, look up the actual value by name.
            if (jsonData.isString() && !ClassReflection.isAssignableFrom(CharSequence.class, type))
                return get(jsonData.asString(), type);
            return super.readValue(type, elementType, jsonData);
        }
    };
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setSerializer(Skin.class, new ReadOnlySerializer<Skin>() {

        public Skin read(Json json, JsonValue typeToValueMap, Class ignored) {
            for (JsonValue valueMap = typeToValueMap.child; valueMap != null; valueMap = valueMap.next) {
                try {
                    readNamedObjects(json, ClassReflection.forName(valueMap.name()), valueMap);
                } catch (ReflectionException ex) {
                    throw new SerializationException(ex);
                }
            }
            return skin;
        }

        private void readNamedObjects(Json json, Class type, JsonValue valueMap) {
            Class addType = type == TintedDrawable.class ? Drawable.class : type;
            for (JsonValue valueEntry = valueMap.child; valueEntry != null; valueEntry = valueEntry.next) {
                Object object = json.readValue(type, valueEntry);
                if (object == null)
                    continue;
                try {
                    add(valueEntry.name, object, addType);
                    if (addType != Drawable.class && ClassReflection.isAssignableFrom(Drawable.class, addType))
                        add(valueEntry.name, object, Drawable.class);
                } catch (Exception ex) {
                    throw new SerializationException("Error reading " + ClassReflection.getSimpleName(type) + ": " + valueEntry.name, ex);
                }
            }
        }
    });
    json.setSerializer(BitmapFont.class, new ReadOnlySerializer<BitmapFont>() {

        public BitmapFont read(Json json, JsonValue jsonData, Class type) {
            String path = json.readValue("file", String.class, jsonData);
            int scaledSize = json.readValue("scaledSize", int.class, -1, jsonData);
            Boolean flip = json.readValue("flip", Boolean.class, false, jsonData);
            Boolean markupEnabled = json.readValue("markupEnabled", Boolean.class, false, jsonData);
            FileHandle fontFile = skinFile.parent().child(path);
            if (!fontFile.exists())
                fontFile = Gdx.files.internal(path);
            if (!fontFile.exists())
                throw new SerializationException("Font file not found: " + fontFile);
            // Use a region with the same name as the font, else use a PNG file in the same directory as the FNT file.
            String regionName = fontFile.nameWithoutExtension();
            try {
                BitmapFont font;
                Array<TextureRegion> regions = skin.getRegions(regionName);
                if (regions != null)
                    font = new BitmapFont(new BitmapFontData(fontFile, flip), regions, true);
                else {
                    TextureRegion region = skin.optional(regionName, TextureRegion.class);
                    if (region != null)
                        font = new BitmapFont(fontFile, region, flip);
                    else {
                        FileHandle imageFile = fontFile.parent().child(regionName + ".png");
                        if (imageFile.exists())
                            font = new BitmapFont(fontFile, imageFile, flip);
                        else
                            font = new BitmapFont(fontFile, flip);
                    }
                }
                font.getData().markupEnabled = markupEnabled;
                // Scaled size is the desired cap height to scale the font to.
                if (scaledSize != -1)
                    font.getData().setScale(scaledSize / font.getCapHeight());
                return font;
            } catch (RuntimeException ex) {
                throw new SerializationException("Error loading bitmap font: " + fontFile, ex);
            }
        }
    });
    json.setSerializer(Color.class, new ReadOnlySerializer<Color>() {

        public Color read(Json json, JsonValue jsonData, Class type) {
            if (jsonData.isString())
                return get(jsonData.asString(), Color.class);
            String hex = json.readValue("hex", String.class, (String) null, jsonData);
            if (hex != null)
                return Color.valueOf(hex);
            float r = json.readValue("r", float.class, 0f, jsonData);
            float g = json.readValue("g", float.class, 0f, jsonData);
            float b = json.readValue("b", float.class, 0f, jsonData);
            float a = json.readValue("a", float.class, 1f, jsonData);
            return new Color(r, g, b, a);
        }
    });
    json.setSerializer(TintedDrawable.class, new ReadOnlySerializer() {

        public Object read(Json json, JsonValue jsonData, Class type) {
            String name = json.readValue("name", String.class, jsonData);
            Color color = json.readValue("color", Color.class, jsonData);
            Drawable drawable = newDrawable(name, color);
            if (drawable instanceof BaseDrawable) {
                BaseDrawable named = (BaseDrawable) drawable;
                named.setName(jsonData.name + " (" + name + ", " + color + ")");
            }
            return drawable;
        }
    });
    return json;
}
Also used : ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) SerializationException(com.badlogic.gdx.utils.SerializationException) BitmapFontData(com.badlogic.gdx.graphics.g2d.BitmapFont.BitmapFontData) FileHandle(com.badlogic.gdx.files.FileHandle) Color(com.badlogic.gdx.graphics.Color) BaseDrawable(com.badlogic.gdx.scenes.scene2d.utils.BaseDrawable) JsonValue(com.badlogic.gdx.utils.JsonValue) TextureRegionDrawable(com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable) Drawable(com.badlogic.gdx.scenes.scene2d.utils.Drawable) BaseDrawable(com.badlogic.gdx.scenes.scene2d.utils.BaseDrawable) SpriteDrawable(com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable) NinePatchDrawable(com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable) TiledDrawable(com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable) Json(com.badlogic.gdx.utils.Json) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) SerializationException(com.badlogic.gdx.utils.SerializationException) ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) Array(com.badlogic.gdx.utils.Array) TextureRegion(com.badlogic.gdx.graphics.g2d.TextureRegion) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) ReadOnlySerializer(com.badlogic.gdx.utils.Json.ReadOnlySerializer) BitmapFont(com.badlogic.gdx.graphics.g2d.BitmapFont)

Example 3 with ReflectionException

use of com.badlogic.gdx.utils.reflect.ReflectionException in project gdx-skineditor by cobolfoo.

the class Skin method getJsonLoader.

protected Json getJsonLoader(final FileHandle skinFile) {
    final Skin skin = this;
    final Json json = new Json() {

        public <T> T readValue(Class<T> type, Class elementType, JsonValue jsonData) {
            // actual value by name.
            if (jsonData.isString() && !ClassReflection.isAssignableFrom(CharSequence.class, type))
                return get(jsonData.asString(), type);
            return super.readValue(type, elementType, jsonData);
        }
    };
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setSerializer(Skin.class, new ReadOnlySerializer<Skin>() {

        public Skin read(Json json, JsonValue typeToValueMap, Class ignored) {
            for (JsonValue valueMap = typeToValueMap.child; valueMap != null; valueMap = valueMap.next) {
                try {
                    readNamedObjects(json, ClassReflection.forName(valueMap.name()), valueMap);
                } catch (ReflectionException ex) {
                    throw new SerializationException(ex);
                }
            }
            return skin;
        }

        private void readNamedObjects(Json json, Class type, JsonValue valueMap) {
            for (JsonValue valueEntry = valueMap.child; valueEntry != null; valueEntry = valueEntry.next) {
                Object object = json.readValue(type, valueEntry);
                if (object == null)
                    continue;
                try {
                    add(valueEntry.name(), object, type);
                } catch (Exception ex) {
                    throw new SerializationException("Error reading " + ClassReflection.getSimpleName(type) + ": " + valueEntry.name(), ex);
                }
            }
        }
    });
    json.setSerializer(BitmapFont.class, new ReadOnlySerializer<BitmapFont>() {

        public BitmapFont read(Json json, JsonValue jsonData, Class type) {
            String path = json.readValue("file", String.class, jsonData);
            int scaledSize = json.readValue("scaledSize", int.class, -1, jsonData);
            Boolean flip = json.readValue("flip", Boolean.class, false, jsonData);
            FileHandle fontFile = skinFile.parent().child(path);
            if (!fontFile.exists())
                fontFile = Gdx.files.internal(path);
            if (!fontFile.exists())
                throw new SerializationException("Font file not found: " + fontFile);
            // Use a region with the same name as the font, else use
            // a PNG file in the same directory as the FNT file.
            String regionName = fontFile.nameWithoutExtension();
            try {
                BitmapFont font;
                TextureRegion region = skin.optional(regionName, TextureRegion.class);
                if (region != null)
                    font = new BitmapFont(fontFile, region, flip);
                else {
                    FileHandle imageFile = fontFile.parent().child(regionName + ".png");
                    if (imageFile.exists())
                        font = new BitmapFont(fontFile, imageFile, flip);
                    else
                        font = new BitmapFont(fontFile, flip);
                }
                // the font to.
                if (scaledSize != -1)
                    font.setScale(scaledSize / font.getCapHeight());
                return font;
            } catch (RuntimeException ex) {
                throw new SerializationException("Error loading bitmap font: " + fontFile, ex);
            }
        }
    });
    json.setSerializer(Color.class, new ReadOnlySerializer<Color>() {

        public Color read(Json json, JsonValue jsonData, Class type) {
            if (jsonData.isString())
                return get(jsonData.asString(), Color.class);
            String hex = json.readValue("hex", String.class, (String) null, jsonData);
            if (hex != null)
                return Color.valueOf(hex);
            float r = json.readValue("r", float.class, 0f, jsonData);
            float g = json.readValue("g", float.class, 0f, jsonData);
            float b = json.readValue("b", float.class, 0f, jsonData);
            float a = json.readValue("a", float.class, 1f, jsonData);
            return new Color(r, g, b, a);
        }
    });
    json.setSerializer(TintedDrawable.class, new ReadOnlySerializer() {

        public Object read(Json json, JsonValue jsonData, Class type) {
            String name = json.readValue("name", String.class, jsonData);
            Color color = json.readValue("color", Color.class, jsonData);
            TintedDrawable td = new TintedDrawable();
            td.name = name;
            td.color = color;
            td.drawable = newDrawable(name, color);
            return td;
        // return newDrawable(name, color);
        }
    });
    return json;
}
Also used : ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) SerializationException(com.badlogic.gdx.utils.SerializationException) FileHandle(com.badlogic.gdx.files.FileHandle) Color(com.badlogic.gdx.graphics.Color) JsonValue(com.badlogic.gdx.utils.JsonValue) Json(com.badlogic.gdx.utils.Json) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) SerializationException(com.badlogic.gdx.utils.SerializationException) ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) TextureRegion(com.badlogic.gdx.graphics.g2d.TextureRegion) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) ReadOnlySerializer(com.badlogic.gdx.utils.Json.ReadOnlySerializer) BitmapFont(com.badlogic.gdx.graphics.g2d.BitmapFont)

Example 4 with ReflectionException

use of com.badlogic.gdx.utils.reflect.ReflectionException in project Mindustry by Anuken.

the class WebsocketClient method connect.

@Override
public void connect(String ip, int port) {
    socket = new Websocket("ws://" + ip + ":" + webPort);
    socket.addListener(new WebsocketListener() {

        public void onMessage(byte[] bytes) {
            try {
                ByteBuffer buffer = ByteBuffer.wrap(bytes);
                byte id = buffer.get();
                if (id != -2) {
                    // ignore framework messages
                    Class<?> type = Registrator.getByID(id);
                    Packet packet = (Packet) ClassReflection.newInstance(type);
                    packet.read(buffer);
                    Net.handleClientReceived(packet);
                }
            } catch (ReflectionException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onClose() {
            Disconnect disconnect = new Disconnect();
            Net.handleClientReceived(disconnect);
        }

        @Override
        public void onMessage(String msg) {
            onMessage(Base64Coder.decode(msg));
        }

        @Override
        public void onOpen() {
            Connect connect = new Connect();
            Net.handleClientReceived(connect);
        }
    });
    socket.open();
}
Also used : ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) Disconnect(io.anuke.mindustry.net.Packets.Disconnect) Websocket(com.sksamuel.gwt.websockets.Websocket) Connect(io.anuke.mindustry.net.Packets.Connect) WebsocketListener(com.sksamuel.gwt.websockets.WebsocketListener) ByteBuffer(java.nio.ByteBuffer)

Example 5 with ReflectionException

use of com.badlogic.gdx.utils.reflect.ReflectionException in project bladecoder-adventure-engine by bladecoder.

the class ActionUtils method readJson.

public static Action readJson(Json json, JsonValue jsonData) {
    String className = jsonData.getString("class", null);
    Action action = null;
    if (className != null) {
        jsonData.remove("class");
        try {
            action = ActionFactory.createByClass(className, null);
        } catch (ClassNotFoundException | ReflectionException e1) {
            throw new SerializationException(e1);
        }
        for (int j = 0; j < jsonData.size; j++) {
            JsonValue v = jsonData.get(j);
            try {
                if (v.isNull())
                    ActionUtils.setParam(action, v.name, null);
                else
                    ActionUtils.setParam(action, v.name, v.asString());
            } catch (NoSuchFieldException e) {
                EngineLogger.error("Action field not found - class: " + className + " field: " + v.name);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                EngineLogger.error("Action field error - class: " + className + " field: " + v.name + " value: " + (v == null ? "null" : v.asString()));
            }
        }
    }
    return action;
}
Also used : ReflectionException(com.badlogic.gdx.utils.reflect.ReflectionException) Action(com.bladecoder.engine.actions.Action) SerializationException(com.badlogic.gdx.utils.SerializationException) JsonValue(com.badlogic.gdx.utils.JsonValue)

Aggregations

ReflectionException (com.badlogic.gdx.utils.reflect.ReflectionException)15 JsonValue (com.badlogic.gdx.utils.JsonValue)5 SerializationException (com.badlogic.gdx.utils.SerializationException)4 Field (com.badlogic.gdx.utils.reflect.Field)4 IOException (java.io.IOException)4 FileHandle (com.badlogic.gdx.files.FileHandle)3 BitmapFont (com.badlogic.gdx.graphics.g2d.BitmapFont)3 TextureRegion (com.badlogic.gdx.graphics.g2d.TextureRegion)3 Array (com.badlogic.gdx.utils.Array)3 Json (com.badlogic.gdx.utils.Json)3 Action (com.bladecoder.engine.actions.Action)3 AccessControlException (java.security.AccessControlException)3 Color (com.badlogic.gdx.graphics.Color)2 Drawable (com.badlogic.gdx.scenes.scene2d.utils.Drawable)2 NinePatchDrawable (com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable)2 SpriteDrawable (com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable)2 TextureRegionDrawable (com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable)2 TiledDrawable (com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable)2 GdxRuntimeException (com.badlogic.gdx.utils.GdxRuntimeException)2 ReadOnlySerializer (com.badlogic.gdx.utils.Json.ReadOnlySerializer)2