Search in sources :

Example 31 with JsonParseException

use of com.google.gson.JsonParseException in project DevRing by LJYcoder.

the class ExceptionHandler method handleException.

public static ResponseThrowable handleException(Throwable e) {
    ResponseThrowable responseThrowable;
    // Log.i("tag", "e.toString = " + e.toString());
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        responseThrowable = new ResponseThrowable(e, ERROR.HTTP_ERROR);
        switch(httpException.code()) {
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            default:
                responseThrowable.code = httpException.code();
                responseThrowable.message = "网络错误";
                break;
        }
        return responseThrowable;
    } else if (e instanceof ServerException) {
        ServerException resultException = (ServerException) e;
        responseThrowable = new ResponseThrowable(resultException, resultException.code);
        responseThrowable.message = resultException.message;
        return responseThrowable;
    } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
        responseThrowable = new ResponseThrowable(e, ERROR.PARSE_ERROR);
        responseThrowable.message = "解析错误";
        return responseThrowable;
    } else if (e instanceof ConnectException) {
        responseThrowable = new ResponseThrowable(e, ERROR.CONNECT_ERROR);
        responseThrowable.message = "连接失败";
        return responseThrowable;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        responseThrowable = new ResponseThrowable(e, ERROR.SSL_ERROR);
        responseThrowable.message = "证书验证失败";
        return responseThrowable;
    } else {
        responseThrowable = new ResponseThrowable(e, ERROR.UNKNOWN);
        responseThrowable.message = "未知错误";
        return responseThrowable;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(android.net.ParseException) JsonParseException(com.google.gson.JsonParseException) ConnectException(java.net.ConnectException)

Example 32 with JsonParseException

use of com.google.gson.JsonParseException in project Wizardry by TeamWizardry.

the class RecipeShapelessFluidFactory method parse.

@Override
public IRecipe parse(JsonContext context, JsonObject json) {
    String group = JsonUtils.getString(json, "group", "");
    NonNullList<Ingredient> ingredients = NonNullList.create();
    for (JsonElement element : JsonUtils.getJsonArray(json, "ingredients")) ingredients.add(CraftingHelper.getIngredient(element, context));
    if (ingredients.isEmpty())
        throw new JsonParseException("No ingredients in shapeless recipe");
    ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
    RecipeShapelessFluid recipe = new RecipeShapelessFluid(group.isEmpty() ? null : new ResourceLocation(group), result, ingredients);
    return recipe;
}
Also used : Ingredient(net.minecraft.item.crafting.Ingredient) JsonElement(com.google.gson.JsonElement) ResourceLocation(net.minecraft.util.ResourceLocation) JsonParseException(com.google.gson.JsonParseException) ItemStack(net.minecraft.item.ItemStack)

Example 33 with JsonParseException

use of com.google.gson.JsonParseException in project Wizardry by TeamWizardry.

the class FireRecipeLoader method processRecipes.

public void processRecipes(Map<Ingredient, FireRecipe> recipes) {
    Wizardry.logger.info("<<========================================================================>>");
    Wizardry.logger.info("> Starting fire recipe loading.");
    JsonContext context = new JsonContext("minecraft");
    LinkedList<File> recipeFiles = new LinkedList<>();
    Stack<File> toProcess = new Stack<>();
    toProcess.push(directory);
    while (!toProcess.isEmpty()) {
        File file = toProcess.pop();
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null)
                for (File child : children) toProcess.push(child);
        } else if (file.isFile())
            if (file.getName().endsWith(".json"))
                recipeFiles.add(file);
    }
    for (File file : recipeFiles) {
        try {
            if (!file.exists()) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
                continue;
            }
            JsonElement element;
            try {
                element = new JsonParser().parse(new FileReader(file));
            } catch (FileNotFoundException e) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
                continue;
            }
            if (element == null) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! Could not parse " + file.getPath() + ". Ignoring file...");
                continue;
            }
            if (!element.isJsonObject()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT contain a JsonObject. Ignoring file...: " + element.toString());
                continue;
            }
            JsonObject fileObject = element.getAsJsonObject();
            int duration = 200;
            if (!fileObject.has("input")) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide an initial input item. Ignoring file...: " + element.toString());
                continue;
            }
            JsonElement inputObject = fileObject.get("input");
            Ingredient input = CraftingHelper.getIngredient(inputObject, context);
            if (input == Ingredient.EMPTY) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid input. Ignoring file...: " + element.toString());
                continue;
            }
            if (!fileObject.has("output")) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT specify a recipe output. Ignoring file...: " + element.toString());
                continue;
            }
            if (!fileObject.get("output").isJsonObject()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
                continue;
            }
            JsonObject outputObject = fileObject.get("output").getAsJsonObject();
            ItemStack output = CraftingHelper.getItemStack(outputObject, context);
            if (output.isEmpty()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
                continue;
            }
            if (fileObject.has("duration")) {
                if (!fileObject.get("duration").isJsonPrimitive() || !fileObject.getAsJsonPrimitive("duration").isNumber()) {
                    Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT give duration as a number. Ignoring file...:" + element.toString());
                    continue;
                }
                duration = fileObject.get("duration").getAsInt();
            }
            recipes.put(input, new FireRecipe(output, duration));
        } catch (JsonParseException jsonException) {
            Wizardry.logger.error("  > WARNING! Skipping " + file.getPath() + " due to error: ", jsonException);
        }
    }
    Wizardry.logger.info("> Finished fire recipe loading.");
    Wizardry.logger.info("<<========================================================================>>");
}
Also used : FileNotFoundException(java.io.FileNotFoundException) JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException) LinkedList(java.util.LinkedList) Stack(java.util.Stack) ItemStack(net.minecraft.item.ItemStack) JsonContext(net.minecraftforge.common.crafting.JsonContext) Ingredient(net.minecraft.item.crafting.Ingredient) JsonElement(com.google.gson.JsonElement) FileReader(java.io.FileReader) ItemStack(net.minecraft.item.ItemStack) File(java.io.File) JsonParser(com.google.gson.JsonParser)

