Example usage for com.google.gson JsonElement getAsInt

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

Introduction

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

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

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

License:Open Source License

/**
 * Gets the integer 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  a  va2  s .com
public static int getInt(JsonElement json, String memberName) {
    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
        return json.getAsInt();
    } else {
        throw new JsonSyntaxException("Expected " + memberName + " to be a Int, was " + toString(json));
    }
}

From source file:net.daporkchop.toobeetooteebot.util.Config.java

License:Open Source License

public int getInt(String key, int def) {
    JsonElement element = this.get(key);
    if (element == null) {
        return this.set(key, def).getAsInt();
    } else {//from   w  ww  .  jav a  2s  .c  om
        return element.getAsInt();
    }
}

From source file:net.doubledoordev.backend.util.TypeHellhole.java

License:Open Source License

public static void set(Field field, Object object, JsonElement value) throws Exception {
    if (field.getType() == byte.class)
        field.setByte(object, value.getAsByte());
    else if (field.getType() == short.class)
        field.setShort(object, value.getAsShort());
    else if (field.getType() == int.class)
        field.setInt(object, value.getAsInt());
    else if (field.getType() == long.class)
        field.setLong(object, value.getAsLong());
    else if (field.getType() == float.class)
        field.setFloat(object, value.getAsFloat());
    else if (field.getType() == double.class)
        field.setDouble(object, value.getAsDouble());
    else if (field.getType() == boolean.class)
        field.setBoolean(object, value.getAsBoolean());
    else if (field.getType() == char.class)
        field.setChar(object, value.getAsCharacter());
    ///*w ww. j a  va 2  s .c om*/
    else if (field.getType() == Byte.class)
        field.set(object, value.getAsByte());
    else if (field.getType() == Short.class)
        field.set(object, value.getAsShort());
    else if (field.getType() == Integer.class)
        field.set(object, value.getAsInt());
    else if (field.getType() == Long.class)
        field.set(object, value.getAsLong());
    else if (field.getType() == Float.class)
        field.set(object, value.getAsFloat());
    else if (field.getType() == Double.class)
        field.set(object, value.getAsDouble());
    else if (field.getType() == Boolean.class)
        field.set(object, value.getAsBoolean());
    else if (field.getType() == Character.class)
        field.set(object, value.getAsCharacter());
    //
    else if (field.getType() == String.class)
        field.set(object, value.getAsString());
    else {
        String m = String.format("Unknown type! Field type: %s Json value: %s Data class: %s", field.getType(),
                value.toString(), object.getClass().getSimpleName());
        Main.LOGGER.error(m);
        throw new Exception(m);
    }
}

From source file:net.oneandone.stool.SystemImport.java

License:Apache License

private Patch stoolConfig() throws IOException {
    String current;/* w ww.j a  va2 s.  co m*/
    final String path = "config.json";
    final FileNode dest;
    final String result;
    String diff;

    dest = session.home.join(path);
    current = dest.readString();
    result = mergeConfig(oldHome.join(path).readString(), current, new Object() {
        void sharedBinRemove() {
        }

        void versionRemove() {
        }

        void stagesRemove() {
        }

        // because values are all-strings no (e.g. in tomcat.select)
        void defaultsRemove() {
        }

        String portPrefixFirstRename() {
            return "portFirst";
        }

        JsonElement portPrefixFirstTransform(JsonElement orig) {
            return new JsonPrimitive(orig.getAsInt() * 10);
        }

        String portPrefixLastRename() {
            return "portLast";
        }

        JsonElement portPrefixLastTransform(JsonElement orig) {
            return new JsonPrimitive(orig.getAsInt() * 10 + 9);
        }

        String autoremoveRename() {
            return "autoRemove";
        }
    });
    diff = Diff.diff(current, result);
    return new Patch("M " + dest.getAbsolute(), diff) {
        public void apply() throws IOException {
            dest.writeString(result);
        }
    };
}

