Example usage for com.fasterxml.jackson.databind JsonNode get

List of usage examples for com.fasterxml.jackson.databind JsonNode get

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode get.

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:org.jetbrains.webdemo.examples.ExamplesLoader.java

private static ExamplesFolder loadFolder(String path, String url, List<ObjectNode> parentCommonFiles,
        ExamplesFolder parentFolder) {//from ww w . ja va2  s  .  c  o m
    File manifestFile = new File(path + File.separator + "manifest.json");
    try (BufferedInputStream reader = new BufferedInputStream(new FileInputStream(manifestFile))) {
        ObjectNode manifest = (ObjectNode) JsonUtils.getObjectMapper().readTree(reader);
        String name = new File(path).getName();
        List<ObjectNode> commonFiles = new ArrayList<>();
        commonFiles.addAll(parentCommonFiles);
        boolean taskFolder = manifest.has("taskFolder") ? manifest.get("taskFolder").asBoolean() : false;

        List<LevelInfo> levels = null;
        if (manifest.has("levels")) {
            levels = new ArrayList<>();
            for (JsonNode level : manifest.get("levels")) {
                levels.add(new LevelInfo(level.get("projectsNeeded").asInt(), level.get("color").asText()));
            }
        }

        if (parentFolder != null && parentFolder.isTaskFolder())
            taskFolder = true;
        ExamplesFolder folder = new ExamplesFolder(name, url, taskFolder, levels);
        if (manifest.has("files")) {
            for (JsonNode node : manifest.get("files")) {
                ObjectNode fileManifest = (ObjectNode) node;
                fileManifest.put("path", path + File.separator + fileManifest.get("filename").asText());
                commonFiles.add(fileManifest);
            }
        }

        if (manifest.has("folders")) {
            for (JsonNode node : manifest.get("folders")) {
                String folderName = node.textValue();
                folder.addChildFolder(loadFolder(path + File.separator + folderName, url + folderName + "/",
                        commonFiles, folder));
            }
        }

        if (manifest.has("examples")) {
            for (JsonNode node : manifest.get("examples")) {
                String projectName = node.textValue();
                String projectPath = path + File.separator + projectName;
                folder.addExample(loadExample(projectPath, url,
                        ApplicationSettings.LOAD_TEST_VERSION_OF_EXAMPLES, commonFiles));
            }
        }

        return folder;
    } catch (IOException e) {
        System.err.println("Can't load folder: " + e.toString());
        return null;
    }
}

From source file:com.github.sarxos.xchange.impl.FetchOpenExchangeImpl.java

private static Collection<ExchangeRate> read(String json, String to, Collection<String> from)
        throws JsonProcessingException, IOException {

    // example JSON

    // {/*w  ww.ja va 2s .  com*/
    // "disclaimer": "...",
    // "license": "...",
    // "timestamp": 1427716861,
    // "base": "USD",
    // "rates": {
    // "AED": 3.67305,
    // "AFN": 57.780167,
    // "ALL": 129.4859,
    // "AMD": 471.586001,
    // "ANG": 1.78948,
    // "AOA": 107.97125,
    // ... etc for more symbols

    LOG.trace("Reading JSON tree: {}", json);

    JsonNode root = MAPPER.readTree(json);
    if (root == null) {
        throw new IOException("Invalid JSON received: " + json);
    }

    JsonNode rates = root.get("rates");
    if (rates == null) {
        throw new IOException("No rate element has been found in received JSON: " + json);
    }

    Iterator<Entry<String, JsonNode>> entries = rates.fields();
    Map<String, BigDecimal> currencies = new HashMap<>();

    while (entries.hasNext()) {

        Entry<String, JsonNode> entry = entries.next();
        String symbol = entry.getKey();
        String value = entry.getValue().asText();

        currencies.put(symbol, new BigDecimal(value));
    }

    BigDecimal base = currencies.get(to);
    Set<ExchangeRate> exchangerates = new HashSet<>();

    for (Entry<String, BigDecimal> entry : currencies.entrySet()) {

        String symbol = entry.getKey();

        if (!from.contains(symbol)) {
            continue;
        }

        BigDecimal rate = entry.getValue();
        BigDecimal newrate = rate.divide(base, 8, RoundingMode.HALF_EVEN);

        exchangerates.add(new ExchangeRate(to + symbol, newrate.toString()));
    }

    return exchangerates;
}

From source file:io.coala.eve3.EveUtil.java

