Search in sources :

Example 81 with JsonSyntaxException

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;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonElement(com.google.gson.JsonElement) FieldConfig(com.nextdoor.bender.deserializer.json.GenericJsonDeserializerConfig.FieldConfig) JsonObject(com.google.gson.JsonObject) DeserializationException(com.nextdoor.bender.deserializer.DeserializationException)

Example 82 with JsonSyntaxException

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);
    }
}
Also used : Item(com.nextdoor.bender.ipc.es.EsResponse.Item) JsonSyntaxException(com.google.gson.JsonSyntaxException) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) Index(com.nextdoor.bender.ipc.es.EsResponse.Index) TransportException(com.nextdoor.bender.ipc.TransportException) HashSet(java.util.HashSet)

Example 83 with JsonSyntaxException

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);
        }
    });
}
Also used : TelemetryUploadRequest(org.thingsboard.server.common.msg.core.TelemetryUploadRequest) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) ServletException(javax.servlet.ServletException) UncheckedApiException(org.thingsboard.server.extensions.api.exception.UncheckedApiException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvalidParametersException(org.thingsboard.server.extensions.api.exception.InvalidParametersException) ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser)

Example 84 with JsonSyntaxException

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;
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) HttpSessionCtx(org.thingsboard.server.transport.http.session.HttpSessionCtx) JsonObject(com.google.gson.JsonObject) DeviceTokenCredentials(org.thingsboard.server.common.data.security.DeviceTokenCredentials) DeferredResult(org.springframework.web.context.request.async.DeferredResult) JsonParser(com.google.gson.JsonParser)

Example 85 with JsonSyntaxException

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;
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) HttpSessionCtx(org.thingsboard.server.transport.http.session.HttpSessionCtx) DeviceTokenCredentials(org.thingsboard.server.common.data.security.DeviceTokenCredentials) DeferredResult(org.springframework.web.context.request.async.DeferredResult) JsonParser(com.google.gson.JsonParser)

Aggregations

JsonSyntaxException (com.google.gson.JsonSyntaxException)379 Gson (com.google.gson.Gson)169 IOException (java.io.IOException)83 HashMap (java.util.HashMap)68 JsonElement (com.google.gson.JsonElement)62 JsonObject (com.google.gson.JsonObject)58 ArrayList (java.util.ArrayList)46 JsonParser (com.google.gson.JsonParser)42 GsonBuilder (com.google.gson.GsonBuilder)38 Cursor (android.database.Cursor)33 InputStreamReader (java.io.InputStreamReader)30 Map (java.util.Map)30 BadRequestException (co.cask.cdap.common.BadRequestException)28 JsonArray (com.google.gson.JsonArray)28 Path (javax.ws.rs.Path)28 Reader (java.io.Reader)26 Type (java.lang.reflect.Type)23 JsonIOException (com.google.gson.JsonIOException)21 FileReader (java.io.FileReader)21 File (java.io.File)19