From source file:org.apache.edgent.runtime.jsoncontrol.JsonControlService.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object[] getArguments(Method method, JsonArray args) {
    final Class<?>[] paramTypes = method.getParameterTypes();

    if (paramTypes.length == 0 || args == null || args.size() == 0)
        return null;

    assert paramTypes.length == args.size();

    Object[] oargs = new Object[paramTypes.length];
    for (int i = 0; i < oargs.length; i++) {
        final Class<?> pt = paramTypes[i];
        final JsonElement arg = args.get(i);
        Object jarg;//from  w w  w. j  a  v  a 2s. c  o m

        if (String.class == pt) {
            if (arg instanceof JsonObject)
                jarg = gson.toJson(arg);
            else
                jarg = arg.getAsString();
        } else if (Integer.TYPE == pt)
            jarg = arg.getAsInt();
        else if (Long.TYPE == pt)
            jarg = arg.getAsLong();
        else if (Double.TYPE == pt)
            jarg = arg.getAsDouble();
        else if (Boolean.TYPE == pt)
            jarg = arg.getAsBoolean();
        else if (pt.isEnum())
            jarg = Enum.valueOf((Class<Enum>) pt, arg.getAsString());
        else
            throw new UnsupportedOperationException(pt.getName());

        oargs[i] = jarg;
    }
    return oargs;
}

From source file:org.apache.edgent.samples.console.ConsoleWaterDetector.java

License:Apache License

/**
 * Look through the stream and check to see if any of the measurements cause concern.
 * Only a TStream that has one or more of the readings at "alert" level are passed through
 * @param readingsDetector The TStream&lt;JsonObject&gt; that represents all of the different sensor readings for the well
 * @param wellId The id of the well/*from ww w  .j a  v a  2s. c o m*/
 * @param simulateNormal Make this stream simulate all readings within the normal range, and therefore will not pass through the filter
 * @return TStream&lt;JsonObject&gt; that contain readings that could cause concern.  Note: if any reading is out of range the tuple 
 * will be returned
 */

public static TStream<JsonObject> alertFilter(TStream<JsonObject> readingsDetector, int wellId,
        boolean simulateNormal) {
    readingsDetector = readingsDetector.filter(r -> {
        if (simulateNormal == true) {
            return false;
        }

        JsonElement tempElement = r.get("temp");
        if (tempElement != null) {
            int temp = tempElement.getAsInt();
            return (temp <= TEMP_ALERT_MIN || temp >= TEMP_ALERT_MAX);
        }

        JsonElement acidElement = r.get("acidity");
        if (acidElement != null) {
            int acid = acidElement.getAsInt();
            return (acid <= ACIDITY_ALERT_MIN || acid >= ACIDITY_ALERT_MAX);
        }

        JsonElement ecoliElement = r.get("ecoli");
        if (ecoliElement != null) {
            int ecoli = ecoliElement.getAsInt();
            return ecoli >= ECOLI_ALERT;
        }

        JsonElement leadElement = r.get("lead");
        if (leadElement != null) {
            int lead = leadElement.getAsInt();
            return lead >= LEAD_ALERT_MAX;
        }

        return false;
    });

    return readingsDetector;
}

From source file:org.apache.gobblin.converter.grok.GrokToJsonConverter.java

License:Apache License

@VisibleForTesting
JsonObject createOutput(JsonArray outputSchema, String inputRecord) throws DataConversionException {
    JsonObject outputRecord = new JsonObject();

    Match gm = grok.match(inputRecord);/*from   w w  w.j a v a  2  s  .  c o  m*/
    gm.captures();

    JsonElement capturesJson = JSON_PARSER.parse(gm.toJson());

    for (JsonElement anOutputSchema : outputSchema) {
        JsonObject outputSchemaJsonObject = anOutputSchema.getAsJsonObject();
        String key = outputSchemaJsonObject.get(COLUMN_NAME_KEY).getAsString();
        String type = outputSchemaJsonObject.getAsJsonObject(DATA_TYPE).get(TYPE_KEY).getAsString();

        if (isFieldNull(capturesJson, key)) {
            if (!outputSchemaJsonObject.get(NULLABLE).getAsBoolean()) {
                throw new DataConversionException(
                        "Field " + key + " is null or not exists but it is non-nullable by the schema.");
            }
            outputRecord.add(key, JsonNull.INSTANCE);
        } else {
            JsonElement jsonElement = capturesJson.getAsJsonObject().get(key);
            switch (type) {
            case "int":
                outputRecord.addProperty(key, jsonElement.getAsInt());
                break;
            case "long":
                outputRecord.addProperty(key, jsonElement.getAsLong());
                break;
            case "double":
                outputRecord.addProperty(key, jsonElement.getAsDouble());
                break;
            case "float":
                outputRecord.addProperty(key, jsonElement.getAsFloat());
                break;
            case "boolean":
                outputRecord.addProperty(key, jsonElement.getAsBoolean());
                break;
            case "string":
            default:
                outputRecord.addProperty(key, jsonElement.getAsString());
            }
        }
    }
    return outputRecord;
}

