Java Code Examples for com.fasterxml.jackson.databind.JsonNode#isArray()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isArray() . 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: BaseTypeFactory.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Get StringBaseType by the type value of JsonNode which contains the
 * constraints.
 * @param type the type value of JsonNode
 * @return StringBaseType
 */
private static StringBaseType getStringBaseType(JsonNode type) {
    int minLength = Integer.MIN_VALUE;
    int maxLength = Integer.MAX_VALUE;
    Set<String> enums = Sets.newHashSet();
    JsonNode node = type.get("minLength");
    if (node != null) {
        minLength = node.asInt();
    }
    node = type.get("maxLength");
    if (node != null) {
        maxLength = node.asInt();
    }
    if (type.has("enum")) {
        JsonNode enumVal = type.get("enum");
        if (enumVal.isArray()) {
            JsonNode anEnum = enumVal.get(1);
            for (JsonNode n : anEnum) {
                enums.add(n.asText());
            }
        } else if (enumVal.isTextual()) {
            enums.add(enumVal.asText());
        }
    }
    return new StringBaseType(minLength, maxLength, enums);
}
 
Example 2
Source File: SimpleHttpClient.java    From sample-apps with Apache License 2.0 6 votes vote down vote up
public static Optional<JsonNode> getNode(JsonNode node, String... path) {
    if (node == null) {
        return Optional.empty();
    }
    if (path.length == 0) {
        return Optional.of(node);
    }
    for (String p : path) {
        node = node.get(p);
        if (node == null) {
            return Optional.empty();
        }
        if (node.isArray()) {
            node = node.get(0);  // use first element if an array
        }
    }
    return Optional.of(node);
}
 
Example 3
Source File: JsonFileIndexer.java    From samantha with MIT License 6 votes vote down vote up
public void index(JsonNode documents, RequestContext requestContext) {
    JsonNode reqBody = requestContext.getRequestBody();
    String operation = JsonHelpers.getOptionalString(reqBody, ConfigKey.DATA_OPERATION.get(),
            DataOperation.INSERT.get());
    if (operation.equals(DataOperation.INSERT.get()) || operation.equals(DataOperation.UPSERT.get())) {
        JsonNode arr;
        if (!documents.isArray()) {
            ArrayNode tmp = Json.newArray();
            tmp.add(documents);
            arr = tmp;
        } else {
            arr = documents;
        }
        int timestamp = (int) (System.currentTimeMillis() / 1000);
        for (JsonNode document : arr) {
            if (document.has(timestampField)) {
                timestamp = document.get(timestampField).asInt();
            } else {
                logger.warn("Time field {} is not present in the entity to be indexed.", timestampField);
            }
            dataService.writeJson(indexType, document, timestamp);
        }
    } else {
        throw new BadRequestException("Data operation " + operation + " is not supported");
    }
}
 
Example 4
Source File: UserConfigUtils.java    From burp-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Given a userconfig, copy it in a new temporary file and injects all the registered extensions
 * @param path a userconfig path to be injected
 * @return a new userconfig path
 * @throws IOException when one of the two userconfig is not accessible/writable/creatable
 */
public String injectExtensions(String path) throws IOException {
    Path userOptionsTempFile = Files.createTempFile("user-options_", ".json");
    FileCopyUtils.copy(new File(path), userOptionsTempFile.toFile());

    //addBurpExtensions here to the temporary file and return the handle to the new temporary file
    //- read all file in in jackson object
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    JsonNode tree = objectMapper.readTree(userOptionsTempFile.toFile());
    //- inject the burp extensions here inside the user configuration
    JsonNode user_options = safeGet(objectMapper, tree, "user_options");
    JsonNode extender = safeGet(objectMapper, user_options, "extender");
    JsonNode extension = extender.get("extensions");
    if (!extension.isArray()) {
        ArrayNode array = objectMapper.createArrayNode();
        ((ObjectNode)extender).replace("extensions", array);
        extension = array;
    }
    for (Extension e : extensions) {
        ((ArrayNode) extension).addPOJO(e);
    }
    //- write the jackson configuration inside the temporary user configuration
    objectMapper.writer(new DefaultPrettyPrinter()).writeValue(userOptionsTempFile.toFile(), tree);

    userOptionsTempFile.toFile().deleteOnExit();
    return userOptionsTempFile.toAbsolutePath().toString();
}
 
