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(Throwable cause) 

Source Link

Document

Creates exception with the specified cause.

Usage

From source file:org.kurento.jsonrpc.JsonUtils.java

License:Apache License

public static List<String> toStringList(JsonArray values) {
    List<String> list = new ArrayList<>();
    for (JsonElement element : values) {
        if (element instanceof JsonPrimitive) {
            list.add(((JsonPrimitive) element).getAsString());
        } else {//  w  w w.j  a va2  s .  co  m
            throw new JsonParseException("JsonArray " + values + " contains non string elements");
        }
    }
    return list;
}

From source file:org.kurento.jsonrpc.JsonUtils.java

License:Apache License

@Override
public Response<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (!(json instanceof JsonObject)) {
        throw new JsonParseException("JonObject expected, found " + json.getClass().getSimpleName());
    }//  w ww. j a v  a 2s .c  om

    JsonObject jObject = (JsonObject) json;

    if (!jObject.has(JSON_RPC_PROPERTY)) {
        throw new JsonParseException(
                "Invalid JsonRpc response lacking version '" + JSON_RPC_PROPERTY + "' field");
    }

    if (!jObject.get(JSON_RPC_PROPERTY).getAsString().equals(JsonRpcConstants.JSON_RPC_VERSION)) {
        throw new JsonParseException("Invalid JsonRpc version");
    }

    Integer id = null;
    JsonElement idAsJsonElement = jObject.get(ID_PROPERTY);
    if (idAsJsonElement != null) {
        try {
            id = Integer.valueOf(idAsJsonElement.getAsInt());
        } catch (Exception e) {
            throw new JsonParseException("Invalid format in '" + ID_PROPERTY + "' field in request " + json);
        }
    }

    if (jObject.has(ERROR_PROPERTY)) {

        return new Response<>(id,
                (ResponseError) context.deserialize(jObject.get(ERROR_PROPERTY), ResponseError.class));

    } else {

        if (jObject.has(RESULT_PROPERTY)) {

            ParameterizedType parameterizedType = (ParameterizedType) typeOfT;

            return new Response<>(id, context.deserialize(jObject.get(RESULT_PROPERTY),
                    parameterizedType.getActualTypeArguments()[0]));

        } else {

            log.warn("Invalid JsonRpc response: " + json + " It lacks a valid '" + RESULT_PROPERTY + "' or '"
                    + ERROR_PROPERTY + "' field");

            return new Response<>(id, null);
        }
    }
}

From source file:org.kurento.jsonrpc.JsonUtils.java

License:Apache License

@Override
public Request<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (!(json instanceof JsonObject)) {
        throw new JsonParseException(
                "Invalid JsonRpc request showning JsonElement type " + json.getClass().getSimpleName());
    }/*from   w  ww  .j a  va  2  s.c o  m*/

    JsonObject jObject = (JsonObject) json;

    // FIXME: Enable again when KMS sends jsonrpc field in register message
    // if (!jObject.has(JSON_RPC_PROPERTY)) {
    // throw new JsonParseException(
    // "Invalid JsonRpc request lacking version '"
    // + JSON_RPC_PROPERTY + "' field");
    // }
    //
    // if (!jObject.get("jsonrpc").getAsString().equals(JSON_RPC_VERSION)) {
    // throw new JsonParseException("Invalid JsonRpc version");
    // }

    if (!jObject.has(METHOD_PROPERTY)) {
        throw new JsonParseException("Invalid JsonRpc request lacking '" + METHOD_PROPERTY + "' field");
    }

    Integer id = null;
    if (jObject.has(ID_PROPERTY)) {
        id = Integer.valueOf(jObject.get(ID_PROPERTY).getAsInt());
    }

    ParameterizedType parameterizedType = (ParameterizedType) typeOfT;

    return new Request<>(id, jObject.get(METHOD_PROPERTY).getAsString(),
            context.deserialize(jObject.get(PARAMS_PROPERTY), parameterizedType.getActualTypeArguments()[0]));

}

From source file:org.lanternpowered.server.asset.json.AssetRepositoryJsonDeserializer.java

License:MIT License

