List of usage examples for com.google.gson JsonElement getAsInt
public int getAsInt()
From source file:org.openhab.binding.russound.internal.rio.models.RioPresetSerializer.java
License:Open Source License
/** * Overridden to simply read the id/valid/name elements and create a {@link RioPreset}. Please note that * the bank/bankPreset are calculated fields from the ID and do not need to be read. * * @param elm the {@link JsonElement} to read from * @param type the type//from ww w. ja va 2 s . c o m * @param context the serialization context */ @Override public RioPreset deserialize(JsonElement elm, Type type, JsonDeserializationContext context) throws JsonParseException { final JsonObject jo = (JsonObject) elm; final JsonElement id = jo.get("id"); final JsonElement valid = jo.get("valid"); final JsonElement name = jo.get("name"); return new RioPreset((id == null ? -1 : id.getAsInt()), (valid == null ? false : valid.getAsBoolean()), (name == null ? null : name.getAsString())); }
From source file:org.openhab.io.transport.modbus.json.WriteRequestJsonUtilities.java
License:Open Source License
private static ModbusWriteRequestBlueprint constructBluerint(int unitId, @Nullable JsonElement functionCodeElem, @Nullable JsonElement addressElem, @Nullable JsonElement maxTriesElem, @Nullable JsonArray valuesElem) { int functionCodeNumeric; if (functionCodeElem == null || functionCodeElem.isJsonNull()) { throw new IllegalStateException(String.format("Value for '%s' is invalid", JSON_FUNCTION_CODE)); }//from www. j a v a2s. co m try { functionCodeNumeric = functionCodeElem.getAsInt(); } catch (ClassCastException | IllegalStateException e) { throw new IllegalStateException(String.format("Value for '%s' is invalid", JSON_FUNCTION_CODE), e); } ModbusWriteFunctionCode functionCode = ModbusWriteFunctionCode.fromFunctionCode(functionCodeNumeric); int address; if (addressElem == null || addressElem.isJsonNull()) { throw new IllegalStateException(String.format("Value for '%s' is invalid", JSON_ADDRESS)); } try { address = addressElem.getAsInt(); } catch (ClassCastException | IllegalStateException e) { throw new IllegalStateException(String.format("Value for '%s' is invalid", JSON_ADDRESS), e); } int maxTries; if (maxTriesElem == null || maxTriesElem.isJsonNull()) { // Go with default maxTries = DEFAULT_MAX_TRIES; } else { try { maxTries = maxTriesElem.getAsInt(); } catch (ClassCastException | IllegalStateException e) { throw new IllegalStateException(String.format("Value for '%s' is invalid", JSON_MAX_TRIES), e); } } if (valuesElem == null || valuesElem.isJsonNull()) { throw new IllegalArgumentException(String.format("Expecting non-null value, got: %s", valuesElem)); } AtomicBoolean writeSingle = new AtomicBoolean(false); switch (functionCode) { case WRITE_COIL: writeSingle.set(true); if (valuesElem.size() != 1) { throw new IllegalArgumentException(String .format("Expecting single value with functionCode=%s, got: %d", functionCode, valuesElem)); } // fall-through to WRITE_MULTIPLE_COILS case WRITE_MULTIPLE_COILS: if (valuesElem.size() == 0) { throw new IllegalArgumentException("Must provide at least one coil"); } BasicBitArray bits = new BasicBitArray(valuesElem.size()); for (int i = 0; i < valuesElem.size(); i++) { bits.setBit(i, valuesElem.get(i).getAsInt() != 0); } return new BasicModbusWriteCoilRequestBlueprint(unitId, address, bits, !writeSingle.get(), maxTries); case WRITE_SINGLE_REGISTER: writeSingle.set(true); if (valuesElem.size() != 1) { throw new IllegalArgumentException(String .format("Expecting single value with functionCode=%s, got: %d", functionCode, valuesElem)); } // fall-through to WRITE_MULTIPLE_REGISTERS case WRITE_MULTIPLE_REGISTERS: { ModbusRegister[] registers = new ModbusRegister[valuesElem.size()]; if (registers.length == 0) { throw new IllegalArgumentException("Must provide at least one register"); } for (int i = 0; i < valuesElem.size(); i++) { registers[i] = new BasicModbusRegister(valuesElem.get(i).getAsInt()); } return new BasicModbusWriteRegisterRequestBlueprint(unitId, address, new BasicModbusRegisterArray(registers), !writeSingle.get(), maxTries); } default: throw new IllegalArgumentException("Unknown function code"); } }
From source file:org.openqa.selenium.json.JsonToBeanConverter.java
License:Apache License
@SuppressWarnings("unchecked") private <T> T convert(Class<T> clazz, Object source, int depth) { if (source == null || source instanceof JsonNull) { return null; }/*w ww .j a v a2s . c o m*/ if (source instanceof JsonElement) { JsonElement json = (JsonElement) source; if (json.isJsonPrimitive()) { JsonPrimitive jp = json.getAsJsonPrimitive(); if (String.class.equals(clazz)) { return (T) jp.getAsString(); } if (jp.isNumber()) { if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) { return (T) Integer.valueOf(jp.getAsNumber().intValue()); } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) { return (T) Long.valueOf(jp.getAsNumber().longValue()); } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) { return (T) Float.valueOf(jp.getAsNumber().floatValue()); } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) { return (T) Double.valueOf(jp.getAsNumber().doubleValue()); } else { return (T) convertJsonPrimitive(jp); } } } } if (isPrimitive(source.getClass())) { return (T) source; } if (isEnum(clazz, source)) { return (T) convertEnum(clazz, source); } if ("".equals(String.valueOf(source))) { return (T) source; } if (Command.class.equals(clazz)) { JsonObject json = new JsonParser().parse((String) source).getAsJsonObject(); SessionId sessionId = null; if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1); } String name = json.get("name").getAsString(); if (json.has("parameters")) { Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1); return (T) new Command(sessionId, name, args); } return (T) new Command(sessionId, name); } if (Response.class.equals(clazz)) { Response response = new Response(); JsonObject json = source instanceof JsonObject ? (JsonObject) source : new JsonParser().parse((String) source).getAsJsonObject(); if (json.has("error") && !json.get("error").isJsonNull()) { String state = json.get("error").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); response.setValue(convert(Object.class, json.get("message"))); } if (json.has("state") && !json.get("state").isJsonNull()) { String state = json.get("state").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } if (json.has("status") && !json.get("status").isJsonNull()) { JsonElement status = json.get("status"); if (status.getAsJsonPrimitive().isString()) { String state = status.getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } else { int intStatus = status.getAsInt(); response.setState(errorCodes.toState(intStatus)); response.setStatus(intStatus); } } if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { response.setSessionId(json.get("sessionId").getAsString()); } if (json.has("value")) { response.setValue(convert(Object.class, json.get("value"))); } else { response.setValue(convert(Object.class, json)); } return (T) response; } if (SessionId.class.equals(clazz)) { // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id. JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject() : (JsonElement) source; if (json.isJsonPrimitive()) { return (T) new SessionId(json.getAsString()); } return (T) new SessionId(json.getAsJsonObject().get("value").getAsString()); } if (Capabilities.class.isAssignableFrom(clazz)) { JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject() : new JsonParser().parse(source.toString()).getAsJsonObject(); Map<String, Object> map = convertMap(json.getAsJsonObject(), depth); return (T) new MutableCapabilities(map); } if (Date.class.equals(clazz)) { return (T) new Date(Long.valueOf(String.valueOf(source))); } if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) { return (T) source; } Method fromJson = getMethod(clazz, "fromJson"); if (fromJson != null) { try { return (T) fromJson.invoke(null, source.toString()); } catch (ReflectiveOperationException e) { throw new WebDriverException(e); } } if (depth == 0) { if (source instanceof String) { source = new JsonParser().parse((String) source); } } if (source instanceof JsonElement) { JsonElement element = (JsonElement) source; if (element.isJsonNull()) { return null; } if (element.isJsonPrimitive()) { return (T) convertJsonPrimitive(element.getAsJsonPrimitive()); } if (element.isJsonArray()) { return (T) convertList(element.getAsJsonArray(), depth); } if (element.isJsonObject()) { if (Map.class.isAssignableFrom(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } if (Object.class.equals(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } return convertBean(clazz, element.getAsJsonObject(), depth); } } return (T) source; // Crap shoot here; probably a string. }
From source file:org.openqa.selenium.remote.JsonToBeanConverter.java
License:Apache License
@SuppressWarnings("unchecked") private <T> T convert(Class<T> clazz, Object source, int depth) { if (source == null || source instanceof JsonNull) { return null; }/*from w ww. jav a2s. c o m*/ if (source instanceof JsonElement) { JsonElement json = (JsonElement) source; if (json.isJsonPrimitive()) { JsonPrimitive jp = json.getAsJsonPrimitive(); if (String.class.equals(clazz)) { return (T) jp.getAsString(); } if (jp.isNumber()) { if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) { return (T) Integer.valueOf(jp.getAsNumber().intValue()); } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) { return (T) Long.valueOf(jp.getAsNumber().longValue()); } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) { return (T) Float.valueOf(jp.getAsNumber().floatValue()); } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) { return (T) Double.valueOf(jp.getAsNumber().doubleValue()); } else { return (T) convertJsonPrimitive(jp); } } } } if (isPrimitive(source.getClass())) { return (T) source; } if (isEnum(clazz, source)) { return (T) convertEnum(clazz, source); } if ("".equals(String.valueOf(source))) { return (T) source; } if (Command.class.equals(clazz)) { JsonObject json = new JsonParser().parse((String) source).getAsJsonObject(); SessionId sessionId = null; if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1); } String name = json.get("name").getAsString(); if (json.has("parameters")) { Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1); return (T) new Command(sessionId, name, args); } return (T) new Command(sessionId, name); } if (Response.class.equals(clazz)) { Response response = new Response(); JsonObject json = source instanceof JsonObject ? (JsonObject) source : new JsonParser().parse((String) source).getAsJsonObject(); if (json.has("error") && !json.get("error").isJsonNull()) { String state = json.get("error").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); response.setValue(convert(Object.class, json.get("message"))); } if (json.has("state") && !json.get("state").isJsonNull()) { String state = json.get("state").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } if (json.has("status") && !json.get("status").isJsonNull()) { JsonElement status = json.get("status"); if (status.getAsJsonPrimitive().isString()) { String state = status.getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } else { int intStatus = status.getAsInt(); response.setState(errorCodes.toState(intStatus)); response.setStatus(intStatus); } } if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { response.setSessionId(json.get("sessionId").getAsString()); } if (json.has("value")) { response.setValue(convert(Object.class, json.get("value"))); } else { response.setValue(convert(Object.class, json)); } return (T) response; } if (SessionId.class.equals(clazz)) { // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id. JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject() : (JsonElement) source; if (json.isJsonPrimitive()) { return (T) new SessionId(json.getAsString()); } return (T) new SessionId(json.getAsJsonObject().get("value").getAsString()); } if (Capabilities.class.isAssignableFrom(clazz)) { JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject() : new JsonParser().parse(source.toString()).getAsJsonObject(); Map<String, Object> map = convertMap(json.getAsJsonObject(), depth); return (T) new DesiredCapabilities(map); } if (Date.class.equals(clazz)) { return (T) new Date(Long.valueOf(String.valueOf(source))); } if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) { return (T) source; } Method fromJson = getMethod(clazz, "fromJson"); if (fromJson != null) { try { return (T) fromJson.invoke(null, source.toString()); } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } if (depth == 0) { if (source instanceof String) { source = new JsonParser().parse((String) source); } } if (source instanceof JsonElement) { JsonElement element = (JsonElement) source; if (element.isJsonNull()) { return null; } if (element.isJsonPrimitive()) { return (T) convertJsonPrimitive(element.getAsJsonPrimitive()); } if (element.isJsonArray()) { return (T) convertList(element.getAsJsonArray(), depth); } if (element.isJsonObject()) { if (Map.class.isAssignableFrom(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } if (Object.class.equals(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } return convertBean(clazz, element.getAsJsonObject(), depth); } } return (T) source; // Crap shoot here; probably a string. }
From source file:org.robovm.devicebridge.internal.adapters.AtomicIntegerTypeAdapter.java
License:Apache License
@Override public AtomicInteger deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { int intValue = jsonElement.getAsInt(); return new AtomicInteger(intValue); }
From source file:org.runbuddy.libtomahawk.infosystem.hatchet.Store.java
License:Open Source License
public int getAsInt(JsonObject object, String memberName) throws IOException { JsonElement element = get(object, memberName); if (element != null && element.isJsonPrimitive()) { return element.getAsInt(); }//from w w w . j a v a2 s. c o m return -1; }
From source file:org.runbuddy.libtomahawk.resolver.ScriptUtils.java
License:Open Source License
public static int getNodeChildAsInt(JsonElement node, String fieldName) { if (node instanceof JsonObject) { JsonElement n = ((JsonObject) node).get(fieldName); if (n != null && n.isJsonPrimitive()) { return n.getAsInt(); }/*ww w . j av a2 s . c o m*/ } return 0; }
From source file:org.slc.sli.util.CheckListHelper.java
License:Apache License
/** * whether sandbox tenant has data in their mongo Tracking * ingestion job doesn't seem like a good solution Possible solution: check * mongo for data for that tenant// w w w.j ava2s . com * * @param mySession * @param token * @return */ private boolean hasUploadedData(JsonObject mySession, String token) { boolean result = false; JsonElement myTenantIdJson = mySession.get(TENANT_ID); if (myTenantIdJson != null && !myTenantIdJson.isJsonNull()) { String myTenantId = myTenantIdJson.getAsString(); // call API // http(s)://xxx.xxx.xxx.xxx/api/rest/v1/tenant_metrics/<tenantId> String path = Constants.API_PREFIX + "/" + Constants.API_V1 + "/" + Constants.TENANT_METRIC + "/" + myTenantId; String jsonText = restClient.makeJsonRequestWHeaders(path, token, true); JsonObject jsonObject = (new JsonParser()).parse(jsonText).getAsJsonObject(); if (jsonObject != null && !jsonObject.isJsonNull()) { JsonElement tenantMetricElement = jsonObject.get(myTenantId); // find element with the same tenant id if there is multiple // records if (tenantMetricElement != null && !tenantMetricElement.isJsonNull()) { JsonObject tenantMetricObject = tenantMetricElement.getAsJsonObject(); if (tenantMetricObject != null && !tenantMetricObject.isJsonNull()) { // get educationOrganization element JsonElement educationOrganizationElement = tenantMetricObject.get(EDUCATION_ORGANIZATION); if (educationOrganizationElement != null && !educationOrganizationElement.isJsonNull()) { JsonObject educatinoOrganizationObject = educationOrganizationElement.getAsJsonObject(); if (educatinoOrganizationObject != null && !educatinoOrganizationObject.isJsonNull()) { // get entityCount JsonElement entityCountElement = educatinoOrganizationObject.get(ENTITY_COUNT); if (entityCountElement != null && !entityCountElement.isJsonNull()) { int entityCount = entityCountElement.getAsInt(); // if there is more than 0, then // consider as data is ready if (entityCount > 0) { result = true; } } } } } } } } return result; }
From source file:org.sonar.server.qualitygate.ws.QualityGateDetailsFormatter.java
License:Open Source License
private static void formatConditionPeriod(ProjectStatusWsResponse.Condition.Builder conditionBuilder, JsonObject jsonCondition) {//from w ww .ja va2 s.c om JsonElement periodIndex = jsonCondition.get("period"); if (periodIndex != null && !isNullOrEmpty(periodIndex.getAsString())) { conditionBuilder.setPeriodIndex(periodIndex.getAsInt()); } }
From source file:org.sonarsource.dotnet.shared.sarif.SarifParser01And04.java
License:Open Source License
private static Location getLocation(boolean offsetStartAtZero, JsonObject analysisTarget, String absolutePath, @Nullable String message) { JsonObject region = analysisTarget.getAsJsonObject("region"); int startLine = region.get("startLine").getAsInt(); int startLineFixed = offsetStartAtZero ? (startLine + 1) : startLine; JsonElement startColumnOrNull = region.get("startColumn"); int startColumn = startColumnOrNull != null ? startColumnOrNull.getAsInt() : 1; int startLineOffset = offsetStartAtZero ? startColumn : (startColumn - 1); JsonElement lengthOrNull = region.get("length"); if (lengthOrNull != null) { return new Location(absolutePath, message, startLineFixed, startLineOffset, startLineFixed, startLineOffset + lengthOrNull.getAsInt()); }/*from w w w.j a va 2s . c o m*/ JsonElement endLineOrNull = region.get("endLine"); int endLine = endLineOrNull != null ? endLineOrNull.getAsInt() : startLine; int endLineFixed = offsetStartAtZero ? (endLine + 1) : endLine; JsonElement endColumnOrNull = region.get("endColumn"); int endColumn; if (endColumnOrNull != null) { endColumn = endColumnOrNull.getAsInt(); } else if (endLineOrNull != null) { endColumn = endLine == startLine ? startColumn : 1; } else { endColumn = startColumn; } int endLineOffset = offsetStartAtZero ? endColumn : (endColumn - 1); if (startColumn == endColumn && startLineFixed == endLineFixed) { return null; } return new Location(absolutePath, message, startLineFixed, startLineOffset, endLineFixed, endLineOffset); }