Java Code Examples for com.fasterxml.jackson.core.JsonParser#readValueAsTree()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#readValueAsTree() . 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: PythonTestIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testXProtocolRuleWithBadTestMainModule() throws IOException, InterruptedException {
  ProcessResult result =
      workspace.runBuckCommand(
          "test",
          "--config",
          "test.external_runner=" + echoTestRunner,
          "//:testx_failure_with_test_main");
  result.assertSuccess();

  Path specOutput =
      workspace.getPath(
          workspace.getBuckPaths().getScratchDir().resolve("external_runner_specs.json"));
  JsonParser parser = ObjectMappers.createParser(specOutput);

  ArrayNode node = parser.readValueAsTree();
  JsonNode spec = node.get(0).get("specs");

  assertSpecParsing(spec);
  ProcessExecutor.Result processResult = executeCmd(spec);

  assertEquals(1, processResult.getExitCode());
  assertTrue(processResult.getStderr().toString().contains("No module named bad_test_main"));
}
 
Example 2
Source File: TransactionReceiptJsonDeserializer.java    From etherjar with Apache License 2.0 6 votes vote down vote up
@Override
public TransactionReceiptJson deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {
    JsonNode node = jp.readValueAsTree();
    TransactionReceiptJson receipt = new TransactionReceiptJson();

    receipt.setBlockHash(getBlockHash(node, "blockHash"));
    receipt.setBlockNumber(getLong(node, "blockNumber"));
    receipt.setContractAddress(getAddress(node, "contractAddress"));
    receipt.setCumulativeGasUsed(getLong(node, "cumulativeGasUsed"));
    receipt.setGasUsed(getLong(node, "gasUsed"));
    receipt.setTransactionHash(getTxHash(node, "transactionHash"));
    receipt.setTransactionIndex(getLong(node, "transactionIndex"));

    List<TransactionLogJson> logs = new ArrayList<>();
    if (node.hasNonNull("logs")) {
        for (JsonNode log: node.get("logs")) {
            logs.add(transactionLogJsonDeserializer.deserialize(log));
        }
    }
    receipt.setLogs(logs);

    return receipt;
}
 
Example 3
Source File: FieldMessageDeserializer.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public JsonField deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode obj = p.readValueAsTree();

    if (obj == null) {
        return null;
    }

    Object fields = obj.get("fields");
    if (fields != null) {
        return p.getCodec().treeToValue(obj, JsonMessage.class);
    } else {
        if (p.getCodec() == INNER_READER) {
            throw new EPSCommonException("This deserializer using like root. Please create separate module with addDeserializer().");
        }
        return INNER_READER.readValue(obj);
    }
}
 
Example 4
Source File: ArtifactDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@Override
public Artifact deserialize(JsonParser parser, DeserializationContext ctxt) 
  throws IOException, JsonProcessingException 
{
    JsonNode node = parser.readValueAsTree();
    ObjectMapper mapper = (ObjectMapper)parser.getCodec();
    ObjectReader reader = null; 
    Object target = null;
    String artifcatType = node.get("artifactType").asText();

    System.out.println(artifcatType);

    if(artifcatType.equalsIgnoreCase("reservedinstance"))
    {
        reader = mapper.readerFor(ReservedInstanceArtifact.class);
    }
    else 
    {
        reader = mapper.readerFor(Artifact.class);
    }

    target = reader.readValue(node);

    return (Artifact)target;
}
 
Example 5
Source File: FeatureCategoriesDeserializer.java    From cineast with MIT License 5 votes vote down vote up
@Override
public List<DoublePair<Class<? extends Retriever>>> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ArrayNode arrayNode = p.readValueAsTree();
    List<DoublePair<Class<? extends Retriever>>> list = new ArrayList<>(arrayNode.size());
    for (JsonNode node : arrayNode) {
        /* Extract feature and weight node. */
        JsonNode featureNode = node.get("feature");
        JsonNode weightNode = node.get("weight");
        if (featureNode == null || weightNode == null) {
          continue;
        }
        String feature = featureNode.asText();
        Double weight = weightNode.asDouble();

        /* Get class for feature. Lookup in HashMap makes sure, that every FeatureModule is only loaded once! */
        Class<Retriever> c = FeatureCategoriesDeserializer.classCache.get(feature);
        if (c == null) {
            try {
                if (feature.contains(".")) {
                    @SuppressWarnings("unchecked")
                    Class<Retriever> clazz = (Class<Retriever>) Class.forName(feature);
                    c = clazz;
                } else {
                    c = ReflectionHelper.getClassFromName(feature, Retriever.class, ReflectionHelper.FEATURE_MODULE_PACKAGE);
                }
            } catch (IllegalArgumentException | ClassNotFoundException | InstantiationException | UnsupportedOperationException e) {
                LOGGER.log(Level.WARN, "The specified feature '" + feature + "' could not be instantiated: {}",
                    LogHelper.getStackTrace(e));
            }
        }

        /* If class could be fetched, add to list. */
        if (c == null) {
          continue;
        }
        list.add(new DoublePair<Class<? extends Retriever>>(c, weight));
    }

    return list;
}
 