From source file:org.apache.tajo.gson.DataTypeAdapter.java

License:Apache License

@Override
public DataType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject obj = (JsonObject) json;//from   www  .j a v  a2 s .co  m
    DataType.Builder builder = DataType.newBuilder();
    TajoDataTypes.Type type = Enum.valueOf(TajoDataTypes.Type.class, obj.get("type").getAsString());
    builder.setType(type);

    JsonElement len = obj.get("len");
    if (len != null) {
        builder.setLength(len.getAsInt());
    }
    JsonElement code = obj.get("code");
    if (code != null) {
        builder.setCode(code.getAsString());
    }
    return builder.build();
}

From source file:org.apache.tajo.json.DataTypeAdapter.java

License:Apache License

@Override
public DataType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject obj = (JsonObject) json;/*from  w  ww  .j  a  v a  2 s. c o m*/
    DataType.Builder builder = DataType.newBuilder();
    TajoDataTypes.Type type = TajoDataTypes.Type.valueOf(CommonGsonHelper.getOrDie(obj, "type").getAsString());
    builder.setType(type);

    JsonElement len = obj.get("len");
    if (len != null) {
        builder.setLength(len.getAsInt());
    }
    JsonElement code = obj.get("code");
    if (code != null) {
        builder.setCode(code.getAsString());
    }
    return builder.build();
}

From source file:org.blockartistry.DynSurround.client.footsteps.parsers.AcousticsJsonReader.java

License:MIT License

private IAcoustic solveAcousticsCompound(final JsonObject unsolved) throws JsonParseException {
    IAcoustic ret = null;/*from  w ww  .ja va2 s  .com*/

    if (!unsolved.has("type") || unsolved.get("type").getAsString().equals("basic")) {
        final BasicAcoustic a = new BasicAcoustic();
        prepareDefaults(a);
        setupClassics(a, unsolved);
        ret = a;
    } else {
        final String type = unsolved.get("type").getAsString();
        if (type.equals("simultaneous")) {
            final List<IAcoustic> acoustics = new ArrayList<IAcoustic>();
            final JsonArray sim = unsolved.getAsJsonArray("array");
            final Iterator<JsonElement> iter = sim.iterator();
            while (iter.hasNext()) {
                final JsonElement subElement = iter.next();
                acoustics.add(solveAcoustic(subElement));
            }

            final SimultaneousAcoustic a = new SimultaneousAcoustic(acoustics);
            ret = a;
        } else if (type.equals("delayed")) {
            final DelayedAcoustic a = new DelayedAcoustic();
            prepareDefaults(a);
            setupClassics(a, unsolved);

            if (unsolved.has("delay")) {
                a.setDelayMin(unsolved.get("delay").getAsInt());
                a.setDelayMax(unsolved.get("delay").getAsInt());
            } else {
                a.setDelayMin(unsolved.get("delay_min").getAsInt());
                a.setDelayMax(unsolved.get("delay_max").getAsInt());
            }

            ret = a;
        } else if (type.equals("probability")) {
            final List<Integer> weights = new ArrayList<Integer>();
            final List<IAcoustic> acoustics = new ArrayList<IAcoustic>();

            final JsonArray sim = unsolved.getAsJsonArray("array");
            final Iterator<JsonElement> iter = sim.iterator();
            while (iter.hasNext()) {
                JsonElement subElement = iter.next();
                weights.add(subElement.getAsInt());

                if (!iter.hasNext())
                    throw new JsonParseException("Probability has odd number of children!");

                subElement = iter.next();
                acoustics.add(solveAcoustic(subElement));
            }

            final ProbabilityWeightsAcoustic a = new ProbabilityWeightsAcoustic(acoustics, weights);

            ret = a;
        }
    }

    return ret;
}