Java Code Examples for com.fasterxml.jackson.databind.node.JsonNodeType#OBJECT

The following examples show how to use com.fasterxml.jackson.databind.node.JsonNodeType#OBJECT . 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: DefaultHealthCheckUpdateHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HealthCheckUpdateResult handlePut(AggregatedHttpRequest req) {
    final JsonNode json = toJsonNode(req);
    if (json.getNodeType() != JsonNodeType.OBJECT) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    final JsonNode healthy = json.get("healthy");
    if (healthy == null) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }
    if (healthy.getNodeType() != JsonNodeType.BOOLEAN) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    return healthy.booleanValue() ? HealthCheckUpdateResult.HEALTHY
                                  : HealthCheckUpdateResult.UNHEALTHY;
}
 
Example 2
Source File: OpenAPIImporter.java    From microcks with Apache License 2.0 6 votes vote down vote up
/** 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 3
Source File: JsonCacheImpl.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
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 4
Source File: JsonObjectMapperDecoder.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private Map<String, String> decodeAttributes(JsonNode tree, String name) {
    final JsonNode n = tree.get(name);

    if (n == null) {
        return EMPTY_ATTRIBUTES;
    }

    if (n.getNodeType() != JsonNodeType.OBJECT) {
        return EMPTY_ATTRIBUTES;
    }

    final Map<String, String> attributes = Maps.newHashMap();

    final Iterator<Map.Entry<String, JsonNode>> iter = n.fields();

    while (iter.hasNext()) {
        final Map.Entry<String, JsonNode> e = iter.next();
        attributes.put(e.getKey(), e.getValue().asText());
    }

    return attributes;
}
 
Example 5
Source File: RoutingConfigParser.java    From styx with Apache License 2.0 5 votes vote down vote up
public static StyxObjectConfiguration toRoutingConfigNode(JsonNode jsonNode) {
    if (jsonNode.getNodeType() == JsonNodeType.STRING) {
        return new StyxObjectReference(jsonNode.asText());
    } else if (jsonNode.getNodeType() == JsonNodeType.OBJECT) {
        String name = getOrElse(jsonNode, "name", "");
        String type = getMandatory(jsonNode, "type", format("Routing config definition must have a 'type' attribute in def='%s'", name));
        JsonNode conf = jsonNode.get("config");
        return new StyxObjectDefinition(name, type, conf);
    }
    throw new IllegalArgumentException("invalid configuration");
}
 
Example 6
Source File: DeviceDescriptionDiscoveryCiscoImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private String getModuleSerial(int moduleId, JsonNode macs) {
    if (macs.getNodeType() == JsonNodeType.ARRAY) {
        Optional<JsonNode> serial = StreamSupport.stream(macs.spliterator(), false)
                .filter(mac -> mac.get(MODULE_MAC).asInt() == moduleId)
                .findAny();
        if (serial.isPresent()) {
            return serial.get().get(MODULE_SERIAL).asText();
        }
    } else if (macs.getNodeType() == JsonNodeType.OBJECT) {
        if (macs.get(MODULE_MAC).asInt() == moduleId) {
            return macs.get(MODULE_SERIAL).asText();
        }
    }
    return UNKNOWN;
}
 
Example 7
Source File: DeviceDescriptionDiscoveryCiscoImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private List<String> prepareModuleAnnotation(JsonNode modules, JsonNode macs) {
    List<String> modulesInfo = new ArrayList<>();
    if (modules.getNodeType() == JsonNodeType.ARRAY) {
        modules.forEach(module -> modulesInfo.add(getModuleInfo(module, macs)));
    } else if (modules.getNodeType() == JsonNodeType.OBJECT) {
        modulesInfo.add(getModuleInfo(modules, macs));
    }
    return modulesInfo;
}
 
Example 8
Source File: UserDeserializer.java    From osiam with MIT License 5 votes vote down vote up
private Extension deserializeExtension(JsonParser jp, JsonNode rootNode, String urn) throws IOException {
    if (urn == null || urn.isEmpty()) {
        throw new IllegalStateException("The URN cannot be null or empty");
    }
    if (rootNode.getNodeType() != JsonNodeType.OBJECT) {
        throw new JsonMappingException(jp, "Extension is of wrong JSON type");
    }
    Extension.Builder extensionBuilder = new Extension.Builder(urn);
    Iterator<Map.Entry<String, JsonNode>> fieldIterator = rootNode.fields();
    while (fieldIterator.hasNext()) {
        Map.Entry<String, JsonNode> entry = fieldIterator.next();
        switch (entry.getValue().getNodeType()) {
            case BOOLEAN:
                Boolean boolValue = ExtensionFieldType.BOOLEAN.fromString(entry.getValue().asText());
                extensionBuilder.setField(entry.getKey(), boolValue);
                break;
            case STRING:
                String stringValue = ExtensionFieldType.STRING.fromString(entry.getValue().asText());
                extensionBuilder.setField(entry.getKey(), stringValue);
                break;
            case NUMBER:
                String numberValueAsString = entry.getValue().asText();
                if (numberValueAsString.contains(".")) {
                    BigDecimal decimalValue = ExtensionFieldType.DECIMAL.fromString(numberValueAsString);
                    extensionBuilder.setField(entry.getKey(), decimalValue);
                } else {
                    BigInteger integerValue = ExtensionFieldType.INTEGER.fromString(numberValueAsString);
                    extensionBuilder.setField(entry.getKey(), integerValue);
                }
                break;
            default:
                throw new IllegalArgumentException("JSON type not supported: " + entry.getValue().getNodeType());
        }
    }

    return extensionBuilder.build();
}
 
Example 9
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String clientData, JsonNode certChainData) {
    try {
        boolean validChain = validateChainData(certChainData);

        connector.getLogger().debug(String.format("Is player data valid? %s", validChain));

        JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText());
        JsonNode payload = JSON_MAPPER.readTree(jwt.getPayload().toBytes());

        if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
            throw new RuntimeException("AuthData was not found!");
        }

        JsonNode extraData = payload.get("extraData");
        session.setAuthenticationData(new AuthData(
                extraData.get("displayName").asText(),
                UUID.fromString(extraData.get("identity").asText()),
                extraData.get("XUID").asText()
        ));

        if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
            throw new RuntimeException("Identity Public Key was not found!");
        }

        ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
        JWSObject clientJwt = JWSObject.parse(clientData);
        EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);

        session.setClientData(JSON_MAPPER.convertValue(JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()), BedrockClientData.class));

        if (EncryptionUtils.canUseEncryption()) {
            LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
        }
    } catch (Exception ex) {
        session.disconnect("disconnectionScreen.internalError.cantConnect");
        throw new RuntimeException("Unable to complete login", ex);
    }
}
 
Example 10
Source File: JsonPatch.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static void generateDiffs(final DiffProcessor processor, final JsonPointer pointer,
                                  final JsonNode source, final JsonNode target) {

    if (EQUIVALENCE.equivalent(source, target)) {
        return;
    }

    final JsonNodeType sourceType = source.getNodeType();
    final JsonNodeType targetType = target.getNodeType();

    /*
     * Node types differ: generate a replacement operation.
     */
    if (sourceType != targetType) {
        processor.valueReplaced(pointer, source, target);
        return;
    }

    /*
     * If we reach this point, it means that both nodes are the same type,
     * but are not equivalent.
     *
     * If this is not a container, generate a replace operation.
     */
    if (!source.isContainerNode()) {
        processor.valueReplaced(pointer, source, target);
        return;
    }

    /*
     * If we reach this point, both nodes are either objects or arrays;
     * delegate.
     */
    if (sourceType == JsonNodeType.OBJECT) {
        generateObjectDiffs(processor, pointer, (ObjectNode) source, (ObjectNode) target);
    } else {
        // array
        generateArrayDiffs(processor, pointer, (ArrayNode) source, (ArrayNode) target);
    }
}
 
