Skip to content

Commit

Permalink
samples/smarthome/java: remove org.json dep
Browse files Browse the repository at this point in the history
- use gson instead of org.json
- temporarly use actions-on-google deprecated method until
  actions-on-google/actions-on-google-java#43
  is fixed.

Bug: 146618154
Change-Id: I6be48ab602befe3764f6d407c8966b8765369971
  • Loading branch information
proppy committed Jan 9, 2020
1 parent 51aa22b commit 742257c
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 53 deletions.
9 changes: 4 additions & 5 deletions src/main/java/com/example/MyDataStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -447,13 +446,13 @@ public Map<String, Object> execute(String userId, String deviceId,
// action.devices.traits.OpenClose
case "action.devices.commands.OpenClose":
// Check if the device can open in multiple directions
JSONObject attributes = (JSONObject) device.getData().get("attributes");
if (attributes != null && attributes.has("openDirection")) {
Map<String, Object> attributes = (Map<String, Object>)device.getData().get("attributes");
if (attributes != null && attributes.containsKey("openDirection")) {
// The device can open in more than one direction
String direction = (String) execution.getParams().get("openDirection");
List<JSONObject> openStates = (List<JSONObject>) states.get("openState");
List<Map<String, Object>> openStates = (List<Map<String, Object>>) states.get("openState");
openStates.forEach(state -> {
if (state.getString("openDirection").equals(direction)) {
if (state.get("openDirection").equals(direction)) {
state.put("openPercent", execution.getParams().get("openPercent"));
}
});
Expand Down
10 changes: 6 additions & 4 deletions src/main/java/com/example/MySmartHomeApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@

import com.google.actions.api.smarthome.*;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.gson.Gson;
import com.google.home.graph.v1.DeviceProto;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -75,11 +75,11 @@ public SyncResponse onSync(SyncRequest syncRequest, Map<?, ?> headers) {
if (device.contains("attributes")) {
Map<String, Object> attributes = new HashMap<>();
attributes.putAll((Map<String, Object>) device.get("attributes"));
JSONObject attributesJson = new JSONObject(attributes);
String attributesJson = new Gson().toJson(attributes);
Struct.Builder attributeBuilder = Struct.newBuilder();
try {
JsonFormat.parser().ignoringUnknownFields()
.merge(attributesJson.toString(), attributeBuilder);
.merge(attributesJson, attributeBuilder);
} catch (Exception e) {
LOGGER.error("FAILED TO BUILD");
}
Expand All @@ -88,7 +88,9 @@ public SyncResponse onSync(SyncRequest syncRequest, Map<?, ?> headers) {
if (device.contains("customData")) {
Map<String, Object> customData = new HashMap<>();
customData.putAll((Map<String, Object>) device.get("customData"));
JSONObject customDataJson = new JSONObject(customData);
// TODO(proppy): remove once
// https://github.com/actions-on-google/actions-on-google-java/issues/43 is fixed.
String customDataJson = new Gson().toJson(customData);
deviceBuilder.setCustomData(customDataJson);
}
response.payload.devices[i] = deviceBuilder.build();
Expand Down
9 changes: 5 additions & 4 deletions src/main/java/com/example/SmartHomeDeleteServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

import com.google.actions.api.smarthome.SmartHomeApp;
import com.google.auth.oauth2.GoogleCredentials;
import org.json.JSONObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -62,9 +63,9 @@ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IO
String body = req.getReader().lines().collect(Collectors.joining());
LOGGER.info("doPost, body = {}", body);
Map<String, String> headerMap = getHeaderMap(req);
JSONObject bodyJson = new JSONObject(body);
database.deleteDevice(bodyJson.getString("userId"),
bodyJson.getString("deviceId"));
JsonObject bodyJson = new JsonParser().parse(body).getAsJsonObject();
database.deleteDevice(bodyJson.get("userId").getAsString(),
bodyJson.get("deviceId").getAsString());
actionsApp.requestSync("1836.15267389");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setContentType("text/plain");
Expand Down
81 changes: 41 additions & 40 deletions src/main/java/com/example/SmartHomeUpdateServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
import com.google.actions.api.smarthome.SmartHomeApp;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.JsonObject;
import com.google.home.graph.v1.HomeGraphApiServiceProto;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -64,52 +65,52 @@ public class SmartHomeUpdateServlet extends HttpServlet {
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
String body = req.getReader().lines().collect(Collectors.joining());
JSONObject bodyJson = new JSONObject(body);
String userId = bodyJson.getString("userId");
String deviceId = bodyJson.getString("deviceId");
JsonObject bodyJson = new JsonParser().parse(body).getAsJsonObject();
String userId = bodyJson.get("userId").getAsString();
String deviceId = bodyJson.get("deviceId").getAsString();
LOGGER.info("doPost, body = {}", body);
String deviceName = bodyJson.has("name") ? bodyJson.getString("name") : null;
String deviceNickname = bodyJson.has("nickname") ? bodyJson.getString("nickname")
String deviceName = bodyJson.has("name") ? bodyJson.get("name").getAsString() : null;
String deviceNickname = bodyJson.has("nickname") ? bodyJson.get("nickname").getAsString()
: null;
Map<String, Object> deviceStates = bodyJson.has("states") ?
new Gson().fromJson(bodyJson.getJSONObject("states").toString(), HashMap.class) :
null;
String errorCode = bodyJson.has("errorCode") ? bodyJson.getString("errorCode") : null;
String tfa = bodyJson.has("tfa") ? bodyJson.getString("tfa") : null;
JsonObject deviceStatesJson = bodyJson.getAsJsonObject("states");
Map<String, Object> deviceStates = deviceStatesJson != null ?
new Gson().fromJson(deviceStatesJson, HashMap.class) :
null;
String errorCode = bodyJson.has("errorCode") ? bodyJson.get("errorCode").getAsString() : null;
String tfa = bodyJson.has("tfa") ? bodyJson.get("tfa").getAsString() : null;
try {
database.updateDevice(userId, deviceId, deviceName, deviceNickname, deviceStates, errorCode, tfa);
if (deviceStates != null) {
JSONObject statesJson = new JSONObject(deviceStates);
// Do state name replacement for ColorSetting trait
// See https://developers.google.com/assistant/smarthome/traits/colorsetting#device-states
if (statesJson.has("color") &&
statesJson.getJSONObject("color").has("spectrumRgb")) {
statesJson.getJSONObject("color")
.put("spectrumRGB", statesJson.getJSONObject("color").get("spectrumRgb"));
statesJson.getJSONObject("color").remove("spectrumRgb");
}
Struct.Builder statesStruct = Struct.newBuilder();
try {
JsonFormat.parser().ignoringUnknownFields()
.merge(statesJson.toString(), statesStruct);
} catch (Exception e) {
LOGGER.error("FAILED TO BUILD");
}
if (deviceStatesJson != null) {
// Do state name replacement for ColorSetting trait
// See https://developers.google.com/assistant/smarthome/traits/colorsetting#device-states
JsonObject colorJson = deviceStatesJson.getAsJsonObject("color");
if (colorJson != null &&
colorJson.has("spectrumRgb")) {
colorJson.add("spectrumRGB", colorJson.get("spectrumRgb"));
colorJson.remove("spectrumRgb");
}
Struct.Builder statesStruct = Struct.newBuilder();
try {
JsonFormat.parser().ignoringUnknownFields()
.merge(new Gson().toJson(deviceStatesJson), statesStruct);
} catch (Exception e) {
LOGGER.error("FAILED TO BUILD");
}

HomeGraphApiServiceProto.ReportStateAndNotificationDevice.Builder deviceBuilder =
HomeGraphApiServiceProto.ReportStateAndNotificationDevice.newBuilder()
.setStates(Struct.newBuilder().putFields(deviceId,
Value.newBuilder().setStructValue(statesStruct).build()));
HomeGraphApiServiceProto.ReportStateAndNotificationDevice.Builder deviceBuilder =
HomeGraphApiServiceProto.ReportStateAndNotificationDevice.newBuilder()
.setStates(Struct.newBuilder().putFields(deviceId,
Value.newBuilder().setStructValue(statesStruct).build()));

HomeGraphApiServiceProto.ReportStateAndNotificationRequest request =
HomeGraphApiServiceProto.ReportStateAndNotificationRequest.newBuilder()
.setRequestId(String.valueOf(Math.random()))
.setAgentUserId("1836.15267389") // our single user's id
.setPayload(HomeGraphApiServiceProto.
StateAndNotificationPayload.newBuilder()
.setDevices(deviceBuilder)).build();
HomeGraphApiServiceProto.ReportStateAndNotificationRequest request =
HomeGraphApiServiceProto.ReportStateAndNotificationRequest.newBuilder()
.setRequestId(String.valueOf(Math.random()))
.setAgentUserId("1836.15267389") // our single user's id
.setPayload(HomeGraphApiServiceProto.
StateAndNotificationPayload.newBuilder()
.setDevices(deviceBuilder)).build();

actionsApp.reportState(request);
actionsApp.reportState(request);
}
} catch (Exception e) {
LOGGER.error("failed to update device");
Expand Down

0 comments on commit 742257c

Please sign in to comment.