List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java
License:Open Source License
/** * This method return a list devices of the specific owner * * @param typeThing Generic type of list. * @param query Query to find devices * @param callbackResult List of devices * @throws KnotException <p>// www . j ava 2 s.c o m * @see <ahttps://meshblu-socketio.readme.io/docs/devices </a> */ public <T extends AbstractThingDevice> void getDeviceList(final KnotList<T> typeThing, JSONObject query, final Event<List<T>> callbackResult) throws KnotException, SocketNotConnected, InvalidParametersException { if (isSocketConnected() && isSocketRegistered()) { if (typeThing != null && callbackResult != null) { if (query == null) { query = new JSONObject(); } mSocket.emit(EVENT_GET_DEVICES, query, new Ack() { @Override public void call(Object... args) { List<T> result = null; try { JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString()); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) { callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString())); return; } JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(DEVICES); if (jsonArray != null || jsonArray.size() > 0) { result = mGson.fromJson(jsonArray, typeThing); } else { result = mGson.fromJson(EMPTY_JSON, typeThing); } callbackResult.onEventFinish((List<T>) result); } catch (Exception e) { callbackResult.onEventError(new KnotException(e)); } } }); } else { throw new InvalidParametersException("Invalid parameters"); } } else { throw new SocketNotConnected("Socket not ready or connected"); } }
From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java
License:Open Source License
/** * Get all data of the specific device/* ww w. j a va 2s. c o m*/ * * @param type List of abstracts objects * @param uuid UUid of device * @param deviceToken token of the device * @param knotQueryData Date query * @param callbackResult Callback for this method * @throws InvalidParametersException * @throws SocketNotConnected */ public <T extends AbstractThingData> void getData(final KnotList<T> type, String uuid, String deviceToken, KnotQueryData knotQueryData, final Event<List<T>> callbackResult) throws InvalidParametersException, SocketNotConnected { if (isSocketConnected() && isSocketRegistered() && knotQueryData != null) { if (uuid != null && callbackResult != null) { JSONObject dataToSend = new JSONObject(); int maxNumberOfItem = -1; try { dataToSend.put(UUID, uuid); dataToSend.put(TOKEN, deviceToken); if (knotQueryData.getStartDate() != null) { dataToSend.put(DATE_START, DateUtils.getTimeStamp(knotQueryData.getStartDate())); } if (knotQueryData.getFinishDate() != null) { dataToSend.put(DATE_FINISH, DateUtils.getTimeStamp(knotQueryData.getFinishDate())); } if (knotQueryData.getLimit() > 0) { maxNumberOfItem = knotQueryData.getLimit(); } dataToSend.put(LIMIT, maxNumberOfItem); } catch (JSONException e) { callbackResult.onEventError(new KnotException()); } mSocket.emit(EVENT_GET_DATA, dataToSend, new Ack() { @Override public void call(Object... args) { if (args != null && args.length > 0) { List<T> result = null; JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(DATA); if (jsonArray != null && jsonArray.size() > 0) { result = mGson.fromJson(jsonArray.toString(), type); } else { result = mGson.fromJson(EMPTY_JSON, type); } callbackResult.onEventFinish(result); } else { callbackResult.onEventError(new KnotException()); } } }); } else { throw new InvalidParametersException("Invalid parameters"); } } else { throw new SocketNotConnected("Socket not ready or connected"); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get a specific device from Meshblu instance. * * @param device the device identifier (uuid) * @param clazz The class for this device. Meshblu works with any type of objects and * it is necessary deserialize the return to a valid object. * Note: The class parameter should be a extension of {@link AbstractThingDevice} * @return an object based on the class parameter * @throws KnotException KnotException//from www .j a v a2s.c o m */ public <T extends AbstractThingDevice> T getDevice(String device, Class<T> clazz) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get the specific device from meshblue instance final String endPoint = mEndPoint + DEVICE_PATH + device; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); if (jsonArray.size() == 0) { return null; } return mGson.fromJson(jsonArray.get(0).toString(), clazz); } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get a specific device's gateway from Meshblu instance. * * @param device the device identifier (uuid) * @param clazz The class for this device. Meshblu works with any type of objects and * it is necessary deserialize the return to a valid object. * Note: The class parameter should be a extension of {@link AbstractThingDevice} * @return an object based on the class parameter * @throws KnotException KnotException/*from ww w .j a va 2 s .c o m*/ */ public <T extends AbstractThingDevice> T getDeviceGateway(String device, Class<T> clazz) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get a specific device's gateway from Meshblu instance. final String endPoint = mEndPoint + DEVICE_PATH + device + DEVICE_PROPERTY_PATH_GATEWAY; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); if (jsonArray.size() == 0) { return null; } return mGson.fromJson(jsonArray.get(0).toString(), clazz); } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get all devices those are claimed by one owner * * @param type object that will define what elements will returned by this method * @return a List with all devices those belongs to the owner * @throws KnotException KnotException/*from w ww . ja v a 2 s. c o m*/ */ public <T extends AbstractThingDevice> List<T> getDeviceList(final KnotList<T> type) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get all devices those are claimed by one owner final String endPoint = mEndPoint + MY_DEVICES_PATH; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.code() != HttpURLConnection.HTTP_OK) { return null; } JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); return mGson.fromJson(jsonArray.toString(), type); } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * @param device the device identifier (uuid) * @param type object that will define what elements will returned by this method * @param knotQueryData Date query/* w w w .ja v a2 s . co m*/ * @return a List with data of the device * @throws KnotException KnotException */ public <T extends AbstractThingData> List<T> getDataList(String device, final KnotList<T> type, KnotQueryData knotQueryData) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } final String endPoint = mEndPoint + DATA_PATH + device + getDataParameter(knotQueryData); Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DATA); if (jsonArray == null || jsonArray.size() == 0) { return mGson.fromJson(EMPTY_ARRAY, type); } return mGson.fromJson(jsonArray.toString(), type); } catch (Exception e) { throw new KnotException(e); } }
From source file:br.ufg.inf.es.saep.sandbox.dominio.infraestrutura.ValorDeserializer.java
License:Creative Commons License
@Override public Valor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); byte tipo = jsonObject.get("tipo").getAsByte(); JsonElement valor = jsonObject.get("valor"); if (tipo == Valor.STRING) { return new Valor(valor.getAsString()); } else if (tipo == REAL) { return new Valor(valor.getAsFloat()); } else if (tipo == LOGICO) { return new Valor(valor.getAsBoolean()); } else if (tipo == DATA) { return Valor.dataFromString(valor.getAsString()); }/* ww w. j a va 2s . c o m*/ return null; }
From source file:brooklyn.entity.mesos.framework.marathon.MarathonFrameworkImpl.java
License:Apache License
@Override public String startApplication(String id, Map<String, Object> flags) { Map<String, Object> substitutions = MutableMap.copyOf(flags); substitutions.put("id", id); Optional<String> result = MesosUtils.httpPost(this, "v2/apps", "classpath:///brooklyn/entity/mesos/framework/marathon/create-app.json", substitutions); if (!result.isPresent()) { JsonElement json = JsonFunctions.asJson().apply(result.get()); String message = json.getAsJsonObject().get("message").getAsString(); LOG.warn("Failed to start task {}: {}", id, message); throw new IllegalStateException("Failed to start Marathon task: " + message); } else {// w ww. j a v a2s. com LOG.debug("Success creating Marathon task"); JsonElement json = JsonFunctions.asJson().apply(result.get()); String version = json.getAsJsonObject().get("version").getAsString(); return version; } }
From source file:brooklyn.entity.mesos.framework.marathon.MarathonFrameworkImpl.java
License:Apache License
@Override public String stopApplication(String id) { Optional<String> result = MesosUtils.httpDelete(this, Urls.mergePaths("v2/apps", id)); if (!result.isPresent()) { throw new IllegalStateException("Failed to stop Marathon task"); } else {/*w w w . j a v a2s .co m*/ LOG.debug("Success deleting Marathon task"); JsonElement json = JsonFunctions.asJson().apply(result.get()); String deployment = json.getAsJsonObject().get("deploymentId").getAsString(); return deployment; } }
From source file:brooklyn.entity.mesos.MesosSlaveImpl.java
License:Apache License
@Override public void connectSensors() { super.connectSensors(); final String id = sensors().get(MESOS_SLAVE_ID); HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(30, TimeUnit.SECONDS) .baseUri(getMesosCluster().sensors().get(Attributes.MAIN_URI)) .credentialsIfNotNull(config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD)) .poll(HttpPollConfig.forSensor(MEMORY_AVAILABLE).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); }/*w ww .j a va 2 s . c om*/ }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "mem"), JsonFunctions.castM(Long.class))) .onFailureOrException(Functions.constant(-1L))) .poll(HttpPollConfig.forSensor(CPU_AVAILABLE).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); } }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "cpus"), JsonFunctions.castM(Double.class))) .onFailureOrException(Functions.constant(-1d))) .poll(HttpPollConfig.forSensor(DISK_AVAILABLE).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); } }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "disk"), JsonFunctions.castM(Long.class))) .onFailureOrException(Functions.constant(-1L))) .poll(HttpPollConfig.forSensor(MEMORY_USED).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); } }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "mem"), JsonFunctions.castM(Long.class))) .onFailureOrException(Functions.constant(-1L))) .poll(HttpPollConfig.forSensor(CPU_USED).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); } }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "cpus"), JsonFunctions.castM(Double.class))) .onFailureOrException(Functions.constant(-1d))) .poll(HttpPollConfig.forSensor(DISK_USED).suburl("/master/state.json") .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return input.getAsJsonObject().get("id").getAsString().equals(id); } }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "disk"), JsonFunctions.castM(Long.class))) .onFailureOrException(Functions.constant(-1L))); httpFeed = httpFeedBuilder.build(); }