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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#get() . 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: PublishHandler.java    From WAMPlay with MIT License 6 votes vote down vote up
private static Set<String> getEligible(String sessionID, JsonNode message) {
	if (!message.has(4) || message.get(4).isNull()) {
		return null;
	}

	JsonNode eligNode = message.get(4);
	Set<String> eligible = new HashSet<String>();

	if (eligNode.isArray()) {
		// eligible array is specified
		for (JsonNode sessionNode : eligNode) {
			if (sessionNode.isTextual()) {
				eligible.add(sessionNode.asText());
			}
		}
	}

	return eligible;
}
 
Example 2
Source File: Favourites.java    From Kore with Apache License 2.0 6 votes vote down vote up
@Override
public ApiList<FavouriteType.DetailsFavourite> resultFromJson(ObjectNode jsonObject) throws ApiException {
    ListType.LimitsReturned limits = new ListType.LimitsReturned(jsonObject);

    JsonNode resultNode = jsonObject.get(RESULT_NODE);
    ArrayNode items = resultNode.has(LIST_NODE) && !resultNode.get(LIST_NODE).isNull() ?
            (ArrayNode) resultNode.get(LIST_NODE) : null;
    if (items == null) {
        return new ApiList<>(Collections.<FavouriteType.DetailsFavourite>emptyList(), limits);
    }
    ArrayList<FavouriteType.DetailsFavourite> result = new ArrayList<>(items.size());
    for (JsonNode item : items) {
        result.add(new FavouriteType.DetailsFavourite(item));
    }
    return new ApiList<>(result, limits);
}
 
Example 3
Source File: TargetsCommandIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void showOutputsWithJsonForEmptyDefaultOutputs() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "output_paths", tmp);
  workspace.setUp();

  ProcessResult result =
      workspace
          .runBuckCommand("targets", "--show-outputs", "--json", "//:test_multiple_outputs")
          .assertSuccess();
  JsonNode observed =
      ObjectMappers.READER.readTree(ObjectMappers.createParser(result.getStdout()));

  assertTrue(observed.isArray());
  JsonNode targetNode = observed.get(0);

  // Empty outputs should not print output paths
  JsonNode cellPath = targetNode.get("buck.outputPath");
  assertNull(cellPath);
  cellPath = targetNode.get("buck.outputPaths");
  assertNull(cellPath);
}
 
Example 4
Source File: DynamicUrlHandler.java    From ingestion with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a param value into its placeholder
 *
 * @param url          Current REST URL
 * @param currentParam paramMapper specification
 * @param checkpoint   current checkpoint
 * @return
 */
private String replaceParameter(String url, JsonNode currentParam, Map<String, String> checkpoint)
        throws Exception {
    String placeHolder = "${" + currentParam.get("name").asText() + "}";
    if (!url.contains(placeHolder)) {
        return url;
    }

    if (checkpoint != null && checkpoint.containsKey(currentParam.get("name").asText())) {
        url = url.replace(placeHolder, checkpoint.get(currentParam.get("name").asText()));
        url = url.replace("+", "%2B");
        return url;
    }

    if (currentParam.get("default") != null && !currentParam.get("default").asText().trim().equals("")) {
        url = url.replace(placeHolder, currentParam.get("default").asText());
    } else {
        throw new Exception("Can't replace the " + currentParam.get("name") + " parameter");
    }

    return url;
}
 
Example 5
Source File: HandledStatePayloadTest.java    From bugsnag-java with MIT License 6 votes vote down vote up
@Test
public void testUserSpecifiedSerialisation() throws IOException {
    Report report = reportFromHandledState(HandledState.newInstance(
            HandledState.SeverityReasonType.REASON_USER_SPECIFIED, Severity.WARNING));
    JsonNode payload = getJsonPayloadFromReport(report);

    assertEquals("warning", payload.get("severity").asText());
    assertFalse(payload.get("unhandled").booleanValue());

    JsonNode severityReason = payload.get("severityReason");
    assertNotNull(severityReason);
    assertEquals(HandledState.SeverityReasonType.REASON_USER_SPECIFIED
                    .toString(),
            severityReason.get("type").asText());
    assertNull(severityReason.get("attributes"));
}
 
