Example usage for com.google.gson JsonElement isJsonNull

List of usage examples for com.google.gson JsonElement isJsonNull

Introduction

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

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

public static boolean getBoolVal(JsonElement json) {
    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }//from  w  w w .  j  a  va  2  s .c o m

    if (!json.isJsonPrimitive()) {
        throw new JsonSyntaxException("Expected value to be a primitive");
    }

    return json.getAsBoolean();
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

@Nonnull
public static ItemStack getItemStack(JsonElement json) {
    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }/*from w w  w. j  a va2s.  com*/

    if (json.isJsonArray()) {
        throw new JsonSyntaxException("Expected value to be an object, not an array");
    }

    if (!json.isJsonObject()) {
        throw new JsonSyntaxException("Expcted value to be an object");
    }

    return getStack((JsonObject) json);
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

@Nonnull
public static NonNullList<ItemStack> getItemStacks(JsonElement json) {
    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }//w  w  w .ja  va 2s.  c o m

    return getStacks(json);
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

private static NonNullList<ItemStack> getStacks(JsonElement json) {
    NonNullList<ItemStack> items = NonNullList.create();

    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }// www. j  a v a 2s.  c  om

    if (json.isJsonArray()) {
        json.getAsJsonArray().forEach(elem -> {
            if (elem != null && elem.isJsonObject()) {
                items.addAll(getStacks(elem));
            } else {
                throw new JsonSyntaxException("Expcted stack to be an object");
            }
        });
    } else if (json.isJsonObject()) {
        JsonObject jsonObj = json.getAsJsonObject();

        if (jsonObj.has("type")
                && MiscUtils.defIfNull(jsonObj.get("type").getAsString(), "").equals("forge:ore_dict")) {
            String oredictName = jsonObj.get("ore").getAsString();
            items.addAll(OreDictionary.getOres(oredictName).stream().map(ItemStack::copy)
                    .collect(Collectors.toList()));
        } else {
            items.add(getStack(jsonObj));
        }
    } else {
        throw new JsonSyntaxException("Expected stack(s) to be an object or an array of objects");
    }

    return items;
}

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;
    }// w ww . j  a v  a  2 s .  c om

    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:de.symeda.sormas.app.rest.RetroProvider.java

License:Open Source License

private RetroProvider(Context context)
        throws ServerConnectionException, ServerCommunicationException, ApiVersionException {

    lastConnectionId = this.hashCode();

    this.context = context;

    RuntimeTypeAdapterFactory<ClassificationCriteriaDto> classificationCriteriaFactory = RuntimeTypeAdapterFactory
            .of(ClassificationCriteriaDto.class, "type")
            .registerSubtype(ClassificationAllOfCriteriaDto.class, "ClassificationAllOfCriteriaDto")
            .registerSubtype(ClassificationCaseCriteriaDto.class, "ClassificationCaseCriteriaDto")
            .registerSubtype(ClassificationNoneOfCriteriaDto.class, "ClassificationNoneOfCriteriaDto")
            .registerSubtype(ClassificationPersonAgeBetweenYearsCriteriaDto.class,
                    "ClassificationPersonAgeBetweenYearsCriteriaDto")
            .registerSubtype(ClassificationPathogenTestPositiveResultCriteriaDto.class,
                    "ClassificationPathogenTestPositiveResultCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.class, "ClassificationXOfCriteriaDto")
            .registerSubtype(ClassificationEpiDataCriteriaDto.class, "ClassificationEpiDataCriteriaDto")
            .registerSubtype(ClassificationNotInStartDateRangeCriteriaDto.class,
                    "ClassificationNotInStartDateRangeCriteriaDto")
            .registerSubtype(ClassificationSymptomsCriteriaDto.class, "ClassificationSymptomsCriteriaDto")
            .registerSubtype(ClassificationPathogenTestCriteriaDto.class,
                    "ClassificationPathogenTestCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.ClassificationXOfSubCriteriaDto.class,
                    "ClassificationXOfSubCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.ClassificationOneOfCompactCriteriaDto.class,
                    "ClassificationOneOfCompactCriteriaDto")
            .registerSubtype(ClassificationAllOfCriteriaDto.ClassificationAllOfCompactCriteriaDto.class,
                    "ClassificationAllOfCompactCriteriaDto");

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonNull()) {
                return null;
            }//from   w ww . j  av a  2s.c o m
            long milliseconds = json.getAsLong();
            return new Date(milliseconds);
        }
    }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            if (src == null) {
                return JsonNull.INSTANCE;
            }
            return new JsonPrimitive(src.getTime());
        }
    }).registerTypeAdapterFactory(classificationCriteriaFactory).create();

    // Basic auth as explained in https://futurestud.io/tutorials/android-basic-authentication-with-retrofit

    String authToken = Credentials.basic(ConfigProvider.getUsername(), ConfigProvider.getPassword());
    AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.connectTimeout(20, TimeUnit.SECONDS);
    httpClient.readTimeout(60, TimeUnit.SECONDS); // for infrastructure data
    httpClient.writeTimeout(30, TimeUnit.SECONDS);

    // adds "Accept-Encoding: gzip" by default
    httpClient.addInterceptor(interceptor);

    // header for logging purposes
    httpClient.addInterceptor(chain -> {

        Request original = chain.request();
        Request.Builder builder = original.newBuilder();

        User user = ConfigProvider.getUser();
        if (user != null) {
            builder.header("User", DataHelper.getShortUuid(user.getUuid()));
            builder.header("Connection", String.valueOf(lastConnectionId)); // not sure if this is a good solution
        }

        builder.method(original.method(), original.body());
        return chain.proceed(builder.build());
    });

    retrofit = new Retrofit.Builder().baseUrl(ConfigProvider.getServerRestUrl())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();

    checkCompatibility();

    updateLocale();
}

