use of com.google.gson.JsonSyntaxException in project bender by Nextdoor.
the class GenericJsonDeserializer method deserialize.
@Override
public DeserializedEvent deserialize(String raw) {
GenericJsonEvent devent = new GenericJsonEvent(null);
JsonElement elm;
try {
elm = parser.parse(raw);
} catch (JsonSyntaxException e) {
throw new DeserializationException(e);
}
if (!elm.isJsonObject()) {
throw new DeserializationException("event is not a json object");
}
JsonObject obj = elm.getAsJsonObject();
/*
* Convert fields which are nested json strings into json objects
*/
for (FieldConfig fconfig : this.nestedFieldConfigs) {
if (obj.has(fconfig.getField())) {
JsonElement msg = obj.get(fconfig.getField());
/*
* Find the JSON in the string and replace the field
*/
NestedData data = deserialize(msg);
obj.remove(fconfig.getField());
obj.add(fconfig.getField(), data.nested);
/*
* If the string contained data before the JSON store it in a new field
*/
if (fconfig.getPrefixField() != null && data.prefix != null) {
obj.add(fconfig.getPrefixField(), data.prefix);
}
}
}
if (rootNodeOverridePath != null) {
obj = JsonPathProvider.read(obj, rootNodeOverridePath);
if (obj == null) {
throw new DeserializationException(rootNodeOverridePath + " path not found in object");
}
}
devent.setPayload(obj);
return devent;
}
use of com.google.gson.JsonSyntaxException in project bender by Nextdoor.
the class ElasticSearchTransport method checkResponse.
@Override
public void checkResponse(HttpResponse resp, String responseString) throws TransportException {
/*
* Check responses status code of the overall bulk call. The call can succeed but have
* individual failures which are checked later.
*/
if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new TransportException("es call failed because " + resp.getStatusLine().getReasonPhrase());
}
/*
* Short circuit deserializing the response by just looking if there are any errors
*/
if (responseString.contains("\"errors\":false")) {
return;
}
/*
* Convert response text to a POJO. Only tested with ES 2.4.x and 5.x.
*/
Gson gson = new GsonBuilder().create();
EsResponse esResp = null;
try {
esResp = gson.fromJson(responseString, EsResponse.class);
} catch (JsonSyntaxException e) {
throw new TransportException("es call failed because " + resp.getStatusLine().getReasonPhrase(), e);
}
/*
* Look for the errors per index request
*/
int failures = 0;
if (esResp.items == null) {
throw new TransportException("es call failed because " + resp.getStatusLine().getReasonPhrase());
}
HashSet<String> errorTypes = new HashSet<String>();
for (Item item : esResp.items) {
Index index = item.index;
if (index == null || index.error == null || index.error.reason == null) {
continue;
}
/*
* For now just allow 200's and 400's. Both are considered non-fatal errors from the lambda's
* perspective.
*/
switch(index.status) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
continue;
default:
failures++;
if (index.error != null && index.error.reason != null && index.error.type != null) {
if (!errorTypes.contains(index.error.type)) {
logger.error("Indexing Error Reason: " + index.error.reason);
if (index.error.caused_by != null) {
logger.error("Indexing Error Cause: " + index.error.caused_by.reason);
}
errorTypes.add(index.error.type);
}
}
}
}
errorTypes.clear();
if (failures != 0) {
throw new TransportException("es index failure count is " + failures);
}
}
use of com.google.gson.JsonSyntaxException in project thingsboard by thingsboard.
the class TelemetryRestMsgHandler method handleHttpPostTimeseries.
private void handleHttpPostTimeseries(PluginContext ctx, PluginRestMsg msg, RestRequest request, EntityId entityId, long ttl) {
TelemetryUploadRequest telemetryRequest;
JsonElement telemetryJson;
try {
telemetryJson = new JsonParser().parse(request.getRequestBody());
} catch (Exception e) {
throw new IllegalArgumentException("Unable to parse timeseries payload: Invalid JSON body!");
}
try {
telemetryRequest = JsonConverter.convertToTelemetry(telemetryJson);
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException(e.getMessage());
}
List<TsKvEntry> entries = new ArrayList<>();
for (Map.Entry<Long, List<KvEntry>> entry : telemetryRequest.getData().entrySet()) {
for (KvEntry kv : entry.getValue()) {
entries.add(new BasicTsKvEntry(entry.getKey(), kv));
}
}
if (entries.isEmpty()) {
throw new IllegalArgumentException("No timeseries data found in request body!");
}
ctx.saveTsData(entityId, entries, ttl, new PluginCallback<Void>() {
@Override
public void onSuccess(PluginContext ctx, Void value) {
msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.OK));
subscriptionManager.onTimeseriesUpdateFromServer(ctx, entityId, entries);
}
@Override
public void onFailure(PluginContext ctx, Exception e) {
log.error("Failed to save attributes", e);
handleError(e, msg, HttpStatus.INTERNAL_SERVER_ERROR);
}
});
}
use of com.google.gson.JsonSyntaxException in project thingsboard by thingsboard.
the class DeviceApiController method replyToCommand.
@RequestMapping(value = "/{deviceToken}/rpc/{requestId}", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> replyToCommand(@PathVariable("deviceToken") String deviceToken, @PathVariable("requestId") Integer requestId, @RequestBody String json, HttpServletRequest request) {
DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
if (quotaExceeded(request, responseWriter)) {
return responseWriter;
}
HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
try {
JsonObject response = new JsonParser().parse(json).getAsJsonObject();
process(ctx, new ToDeviceRpcResponseMsg(requestId, response.toString()));
} catch (IllegalStateException | JsonSyntaxException ex) {
responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
} else {
responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
}
return responseWriter;
}
use of com.google.gson.JsonSyntaxException in project thingsboard by thingsboard.
the class DeviceApiController method postDeviceAttributes.
@RequestMapping(value = "/{deviceToken}/attributes", method = RequestMethod.POST)
public DeferredResult<ResponseEntity> postDeviceAttributes(@PathVariable("deviceToken") String deviceToken, @RequestBody String json, HttpServletRequest request) {
DeferredResult<ResponseEntity> responseWriter = new DeferredResult<ResponseEntity>();
if (quotaExceeded(request, responseWriter)) {
return responseWriter;
}
HttpSessionCtx ctx = getHttpSessionCtx(responseWriter);
if (ctx.login(new DeviceTokenCredentials(deviceToken))) {
try {
process(ctx, JsonConverter.convertToAttributes(new JsonParser().parse(json)));
} catch (IllegalStateException | JsonSyntaxException ex) {
responseWriter.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
}
} else {
responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
}
return responseWriter;
}
Aggregations