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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isMissingNode() . 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: JsonNodeMappingSupport.java    From shimmer with Apache License 2.0 6 votes vote down vote up
/**
 * @param parentNode a parent node
 * @param path a path to a child node, where dots denote nested nodes
 * @return the child node reached by traversing the path, or an empty optional if the child doesn't exist
 */
public static Optional<JsonNode> asOptionalNode(final JsonNode parentNode, final String path) {

    Iterable<String> pathSegments = Splitter.on(".").split(path);
    JsonNode node = parentNode;

    for (String pathSegment : pathSegments) {
        JsonNode childNode = node.path(pathSegment);

        if (childNode.isMissingNode()) {
            logger.debug("A '{}' field wasn't found in node '{}'.", pathSegment, node);
            return empty();
        }

        if (childNode.isNull()) {
            logger.debug("The '{}' field is null in node '{}'.", pathSegment, node);
            return empty();
        }

        node = childNode;
    }

    return Optional.of(node);
}
 
Example 2
Source File: Context.java    From template-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * SECTION/REPEATED scope does not look up the stack.  It only resolves
 * names against the current frame's node downward.
 */
public void pushSection(Object[] names) {
  JsonNode node;
  if (names == null) {
    node = currentFrame.node();
  } else {
    node = resolve(names[0], currentFrame);
    for (int i = 1, len = names.length; i < len; i++) {
      if (node.isMissingNode()) {
        break;
      }
      node = nodePath(node, names[i]);
    }
  }
  push(node);
}
 
Example 3
Source File: ScrollingTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures there are no pending scroll contexts in elastic search cluster.
 * Queries {@code /_nodes/stats/indices/search} endpoint.
 * @see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html">Indices Stats</a>
 */
private void assertNoActiveScrolls() throws IOException  {
  // get node stats
  final Response response = NODE.restClient()
      .performRequest(new Request("GET", "/_nodes/stats/indices/search"));

  try (InputStream is = response.getEntity().getContent()) {
    final ObjectNode node = NODE.mapper().readValue(is, ObjectNode.class);
    final String path = "/indices/search/scroll_current";
    final JsonNode scrollCurrent = node.with("nodes").elements().next().at(path);
    if (scrollCurrent.isMissingNode()) {
      throw new IllegalStateException("Couldn't find node at " + path);
    }

    if (scrollCurrent.asInt() != 0) {
      final String message = String.format(Locale.ROOT, "Expected no active scrolls "
          + "but got %d. Current index stats %s", scrollCurrent.asInt(), node);
      throw new AssertionError(message);
    }
  }
}
 
Example 4
Source File: CopyOperation.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
JsonNode apply(final JsonNode node) {
    JsonNode source = node.at(from);
    if (source.isMissingNode()) {
        throw new JsonPatchException("non-existent source path: " + from);
    }

    if (path.toString().isEmpty()) {
        return source;
    }

    final JsonNode targetParent = ensureTargetParent(node, path);
    source = source.deepCopy();
    return targetParent.isArray() ? AddOperation.addToArray(path, node, source)
                                  : AddOperation.addToObject(path, node, source);
}
 
Example 5
Source File: SpatialFilterDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
public SpatialFilter decodeJSON(JsonNode node, boolean validate)
        throws DecodingException {
    if (node == null || node.isNull() || node.isMissingNode()) {
        return null;
    }
    if (validate) {
        JSONValidator.getInstance().validateAndThrow(node, SchemaConstants.Common.SPATIAL_FILTER);
    }
    if (node.isObject()) {
        final String oName = node.fields().next().getKey();
        final SOp o = SOp.valueOf(oName);
        JsonNode value = node.path(oName).path(JSONConstants.VALUE);
        JsonNode ref = node.path(oName).path(JSONConstants.REF);
        return new SpatialFilter(o.getOp(), decodeGeometry(value), ref.textValue());
    } else {
        return null;
    }
}
 