Example 6
Source File: JSOGDeserialize622Test.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public JSOGRef deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    JsonNode node = p.readValueAsTree();
    if (node.isTextual()) {
        return new JSOGRef(node.asInt());
    }
    JsonNode n = node.get(REF_KEY);
    if (n == null) {
        throw new JsonMappingException(p, "Could not find key '"+REF_KEY
                +"' from ("+node.getClass().getName()+"): "+node);
    }
    return new JSOGRef(n.asInt());
}
 
Example 7
Source File: CommitMessageDtoDeserializer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CommitMessageDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    final JsonNode jsonNode = p.readValueAsTree();
    final JsonNode summary = jsonNode.get("summary");
    if (summary == null || summary.textValue() == null) {
        ctxt.reportInputMismatch(CommitMessageDto.class, "commit message should have a summary.");
        // should never reach here
        throw new Error();
    }

    final String detail = jsonNode.get("detail") == null ? "" : jsonNode.get("detail").textValue();
    final JsonNode markupNode = jsonNode.get("markup");
    final Markup markup = Markup.parse(markupNode == null ? "unknown" : markupNode.textValue());
    return new CommitMessageDto(summary.textValue(), detail, markup);
}
 
Example 8
Source File: ShellCommand.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a JSON object
 * @param jp the JSON parse
 * @return the JSON node
 * @throws IOException
 */
protected JsonNode validateJson(JsonParser jp) throws IOException {
    JsonNode parsed = null;
    
    try {
        parsed = jp.readValueAsTree();
    } catch (JsonProcessingException e) {
        System.err.println("Could not parse JSON: " + e.getMessage());
        return null;
    }  
    return parsed;
}
 
Example 9
Source File: RobolectricTestRuleIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void robolectricTestXWithExternalRunnerWithoutRobolectricRuntimeDependencyArgument()
    throws Exception {
  workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "android_project", tmpFolder);
  workspace.setUp();
  AssumeAndroidPlatform.get(workspace).assumeSdkIsAvailable();
  workspace.addBuckConfigLocalOption("test", "external_runner", "echo");
  workspace.runBuckTest("//java/com/sample/runner:robolectric_without_runner_runtime_dep_failed");
  Path specOutput =
      workspace.getPath(
          workspace.getBuckPaths().getScratchDir().resolve("external_runner_specs.json"));
  JsonParser parser = ObjectMappers.createParser(specOutput);

  ArrayNode node = parser.readValueAsTree();
  JsonNode spec = node.get(0).get("specs");

  assertEquals("spec", spec.get("my").textValue());

  JsonNode other = spec.get("other");
  assertTrue(other.isArray());
  assertTrue(other.has(0));
  assertEquals("stuff", other.get(0).get("complicated").textValue());
  assertEquals(1, other.get(0).get("integer").intValue());
  assertEquals(1.2, other.get(0).get("double").doubleValue(), 0);
  assertTrue(other.get(0).get("boolean").booleanValue());

  String cmd = spec.get("cmd").textValue();
  DefaultProcessExecutor processExecutor =
      new DefaultProcessExecutor(Console.createNullConsole());
  ProcessExecutor.Result processResult =
      processExecutor.launchAndExecute(
          ProcessExecutorParams.builder().addCommand(cmd.split(" ")).build());
  assertEquals(1, processResult.getExitCode());
  assertTrue(processResult.getStderr().isPresent());
  assertTrue(processResult.getStderr().get().contains("java.lang.ClassNotFoundException"));
}
 
Example 10
Source File: FilterDescriptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public FilterDescriptor deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode jsonNode = p.readValueAsTree();

    FromNode fromNode = readValueAs(FromNode.class, jsonNode, p);
    ToNode toNode = readValueAs(ToNode.class, jsonNode, p);
    SelfNode selfNode = readValueAs(SelfNode.class, jsonNode, p);
    ResponseTime responseTime= readValueAs(ResponseTime.class, jsonNode, p);
    Option option = readValueAs(Option.class, jsonNode, p);
    return new FilterDescriptor(fromNode, toNode, selfNode, responseTime, option);
}
 