Example 6
Source File: StockToStockWithCompanyInfoMapper.java    From XueQiuSuperSpider with MIT License 6 votes vote down vote up
private void processStock(Stock stock, JsonNode node) {
    String compsname = node.get("compsname").asText();
    String orgtype = node.get("orgtype").asText();
    String founddate = node.get("founddate").asText();
    String bizscope = node.get("bizscope").asText();
    String majorbiz = node.get("majorbiz").asText();
    String region = node.get("region").asText();

    List<Industry> industries = new ArrayList<>();
    JsonNode subNode = node.get("tqCompIndustryList");

    for (JsonNode jsonNode : subNode) {
        String industryName = jsonNode.get("level2name").asText();
        industries.add(industryMap.get(industryName).copy());
    }

    CompanyInfo companyInfo = new CompanyInfo(
            compsname, orgtype, founddate, bizscope, majorbiz, region, industries);

    stock.setCompanyInfo(companyInfo);

}
 
Example 7
Source File: JsonDiff.java    From zjsonpatch with Apache License 2.0 5 votes vote down vote up
private int addRemaining(JsonPointer path, JsonNode target, int pos, int targetIdx, int targetSize) {
    while (targetIdx < targetSize) {
        JsonNode jsonNode = target.get(targetIdx);
        JsonPointer currPath = path.append(pos);
        diffs.add(Diff.generateDiff(Operation.ADD, currPath, jsonNode.deepCopy()));
        pos++;
        targetIdx++;
    }
    return pos;
}
 
Example 8
Source File: OpenstackVtapNetworkWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
private OpenstackVtapNetwork readNetworkConfiguration(InputStream input) {
    try {
        JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
        ObjectNode vtap = (ObjectNode) jsonTree.get(NETWORK);
        return codec(OpenstackVtapNetwork.class).decode(vtap, this);
    } catch (Exception e) {
        log.error(e.toString());
        return null;
    }
}
 
Example 9
Source File: AbstractCommand.java    From mirror with Apache License 2.0 5 votes vote down vote up
protected String text(JsonNode node, String key) {
    JsonNode keyNode = jsonNodeValue(node, key);
    if (keyNode != null) {
        keyNode = keyNode.get(0);
        if (keyNode != null) {
            return StringUtils.trimToNull(keyNode.textValue());
        }
    }
    return null;
}
 
Example 10
Source File: BaseSpringRestTestCase.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void assertResultsPresentInPostDataResponseWithStatusCheck(String url, ObjectNode body, int expectedStatusCode, String... expectedResourceIds) throws IOException {
    int numberOfResultsExpected = 0;
    if (expectedResourceIds != null) {
        numberOfResultsExpected = expectedResourceIds.length;
    }

    // Do the actual call
    HttpPost post = new HttpPost(SERVER_URL_PREFIX + url);
    post.setEntity(new StringEntity(body.toString()));
    CloseableHttpResponse response = executeRequest(post, expectedStatusCode);

    if (expectedStatusCode == HttpStatus.SC_OK) {
        // Check status and size
        JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent());
        JsonNode dataNode = rootNode.get("data");
        assertThat(numberOfResultsExpected).isEqualTo(dataNode.size());

        // Check presence of ID's
        if (expectedResourceIds != null) {
            List<String> toBeFound = new ArrayList<>(Arrays.asList(expectedResourceIds));
            for (JsonNode aDataNode : dataNode) {
                String id = aDataNode.get("id").textValue();
                toBeFound.remove(id);
            }
            assertThat(toBeFound).as("Not all entries have been found in result, missing: " + StringUtils.join(toBeFound, ", ")).isEmpty();
        }
    }

    closeResponse(response);
}
 
Example 11
Source File: XYGraphicsSerializerTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeBigIntXWithNanoPlotType_resultJsonHasStringX() throws IOException {
  //when
  line.setX(
      Arrays.asList(
          new BigInteger("12345678901234567891000"), new BigInteger("12345678901234567891000")));
  line.setPlotType(NanoPlot.class);
  xyGraphicsSerializer.serialize(line, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("x")).isTrue();
  ArrayNode arrayNode = (ArrayNode) actualObj.get("x");
  Assertions.assertThat(arrayNode.get(1).isTextual()).isTrue();
}
 
