Example usage for com.google.gson JsonParseException JsonParseException

List of usage examples for com.google.gson JsonParseException JsonParseException

Introduction

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

Prototype

public JsonParseException(String msg, Throwable cause) 

Source Link

Document

Creates exception with the specified message and cause.

Usage

From source file:org.couchpotato.json.deserializer.JsonBooleanDeserializer.java

License:Open Source License

@Override
public JsonBoolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {
    try {//from   ww  w  .ja va 2  s .  c  o m
        String value = arg0.getAsJsonPrimitive().getAsString();
        if (value.toLowerCase().equals("true")) {
            return new JsonBoolean(true);
        } else if (value.toLowerCase().equals("false")) {
            return new JsonBoolean(false);
        } else {
            return new JsonBoolean(Integer.valueOf(value) != 0);
        }
    } catch (ClassCastException e) {
        throw new JsonParseException("Cannot parse JsonBoolean string '" + arg0.toString() + "'", e);
    } catch (Exception e) {
        throw new JsonParseException("Cannot parse JsonBoolean string '" + arg0.toString() + "'", e);
    }
}

From source file:org.infoglue.deliver.externalsearch.ExternalSearchManager.java

License:Open Source License

private void initGSon() {
    final Type configType = new TypeToken<Map<String, Object>>() {
    }.getType();/*from  w  w w. j a  va  2s.c om*/
    class DelegateDeserializer<T extends ExternalSearchDelegate> implements JsonDeserializer<T> {
        @Override
        public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                JsonObject obj = (JsonObject) json;
                Class<?> clazz = Class.forName(obj.get("class").getAsString());
                @SuppressWarnings("unchecked")
                T delegate = (T) clazz.newInstance();

                if (obj.has("config")) {
                    Map<String, Object> config = context.deserialize(obj.get("config"), configType);
                    delegate.setConfig(config);
                }

                return delegate;
            } catch (Exception ex) {
                throw new JsonParseException(
                        "Failed to deserialize element. Exception message: " + ex.getMessage(), ex);
            }
        }

    }
    class DelegateConfigDeserializer implements JsonDeserializer<Map<String, Object>> {
        @Override
        public Map<String, Object> deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context) throws JsonParseException {
            try {
                Map<String, Object> config = new HashMap<String, Object>();
                JsonObject configObject = json.getAsJsonObject();
                for (Map.Entry<String, JsonElement> configEntry : configObject.entrySet()) {
                    if (configEntry.getValue().isJsonObject()) {
                        config.put(configEntry.getKey(),
                                context.deserialize(configEntry.getValue(), configType));
                    } else if (configEntry.getValue().isJsonPrimitive()
                            && ((JsonPrimitive) configEntry.getValue()).isString()) {
                        config.put(configEntry.getKey(), configEntry.getValue().getAsString());
                    }
                }

                return config;
            } catch (Exception ex) {
                throw new JsonParseException(
                        "Failed to deserialize element. Exception message: " + ex.getMessage(), ex);
            }
        }

    }

    GsonBuilder gson = new GsonBuilder();

    Type fieldsType = new TypeToken<Map<String, IndexableField>>() {
    }.getType();

    gson.registerTypeAdapter(fieldsType, new IndexableField.Deserializer());
    gson.registerTypeAdapter(configType, new DelegateConfigDeserializer());
    gson.registerTypeAdapter(DataRetriever.class, new DelegateDeserializer<DataRetriever>());
    gson.registerTypeAdapter(Parser.class, new DelegateDeserializer<Parser>());
    gson.registerTypeAdapter(Indexer.class, new DelegateDeserializer<Indexer>());

    configParser = gson.create();
}

From source file:org.lanternpowered.server.text.LanternTextHelper.java

License:MIT License

@SuppressWarnings("deprecation")
public static HoverAction<?> parseHoverAction(String action, String value) throws JsonParseException {
    final DataView dataView;
    switch (action) {
    case "show_text":
        return TextActions.showText(TextSerializers.LEGACY_FORMATTING_CODE.deserializeUnchecked(value));
    case "show_item":
        try {//  ww w.  j a v  a  2 s  . co  m
            dataView = JsonDataFormat.readContainer(value, false);
        } catch (IOException e) {
            throw new JsonParseException("Failed to parse the item data container", e);
        }
        final ItemStack itemStack = ItemStackStore.INSTANCE.deserialize(dataView);
        return TextActions.showItem(itemStack.createSnapshot());
    case "show_entity":
        try {
            dataView = JsonDataFormat.readContainer(value, false);
        } catch (IOException e) {
            throw new JsonParseException("Failed to parse the entity data container", e);
        }

        final UUID uuid = UUID.fromString(dataView.getString(SHOW_ENTITY_ID).get());
        final String name = dataView.getString(SHOW_ENTITY_NAME).get();
        EntityType entityType = null;
        if (dataView.contains(SHOW_ENTITY_TYPE)) {
            entityType = Sponge.getRegistry()
                    .getType(EntityType.class, dataView.getString(SHOW_ENTITY_TYPE).get()).orElse(null);
        }

        return TextActions.showEntity(uuid, name, entityType);
    default:
        throw new IllegalArgumentException("Unknown hover action type: " + action);
    }
}