Example 11
Source File: Validate.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Replace $ref references with relevant schemas and recreate the swagger definition.
 *
 * @param parent Swagger definition parent Node
 */
private static void generateSchema(JsonNode parent) {
    JsonNode schemaProperty;
    Iterator<Map.Entry<String, JsonNode>> schemaNode;
    if (parent.get(0) != null) {
        schemaNode = parent.get(0).fields();
    } else {
        schemaNode = parent.fields();
    }
    while (schemaNode.hasNext()) {
        Map.Entry<String, JsonNode> entry = schemaNode.next();
        if (entry.getValue().has(Constants.SCHEMA_REFERENCE)) {
            JsonNode refNode = entry.getValue();
            Iterator<Map.Entry<String, JsonNode>> refItems = refNode.fields();
            while (refItems.hasNext()) {
                Map.Entry<String, JsonNode> entryRef = refItems.next();
                if (entryRef.getKey().equals(Constants.SCHEMA_REFERENCE)) {
                    JsonNode schemaObject = extractSchemaObject(entryRef.getValue());
                    if (schemaObject != null) {
                        entry.setValue(schemaObject);
                    }
                }
            }
        }
        schemaProperty = entry.getValue();
        if (JsonNodeType.OBJECT == schemaProperty.getNodeType()) {
            generateSchema(schemaProperty);
        }
        if (JsonNodeType.ARRAY == schemaProperty.getNodeType()) {
            generateArraySchemas(entry);
        }
    }
}
 
