Search in sources :

Example 16 with JsonParseException

use of com.google.gson.JsonParseException in project GregTech by GregTechCE.

the class MetaItemShapelessRecipeFactory method parse.

@Override
public IRecipe parse(JsonContext context, JsonObject json) {
    String group = JsonUtils.getString(json, "group", "");
    NonNullList<Ingredient> ings = NonNullList.create();
    for (JsonElement ele : JsonUtils.getJsonArray(json, "ingredients")) ings.add(CraftingHelper.getIngredient(ele, context));
    if (ings.isEmpty())
        throw new JsonParseException("No ingredients for shapeless recipe");
    JsonObject result = JsonUtils.getJsonObject(json, "result");
    String name = JsonUtils.getString(result, "name");
    int amount = JsonUtils.getInt(result, "amount", 1);
    ItemStack stack = ItemStack.EMPTY;
    for (MetaItem<?> item : MetaItems.ITEMS) {
        MetaItem<?>.MetaValueItem value = item.getItem(name);
        if (value != null) {
            stack = value.getStackForm(amount);
        }
    }
    return new ShapelessOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), ings, stack);
}
Also used : MetaItem(gregtech.api.items.metaitem.MetaItem) JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException) Ingredient(net.minecraft.item.crafting.Ingredient) JsonElement(com.google.gson.JsonElement) ResourceLocation(net.minecraft.util.ResourceLocation) ShapelessOreRecipe(net.minecraftforge.oredict.ShapelessOreRecipe) ItemStack(net.minecraft.item.ItemStack)

Example 17 with JsonParseException

use of com.google.gson.JsonParseException in project apps-android-wikipedia by wikimedia.

the class WikitextClient method request.

@VisibleForTesting
Call<MwQueryResponse> request(@NonNull Service service, @NonNull final PageTitle title, final int sectionID, @NonNull final Callback cb) {
    Call<MwQueryResponse> call = service.request(title.getPrefixedText(), sectionID);
    call.enqueue(new retrofit2.Callback<MwQueryResponse>() {

        @Override
        public void onResponse(@NonNull Call<MwQueryResponse> call, @NonNull Response<MwQueryResponse> response) {
            // noinspection ConstantConditions
            if (response.body() != null && response.body().success() && response.body().query() != null && response.body().query().firstPage() != null && getRevision(response.body().query()) != null) {
                // noinspection ConstantConditions
                MwQueryPage.Revision rev = getRevision(response.body().query());
                cb.success(call, response.body().query().firstPage().title(), rev.content(), rev.timeStamp());
            } else if (response.body() != null && response.body().hasError()) {
                // noinspection ConstantConditions
                cb.failure(call, new MwException(response.body().getError()));
            } else {
                Throwable t = new JsonParseException("Error parsing wikitext from query response");
                cb.failure(call, t);
            }
        }

        @Override
        public void onFailure(@NonNull Call<MwQueryResponse> call, @NonNull Throwable t) {
            cb.failure(call, t);
        }
    });
    return call;
}
Also used : MwQueryResponse(org.wikipedia.dataclient.mwapi.MwQueryResponse) MwException(org.wikipedia.dataclient.mwapi.MwException) JsonParseException(com.google.gson.JsonParseException) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 18 with JsonParseException

use of com.google.gson.JsonParseException in project java-cloudant by cloudant.

the class Helpers method selectorStringAsJsonObject.

private static JsonObject selectorStringAsJsonObject(String key, String selectorJson) {
    Gson gson = new Gson();
    JsonObject selectorObject = null;
    boolean isObject = true;
    try {
        selectorObject = gson.fromJson(selectorJson, JsonObject.class);
    } catch (JsonParseException e) {
        isObject = false;
    }
    if (!isObject) {
        if (selectorJson.startsWith(key) || selectorJson.startsWith("\"" + key + "\"")) {
            selectorJson = selectorJson.substring(selectorJson.indexOf(":") + 1, selectorJson.length()).trim();
            selectorObject = gson.fromJson(selectorJson, JsonObject.class);
        } else {
            throw new JsonParseException("selectorJson should be valid json or like " + "\"" + key + "\": {...} ");
        }
    }
    return selectorObject;
}
Also used : Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException)

Example 19 with JsonParseException

use of com.google.gson.JsonParseException in project java-cloudant by cloudant.

the class ClientBuilder method bluemix.

/**
 * Sets Cloudant client credentials by inspecting a service information JSON string. This object
 * takes the form of a {@code VCAP_SERVICES} environment variable which is a JSON object that
 * contains information that you can use to interact with a service instance in Bluemix.
 *
 * @param vcapServices service information JSON string, for example the contents of
 *                     {@code VCAP_SERVICES} environment variable
 * @param serviceName name of Bluemix service to use
 * @param instanceName name of Bluemix service instance or {@code null} to try to use the only
 *                    available Cloudant service
 * @return a new ClientBuilder for the account
 *
 * @throws IllegalArgumentException if any of the following conditions are true:
 * <ul>
 *     <li>The {@code vcapServices} is {@code null}.</li>
 *     <li>The {@code serviceName} is {@code null}.</li>
 *     <li>The {@code vcapServices} is not valid.</li>
 *     <li>A service with the name matching {@code serviceName} could not be found in
 *     {@code vcapServices}.</li>
 *     <li>An instance with a name matching {@code instanceName} could not be found in
 *     {@code vcapServices}.</li>
 *     <li>The {@code instanceName} is {@code null} and multiple Cloudant service instances
 *     exist in {@code vcapServices}.</li>
 * </ul>
 */