From source file:org.mgenterprises.openbooks.saving.AbstractSaveableAdapter.java

License:Open Source License

@Override
public Saveable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    String type = jsonObject.get("type").getAsString();
    JsonElement element = jsonObject.get("properties");

    try {/*from w w w .j  a v a 2  s  .  c o m*/
        return context.deserialize(element, Class.forName(type));
    } catch (ClassNotFoundException cnfe) {
        throw new JsonParseException("Unknown element type: " + type, cnfe);
    }
}

From source file:org.onos.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public JsonParserStream parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
    // code copied from gson's JsonParser and Stream classes

    final boolean lenient = reader.isLenient();
    reader.setLenient(true);//from ww w .  j  a v a 2s .c o m
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(
                parentNode);
        read(reader, compositeNodeDataWithSchema);
        compositeNodeDataWithSchema.write(writer);

        return this;
        // return read(reader);
    } catch (final EOFException e) {
        if (isEmpty) {
            return this;
            // return JsonNull.INSTANCE;
        }
        // The stream ended prematurely so it is likely a syntax error.
        throw new JsonSyntaxException(e);
    } catch (final MalformedJsonException e) {
        throw new JsonSyntaxException(e);
    } catch (final IOException e) {
        throw new JsonIOException(e);
    } catch (final NumberFormatException e) {
        throw new JsonSyntaxException(e);
    } catch (StackOverflowError | OutOfMemoryError e) {
        throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
    } finally {
        reader.setLenient(lenient);
    }
}

From source file:org.opendaylight.controller.sal.rest.gson.JsonParser.java

License:Open Source License

public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException {
    // code copied from gson's JsonParser and Stream classes

    boolean lenient = reader.isLenient();
    reader.setLenient(true);//from  w w w .j a v  a2s  . c  o  m
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        return read(reader);
    } catch (EOFException e) {
        if (isEmpty) {
            return JsonNull.INSTANCE;
        }
        // The stream ended prematurely so it is likely a syntax error.
        throw new JsonSyntaxException(e);
    } catch (MalformedJsonException e) {
        throw new JsonSyntaxException(e);
    } catch (IOException e) {
        throw new JsonIOException(e);
    } catch (NumberFormatException e) {
        throw new JsonSyntaxException(e);
    } catch (StackOverflowError | OutOfMemoryError e) {
        throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
    } finally {
        reader.setLenient(lenient);
    }
}

From source file:org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public JsonParserStream parse(final JsonReader reader) {
    // code copied from gson's JsonParser and Stream classes

    final boolean lenient = reader.isLenient();
    reader.setLenient(true);/* ww  w  .  ja v  a 2  s .  c o m*/
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(
                parentNode);
        read(reader, compositeNodeDataWithSchema);
        compositeNodeDataWithSchema.write(writer);

        return this;
    } catch (final EOFException e) {
        if (isEmpty) {
            return this;
        }
        // The stream ended prematurely so it is likely a syntax error.
        throw new JsonSyntaxException(e);
    } catch (final MalformedJsonException | NumberFormatException e) {
        throw new JsonSyntaxException(e);
    } catch (final IOException e) {
        throw new JsonIOException(e);
    } catch (StackOverflowError | OutOfMemoryError e) {
        throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
    } finally {
        reader.setLenient(lenient);
    }
}

From source file:org.opendolphin.core.comm.JsonCodec.java

License:Apache License

