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:com.spotify.docker.client.messages.AuthConfig.java

private static AuthConfig.Builder parseDockerConfig(final Path configPath, String serverAddress)
        throws IOException {
    checkNotNull(configPath);/*from  w w  w . j  a  va 2  s .  com*/
    final AuthConfig.Builder authBuilder = AuthConfig.builder();
    final JsonNode authJson = extractAuthJson(configPath);

    if (isNullOrEmpty(serverAddress)) {
        final Iterator<String> servers = authJson.fieldNames();
        if (servers.hasNext()) {
            serverAddress = servers.next();
        }
    } else {
        if (!authJson.has(serverAddress)) {
            log.error("Could not find auth config for {}. Returning empty builder", serverAddress);
            return AuthConfig.builder().serverAddress(serverAddress);
        }
    }

    final JsonNode serverAuth = authJson.get(serverAddress);
    if (serverAuth != null && serverAuth.has("auth")) {
        authBuilder.serverAddress(serverAddress);
        final String authString = serverAuth.get("auth").asText();
        final String[] authParams = Base64.decodeAsString(authString).split(":");

        if (authParams.length == 2) {
            authBuilder.username(authParams[0].trim());
            authBuilder.password(authParams[1].trim());
        } else {
            log.warn("Failed to parse auth string for {}", serverAddress);
            return authBuilder;
        }
    } else {
        log.warn("Could not find auth field for {}", serverAddress);
        return authBuilder;
    }

    if (serverAuth.has("email")) {
        authBuilder.email(serverAuth.get("email").asText());
    }

    return authBuilder;
}

From source file:mobile.service.GroupService.java

/**
 * ??//from w  w  w . j a v a2  s . c o  m
 *
 * @param messageId ?Id
 * @return
 */
