private void invalidJsonPayload(JsonParseException ex, Request req, Response res) { res.body(new Gson().toJson(Collections.singletonMap("error", "Payload data is not valid JSON: " + ex.getMessage()))); res.status(HttpStatus.SC_BAD_REQUEST); }
/** * Read metadata from reader. * * @param reader reader to read from * @return Metadata or null if nothing could be read from the reader * @throws TikaException in case of parse failure by Gson or IO failure with Reader */ public static Metadata fromJson(Reader reader) throws TikaException { Metadata m = null; try { m = GSON.fromJson(reader, Metadata.class); } catch (com.google.gson.JsonParseException e){ //covers both io and parse exceptions throw new TikaException(e.getMessage()); } return m; }
} catch (com.google.gson.JsonParseException e){ throw new TikaException(e.getMessage());
private Object readObject(HttpInputMessage inputMessage, TypeToken<?> token) throws IOException { try (Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()))) { return this.gsonForReader.fromJson(json, token.getType()); } catch (JsonParseException ex) { throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex); } } }
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) { return; } String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } }
DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (InvalidDataException ex) { log.debug(String.format("Invalid request body: %s", body));
DefaultHandler.sendErrorResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (InvalidDataException ex) { log.debug(String.format("Invalid request body: %s", body));
@Override public Response toResponse(JsonParseException e) { return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build(); } }
@Override public boolean isValidJson(String message) { checkNotNull(message, "Message must not be null"); checkArgument(!message.isEmpty(), "Message must not be empty"); LOGGER.debug("Validating message: {}", message); try { jsonParser.parse(message); LOGGER.debug("Validation successful"); return true; } catch (JsonParseException e) { LOGGER.debug("Validation failed: {}", e.getMessage(), e); return false; } }
public Report[] convertJsonToReportPojos(final String json) throws CluecumberPluginException { Report[] reports; try { reports = gsonParserWithProcessors.fromJson(json, Report[].class); } catch (JsonParseException e) { throw new CluecumberPluginException(e.getMessage()); } return reports; } }
/** * Read metadata from reader. * * @param reader reader to read from * @return Metadata or null if nothing could be read from the reader * @throws TikaException in case of parse failure by Gson or IO failure with Reader */ public static Metadata fromJson(Reader reader) throws TikaException { Metadata m = null; try { m = GSON.fromJson(reader, Metadata.class); } catch (com.google.gson.JsonParseException e){ //covers both io and parse exceptions throw new TikaException(e.getMessage()); } return m; }
private void loadExclusivePIDList() { try (FileReader reader = new FileReader(exclusivePIDStore)) { exclusivePIDMap = gson.fromJson(reader, ExclusivePIDMap.class); if (exclusivePIDMap != null) { exclusivePIDMap.initializeProcessPIDMapping(); } } catch (JsonSyntaxException | JsonIOException e) { logger.error("Error parsing exclusive pids from '{}': {}", exclusivePIDStore.getAbsolutePath(), e.getMessage()); } catch (IOException e) { logger.debug("Error loading exclusive pids from '{}': {}", exclusivePIDStore.getAbsolutePath(), e.getMessage()); } finally { if (exclusivePIDMap == null) { exclusivePIDMap = new ExclusivePIDMap(); } } }
public static BidResponse.Builder parse(final String result, final SSPAdapter adapter) { RtbResponseLogProcessor.instance.setLogData(result, "bidresponse", adapter.getName()); try { // TODO: define new responsetype final BidResponse response = gson.fromJson(result, BidResponse.class); return response.getBuilder(); } catch (final JsonIOException | JsonSyntaxException e) { log.error(e.getMessage()); } return null; } }
@SuppressWarnings("unchecked") public <T> T fromJson(String input, Class<T> clazz) throws PubNubException { try { return this.objectMapper.fromJson(input, clazz); } catch (JsonParseException e) { throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_PARSING_ERROR).errormsg(e.getMessage()).build(); } }
public String toJson(Object input) throws PubNubException { try { return this.objectMapper.toJson(input); } catch (JsonParseException e) { throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_JSON_ERROR).errormsg(e.getMessage()).build(); } }
private static <T> T getNonEmptyJsonPrimitiveValue( JsonObject object, String elementName, PrimitiveJsonValueGetter<T> getter ) { assert object != null; assert !StringUtils.isEmpty(elementName); try { JsonElement element = object.get( elementName ); if( element == null ) { RequestException ex = RequestException.forJsonElementMissing(elementName); logger.error( ex.getMessage(), ex ); throw ex; } // Take into account that the element must be a primitive, and then a string! T result = null; if( element.isJsonPrimitive() ) { result = getter.checkedGet( (JsonPrimitive) element ); } if( result == null ) { RequestException ex = RequestException.forJsonElementMustBeANonNullOrEmptyValue(elementName, getter.getValueType() ); logger.error( ex.getMessage(), ex ); throw ex; } return result; } catch( JsonParseException e ) { String message = "Probably a DirectJNgine BUG: there should not be JSON parse exceptions: we should have checked ALL error conditions. " + e.getMessage(); logger.error( message, e ); assert false : message; throw e; // Just to make the compiler happy -because of the assert } }
@Override protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders())); try { Type typeOfT = getType(); if (typeOfT != null) { return this.gson.fromJson(json, typeOfT); } else { return this.gson.fromJson(json, clazz); } } catch (JsonSyntaxException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (JsonIOException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (JsonParseException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } }
private static NameMappings parseNameMappings(String jsonStr) { // Result to be returned NameMappings nameMappings; // Check if the Json is empty if (jsonStr == null || jsonStr.isEmpty()) { LOGGER.debug("No Json to parse"); return null; } // if // Parse the Json string Gson gson = new Gson(); try { nameMappings = gson.fromJson(jsonStr, NameMappings.class); LOGGER.debug("Name mappings Json parsed: " + nameMappings.toString()); } catch (JsonIOException | JsonSyntaxException e) { LOGGER.error("Runtime error (" + e.getMessage() + ")"); return null; } // try catch // Check if any of the mappings is not valid, e.g. some field is missing nameMappings.purge(); LOGGER.debug("Name mappings Json purged: " + nameMappings.toString()); // Pre-compile the regular expressions nameMappings.compilePatterns(); LOGGER.debug("Regular expressions within name mappings Json were pre-compiled"); return nameMappings; } // parseNameMappings
@Test public void givenNullTypeField_whenReadingJson_thenExpectException() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GsonPath.createTypeAdapterFactory(TestGsonTypeFactory.class)) .create(); ClassLoader classLoader = ClassLoader.getSystemClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("Polymorphism_type_is_null.json"); try { gson.fromJson(new InputStreamReader(resourceAsStream), TypesList.class); } catch (JsonParseException e) { // Since the mandatory value is not found, we are expecting an exception. Assert.assertEquals(JsonParseException.class, e.getClass()); Assert.assertEquals("cannot deserialize gsonpath.polymorphism.Type because the subtype field 'type' is either null or does not exist.", e.getMessage()); return; } Assert.fail("Expected JsonParseException was not triggered"); }
@Test void parse_invalid_token() { assertEquals("Attributes 'line' and 'column' are mandatory on 'token' object.", assertThrows(JsonParseException.class, () -> UastNode.from(new StringReader("{ token: { } }"))) .getMessage()); }