com.fasterxml.jackson.databind.node.JsonNodeType Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.node.JsonNodeType.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PacketHandler.java From BedrockConnect with GNU General Public License v3.0 | 7 votes |
private static boolean validateChainData(JsonNode data) throws Exception { ECPublicKey lastKey = null; boolean validChain = false; for (JsonNode node : data) { JWSObject jwt = JWSObject.parse(node.asText()); if (!validChain) { validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey()); } if (lastKey != null) { verifyJwt(jwt, lastKey); } JsonNode payloadNode = Server.JSON_MAPPER.readTree(jwt.getPayload().toString()); JsonNode ipkNode = payloadNode.get("identityPublicKey"); Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain"); lastKey = EncryptionUtils.generateKey(ipkNode.asText()); } return validChain; }
Example #2
Source File: DslJsonSerializerTest.java From apm-agent-java with Apache License 2.0 | 6 votes |
@Test void testSpanStackFrameSerialization() { Span span = new Span(MockTracer.create()); span.setStackTrace(Arrays.asList(StackFrame.of("foo.Bar", "baz"), StackFrame.of("foo.Bar$Baz", "qux"))); JsonNode spanJson = readJsonString(serializer.toJsonString(span)); JsonNode jsonStackTrace = spanJson.get("stacktrace"); assertThat(jsonStackTrace.getNodeType()).isEqualTo(JsonNodeType.ARRAY); assertThat(jsonStackTrace).isNotNull(); assertThat(jsonStackTrace).hasSize(2); assertThat(jsonStackTrace.get(0).get("filename").textValue()).isEqualTo("Bar.java"); assertThat(jsonStackTrace.get(0).get("function").textValue()).isEqualTo("baz"); assertThat(jsonStackTrace.get(0).get("library_frame").booleanValue()).isTrue(); assertThat(jsonStackTrace.get(0).get("lineno").intValue()).isEqualTo(-1); assertThat(jsonStackTrace.get(0).get("module")).isNull(); assertThat(jsonStackTrace.get(1).get("filename").textValue()).isEqualTo("Bar.java"); assertThat(jsonStackTrace.get(1).get("function").textValue()).isEqualTo("qux"); assertThat(jsonStackTrace.get(1).get("library_frame").booleanValue()).isTrue(); assertThat(jsonStackTrace.get(1).get("lineno").intValue()).isEqualTo(-1); assertThat(jsonStackTrace.get(1).get("module")).isNull(); }
Example #3
Source File: JsonUtil.java From besu with Apache License 2.0 | 6 votes |
public static Optional<ArrayNode> getArrayNode( final ObjectNode json, final String fieldKey, final boolean strict) { final JsonNode obj = json.get(fieldKey); if (obj == null || obj.isNull()) { return Optional.empty(); } if (!obj.isArray()) { if (strict) { validateType(obj, JsonNodeType.ARRAY); } else { return Optional.empty(); } } return Optional.of((ArrayNode) obj); }
Example #4
Source File: JerseyApplicationTest.java From katharsis-framework with Apache License 2.0 | 6 votes |
@Test public void testGetTasks() throws Exception { Response response = target("/tasks").request().get(); assertResponseStatus(response, Response.Status.OK); assertHeader(response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API); JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data"); assertThat(data.getNodeType(), is(JsonNodeType.ARRAY)); List<Task> tasks = new ArrayList<>(); for (JsonNode node : data) { tasks.add(getTaskFromJson(node)); } assertThat(tasks, hasSize(1)); final Task task = tasks.get(0); assertThat(task.getId(), is(1L)); assertThat(task.getName(), is("First task")); assertThat(task.getProject(), is(nullValue())); }
Example #5
Source File: ServerErrorSerializerTest.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Test public void verifiedWithJacksonParser() throws Exception { ODataServerError error = new ODataServerError().setCode("Code").setMessage("Message").setTarget("Target") .setDetails(Collections.singletonList( new ODataErrorDetail().setCode("detailCode").setMessage("detailMessage").setTarget("detailTarget"))); InputStream stream = ser.error(error).getContent(); JsonNode tree = new ObjectMapper().readTree(stream); assertNotNull(tree); tree = tree.get("error"); assertNotNull(tree); assertEquals("Code", tree.get("code").textValue()); assertEquals("Message", tree.get("message").textValue()); assertEquals("Target", tree.get("target").textValue()); tree = tree.get("details"); assertNotNull(tree); assertEquals(JsonNodeType.ARRAY, tree.getNodeType()); tree = tree.get(0); assertNotNull(tree); assertEquals("detailCode", tree.get("code").textValue()); assertEquals("detailMessage", tree.get("message").textValue()); assertEquals("detailTarget", tree.get("target").textValue()); }
Example #6
Source File: JsonParsingServiceTest.java From konker-platform with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { expectedFlattenMap = new HashMap<>(); expectedFlattenMap.put("ts", JsonParsingService.JsonPathData.builder() .value("2016-03-03T18:15:00Z") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("value", JsonParsingService.JsonPathData.builder() .value(31.0) .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build()); expectedFlattenMap.put("command.type", JsonParsingService.JsonPathData.builder() .value("ButtonPressed") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("data.channels.0.name", JsonParsingService.JsonPathData.builder() .value("channel_0") .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.ARRAY,JsonNodeType.OBJECT,JsonNodeType.STRING})).build()); expectedFlattenMap.put("time", JsonParsingService.JsonPathData.builder() .value(123L) .types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build()); }
Example #7
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 6 votes |
public List<Server> getServersList(ArrayNode obj, String location, ParseResult result, String path) { List<Server> servers = new ArrayList<>(); if (obj == null) { return null; } for (JsonNode item : obj) { if (item.getNodeType().equals(JsonNodeType.OBJECT)) { Server server = getServer((ObjectNode) item, location, result, path); if (server != null) { servers.add(server); }else{ Server defaultServer = new Server(); defaultServer.setUrl("/"); servers.add(defaultServer); } } } return servers; }
Example #8
Source File: DslJsonSerializerTest.java From apm-agent-java with Apache License 2.0 | 6 votes |
private static JsonNode checkException(JsonNode jsonException, Class<?> expectedType, String expectedMessage){ assertThat(jsonException.get("type").textValue()).isEqualTo(expectedType.getName()); assertThat(jsonException.get("message").textValue()).isEqualTo(expectedMessage); JsonNode jsonStackTrace = jsonException.get("stacktrace"); assertThat(jsonStackTrace.getNodeType()).isEqualTo(JsonNodeType.ARRAY); assertThat(jsonStackTrace).isNotNull(); for (JsonNode stackTraceElement : jsonStackTrace) { assertThat(stackTraceElement.get("filename")).isNotNull(); assertThat(stackTraceElement.get("classname")).isNotNull(); assertThat(stackTraceElement.get("function")).isNotNull(); assertThat(stackTraceElement.get("library_frame")).isNotNull(); assertThat(stackTraceElement.get("lineno")).isNotNull(); assertThat(stackTraceElement.get("module")).isNotNull(); } return jsonException; }
Example #9
Source File: OpenAPIImporter.java From microcks with Apache License 2.0 | 6 votes |
/** Get the value of an example. This can be direct value field or those of followed $ref */ private String getExampleValue(JsonNode example) { if (example.has("value")) { if (example.path("value").getNodeType() == JsonNodeType.ARRAY || example.path("value").getNodeType() == JsonNodeType.OBJECT ) { return example.path("value").toString(); } return example.path("value").asText(); } if (example.has("$ref")) { // $ref: '#/components/examples/param_laurent' String ref = example.path("$ref").asText(); JsonNode component = spec.at(ref.substring(1)); return getExampleValue(component); } return null; }
Example #10
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 6 votes |
public Integer getInteger(String key, ObjectNode node, boolean required, String location, ParseResult result) { Integer value = null; JsonNode v = node.get(key); if (node == null || v == null) { if (required) { result.missing(location, key); result.invalid(); } } else if(v.getNodeType().equals(JsonNodeType.NUMBER)) { if (v.isInt()) { value = v.intValue(); } } else if(!v.isValueNode()) { result.invalidType(location, key, "integer", node); } return value; }
Example #11
Source File: JSONUtilsTest.java From SkaETL with Apache License 2.0 | 6 votes |
@Test public void remove() { String input = "{\n" + " \"name\":\"John\",\n" + " \"age\":30,\n" + " \"cars\": {\n" + " \"car1\":\"Ford\",\n" + " \"car2\":\"BMW\",\n" + " \"car3\":\"Fiat\"\n" + " }\n" + " }"; JsonNode parse = jsonUtils.parse(input); jsonUtils.remove(parse, "age"); Assertions.assertThat(parse.at("/age").getNodeType()).isEqualTo(JsonNodeType.MISSING); jsonUtils.remove(parse, "cars.car3"); Assertions.assertThat(parse.at("/cars/cars3").getNodeType()).isEqualTo(JsonNodeType.MISSING); }
Example #12
Source File: JsonCacheImpl.java From openapi-generator with Apache License 2.0 | 6 votes |
protected JsonNodeType nodeTypeFor(Object value) { JsonNodeType type; if (value == null) { type = JsonNodeType.NULL; } else if (value instanceof Boolean) { type = JsonNodeType.BOOLEAN; } else if (value instanceof Number) { type = JsonNodeType.NUMBER; } else if (value instanceof String) { type = JsonNodeType.STRING; } else if (value instanceof ArrayNode || value instanceof List) { type = JsonNodeType.ARRAY; } else if (value instanceof byte[]) { type = JsonNodeType.BINARY; } else if (value instanceof ObjectNode || value instanceof Map) { type = JsonNodeType.OBJECT; } else { type = JsonNodeType.POJO; } return type; }
Example #13
Source File: JsonObjectMapperDecoder.java From ffwd with Apache License 2.0 | 6 votes |
private Set<String> decodeTags(JsonNode tree, String name) { final JsonNode n = tree.get(name); if (n == null) { return EMPTY_TAGS; } if (n.getNodeType() != JsonNodeType.ARRAY) { return EMPTY_TAGS; } final List<String> tags = Lists.newArrayList(); final Iterator<JsonNode> iter = n.elements(); while (iter.hasNext()) { tags.add(iter.next().asText()); } return Sets.newHashSet(tags); }
Example #14
Source File: RntbdObjectMapper.java From azure-cosmosdb-java with MIT License | 6 votes |
static ObjectNode readTree(final ByteBuf in) { checkNotNull(in, "in"); final JsonNode node; try (final InputStream istream = new ByteBufInputStream(in)) { node = objectMapper.readTree(istream); } catch (final IOException error) { throw new CorruptedFrameException(error); } if (node.isObject()) { return (ObjectNode)node; } final String cause = lenientFormat("Expected %s, not %s", JsonNodeType.OBJECT, node.getNodeType()); throw new CorruptedFrameException(cause); }
Example #15
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 6 votes |
private static Map<String, RepositoryInfo> listRepositories(AggregatedHttpResponse res) { switch (res.status().code()) { case 200: return Streams.stream(toJson(res, JsonNodeType.ARRAY)) .map(node -> { final String name = getField(node, "name").asText(); final Revision headRevision = new Revision(getField(node, "headRevision").asInt()); return new RepositoryInfo(name, headRevision); }) .collect(toImmutableMap(RepositoryInfo::name, Function.identity())); case 204: return ImmutableMap.of(); } return handleErrorResponse(res); }
Example #16
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 6 votes |
/** * Parses the content of the specified {@link AggregatedHttpResponse} into a {@link JsonNode}. */ private static JsonNode toJson(AggregatedHttpResponse res, @Nullable JsonNodeType expectedNodeType) { final String content = toString(res); final JsonNode node; try { node = Jackson.readTree(content); } catch (JsonParseException e) { throw new CentralDogmaException("failed to parse the response JSON", e); } if (expectedNodeType != null && node.getNodeType() != expectedNodeType) { throw new CentralDogmaException( "invalid server response; expected: " + expectedNodeType + ", actual: " + node.getNodeType() + ", content: " + content); } return node; }
Example #17
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 6 votes |
private static <T> T handleErrorResponse(AggregatedHttpResponse res) { final HttpStatus status = res.status(); if (status.codeClass() != HttpStatusClass.SUCCESS) { final JsonNode node = toJson(res, JsonNodeType.OBJECT); final JsonNode exceptionNode = node.get("exception"); final JsonNode messageNode = node.get("message"); if (exceptionNode != null) { final String typeName = exceptionNode.textValue(); if (typeName != null) { final Function<String, CentralDogmaException> exceptionFactory = EXCEPTION_FACTORIES.get(typeName); if (exceptionFactory != null) { throw exceptionFactory.apply(messageNode.textValue()); } } } } throw new CentralDogmaException("unexpected response: " + res.headers() + ", " + res.contentUtf8()); }
Example #18
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 5 votes |
@Nullable private static <T> Change<T> getDiff(AggregatedHttpResponse res) { switch (res.status().code()) { case 200: return toChange(toJson(res, JsonNodeType.OBJECT)); case 204: return null; } return handleErrorResponse(res); }
Example #19
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 5 votes |
private static PushResult push(AggregatedHttpResponse res) { if (res.status().code() == 200) { final JsonNode node = toJson(res, JsonNodeType.OBJECT); return new PushResult( new Revision(getField(node, "revision").asInt()), Instant.parse(getField(node, "pushedAt").asText()).toEpochMilli()); } return handleErrorResponse(res); }
Example #20
Source File: IsJsonObject.java From java-hamcrest with Apache License 2.0 | 5 votes |
private static Matcher<JsonNode> createNodeMatcher(final JsonNode value) { final JsonNodeType nodeType = value.getNodeType(); switch (nodeType) { case ARRAY: return IsJsonArray.jsonArray((ArrayNode) value); case BINARY: throw new UnsupportedOperationException( "Expected value contains a binary node, which is not implemented."); case BOOLEAN: return IsJsonBoolean.jsonBoolean((BooleanNode) value); case MISSING: return IsJsonMissing.jsonMissing((MissingNode) value); case NULL: return IsJsonNull.jsonNull((NullNode) value); case NUMBER: return IsJsonNumber.jsonNumber((NumericNode) value); case OBJECT: return IsJsonObject.jsonObject((ObjectNode) value); case POJO: throw new UnsupportedOperationException( "Expected value contains a POJO node, which is not implemented."); case STRING: return IsJsonText.jsonText((TextNode) value); default: throw new UnsupportedOperationException("Unsupported node type " + nodeType); } }
Example #21
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 5 votes |
@Nullable private static <T> Entry<T> watchFile(AggregatedHttpResponse res, QueryType queryType) { switch (res.status().code()) { case 200: // OK final JsonNode node = toJson(res, JsonNodeType.OBJECT); final Revision revision = new Revision(getField(node, "revision").asInt()); return toEntry(revision, getField(node, "entry"), queryType); case 304: // Not Modified return null; } return handleErrorResponse(res); }
Example #22
Source File: JsonUtil.java From besu with Apache License 2.0 | 5 votes |
public static OptionalInt getInt(final ObjectNode node, final String key) { return getValue(node, key) .filter(jsonNode -> validateType(jsonNode, JsonNodeType.NUMBER)) .filter(JsonUtil::validateInt) .map(JsonNode::asInt) .map(OptionalInt::of) .orElse(OptionalInt.empty()); }
Example #23
Source File: JsonNumEquals.java From centraldogma with Apache License 2.0 | 5 votes |
@Override protected boolean doEquivalent(final JsonNode a, final JsonNode b) { /* * If both are numbers, delegate to the helper method */ if (a.isNumber() && b.isNumber()) { return numEquals(a, b); } final JsonNodeType typeA = a.getNodeType(); final JsonNodeType typeB = b.getNodeType(); /* * If they are of different types, no dice */ if (typeA != typeB) { return false; } /* * For all other primitive types than numbers, trust JsonNode */ if (!a.isContainerNode()) { return a.equals(b); } /* * OK, so they are containers (either both arrays or objects due to the * test on types above). They are obviously not equal if they do not * have the same number of elements/members. */ if (a.size() != b.size()) { return false; } /* * Delegate to the appropriate method according to their type. */ return typeA == JsonNodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b); }
Example #24
Source File: InputSourceDeser.java From hugegraph-loader with Apache License 2.0 | 5 votes |
private static JsonNode getNode(JsonNode node, String name, JsonNodeType nodeType) { JsonNode subNode = node.get(name); if (subNode == null || subNode.getNodeType() != nodeType) { throw DeserializeException.expectField(name, node); } return subNode; }
Example #25
Source File: JsonQueryObjectModelConverter.java From BIMserver with GNU Affero General Public License v3.0 | 5 votes |
private void parseProperties(QueryPart queryPart, ObjectNode properties) throws QueryException { Iterator<Entry<String, JsonNode>> fields = properties.fields(); while (fields.hasNext()) { Entry<String, JsonNode> entry = fields.next(); String propertySetName = entry.getKey(); JsonNode value = entry.getValue(); if (value.isObject()) { ObjectNode set = (ObjectNode)value; Iterator<Entry<String, JsonNode>> propertySetFields = set.fields(); while (propertySetFields.hasNext()) { Entry<String, JsonNode> propertyEntry = propertySetFields.next(); JsonNode propertyValue = propertyEntry.getValue(); if (propertyValue.isValueNode()) { if (propertyValue.getNodeType() == JsonNodeType.BOOLEAN) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asBoolean()); } else if (propertyValue.getNodeType() == JsonNodeType.NUMBER) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asDouble()); } else if (propertyValue.getNodeType() == JsonNodeType.STRING) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asText()); } else if (propertyValue.getNodeType() == JsonNodeType.NULL) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), null); } } else { throw new QueryException("property \"" + propertyEntry.getKey() + "\" type not supported"); } } } else { throw new QueryException("Query language has changed, propertyset name required now"); } } }
Example #26
Source File: JerseyApplicationTest.java From crnk-framework with Apache License 2.0 | 5 votes |
@Test public void testGetProjects() throws Exception { Response response = target("/projects").request().get(); assertResponseStatus(response, Response.Status.OK); assertHeader(response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API); JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data"); assertThat(data.getNodeType(), is(JsonNodeType.ARRAY)); List<Project> projects = new ArrayList<>(); for (JsonNode node : data) { projects.add(getProjectFromJson(node)); } assertThat(projects, hasSize(4)); }
Example #27
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 5 votes |
public Map<String, Example> getExamples(ObjectNode obj, String location, ParseResult result, boolean underComponents) { if (obj == null) { return null; } Map<String, Example> examples = new LinkedHashMap<>(); Set<String> exampleKeys = getKeys(obj); for(String exampleName : exampleKeys) { if(underComponents) { if (!Pattern.matches("^[a-zA-Z0-9\\.\\-_]+$", exampleName)) { result.warning(location, "Example name " + exampleName + " doesn't adhere to regular expression ^[a-zA-Z0-9\\.\\-_]+$"); } } JsonNode exampleValue = obj.get(exampleName); if (!exampleValue.getNodeType().equals(JsonNodeType.OBJECT)) { result.invalidType(location, exampleName, "object", exampleValue); } else { ObjectNode example = (ObjectNode) exampleValue; if(example != null) { Example exampleObj = getExample(example, String.format("%s.%s", location, exampleName), result); if(exampleObj != null) { examples.put(exampleName, exampleObj); } } } } return examples; }
Example #28
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 5 votes |
public List<Example> getExampleList(ArrayNode obj, String location, ParseResult result) { List<Example> examples = new ArrayList<>(); if (obj == null) { return examples; } for (JsonNode item : obj) { if (item.getNodeType().equals(JsonNodeType.OBJECT)) { Example example = getExample((ObjectNode) item, location, result); if (example != null) { examples.add(example); } } } return examples; }
Example #29
Source File: OpenAPIDeserializer.java From swagger-parser with Apache License 2.0 | 5 votes |
public List<SecurityRequirement> getSecurityRequirementsList(ArrayNode nodes, String location, ParseResult result) { if (nodes == null) return null; List<SecurityRequirement> securityRequirements = new ArrayList<>(); for (JsonNode node : nodes) { if (node.getNodeType().equals(JsonNodeType.OBJECT)) { SecurityRequirement securityRequirement = new SecurityRequirement(); Set<String> keys = getKeys((ObjectNode) node); if (keys.size() == 0){ securityRequirements.add(securityRequirement); }else { for (String key : keys) { if (key != null) { JsonNode value = node.get(key); if (key != null && JsonNodeType.ARRAY.equals(value.getNodeType())) { ArrayNode arrayNode = (ArrayNode) value; List<String> scopes = Stream .generate(arrayNode.elements()::next) .map((n) -> n.asText()) .limit(arrayNode.size()) .collect(Collectors.toList()); securityRequirement.addList(key, scopes); } } } if (securityRequirement.size() > 0) { securityRequirements.add(securityRequirement); } } } } return securityRequirements; }
Example #30
Source File: LoginEncryptionUtils.java From Geyser with MIT License | 5 votes |
public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) { JsonNode certData; try { certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray()); } catch (IOException ex) { throw new RuntimeException("Certificate JSON can not be read."); } JsonNode certChainData = certData.get("chain"); if (certChainData.getNodeType() != JsonNodeType.ARRAY) { throw new RuntimeException("Certificate data is not valid"); } encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData); }