@Override
public List<Command> decode(String transmitted) {
    LOG.trace("Decoding message: {}", transmitted);
    try {//from   ww w .  j  av a2s  .c  o m
        final List<Command> commands = new ArrayList<>();
        final JsonArray array = (JsonArray) new JsonParser().parse(transmitted);

        for (final JsonElement jsonElement : array) {
            final JsonObject commandElement = (JsonObject) jsonElement;
            final String className = commandElement.getAsJsonPrimitive("className").getAsString();
            LOG.trace("Decoding command type: {}", className);
            Class<? extends Command> commandClass = (Class<? extends Command>) Class.forName(className);
            if (commandClass.equals(ValueChangedCommand.class)) {
                commands.add(createValueChangedCommand(commandElement));
            } else if (commandClass.equals(CreatePresentationModelCommand.class)) {
                commands.add(createCreatePresentationModelCommand(commandElement));
            } else {
                commands.add(GSON.fromJson(commandElement, commandClass));
            }
        }
        LOG.trace("Decoded command list with {} commands", commands.size());
        return commands;
    } catch (Exception ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:org.rapla.rest.gwtjsonrpc.server.JsonServlet.java

License:Apache License

private void parseGetRequest(final ActiveCall call) {
    final HttpServletRequest req = call.httpRequest;

    if ("2.0".equals(req.getParameter("jsonrpc"))) {
        final JsonObject d = new JsonObject();
        d.addProperty("jsonrpc", "2.0");
        d.addProperty("method", req.getParameter("method"));
        d.addProperty("id", req.getParameter("id"));
        try {// ww w  .j  ava  2  s  . c o m
            String parameter = req.getParameter("params");
            final byte[] params = parameter.getBytes("ISO-8859-1");
            JsonElement parsed;
            try {
                parsed = new JsonParser().parse(parameter);
            } catch (JsonParseException e) {
                final String p = new String(Base64.decodeBase64(params), "UTF-8");
                parsed = new JsonParser().parse(p);
            }
            d.add("params", parsed);
        } catch (UnsupportedEncodingException e) {
            throw new JsonParseException("Cannot parse params", e);
        }

        try {
            final GsonBuilder gb = createGsonBuilder();
            gb.registerTypeAdapter(ActiveCall.class, new CallDeserializer(call, this));
            gb.create().fromJson(d, ActiveCall.class);
        } catch (JsonParseException err) {
            call.method = null;
            call.params = null;
            throw err;
        }
    } else { /* JSON-RPC 1.1 or GET REST API */
        String body = (String) req.getAttribute("postBody");
        mapRequestToCall(call, req, body);
    }

    String childLoggerName = class1.getName() + "." + call.method.getName() + ".arguments";
    Logger childLogger = logger.getChildLogger(childLoggerName);
    if (childLogger.isDebugEnabled()) {
        childLogger.debug(req.getQueryString());
    }

}

From source file:org.rapla.server.jsonrpc.JsonServlet.java

License:Apache License

private void parseGetRequest(final CallType call) {
    final HttpServletRequest req = call.httpRequest;

    if ("2.0".equals(req.getParameter("jsonrpc"))) {
        final JsonObject d = new JsonObject();
        d.addProperty("jsonrpc", "2.0");
        d.addProperty("method", req.getParameter("method"));
        d.addProperty("id", req.getParameter("id"));
        try {/*from ww  w.  j  a  v a 2s. co m*/
            String parameter = req.getParameter("params");
            final byte[] params = parameter.getBytes("ISO-8859-1");
            JsonElement parsed;
            try {
                parsed = new JsonParser().parse(parameter);
            } catch (JsonParseException e) {
                final String p = new String(Base64.decodeBase64(params), "UTF-8");
                parsed = new JsonParser().parse(p);
            }
            d.add("params", parsed);
        } catch (UnsupportedEncodingException e) {
            throw new JsonParseException("Cannot parse params", e);
        }

        try {
            final GsonBuilder gb = createGsonBuilder();
            gb.registerTypeAdapter(ActiveCall.class, //
                    new CallDeserializer<CallType>(call, this));
            gb.create().fromJson(d, ActiveCall.class);
        } catch (JsonParseException err) {
            call.method = null;
            call.params = null;
            throw err;
        }

    } else { /* JSON-RPC 1.1 */
        final Gson gs = createGsonBuilder().create();

        call.method = lookupMethod(req.getParameter("method"));
        if (call.method == null) {
            throw new NoSuchRemoteMethodException();
        }
        final Type[] paramTypes = call.method.getParamTypes();
        final Object[] r = new Object[paramTypes.length];

        for (int i = 0; i < r.length; i++) {
            final String v = req.getParameter("param" + i);
            if (v == null) {
                r[i] = null;
            } else if (paramTypes[i] == String.class) {
                r[i] = v;
            } else if (paramTypes[i] instanceof Class<?> && ((Class<?>) paramTypes[i]).isPrimitive()) {
                // Primitive type, use the JSON representation of that type.
                //
                r[i] = gs.fromJson(v, paramTypes[i]);
            } else {
                // Assume it is like a java.sql.Timestamp or something and treat
                // the value as JSON string.
                //
                r[i] = gs.fromJson(gs.toJson(v), paramTypes[i]);
            }
        }
        call.params = r;
        call.callback = req.getParameter("callback");
    }
}