Example 5
Source File: JsonUtils.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Converts array JSON node to a list of JSON object strings. Used when splitting a
 * JSON array with split EIP.
 * @param json a JSON node that {@link JsonNode#isArray() is an array}
 * @return each element of the given JSON array serialized as a String
 * @throws JsonProcessingException when serialization fails
 */
public static List<String> arrayToJsonBeans(JsonNode json) throws JsonProcessingException {
    List<String> jsonBeans = new ArrayList<>();

    if (json.isArray()) {
        Iterator<JsonNode> it = json.elements();
        while (it.hasNext()) {
            jsonBeans.add(writer().writeValueAsString(it.next()));
        }

        return jsonBeans;
    }

    return jsonBeans;
}
 
Example 6
Source File: EntityUpdateJsonTraverser.java    From agrest with Apache License 2.0 5 votes vote down vote up
public void traverse(AgEntity<?> entity, JsonNode json, EntityUpdateJsonVisitor visitor) {
    if (json != null) { // empty requests are fine. we just do nothing...
        if (json.isArray()) {
            processArray(entity, json, visitor);
        } else if (json.isObject()) {
            processObject(entity, json, visitor);
        } else {
            throw new AgException(Response.Status.BAD_REQUEST, "Expected Object or Array. Got: " + json.asText());
        }
    }
}
 
Example 7
Source File: TopicsDeserializer.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public List<List<LogTopic>> deserialize(
    final JsonParser jsonparser, final DeserializationContext context) throws IOException {
  final JsonNode topicsNode = jsonparser.getCodec().readTree(jsonparser);
  final List<List<LogTopic>> topics = Lists.newArrayList();

  if (!topicsNode.isArray()) {
    topics.add(singletonList(LogTopic.fromHexString(topicsNode.textValue())));
  } else {
    for (JsonNode child : topicsNode) {
      if (child.isArray()) {
        final List<LogTopic> childItems = Lists.newArrayList();
        for (JsonNode subChild : child) {
          if (subChild.isNull()) {
            childItems.add(null);
          } else {
            childItems.add(LogTopic.fromHexString(subChild.textValue()));
          }
        }
        topics.add(childItems);
      } else {
        if (child.isNull()) {
          topics.add(singletonList(null));
        } else {
          topics.add(singletonList(LogTopic.fromHexString(child.textValue())));
        }
      }
    }
  }

  return topics;
}
 
Example 8
Source File: JsonConfigConverter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static ModelNode theme(JsonNode root, PathAddress addr) {
    JsonNode themeNode = getNode(root, "theme");
    ModelNode op = Util.createAddOperation(addr);
    
    JsonNode targetNode = getNode(themeNode, "staticMaxAge");
    Long lValue = STATIC_MAX_AGE.getDefaultValue().asLong();
    if (targetNode != null) lValue = targetNode.asLong(lValue);
    op.get(STATIC_MAX_AGE.getName()).set(lValue);

    targetNode = getNode(themeNode, "cacheTemplates");
    Boolean bValue = CACHE_TEMPLATES.getDefaultValue().asBoolean();
    if (targetNode != null) bValue = targetNode.asBoolean(bValue);
    op.get(CACHE_TEMPLATES.getName()).set(bValue);
    
    targetNode = getNode(themeNode, "cacheThemes");
    bValue = CACHE_THEMES.getDefaultValue().asBoolean();
    if (targetNode != null) bValue = targetNode.asBoolean(bValue);
    op.get(CACHE_THEMES.getName()).set(bValue);
    
    targetNode = getNode(themeNode, "folder", "dir");
    String sValue = DIR.getDefaultValue().asString();
    if (targetNode != null) sValue = targetNode.asText(sValue);
    op.get(DIR.getName()).set(sValue);
    
    targetNode = getNode(themeNode, "welcomeTheme");
    if (targetNode != null) op.get(WELCOME_THEME.getName()).set(targetNode.asText());
    
    targetNode = getNode(themeNode, "default");
    if (targetNode != null) op.get(DEFAULT.getName()).set(targetNode.asText());
    
    targetNode = getNode(themeNode, "module", "modules");
    if (targetNode != null && targetNode.isArray()) {
        op.get(MODULES.getName()).set(themeModules(targetNode));
    }
    
    return op;
}
 
Example 9
Source File: Service.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
protected Map<String, Set<String>> getResultset(Model model, JsonNode query, Set<String> input, Set<String> markers , HGQLSchema schema) {

        Map<String, Set<String>> resultset = new HashMap<>();
        JsonNode node;

        if (!query.isArray()) {
            node = query.get("fields");
            if (markers.contains(query.get("nodeId").asText())){
                resultset.put(query.get("nodeId").asText(),findRootIdentifiers(model,schema.getTypes().get(query.get("targetName").asText())));
            }
        } else {
            node = query;
        }
        Set<LinkedList<QueryNode>> paths = new HashSet<>();
        if (node != null && !node.isNull()) {
            paths = getQueryPaths(node, schema);
        }

        for (LinkedList<QueryNode> path : paths) {
            if (hasMarkerLeaf(path, markers)) {
                Set<String> identifiers = findIdentifiers(model, input, path);
                String marker = getLeafMarker(path);
                resultset.put(marker, identifiers);
            }
        }

        //todo query happens to be an array sometimes - then the following line fails.

        return resultset;
    }
 
Example 10
Source File: PanResult.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Object是集合转化
 * 
 * @param jsonData json数据
 * @param clazz 集合中的类型
 * @return
 */
public static PanResult formatToList(String jsonData, Class<?> clazz) {
    try {
        JsonNode jsonNode = MAPPER.readTree(jsonData);
        JsonNode data = jsonNode.get("data");
        Object obj = null;
        if (data.isArray() && data.size() > 0) {
            obj = MAPPER.readValue(data.traverse(),
                    MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        }
        return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
    } catch (Exception e) {
        return null;
    }
}
 
Example 11
Source File: JsonPolicyReader.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a list of actions from the Action Json Node.
 *
 * @param actionNodes
 *            the action Json node to be parsed.
 * @return the list of actions.
 */
private List<Action> actionsOf(JsonNode actionNodes) {
    List<Action> actions = new LinkedList<>();

    if (actionNodes.isArray()) {
        for (JsonNode action : actionNodes) {
            actions.add(new Action(action.asText()));
        }
    } else {
        actions.add(new Action(actionNodes.asText()));
    }
    return actions;
}
 
Example 12
Source File: ConfigEvalEngine.java    From digdag with Apache License 2.0 5 votes vote down vote up
private ObjectNode evalObjectRecursive(ObjectNode local)
    throws TemplateException
{
    ObjectNode built = local.objectNode();
    for (Map.Entry<String, JsonNode> pair : ImmutableList.copyOf(local.fields())) {
        JsonNode value = pair.getValue();
        JsonNode evaluated;
        if (noEvaluatedKeys.contains(pair.getKey())) {
            // don't evaluate _do parameters
            evaluated = value;
        }
        else if (value.isObject()) {
            evaluated = evalObjectRecursive((ObjectNode) value);
        }
        else if (value.isArray()) {
            evaluated = evalArrayRecursive(built, (ArrayNode) value);
        }
        else if (value.isTextual()) {
            // eval using template engine
            String code = value.textValue();
            evaluated = evalValue(built, code);
        }
        else {
            evaluated = value;
        }
        built.set(pair.getKey(), evaluated);
    }
    return built;
}
 
Example 13
Source File: OperationFactory.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
public static BaseOperation operation(JsonNode message) {
    String type = null;
    if (message.has("type")) {
        type = message.get("type").asText();
    }
    if (type == null) {
        throw new IllegalArgumentException("Couldn't create Operation, missing 'type' property: " + JsonUtil.toJson(message));
    }
    Class<? extends BaseOperation> unmarshallClass = OP_CLASSES.get(type);
    if (unmarshallClass == null) {
        throw new IllegalArgumentException("Couldn't create Operation, unknown type: " + type);
    }
    
    // Handle batch a bit differently.
    if ("batch".equals(type)) {
        final BatchOperation batchOp = batch();
        if (message.has("operations")) {
            JsonNode operationsNode = message.get("operations");
            if (operationsNode.isArray()) {
                ArrayNode array = (ArrayNode) operationsNode;
                array.forEach(subop -> {
                    batchOp.getOperations().add(operation(subop));
                });
            }
        }
        return batchOp;
    } else {
        return JsonUtil.fromJsonToOperation(message, unmarshallClass);
    }
}
 
Example 14
Source File: RouterConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of interfaces enabled on this router.
 *
 * @return list of interface names that are enabled, or an empty list if
 * all available interfaces should be used
 */
public List<String> getInterfaces() {
    JsonNode intfNode = object.path(INTERFACES);
    if (intfNode.isMissingNode() || !intfNode.isArray()) {
        return Collections.emptyList();
    }
    ArrayNode array = (ArrayNode) intfNode;
    List<String> interfaces = new ArrayList<>(array.size());
    for (JsonNode intf : array) {
        interfaces.add(intf.asText());
    }
    return interfaces;
}
 
Example 15
Source File: JacksonRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<JsonNode> toList(JsonNode value) {
  if (value.isArray()) {
    return new ArrayNodeListWrapper((ArrayNode) value);
  } else if (value.isObject()) {
    List<JsonNode> elements = new ArrayList<>(value.size());
    for (JsonNode element : value) {
      elements.add(element);
    }
    return elements;
  } else {
    return Collections.emptyList();
  }
}
 
Example 16
Source File: DataDragon.java    From orianna with MIT License 5 votes vote down vote up
@Override
public JsonNode apply(final JsonNode spellTree) {
    if(spellTree == null) {
        return spellTree;
    }

    // Swap key and id. They're reversed between ddragon and the API.
    if(spellTree.has("key") && spellTree.has("id")) {
        final ObjectNode spell = (ObjectNode)spellTree;
        final String id = spell.get("key").asText();
        spell.set("key", spell.get("id"));
        spell.set("id", new IntNode(Integer.parseInt(id)));
    }

    final JsonNode temp = spellTree.get("vars");
    if(temp == null) {
        return spellTree;
    }

    for(final JsonNode vars : temp) {
        if(vars == null) {
            continue;
        }

        final JsonNode coeff = vars.get("coeff");
        if(coeff == null) {
            continue;
        } else if(!coeff.isArray()) {
            ((ObjectNode)vars).putArray("coeff").add(coeff.asDouble());
        }
    }
    return spellTree;
}
 
Example 17
Source File: WAMPMessage.java    From jlibs with Apache License 2.0 4 votes vote down vote up
static ArrayNode arrayValue(ArrayNode array, int index) throws InvalidMessageException{
    JsonNode node = array.get(index);
    if(!node.isArray())
        throw new InvalidMessageException();
    return (ArrayNode)node;
}
 
Example 18
Source File: BasicURLNormalizer.java    From storm-crawler with Apache License 2.0 4 votes vote down vote up
@Override
public void configure(Map stormConf, JsonNode paramNode) {
    JsonNode node = paramNode.get("removeAnchorPart");
    if (node != null) {
        removeAnchorPart = node.booleanValue();
    }

    node = paramNode.get("unmangleQueryString");
    if (node != null) {
        unmangleQueryString = node.booleanValue();
    }

    node = paramNode.get("queryElementsToRemove");
    if (node != null) {
        if (!node.isArray()) {
            LOG.warn(
                    "Failed to configure queryElementsToRemove.  Not an array: {}",
                    node.toString());
        } else {
            ArrayNode array = (ArrayNode) node;
            for (JsonNode element : array) {
                queryElementsToRemove.add(element.asText());
            }
        }
    }

    node = paramNode.get("checkValidURI");
    if (node != null) {
        checkValidURI = node.booleanValue();
    }

    node = paramNode.get("removeHashes");
    if (node != null) {
        removeHashes = node.booleanValue();
    }

    node = paramNode.get("hostIDNtoASCII");
    if (node != null) {
        hostIDNtoASCII = node.booleanValue();
    }
}
 
Example 19
Source File: AbstractRValueJacksonDeserializer.java    From datacollector with Apache License 2.0 4 votes vote down vote up
protected boolean isScrubbed(JsonNode jsonValue, DeserializationContext deserializationContext) {
  boolean scrubbed = jsonValue.isArray() &&
      (jsonValue).size() == 1 &&
      RValueJacksonSerializer.SCRUBBED_ELEMENT.equals((jsonValue).get(0).asText());
  return scrubbed;
}
 
Example 20
Source File: ApiV2ControllerStateTransitionTest.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
private void updateCiData(int ciTypeId, String guid) throws Exception {
    // get existing description
    com.webank.cmdb.dto.QueryRequest request;
    String existingDesc = getFieldValue(ciTypeId, guid, "description", false);

    Map<?, ?> jsonMap = ImmutableMap.builder()
            .put("guid", guid)
            .put("description", "update desc new")
            .build();
    String updateJson = JsonUtil.toJson(ImmutableList.of(jsonMap));

    MvcResult updateResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/update", ciTypeId).contentType(MediaType.APPLICATION_JSON)
            .content(updateJson))
            .andExpect(jsonPath("$.statusCode", is("OK")))
            .andExpect(jsonPath("$.data", hasSize(equalTo(1))))
            .andReturn();

    String updatedRet = updateResult.getResponse()
            .getContentAsString();
    JsonNode updateResultDataNode = new ObjectMapper().readTree(updatedRet)
            .get("data");
    if (updateResultDataNode.isArray()) {
        assertThat(updateResultDataNode.get(0)
                .get("description")
                .asText(), equalTo("update desc new"));
    }

    String parentGuid = JsonUtil.asNodeByPath(updatedRet, "/data/0/p_guid")
            .asText();
    if (!Strings.isNullOrEmpty(parentGuid)) {
        // compare the description from parent ci with existing description
        request = new com.webank.cmdb.dto.QueryRequest();
        request.getDialect()
                .setShowCiHistory(true);
        request.setFilters(Lists.newArrayList(new Filter("guid", FilterOperator.Equal.getCode(), parentGuid)));
        MvcResult parentResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/retrieve", ciTypeId).contentType(MediaType.APPLICATION_JSON)
                .content(JsonUtil.toJson(request)))
                .andReturn();
        String parentRetContent = parentResult.getResponse()
                .getContentAsString();
        String parentDesc = JsonUtil.asNodeByPath(parentRetContent, "/data/contents/0/data/description")
                .asText();
        assertThat(parentDesc, equalTo(existingDesc));
    }

}