Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#get()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#get() . 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: ModelsResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
    JsonNode childShapesNode = editorJsonNode.get("childShapes");
    if (childShapesNode != null && childShapesNode.isArray()) {
        ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
        for (JsonNode childShapeNode : childShapesArrayNode) {
            // Properties
            ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
            if (properties != null && properties.has(propertyName)) {
                JsonNode propertyNode = properties.get(propertyName);
                if (propertyNode != null) {
                    properties.remove(propertyName);
                }
            }

            // Potential nested child shapes
            if (childShapeNode.has("childShapes")) {
                internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
            }

        }
    }
}
 
Example 2
Source File: NavigateResponseConverterTest.java    From graphhopper-navigation with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void alternativeRoutesTest() {

    GHResponse rsp = hopper.route(new GHRequest(42.554851, 1.536198, 42.510071, 1.548128).
            setProfile(profile).setAlgorithm(Parameters.Algorithms.ALT_ROUTE));

    assertEquals(2, rsp.getAll().size());

    ObjectNode json = NavigateResponseConverter.convertFromGHResponse(rsp, trMap, mtrMap, Locale.ENGLISH, distanceConfig);

    JsonNode routes = json.get("routes");
    assertEquals(2, routes.size());

    assertEquals("GraphHopper Route 0", routes.get(0).get("legs").get(0).get("summary").asText());
    assertEquals("Avinguda Sant Antoni, CG-3", routes.get(1).get("legs").get(0).get("summary").asText());
}
 
Example 3
Source File: GDKSession.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public Map<String, Bitmap> getAssetsIcons(final boolean refresh) throws Exception {
    final ObjectNode details = mObjectMapper.createObjectNode();
    details.put("icons", true);
    details.put("assets", false);
    details.put("refresh", refresh);
    final ObjectNode data = (ObjectNode) GDK.refresh_assets(mNativeSession, details);
    final ObjectNode iconsData = (ObjectNode) data.get("icons");
    if (iconsData.has("last_modified"))
        iconsData.remove("last_modified");
    final Map<String, Bitmap> icons = new HashMap<>();
    final Iterator<String> iterator = iconsData.fieldNames();
    while (iterator.hasNext()) {
        final String key = iterator.next();
        final byte[] decodedString = Base64.decode(iconsData.get(key).asText(), Base64.DEFAULT);
        final Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        icons.put(key, decodedByte);
    }
    return icons;
}
 
Example 4
Source File: ConfigFile.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void upgradePluginPropertiesIfNeeded(ObjectNode rootObjectNode) {
    JsonNode pluginsNode = rootObjectNode.get("plugins");
    if (pluginsNode == null || !pluginsNode.isArray()) {
        return;
    }
    for (JsonNode pluginNode : pluginsNode) {
        if (!(pluginNode instanceof ObjectNode)) {
            continue;
        }
        ObjectNode pluginObjectNode = (ObjectNode) pluginNode;
        if (pluginObjectNode.path("id").asText().equals("jdbc")) {
            JsonNode propertiesNode = pluginObjectNode.get("properties");
            if (propertiesNode != null && propertiesNode.isObject()) {
                upgradeJdbcPluginPropertiesIfNeeded((ObjectNode) propertiesNode);
            }
            // since no other plugin property upgrades at this point, can return now
            return;
        }
    }
}
 
Example 5
Source File: UserResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * PUT  /rest/users/:login/change_password -> changes the user's password
 */
@RequestMapping(value = "/rest/users/{login}/change-password", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)
public void changePassword(@PathVariable String login, @RequestBody ObjectNode actionBody) {
    if (actionBody.get("oldPassword") == null || actionBody.get("oldPassword").isNull()) {
        throw new BadRequestException("oldPassword should not be empty");

    } else if (actionBody.get("newPassword") == null || actionBody.get("newPassword").isNull()) {
        throw new BadRequestException("newPassword should not be empty");

    } else {
    	try {
    		userService.changePassword(login, actionBody.get("oldPassword").asText(), actionBody.get("newPassword").asText());
    	} catch(ActivitiServiceException ase) {
    		throw new BadRequestException(ase.getMessage());
    	}
    }
}
 
Example 6
Source File: JsonUtils.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> parserMap(ObjectNode node) {
    Map<String, Object> map = new HashMap<String, Object>();
    Iterator<String> iterable = node.fieldNames();
    while (iterable.hasNext()) {
        String key = iterable.next();
        JsonNode jsonNode = node.get(key);
        if (jsonNode.isValueNode()) {
            map.put(key, parserValue(jsonNode));
        } else if (jsonNode.isArray()) {
            map.put(key, parserArrayNode((ArrayNode) jsonNode));
        } else if (jsonNode.isObject()) {
            map.put(key, parserMap((ObjectNode) jsonNode));
        }
    }
    return map;
}
 