Example 34 with JsonParseException

use of com.google.gson.JsonParseException in project smarthome by eclipse.

the class TradfriGatewayHandler method obtainIdentityAndPreSharedKey.

/**
 * Authenticates against the gateway with the security code in order to receive a pre-shared key for a newly
 * generated identity.
 * As this requires a remote request, this method might be long-running.
 *
 * @return true, if credentials were successfully obtained, false otherwise
 */
protected boolean obtainIdentityAndPreSharedKey() {
    TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
    String identity = UUID.randomUUID().toString().replace("-", "");
    String preSharedKey = null;
    CoapResponse gatewayResponse;
    String authUrl = null;
    String responseText = null;
    try {
        DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
        builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
        DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
        CoapEndpoint authEndpoint = new CoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
        authUrl = "coaps://" + configuration.host + ":" + configuration.port + "/15011/9063";
        CoapClient deviceClient = new CoapClient(new URI(authUrl));
        deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
        deviceClient.setEndpoint(authEndpoint);
        JsonObject json = new JsonObject();
        json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
        gatewayResponse = deviceClient.post(json.toString(), 0);
        authEndpoint.destroy();
        deviceClient.shutdown();
        if (gatewayResponse == null) {
            // seems we ran in a timeout, which potentially also happens
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "No response from gateway. Might be due to an invalid security code.");
            return false;
        }
        if (gatewayResponse.isSuccess()) {
            responseText = gatewayResponse.getResponseText();
            json = new JsonParser().parse(responseText).getAsJsonObject();
            preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
            if (isNullOrEmpty(preSharedKey)) {
                logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(), configuration.host);
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Pre-shared key was not obtain successfully");
                return false;
            } else {
                logger.info("Received pre-shared key for gateway '{}'", configuration.host);
                logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
                Configuration editedConfig = editConfiguration();
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_CODE, null);
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, identity);
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, preSharedKey);
                updateConfiguration(editedConfig);
                return true;
            }
        } else {
            logger.warn("Failed obtaining pre-shared key for identity '{}' (response code '{}', response text '{}')", identity, gatewayResponse.getCode(), isNullOrEmpty(gatewayResponse.getResponseText()) ? "<empty>" : gatewayResponse.getResponseText());
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Failed obtaining pre-shared key with status code '%s'", gatewayResponse.getCode()));
        }
    } catch (URISyntaxException e) {
        logger.error("Illegal gateway URI '{}'", authUrl, e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
    } catch (JsonParseException e) {
        logger.warn("Invalid response recieved from gateway '{}'", responseText, e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Invalid response recieved from gateway '%s'", responseText));
    }
    return false;
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) Configuration(org.eclipse.smarthome.config.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) JsonObject(com.google.gson.JsonObject) URISyntaxException(java.net.URISyntaxException) JsonParseException(com.google.gson.JsonParseException) URI(java.net.URI) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) CoapClient(org.eclipse.californium.core.CoapClient) TradfriCoapClient(org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapClient) StaticPskStore(org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore) TradfriGatewayConfig(org.eclipse.smarthome.binding.tradfri.internal.config.TradfriGatewayConfig) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) TradfriCoapEndpoint(org.eclipse.smarthome.binding.tradfri.internal.TradfriCoapEndpoint) JsonParser(com.google.gson.JsonParser)

Example 35 with JsonParseException

use of com.google.gson.JsonParseException in project bitflyer4j by after-the-sunrise.

the class GsonProviderTest method testGet_ZonedDateTime.

@Test
public void testGet_ZonedDateTime() throws Exception {
    ZonedDateTime result = gson.fromJson("null", ZonedDateTime.class);
    assertNull(result);
    result = gson.fromJson("\"2017-04-14T12:34:56.78\"", ZonedDateTime.class);
    assertEquals(result.getZone().getId(), "GMT");
    assertEquals(result.getYear(), 2017);
    assertEquals(result.getMonthValue(), 4);
    assertEquals(result.getDayOfMonth(), 14);
    assertEquals(result.getHour(), 12);
    assertEquals(result.getMinute(), 34);
    assertEquals(result.getSecond(), 56);
    assertEquals(result.getNano(), 780 * 1000L * 1000L);
    result = gson.fromJson("\"2017-04-14T12:34:56.7890123Z\"", ZonedDateTime.class);
    assertEquals(result.getZone().getId(), "GMT");
    assertEquals(result.getYear(), 2017);
    assertEquals(result.getMonthValue(), 4);
    assertEquals(result.getDayOfMonth(), 14);
    assertEquals(result.getHour(), 12);
    assertEquals(result.getMinute(), 34);
    assertEquals(result.getSecond(), 56);
    assertEquals(result.getNano(), 789_012_300);
    assertNull(gson.fromJson("null", ZonedDateTime.class));
    assertNull(gson.fromJson("\"\"", ZonedDateTime.class));
    try {
        gson.fromJson("\"foo\"", ZonedDateTime.class);
        fail();
    } catch (JsonParseException e) {
    // Success
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JsonParseException(com.google.gson.JsonParseException) Test(org.testng.annotations.Test)

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