Example 12
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void remove(JsonNode jsonNode, String path) {
    JsonPointer valueNodePointer = JsonPointer.compile(asJsonPath(path));
    JsonPointer parentPointer = valueNodePointer.head();
    JsonNode parentNode = jsonNode.at(parentPointer);
    if (parentNode.getNodeType() == JsonNodeType.OBJECT) {
        ObjectNode parentNodeToUpdate = (ObjectNode) parentNode;
        parentNodeToUpdate.remove(StringUtils.replace(valueNodePointer.last().toString(),"/",""));
    }

}
 
Example 13
Source File: JSONUtils.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void put(JsonNode jsonNode, String path, JsonNode value) {
    JsonPointer valueNodePointer = JsonPointer.compile(asJsonPath(path));
    JsonPointer parentPointer = valueNodePointer.head();
    addMissingNodeIfNecessary(jsonNode, path);
    JsonNode parentNode = jsonNode.at(parentPointer);

    if (parentNode.getNodeType() == JsonNodeType.OBJECT) {
        ObjectNode parentNodeToUpdate = (ObjectNode) parentNode;
        parentNodeToUpdate.set(StringUtils.replace(valueNodePointer.last().toString(),"/", ""), value);
    }
}
 
Example 14
Source File: KeywordFieldTransformator.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void apply(String idProcess, ParameterTransformation parameterTransformation, ObjectNode jsonValue) {
    JsonNode at = at(parameterTransformation.getKeyField(), jsonValue);
    String valueToFormat = at.getNodeType() == JsonNodeType.OBJECT ? at.toString() : at.asText();
    if (StringUtils.isNotBlank(valueToFormat)) {
        put(jsonValue, parameterTransformation.getKeyField() + "_keyword", valueToFormat);
        remove(jsonValue,parameterTransformation.getKeyField());
    }
}
 
Example 15
Source File: GenieClientUtils.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Given a response from a Genie search API parse the results from the list.
 *
 * @param response        The response JSON from the server
 * @param searchResultKey The JSON key the search result list is expected to exist under
 * @param clazz           The expected response type to bind to
 * @param <T>             The type of POJO to bind to
 * @return A {@link List} of {@literal T} or empty if no results
 * @throws IOException          On error reading the body
 * @throws GenieClientException On unsuccessful query
 */
static <T> List<T> parseSearchResultsResponse(
    final Response<JsonNode> response,
    final String searchResultKey,
    final Class<T> clazz
) throws IOException {
    if (!response.isSuccessful()) {
        throw new GenieClientException(
            "Search failed due to "
                + (response.errorBody() == null ? response.message() : response.errorBody().toString())
        );
    }

    // Request returned some 2xx
    final JsonNode body = response.body();
    if (body == null || body.getNodeType() != JsonNodeType.OBJECT) {
        return Lists.newArrayList();
    }
    final JsonNode embedded = body.get("_embedded");
    if (embedded == null || embedded.getNodeType() != JsonNodeType.OBJECT) {
        // Kind of an invalid response? Could return error or just swallow?
        return Lists.newArrayList();
    }
    final JsonNode searchResultsJson = embedded.get(searchResultKey);
    if (searchResultsJson == null || searchResultsJson.getNodeType() != JsonNodeType.ARRAY) {
        return Lists.newArrayList();
    }

    final List<T> searchList = new ArrayList<>();
    for (final JsonNode searchResultJson : searchResultsJson) {
        final T searchResult = GenieClientUtils.treeToValue(searchResultJson, clazz);
        searchList.add(searchResult);
    }
    return searchList;
}
 
Example 16
Source File: JsonNode.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final boolean isContainerNode() {
    final JsonNodeType type = getNodeType();
    return type == JsonNodeType.OBJECT || type == JsonNodeType.ARRAY;
}
 
Example 17
Source File: IsJsonObject.java    From java-hamcrest with Apache License 2.0 4 votes vote down vote up
private IsJsonObject(final LinkedHashMap<String, Matcher<? super JsonNode>> entryMatchers) {
  super(JsonNodeType.OBJECT);
  this.entryMatchers = Objects.requireNonNull(entryMatchers);
}
 
Example 18
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private static <T> T rejectNeitherArrayNorObject(AggregatedHttpResponse res) {
    throw new CentralDogmaException(
            "invalid server response; expected: " + JsonNodeType.OBJECT + " or " + JsonNodeType.ARRAY +
            ", content: " + toString(res));
}
 
