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

The following examples show how to use com.fasterxml.jackson.databind.node.JsonNodeType#ARRAY . 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: 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 2
Source File: RestService.java    From kieker with Apache License 2.0 6 votes vote down vote up
private Response processJsonRequest(final byte[] buffer) {
	try {
		final ObjectMapper mapper = new ObjectMapper();
		mapper.readTree(buffer);
		final JsonNode object = mapper.readTree(buffer);
		if (object.getNodeType() == JsonNodeType.ARRAY) {
			return this.processJsonArray((ArrayNode) object);
		} else {
			return NanoHTTPD.newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "JSON array expected");
		}
	} catch (final IOException e) {
		try {
			LOGGER.error("Parsing error for JSON message: {}", new String(buffer, "UTF-8"));
			return NanoHTTPD.newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "Malformed JSON data");
		} catch (final UnsupportedEncodingException e1) {
			return NanoHTTPD.newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT, "Malformed JSON data, is not UTF-8");
		}
	}
}
 
Example 3
Source File: DefaultHealthCheckUpdateHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HealthCheckUpdateResult handlePatch(AggregatedHttpRequest req) {
    final JsonNode json = toJsonNode(req);
    if (json.getNodeType() != JsonNodeType.ARRAY ||
        json.size() != 1) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    final JsonNode patchCommand = json.get(0);
    final JsonNode op = patchCommand.get("op");
    final JsonNode path = patchCommand.get("path");
    final JsonNode value = patchCommand.get("value");
    if (op == null || path == null || value == null ||
        !"replace".equals(op.textValue()) ||
        !"/healthy".equals(path.textValue()) ||
        !value.isBoolean()) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    return value.booleanValue() ? HealthCheckUpdateResult.HEALTHY
                                : HealthCheckUpdateResult.UNHEALTHY;
}
 
Example 4
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 5
Source File: JsonObjectMapperDecoder.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private Set<String> decodeTags(JsonNode tree, String name) {
    final JsonNode n = tree.get(name);

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

    if (n.getNodeType() != JsonNodeType.ARRAY) {
        return EMPTY_TAGS;
    }

    final List<String> tags = Lists.newArrayList();

    final Iterator<JsonNode> iter = n.elements();

    while (iter.hasNext()) {
        tags.add(iter.next().asText());
    }

    return Sets.newHashSet(tags);
}
 
Example 6
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 7
Source File: JsonDataModelTree.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creating empty json node.
 *
 * @param type json node type to create
 * @return created json node
 * @throws WorkflowException workflow exception
 */
private JsonNode createEmpty(JsonNodeType type) throws WorkflowException {
    if (type == JsonNodeType.OBJECT) {
        return JsonNodeFactory.instance.objectNode();
    } else if (type == JsonNodeType.ARRAY) {
        return JsonNodeFactory.instance.arrayNode();
    } else if (type == JsonNodeType.STRING) {
        return JsonNodeFactory.instance.textNode("");
    } else {
        throw new WorkflowException("Not supported JsonNodetype(" + type + ")");
    }
}
 
Example 8
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 9
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 10
Source File: CmRestController.java    From oneops with Apache License 2.0 5 votes vote down vote up
@Override
public CiListRequest deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    if (node.getNodeType() == JsonNodeType.ARRAY) {
        return new CiListRequest(getIds(node));
    }
    else {
        JsonNode attrProps = node.get("attrProps");
        JsonNode altNsTag = node.get("includeAltNs");
        return new CiListRequest(getIds(node.get("ids")),
                attrProps == null ? null :attrProps.asText(),
                altNsTag == null ? null : altNsTag.asText());
    }
}
 
Example 11
Source File: JsonNumEquals.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doEquivalent(final JsonNode a, final JsonNode b) {
    /*
     * If both are numbers, delegate to the helper method
     */
    if (a.isNumber() && b.isNumber()) {
        return numEquals(a, b);
    }

    final JsonNodeType typeA = a.getNodeType();
    final JsonNodeType typeB = b.getNodeType();

    /*
     * If they are of different types, no dice
     */
    if (typeA != typeB) {
        return false;
    }

    /*
     * For all other primitive types than numbers, trust JsonNode
     */
    if (!a.isContainerNode()) {
        return a.equals(b);
    }

    /*
     * OK, so they are containers (either both arrays or objects due to the
     * test on types above). They are obviously not equal if they do not
     * have the same number of elements/members.
     */
    if (a.size() != b.size()) {
        return false;
    }

    /*
     * Delegate to the appropriate method according to their type.
     */
    return typeA == JsonNodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b);
}
 