Example 11
Source File: GenerateBatch.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    TreeNode node = p.readValueAsTree();
    JsonNode include = (JsonNode) node.get(INCLUDE);
    ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();

    if (include != null) {
        String ref = include.textValue();
        if (ref != null) {
            File includeFile = scanDir != null ? new File(scanDir, ref) : new File(ref);
            if (includeFile.exists()) {
                // load the file into the tree node and continue parsing as normal
                ((ObjectNode) node).remove(INCLUDE);

                TreeNode includeNode;
                try (JsonParser includeParser = codec.getFactory().createParser(includeFile)) {
                    includeNode = includeParser.readValueAsTree();
                }

                ObjectReader reader = codec.readerForUpdating(node);
                TreeNode updated = reader.readValue(includeNode.traverse());
                JsonParser updatedParser = updated.traverse();
                updatedParser.nextToken();
                return super.deserialize(updatedParser, ctx);
            }
        }
    }

    JsonParser newParser = node.traverse();
    newParser.nextToken();
    return super.deserialize(newParser, ctx);
}
 
Example 12
Source File: KubernetesDeserializer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public KubernetesResource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.readValueAsTree();
    if (node.isObject()) {
        return fromObjectNode(jp, node);
    } else if (node.isArray()) {
        return fromArrayNode(jp, node);
    } else {
        return null;
    }
}
 
Example 13
Source File: JSOGRefDeserializer.java    From jsog-jackson with MIT License 5 votes vote down vote up
@Override
public JSOGRef deserialize(JsonParser jp, DeserializationContext ctx) throws IOException, JsonProcessingException {
	JsonNode node = jp.readValueAsTree();
	if (node.isTextual()) {
		return new JSOGRef(node.asText());
	} else {
		return new JSOGRef(node.get(JSOGRef.REF_KEY).asText());
	}
}
 
Example 14
Source File: CreateCardPaymentRequestDeserializer.java    From pay-publicapi with MIT License 5 votes vote down vote up
@Override
public CreateCardPaymentRequest deserialize(JsonParser parser, DeserializationContext context) {
    try {
        JsonNode json = parser.readValueAsTree();
        return parsePaymentRequest(json);
    } catch (IOException e) {
        throw new BadRequestException(aPaymentError(CREATE_PAYMENT_PARSING_ERROR));
    }
}
 
Example 15
Source File: LazyParsable.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
  int start = (int) jp.getCurrentLocation().getCharOffset();

  //TODO: Currently the object is parsed, in few cases when this could be avoided.
  // 1. If getTokenLocation()/getCurrentLocation().getCharOffset() returns -1, the source reference is not a string, but an input
  //  stream, byte array, etc. and the value could be still extracted as a string efficiently.
  // 2.  If getTokenLocation()/getCurrentLocation().getCharOffset() larger than 0, but the location doesn't point to the position of
  // the token, then it is possible to extract the value in some cases. For the rest (e.g. input stream without mark support, etc.)
  // the value must be parsed.
  final Object sourceRef = jp.getCurrentLocation().getSourceRef();
  if (start <= 1 || !(sourceRef instanceof String) || ((String) sourceRef).charAt(start - 1) != '[') {
    // necessary to allow Feature objects which has no type attribute (for backward compatibility)
    final JsonNode node = jp.readValueAsTree();
    for (JsonNode currNode : node) {
      // check the type and set in case of null
      if (currNode instanceof ObjectNode && currNode.get("type") == null) {
        ((ObjectNode) currNode).put("type", FEATURE_TYPE);
      }
    }

    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    return mapper.treeAsTokens(node).readValueAs(FEATURE_LIST);
  }

  jp.skipChildren();
  long end = jp.getCurrentLocation().getCharOffset();

  String json = (String) sourceRef;
  return json.substring(start - 1, (int) end);
}
 
Example 16
Source File: RegistrationDeserializer.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
	JsonNode node = p.readValueAsTree();
	Registration.Builder builder = Registration.builder();

	if (node.hasNonNull("name")) {
		builder.name(node.get("name").asText());
	}
	if (node.hasNonNull("url")) {
		String url = node.get("url").asText();
		builder.healthUrl(url.replaceFirst("/+$", "") + "/health").managementUrl(url);
	}
	else {
		if (node.hasNonNull("healthUrl")) {
			builder.healthUrl(node.get("healthUrl").asText());
		}
		if (node.hasNonNull("managementUrl")) {
			builder.managementUrl(node.get("managementUrl").asText());
		}
		if (node.hasNonNull("serviceUrl")) {
			builder.serviceUrl(node.get("serviceUrl").asText());
		}
	}

	if (node.has("metadata")) {
		Iterator<Map.Entry<String, JsonNode>> it = node.get("metadata").fields();
		while (it.hasNext()) {
			Map.Entry<String, JsonNode> entry = it.next();
			builder.metadata(entry.getKey(), entry.getValue().asText());
		}
	}

	if (node.hasNonNull("source")) {
		builder.source(node.get("source").asText());
	}

	return builder.build();
}
 