Example 19
Source File: JsonPath.java    From knox with Apache License 2.0 4 votes vote down vote up
public List<Match> evaluate( JsonNode root ) {
  JsonNode parent;
  JsonNode child;
  Match newMatch;
  List<Match> tempMatches;
  List<Match> oldMatches = new ArrayList<>();
  List<Match> newMatches = new ArrayList<>();
  if( root != null ) {
    for( Segment seg : segments ) {
      if( Segment.Type.ROOT == seg.getType() ) {
        oldMatches.add( new Match( null, segments.get( 0 ), root, null, -1 ) );
        continue;
      } else {
        for( Match oldMatch : oldMatches ) {
          parent = oldMatch.getNode();
          switch( seg.getType() ) {
            case FIELD:
              if( JsonNodeType.OBJECT == oldMatch.getNode().getNodeType() ) {
                child = oldMatch.getNode().get( seg.getField() );
                if( child == null ) {
                  continue;
                } else {
                  newMatches.add( new Match( oldMatch, seg, child, seg.getField() ) );
                }
              } else {
                continue;
              }
              break;
            case INDEX:
              if( JsonNodeType.ARRAY == oldMatch.getNode().getNodeType() ) {
                child = oldMatch.getNode().get( seg.getIndex() );
                if( child == null ) {
                  continue;
                } else {
                  newMatches.add( new Match( oldMatch, seg, child, seg.getIndex() ) );
                }
              } else {
                continue;
              }
              break;
            case GLOB:
              newMatches.add( oldMatch );
            case WILD:
              switch( parent.getNodeType() ) {
                case OBJECT:
                  Iterator<Map.Entry<String,JsonNode>> fields = parent.fields();
                  while( fields.hasNext() ) {
                    Map.Entry<String,JsonNode> field = fields.next();
                    newMatch = new Match( oldMatch, seg, field.getValue(), field.getKey() );
                    newMatches.add( newMatch );
                    if( seg.getType() == Segment.Type.GLOB ) {
                      addAllChildren( oldMatch, newMatches, field.getValue() );
                    }
                  }
                  break;
                case ARRAY:
                  for( int i=0, n=parent.size(); i<n; i++ ) {
                    newMatch = new Match( oldMatch, seg, parent.get( i ), i );
                    newMatches.add( newMatch );
                    if( seg.getType() == Segment.Type.GLOB ) {
                      addAllChildren( oldMatch, newMatches, newMatch.getNode() );
                    }
                  }
                  break;
              }
              break;
            default:
              throw new IllegalStateException();
          }
        }
        if( newMatches.isEmpty() ) {
          return newMatches;
        } else {
          tempMatches = oldMatches;
          oldMatches = newMatches;
          newMatches = tempMatches;
          newMatches.clear();
        }
      }
    }
  }
  return oldMatches;
}
 
Example 20
Source File: CodeTransProcessor.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
  super.init(processingEnv);
  String outputOption = processingEnv.getOptions().get("codetrans.output");
  if (outputOption != null) {
    outputDir = new File(outputOption);
  }
  translator = new CodeTranslator(processingEnv);
  langs = new ArrayList<>();
  String renderOpt = processingEnv.getOptions().get("codetrans.render");
  renderMode = renderOpt != null ? RenderMode.valueOf(renderOpt.toUpperCase()) : RenderMode.EXAMPLE;
  String langsOpt = processingEnv.getOptions().get("codetrans.langs");
  Set<String> langs;
  if (langsOpt != null) {
    langs = new HashSet<>(Arrays.asList(langsOpt.split("\\s*,\\s*")));
  } else {
    langs = new HashSet<>(Arrays.asList("js", "ruby", "kotlin", "groovy"));
  }
  String configOpt = processingEnv.getOptions().get("codetrans.config");
  if (configOpt != null) {
    ObjectMapper mapper = new ObjectMapper()
        .enable(JsonParser.Feature.ALLOW_COMMENTS)
        .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
    File file = new File(configOpt);
    try {
      config = (ObjectNode) mapper.readTree(file);
    } catch (IOException e) {
      System.err.println("[ERROR] Cannot read configuration file " + file.getAbsolutePath() + " : " + e.getMessage());
      e.printStackTrace();
    }
  }
  for (String lang : langs) {
    Lang l;
    switch (lang) {
      case "kotlin":
        l = new KotlinLang();
        break;
      case "groovy":
        l = new GroovyLang();
        break;
      case "scala":
        l = new ScalaLang();
        break;
      default:
        continue;
    }
    this.langs.add(l);
    if (config != null) {
      JsonNode n = config.get(lang);
      if (n != null && n.getNodeType() == JsonNodeType.OBJECT) {
        JsonNode excludes = n.get("excludes");
        if (excludes != null && excludes.getNodeType() == JsonNodeType.ARRAY) {
          Set<String> t = new HashSet<>();
          abc.put(l.id(), t);
          for (int i = 0;i < excludes.size();i++) {
            JsonNode c = excludes.get(i);
            if (c.getNodeType() == JsonNodeType.STRING) {
              TextNode tn = (TextNode) c;
              t.add(tn.asText());
            }
          }
        }
      }
    }
  }
}