Example 7
Source File: VirtualNetworkWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a virtual device from the JSON input stream.
 *
 * @param networkId network identifier
 * @param stream    virtual device JSON stream
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel VirtualDevice
 */
@POST
@Path("{networkId}/devices")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualDevice(@PathParam("networkId") long networkId,
                                    InputStream stream) {
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        final VirtualDevice vdevReq = codec(VirtualDevice.class).decode(jsonTree, this);
        JsonNode specifiedNetworkId = jsonTree.get("networkId");
        if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) {
            throw new IllegalArgumentException(INVALID_FIELD + "networkId");
        }
        final VirtualDevice vdevRes = vnetAdminService.createVirtualDevice(vdevReq.networkId(),
                                                                           vdevReq.id());
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("vnets").path(specifiedNetworkId.asText())
                .path("devices").path(vdevRes.id().toString());
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 8
Source File: VirtualNetworkWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the virtual network link from the JSON input stream.
 *
 * @param networkId network identifier
 * @param stream    virtual link JSON stream
 * @return 204 NO CONTENT
 * @onos.rsModel VirtualLink
 */
@DELETE
@Path("{networkId}/links")
@Consumes(MediaType.APPLICATION_JSON)
public Response removeVirtualLink(@PathParam("networkId") long networkId,
                                  InputStream stream) {
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode specifiedNetworkId = jsonTree.get("networkId");
        if (specifiedNetworkId != null &&
                specifiedNetworkId.asLong() != (networkId)) {
            throw new IllegalArgumentException(INVALID_FIELD + "networkId");
        }
        final VirtualLink vlinkReq = codec(VirtualLink.class).decode(jsonTree, this);
        vnetAdminService.removeVirtualLink(vlinkReq.networkId(),
                                           vlinkReq.src(), vlinkReq.dst());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    return Response.noContent().build();
}
 
Example 9
Source File: CWLOutputJsonParser.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
private static JsonNode mapDockerFilePath(CWLInstance instance, JsonNode jsonNode) {
    if (jsonNode == null || !(jsonNode instanceof ObjectNode)) {
        return jsonNode;
    }
    ObjectNode objectNode = (ObjectNode) jsonNode;
    String tmpDir = instance.getRuntime().get(CommonUtil.RUNTIME_TMP_DIR);
    JsonNode pathNode = objectNode.get("path");
    if (pathNode != null && pathNode.isTextual() && pathNode.asText() != null
            && pathNode.asText().indexOf(VAR_SPOOL_CWL) != -1) {
        objectNode.put("path", pathNode.asText().replace(VAR_SPOOL_CWL, tmpDir));
    }
    JsonNode locationNode = objectNode.get("location");
    if (locationNode != null && locationNode.isTextual() && locationNode.asText() != null
            && locationNode.asText().indexOf(VAR_SPOOL_CWL) != -1) {
        objectNode.put("location", locationNode.asText().replace(VAR_SPOOL_CWL, tmpDir));
    }
    return jsonNode;
}
 
Example 10
Source File: FlowEntryCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public FlowEntry decode(ObjectNode json, CodecContext context) {
    checkNotNull(json, "JSON object cannot be null");

    // decode FlowRule-specific fields using the FlowRule codec
    FlowRule flowRule = context.codec(FlowRule.class).decode(json, context);

    JsonNode stateNode = json.get(STATE);
    FlowEntry.FlowEntryState state = (null == stateNode) ?
            FlowEntry.FlowEntryState.ADDED : FlowEntry.FlowEntryState.valueOf(stateNode.asText());

    JsonNode lifeNode = json.get(LIFE);
    long life = (null == lifeNode) ? 0 : lifeNode.asLong();

    JsonNode liveTypeNode = json.get(LIVE_TYPE);
    FlowEntry.FlowLiveType liveType = (null == liveTypeNode) ?
            FlowEntry.FlowLiveType.UNKNOWN : FlowEntry.FlowLiveType.valueOf(liveTypeNode.asText());

    JsonNode packetsNode = json.get(PACKETS);
    long packets = (null == packetsNode) ? 0 : packetsNode.asLong();

    JsonNode bytesNode = json.get(BYTES);
    long bytes = (null == bytesNode) ? 0 : bytesNode.asLong();

    return new DefaultFlowEntry(flowRule, state, life,
                                liveType, packets, bytes);
}
 