/** */
@SafeVarargs//from w  w  w .  j a  va 2s.c o m
public static final <T extends Agent> T valueOf(final String id, final Class<T> agentType,
        final Map.Entry<String, ? extends JsonNode>... parameters) {
    @SuppressWarnings("unchecked")
    final EveAgentConfig cfg = ConfigFactory.create(EveAgentConfig.class, EveAgentConfig.DEFAULT_VALUES,
            map(entry(EveAgentConfig.AGENT_CLASS_KEY, agentType.getName()),
                    entry(EveAgentConfig.AGENT_ID_KEY, id), entry(EveAgentConfig.AGENT_ID_KEY, id)));

    final InputStream is = cfg.agentConfigStream();
    if (is != null) {
        final Config config = YamlReader.load(is).expand();
        try {
            is.close();
        } catch (final IOException ignore) {
            // empty
        }

        for (final JsonNode agent : (ArrayNode) config.get("agents")) {
            final JsonNode idNode = agent.get("id");
            if (idNode != null && !idNode.asText().equals(id))
                continue;

            LOG.info("Creating agent " + id + " from config at " + cfg.agentConfigUri());
            return valueOf(new AgentConfig((ObjectNode) agent), agentType, parameters);
        }
    }
    LOG.info("No config for agent " + id + " found at: " + cfg.agentConfigUri() + ". Using default config");
    return valueOf(cfg.agentConfig(), agentType, parameters);
}

From source file:com.nirmata.workflow.details.JsonSerializer.java

public static RunnableTaskDag getRunnableTaskDag(JsonNode node) {
    List<TaskId> children = Lists.newArrayList();
    JsonNode childrenNode = node.get("dependencies");
    if ((childrenNode != null) && (childrenNode.size() > 0)) {
        childrenNode.forEach(n -> children.add(new TaskId(n.asText())));
    }//from w  w  w.ja v a  2  s  .co  m

    return new RunnableTaskDag(new TaskId(node.get("taskId").asText()), children);
}

From source file:org.glowroot.tests.WebDriverIT.java

private static String getVersion(String content) throws IOException {
    JsonNode responseNode = new ObjectMapper().readTree(content);
    JsonNode versionNode = responseNode.get("version");
    if (versionNode == null) {
        return responseNode.get("config").get("version").asText();
    }/*from   www  . ja  v  a 2  s .c o m*/
    return versionNode.asText();
}

From source file:automenta.knowtention.Core.java