@Override
public AssetRepository deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final MultiAssetRepository repository = new MultiAssetRepository();
    // The class loader asset repository will always be present,
    // this cannot be overridden, but the assets themselves can
    // be overridden like the minecraft resource pack system
    final ClassLoaderAssetRepository classLoaderAssetRepository = new ClassLoaderAssetRepository(
            this.pluginManager);
    repository.add(classLoaderAssetRepository);
    final LanternClassLoader classLoader = LanternClassLoader.get();
    final Consumer<URL> consumer = url -> {
        Path path = new File(url.getFile()).toPath();
        if (Files.isDirectory(path) && Files.exists(path.resolve("data-packs.info"))) {
            Lantern.getLogger().debug("Registered a data pack asset repository: " + path);
            repository.add(new PacksAssetRepository(this.pluginManager, path));
        } else {//from w  w  w  . j  a  v  a2 s .  co m
            classLoaderAssetRepository.addRepository(path);
        }
    };
    classLoader.getBaseURLs().forEach(consumer);
    classLoader.addBaseURLTracker(consumer);
    final JsonArray array = json.getAsJsonArray();
    for (int i = 0; i < array.size(); i++) {
        final JsonObject obj = array.get(i).getAsJsonObject();
        final String type = obj.get("type").getAsString().toLowerCase(Locale.ENGLISH);
        Path path;
        switch (type) {
        // Currently only directory asset repositories
        case "dir":
        case "directory":
            path = Paths.get(obj.get("path").getAsString());
            Lantern.getLogger().debug("Registered a directory asset repository: " + path);
            repository.add(new DirectoryAssetRepository(this.pluginManager, path));
            break;
        // Also support a directory with data/asset packs
        case "packs":
            path = Paths.get(obj.get("path").getAsString());
            Lantern.getLogger().debug("Registered a data pack asset repository: " + path);
            repository.add(new PacksAssetRepository(this.pluginManager, path));
            break;
        default:
            throw new JsonParseException("Unknown repository type: " + type);
        }
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return repository;
}

From source file:org.lanternpowered.server.text.gson.JsonTextSerializer.java

License:MIT License

@Override
public Text deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonPrimitive()) {
        return context.deserialize(json, LiteralText.class);
    }/*from   w w  w  . j av a  2s. c  om*/
    if (json.isJsonArray()) {
        final Text.Builder builder = Text.builder();
        builder.append(context.<Text[]>deserialize(json, Text[].class));
        return builder.build();
    }
    final JsonObject obj = json.getAsJsonObject();
    if (obj.has(TEXT)) {
        return context.deserialize(json, LiteralText.class);
    } else if (obj.has(TRANSLATABLE)) {
        return context.deserialize(json, TranslatableText.class);
    } else if (obj.has(SCORE_VALUE)) {
        return context.deserialize(json, ScoreText.class);
    } else if (obj.has(SELECTOR)) {
        return context.deserialize(json, SelectorText.class);
    } else {
        throw new JsonParseException("Unknown text format: " + json.toString());
    }
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

public ProvenanceCollection deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        log.info("Cannot deserialize this: " + json);
        throw new JsonParseException("Can only deserialize objects");
    }//from w  w w . ja v a 2 s.  c  om
    JsonObject obj = json.getAsJsonObject();

    ProvenanceCollection col = new ProvenanceCollection();

    JsonElement nodes = obj.get("nodes");
    JsonElement links = obj.get("links");
    JsonElement actors = obj.get("actors");

    if (!nodes.isJsonArray())
        throw new JsonParseException("Missing top-level nodes array");
    if (!links.isJsonArray())
        throw new JsonParseException("Missing top-level links array");
    if (!actors.isJsonArray())
        throw new JsonParseException("Missing top-level actors array");

    JsonArray n = (JsonArray) nodes;
    JsonArray l = (JsonArray) links;
    JsonArray a = (JsonArray) actors;

    for (JsonElement actor : a) {
        if (!actor.isJsonObject())
            throw new JsonParseException("Actors list contains non-object " + actor.toString());

        PLUSActor convertedActor = convertActor((JsonObject) actor);
        // log.info("Adding converted actor " +convertedActor);
        col.addActor(convertedActor);
    }

    for (JsonElement e : n) {
        if (!e.isJsonObject())
            throw new JsonParseException("Node list contains non-object " + e.toString());
        JsonObject o = (JsonObject) e;

        // NPID nodes are dummy stand-ins, and not provenance objects to be added.
        if ("npid".equals(o.get("type").getAsString()))
            continue;

        PLUSObject pobj = convertObject(o, col);
        col.addNode(pobj);
    }

    for (JsonElement linkItem : l) {
        if (!linkItem.isJsonObject())
            throw new JsonParseException("Link list contains non-object " + linkItem.toString());
        JsonObject link = (JsonObject) linkItem;

        if (link == null || link.isJsonNull()) {
            log.warning("Null link; skipping");
            continue;
        } else if (link.get("label") == null) {
            log.warning("Link " + link + " MISSING type");
            continue;
        }

        if (link.get("label") == null || link.get("label").isJsonNull())
            throw new JsonParseException("Missing attribute label on link/edge " + link);
        if (link.get("type") == null || link.get("type").isJsonNull())
            throw new JsonParseException("Missing attribute type on link/edge " + link);

        String label = link.get("label").getAsString();
        String type = link.get("type").getAsString();

        if (PLUSEdge.isProvenanceEdgeType(type) && !"npe".equals(label)) {
            PLUSEdge e = convertEdge(link, col);
            if (e != null)
                col.addEdge(e);
        } else {
            NonProvenanceEdge npe = convertNPE(link);
            if (npe != null)
                col.addNonProvenanceEdge(npe);
        }
    } // End for

    return col;
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