Example 6
Source File: LogicalFilter4.java    From jolt with Apache License 2.0 6 votes vote down vote up
@Override
public LogicalFilter4 deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {

    ObjectCodec objectCodec = jp.getCodec();
    ObjectNode root = jp.readValueAsTree();

    // We assume it is a LogicalFilter
    Iterator<String> iter = root.fieldNames();
    String key = iter.next();

    JsonNode arrayNode = root.iterator().next();
    if ( arrayNode == null || arrayNode.isMissingNode() || ! arrayNode.isArray() ) {
        throw new RuntimeException( "Invalid format of LogicalFilter encountered." );
    }

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = arrayNode.traverse( objectCodec );
    List<QueryFilter4> childrenQueryFilters = subJsonParser.readValueAs( new TypeReference<List<QueryFilter4>>() {} );

    return new LogicalFilter4( QueryParam.valueOf( key ), childrenQueryFilters );
}
 
Example 7
Source File: PatchProcessor.java    From data-highway with Apache License 2.0 6 votes vote down vote up
JsonNode processPatch(PatchSet patchSet) throws PatchApplicationException {
  String documentId = patchSet.getDocumentId();
  List<PatchOperation> operations = patchSet.getOperations();

  synchronized (store) {
    JsonNode document = store.getOrDefault(documentId, NullNode.getInstance());
    JsonNode updatedDocument = patchApplier.apply(document, operations);

    if (updatedDocument.isMissingNode()) {
      log.info("Removing document {}", documentId);
      store.remove(documentId);
    } else {
      log.info("Updating document {}", documentId);
      log.info("New document : {}", updatedDocument);
      store.put(documentId, updatedDocument);
    }
    return updatedDocument;
  }
}
 
Example 8
Source File: Agent.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
protected Agent(JsonNode jsonNode) {
    this();

    JsonNode nameNode = jsonNode.path("name");
    if (! nameNode.isMissingNode()) {
        this.setName(nameNode.textValue());
    }

    JsonNode mboxNode = jsonNode.path("mbox");
    if (! mboxNode.isMissingNode()) {
        this.setMbox(mboxNode.textValue());
    }

    JsonNode mboxSHA1SumNode = jsonNode.path("mbox_sha1sum");
    if (! mboxSHA1SumNode.isMissingNode()) {
        this.setMboxSHA1Sum(mboxSHA1SumNode.textValue());
    }

    JsonNode openIDNode = jsonNode.path("openid");
    if (! openIDNode.isMissingNode()) {
        this.setOpenID(openIDNode.textValue());
    }

    JsonNode acctNode = jsonNode.path("account");
    if (! acctNode.isMissingNode()) {
        this.setAccount(new AgentAccount(acctNode));
    }
}
 
Example 9
Source File: HttpResponseAssert.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the Http Response contains a numeric value at the given Json Pointer (JavaScript Object Notation
 * (JSON) Pointer). The Json Pointer syntax is described in the
 * <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>.
 *
 * @param path  the Json Pointer
 * @param value the expected value
 * @return the current {@link HttpResponseAssert}
 */
public HttpResponseAssert<T> hasJsonNumericField(String path, int value) {
    isNotNull();
    isJson();

    final JsonNode node = ((JsonNode) actual.body()).at(path);
    if (node.isMissingNode()) {
        failWithMessage("Expected node pointed by <%s> to be present in <%s>", path, actual.body().toString());
    }
    if (node.asInt() != value) {
        failWithMessage("Expected node pointed by <%s> to be <%s> but was <%s>", path, value, node.asInt());
    }

    return this;
}
 
Example 10
Source File: DafPreStandardization.java    From daf-kylo with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method is public to be testable
 * @param mapper
 * @param root
 * @return
 * @throws IOException
 */
public static List<String> getTransformations(ObjectMapper mapper, JsonNode root) throws IOException {
    final JsonNode node = root.at("/operational/ingestion_pipeline");
    if (node.isMissingNode()) {
        return new ArrayList<>();
    } else {
        final ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
        });
        return reader.readValue(node);
    }
}
 
Example 11
Source File: InteractionComponent.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
public InteractionComponent(JsonNode jsonNode) {
    this();

    JsonNode idNode = jsonNode.path("id");
    if (! idNode.isMissingNode()) {
        this.setId(idNode.textValue());
    }

    JsonNode descriptionNode = jsonNode.path("description");
    if (! descriptionNode.isMissingNode()) {
        this.setDescription(new LanguageMap(descriptionNode));
    }
}
 