Example 12
Source File: RxDocumentServiceResponse.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public <T extends Resource> List<T> getQueryResponse(Class<T> c) {
    String responseBody = this.getReponseBodyAsString();
    if (responseBody == null) {
        return new ArrayList<T>();
    }

    JsonNode jobject = fromJson(responseBody);
    String resourceKey = RxDocumentServiceResponse.getResourceKey(c);
    ArrayNode jTokenArray = (ArrayNode) jobject.get(resourceKey);

    // Aggregate queries may return a nested array
    ArrayNode innerArray;
    while (jTokenArray != null && jTokenArray.size() == 1 && (innerArray = toArrayNode(jTokenArray.get(0))) != null) {
        jTokenArray = innerArray;
    }

    List<T> queryResults = new ArrayList<T>();

    if (jTokenArray != null) {
        for (int i = 0; i < jTokenArray.size(); ++i) {
            JsonNode jToken = jTokenArray.get(i);
            // Aggregate on single partition collection may return the aggregated value only
            // In that case it needs to encapsulated in a special document
            String resourceJson = jToken.isNumber() || jToken.isBoolean()
                    ? String.format("{\"%s\": %s}", Constants.Properties.AGGREGATE, jToken.asText())
                            : toJson(jToken);
                    T resource = null;
                    try {
                        resource = c.getConstructor(String.class).newInstance(resourceJson);
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                        throw new IllegalStateException("Failed to instantiate class object.", e);
                    }

                    queryResults.add(resource);
        }
    }

    return queryResults;
}
 
Example 13
Source File: DataMovementServices.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public ForestConfigurationImpl readForestConfig() {
  List<ForestImpl> forests = new ArrayList<>();
  JsonNode results = ((DatabaseClientImpl) client).getServices()
    .getResource(null, "internal/forestinfo", null, null, new JacksonHandle())
    .get();
  for ( JsonNode forestNode : results ) {
    String id = forestNode.get("id").asText();
    String name = forestNode.get("name").asText();
    String database = forestNode.get("database").asText();
    String host = forestNode.get("host").asText();
    String openReplicaHost = null;
    if ( forestNode.get("openReplicaHost") != null ) openReplicaHost = forestNode.get("openReplicaHost").asText();
    String requestHost = null;
    if ( forestNode.get("requestHost") != null ) requestHost = forestNode.get("requestHost").asText();
    String alternateHost = null;
    if ( forestNode.get("alternateHost") != null ) alternateHost = forestNode.get("alternateHost").asText();
    // Since we added the forestinfo end point to populate both alternateHost and requestHost
    // in case we have a requestHost so that we don't break the existing API code, we will make the
    // alternateHost as null if both alternateHost and requestHost is set.
    if ( requestHost != null && alternateHost != null )
      alternateHost = null;
    boolean isUpdateable = "all".equals(forestNode.get("updatesAllowed").asText());
    boolean isDeleteOnly = false; // TODO: get this for real after we start using a REST endpoint
    forests.add(
          new ForestImpl(host, openReplicaHost, requestHost, alternateHost, database, name, id, isUpdateable, isDeleteOnly)
    );
  }

  return new ForestConfigurationImpl(forests.toArray(new ForestImpl[forests.size()]));
}
 
Example 14
Source File: WorkMgr.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Return the JSON-serialized settings for the specified question class for the specified network;
 * or {@code null} if either no custom settings exist for the question or no value is present at
 * the path produced from the sepcified components.
 *
 * @param network The name of the network
 * @param questionClassId The ID of the class of questions whose settings are to be returned
 * @param components The components to traverse from the root of the question settings to reach
 *     the desired section or value
 * @throws IOException if there is an error reading the settings
 */