Example 12
Source File: JSONExamples.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public void treeTraversalSolution() {
    try {
        ObjectMapper mapper = new ObjectMapper();
        // use the ObjectMapper to read the json string and create a tree
        JsonNode node = mapper.readTree(new File("Persons.json"));
        Iterator<String> fieldNames = node.fieldNames();
        while (fieldNames.hasNext()) {
            JsonNode personsNode = node.get("persons");
            Iterator<JsonNode> elements = personsNode.iterator();
            while (elements.hasNext()) {
                JsonNode element = elements.next();
                JsonNodeType nodeType = element.getNodeType();
                
                if (nodeType == JsonNodeType.STRING) {
                    out.println("Group: " + element.textValue());
                }

                if (nodeType == JsonNodeType.ARRAY) {
                    Iterator<JsonNode> fields = element.iterator();
                    while (fields.hasNext()) {
                        parsePerson(fields.next());
                    }
                }
            }
            fieldNames.next();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 13
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 14
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {
    JsonNode certData;
    try {
        certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());
    } catch (IOException ex) {
        throw new RuntimeException("Certificate JSON can not be read.");
    }

    JsonNode certChainData = certData.get("chain");
    if (certChainData.getNodeType() != JsonNodeType.ARRAY) {
        throw new RuntimeException("Certificate data is not valid");
    }

    encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);
}
 
Example 15
Source File: IsJsonArray.java    From java-hamcrest with Apache License 2.0 4 votes vote down vote up
private IsJsonArray(Matcher<? super Collection<JsonNode>> elementsMatcher) {
  super(JsonNodeType.ARRAY);
  this.elementsMatcher = Objects.requireNonNull(elementsMatcher);
}
 
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: 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 18
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 19
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());
            }
          }
        }
      }
    }
  }
}
 
Example 20
Source File: AddRecordStore.java    From constellation with Apache License 2.0 4 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final String graphId = parameters.getStringValue(GRAPH_ID_PARAMETER_ID);
    final boolean completeWithSchema = parameters.getBooleanValue(COMPLETE_PARAMETER_ID);
    final String arrange = parameters.getStringValue(ARRANGE_PARAMETER_ID);
    final boolean resetView = parameters.getBooleanValue(RESET_PARAMETER_ID);

    final RecordStore rs = new GraphRecordStore();
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode json = mapper.readTree(in);

    // We want to read a JSON document that looks like:
    //
    // {"columns":["A","B"],"data":[[1,"a"],[2,"b"],[3,"c"]]}
    //
    // which is what is output by pandas.to_json(..., orient="split').
    // (We ignore the index array.)
    if (!json.hasNonNull(COLUMNS) || !json.get(COLUMNS).isArray()) {
        throw new RestServiceException("Could not find columns object containing column names");
    }

    if (!json.hasNonNull("data") || !json.get("data").isArray()) {
        throw new RestServiceException("Could not find data object containing data rows");
    }

    final ArrayNode columns = (ArrayNode) json.get(COLUMNS);
    final String[] headers = new String[columns.size()];
    for (int i = 0; i < headers.length; i++) {
        headers[i] = columns.get(i).asText();
    }

    final ArrayNode data = (ArrayNode) json.get("data");
    for (final Iterator<JsonNode> i = data.elements(); i.hasNext();) {
        final ArrayNode jrow = (ArrayNode) i.next();
        rs.add();
        boolean txFound = false;
        boolean txSourceFound = false;
        for (int ix = 0; ix < headers.length; ix++) {
            final String h = headers[ix];
            final JsonNode jn = jrow.get(ix);
            if (!jn.isNull()) {
                if (jn.getNodeType() == JsonNodeType.ARRAY) {
                    rs.set(h, RestServiceUtilities.toList((ArrayNode) jn));
                } else {
                    rs.set(h, jn.asText());
                }
            }
            txFound |= h.startsWith(GraphRecordStoreUtilities.TRANSACTION);
            txSourceFound |= TX_SOURCE.equals(h);
        }

        if (txFound && !txSourceFound) {
            rs.set(TX_SOURCE, API_SOURCE);
        }
    }

    addToGraph(graphId, rs, completeWithSchema, arrange, resetView);
}