From source file:donky.microsoft.aspnet.signalr.client.transport.NegotiationResponse.java

License:Open Source License

/**
 * Initializes the negotiation response with Json data
 * //from   w  w w  .java 2 s.  c o m
 * @param jsonContent
 *            Json data
 */
public NegotiationResponse(String jsonContent, JsonParser parser) {
    if (jsonContent == null || "".equals(jsonContent)) {
        return;
    }

    JsonObject json = parser.parse(jsonContent).getAsJsonObject();

    setConnectionId(json.get("ConnectionId").getAsString());
    setConnectionToken(json.get("ConnectionToken").getAsString());
    setUrl(json.get("Url").getAsString());
    setProtocolVersion(json.get("ProtocolVersion").getAsString());
    setDisconnectTimeout(json.get("DisconnectTimeout").getAsDouble());
    setTryWebSockets(json.get("TryWebSockets").getAsBoolean());

    JsonElement keepAliveElement = json.get("KeepAliveTimeout");
    if (keepAliveElement != null && !keepAliveElement.isJsonNull()) {
        setKeepAliveTimeout(keepAliveElement.getAsDouble());
    } else {
        setKeepAliveTimeout(INVALID_KEEP_ALIVE_TIMEOUT);
    }

}

From source file:edu.cmu.sv.trailscribe.controller.SynchronizationCenterController.java

License:MIT License

@Override
public void onTaskCompleted(String syncResult) {
    if (mBackendFacade != null) {
        mBackendFacade.cancel(true);//from  ww w .ja v a2 s .  co m
    }
    ArrayList<SyncItem> itemsToSync = null;

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(syncResult);

    // Unless there is an error in the communication, jsonElement should not be null
    if (!jsonElement.isJsonNull()) {
        JsonArray syncResultJson = (JsonArray) jsonParser.parse(syncResult);
        itemsToSync = new ArrayList<SyncItem>();
        for (JsonElement item : syncResultJson) {
            String model = item.getAsJsonObject().get("model").getAsString();
            JsonObject syncItemJsonArray = item.getAsJsonObject().get("fields").getAsJsonObject();

            // Parsing maps and kmls differently given their attributes are not quite the same
            if (model.equals("sync_center.map")) {
                itemsToSync.add(parseMapInformation(item, syncItemJsonArray));
            } else if (model.equals("sync_center.kml")) {
                itemsToSync.add(parseKmlInformation(item, syncItemJsonArray));
            }
        }
    }
    mTaskCompletedCallback.onTaskCompleted(itemsToSync);
}

From source file:edu.mit.media.funf.probe.builtin.SensorProbe.java

License:Open Source License

protected int getSensorDelay(String specifiedSensorDelay) {
    int sensorDelay = -1;
    JsonElement el = getGson().toJsonTree(specifiedSensorDelay);
    if (!el.isJsonNull()) {
        try {/*from www. j  a  va  2s. co m*/
            int sensorDelayInt = el.getAsInt();
            if (sensorDelayInt == SensorManager.SENSOR_DELAY_FASTEST
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_GAME
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_UI
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_NORMAL) {
                sensorDelay = sensorDelayInt;
            }
        } catch (NumberFormatException e) {
        } catch (ClassCastException e) {
        } catch (IllegalStateException e) {
        }
    }

    if (sensorDelay < 0) {
        try {
            String sensorDelayString = el.getAsString().toUpperCase().replace("SENSOR_DELAY_", "");
            if (SENSOR_DELAY_FASTEST.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
            } else if (SENSOR_DELAY_GAME.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_GAME;
            } else if (SENSOR_DELAY_UI.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_UI;
            } else if (SENSOR_DELAY_NORMAL.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_NORMAL;
            }
        } catch (ClassCastException cce) {
            Log.w(LogUtil.TAG, "Unknown sensor delay value: " + specifiedSensorDelay);
        }
    }

    if (sensorDelay < 0) {
        sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
    }

    return sensorDelay;
}

From source file:eu.betaas.service.bigdatamanager.dataservice.database.services.impl.DatabaseBDMService.java

License:Apache License

private String getNormalizedValue(JsonElement input) {
    if (input == null)
        return "null";
    if (input.isJsonNull())
        return "null";
    return input.getAsString();
}