Example 17
Source File: StringOrArrayDeserializer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode jsonNode = jsonParser.readValueAsTree();
    if (jsonNode.isArray()) {
        ArrayList<String> a = new ArrayList<>(1);
        Iterator<JsonNode> itr = jsonNode.iterator();
        while (itr.hasNext()) {
            a.add(itr.next().textValue());
        }
        return a.toArray(new String[a.size()]);
    } else {
        return new String[] { jsonNode.textValue() };
    }
}
 
Example 18
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));
      }
    }
 
Example 19
Source File: PlainJsonDocumentDeserializer.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public PlainJsonDocument deserialize(JsonParser jp, DeserializationContext context) throws IOException {
	JsonNode documentNode = jp.readValueAsTree();

	PlainJsonDocument document = new PlainJsonDocument();
	document.setMeta((ObjectNode) documentNode.get("meta"));
	document.setLinks((ObjectNode) documentNode.get("links"));
	document.setJsonapi((ObjectNode) documentNode.get("jsonapi"));

	ArrayNode errors = (ArrayNode) documentNode.get("errors");
	if (errors != null) {
		ObjectReader errorReader = objectMapper.readerFor(ErrorData.class);
		List<ErrorData> errorDataList = new ArrayList<>();
		for (JsonNode error : errors) {
			ErrorData errorData = errorReader.readValue(error);
			errorDataList.add(errorData);
		}
		document.setErrors(errorDataList);
	}

		Map<ResourceIdentifier, Resource> included = new HashMap<>();

	JsonNode data = documentNode.get("data");
	if (data instanceof ArrayNode) {
		ArrayNode arrayNode = (ArrayNode) data;
		List<Resource> resources = new ArrayList<>();
		for (JsonNode element : arrayNode) {
			resources.add(deserializeResource(element, included));
		}
		document.setData(Nullable.of(resources));
	}
	else if (data instanceof NullNode) {
		document.setData(Nullable.nullValue());
	}
	else if (data != null) {
		Resource resource = deserializeResource(data, included);
		document.setData(Nullable.of(resource));
	}
	else {
		document.setData(Nullable.empty());
	}

	if (!included.isEmpty()) {
		document.setIncluded(new ArrayList<>(included.values()));
	}

	return document;
}
 
Example 20
Source File: BlockStateDeserializer.java    From Web-API with MIT License 4 votes vote down vote up
@Override
public BlockState deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonNode root = p.readValueAsTree();
    if (root.path("type").isMissingNode()) {
        throw new IOException("Missing block type");
    }

    String typeStr = root.path("type").isTextual()
            ? root.path("type").asText()
            : root.path("type").path("id").asText();
    Optional<BlockType> optType = Sponge.getRegistry().getType(BlockType.class, typeStr);
    if (!optType.isPresent()) {
        throw new IOException("Invalid block type " + typeStr);
    }
    BlockType type = optType.get();

    BlockState state = type.getDefaultState();
    Collection<BlockTrait<?>> traits = type.getTraits();

    if (!root.path("data").isMissingNode()) {
        Iterator<Map.Entry<String, JsonNode>> it = root.path("data").fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> entry = it.next();

            Optional<BlockTrait<?>> optTrait = traits.stream().filter(t ->
                    t.getName().equalsIgnoreCase(entry.getKey())
            ).findAny();

            if (!optTrait.isPresent())
                throw new IOException("Unknown trait '" + entry.getKey() + "'");

            BlockTrait trait = optTrait.get();
            Object value = null;

            JsonNode nodeValue = entry.getValue();
            if (nodeValue.isBoolean()) {
                value = nodeValue.asBoolean();
            } else if (nodeValue.isInt()) {
                value = nodeValue.asInt();
            } else if (nodeValue.isTextual()) {
                Collection<?> values = trait.getPossibleValues();
                Optional<?> val = values.stream()
                        .filter(v -> v.toString().equalsIgnoreCase(nodeValue.asText()))
                        .findAny();

                if (!val.isPresent()) {
                    String allowedValues = values.stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(", "));
                    throw new IOException("Trait '" + trait.getName() + "' has value '" +
                            nodeValue.asText() + "' but can only have one of: " + allowedValues);
                } else {
                    value = val.get();
                }
            }

            Optional<BlockState> newState = state.withTrait(trait, value);
            if (!newState.isPresent())
                throw new IOException("Could not apply trait '" + trait.getName() + " to block state");

            state = newState.get();
        }
    }

    return state;
}