Example 12
Source File: ContentFormatters.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private static void outputImageMeta(JsonNode image, StringBuilder buf, String preferredAltText) {
  if (image.isMissingNode()) {
    return;
  }

  JsonNode componentKey = image.path("componentKey");
  String focalPoint = getFocalPoint(image);
  String origSize = image.path("originalSize").asText();
  String assetUrl = image.path("assetUrl").asText();

  String altText = preferredAltText != null ? preferredAltText : getAltTextFromContentItem(image);

  if (isLicensedAssetPreview(image)) {
    buf.append("data-licensed-asset-preview=\"true\" ");
  }

  if (!componentKey.isMissingNode()) {
    buf.append("data-component-key=\"").append(componentKey.asText()).append("\" ");
  }

  buf.append("data-src=\"").append(assetUrl).append("\" ");
  buf.append("data-image=\"").append(assetUrl).append("\" ");
  buf.append("data-image-dimensions=\"").append(origSize).append("\" ");
  buf.append("data-image-focal-point=\"").append(focalPoint).append("\" ");
  buf.append("alt=\"");
  PluginUtils.escapeHtmlAttribute(altText, buf);
  buf.append("\" ");
}
 
Example 13
Source File: PropertiesMetadataCollection.java    From amazon-neptune-tools with Apache License 2.0 5 votes vote down vote up
public static PropertiesMetadataCollection fromJson(JsonNode json) {

        Map<GraphElementType<?>, PropertiesMetadata> metadataCollection = new HashMap<>();

        for (GraphElementType<?> graphElementType : MetadataTypes.values()) {
            JsonNode node = json.path(graphElementType.name());
            if (!node.isMissingNode() && node.isArray()) {
                metadataCollection.put(graphElementType, PropertiesMetadata.fromJson((ArrayNode) node));
            }
        }

        return new PropertiesMetadataCollection(metadataCollection);
    }
 
Example 14
Source File: BpmnDeployer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected boolean isEqualToCurrentLocalizationValue(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) {
    boolean isEqual = false;
    JsonNode localizationNode = infoNode.path("localization").path(language).path(id).path(propertyName);
    if (!localizationNode.isMissingNode() && !localizationNode.isNull() && localizationNode.asText().equals(propertyValue)) {
        isEqual = true;
    }
    return isEqual;
}
 
Example 15
Source File: PluginFQNParser.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Evaluates plugin FQN from provided reference by trying to fetch and parse its meta information.
 *
 * @param reference plugin reference to evaluate FQN from
 * @param fileContentProvider content provider instance to perform plugin meta requests
 * @return plugin FQN evaluated from given reference
 * @throws InfrastructureException if plugin reference is invalid or inaccessible
 */
public ExtendedPluginFQN evaluateFqn(String reference, FileContentProvider fileContentProvider)
    throws InfrastructureException {
  JsonNode contentNode;
  try {
    String pluginMetaContent = fileContentProvider.fetchContent(reference);
    contentNode = yamlReader.readTree(pluginMetaContent);
  } catch (DevfileException | IOException e) {
    throw new InfrastructureException(
        format("Plugin reference URL '%s' is invalid.", reference), e);
  }
  JsonNode publisher = contentNode.path("publisher");
  if (publisher.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "publisher"));
  }
  JsonNode name = contentNode.get("name");
  if (name.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "name"));
  }
  JsonNode version = contentNode.get("version");
  if (version.isMissingNode()) {
    throw new InfrastructureException(formatMessage(reference, "version"));
  }
  if (!version.isValueNode()) {
    throw new InfrastructureException(
        format(
            "Plugin specified by reference URL '%s' has version field that cannot be parsed to string",
            reference));
  }
  return new ExtendedPluginFQN(
      reference, publisher.textValue(), name.textValue(), version.asText());
}
 
