Example usage for com.google.gson JsonSyntaxException JsonSyntaxException

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

Introduction

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

Prototype

public JsonSyntaxException(Throwable cause) 

Source Link

Document

Creates exception with the specified cause.

Usage

From source file:de.sanandrew.mods.turretmod.registry.assembly.TurretAssemblyRecipes.java

License:Creative Commons License

@SuppressWarnings("RedundantThrows")
private static boolean registerJsonRecipes(JsonObject json, final ITurretAssemblyRegistry registry)
        throws JsonParseException, IOException {
    String id = JsonUtils.getStringVal(json.get("id"));
    String group = JsonUtils.getStringVal(json.get("group"));
    int fluxPerTick = JsonUtils.getIntVal(json.get("fluxPerTick"));
    int ticksProcessing = JsonUtils.getIntVal(json.get("ticksProcessing"));
    ItemStack result = JsonUtils.getItemStack(json.get("result"));

    JsonElement ingredients = json.get("ingredients");
    if (!ingredients.isJsonArray()) {
        throw new JsonSyntaxException("Ingredients must be an array");
    }/*from  ww w . j a va  2s.com*/
    List<IRecipeEntry> entries = new ArrayList<>();
    ingredients.getAsJsonArray().forEach(elem -> {
        if (elem != null && elem.isJsonObject()) {
            JsonObject elemObj = elem.getAsJsonObject();
            int count = JsonUtils.getIntVal(elemObj.get("count"));
            boolean showTooltipText = JsonUtils.getBoolVal(elemObj.get("showTooltipText"), false);
            NonNullList<ItemStack> items = JsonUtils.getItemStacks(elemObj.get("items"));

            int sz = items.size();
            if (sz > 0) {
                IRecipeEntry entry = new RecipeEntry(count).put(items.toArray(new ItemStack[sz]));
                if (showTooltipText) {
                    entry.drawTooltip();
                }

                entries.add(entry);
            }
        }
    });

    return registry.registerRecipe(UUID.fromString(id), registry.getGroup(group), result, fluxPerTick,
            ticksProcessing, entries.toArray(new IRecipeEntry[entries.size()]));
}

From source file:de.sanandrew.mods.turretmod.registry.electrolytegen.ElectrolyteRegistry.java

License:Creative Commons License

