Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#path()
The following examples show how to use
com.fasterxml.jackson.databind.node.ObjectNode#path() .
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: RestResponseResultWriterTest.java From endpoints-java with Apache License 2.0 | 6 votes |
private void writeError(int exceptionCode, int expectedCode, String reason, String message, boolean enableExceptionCompatibility) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); RestResponseResultWriter writer = new RestResponseResultWriter( response, null, true /* prettyPrint */, true /* addContentLength */, enableExceptionCompatibility); writer.writeError(new ServiceException(exceptionCode, message)); ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class); JsonNode outerError = content.path("error"); assertThat(outerError.path("code").asInt()).isEqualTo(expectedCode); if (message == null) { assertThat(outerError.path("message").isNull()).isTrue(); } else { assertThat(outerError.path("message").asText()).isEqualTo(message); } JsonNode innerError = outerError.path("errors").path(0); assertThat(innerError.path("domain").asText()).isEqualTo("global"); assertThat(innerError.path("reason").asText()).isEqualTo(reason); if (message == null) { assertThat(innerError.path("message").isNull()).isTrue(); } else { assertThat(innerError.path("message").asText()).isEqualTo(message); } }
Example 2
Source File: JsonConfigWriterTest.java From endpoints-java with Apache License 2.0 | 6 votes |
@Test public void testEnumType() throws Exception { ObjectMapper mapper = new ObjectMapper(); ObjectNode schemasConfig = mapper.createObjectNode(); writer.addTypeToSchema(schemasConfig, TypeToken.of(Outcome.class), apiConfig, null); JsonNode outcome = schemasConfig.path("Outcome"); assertEquals("Outcome", outcome.path("id").asText()); assertEquals("string", outcome.path("type").asText()); JsonNode enumConfig = outcome.path("enum"); assertTrue(enumConfig.isArray()); assertEquals(3, enumConfig.size()); assertEquals(Outcome.WON.toString(), enumConfig.get(0).asText()); assertEquals(Outcome.LOST.toString(), enumConfig.get(1).asText()); assertEquals(Outcome.TIE.toString(), enumConfig.get(2).asText()); }
Example 3
Source File: IsJsonObject.java From java-hamcrest with Apache License 2.0 | 6 votes |
@Override protected boolean matchesNode(ObjectNode node, Description mismatchDescription) { LinkedHashMap<String, Consumer<Description>> mismatchedKeys = new LinkedHashMap<>(); for (Map.Entry<String, Matcher<? super JsonNode>> entryMatcher : entryMatchers.entrySet()) { final String key = entryMatcher.getKey(); final Matcher<? super JsonNode> valueMatcher = entryMatcher.getValue(); final JsonNode value = node.path(key); if (!valueMatcher.matches(value)) { mismatchedKeys.put(key, d -> valueMatcher.describeMismatch(value, d)); } } if (!mismatchedKeys.isEmpty()) { DescriptionUtils.describeNestedMismatches( entryMatchers.keySet(), mismatchDescription, mismatchedKeys, IsJsonObject::describeKey); return false; } return true; }
Example 4
Source File: RoutersConfig.java From onos with Apache License 2.0 | 6 votes |
@Override public boolean isValid() { for (JsonNode node : array) { ObjectNode routerNode = (ObjectNode) node; if (!hasOnlyFields(routerNode, INTERFACES, CP_CONNECT_POINT, OSPF_ENABLED, PIM_ENABLED)) { return false; } JsonNode intfNode = routerNode.path(INTERFACES); if (!intfNode.isMissingNode() && !intfNode.isArray()) { return false; } boolean valid = isConnectPoint(routerNode, CP_CONNECT_POINT, FieldPresence.MANDATORY) && isBoolean(routerNode, OSPF_ENABLED, FieldPresence.OPTIONAL) && isBoolean(routerNode, PIM_ENABLED, FieldPresence.OPTIONAL); if (!valid) { return false; } } return true; }
Example 5
Source File: Config.java From onos with Apache License 2.0 | 6 votes |
/** * Indicates whether a field in the node is present and of correct value or * not mandatory and absent. * * @param objectNode JSON object node containing field to validate * @param field name of field to validate * @param presence specified if field is optional or mandatory * @param validationFunction function which can be used to verify if the * node has the correct value * @return true if the field is as expected * @throws InvalidFieldException if the field is present but not valid */ private boolean isValid(ObjectNode objectNode, String field, FieldPresence presence, Function<JsonNode, Boolean> validationFunction) { JsonNode node = objectNode.path(field); boolean isMandatory = presence == FieldPresence.MANDATORY; if (isMandatory && node.isMissingNode()) { throw new InvalidFieldException(field, "Mandatory field not present"); } if (!isMandatory && (node.isNull() || node.isMissingNode())) { return true; } try { if (validationFunction.apply(node)) { return true; } else { throw new InvalidFieldException(field, "Validation error"); } } catch (IllegalArgumentException e) { throw new InvalidFieldException(field, e); } }
Example 6
Source File: NodeSelection.java From onos with Apache License 2.0 | 5 votes |
private Set<String> extractIds(ObjectNode payload) { ArrayNode array = (ArrayNode) payload.path(IDS); if (array == null || array.size() == 0) { return Collections.emptySet(); } Set<String> ids = new HashSet<>(); for (JsonNode node : array) { ids.add(node.asText()); } return ids; }
Example 7
Source File: JsonSettingsDao.java From arctic-sea with Apache License 2.0 | 5 votes |
@Override public void saveSettingValue(SettingValue<?> value) { writeLock().lock(); try { ObjectNode settings = getConfiguration().with(JSONSettingConstants.SETTINGS_KEY); JsonNode node = settings.path(value.getKey()); ObjectNode settingNode = (ObjectNode) Optional.ofNullable(node.isObject() ? node : null) .orElseGet(() -> settings.putObject(value.getKey())); settingNode.put(JSONSettingConstants.TYPE_KEY, value.getType().toString()); settingNode.set(JSONSettingConstants.VALUE_KEY, getSettingsEncoder().encodeValue(value)); } finally { writeLock().unlock(); } configuration().scheduleWrite(); }
Example 8
Source File: TunnelCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public DefaultTunnel decode(ObjectNode json, CodecContext context) { String tid = json.path(TUNNEL_ID).asText(); List<Integer> labels = new ArrayList<>(); if (!json.path(LABEL_PATH).isMissingNode()) { ArrayNode labelArray = (ArrayNode) json.path(LABEL_PATH); for (JsonNode o : labelArray) { labels.add(o.asInt()); } } return new DefaultTunnel(tid, labels); }
Example 9
Source File: JsonConfigWriterTest.java From endpoints-java with Apache License 2.0 | 5 votes |
@Test public void testBeanPropertyDateType() throws Exception { ObjectMapper mapper = new ObjectMapper(); ObjectNode schemasConfig = mapper.createObjectNode(); writer.addTypeToSchema(schemasConfig, TypeToken.of(Bean.class), apiConfig, null); JsonNode beanConfig = schemasConfig.path("Bean"); assertEquals("Bean", beanConfig.path("id").asText()); assertEquals("object", beanConfig.path("type").asText()); assertEquals("string", beanConfig.path("properties").path("date").path("type").asText()); assertEquals("date-time", beanConfig.path("properties").path("date").path("format").asText()); }
Example 10
Source File: DevicesWebResource.java From onos with Apache License 2.0 | 5 votes |
/** * Changes the administrative state of a port. * * @onos.rsModel PortAdministrativeState * @param id device identifier * @param portId port number * @param stream input JSON * @return 200 OK if the port state was set to the given value */ @POST @Path("{id}/portstate/{port_id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response setPortState(@PathParam("id") String id, @PathParam("port_id") String portId, InputStream stream) { try { DeviceId deviceId = deviceId(id); PortNumber portNumber = PortNumber.portNumber(portId); nullIsNotFound(get(DeviceService.class).getPort( new ConnectPoint(deviceId, portNumber)), DEVICE_NOT_FOUND); ObjectNode root = readTreeFromStream(mapper(), stream); JsonNode node = root.path(ENABLED); if (!node.isMissingNode()) { get(DeviceAdminService.class) .changePortState(deviceId, portNumber, node.asBoolean()); return Response.ok().build(); } throw new IllegalArgumentException(INVALID_JSON); } catch (IOException ioe) { throw new IllegalArgumentException(ioe); } }
Example 11
Source File: ServerDevicesDiscovery.java From onos with Apache License 2.0 | 5 votes |
/** * Parse the input JSON object, looking for CPU-related * information. Upon success, construct and return a list * of CPU devices. * * @param objNode input JSON node with CPU device information * @return list of CPU devices */ private Collection<CpuDevice> parseCpuDevices(ObjectNode objNode) { Collection<CpuDevice> cpuSet = Sets.newHashSet(); JsonNode cpuNode = objNode.path(PARAM_CPUS); // Construct CPU objects for (JsonNode cn : cpuNode) { ObjectNode cpuObjNode = (ObjectNode) cn; // All the CPU attributes int physicalCpuId = cpuObjNode.path(PARAM_CPU_ID_PHY).asInt(); int logicalCpuId = cpuObjNode.path(PARAM_CPU_ID_LOG).asInt(); int cpuSocket = cpuObjNode.path(PARAM_CPU_SOCKET).asInt(); String cpuVendorStr = get(cn, PARAM_CPU_VENDOR); long cpuFrequency = cpuObjNode.path(PARAM_CPU_FREQUENCY).asLong(); // Construct a CPU device and add it to the set cpuSet.add( DefaultCpuDevice.builder() .setCoreId(logicalCpuId, physicalCpuId) .setVendor(cpuVendorStr) .setSocket(cpuSocket) .setFrequency(cpuFrequency) .build()); } return cpuSet; }
Example 12
Source File: PortPairGroupCodec.java From onos with Apache License 2.0 | 5 votes |
@Override public PortPairGroup decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } PortPairGroup.Builder resultBuilder = new DefaultPortPairGroup.Builder(); CoreService coreService = context.getService(CoreService.class); String id = nullIsIllegal(json.get(ID), ID + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setId(PortPairGroupId.of(id)); String tenantId = nullIsIllegal(json.get(TENANT_ID), TENANT_ID + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setTenantId(TenantId.tenantId(tenantId)); String name = nullIsIllegal(json.get(NAME), NAME + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setName(name); String description = nullIsIllegal(json.get(DESCRIPTION), DESCRIPTION + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setDescription(description); List<PortPairId> list = Lists.newArrayList(); ArrayNode arrayNode = (ArrayNode) json.path(PORT_PAIRS); arrayNode.forEach(i -> list.add(PortPairId.of(i.asText()))); resultBuilder.setPortPairs(list); return resultBuilder.build(); }
Example 13
Source File: ServerDevicesDiscovery.java From onos with Apache License 2.0 | 4 votes |
/** * Parse the input JSON object, looking for CPU cache-related * information. Upon success, construct and return a CPU cache * hierarchy device. * * @param objNode input JSON node with CPU cache device information * @return a CPU cache hierarchy devices */ private CpuCacheHierarchyDevice parseCpuCacheHierarchyDevice(ObjectNode objNode) { JsonNode cacheHierarchyNode = objNode.path(PARAM_CPU_CACHE_HIERARCHY); ObjectNode cacheHierarchyObjNode = (ObjectNode) cacheHierarchyNode; if (cacheHierarchyObjNode == null) { return null; } int socketsNb = cacheHierarchyObjNode.path(PARAM_CPU_SOCKETS).asInt(); int coresNb = cacheHierarchyObjNode.path(PARAM_CPU_CORES).asInt(); int levels = cacheHierarchyObjNode.path(PARAM_CPU_CACHE_LEVELS).asInt(); JsonNode cacheNode = cacheHierarchyObjNode.path(PARAM_CPU_CACHES); DefaultCpuCacheHierarchyDevice.Builder cacheBuilder = DefaultCpuCacheHierarchyDevice.builder() .setSocketsNumber(socketsNb) .setCoresNumber(coresNb) .setLevels(levels); // Construct CPU cache objects for (JsonNode cn : cacheNode) { ObjectNode cacheObjNode = (ObjectNode) cn; // CPU cache attributes String cpuVendorStr = get(cn, PARAM_CPU_VENDOR); String levelStr = get(cn, PARAM_CPU_CACHE_LEVEL); String typeStr = get(cn, PARAM_CPU_CACHE_TYPE); String policyStr = get(cn, PARAM_CPU_CACHE_POLICY); long capacity = cacheObjNode.path(PARAM_CAPACITY).asLong(); int sets = cacheObjNode.path(PARAM_CPU_CACHE_SETS).asInt(); int ways = cacheObjNode.path(PARAM_CPU_CACHE_WAYS).asInt(); int lineLen = cacheObjNode.path(PARAM_CPU_CACHE_LINE_LEN).asInt(); boolean shared = cacheObjNode.path(PARAM_CPU_CACHE_SHARED).asInt() > 0; // Construct a basic CPU cache device and add it to the hierarchy cacheBuilder.addBasicCpuCacheDevice( DefaultBasicCpuCacheDevice.builder() .setVendor(cpuVendorStr) .setCacheId(levelStr, typeStr) .setPolicy(policyStr) .setCapacity(capacity) .setNumberOfSets(sets) .setNumberOfWays(ways) .setLineLength(lineLen) .isShared(shared) .build()); } return cacheBuilder.build(); }
Example 14
Source File: PcePathCodec.java From onos with Apache License 2.0 | 4 votes |
@Override public PcePath decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { log.error("Empty json input"); return null; } // build pce-path PcePath.Builder resultBuilder = new DefaultPcePath.Builder(); // retrieve source JsonNode jNode = json.get(SOURCE); if (jNode != null) { String src = jNode.asText(); resultBuilder.source(src); } // retrieve destination jNode = json.get(DESTINATION); if (jNode != null) { String dst = jNode.asText(); resultBuilder.destination(dst); } // retrieve lsp-type jNode = json.get(LSP_TYPE); if (jNode != null) { String lspType = jNode.asText(); //Validating LSP type int type = Integer.parseInt(lspType); if ((type < 0) || (type > 2)) { return null; } resultBuilder.lspType(lspType); } // retrieve symbolic-path-name jNode = json.get(SYMBOLIC_PATH_NAME); if (jNode != null) { String name = jNode.asText(); resultBuilder.name(name); } // retrieve constraint JsonNode constraintJNode = (JsonNode) json.path(CONSTRAINT); if ((constraintJNode != null) && (!constraintJNode.isMissingNode())) { // retrieve cost jNode = constraintJNode.get(COST); if (jNode != null) { String cost = jNode.asText(); //Validating Cost type int costType = Integer.parseInt(cost); if ((costType < 1) || (costType > 2)) { return null; } resultBuilder.costConstraint(cost); } // retrieve bandwidth jNode = constraintJNode.get(BANDWIDTH); if (jNode != null) { String bandwidth = jNode.asText(); double bw = Double.parseDouble(bandwidth); if (bw < 0) { return null; } resultBuilder.bandwidthConstraint(bandwidth); } } // Retrieve explicit path info JsonNode explicitPathInfo = json.get(EXPLICIT_PATH_INFO); if (explicitPathInfo != null) { List<ExplicitPathInfo> explicitPathInfoList = ImmutableList.copyOf(jsonNodeToExplicitPathInfo(explicitPathInfo)); if (explicitPathInfoList != null) { resultBuilder.explicitPathInfo(explicitPathInfoList); } } return resultBuilder.build(); }
Example 15
Source File: ServerDevicesDiscovery.java From onos with Apache License 2.0 | 4 votes |
/** * Parse the input JSON object, looking for NIC-related * information. Upon success, construct and return a list * of NIC devices. * * @param mapper input JSON object mapper * @param objNode input JSON node with NIC device information * @param annotations device annotations * @return list of CPU devices */ private Collection<NicDevice> parseNicDevices( ObjectMapper mapper, ObjectNode objNode, DefaultAnnotations.Builder annotations) { Collection<NicDevice> nicSet = Sets.newHashSet(); JsonNode nicNode = objNode.path(PARAM_NICS); // Construct NIC objects for (JsonNode nn : nicNode) { ObjectNode nicObjNode = (ObjectNode) nn; // All the NIC attributes String nicName = get(nn, PARAM_NAME); long nicIndex = nicObjNode.path(PARAM_ID).asLong(); long speed = nicObjNode.path(PARAM_SPEED).asLong(); String portTypeStr = get(nn, PARAM_NIC_PORT_TYPE); boolean status = nicObjNode.path(PARAM_STATUS).asInt() > 0; String hwAddr = get(nn, PARAM_NIC_HW_ADDR); JsonNode tagNode = nicObjNode.path(PARAM_NIC_RX_FILTER); if (tagNode == null) { throw new IllegalArgumentException( "The Rx filters of NIC " + nicName + " are not reported"); } // Convert the JSON list into an array of strings List<String> rxFilters = null; try { rxFilters = mapper.readValue(tagNode.traverse(), new TypeReference<ArrayList<String>>() { }); } catch (IOException ioEx) { continue; } // Store NIC name to number mapping as an annotation annotations.set(nicName, Long.toString(nicIndex)); // Construct a NIC device and add it to the set nicSet.add( DefaultNicDevice.builder() .setName(nicName) .setPortNumber(nicIndex) .setPortNumber(nicIndex) .setPortType(portTypeStr) .setSpeed(speed) .setStatus(status) .setMacAddress(hwAddr) .setRxFilters(rxFilters) .build()); } return nicSet; }
Example 16
Source File: ServerDevicesDiscovery.java From onos with Apache License 2.0 | 4 votes |
/** * Parse the input JSON object, looking for memory-related * information. Upon success, construct and return a memory * hierarchy device. * * @param objNode input JSON node with memory device information * @return a memory hierarchy device */ private MemoryHierarchyDevice parseMemoryHierarchyDevice(ObjectNode objNode) { JsonNode memHierarchyNode = objNode.path(PARAM_MEMORY_HIERARCHY); ObjectNode memoryHierarchyObjNode = (ObjectNode) memHierarchyNode; if (memoryHierarchyObjNode == null) { return null; } JsonNode memoryNode = memoryHierarchyObjNode.path(PARAM_MEMORY_MODULES); DefaultMemoryHierarchyDevice.Builder memoryBuilder = DefaultMemoryHierarchyDevice.builder(); // Construct memory modules for (JsonNode mn : memoryNode) { ObjectNode memoryObjNode = (ObjectNode) mn; String typeStr = get(mn, PARAM_TYPE); String manufacturerStr = get(mn, PARAM_MANUFACTURER); String serialStr = get(mn, PARAM_SERIAL); int dataWidth = memoryObjNode.path(PARAM_MEMORY_WIDTH_DATA).asInt(); int totalWidth = memoryObjNode.path(PARAM_MEMORY_WIDTH_TOTAL).asInt(); long capacity = memoryObjNode.path(PARAM_CAPACITY).asLong(); long speed = memoryObjNode.path(PARAM_SPEED).asLong(); long configuredSpeed = memoryObjNode.path(PARAM_SPEED_CONF).asLong(); // Construct a memory module and add it to the hierarchy memoryBuilder.addMemoryModule( DefaultMemoryModuleDevice.builder() .setType(typeStr) .setManufacturer(manufacturerStr) .setSerialNumber(serialStr) .setDataWidth(dataWidth) .setTotalWidth(totalWidth) .setCapacity(capacity) .setSpeed(speed) .setConfiguredSpeed(configuredSpeed) .build()); } return memoryBuilder.build(); }
Example 17
Source File: JsonMetadataExporter.java From jasperreports with GNU Lesser General Public License v3.0 | 4 votes |
private boolean isValid(ObjectNode objectNode, String objectName, String currentPath, SchemaNode parent) { String nodeTypeValue = null; JsonNode typeNode = objectNode.path("_type"); if (typeNode.isMissingNode()) { nodeTypeValue = "object"; } else if (!typeNode.isTextual()) { return false; } if (nodeTypeValue == null) { nodeTypeValue = typeNode.asText(); } NodeTypeEnum nodeType = NodeTypeEnum.getByName(nodeTypeValue); // enforce type "object" or "array" with "_children" if (!(NodeTypeEnum.OBJECT.equals(nodeType) || (NodeTypeEnum.ARRAY.equals(nodeType) && objectNode.has("_children")))) { return false; } // enforce "_children" of type Object when typeNode is "array" if (NodeTypeEnum.ARRAY.equals(nodeType) && !objectNode.path("_children").isObject()) { return false; } boolean result = true; String availablePath = currentPath; SchemaNode schemaNode; availablePath = availablePath.length() > 0 ? (availablePath.endsWith(".") ? availablePath : availablePath + ".") + objectName : objectName; // _children properties are passed to the parent array if (parent != null) { schemaNode = parent; } else { int level; if (JSON_SCHEMA_ROOT_NAME.equals(objectName)) { level = 0; } else if (availablePath.length() > 0 && availablePath.indexOf(".") > 0) { level = availablePath.split("\\.").length - 1; } else { level = 1; } schemaNode = new SchemaNode(level, objectName, nodeType, currentPath.endsWith(".") ? currentPath.substring(0, currentPath.length() - 2) : currentPath); pathToObjectNode.put(availablePath, schemaNode); } Iterator<String> it = objectNode.fieldNames(); while (it.hasNext()) { String field = it.next(); JsonNode node = objectNode.path(field); String localPath = availablePath; if (!field.startsWith("_")) { schemaNode.addMember(field); if (node.isTextual() && node.asText().equals("value")) { localPath = localPath.length() > 0 ? (localPath.endsWith(".") ? localPath : localPath + ".") + field : field; pathToValueNode.put(localPath, schemaNode); } else if ((node.isObject() && !isValid((ObjectNode) node, field, availablePath, null)) || !node.isObject()) { result = false; break; } } else if (field.equals("_children") && !isValid((ObjectNode) node, "", availablePath, schemaNode)) { result = false; break; } } if (log.isDebugEnabled()) { log.debug("object is valid: " + objectNode); log.debug("objectName: " + objectName); log.debug("currentPath: " + currentPath); } return result; }
Example 18
Source File: ParsePayload.java From gcp-ingestion with Mozilla Public License 2.0 | 4 votes |
/** Tries to extract glean-style client_info object from payload. */ private static JsonNode getGleanClientInfo(ObjectNode json) { return json.path("client_info"); }
Example 19
Source File: JsonCodec.java From onos with Apache License 2.0 | 2 votes |
/** * Gets a child Object Node from a parent by name. If the child is not found * or does nor represent an object, null is returned. * * @param parent parent object * @param childName name of child to query * @return child object if found, null if not found or if not an object */ protected static ObjectNode get(ObjectNode parent, String childName) { JsonNode node = parent.path(childName); return node.isObject() && !node.isNull() ? (ObjectNode) node : null; }
Example 20
Source File: JsonUtils.java From onos with Apache License 2.0 | 2 votes |
/** * Returns the payload from the specified event. * * @param event message event * @return extracted payload object */ public static ObjectNode payload(ObjectNode event) { return (ObjectNode) event.path("payload"); }