Example 11
Source File: JsonToEntityMapper.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public UpdateEntity newUpdateEntity(Collection collection, UUID id, ObjectNode data)
  throws IOException {
  if (data.get("^rev") == null) {
    throw new IOException("data object should have a ^rev property indicating the revision this update was based on");
  }
  int rev = data.get("^rev").asInt();

  List<TimProperty<?>> properties = getDataProperties(collection, data);

  return new UpdateEntity(id, properties, rev);
}
 
Example 12
Source File: MappingTest4.java    From jolt with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates how to do recursive polymorphic JSON deserialization in Jackson 2.2.
 *
 * Aka specify a Deserializer and "catch" some input, determine what type of Class it
 *  should be parsed too, and then reuse the Jackson infrastructure to recursively do so.
 */
@Override
public QueryFilter4 deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {

    ObjectNode root = jp.readValueAsTree();

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = root.traverse( jp.getCodec() );

    // Check if it is a "RealFilter"
    JsonNode valueParam = root.get("value");

    if ( valueParam == null ) {
         return subJsonParser.readValueAs( LogicalFilter4.class );
    }
    if ( valueParam.isBoolean() ) {
        return subJsonParser.readValueAs( BooleanRealFilter4.class );
    }
    else if ( valueParam.isTextual() ) {
        return subJsonParser.readValueAs( StringRealFilter4.class );
    }
    else if ( valueParam.isIntegralNumber() ) {
        return subJsonParser.readValueAs( IntegerRealFilter4.class );
    }
    else {
        throw new RuntimeException("Unknown type");
    }
}
 
Example 13
Source File: CmmnJsonConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void filterAllEdges(JsonNode objectNode, Map<String, JsonNode> edgeMap, Map<String, List<JsonNode>> sourceAndTargetMap, Map<String, JsonNode> shapeMap, Map<String, JsonNode> sourceRefMap) {

        if (objectNode.get(EDITOR_CHILD_SHAPES) != null) {
            for (JsonNode jsonChildNode : objectNode.get(EDITOR_CHILD_SHAPES)) {

                ObjectNode childNode = (ObjectNode) jsonChildNode;
                String stencilId = CmmnJsonConverterUtil.getStencilId(childNode);
                if (STENCIL_PLANMODEL.equals(stencilId) || STENCIL_STAGE.equals(stencilId)) {

                    filterAllEdges(childNode, edgeMap, sourceAndTargetMap, shapeMap, sourceRefMap);

                } else if (STENCIL_ASSOCIATION.equals(stencilId)) {

                    String childEdgeId = CmmnJsonConverterUtil.getElementId(childNode);
                    JsonNode targetNode = childNode.get("target");
                    if (targetNode != null && !targetNode.isNull()) {
                        String targetRefId = targetNode.get(EDITOR_SHAPE_ID).asText();
                        List<JsonNode> sourceAndTargetList = new ArrayList<>();
                        sourceAndTargetList.add(sourceRefMap.get(childNode.get(EDITOR_SHAPE_ID).asText()));
                        sourceAndTargetList.add(shapeMap.get(targetRefId));
                        sourceAndTargetMap.put(childEdgeId, sourceAndTargetList);
                    }
                    edgeMap.put(childEdgeId, childNode);
                }
            }
        }
    }
 
Example 14
Source File: ApiException.java    From Kore with Apache License 2.0 5 votes vote down vote up
/**
 * Construct exception from JSON response
 * @param code Exception code
 * @param jsonResponse Json response, with an Error node
 */
public ApiException(int code, ObjectNode jsonResponse) {
       super((jsonResponse.get(ApiMethod.ERROR_NODE) != null) ?
               JsonUtils.stringFromJsonNode(jsonResponse.get(ApiMethod.ERROR_NODE), "message") :
               "No message returned");
	this.code = code;
}
 
Example 15
Source File: JsonEventConventions.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public void setInstanceId(ObjectNode event, Id id, String className) {
    JsonNode got = event.get(className);
    if (got == null || got.isNull() || !got.isObject()) {
        throw new IllegalArgumentException("Supplied event node has no instance node corresponding to " + className);
    }

    ObjectNode instanceNode = (ObjectNode) got;
    instanceNode.put(ReservedFields.INSTANCE_ID, id.toStringForm());
}
 
Example 16
Source File: JsonQueryObjectModelConverter.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
private double checkFloat(ObjectNode node, String key) throws QueryException {
	if (!node.has(key)) {
		throw new QueryException("\"" + key + "\" not found on \"inBoundingBox\"");
	}
	JsonNode jsonNode = node.get(key);
	if (jsonNode.isNumber()) {
		return jsonNode.asDouble();
	} else {
		throw new QueryException("\"" + key + "\" should be of type number");
	}
}
 