private static boolean processJson(Path root, Path file) {
    if (!"json".equals(FilenameUtils.getExtension(file.toString()))
            || root.relativize(file).toString().startsWith("_")) {
        return true;
    }/*from  w w  w  .j  a v a2  s  . co  m*/

    try (BufferedReader reader = Files.newBufferedReader(file)) {
        JsonObject json = JsonUtils.fromJson(reader, JsonObject.class);

        if (json == null || json.isJsonNull()) {
            throw new JsonSyntaxException("Json cannot be null");
        }

        NonNullList<ItemStack> inputItems = JsonUtils.getItemStacks(json.get("electrolytes"));
        float effectiveness = JsonUtils.getFloatVal(json.get("effectiveness"));
        int ticksProcessing = JsonUtils.getIntVal(json.get("timeProcessing"));
        ItemStack trash = ItemStackUtils.getEmpty();
        ItemStack treasure = ItemStackUtils.getEmpty();

        JsonElement elem = json.get("trash");
        if (elem != null && !elem.isJsonNull()) {
            trash = JsonUtils.getItemStack(elem);
        }
        elem = json.get("treasure");
        if (elem != null && !elem.isJsonNull()) {
            treasure = JsonUtils.getItemStack(elem);
        }

        registerFuels(inputItems, effectiveness, ticksProcessing, trash, treasure);
    } catch (JsonParseException e) {
        TmrConstants.LOG.log(Level.ERROR,
                String.format("Parsing error loading electrolyte generator recipe from %s", file), e);
        return false;
    } catch (IOException e) {
        TmrConstants.LOG.log(Level.ERROR, String.format("Couldn't read recipe from %s", file), e);
        return false;
    }

    return true;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.base.PersistentObjectFactory.java

License:Open Source License

/**
 * Sets any other data to attach to the target object.
 * @param otherData the {@link String} representing any other data (must be valid JSON).
 * @return the {@code this} object./*  w ww. j ava 2  s.c  o  m*/
 * @throws IllegalArgumentException when the argument cannot be parsed as a JSON object.
 */
public PersistentObjectFactory<T> setOtherData(String otherData) {
    if (otherData != null) {
        try {
            if (!new JsonParser().parse(otherData).isJsonObject()) {
                throw new JsonSyntaxException("");
            }
        } catch (JsonSyntaxException e) {
            throw new IllegalArgumentException("argument 'otherData' must be valid JSON", e);
        }
    }

    this.otherData = otherData;
    return this;
}

From source file:eu.freme.eservices.pipelines.serialization.Serializer.java

License:Apache License

/**
 * Converts a JSON string to a list of requests.
 * @param serializedRequests   The JSON string of requests to convert.
 * @return                  The list of requests represented by the JSON string.
 * @throws JsonSyntaxException    Something is wrong with the JSON syntax.
 *//*from   w  ww.  j  av  a 2s.co  m*/
@SuppressWarnings("unused")
public static List<SerializedRequest> fromJson(final String serializedRequests) {
    checkOnRequestsMembers(serializedRequests);
    SerializedRequest[] requests = gson.fromJson(serializedRequests, SerializedRequest[].class);
    for (int reqNr = 0; reqNr < requests.length; reqNr++) {
        String invalid = requests[reqNr].isValid();
        if (!invalid.isEmpty()) {
            throw new JsonSyntaxException("Request " + (reqNr + 1) + ": " + invalid);
        }
    }
    return Arrays.asList(requests);
}

From source file:eu.freme.eservices.pipelines.serialization.Serializer.java

License:Apache License

/**
 * Converts a JSON string into an object containing pipeline template information.
 * @param pipelineTemplate    A JSON string representing the pipeline template.
 * @return               The pipeline template info object.
 * @throws JsonSyntaxException   Something is wrong with the JSON syntax.   .
 *//*w  ww  .  ja v  a  2 s  .c  o  m*/
@SuppressWarnings("unused")
public static Pipeline templateFromJson(final String pipelineTemplate) {
    checkOnPipelineMembers(pipelineTemplate);
    Pipeline pipeline = gson.fromJson(pipelineTemplate, Pipeline.class);
    checkOnRequestsMembers(toJson(pipeline.getSerializedRequests()));
    String invalid = pipeline.isValid();
    if (!invalid.isEmpty()) {
        throw new JsonSyntaxException(invalid);
    }
    return gson.fromJson(pipelineTemplate, Pipeline.class);
}

From source file:eu.freme.eservices.pipelines.serialization.Serializer.java

License:Apache License

/**
 * Checks if all fields in the JSON string are valid field names of the {@link SerializedRequest} class. Throws an
 * exception if not valid.//ww  w.j  ava 2s  .com
 * @param serializedRequests   The JSON string to check; it should represent a list of {@link SerializedRequest} objects.
 * @throws JsonSyntaxException   A field is not recognized.
 */
private static void checkOnRequestsMembers(final String serializedRequests) {
    Object serReqObj = gson.fromJson(serializedRequests, Object.class);
    if (!(serReqObj instanceof ArrayList)) {
        throw new JsonSyntaxException("Expected an array of requests");
    }
    ArrayList<LinkedTreeMap> requests = (ArrayList<LinkedTreeMap>) serReqObj;
    for (int reqNr = 0; reqNr < requests.size(); reqNr++) {
        LinkedTreeMap map = requests.get(reqNr);
        for (Object o : map.keySet()) {
            String fieldName = (String) o;
            if (!requestFieldNames.contains(fieldName)) {
                throw new JsonSyntaxException(
                        "request " + (reqNr + 1) + ": field \"" + fieldName + "\" not known.");
            }
        }
    }
}

From source file:eu.freme.eservices.pipelines.serialization.Serializer.java

License:Apache License

private static void checkOnPipelineMembers(final String pipeline) {
    LinkedTreeMap<String, String> pipelineObject = (LinkedTreeMap<String, String>) gson.fromJson(pipeline,
            Object.class);
    for (String fieldName : pipelineObject.keySet()) {
        if (!pipelineFieldNames.contains(fieldName)) {
            throw new JsonSyntaxException("field \"" + fieldName + "\" not known.");
        }//  w w  w . j av a 2s.co m
    }
}

From source file:in.mtap.iincube.mongoser.codec.JsonArrayDecoder.java

License:Apache License

private JsonElement extractData(String jsonString) throws JsonSyntaxException {
    JsonElement element = parser.parse(jsonString);
    if (!element.isJsonArray() && !element.isJsonObject())
        throw new JsonSyntaxException("Not a valid json");
    return element;
}

From source file:io.vertigo.vega.engines.webservice.json.UiObjectDeserializer.java

License:Apache License

/** {@inheritDoc} */
@Override/*from   w  ww.  j  a v a2  s. c o m*/
public UiObject<D> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) {
    final Type[] typeParameters = ((ParameterizedType) typeOfT).getActualTypeArguments();
    final Class<D> dtoClass = (Class<D>) typeParameters[0]; // Id has only one parameterized type T
    final JsonObject jsonObject = json.getAsJsonObject();
    final D inputDto = context.deserialize(jsonObject, dtoClass);
    final DtDefinition dtDefinition = DtObjectUtil.findDtDefinition(dtoClass);
    final Set<String> dtFields = getFieldNames(dtDefinition);
    final Set<String> modifiedFields = new HashSet<>();
    for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        final String fieldName = entry.getKey();
        if (dtFields.contains(fieldName)) { //we only keep fields of this dtObject
            modifiedFields.add(fieldName);
        }
    }
    //Send a alert if no fields match the DtObject ones : details may be a security issue ?
    if (modifiedFields.isEmpty()) {
        final Set<String> jsonEntry = new HashSet<>();
        for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            jsonEntry.add(entry.getKey());
        }
        throw new JsonSyntaxException(
                "Received Json's fields doesn't match " + dtoClass.getSimpleName() + " ones : " + jsonEntry);
    }
    final UiObject<D> uiObject = new VegaUiObject<>(inputDto, modifiedFields);
    if (jsonObject.has(JsonEngine.SERVER_SIDE_TOKEN_FIELDNAME)) {
        uiObject.setServerSideToken(jsonObject.get(JsonEngine.SERVER_SIDE_TOKEN_FIELDNAME).getAsString());
    }
    return uiObject;
}

From source file:net.daporkchop.toobeetooteebot.text.JsonUtils.java

License:Open Source License

/**
 * Gets the string value of the given JsonElement.  Expects the second parameter to be the name of the element's
 * field if an error message needs to be thrown.
 *///  ww  w  .  j  av  a 2s. c om
public static String getString(JsonElement json, String memberName) {
    if (json.isJsonPrimitive()) {
        return json.getAsString();
    } else {
        throw new JsonSyntaxException("Expected " + memberName + " to be a string, was " + toString(json));
    }
}