com.fasterxml.jackson.core.TreeNode Java Examples

The following examples show how to use com.fasterxml.jackson.core.TreeNode. 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: SelfHealingEngine.java    From healenium-web with Apache License 2.0 7 votes vote down vote up
/**
 * Convert raw data to {@code Node}
 * @param parser - JSON reader
 * @return path node
 * @throws IOException
 */
private Node toNode(JsonParser parser) throws IOException {
    ObjectCodec codec = parser.getCodec();
    TreeNode tree = parser.readValueAsTree();
    String tag = codec.treeToValue(tree.path(FieldName.TAG), String.class);
    Integer index = codec.treeToValue(tree.path(FieldName.INDEX), Integer.class);
    String innerText = codec.treeToValue(tree.path(FieldName.INNER_TEXT), String.class);
    String id = codec.treeToValue(tree.path(FieldName.ID), String.class);
    //noinspection unchecked
    Set<String> classes = codec.treeToValue(tree.path(FieldName.CLASSES), Set.class);
    //noinspection unchecked
    Map<String, String> attributes = codec.treeToValue(tree.path(FieldName.OTHER), Map.class);
    return new NodeBuilder()
            //TODO: fix attribute setting, because they override 'id' and 'classes' property
            .setAttributes(attributes)
            .setTag(tag)
            .setIndex(index)
            .setId(id)
            .addContent(innerText)
            .setClasses(classes)
            .build();
}
 
Example #2
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 6 votes vote down vote up
private Map<Object, Class<?>> fetchParameterMap(TreeNode paramsNode) throws IOException {
  try {
    final Map<Object, Class<?>> parameterMap = new HashMap<>();
    final Iterator<String> paramsFieldNamesIterator = paramsNode.fieldNames();
    String parameterValueAsString;
    Class<?> parameterType;
    while (paramsFieldNamesIterator.hasNext()) {
      parameterValueAsString = trimJSONQuotes(paramsFieldNamesIterator.next());
      parameterType = Class.forName(trimJSONQuotes(paramsNode.get(parameterValueAsString).toString()));
      parameterMap.put(cast(parameterValueAsString, parameterType), parameterType);
    }
    return parameterMap;
  } catch (Exception e) {
    throw new IOException("Error while fetching parameters " + paramsNode, e);
  }
}
 
Example #3
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 6 votes vote down vote up
private KnoxShellTable parseJsonWithData(final TreeNode jsonContent) {
  if (jsonContent.get("title").size() != 0) {
    table.title(trimJSONQuotes(jsonContent.get("title").toString()));
  }

  final TreeNode headers = jsonContent.get("headers");
  for (int i = 0; i < headers.size(); i++) {
    table.header(trimJSONQuotes(headers.get(i).toString()));
  }
  final TreeNode rows = jsonContent.get("rows");
  for (int i = 0; i < rows.size(); i++) {
    TreeNode row = rows.get(i);
    table.row();
    for (int j = 0; j < row.size(); j++) {
      table.value(trimJSONQuotes(row.get(j).toString()));
    }
  }
  return table;
}
 
Example #4
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 6 votes vote down vote up
private List<KnoxShellTableCall> parseCallHistoryListJSONNode(TreeNode callHistoryNode) throws IOException {
  final List<KnoxShellTableCall> callHistoryList = new LinkedList<>();
  TreeNode callNode;
  Map<Object, Class<?>> params;
  String invokerClass, method;
  Boolean builderMethod;
  for (int i = 0; i < callHistoryNode.size(); i++) {
    callNode = callHistoryNode.get(i);
    invokerClass = trimJSONQuotes(callNode.get("invokerClass").toString());
    method = trimJSONQuotes(callNode.get("method").toString());
    builderMethod = Boolean.valueOf(trimJSONQuotes(callNode.get("builderMethod").toString()));
    params = fetchParameterMap(callNode.get("params"));
    callHistoryList.add(new KnoxShellTableCall(invokerClass, method, builderMethod, params));
  }
  return callHistoryList;
}
 