public static PLUSActor convertActor(JsonObject act) throws JsonParseException {
    String id = act.get(JSONConverter.KEY_ID).getAsString();
    String name = act.get(JSONConverter.KEY_NAME).getAsString();
    long created = act.get(JSONConverter.KEY_CREATED).getAsLong();
    String type = act.get(JSONConverter.KEY_TYPE).getAsString();

    if (id == null || "".equals(id))
        throw new JsonParseException("Invalid empty or missing 'id' on actor " + act);
    if (name == null || "".equals(name))
        throw new JsonParseException("Invalid empty or missing 'name' on actor " + act);
    if (created <= 0)
        throw new JsonParseException("Invalid created " + created + " on actor " + act);
    if (type == null || "".equals(type))
        throw new JsonParseException("Invalid empty or missing 'type' on actor " + act);

    if (!"actor".equals(type)) {
        log.warning("At this time, only type='actor' PLUSActors can be converted, but provided JSON presents "
                + type + "; "
                + "this may mean that some information about the object was omitted during conversion.");
    }/*from   ww w  .  j av a2 s . c  om*/

    return new PLUSActor(id, name, created, type);
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

protected static PLUSObject convertObject(JsonObject obj, ProvenanceCollection contextCollection)
        throws JsonParseException {
    String t = obj.get(JSONConverter.KEY_TYPE).getAsString();
    String st = obj.get(JSONConverter.KEY_SUBTYPE).getAsString();
    String name = obj.get(JSONConverter.KEY_NAME).getAsString();

    if (name == null || "null".equals(name))
        throw new JsonParseException("Missing name on object " + obj);
    if (t == null || "null".equals(t))
        throw new JsonParseException("Missing type on object " + obj);
    if (st == null || "null".equals(st))
        throw new JsonParseException("Missing subtype on object " + obj);

    JsonObjectPropertyWrapper n = new JsonObjectPropertyWrapper(obj);

    try {/*w w w.ja v  a2  s.co m*/
        PLUSObject o = null;

        if (PLUSInvocation.PLUS_SUBTYPE_INVOCATION.equals(st)) {
            o = new PLUSInvocation().setProperties(n, contextCollection);
        } else if (PLUSWorkflow.PLUS_TYPE_WORKFLOW.equals(t)) {
            o = new PLUSWorkflow().setProperties(n, contextCollection);
        } else if (st.equals(PLUSString.PLUS_SUBTYPE_STRING)) {
            o = new PLUSString().setProperties(n, contextCollection);
        } else if (PLUSFile.PLUS_SUBTYPE_FILE.equals(st)) {
            o = new PLUSFile().setProperties(n, contextCollection);
        } else if (PLUSFileImage.PLUS_SUBTYPE_FILE_IMAGE.equals(st)) {
            o = new PLUSFileImage().setProperties(n, contextCollection);
        } else if (PLUSURL.PLUS_SUBTYPE_URL.equals(st)) {
            o = new PLUSURL().setProperties(n, contextCollection);
        } else if (PLUSActivity.PLUS_TYPE_ACTIVITY.equals(t)) {
            o = new PLUSActivity().setProperties(n, contextCollection);
        } else if (PLUSRelational.PLUS_SUBTYPE_RELATIONAL.equals(st)) {
            o = new PLUSRelational().setProperties(n, contextCollection);
        } else if (Taint.PLUS_SUBTYPE_TAINT.equals(st)) {
            o = new Taint().setProperties(n, contextCollection);
        } else {
            log.info("Couldn't find more specific type for " + t + "/" + st + " so loading as generic.");
            o = new PLUSGeneric().setProperties(n, contextCollection);
        }

        // Check metadata
        if (obj.has(JSONConverter.KEY_METADATA) && obj.get(JSONConverter.KEY_METADATA).isJsonObject()) {
            JsonObject md = obj.get(JSONConverter.KEY_METADATA).getAsJsonObject();

            Metadata m = new Metadata();

            for (Map.Entry<String, JsonElement> entry : md.entrySet()) {
                String key = entry.getKey();
                String val = null;

                JsonElement v = entry.getValue();
                if (!v.isJsonPrimitive()) {
                    log.warning("Skipping metadata key/value " + key + " => " + v
                            + " because value isn't primitive.");
                    continue;
                } else {
                    val = v.getAsJsonPrimitive().getAsString();
                }

                m.put(key, val);
            } // End for

            o.getMetadata().putAll(m);
        }

        // Check owner status.
        // Property is not guaranteed to be present; if it's present, get it as a string, otherwise use null.
        String aid = (obj.get("ownerid") != null ? obj.get("ownerid").getAsString() : null);

        // log.info("Deserializing " + o + " actorID = " + aid + " and owner=" + obj.get(JSONConverter.KEY_OWNER));
        if (isBlank(aid) && obj.has(JSONConverter.KEY_OWNER)) {
            JsonElement ownerJson = obj.get(JSONConverter.KEY_OWNER);
            if (!ownerJson.isJsonObject())
                throw new JsonParseException("Property 'owner' must be an object on " + obj);

            PLUSActor owner = convertActor((JsonObject) ownerJson);
            if (owner != null) {
                log.info("Set using converted owner property " + owner);
                o.setOwner(owner);
            }
        } else if (!isBlankOrNull(aid)) {
            if (contextCollection.containsActorID(aid)) {
                // log.info("Set using provided context collection " + contextCollection.getActor(aid));
                o.setOwner(contextCollection.getActor(aid));
            } else {
                log.severe("Deserializer cannot find actor by dangling reference " + aid
                        + " - provenance context collection is needed to identify this actor without database access.");
                o.setOwner(null);
            }
        }

        return o;
    } catch (PLUSException exc) {
        exc.printStackTrace();
        throw new JsonParseException(exc.getMessage());
    }
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

protected static NonProvenanceEdge convertNPE(JsonObject obj) throws JsonParseException {
    String from = obj.get(JSONConverter.KEY_FROM).getAsString();
    String to = obj.get(JSONConverter.KEY_TO).getAsString();
    String oid = obj.get(JSONConverter.KEY_NPEID).getAsString();

    // NPEs have a type field=npe to indicate that they're non-provenance edges.
    // The actual type of edge ("md5sum") is stored in the label.
    String type = obj.get(JSONConverter.KEY_LABEL).getAsString();
    long created = obj.get(JSONConverter.KEY_CREATED).getAsLong();

    if (from == null || "null".equals(from))
        throw new JsonParseException("Missing from on NPE " + obj);
    if (to == null || "null".equals(to))
        throw new JsonParseException("Missing to on NPE " + obj);
    if (type == null || "null".equals(type))
        throw new JsonParseException("Missing label on NPE " + obj);
    if (oid == null) {
        log.warning("NPEID mising on " + obj);
        oid = PLUSUtils.generateID();//  w  ww. j  ava  2  s.c om
    }

    try {
        return new NonProvenanceEdge(oid, from, to, type, created);
    } catch (PLUSException exc) {
        exc.printStackTrace();
        throw new JsonParseException(exc.getMessage());
    }
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

protected static PLUSEdge convertEdge(JsonObject obj, ProvenanceCollection col) throws JsonParseException {
    try {//www. j  a v  a2s  . co m
        String from = obj.get("from").getAsString();
        String to = obj.get("to").getAsString();
        String wfid = obj.get("workflow").getAsString();
        String type = obj.get("type").getAsString();

        if (from == null || "null".equals(from))
            throw new JsonParseException("Missing from on edge " + obj);
        if (to == null || "null".equals(to))
            throw new JsonParseException("Missing to on edge " + obj);
        if (type == null || "null".equals(type))
            throw new JsonParseException("Missing type/label on edge " + obj);
        if (wfid == null || "null".equals(wfid))
            wfid = PLUSWorkflow.DEFAULT_WORKFLOW.getId();

        if (!PLUSEdge.isProvenanceEdgeType(type))
            throw new JsonParseException("Edge type " + type + " on edge " + obj + " isn't provenance.");

        PLUSObject fromObj = null, toObj = null;

        try {
            fromObj = resurrect(from, col);
        } catch (PLUSException exc) {
            log.warning("Ignoring edge because of non-existant from ID " + from);
            return null;
        }

        try {
            toObj = resurrect(to, col);
        } catch (PLUSException exc2) {
            log.warning("Ignoring edge because of non-existant to ID " + to);
            return null;
        }

        PLUSWorkflow wf = PLUSWorkflow.DEFAULT_WORKFLOW;

        if (wfid != null && !PLUSWorkflow.DEFAULT_WORKFLOW.getId().equals(wfid)) {
            if (col.containsObjectID(wfid))
                wf = (PLUSWorkflow) col.getNode(wfid);
            else {
                // TODO -- there's a design argument that this should be a fatal error/exception.
                log.severe("Cannot re-load workflow " + wfid
                        + " because it isn't in context provenance collection.  "
                        + "Database lookups are disabled on deserialization.");
                wf = PLUSWorkflow.DEFAULT_WORKFLOW;
            }
        }

        return new PLUSEdge(fromObj, toObj, wf, type);
    } catch (NullPointerException exc) {
        exc.printStackTrace();
        throw new JsonParseException(
                "Edge missing one or more properties of from, to, workflow, label:  " + obj);
    }
}