public static ServiceResult agreeJoinGroupInvite(Long messageId) {
    User me = User.getFromSession(Context.current().session());

    Message message = Message.queryById(messageId);
    if (null == message || message.msgType != MsgType.INVIT_GROUP_MEMBER
            || !Objects.equals(message.consumeOnly, me.id.toString())) {
        return ServiceResult.error("100005", "?messageId = " + messageId);
    }

    User receiverUser = User.findById(NumberUtils.toLong(message.consumeOnly, -1));
    if (null == receiverUser) {
        LOGGER.error("invalid receiverId. message.content = " + message.content);
        return ServiceResult.error("100001", "");
    }

    JsonNode content = Json.parse(message.content);

    long groupId = content.get("groupId").asLong(-1);
    Group group = Group.queryGroupById(groupId);
    if (null == group) {
        LOGGER.error("invalid groupId. message.content = " + message.content);
        return ServiceResult.error("2001", "?");
    }
    List<Long> groupIdList = Arrays.asList(groupId);
    Map<Long, Boolean> checkJoinGroup = models.GroupMember.checkJoinGroup(receiverUser.getId(), groupIdList);
    if (checkJoinGroup.get(groupId) == true) {
        MessageService.handlerMessage(messageId);
        return ServiceResult.error("2003", "??");
    }

    User senderUser = User.findById(NumberUtils.toLong(message.senderOnly, -1));
    if (null == senderUser) {
        LOGGER.error("invalid senderId. message.content = " + message.content);
        return ServiceResult.error("100001", "");
    }

    try {
        ChatService.appendMemberToGroup(groupId, receiverUser.getId());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    MessageService.pushMsgInvitAgree(me, senderUser, group);
    MessageService.handlerMessage(messageId);
    return ServiceResult.success();
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java

/** Builds a V2 bucket out of a V1 source
 * @param src_json/*from   www .  j ava 2s. c  o  m*/
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 * @throws ParseException
 */
protected static DataBucketBean getBucketFromV1Source(final JsonNode src_json)
        throws JsonParseException, JsonMappingException, IOException, ParseException {
    // (think we'll use key instead of _id):
    //final String _id = safeJsonGet(JsonUtils._ID, src_json).asText(); 
    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
    //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 = ((ObjectNode) px_pipeline.get(0))
            .without(Arrays.asList("test_params"));
    final JsonNode data_bucket_tmp = safeJsonGet("data_bucket", px_pipeline_first_el);// (WARNING: mutable, see below)
    final JsonNode scripting = safeJsonGet("scripting", data_bucket_tmp);

    // HANDLE SUBSTITUTION
    final String sub_prefix = Optional.ofNullable(scripting.get("sub_prefix")).map(x -> x.asText())
            .orElse("$$SCRIPT_");
    final String sub_suffix = Optional.ofNullable(scripting.get("sub_suffix")).map(x -> x.asText())
            .orElse("$$");
    final List<UnaryOperator<String>> search_replace = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(scripting.fieldNames(), Spliterator.ORDERED), false)
            .filter(f -> !f.equals("sub_prefix") && !f.equals("sub_suffix")) // (remove non language fields)
            .map(lang -> Tuples._2T(scripting.get(lang), lang))
            // Get (separator regex, entire script, sub prefix)
            .map(scriptobj_lang -> Tuples._3T(safeJsonGet("separator_regex", scriptobj_lang._1()).asText(),
                    safeJsonGet("script", scriptobj_lang._1()).asText(), sub_prefix + scriptobj_lang._2()))
            // Split each "entire script" up into blocks of format (bloc, lang)
            .<Stream<Tuple2<String, String>>>map(regex_script_lang -> Stream.concat(
                    Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3())),
                    regex_script_lang._1().isEmpty()
                            ? Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3()))
                            : Arrays.stream(regex_script_lang._2().split(regex_script_lang._1()))
                                    .<Tuple2<String, String>>map(s -> Tuples._2T(s, regex_script_lang._3()))))
            // Associate a per-lang index with each  script block -> (replacement, string_sub)
            .<Tuple2<String, String>>flatMap(stream -> StreamUtils.zip(stream, Stream.iterate(0, i -> i + 1),
                    (script_lang, i) -> Tuples._2T(
                            script_lang._1().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r"),
                            i == 0 ? script_lang._2() + sub_suffix // (entire thing)
                                    : script_lang._2() + "_" + i + sub_suffix))) //(broken down components)

            .<UnaryOperator<String>>map(t2 -> (String s) -> s.replace(t2._2(), t2._1()))
            //(need to escape "s and newlines)
            .collect(Collectors.toList());

    // Apply the list of transforms to the string
    ((ObjectNode) data_bucket_tmp).remove("scripting"); // (WARNING: mutable)
    final String data_bucket_str = search_replace.stream().reduce(data_bucket_tmp.toString(),
            (acc, s) -> s.apply(acc), (acc1, acc2) -> acc1);

    // Convert back to the bucket JSON
    final JsonNode data_bucket = ((ObjectNode) _mapper.readTree(data_bucket_str))
            .without(Arrays.asList("test_params"));

    final DataBucketBean bucket = BeanTemplateUtils.build(data_bucket, DataBucketBean.class)
            .with(DataBucketBean::_id, getBucketIdFromV1SourceKey(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();

    return bucket;

}

From source file:com.heliosapm.mws.server.net.json.JSONRequest.java

/**
 * Creates a new JSONRequest/*from w w  w.  jav a  2s  .  co  m*/
 * @param channel The channel the request came in on
 * @param jsonContent The json content to build the request from
 * @return a new JSONRequest
 */
public static JSONRequest newJSONRequest(Channel channel, CharSequence jsonContent) {
    if (jsonContent == null || jsonContent.toString().trim().isEmpty())
        throw new IllegalArgumentException("The passed json content was null or empty");
    try {
        JsonNode jsonNode = jsonMapper.readTree(jsonContent.toString().trim());
        return new JSONRequest(channel, jsonNode.get("t").asText(), jsonNode.get("rid").asLong(-1L), -1L,
                jsonNode.get("svc").asText(), jsonNode.get("op").asText(), jsonNode);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse JsonNode from passed string [" + jsonContent + "]", e);
    }
}

From source file:org.dswarm.wikidataimporter.WikibaseAPIClient.java

public static String getToken(final Response loginResponse) {

    try {/*from w ww .jav  a 2 s. c  o  m*/

        final String responseBody = loginResponse.readEntity(String.class);

        if (responseBody == null) {

            LOG.error("cannot extract token - response body is not available");

            return null;
        }

        final ObjectNode json = MAPPER.readValue(responseBody, ObjectNode.class);

        if (json == null) {

            LOG.error("cannot extract token - response JSON is not available");

            return null;
        }

        final JsonNode loginNode = json.get(MEDIAWIKI_API_LOGIN);

        if (loginNode == null) {

            LOG.error("cannot extract token - '{}' node is not available in response JSON '{}'",
                    MEDIAWIKI_API_LOGIN, responseBody);

            return null;
        }

        final JsonNode tokenNode = loginNode.get(MEDIAWIKI_API_TOKEN_IDENTIFIER);

        if (tokenNode == null) {

            LOG.error("cannot extract token - '{}' node is not available in response JSON '{}'",
                    MEDIAWIKI_API_TOKEN_IDENTIFIER, responseBody);

            return null;
        }

        return tokenNode.asText();
    } catch (final Exception e) {

        LOG.error(
                "cannot extract token - an error occurred while trying to extract the token from the response body",
                e);

        return null;
    }
}

From source file:controllers.user.UserSettingApp.java

/**
 * ?//w  w  w  .  j a  v  a2  s  . c  o m
 * 
 * @return
 */
@Transactional(readOnly = false)
public static Result updateMobilePhone() {
    JsonNode json = getJson();

    // ?
    boolean isValidParams = json.hasNonNull("phoneNum") && json.hasNonNull("code");
    if (!isValidParams) {
        return illegalParameters();
    }

    User user = User.getFromSession(session());
    String phoneNum = user.getMaskPhoneNumber();
    ObjectNodeResult result = User.bindMobilePhone(user, phoneNum, json.get("phoneNum").asText(),
            json.get("code").asText(), session());

    return ok(result.getObjectNode());
}

From source file:com.meli.client.controller.AppController.java

private static void doApiCalls(String query, String countryCode) {
        List<Item> items = new ArrayList<Item>();
        Random r = new Random();

        Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq");
        try {/*  w ww . ja  va2  s .co m*/

            FluentStringsMap params = new FluentStringsMap();
            params.add("q", query);

            String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search";
            Response response = meliOb.get(path, params);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response.getResponseBody());
            JsonNode resultNode = rootNode.findPath("results");

            if (resultNode.size() > 0) {
                JsonNode currNode = null;
                JsonNode dupNode = null;
                boolean dupNodeVal = false;

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();

                Item item = null;

                int randomMins;

                String checkDupsUrl = null;

                HttpGet get = null;
                URIBuilder builder = null;
                URI uri = null;

                for (int i = 0; i < resultNode.size(); i++) {
                    currNode = resultNode.get(i);

                    builder = new URIBuilder();
                    builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check")
                            .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText());
                    uri = builder.build();

                    get = new HttpGet(uri);
                    get.addHeader("accept", "application/json");

                    CloseableHttpResponse res = httpClient.execute(get);
                    BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
                    String content = "", line;

                    while ((line = br.readLine()) != null) {
                        content = content + line;
                    }

                    if (!content.isEmpty()) {
                        dupNode = objectMapper.readTree(content);
                        dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText());

                        if (dupNodeVal && !allowDuplicates)
                            continue;

                        item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? 
                                currNode.get("site_id").asText(), currNode.get("title").asText(),
                                currNode.get("permalink").asText(), currNode.get("category_id").asText(),
                                currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText()
                                "", //currNode.get("seller").get("link").asText()
                                "", //currNode.get("seller").get("email").asText()
                                currNode.get("price").asText(), "", //currNode.get("auction_price").asText(),
                                "", //currNode.get("currency_id").asText(),
                                currNode.get("thumbnail").asText());
                        items.add(item);
                    }
                    randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime;
                    Thread.sleep(randomMins);
                }

                if (!items.isEmpty()) {
                    HttpPost post = new HttpPost(apiUrl + "/proxy/add");
                    StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items));

                    post.setEntity(stringEntity);
                    post.setHeader("Content-type", "application/json");

                    CloseableHttpResponse postResponse = httpClient.execute(post);
                    System.out.println("this is the reponse of the final request: "
                            + postResponse.getStatusLine().getStatusCode());
                }
            }

        } catch (MeliException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

From source file:com.baasbox.service.storage.DocumentService.java

public static ODocument update(String collectionName, String rid, JsonNode bodyJson, PartsParser pp)
        throws MissingNodeException, InvalidCollectionException, InvalidModelException, ODatabaseException,
        IllegalArgumentException, DocumentNotFoundException {
    ODocument od = get(rid);/*from ww w  .  j  a v a 2  s .  c  o  m*/
    if (od == null)
        throw new InvalidParameterException(rid + " is not a valid document");
    ObjectMapper mapper = new ObjectMapper();
    StringBuffer q = new StringBuffer("");

    if (!pp.isMultiField() && !pp.isArray()) {
        q.append("update ").append(collectionName).append(" set ").append(pp.treeFields()).append(" = ")
                .append(bodyJson.get("data").toString());

    } else {
        q.append("update ").append(collectionName).append(" merge ");
        String content = od.toJSON();
        ObjectNode json = null;
        try {
            json = (ObjectNode) mapper.readTree(content.toString());
        } catch (Exception e) {
            throw new RuntimeException("Unable to modify inline json");
        }
        JsonTree.write(json, pp, bodyJson.get("data"));
        q.append(json.toString());
    }
    q.append(" where @rid = ").append(rid);
    try {
        DocumentDao.getInstance(collectionName).updateByQuery(q.toString());
    } catch (OSecurityException e) {
        throw e;
    } catch (InvalidCriteriaException e) {
        throw new RuntimeException(e);
    }
    od = get(collectionName, rid);
    return od;
}

From source file:org.dswarm.wikidataimporter.WikibaseAPIClient.java

public static String getEditToken(final Response editTokenResponse) {

    try {//from   w w w .  j a  v  a 2  s.c om

        final String responseBody = editTokenResponse.readEntity(String.class);

        if (responseBody == null) {

            LOG.error("cannot extract edit token - response body is not available");

            return null;
        }

        final ObjectNode json = MAPPER.readValue(responseBody, ObjectNode.class);

        if (json == null) {

            LOG.error("cannot extract edit token - response JSON is not available");

            return null;
        }

        final JsonNode queryNode = json.get(MEDIAWIKI_API_QUERY);

        if (queryNode == null) {

            LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'",
                    MEDIAWIKI_API_QUERY, responseBody);

            return null;
        }

        final JsonNode tokensNode = queryNode.get(MEDIAWIKI_API_TOKENS_IDENTIFIER);

        if (tokensNode == null) {

            LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'",
                    MEDIAWIKI_API_TOKENS_IDENTIFIER, responseBody);

            return null;
        }

        final JsonNode csrfTokenNode = tokensNode.get(MEDIAWIKI_API_CSRFTOKEN_IDENTIFIER);

        if (csrfTokenNode == null) {

            LOG.error("cannot extract edit token - '{}' node is not available in response JSON '{}'",
                    MEDIAWIKI_API_CSRFTOKEN_IDENTIFIER, responseBody);

            return null;
        }

        return csrfTokenNode.asText();
    } catch (final Exception e) {

        LOG.error(
                "cannot extract edit token - an error occurred while trying to extract the edit token from the response body",
                e);

        return null;
    }
}