Example #5
Source File: YAMLSchemaValidator.java    From pegasus with Apache License 2.0 6 votes vote down vote up
/** This is used to populate the error location or the node which causes the error.. */
private void populateSiteErrorMessage(
        TreeNode node, StringBuilder errorMessage, JsonNode jsonNode) {
    String path = jsonNode.get("instance").get("pointer").asText();
    String[] splitPaths = path.split("/");

    // this means some node inside the top level has a problem..
    if (splitPaths.length > 1) {
        try {
            // this represents the location of error..
            int location = Integer.parseInt(splitPaths[2]);

            TreeNode nodeDetails = node.get("site").get(location);
            errorMessage.append(nodeDetails);
        } catch (Exception e) {
            errorMessage.append(path);
        }

    } else {
        errorMessage.append("top level error");
    }
}
 
Example #6
Source File: PipelineOptionsTranslation.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Converts the provided {@link Struct} into {@link PipelineOptions}. */
public static PipelineOptions fromProto(Struct protoOptions) {
  try {
    Map<String, TreeNode> mapWithoutUrns = new HashMap<>();
    TreeNode rootOptions = MAPPER.readTree(JsonFormat.printer().print(protoOptions));
    Iterator<String> optionsKeys = rootOptions.fieldNames();
    while (optionsKeys.hasNext()) {
      String optionKey = optionsKeys.next();
      TreeNode optionValue = rootOptions.get(optionKey);
      mapWithoutUrns.put(
          CaseFormat.LOWER_UNDERSCORE.to(
              CaseFormat.LOWER_CAMEL,
              optionKey.substring("beam:option:".length(), optionKey.length() - ":v1".length())),
          optionValue);
    }
    return MAPPER.readValue(
        MAPPER.writeValueAsString(ImmutableMap.of("options", mapWithoutUrns)),
        PipelineOptions.class);
  } catch (IOException e) {
    throw new RuntimeException("Failed to read PipelineOptions from Protocol", e);
  }
}
 
Example #7
Source File: LSServerFilterDeserializer.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Override
public List<LSServerFilter> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  ObjectCodec oc = jp.getCodec();
  JsonNode node = oc.readTree(jp);
  
  List<LSServerFilter> filters = new ArrayList<>();
  for (JsonNode filterNode : node) {
    if (filterNode.get("filter") == null) {
      throw new IllegalArgumentException("Each filter element must have a field called 'filter' declaring it's type");
    }
    switch (filterNode.get("filter").asText()) {
      case "grok" :
        filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterGrok.class));
        break;
      case "keyvalue" :
        filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterKeyValue.class));
        break;
      case "json" :
        filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterJson.class));
        break;
    }
  }
  
  return filters;
}
 
Example #8
Source File: GuestBloggerPairDeserializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<Pair<AccountName, Long>> deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws IOException {

    List<Pair<AccountName, Long>> result = new ArrayList<>();

    ObjectCodec codec = jsonParser.getCodec();
    TreeNode rootNode = codec.readTree(jsonParser);

    if (rootNode.isArray()) {
        for (JsonNode node : (ArrayNode) rootNode) {
            // result.put((node.get(0)).asText(), (node.get(0)).asInt());
        }

        return result;
    }

    throw new IllegalArgumentException("JSON Node is not an array.");
}
 
Example #9
Source File: TagUsagePairDeserializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<Pair<String, Long>> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    List<Pair<String, Long>> result = new ArrayList<>();

    ObjectCodec codec = jsonParser.getCodec();
    TreeNode rootNode = codec.readTree(jsonParser);

    if (rootNode.isArray()) {
        for (JsonNode node : (ArrayNode) rootNode) {
            // result.put((node.get(0)).asText(), (node.get(0)).asInt());
        }

        return result;
    }

    throw new IllegalArgumentException("JSON Node is not an array.");
}
 