Example 16
Source File: GeneralUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the {@code parent} node to see if it contains one of the keys, and
 * returns the first that matches. If none match it returns {@link Constants#MISSING_NODE}
 */
public static JsonNode getFirstMatchingNode(JsonNode parent, String... keys) {
  for (String key : keys) {
    JsonNode node = parent.path(key);
    if (!node.isMissingNode()) {
      return node;
    }
  }
  return Constants.MISSING_NODE;
}
 
Example 17
Source File: OpticalPortConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the output lambda configured for this port. The lambda value is
 * expressed as a frequency value. If the port type doesn't have a notion of
 * lambdas, this returns an empty Optional.
 *
 * @return an Optional that may contain a frequency value.
 */
public Optional<Long> staticLambda() {
    JsonNode sl = object.path(STATIC_LAMBDA);
    if (sl.isMissingNode()) {
        return Optional.empty();
    }
    return Optional.of(sl.asLong());
}
 
Example 18
Source File: ModelConversion.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the text value of a node or its inner string representation.
 * 
 * textOrJson( "constraint" : "performance < 10" ) -> "performance < 10"
 * textOrJson( "constraint" : { "hasMaxValue": 10 } ) -> "{\"hasMaxValue\": 10}"
 */
private static String textOrJson(JsonNode constraintNode) {
    String constraint = null;
    
    if (!constraintNode.isMissingNode()) {
        constraint = constraintNode.textValue();
        if (constraint == null) {
            constraint = constraintNode.toString();
        }
    }
    return constraint;
}
 
Example 19
Source File: CommerceUtils.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
public static JsonNode getHighestPriceAmongVariants(JsonNode item) {
  ProductType type = getProductType(item);
  JsonNode structuredContent = item.path("structuredContent");

  switch (type) {
    case PHYSICAL:
    case SERVICE:
    case GIFT_CARD:
      JsonNode variants = structuredContent.path("variants");
      if (variants.size() == 0) {
        return DEFAULT_MONEY_NODE;
      }
      JsonNode moneyNode = variants.get(0).path("priceMoney");
      Decimal price = getAmountFromMoneyNode(moneyNode);
      for (int i = 1; i < variants.size(); i++) {
        JsonNode currMoneyNode = variants.get(i).path("priceMoney");
        Decimal curr = getAmountFromMoneyNode(currMoneyNode);
        if (curr.compare(price) > 0) {
          price = curr;
          moneyNode = currMoneyNode;
        }
      }
      return moneyNode;

    case DIGITAL:
      JsonNode digitalMoneyNode = structuredContent.path("priceMoney");
      return digitalMoneyNode.isMissingNode() ? DEFAULT_MONEY_NODE : digitalMoneyNode;

    default:
      return DEFAULT_MONEY_NODE;
  }
}
 
Example 20
Source File: Context.java    From TinCanJava with Apache License 2.0 4 votes vote down vote up
public Context(JsonNode jsonNode) throws MalformedURLException, URISyntaxException {
    this();

    JsonNode registrationNode = jsonNode.path("registration");
    if (! registrationNode.isMissingNode()) {
        this.setRegistration(UUID.fromString(registrationNode.textValue()));
    }

    // TODO: check these for Group
    JsonNode instructorNode = jsonNode.path("instructor");
    if (! instructorNode.isMissingNode()) {
        this.setInstructor(Agent.fromJson(instructorNode));
    }

    JsonNode teamNode = jsonNode.path("team");
    if (! teamNode.isMissingNode()) {
        this.setTeam(Agent.fromJson(teamNode));
    }

    JsonNode contextActivitiesNode = jsonNode.path("contextActivities");
    if (! contextActivitiesNode.isMissingNode()) {
        this.setContextActivities(new ContextActivities(contextActivitiesNode));
    }

    JsonNode revisionNode = jsonNode.path("revision");
    if (! revisionNode.isMissingNode()) {
        this.setRevision(revisionNode.textValue());
    }

    JsonNode platformNode = jsonNode.path("platform");
    if (! platformNode.isMissingNode()) {
        this.setPlatform(platformNode.textValue());
    }

    JsonNode languageNode = jsonNode.path("language");
    if (! languageNode.isMissingNode()) {
        this.setLanguage(languageNode.textValue());
    }

    JsonNode statementNode = jsonNode.path("statement");
    if (! statementNode.isMissingNode()) {
        this.setStatement(new StatementRef(statementNode));
    }

    JsonNode extensionsNode = jsonNode.path("extensions");
    if (! extensionsNode.isMissingNode()) {
        this.setExtensions(new Extensions(extensionsNode));
    }
}