From source file:com.facebook.presto.kinesis.decoder.json.JsonKinesisRowDecoder.java

private static JsonNode locateNode(JsonNode tree, KinesisColumnHandle columnHandle) {
    String mapping = columnHandle.getMapping();
    checkState(mapping != null, "No mapping for %s", columnHandle.getName());

    JsonNode currentNode = tree;
    for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) {
        String baseName = pathElement;
        int index = -1;
        if (pathElement.contains("[")) {
            String[] splits = pathElement.split("[\\[\\]]");
            if (splits.length == 2) {
                if (splits[1].matches("[0-9]+")) {
                    index = Integer.parseInt(splits[1]);
                }/*from   w  w  w .j a va 2  s.  c  om*/
            }
            baseName = splits[0];
        }

        if (!currentNode.has(baseName)) {
            return MissingNode.getInstance();
        }

        currentNode = currentNode.path(baseName);
        if (index >= 0 && currentNode.isArray()) {
            currentNode = currentNode.get(index);

            // From Jackson docs: If index is less than 0, or equal-or-greater than node.size(), null is returned;
            // no exception is thrown for any index.
            if (currentNode == null) {
                return MissingNode.getInstance();
            } else if (currentNode.isMissingNode() || currentNode.isNull()) {
                return currentNode; // don't continue
            }
        }
    }
    return currentNode;
}