Example #10
Source File: ReadViaCodecTest.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
public void testSimpleMixed() throws Exception
{
    final String INPUT = "{\"a\":[1,2,{\"b\":true},3],\"c\":3}";
    TreeNode node = TREE_CODEC.readTree(_factory.createParser(READ_CONTEXT, INPUT));
    assertTrue(node instanceof JrsObject);
    assertEquals(2, node.size());
    TreeNode list = node.get("a");
    assertTrue(list instanceof JrsArray);

    // actually, verify with write...
    final StringWriter writer = new StringWriter();
    final JsonGenerator g = _factory.createGenerator(WRITE_CONTEXT, writer);
    TREE_CODEC.writeTree(g, node);
    g.close();
    assertEquals(INPUT, writer.toString());
}
 
Example #11
Source File: AccountAuthHashMapDeserializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, Integer> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    HashMap<String, Integer> result = new HashMap<>();

    ObjectCodec codec = jsonParser.getCodec();
    TreeNode rootNode = codec.readTree(jsonParser);

    if (rootNode.isArray()) {
        for (JsonNode node : (ArrayNode) rootNode) {
            result.put((node.get(0)).asText(), (node.get(0)).asInt());
        }

        return result;
    }

    throw new IllegalArgumentException("JSON Node is not an array.");
}
 
Example #12
Source File: PublicKeyHashMapDeserializer.java    From steem-java-api-wrapper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Map<PublicKey, Integer> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException {

    HashMap<PublicKey, Integer> result = new HashMap<>();

    ObjectCodec codec = jsonParser.getCodec();
    TreeNode rootNode = codec.readTree(jsonParser);

    if (rootNode.isArray()) {
        for (JsonNode node : (ArrayNode) rootNode) {
            PublicKey publicKey = new PublicKey((node.get(0)).asText());
            result.put(publicKey, (node.get(0)).asInt());
        }

        return result;
    }

    throw new IllegalArgumentException("JSON Node is not an array.");
}
 
Example #13
Source File: SortJsonComponent.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Override
public Sort deserialize(JsonParser jsonParser,
		DeserializationContext deserializationContext) throws IOException {
	TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
	if (treeNode.isArray()) {
		ArrayNode arrayNode = (ArrayNode) treeNode;
		List<Sort.Order> orders = new ArrayList<>();
		for (JsonNode jsonNode : arrayNode) {
			Sort.Order order = new Sort.Order(
					Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
					jsonNode.get("property").textValue());
			orders.add(order);
		}
		return Sort.by(orders);
	}
	return null;
}
 
Example #14
Source File: DateJsonConvert.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
public InfoDTO deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
    throws IOException {
    InfoDTO infoDTO = new InfoDTO();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);

    TextNode appNameNode = (TextNode) treeNode.get("appName");
    infoDTO.setAppName(appNameNode.asText());
    TextNode versionNode = (TextNode) treeNode.get("version");
    infoDTO.setVersion(versionNode.asText());
    TextNode dateNode = (TextNode) treeNode.get("date");
    try {
        infoDTO.setDate(sdf.parse(dateNode.asText()));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return infoDTO;
}
 
Example #15
Source File: PrivateTransaction.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public PrivateTransaction deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    final TreeNode node = p.readValueAsTree();

    // Select the concrete class based on the existence of a property
    if (node.get("privateFor") != null && node.get("privateFor").isArray()) {
        return p.getCodec().treeToValue(node, PrivateTransactionLegacy.class);
    } else if ((node.get("privateFor") != null && node.get("privateFor").isValueNode())
            || (node.get("privacyGroupId") != null
                    && node.get("privacyGroupId").isValueNode())) {
        return p.getCodec().treeToValue(node, PrivateTransactionWithPrivacyGroup.class);
    }

    return null;
}
 