/** adapter for JSONPatch+ */
static JsonPatch getPatch(ArrayNode patch) throws IOException {

    //System.out.println("min: " + patch.toString());

    /*/*from w ww. ja v a2s.  c om*/
            
    JSONPatch+
            
    [ [ <op>, <param1>[, <param2> ], .... ]
            
    + add
    - remove
    * copy
    / move
    = replace
    ? test
            
    [
      { "op": "test", "path": "/a/b/c", "value": "foo" },
      { "op": "remove", "path": "/a/b/c" },
      { "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
      { "op": "replace", "path": "/a/b/c", "value": 42 },
      { "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
      { "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
    ]
    */

    int i = 0;
    for (JsonNode k : patch) {
        JsonNode nextOp = k;
        ObjectNode m = null;
        if (k.isArray()) {
            String op = k.get(0).textValue();
            switch (op.charAt(0)) {
            case '+':
                m = new ObjectNode(newJson);
                m.put("op", "add");
                m.put("path", k.get(1));
                m.put("value", k.get(2));
                break;
            case '-':
                m = new ObjectNode(newJson);
                m.put("op", "remove");
                m.put("path", k.get(1));
                break;
            case '*':
                m = new ObjectNode(newJson);
                m.put("op", "copy");
                m.put("from", k.get(1));
                m.put("path", k.get(2));
                break;
            case '/':
                m = new ObjectNode(newJson);
                m.put("op", "move");
                m.put("from", k.get(1));
                m.put("path", k.get(2));
                break;
            case '?':
                m = new ObjectNode(newJson);
                m.put("op", "test");
                m.put("path", k.get(1));
                m.put("value", k.get(2));
                break;
            case '=':
                m = new ObjectNode(newJson);
                m.put("op", "replace");
                m.put("path", k.get(1));
                m.put("value", k.get(2));
                break;
            }
        }
        if (m != null)
            patch.set(i++, m);
    }

    //System.out.println("standard: " + patch.toString());

    return JsonPatch.fromJson(patch);
}

From source file:com.ikanow.aleph2.data_import_manager.harvest.modules.LocalHarvestTestModule.java

private static DataBucketBean createBucketFromSource(JsonNode src_json) throws Exception {

    @SuppressWarnings("unused")
    final String _id = safeJsonGet(JsonUtils._ID, src_json).asText(); // (think we'll use key instead of _id?)
    final String key = safeJsonGet("key", src_json).asText();
    final String created = safeJsonGet("created", src_json).asText();
    final String modified = safeJsonGet("modified", src_json).asText();
    final String title = safeJsonGet("title", src_json).asText();
    final String description = safeJsonGet("description", src_json).asText();
    final String owner_id = safeJsonGet("ownerId", src_json).asText();

    final JsonNode tags = safeJsonGet("tags", src_json); // collection of strings
    //TODO (ALEPH-19): need to convert the DB authentication across to the Aleph2 format 
    @SuppressWarnings("unused")
    final JsonNode comm_ids = safeJsonGet("communityIds", src_json); // collection of strings
    final JsonNode px_pipeline = safeJsonGet("processingPipeline", src_json); // collection of JSON objects, first one should have data_bucket
    final JsonNode px_pipeline_first_el = px_pipeline.get(0);
    final JsonNode data_bucket = safeJsonGet("data_bucket", px_pipeline_first_el);

    final DataBucketBean bucket = BeanTemplateUtils.build(data_bucket, DataBucketBean.class)
            .with(DataBucketBean::_id, key).with(DataBucketBean::created, parseJavaDate(created))
            .with(DataBucketBean::modified, parseJavaDate(modified)).with(DataBucketBean::display_name, title)
            .with(DataBucketBean::description, description).with(DataBucketBean::owner_id, owner_id)
            .with(DataBucketBean::tags, StreamSupport.stream(tags.spliterator(), false).map(jt -> jt.asText())
                    .collect(Collectors.toSet()))
            .done().get();/* w  ww . j  av  a 2  s  .c o m*/

    return bucket;
}

From source file:controllers.Features.java

@BodyParser.Of(BodyParser.Json.class)
private static Promise<Result> addTarget(String name, JsonNode json) {
    ObjectNode feature = Json.newObject();
    feature.put("name", name);
    feature.put("type", json.get("type").asText());
    ObjectNode target = Json.newObject();
    target.put("name", json.get("target").asText());
    Promise<Boolean> connected = Feature.nodes.connect(feature, target);
    return connected.map(new Function<Boolean, Result>() {
        ObjectNode result = Json.newObject();

        public Result apply(Boolean connected) {
            if (connected) {
                result.put("message", "Target successfully added.");
                return ok(result);
            }//w  w w  .j  a  v  a 2 s. c om
            result.put("message", "Target not added.");
            return badRequest(result);
        }
    });
}

From source file:com.reprezen.swagedit.schema.JsonType.java

public static JsonType valueOf(JsonNode node) {
    if (node == null) {
        return JsonType.UNDEFINED;
    } else if (node.has("oneOf")) {
        return JsonType.ONE_OF;
    } else if (node.has("enum")) {
        return JsonType.ENUM;
    } else if (node.has("type")) {
        String type = node.has("type") ? node.get("type").asText() : null;

        if (type != null) {
            for (JsonType jsonType : JsonType.values()) {
                if (type.equals(jsonType.getValue())) {
                    return jsonType;
                }//w  ww.j  ava 2  s.  c o m
            }
        }
    } else if (node.has("properties")) {
        return JsonType.OBJECT;
    } else if (node.has("anyOf")) {
        return JsonType.ANY_OF;
    } else if (node.has("allOf")) {
        return JsonType.ALL_OF;
    }

    return JsonType.UNDEFINED;
}

From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

@NotNull
private static Object handleIndex(JsonNode n, ObjectMapper mapper, List<List<?>> values, List<String> columns,
        List<String> classes) throws IOException {
    List<String> indexName = (List<String>) mapper.readValue(n.get(INDEX_NAME).toString(), List.class);
    boolean standardIndex = indexName.size() == 1 && indexName.get(0).equals(INDEX);
    if (standardIndex) {
        columns.remove(0);//from ww w  .j  av a2  s  .com
        classes.remove(0);
        for (List<?> v : values) {
            v.remove(0);
        }
    } else {
        columns.set(0, join(", ", indexName.stream().map(TableDisplayDeSerializer::convertNullToIndexName)
                .collect(Collectors.toList())));
    }
    TableDisplay td = new TableDisplay(values, columns, classes);
    if (!standardIndex) {
        td.setHasIndex("true");
    }
    return td;
}