@Test public void testJsonParseException(@Mocked Response response, @Mocked ResponseBuilder builder) { exMapper.toResponse(new JsonParseException("TestException", JsonLocation.NA)); new Verifications() {{ ResponseBuilder rb; Status s; String json; rb = Response.status(s = withCapture()); times = 1; rb.entity(json = withCapture()); times = 1; Assert.assertEquals(Response.Status.BAD_REQUEST, s); Assert.assertTrue("Stringified json should include status 400: [" + json + "]", json.contains("\"status\":400")); Assert.assertTrue("Stringified json should include message containing exception's message: [" + json + "]", json.contains("\"message\":\"TestException\\n at [Source: N/A; line: -1, column: -1]\"")); Assert.assertFalse("Stringified json should not include info: [" + json + "]", json.contains("more_info")); }}; }
@Test public void testDelegateDeclaredExceptionPropagation() throws Exception { doThrow(new JsonParseException("Simulated declared exception", JsonLocation.NA)).when(_delegate).doIt(); TestInterface service = _serviceFactory.create(_remoteEndPoint); try { service.doIt(); fail("JsonParseException not thrown"); } catch (JsonParseException e) { assertEquals(e.getOriginalMessage(), "Simulated declared exception"); } assertEquals(_metricRegistry.getMeters().get("bv.emodb.web.partition-forwarding.TestInterface.errors").getCount(), 0); verify(_delegateServiceFactory).create(_remoteEndPoint); verify(_delegate).doIt(); }
JsonState( final JsonToken token, final String text, final String name, final int intValue, final String stringValue, final long longValue, final double doubleValue, final boolean booleanValue, final JsonLocation location) { this.token = token; this.text = text; this.name = name; this.intValue = intValue; this.stringValue = stringValue; this.longValue = longValue; this.doubleValue = doubleValue; this.booleanValue = booleanValue; this.location = location; }
@Test public void testSafeObjectMapperWriteValueAsStringJsonParseException() { // Create a tag entity. final TagEntity tagEntity = tagDaoTestHelper.createTagEntity(TAG_TYPE, TAG_CODE, TAG_DISPLAY_NAME, TAG_DESCRIPTION); // Mock the external calls. when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); // Call the method being tested. String result = tagHelper.safeObjectMapperWriteValueAsString(tagEntity); // Verify the external calls. verify(jsonHelper).objectToJson(any()); verifyNoMoreInteractions(alternateKeyHelper, jsonHelper); // Validate the returned object. assertEquals("", result); }
@Test public void testHandle() throws Exception { // Given JsonLocation loc = new JsonLocation(null, 1L, 1, 1, 1); Class<?> clz = UnrecognizedPropertyException.class; Collection<Object> fields = Arrays.asList("field1", "field2"); String propName = "propName"; String message = "message"; UnrecognizedPropertyException e = new UnrecognizedPropertyException(message, loc, clz, propName, fields); MessageResource expected = new UnrecognizedPropertyMessageResource(MessageType.ERROR, "Unrecognized Property sent", propName, fields.stream().map(field -> field.toString()).collect(Collectors.toList())); // When MessageResource actual = unit.handle(e); // Then assertEquals(expected, actual); }
@Override public AbstractNode deserialize(JsonParser p, DeserializationContext context) throws IOException, JsonProcessingException { JsonLocation startLocation = p.getTokenLocation(); if (p.getCurrentToken() == JsonToken.FIELD_NAME) { p.nextToken(); } switch (p.getCurrentToken()) { case START_OBJECT: return deserializeObjectNode(p, context, startLocation); case START_ARRAY: return deserializeArrayNode(p, context, startLocation); default: return deserializeValueNode(p, context, startLocation); } }
protected ObjectNode deserializeObjectNode(JsonParser p, DeserializationContext context, JsonLocation startLocation) throws IllegalArgumentException, IOException { final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL); final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT); final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER); final ObjectNode node = model.objectNode(parent, ptr); node.setStartLocation(createLocation(startLocation)); while (p.nextToken() != JsonToken.END_OBJECT) { String name = p.getCurrentName(); JsonPointer pp = JsonPointer.compile(ptr.toString() + "/" + name.replaceAll("/", "~1")); context.setAttribute(ATTRIBUTE_PARENT, node); context.setAttribute(ATTRIBUTE_POINTER, pp); AbstractNode v = deserialize(p, context); v.setProperty(name); node.put(name, v); } node.setEndLocation(createLocation(p.getCurrentLocation())); return node; }
protected ArrayNode deserializeArrayNode(JsonParser p, DeserializationContext context, JsonLocation startLocation) throws IOException { final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL); final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT); final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER); ArrayNode node = model.arrayNode(parent, ptr); int i = 0; while (p.nextToken() != JsonToken.END_ARRAY) { JsonPointer pp = JsonPointer.compile(ptr.toString() + "/" + i); context.setAttribute(ATTRIBUTE_PARENT, node); context.setAttribute(ATTRIBUTE_POINTER, pp); AbstractNode v = deserialize(p, context); node.add(v); i++; } node.setStartLocation(createLocation(startLocation)); node.setEndLocation(createLocation(p.getCurrentLocation())); return node; }
@SuppressWarnings("unchecked") private void readSingle(EB msg, JsonParser par, XB ext) throws IOException { if (isJsonObject) { startObject(par); } boolean extRead = false; JsonToken tokLast = par.getCurrentToken(); JsonLocation locLast = par.getCurrentLocation(); while (endObject(par) && (isJsonObject || filter(par))) { read(ext, par); if (par.getCurrentToken() != tokLast || !par.getCurrentLocation().equals(locLast)) { extRead = true; par.nextToken(); tokLast = par.getCurrentToken(); locLast = par.getCurrentLocation(); } else { break; } } if (extRead) { msg.setExtension(key, ext.build()); } if (isJsonObject) { par.nextToken(); } }
@SuppressWarnings("unchecked") private void readRepeated(EB msg, JsonParser par) throws IOException { par.nextToken(); JsonToken tokLast = par.getCurrentToken(); JsonLocation locLast = par.getCurrentLocation(); for (startArray(par); endArray(par); par.nextToken()) { boolean objRead = false; XB ext = (XB) key.getMessageDefaultInstance().toBuilder(); for (startObject(par); endObject(par); par.nextToken()) { read(ext, par); JsonToken tokNew = par.getCurrentToken(); JsonLocation locNew = par.getCurrentLocation(); if (tokNew != tokLast || !locNew.equals(locLast)) { objRead = true; } tokLast = tokNew; locLast = locNew; } if (objRead) { msg.addExtension(key, ext.build()); } } }
private String getLocationString() { JsonLocation l = parser.getCurrentLocation(); List<String> parts = new ArrayList<>(4); parts.add("line: " + l.getLineNr()); parts.add("column: " + l.getColumnNr()); if (l.getByteOffset() >= 0) { parts.add("byte offset: " + l.getByteOffset()); } return parts.toString(); }
@Override public XContentLocation getTokenLocation() { JsonLocation loc = parser.getTokenLocation(); if (loc == null) { return null; } return new XContentLocation(loc.getLineNr(), loc.getColumnNr()); }
@Override public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonLocation l = jp.getTokenLocation(); // logger.debug("Reading tree."); TreeNode n = jp.readValueAsTree(); // logger.debug("Tree {}", n); if (n instanceof JsonNode) { return new JSONOptions( (JsonNode) n, l); } else { throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n)); } }
private static String getJacksonProcessingExceptionMessage(JsonProcessingException ex) { JsonLocation loc = ex.getLocation(); if (loc != null) { return String.format("Failed to decode JSON at line: %s, column: %s", loc.getLineNr(), loc.getColumnNr()); } return "Failed to decode JSON"; }
@Override protected JsonFormatException error(@NotNull String message) { final JsonLocation location = currentLocation(); return new JsonFormatException( String.format( "%s at line %s column %s", message, location.getLineNr(), location.getColumnNr() ) ); }
@Test public void testExecuteFunctionForBusinessObjectDefinitionEntitiesJsonParseException() { // Create a list of business object definition entities. final List<BusinessObjectDefinitionEntity> businessObjectDefinitionEntities = Collections.unmodifiableList(Arrays.asList( businessObjectDefinitionDaoTestHelper.createBusinessObjectDefinitionEntity(BDEF_NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, BDEF_DESCRIPTION, businessObjectDefinitionServiceTestHelper.getNewAttributes()), businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(BDEF_NAMESPACE_2, BDEF_NAME_2, DATA_PROVIDER_NAME_2, BDEF_DESCRIPTION_2, businessObjectDefinitionServiceTestHelper.getNewAttributes2()))); businessObjectDefinitionEntities.forEach(entity -> { entity.setDescriptiveBusinessObjectFormat(new BusinessObjectFormatEntity()); entity.getDescriptiveBusinessObjectFormat().setSchemaColumns(new ArrayList<>()); entity.setSubjectMatterExperts(new ArrayList<>()); }); // Mock the external calls. when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); // Execute a function for all business object definition entities. businessObjectDefinitionHelper .executeFunctionForBusinessObjectDefinitionEntities(SEARCH_INDEX_NAME, SEARCH_INDEX_DOCUMENT_TYPE, businessObjectDefinitionEntities, (indexName, documentType, id, json) -> { }); // Verify the external calls. verify(jsonHelper, times(businessObjectDefinitionEntities.size())).objectToJson(any()); verifyNoMoreInteractions(alternateKeyHelper, jsonHelper); }
@Test public void testIndexSpotCheckPercentageValidationTagsObjectMappingException() throws Exception { // Create a tag type entity. TagTypeEntity tagTypeEntity = tagTypeDaoTestHelper.createTagTypeEntity(TAG_TYPE, TAG_TYPE_DISPLAY_NAME, TAG_TYPE_ORDER, TAG_TYPE_DESCRIPTION); // Create two root tag entities for the tag type with tag display name in reverse order. List<TagEntity> rootTagEntities = Arrays.asList(tagDaoTestHelper.createTagEntity(tagTypeEntity, TAG_CODE, TAG_DISPLAY_NAME_2, TAG_DESCRIPTION), tagDaoTestHelper.createTagEntity(tagTypeEntity, TAG_CODE_2, TAG_DISPLAY_NAME, TAG_DESCRIPTION_2)); // Mock the call to external methods when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_TAG_SPOT_CHECK_PERCENTAGE, Double.class)).thenReturn(0.2); when(tagDao.getPercentageOfAllTags(0.2)).thenReturn(rootTagEntities); when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class)).thenReturn("DOCUMENT_TYPE"); when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); // Call the method under test boolean isSpotCheckPercentageValid = tagService.indexSpotCheckPercentageValidationTags(SEARCH_INDEX_TYPE_TAG); assertThat("Tag service index spot check random validation is true when it should have been false.", isSpotCheckPercentageValid, is(false)); // Verify the calls to external methods verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_TAG_SPOT_CHECK_PERCENTAGE, Double.class); verify(tagDao).getPercentageOfAllTags(0.2); verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class); verify(tagHelper, times(2)).safeObjectMapperWriteValueAsString(any(TagEntity.class)); verifyNoMoreInteractions(tagDao, configurationHelper, jsonHelper); }
@Test public void testIndexSpotCheckMostRecentValidationTagsObjectMappingException() throws Exception { // Create a tag type entity. TagTypeEntity tagTypeEntity = tagTypeDaoTestHelper.createTagTypeEntity(TAG_TYPE, TAG_TYPE_DISPLAY_NAME, TAG_TYPE_ORDER, TAG_TYPE_DESCRIPTION); // Create two root tag entities for the tag type with tag display name in reverse order. List<TagEntity> rootTagEntities = Arrays.asList(tagDaoTestHelper.createTagEntity(tagTypeEntity, TAG_CODE, TAG_DISPLAY_NAME_2, TAG_DESCRIPTION), tagDaoTestHelper.createTagEntity(tagTypeEntity, TAG_CODE_2, TAG_DISPLAY_NAME, TAG_DESCRIPTION_2)); // Mock the call to external methods when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_TAG_SPOT_CHECK_MOST_RECENT_NUMBER, Integer.class)).thenReturn(10); when(tagDao.getMostRecentTags(10)).thenReturn(rootTagEntities); when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class)).thenReturn("DOCUMENT_TYPE"); when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); when(indexFunctionsDao.isValidDocumentIndex(any(), any(), any(), any())).thenReturn(false); // Call the method under test boolean isSpotCheckMostRecentValid = tagService.indexSpotCheckMostRecentValidationTags(SEARCH_INDEX_TYPE_TAG); assertThat("Tag service index spot check most recent validation is true when it should have been false.", isSpotCheckMostRecentValid, is(false)); // Verify the calls to external methods verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_TAG_SPOT_CHECK_MOST_RECENT_NUMBER, Integer.class); verify(tagDao).getMostRecentTags(10); verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class); verify(tagHelper, times(2)).safeObjectMapperWriteValueAsString(any(TagEntity.class)); verify(indexFunctionsDao, times(2)).isValidDocumentIndex(any(), any(), any(), any()); verifyNoMoreInteractions(tagDao, indexFunctionsDao, configurationHelper, jsonHelper, tagHelper); }
@Test public void testIndexSpotCheckPercentageValidationBusinessObjectDefinitionsObjectMappingException() throws Exception { List<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityList = new ArrayList<>(); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, BDEF_DESCRIPTION, businessObjectDefinitionServiceTestHelper.getNewAttributes())); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME_2, DATA_PROVIDER_NAME_2, BDEF_DESCRIPTION_2, businessObjectDefinitionServiceTestHelper.getNewAttributes())); // Mock the call to external methods when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_SPOT_CHECK_PERCENTAGE, Double.class)).thenReturn(0.05); when(businessObjectDefinitionDao.getPercentageOfAllBusinessObjectDefinitions(0.05)).thenReturn(businessObjectDefinitionEntityList); when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class)).thenReturn(SEARCH_INDEX_DOCUMENT_TYPE); when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); when(indexFunctionsDao.isValidDocumentIndex(any(), any(), any(), any())).thenReturn(false); // Call the method under test boolean isSpotCheckPercentageValid = businessObjectDefinitionService.indexSpotCheckPercentageValidationBusinessObjectDefinitions(SEARCH_INDEX_NAME); assertThat("Business object definition service index spot check random validation is true when it should have been false.", isSpotCheckPercentageValid, is(false)); // Verify the calls to external methods verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_SPOT_CHECK_PERCENTAGE, Double.class); verify(businessObjectDefinitionDao).getPercentageOfAllBusinessObjectDefinitions(0.05); verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class); verify(businessObjectDefinitionHelper, times(2)).safeObjectMapperWriteValueAsString(any(BusinessObjectDefinitionEntity.class)); verify(indexFunctionsDao, times(2)).isValidDocumentIndex(any(), any(), any(), any()); verifyNoMoreInteractionsHelper(); }
@Test public void testIndexSpotCheckMostRecentValidationBusinessObjectDefinitionsObjectMappingException() throws Exception { List<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityList = new ArrayList<>(); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, BDEF_DESCRIPTION, businessObjectDefinitionServiceTestHelper.getNewAttributes())); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME_2, DATA_PROVIDER_NAME_2, BDEF_DESCRIPTION_2, businessObjectDefinitionServiceTestHelper.getNewAttributes())); // Mock the call to external methods when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_SPOT_CHECK_MOST_RECENT_NUMBER, Integer.class)).thenReturn(100); when(businessObjectDefinitionDao.getMostRecentBusinessObjectDefinitions(100)).thenReturn(businessObjectDefinitionEntityList); when(configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class)).thenReturn(SEARCH_INDEX_DOCUMENT_TYPE); when(jsonHelper.objectToJson(any())) .thenThrow(new IllegalStateException(new JsonParseException("Failed to Parse", new JsonLocation("SRC", 100L, 1, 2)))); when(indexFunctionsDao.isValidDocumentIndex(any(), any(), any(), any())).thenReturn(false); // Call the method under test boolean isSpotCheckPercentageValid = businessObjectDefinitionService.indexSpotCheckMostRecentValidationBusinessObjectDefinitions(SEARCH_INDEX_NAME); assertThat("Business object definition service index spot check most recent validation is true when it should have been false.", isSpotCheckPercentageValid, is(false)); // Verify the calls to external methods verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_SPOT_CHECK_MOST_RECENT_NUMBER, Integer.class); verify(businessObjectDefinitionDao).getMostRecentBusinessObjectDefinitions(100); verify(configurationHelper).getProperty(ConfigurationValue.ELASTICSEARCH_BDEF_DOCUMENT_TYPE, String.class); verify(businessObjectDefinitionHelper, times(2)).safeObjectMapperWriteValueAsString(any(BusinessObjectDefinitionEntity.class)); verify(indexFunctionsDao, times(2)).isValidDocumentIndex(any(), any(), any(), any()); verifyNoMoreInteractionsHelper(); }
@Override public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode rootNode = jp.readValueAsTree(); User user = MAPPER.readValue(rootNode.traverse(), User.class); if (user.getSchemas() == null) { throw new JsonMappingException(jp, "Required field 'schemas' is missing"); } if (user.getSchemas().size() == 1) { return user; } User.Builder builder = new User.Builder(user); for (String urn : user.getSchemas()) { if (urn.equals(schema)) { continue; } JsonNode extensionNode = rootNode.get(urn); if (extensionNode == null) { throw new JsonParseException(jp, "Registered extension not present: " + urn, JsonLocation.NA); } builder.addExtension(deserializeExtension(jp, extensionNode, urn)); } return builder.build(); }
@Override public Response toResponse(JsonParseException e) { final JsonLocation l = e.getLocation(); return Response .status(Response.Status.BAD_REQUEST) .entity(new JsonParseErrorMessage(e.getOriginalMessage(), Response.Status.BAD_REQUEST, l.getLineNr(), l.getColumnNr())) .type(MediaType.APPLICATION_JSON) .build(); }
private void initializeJsonLocation(@Nullable JsonLocation jsonLoc) { if (jsonLoc == null) { return; } this.charOffset = ((int) jsonLoc.getCharOffset()); this.colNum = jsonLoc.getColumnNr(); this.lineNum = jsonLoc.getLineNr(); }
protected ValueNode deserializeValueNode(JsonParser p, DeserializationContext context, JsonLocation startLocation) throws IOException { final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL); final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT); final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER); Object v = context.readValue(p, Object.class); ValueNode node = model.valueNode(parent, ptr, v); node.setStartLocation(createLocation(startLocation)); node.setEndLocation(createLocation(p.getCurrentLocation())); return node; }
public UnrecognizedPropertyException(String paramString1, JsonLocation paramJsonLocation, Class<?> paramClass, String paramString2, Collection<Object> paramCollection) { super(paramString1, paramJsonLocation); this._referringClass = paramClass; this._unrecognizedPropertyName = paramString2; this._propertyIds = paramCollection; }
public static JsonMappingException from(JsonParser paramJsonParser, String paramString) { JsonLocation localJsonLocation; if (paramJsonParser == null) localJsonLocation = null; else localJsonLocation = paramJsonParser.getTokenLocation(); return new JsonMappingException(paramString, localJsonLocation); }
public static JsonMappingException from(JsonParser paramJsonParser, String paramString, Throwable paramThrowable) { JsonLocation localJsonLocation; if (paramJsonParser == null) localJsonLocation = null; else localJsonLocation = paramJsonParser.getTokenLocation(); return new JsonMappingException(paramString, localJsonLocation, paramThrowable); }
protected final void _reportInvalidBase64(Base64Variant paramBase64Variant, char paramChar, int paramInt, String paramString) { String str; if (paramChar <= ' ') str = "Illegal white space character (code 0x" + Integer.toHexString(paramChar) + ") as character #" + (paramInt + 1) + " of 4-char base64 unit: can only used between units"; else if (paramBase64Variant.usesPaddingChar(paramChar)) str = "Unexpected padding character ('" + paramBase64Variant.getPaddingChar() + "') as character #" + (paramInt + 1) + " of 4-char base64 unit: padding only legal as 3rd or 4th character"; else if ((!Character.isDefined(paramChar)) || (Character.isISOControl(paramChar))) str = "Illegal character (code 0x" + Integer.toHexString(paramChar) + ") in base64 content"; else str = "Illegal character '" + paramChar + "' (code 0x" + Integer.toHexString(paramChar) + ") in base64 content"; if (paramString != null) str = str + ": " + paramString; throw new JsonParseException(str, JsonLocation.NA); }
@Override public void doSerializeV3(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); if (property.getMetadata() != null) { jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString()); } final Element content = property.getContent(); if (XMLUtils.hasOnlyTextChildNodes(content)) { jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent()); } else { try { final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY); if (XMLUtils.hasElementsChildNode(content)) { wrapper.appendChild(document.renameNode( document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtils.writeSubtree(client, jgen, wrapper); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { wrapper.appendChild(document.renameNode( document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtilsV3.writeSubtree(client, jgen, wrapper, true); } else { DOMTreeUtils.writeSubtree(client, jgen, content); } } catch (Exception e) { throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e); } } jgen.writeEndObject(); }
@Override public void doSerializeV4(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); final Element content = property.getContent(); if (XMLUtils.hasOnlyTextChildNodes(content)) { jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent()); } else { try { final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY); if (XMLUtils.hasElementsChildNode(content)) { wrapper.appendChild(document.renameNode( document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtils.writeSubtree(client, jgen, wrapper); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { wrapper.appendChild(document.renameNode( document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtilsV4.writeSubtree(client, jgen, wrapper, true); } else { DOMTreeUtils.writeSubtree(client, jgen, content); } } catch (Exception e) { throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e); } } jgen.writeEndObject(); }
@Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); try { return sdf.parse(jsonParser.getText()); } catch (ParseException ex) { try { long numericDate = Long.parseLong(jsonParser.getText()); return new Date(numericDate); } catch (NumberFormatException ex2) { throw new JsonParseException ("El formato de la fecha '" + jsonParser.getText() + "' no es correcto",JsonLocation.NA); } } }
private void throwParsingError(JsonLocation jsonLocation, String message) { throw BusinessException.createNew(DataErrorCode.FAILED_TO_PARSE_DATA_STREAM) .put("parsingError", message) .put("line", jsonLocation.getLineNr()) .put("col", jsonLocation.getColumnNr()) .put("offset", jsonLocation.getCharOffset()); }
/** * Constructs a {@link JacksonStreamReaderImpl} with the provided {@link JsonParser}. * * @param jp * JsonParser from which to get tokens * @throws IOException * Null JsonParser or error getting token */ public JacksonStreamReaderImpl(final JsonParser jp) throws IOException { if (jp == null) { throw new JacksonStreamReaderException("JsonParser cannot be null", JsonLocation.NA); } this.jp = jp; if (jp.getCurrentToken() == null) { jp.nextToken(); } }
@Test public void shouldTranslateJsonParseException() { String originalMessage = "originalMessage"; JsonParseException jsonParseException = new JsonParseException(originalMessage, JsonLocation.NA); Exception translatedException = JsonProcessingExceptionTranslator.translateJsonProcessingException(jsonParseException); assertThat(translatedException, instanceOf(DNSAPIClientJsonMappingException.class)); assertEquals(DNSAPIClientJsonMappingException.DNSAPIClientJsonMappingExceptionCode.unexpectedMappingError, ((DNSAPIClientJsonMappingException) translatedException).getExceptionCode()); assertArrayEquals(new Object[] {"unknown", originalMessage + "\n at [Source: N/A; line: -1, column: -1]"}, ((DNSAPIClientJsonMappingException) translatedException).getObjects()); }
@Override public JsonLocation getTokenLocation() { ConfigValue current = currentConfig(); if (current == null) { return JsonLocation.NA; } ConfigOrigin nodeOrigin = current.origin(); return new JsonLocation(current, -1, nodeOrigin.lineNumber(), -1); }