Example #16
Source File: ComponentInstanceDeserializer.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public ComponentInstance readAsTree(final TreeNode p) throws IOException {
	ObjectMapper mapper = new ObjectMapper();
	// read the parameter values
	Map<String, String> parameterValues = mapper.treeToValue(p.get("params"), HashMap.class);
	// read the component

	String componentName = p.get("component").toString().replaceAll("\"", "");

	Component component = this.possibleComponents.stream().filter(c -> c.getName().equals(componentName)).findFirst()
			.orElseThrow(NoSuchElementException::new);

	Map<String, ComponentInstance> satisfactionOfRequiredInterfaces = new HashMap<>();
	// recursively resolve the requiredInterfaces
	TreeNode n = p.get("requiredInterfaces");
	Iterator<String> fields = n.fieldNames();
	while (fields.hasNext()) {
		String key = fields.next();
		satisfactionOfRequiredInterfaces.put(key, this.readAsTree(n.get(key)));
	}
	return new ComponentInstance(component, parameterValues, satisfactionOfRequiredInterfaces);
}
 
Example #17
Source File: ClaimInformationPointProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testBodyJsonClaimsInformationPoint() throws Exception {
    Map<String, List<String>> headers = new HashMap<>();

    headers.put("Content-Type", Arrays.asList("application/json"));

    ObjectMapper mapper = JsonSerialization.mapper;
    JsonParser parser = mapper.getFactory().createParser("{\"a\": {\"b\": {\"c\": \"c-value\"}}, \"d\": [\"d-value1\", \"d-value2\"], \"e\": {\"number\": 123}}");
    TreeNode treeNode = mapper.readTree(parser);
    HttpFacade httpFacade = createHttpFacade(headers, new ByteArrayInputStream(treeNode.toString().getBytes()));

    Map<String, List<String>> claims = getClaimInformationProviderForPath("/claims-provider", "claims").resolve(httpFacade);

    assertEquals("c-value", claims.get("claim-from-json-body-object").get(0));
    assertEquals("d-value2", claims.get("claim-from-json-body-array").get(0));
    assertEquals("123", claims.get("claim-from-json-body-number").get(0));
}
 
Example #18
Source File: TreeNodeTypeHandler.java    From mybatis-jackson with MIT License 5 votes vote down vote up
@Override
public TreeNode getResult(CallableStatement cs, int columnIndex) throws SQLException {
    try {
        return getNullableResult(cs, columnIndex);
    } catch (Exception e) {
        throw new ResultMapException("Error attempting to get column #" + columnIndex + " from callable statement.  Cause: " + e, e);
    }
}
 
Example #19
Source File: TreeNodeTypeHandler.java    From mybatis-jackson with MIT License 5 votes vote down vote up
@Override
public TreeNode getResult(ResultSet rs, int columnIndex) throws SQLException {
    try {
        return getNullableResult(rs, columnIndex);
    } catch (Exception e) {
        throw new ResultMapException("Error attempting to get column #" + columnIndex + " from result set.  Cause: " + e, e);
    }
}
 
Example #20
Source File: DocumentGenerator.java    From ojai with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTree(TreeNode rootNode) throws IOException {
  if (rootNode == null) {
    writeNull();
  } else {
    if (objectCodec == null) {
      throw new IllegalStateException("No ObjectCodec defined");
    }
    objectCodec.writeValue(this, rootNode);
  }
}
 
Example #21
Source File: TreeNodeTypeHandler.java    From mybatis-jackson with MIT License 5 votes vote down vote up
@Override
public TreeNode getResult(ResultSet rs, String columnName) throws SQLException {
    try {
        return getNullableResult(rs, columnName);
    } catch (Exception e) {
        throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
    }
}
 