public @Nullable String getQuestionSettings(
    String network, String questionClassId, List<String> components) throws IOException {
  Optional<NetworkId> networkIdOpt = _idManager.getNetworkId(network);
  checkArgument(networkIdOpt.isPresent(), "Missing network: '%s'", network);
  NetworkId networkId = networkIdOpt.get();
  Optional<QuestionSettingsId> questionSettingsIdOpt =
      _idManager.getQuestionSettingsId(questionClassId, networkId);
  if (!questionSettingsIdOpt.isPresent()) {
    return null;
  }
  QuestionSettingsId questionSettingsId = questionSettingsIdOpt.get();
  String questionSettings;
  questionSettings = _storage.loadQuestionSettings(networkId, questionSettingsId);
  if (questionSettings == null) {
    return null;
  }
  if (components.isEmpty()) {
    return questionSettings;
  }
  JsonNode root = BatfishObjectMapper.mapper().readTree(questionSettings);
  JsonNode current = root;
  for (String component : components) {
    if (!current.has(component)) {
      return null;
    }
    current = current.get(component);
  }
  return BatfishObjectMapper.writeString(current);
}
 
Example 15
Source File: JSONUtil.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
/**
 * Get specific claim from token.
 *
 * @param node parsed JWT token payload
 * @param path name segments where all but last should each point to the next nested object
 * @return Value of the specific claim as String or null if claim not present
 */
public static String getClaimFromJWT(JsonNode node, String... path) {
    for (String p: path) {
        node = node.get(p);
        if (node == null) {
            return null;
        }
    }
    return node.asText();
}
 
Example 16
Source File: AbstractTextDecoder.java    From synapse with Apache License 2.0 5 votes vote down vote up
private static Optional<Key> keyFrom(final JsonNode json) {
    final JsonNode keyNode = json.get(MessageFormat.SYNAPSE_MSG_KEY);
    if (keyNode == null || keyNode.isNull()) {
        return Optional.empty();
    } else if (keyNode.isObject()) {
        final String partitionKey = keyNode.get(MessageFormat.SYNAPSE_MSG_PARTITIONKEY).textValue();
        final String compactionKey = keyNode.get(MessageFormat.SYNAPSE_MSG_COMPACTIONKEY).textValue();
        return Optional.of(Key.of(partitionKey, compactionKey));
    } else {
        final String msg = "Unexpected json node containing " + json + ": ";
        LOG.error(msg);
        throw new IllegalStateException(msg);
    }
}
 
Example 17
Source File: JacksonUtil.java    From litemall with MIT License 5 votes vote down vote up
public static Integer parseInteger(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);
        if (leaf != null)
            return leaf.asInt();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 18
Source File: ClusterBackupControllerTest.java    From cassandra-mesos-deprecated with Apache License 2.0 4 votes vote down vote up
@Test
public void testBackup() throws Exception {
    threeNodeCluster();

    Tuple2<Integer, JsonNode> tup = fetchJson("/cluster/backup/start", true);
    assertEquals(200, tup._1.intValue());
    JsonNode json = tup._2;

    assertTrue(json.has("started"));
    assertTrue(json.get("started").asBoolean());

    // fail for backup

    tup = fetchJson("/cluster/backup/start", true);
    assertEquals(200, tup._1.intValue());
    json = tup._2;

    assertTrue(json.has("started"));
    assertFalse(json.get("started").asBoolean());

    // status

    tup = fetchJson("/cluster/backup/status", false);
    assertEquals(200, tup._1.intValue());
    json = tup._2;
    assertTrue(json.get("running").asBoolean());
    JsonNode status = json.get("backup");
    assertTrue(status.has("type"));
    assertTrue(status.has("started"));
    assertTrue(status.get("started").isNumber());
    assertTrue(status.has("finished"));
    assertTrue(status.get("finished").isNull());
    assertTrue(status.has("aborted"));
    assertFalse(status.get("aborted").asBoolean());
    assertTrue(status.has("remainingNodes"));
    assertTrue(status.get("remainingNodes").isArray());
    assertTrue(status.has("currentNode"));
    assertTrue(status.has("completedNodes"));
    assertTrue(status.get("completedNodes").isArray());
    assertTrue(status.get("backupName").asText(), status.get("backupName").asText().startsWith("backup-"));

    // abort

    tup = fetchJson("/cluster/backup/abort", true);
    assertEquals(200, tup._1.intValue());
    json = tup._2;
    assertTrue(json.get("aborted").asBoolean());

    tup = fetchJson("/cluster/backup/status", false);
    assertEquals(200, tup._1.intValue());
    json = tup._2;
    status = json.get("backup");
    assertTrue(status.has("aborted"));
    assertTrue(status.get("aborted").asBoolean());

    // last

    tup = fetchJson("/cluster/backup/last", false);
    assertEquals(200, tup._1.intValue());
    json = tup._2;
    assertFalse(json.get("present").asBoolean());
    assertTrue(json.get("backup").isNull());


}
 