public static ClientBuilder bluemix(String vcapServices, String serviceName, String instanceName) {
    if (vcapServices == null) {
        throw new IllegalArgumentException("The vcapServices JSON information was null.");
    }
    if (serviceName == null) {
        throw new IllegalArgumentException("No Cloudant services information present.");
    }
    JsonObject obj;
    try {
        obj = (JsonObject) new JsonParser().parse(vcapServices);
    } catch (JsonParseException e) {
        throw new IllegalArgumentException("The vcapServices was not valid JSON.", e);
    }
    Gson gson = new GsonBuilder().create();
    List<CloudFoundryService> cloudantServices = null;
    JsonElement service = obj.get(serviceName);
    if (service != null) {
        Type listType = new TypeToken<ArrayList<CloudFoundryService>>() {
        }.getType();
        cloudantServices = gson.fromJson(service, listType);
    }
    if (cloudantServices == null || cloudantServices.size() == 0) {
        throw new IllegalArgumentException("No Cloudant services information present.");
    }
    if (instanceName == null) {
        if (cloudantServices.size() == 1) {
            CloudFoundryService cloudantService = cloudantServices.get(0);
            if (cloudantService.credentials == null || cloudantService.credentials.url == null) {
                throw new IllegalArgumentException("The Cloudant service instance information was invalid.");
            }
            return ClientBuilder.url(cloudantService.credentials.url);
        } else {
            throw new IllegalArgumentException("Multiple Cloudant service instances present. " + "A service instance name must be specified.");
        }
    }
    for (CloudFoundryService cloudantService : cloudantServices) {
        if (instanceName.equals(cloudantService.name)) {
            if (cloudantService.credentials == null || cloudantService.credentials.url == null) {
                throw new IllegalArgumentException("The Cloudant service instance information was invalid.");
            }
            return ClientBuilder.url(cloudantService.credentials.url);
        }
    }
    throw new IllegalArgumentException(String.format("Cloudant service instance matching name %s was not found.", instanceName));
}
Also used : Type(java.lang.reflect.Type) GsonBuilder(com.google.gson.GsonBuilder) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) CloudFoundryService(com.cloudant.client.internal.util.CloudFoundryService) JsonParseException(com.google.gson.JsonParseException) JsonParser(com.google.gson.JsonParser)

Example 20 with JsonParseException

use of com.google.gson.JsonParseException in project c0debaseBot by Biospheere.

the class UrbandirectoryCommand method execute.

@Override
public void execute(String[] args, Message message) {
    if (args.length < 1) {
        message.getTextChannel().sendMessage(getEmbed(message.getGuild(), message.getAuthor()).setDescription("!ud [term]").build()).queue();
    } else {
        message.getTextChannel().sendTyping().queue();
        final String search = String.join(" ", args);
        final StringWriter writer = new StringWriter();
        try {
            URL url = new URL("http://api.urbandictionary.com/v0/define?term=" + URLEncoder.encode(search, "UTF-8"));
            try (final InputStream inputStream = url.openConnection().getInputStream()) {
                IOUtils.copy(inputStream, writer, "UTF-8");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        EmbedBuilder embedBuilder = getEmbed(message.getGuild(), message.getAuthor());
        embedBuilder.setTitle("Definition: " + search);
        try {
            JsonArray jsonResult = new JsonParser().parse(writer.toString()).getAsJsonObject().getAsJsonArray("list");
            embedBuilder.appendDescription(jsonResult.size() != 0 ? jsonResult.get(0).getAsJsonObject().get("definition").getAsString() : "Search term not found.");
        } catch (JsonParseException ex) {
            embedBuilder.appendDescription("An error occurred.");
        } finally {
            message.getTextChannel().sendMessage(embedBuilder.build()).queue();
        }
    }
}
Also used : JsonArray(com.google.gson.JsonArray) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) JsonParseException(com.google.gson.JsonParseException) URL(java.net.URL) JsonParseException(com.google.gson.JsonParseException) JsonParser(com.google.gson.JsonParser)

Aggregations

JsonParseException (com.google.gson.JsonParseException)210 JsonObject (com.google.gson.JsonObject)81 JsonElement (com.google.gson.JsonElement)55 IOException (java.io.IOException)54 Gson (com.google.gson.Gson)34 InputStreamReader (java.io.InputStreamReader)24 JsonArray (com.google.gson.JsonArray)21 InputStream (java.io.InputStream)20 GsonBuilder (com.google.gson.GsonBuilder)18 JsonParser (com.google.gson.JsonParser)18 JsonPrimitive (com.google.gson.JsonPrimitive)18 Type (java.lang.reflect.Type)17 Map (java.util.Map)17 JsonReader (com.google.gson.stream.JsonReader)16 ArrayList (java.util.ArrayList)14 HttpUrl (okhttp3.HttpUrl)13 Request (okhttp3.Request)13 Response (okhttp3.Response)13 JsonSyntaxException (com.google.gson.JsonSyntaxException)10 SocketTimeoutException (java.net.SocketTimeoutException)8