Example #22
Source File: TreeNodeTypeHandler.java    From mybatis-jackson with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, TreeNode parameter, JdbcType jdbcType) throws SQLException {
    try {
        ps.setString(i, ReaderWriter.write(parameter));
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
 
Example #23
Source File: CapturingCodec.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("TypeParameterUnusedInFormals")
public <T extends TreeNode> T readTree(final JsonParser p) throws IOException {
    final T ret = delegate.readTree(p);
    captured = ret;

    return ret;
}
 
Example #24
Source File: ReadViaCodecTest.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public void testSimpleList() throws Exception
{
    final String INPUT = "[true,\"abc\"]";
    TreeNode node = TREE_CODEC.readTree(_factory.createParser(READ_CONTEXT, INPUT));

    assertTrue(node instanceof JrsArray);
    assertEquals(2, node.size());
    // actually, verify with write...
    final StringWriter writer = new StringWriter();
    final JsonGenerator g = _factory.createGenerator(WRITE_CONTEXT, writer);
    TREE_CODEC.writeTree(g, node);
    g.close();
    assertEquals(INPUT, writer.toString());
}
 
Example #25
Source File: KeepAsJsonDeserialzier.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    TreeNode tree = jp.getCodec().readTree(jp);
    return tree.toString();
}
 
Example #26
Source File: VideoDeserializerModule.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Video deserialize(JsonParser jp, DeserializationContext ctxt)
		throws IOException, JsonProcessingException {
	
	// First, do the default deserialization.
    TreeNode tree = defaultMapper.readTree(jp);
    Video video = defaultMapper.treeToValue(tree, Video.class);
    
    // Then, in case this video came from the child list of a Topic's detail record, copy the 'id' onto 'readable_id'.
    try {
    	// ClassCastException if this is really a NullNode.
    	// That should never happen. I think it was just happening because I was accidentally trying to consume the video twice.
    	ObjectNode root = (ObjectNode) tree;
	    Iterator<String> keys = root.fieldNames();
	    
	    while (keys.hasNext()) {
	    	String key = keys.next();
	    	if ("id".equals(key)) {
	    		JsonNode value = root.get(key);
	    		if (value.isTextual()) {
	    			video.setReadable_id(value.asText());
	    		}
	    	}
	    }
    } catch (ClassCastException e) {
    	e.printStackTrace();
    	// fall through and return video unchanged.
    }
	
	return video;
}
 
Example #27
Source File: TsdbResult.java    From splicer with Apache License 2.0 5 votes vote down vote up
@Override
public Tags deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	TreeNode n = jp.getCodec().readTree(jp);
	Map<String, String> tags = new HashMap<>();
	Iterator<String> namesIter = n.fieldNames();
	while(namesIter.hasNext()) {
		String field = namesIter.next();
		TreeNode child = n.get(field);
		if (child instanceof TextNode) {
			tags.put(field, ((TextNode) child).asText());
		}
	}
	return new Tags(tags);
}
 
Example #28
Source File: JSONOptions.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
    public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      JsonLocation l = jp.getTokenLocation();
//      logger.debug("Reading tree.");
      TreeNode n = jp.readValueAsTree();
//      logger.debug("Tree {}", n);
      if (n instanceof JsonNode) {
        return new JSONOptions( (JsonNode) n, l);
      } else {
        throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n));
      }
    }
 
Example #29
Source File: DurationSerialization.java    From heroic with Apache License 2.0 5 votes vote down vote up
private Duration deserializeObject(TreeNode tree, DeserializationContext c)
    throws JsonMappingException {
    if (tree == null) {
        throw c.mappingException("expected object");
    }

    TreeNode node;
    ValueNode valueNode;

    final long duration;
    final TimeUnit unit;

    if ((node = tree.get("duration")) != null && node.isValueNode() &&
        (valueNode = (ValueNode) node).isNumber()) {
        duration = valueNode.asLong();
    } else {
        throw c.mappingException("duration is not a numeric field");
    }

    if ((node = tree.get("unit")) != null && node.isValueNode() &&
        (valueNode = (ValueNode) node).isTextual()) {
        unit = TimeUnit.valueOf(valueNode.asText().toUpperCase());
    } else {
        unit = Duration.DEFAULT_UNIT;
    }

    return new Duration(duration, unit);
}
 
Example #30
Source File: JSONOptions.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
    public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      JsonLocation l = jp.getTokenLocation();
//      logger.debug("Reading tree.");
      TreeNode n = jp.readValueAsTree();
//      logger.debug("Tree {}", n);
      if (n instanceof JsonNode) {
        return new JSONOptions( (JsonNode) n, l);
      } else {
        throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n));
      }
    }