List of usage examples for com.google.gson JsonObject getAsJsonObject
public JsonObject getAsJsonObject(String memberName)
From source file:com.willwinder.universalgcodesender.TinyGUtils.java
License:Open Source License
public static boolean isRestartingResponse(JsonObject response) { if (response.has(FIELD_RESPONSE)) { JsonObject jo = response.getAsJsonObject(FIELD_RESPONSE); if (jo.has("msg")) { String msg = jo.get("msg").getAsString(); return StringUtils.equals(msg, "Loading configs from EEPROM"); }// w w w .java 2 s . c om } return false; }
From source file:com.willwinder.universalgcodesender.TinyGUtils.java
License:Open Source License
public static boolean isReadyResponse(JsonObject response) { if (response.has(FIELD_RESPONSE)) { JsonObject jo = response.getAsJsonObject(FIELD_RESPONSE); if (jo.has("msg")) { String msg = jo.get("msg").getAsString(); return StringUtils.equals(msg, "SYSTEM READY"); }/* ww w . j a v a2s.co m*/ } return false; }
From source file:com.willwinder.universalgcodesender.TinyGUtils.java
License:Open Source License
/** * Parses the TinyG status result response and creates a new current controller status * * @param lastControllerStatus the last controller status to update * @param response the response string from the controller * @return a new updated controller status *//* w w w . j av a 2 s . co m*/ public static ControllerStatus updateControllerStatus(final ControllerStatus lastControllerStatus, final JsonObject response) { if (response.has(FIELD_STATUS_REPORT)) { JsonObject statusResultObject = response.getAsJsonObject(FIELD_STATUS_REPORT); Position workCoord = lastControllerStatus.getWorkCoord(); UnitUtils.Units feedSpeedUnits = lastControllerStatus.getFeedSpeedUnits(); if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_UNIT)) { UnitUtils.Units units = statusResultObject.get(FIELD_STATUS_REPORT_UNIT).getAsInt() == 1 ? UnitUtils.Units.MM : UnitUtils.Units.INCH; workCoord = new Position(workCoord.getX(), workCoord.getY(), workCoord.getZ(), units); feedSpeedUnits = units; } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_POSX)) { workCoord.setX(statusResultObject.get(FIELD_STATUS_REPORT_POSX).getAsDouble()); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_POSY)) { workCoord.setY(statusResultObject.get(FIELD_STATUS_REPORT_POSY).getAsDouble()); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_POSZ)) { workCoord.setZ(statusResultObject.get(FIELD_STATUS_REPORT_POSZ).getAsDouble()); } // The machine coordinates are always in MM, make sure the position is using that unit before updating the values Position machineCoord = lastControllerStatus.getMachineCoord().getPositionIn(UnitUtils.Units.MM); if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_MPOX)) { machineCoord.setX(statusResultObject.get(FIELD_STATUS_REPORT_MPOX).getAsDouble()); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_MPOY)) { machineCoord.setY(statusResultObject.get(FIELD_STATUS_REPORT_MPOY).getAsDouble()); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_MPOZ)) { machineCoord.setZ(statusResultObject.get(FIELD_STATUS_REPORT_MPOZ).getAsDouble()); } int overrideFeed = 100; int overrideRapid = 100; int overrideSpindle = 100; if (lastControllerStatus.getOverrides() != null) { overrideFeed = lastControllerStatus.getOverrides().feed; overrideRapid = lastControllerStatus.getOverrides().rapid; overrideSpindle = lastControllerStatus.getOverrides().spindle; } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_MFO)) { double speed = statusResultObject.get(FIELD_STATUS_REPORT_MFO).getAsDouble(); overrideFeed = (int) Math.round(speed * 100.0); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_SSO)) { double speed = statusResultObject.get(FIELD_STATUS_REPORT_SSO).getAsDouble(); overrideSpindle = (int) Math.round(speed * 100.0); } if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_MTO)) { double speed = statusResultObject.get(FIELD_STATUS_REPORT_MTO).getAsDouble(); overrideRapid = (int) Math.round(speed * 100.0); } Double feedSpeed = lastControllerStatus.getFeedSpeed(); if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_VELOCITY)) { feedSpeed = statusResultObject.get(FIELD_STATUS_REPORT_VELOCITY).getAsDouble(); } ControllerState state = lastControllerStatus.getState(); String stateString = lastControllerStatus.getStateString(); if (hasNumericField(statusResultObject, FIELD_STATUS_REPORT_STATUS)) { state = getState(statusResultObject.get(FIELD_STATUS_REPORT_STATUS).getAsInt()); stateString = getStateAsString(statusResultObject.get(FIELD_STATUS_REPORT_STATUS).getAsInt()); } Double spindleSpeed = lastControllerStatus.getSpindleSpeed(); Position workCoordinateOffset = lastControllerStatus.getWorkCoordinateOffset(); ControllerStatus.EnabledPins enabledPins = lastControllerStatus.getEnabledPins(); ControllerStatus.AccessoryStates accessoryStates = lastControllerStatus.getAccessoryStates(); ControllerStatus.OverridePercents overrides = new ControllerStatus.OverridePercents(overrideFeed, overrideRapid, overrideSpindle); return new ControllerStatus(stateString, state, machineCoord, workCoord, feedSpeed, feedSpeedUnits, spindleSpeed, overrides, workCoordinateOffset, enabledPins, accessoryStates); } return lastControllerStatus; }
From source file:com.willwinder.universalgcodesender.TinyGUtils.java
License:Open Source License
/** * Updates the Gcode state from the response if it contains a status line * * @param response the response to parse the gcode state from * @return a list of gcodes representing the state of the controllers */// ww w .ja va 2s . c o m public static List<String> convertStatusReportToGcode(JsonObject response) { List<String> gcodeList = new ArrayList<>(); if (response.has(TinyGUtils.FIELD_STATUS_REPORT)) { JsonObject statusResultObject = response.getAsJsonObject(TinyGUtils.FIELD_STATUS_REPORT); if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_COORD)) { int offsetCode = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_COORD).getAsInt(); gcodeList.add(WorkCoordinateSystem.fromPValue(offsetCode).getGcode().name()); } if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_UNIT)) { int units = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_UNIT).getAsInt(); // 0=inch, 1=mm if (units == 0) { gcodeList.add(Code.G20.toString()); } else { gcodeList.add(Code.G21.toString()); } } if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_PLANE)) { int plane = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_PLANE).getAsInt(); // 0=XY plane, 1=XZ plane, 2=YZ plane if (plane == 0) { gcodeList.add(Code.G17.toString()); } else if (plane == 1) { gcodeList.add(Code.G18.toString()); } else if (plane == 2) { gcodeList.add(Code.G19.toString()); } } if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_FEED_MODE)) { int feedMode = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_FEED_MODE).getAsInt(); // 0=units-per-minute-mode, 1=inverse-time-mode if (feedMode == 0) { gcodeList.add(Code.G93.toString()); } else if (feedMode == 1) { gcodeList.add(Code.G94.toString()); } } if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_DISTANCE_MODE)) { int distance = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_DISTANCE_MODE).getAsInt(); // 0=absolute distance mode, 1=incremental distance mode if (distance == 0) { gcodeList.add(Code.G90.name()); } else if (distance == 1) { gcodeList.add(Code.G91.name()); } } if (hasNumericField(statusResultObject, TinyGUtils.FIELD_STATUS_REPORT_ARC_DISTANCE_MODE)) { int arcDistance = statusResultObject.get(TinyGUtils.FIELD_STATUS_REPORT_ARC_DISTANCE_MODE) .getAsInt(); // 0=absolute distance mode, 1=incremental distance mode if (arcDistance == 0) { gcodeList.add(Code.G90_1.toString()); } else if (arcDistance == 1) { gcodeList.add(Code.G91_1.toString()); } } } return gcodeList; }
From source file:com.xpbytes.gson.hal.HalTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> basicAdapter = gson.getAdapter(JsonElement.class); // If we convert to JSON, isn't the deserializer more appropriate...? // Is this a HalResource? if (!HalReflection.isResource(type.getRawType())) return delegate; return new TypeAdapter<T>() { @Override/* w w w.ja va 2s . c o m*/ public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { JsonElement fullJson = basicAdapter.read(in); Logger.getGlobal().log(Level.ALL, fullJson.toString()); T deserialized = delegate.fromJsonTree(fullJson); if (fullJson.isJsonObject()) { JsonObject fullJsonObject = fullJson.getAsJsonObject(); JsonObject linksObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_LINKS_ROOT); JsonObject embeddedObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_EMBEDDED_ROOT); List<Field> fieldsList = HalReflection.getHalFields(type.getRawType()); for (Field field : fieldsList) { if (HalReflection.isLink(field)) readLink(field, linksObject, deserialized); else if (HalReflection.isEmbed(field)) readEmbed(field, embeddedObject, deserialized); } } return deserialized; } private <A> void readEmbed(Field field, JsonObject rootObject, A deserialized) { HalEmbed embed = field.getAnnotation(HalEmbed.class); boolean optional = embed.optional(); if (rootObject == null && optional) return; String memberName = HalReflection.getJsonFieldName(embed, field); JsonParseException missingException = new JsonParseException( String.format(Locale.US, "Expected embed `%s` in the embedded root `%s` to be present", memberName, HalConstants.RESERVED_EMBEDDED_ROOT)); if (rootObject == null) throw missingException; boolean exists = rootObject.has(memberName); if (!exists) { if (optional) return; throw missingException; } Type innerType = HalReflection.getFieldItemizedType(field); //Class outerType = HalReflection.getFieldType( field ); JsonElement element = rootObject.get(memberName); // This gson.fromJson call will actually call into the proper stack to recursively // deserialize embeds and set their links where necessary. HalReflection.setEmbed(field, gson.fromJson(element, innerType), deserialized); } private <A> void readLink(Field field, JsonObject rootObject, A deserialized) { HalLink link = field.getAnnotation(HalLink.class); boolean optional = link.optional(); if (rootObject == null && optional) return; String memberName = HalReflection.getJsonFieldName(link, field); JsonParseException missingException = new JsonParseException( String.format(Locale.US, "Expected link `%s` in the links root `%s` to be present", memberName, HalConstants.RESERVED_LINKS_ROOT)); if (rootObject == null) throw missingException; boolean exists = rootObject.has(memberName); if (!exists) { if (optional) return; throw missingException; } // If this is not a descendant of a HalLinkObject, we better treat it as one. Class<?> innerType = HalReflection.getFieldItemizedType(field); if (!innerType.isAssignableFrom(HalLinkObject.class)) innerType = HalLinkObject.class; //Class outerType = HalReflection.getFieldType( field ); JsonElement element = rootObject.get(memberName); // TODO support collections /*if ( Collection.class.isAssignableFrom( outerType ) ) { innerType. //noinspection unchecked Class<Collection> collectionClass = (Class<Collection>)outerType; Collection collection = gson.fromJson( element, collectionClass ); } field.getType() if ( element.isJsonArray() ) { for ( JsonElement element1 : element.getAsJsonArray() ) HalReflection.setLink( field, , deserialized ); } else { */ HalReflection.setLink(field, (HalLinkObject) gson.fromJson(element, (Type) innerType), deserialized); } }.nullSafe(); }
From source file:com.yahoo.yqlplus.example.apis.GeoSource.java
@Query public Place getPlace(@Key("text") String text) throws InterruptedException, ExecutionException, TimeoutException { JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q", "select * from geo.places where text='" + text + "'"); JsonPrimitive jsonObj = jsonObject.getAsJsonObject("query").getAsJsonObject("results") .getAsJsonObject("place").getAsJsonPrimitive("woeid"); return new Place(text, jsonObj.getAsString()); }
From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java
@Query public List<Forecast> getForecast(@Key("woeid") String woeid) throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException { JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q", "select * from weather.forecast where u = 'f' and woeid = " + woeid); JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results") .getAsJsonObject("channel").getAsJsonObject("item").get("forecast"); Iterator<JsonElement> it = jsonArray.iterator(); List<Forecast> forecasts = Lists.newArrayList(); while (it.hasNext()) { JsonElement ele = it.next();//from w w w . j av a 2s .com ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class); forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(), tmp.getText(), woeid, "f")); } return forecasts; }
From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java
@Query public List<Forecast> getForecast(@Key("woeid") String woeid, @Key("u") String u) throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException { JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL.replace("{woeid}", woeid).replace("{u}", u)); JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results") .getAsJsonObject("channel").getAsJsonObject("item").get("forecast"); Iterator<JsonElement> it = jsonArray.iterator(); List<Forecast> forecasts = Lists.newArrayList(); while (it.hasNext()) { JsonElement ele = it.next();/*from ww w . j a va2s .c om*/ ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class); forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(), tmp.getText(), woeid, u)); } return forecasts; }
From source file:com.yandex.money.api.typeadapters.methods.RequestPaymentTypeAdapter.java
License:Open Source License
@Override public RequestPayment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); RequestPayment.Builder builder = new RequestPayment.Builder() .setBalance(getBigDecimal(object, MEMBER_BALANCE)) .setRecipientAccountStatus(AccountStatus.parse(getString(object, MEMBER_RECIPIENT_ACCOUNT_STATUS))) .setRecipientAccountType(AccountType.parse(getString(object, MEMBER_RECIPIENT_ACCOUNT_TYPE))) .setProtectionCode(getString(object, MEMBER_PROTECTION_CODE)) .setAccountUnblockUri(getString(object, MEMBER_ACCOUNT_UNBLOCK_URI)) .setExtActionUri(getString(object, MEMBER_EXT_ACTION_URI)) .setMultipleRecipientsFound(getBoolean(object, MEMBER_MULTIPLE_RECIPIENTS_FOUND)); JsonObject moneySourceObject = object.getAsJsonObject(MEMBER_MONEY_SOURCE); if (moneySourceObject != null) { builder.setMoneySources(MoneySourceListTypeAdapter.Delegate.deserialize(moneySourceObject, builder)); }/*from ww w . j a va2 s . c o m*/ BaseRequestPaymentTypeAdapter.Delegate.deserialize(object, builder); return builder.create(); }
From source file:com.yandex.money.api.typeadapters.model.showcase.ShowcaseReferenceTypeAdapter.java
License:Open Source License
@Override public ShowcaseReference deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); JsonObject paramsObject = object.getAsJsonObject(MEMBER_PARAMS); Map<String, String> params = paramsObject == null ? new HashMap<String, String>() : map(paramsObject); return new ShowcaseReference.Builder().setScid(getMandatoryLong(object, MEMBER_ID)) .setTitle(getString(object, MEMBER_TITLE)).setTopIndex(getInt(object, MEMBER_TOP)) .setUrl(getString(object, MEMBER_URL)) .setFormat(ShowcaseReference.Format.parse(getString(object, MEMBER_FORMAT))).setParams(params) .create();//from w w w .j av a2 s. c o m }