Example 17
Source File: StreamsCassandraResourceGenerator.java    From streams with Apache License 2.0 4 votes vote down vote up
private StringBuilder appendPropertiesNode(StringBuilder builder, Schema schema, ObjectNode propertiesNode, Character seperator) {
  Objects.requireNonNull(builder);
  Objects.requireNonNull(propertiesNode);
  Iterator<Map.Entry<String, JsonNode>> fields = propertiesNode.fields();
  List<String> fieldStrings = new ArrayList<>();
  for ( ; fields.hasNext(); ) {
    Map.Entry<String, JsonNode> field = fields.next();
    String fieldId = field.getKey();
    if ( !config.getExclusions().contains(fieldId) && field.getValue().isObject()) {
      ObjectNode fieldNode = (ObjectNode) field.getValue();
      FieldType fieldType = FieldUtil.determineFieldType(fieldNode);
      if (fieldType != null ) {
        switch (fieldType) {
          case ARRAY:
            ObjectNode itemsNode = (ObjectNode) fieldNode.get("items");
            if ( currentDepth <= config.getMaxDepth()) {
              StringBuilder arrayItemsBuilder = appendArrayItems(new StringBuilder(), schema, fieldId, itemsNode, seperator);
              if (StringUtils.isNotBlank(arrayItemsBuilder.toString())) {
                fieldStrings.add(arrayItemsBuilder.toString());
              }
            }
            break;
          case OBJECT:
            Schema objectSchema = null;
            URI parentUri = null;
            if ( fieldNode.has("$ref") || fieldNode.has("extends") ) {
              JsonNode refNode = fieldNode.get("$ref");
              JsonNode extendsNode = fieldNode.get("extends");
              if (refNode != null && refNode.isValueNode()) {
                parentUri = URI.create(refNode.asText());
              } else if (extendsNode != null && extendsNode.isObject()) {
                parentUri = URI.create(extendsNode.get("$ref").asText());
              }
              URI absoluteUri;
              if (parentUri.isAbsolute()) {
                absoluteUri = parentUri;
              } else {
                absoluteUri = schema.getUri().resolve(parentUri);
                if (!absoluteUri.isAbsolute() || (absoluteUri.isAbsolute() && !schemaStore.getByUri(absoluteUri).isPresent() )) {
                  absoluteUri = schema.getParentUri().resolve(parentUri);
                }
              }
              if (absoluteUri != null && absoluteUri.isAbsolute()) {
                Optional<Schema> schemaLookup = schemaStore.getByUri(absoluteUri);
                if (schemaLookup.isPresent()) {
                  objectSchema = schemaLookup.get();
                }
              }
            }
            //ObjectNode childProperties = schemaStore.resolveProperties(schema, fieldNode, fieldId);
            if ( currentDepth < config.getMaxDepth()) {
              StringBuilder structFieldBuilder = appendSchemaField(new StringBuilder(), objectSchema, fieldId, seperator);
              if (StringUtils.isNotBlank(structFieldBuilder.toString())) {
                fieldStrings.add(structFieldBuilder.toString());
              }
            }
            break;
          default:
            StringBuilder valueFieldBuilder = appendValueField(new StringBuilder(), schema, fieldId, fieldType, seperator);
            if (StringUtils.isNotBlank(valueFieldBuilder.toString())) {
              fieldStrings.add(valueFieldBuilder.toString());
            }
        }
      }
    }
  }
  builder.append(String.join("," + LS, fieldStrings)).append(LS);
  Objects.requireNonNull(builder);
  return builder;
}
 
Example 18
Source File: DynamicBpmnServiceImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) {
    if (!infoNode.has(BPMN_NODE)) {
        infoNode.putObject(BPMN_NODE);
    }
    return (ObjectNode) infoNode.get(BPMN_NODE);
}
 
Example 19
Source File: JsonRpcClient.java    From jsonrpc4j with MIT License 4 votes vote down vote up
private boolean isIdValueNotCorrect(String id, ObjectNode jsonObject) {
	return !jsonObject.has(ID) || jsonObject.get(ID) == null || !jsonObject.get(ID).asText().equals(id);
}
 
Example 20
Source File: Player.java    From Kore with Apache License 2.0 4 votes vote down vote up
@Override
public PlayerType.SeekReturnType resultFromJson(ObjectNode jsonObject) throws ApiException {
    return new PlayerType.SeekReturnType(jsonObject.get(RESULT_NODE));
}