Example 19
Source File: ReaperServiceImpl.java    From train-ticket-reaper with MIT License 4 votes vote down vote up
@Override
public void monitor() {
    try {
        logger.info("开始进行第 " + counter.getAndIncrement() + " 次检测");

        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json, text/plain");
        headers.put("Accept-Encoding", "gzip, deflate");
        headers.put("Accept-Language", "zh-CN");
        headers.put("Connection", "keep-alive");
        headers.put("Content-Type", "application/json");
        headers.put("DNT", "1");
        headers.put("Host", "api.12306.com");
        headers.put("Origin", "http://www.12306.com");
        headers.put("Referer", "http://www.12306.com/");
        String maskIp = ((int)(Math.random()*200)+50)+"."+((int)(Math.random()*200)+50)+"."+((int)(Math.random()*200)+50)+"."+((int)(Math.random()*200)+50);
        headers.put("X-Real-IP", maskIp);
        headers.put("X-Forwarded-For", maskIp);
        headers.put("User-Agent", HttpClientUtils.pcUserAgentArray[new Random().nextInt(HttpClientUtils.pcUserAgentArray.length)]);

        //获取列车信息
        JsonNode trainInfosNode = getTrainInfosNode(fromStation, toStation, deptDate, justGD, headers, webhookToken);
        if (trainInfosNode == null) {
            logger.error("获取列车信息失败,请查看参数 from-station 、 to-station 、 dept-date 是否有误。或 www.12306.com是否封了IP");
            DingRobotUtils.send(webhookToken, "获取列车信息失败,请查看参数 from-station 、 to-station 、 dept-date 是否有误。或 www.12306.com是否封了IP", true);
            return;
        }

        //获取适合的列车信息(符合配置文件中配置的)
        List<JsonNode> trainNodes = getApplicableTrainInfoNodes(trainInfosNode, seatName, timeRange, webhookToken);
        if (trainNodes == null) {
            logger.error("没有符合要求的班次,请检查 " + timeRange + " 是否有符合要求的列车信息。目标座位为:" + seatName);
            DingRobotUtils.send(webhookToken, "没有符合要求的班次,请检查 " + timeRange + " 是否有符合要求的列车信息。目标座位为:" + seatName, true);
            return;
        }

        for (JsonNode infoNode : trainNodes) {

            if (!isSellTime(infoNode)) {
                continue;
            }

            JsonNode classSeatNode = getClassSeatNode(infoNode, seatName);
            JsonNode seatNum = classSeatNode.get("seatNum");

            if ("0".equals(seatNum.asText())) {
                continue;
            }

            //通过登陆获取accessToken
            String accessToken = getAccessTokenByLogin(account, password, webhookToken);
            if (StringUtils.isEmpty(accessToken)) {
                DingRobotUtils.send(webhookToken, "登陆失败,请检查username和password", true);
                logger.error("登陆失败,请检查username和password");
                continue;
            }

            //构建订单
            JsonNode orderNode = buildOrder(accessToken, passengerName, passportNo, sex, contactMobile, contactName, infoNode);
            if (orderNode == null) {
                continue;
            }

            //占座(会一直刷到出结果,成功则程序退出,失败则return,进行下一次)
            occupy(accessToken, orderNode, infoNode, seatName, headers, webhookToken);

        }
    } catch (Exception e) {
        logger.error("第 " + counter.get() + " 次检测报错", e);
    }
}
 
Example 20
Source File: CommerceUtils.java    From template-compiler with Apache License 2.0 3 votes vote down vote up
public static boolean isMultipleQuantityAllowedForServices(JsonNode websiteSettings) {

    boolean defaultValue = true;
    String fieldName = "multipleQuantityAllowedForServices";

    JsonNode storeSettings = websiteSettings.get("storeSettings");

    if (storeSettings == null || !storeSettings.hasNonNull(fieldName)) {
      return defaultValue;
    }

    return storeSettings.get(fieldName).asBoolean(defaultValue);
  }