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

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

Introduction

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

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.baasbox.service.scripting.ScriptingService.java

public static ODocument resetStore(String name, JsonNode data) throws ScriptException {
    ScriptsDao dao = ScriptsDao.getInstance();
    ODocument script = dao.getByName(name);
    if (script == null)
        throw new ScriptException("Script not found");
    ODocument embedded;//from   w w  w .ja  v a 2  s .  c  o  m
    if (data == null || data.isNull()) {
        embedded = null;
        script.removeField(ScriptsDao.LOCAL_STORAGE);
    } else {
        embedded = new ODocument().fromJSON(data.toString());
        script.field(ScriptsDao.LOCAL_STORAGE, embedded);
    }
    dao.save(script);
    return embedded;
}

From source file:com.redhat.lightblue.query.RValueExpression.java

/**
 * Parses an rvalue from a json node.// w w  w.ja v  a  2  s . c o m
 */
public static RValueExpression fromJson(JsonNode node) {
    if (node instanceof ObjectNode) {
        if (node.size() == 1) {
            JsonNode path = node.get("$valueof");
            if (path != null && path.isValueNode()) {
                return new RValueExpression(new Path(path.asText()));
            }
        } else {
            return new RValueExpression();
        }
    } else if (node.isValueNode()) {
        if (node.asText().equals("$null")) {
            return new RValueExpression(RValueType._null);
        } else {
            return new RValueExpression(Value.fromJson(node));
        }
    }
    throw Error.get(QueryConstants.ERR_INVALID_RVALUE_EXPRESSION, node.toString());
}

From source file:fr.gouv.vitam.mdbes.QueryBench.java

private static String getRequest(JsonNode request, List<TypeField> fields, AtomicLong rank,
        BenchContext bench) {//from ww  w. j  a  v  a  2 s . com
    if (fields != null && !fields.isEmpty()) {
        String finalRequest = request.toString();
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        for (TypeField field : fields) {
            String val = null;
            switch (field.type) {
            case save:
                finalRequest = getFinalRequest(field, "", bench.savedNames, finalRequest);
                break;
            case liste:
                int rlist = rnd.nextInt(field.listeValeurs.length);
                val = field.listeValeurs[rlist];
                finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest);
                break;
            case listeorder:
                long i = rank.getAndIncrement();
                if (i >= field.listeValeurs.length) {
                    i = field.listeValeurs.length - 1;
                }
                val = field.listeValeurs[(int) i];
                finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest);
                break;
            case serie:
                AtomicLong newcpt = rank;
                if (field.idcpt != null) {
                    newcpt = bench.cpts.get(field.idcpt);
                    if (newcpt == null) {
                        newcpt = rank;
                        System.err.println("wrong cpt name: " + field.idcpt);
                    }
                }
                long j = newcpt.getAndIncrement();
                if (field.modulo > 0) {
                    j = j % field.modulo;
                }
                val = (field.prefix != null ? field.prefix : "") + j;
                finalRequest = getFinalRequest(field, val, bench.savedNames, finalRequest);
                break;
            case interval:
                int newval = rnd.nextInt(field.low, field.high + 1);
                finalRequest = getFinalRequest(field, "" + newval, bench.savedNames, finalRequest);
                break;
            default:
                break;
            }
        }
        return finalRequest;
    }
    return null;
}

From source file:com.redhat.lightblue.query.Value.java

/**
 * Creates a value from a json node//from w w w .  j  a v a2s.c  om
 *
 * If the node is decimal, double, or float, create s a BigDecimal value. If
 * the node is BigInteger, creates a BigIngeter value. If the node is a long
 * or int, creates a long or int value. If the node is a boolean, creates a
 * boolean value. Otherwise, creates a string value.
 */
public static Value fromJson(JsonNode node) {
    if (node.isValueNode()) {
        Object v = null;
        if (node.isNumber()) {
            if (node.isBigDecimal() || node.isDouble() || node.isFloat()) {
                v = node.decimalValue();
            } else if (node.isBigInteger()) {
                v = node.bigIntegerValue();
            } else if (node.isLong()) {
                v = node.longValue();
            } else {
                v = node.intValue();
            }
        } else if (node.isBoolean()) {
            v = node.booleanValue();
        } else {
            v = node.textValue();
        }
        return new Value(v);
    } else {
        throw Error.get(QueryConstants.ERR_INVALID_VALUE, node.toString());
    }
}

From source file:controllers.nwbib.Application.java

static Promise<Result> call(final String q, final String person, final String name, final String subject,
        final String id, final String publisher, final String issued, final String medium,
        final String nwbibspatial, final String nwbibsubject, final int from, final int size, String owner,
        String t, String sort, boolean showDetails, String set, String location, String word,
        String corporation, String raw) {
    final WSRequestHolder requestHolder = Lobid.request(q, person, name, subject, id, publisher, issued, medium,
            nwbibspatial, nwbibsubject, from, size, owner, t, sort, showDetails, set, location, word,
            corporation, raw);//from w  ww.  ja v a2  s  .com
    return requestHolder.get().map((WSResponse response) -> {
        Long hits = 0L;
        String s = "{}";
        if (response.getStatus() == Http.Status.OK) {
            JsonNode json = response.asJson();
            hits = Lobid.getTotalResults(json);
            s = json.toString();
            if (id.isEmpty()) {
                List<JsonNode> ids = json.findValues("hbzId");
                uncache(ids.stream().map(j -> j.asText()).collect(Collectors.toList()));
                Cache.set(session("uuid") + "-lastSearch", ids.toString(), ONE_DAY);
            }
        } else {
            Logger.warn("{}: {} ({}, {})", response.getStatus(), response.getStatusText(),
                    requestHolder.getUrl(), requestHolder.getQueryParameters());
        }
        if (showDetails) {
            String json = "";
            JsonNode nodes = Json.parse(s);
            if (nodes.isArray() && nodes.size() == 2) { // first: metadata
                json = nodes.get(1).toString();
            } else {
                Logger.warn("No suitable data to show details for: {}", nodes);
            }
            return ok(details.render(CONFIG, json, id));
        }
        return ok(search.render(s, q, person, name, subject, id, publisher, issued, medium, nwbibspatial,
                nwbibsubject, from, size, hits, owner, t, sort, set, location, word, corporation, raw));
    });
}

From source file:controllers.nwbib.Application.java

/**
 * @param t The register type ("Raumsystematik" or "Sachsystematik")
 * @return The alphabetical register for the given classification type
 *///from www  .j  a  v  a  2s.c om
public static Result register(final String t) {
    Result cachedResult = (Result) Cache.get("register." + t);
    if (cachedResult != null)
        return cachedResult;
    Result result = null;
    if (t.isEmpty()) {
        result = ok(register.render());
    } else {
        SearchResponse response = Classification.dataFor(t);
        if (response == null) {
            Logger.error("Failed to get data for register type: " + t);
            flashError();
            return internalServerError(browse_register.render(null, t, ""));
        }
        JsonNode sorted = Classification.sorted(response);
        String placeholder = "Register zur " + t + " filtern";
        result = ok(browse_register.render(sorted.toString(), t, placeholder));
    }
    Cache.set("result." + t, result, ONE_DAY);
    return result;
}

From source file:org.lenskit.data.dao.file.TextEntitySource.java

private static TypedName<?> parseAttribute(EntityDefaults entityDefaults, JsonNode col) {
    if (col.isNull() || col.isMissingNode()) {
        return null;
    } else if (col.isObject()) {
        String name = col.get("name").asText();
        String type = col.get("type").asText();
        return TypedName.create(name, type);
    } else if (col.isTextual()) {
        TypedName<?> attr = entityDefaults.getAttributeDefaults(col.asText());
        if (attr == null) {
            attr = TypedName.create(col.asText(), col.asText().equals("id") ? Long.class : String.class);
        }//  w  w w.ja  v a 2 s  . com
        return attr;
    } else {
        throw new IllegalArgumentException("invalid attribute specification: " + col.toString());
    }
}

From source file:com.baasbox.controllers.Push.java

public static Result sendUsers() throws Exception {
    boolean verbose = false;
    try {//from  ww w  .  jav  a 2 s .  c  o m

        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method Start");
        PushLogger pushLogger = PushLogger.getInstance().init();
        if (UserService.isAnAdmin(DbHelper.currentUsername())) {
            pushLogger.enable();
        } else {
            pushLogger.disable();
        }
        if (request().getQueryString("verbose") != null
                && request().getQueryString("verbose").equalsIgnoreCase("true"))
            verbose = true;

        Http.RequestBody body = request().body();
        JsonNode bodyJson = body.asJson(); //{"message":"Text"}
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("send bodyJson: " + bodyJson);
        if (bodyJson == null)
            return status(CustomHttpCode.JSON_PAYLOAD_NULL.getBbCode(),
                    CustomHttpCode.JSON_PAYLOAD_NULL.getDescription());
        pushLogger.addMessage("Payload received: %s", bodyJson.toString());
        JsonNode messageNode = bodyJson.findValue("message");
        pushLogger.addMessage("Payload message received: %s",
                messageNode == null ? "null" : messageNode.asText());
        if (messageNode == null)
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());
        if (!messageNode.isTextual())
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());

        String message = messageNode.asText();

        JsonNode usernamesNodes = bodyJson.get("users");
        pushLogger.addMessage("users: %s", usernamesNodes == null ? "null" : usernamesNodes.toString());

        List<String> usernames = new ArrayList<String>();

        if (!(usernamesNodes == null)) {

            if (!(usernamesNodes.isArray()))
                return status(CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getDescription());

            for (JsonNode usernamesNode : usernamesNodes) {
                usernames.add(usernamesNode.asText());
            }

            HashSet<String> hs = new HashSet<String>();
            hs.addAll(usernames);
            usernames.clear();
            usernames.addAll(hs);
            pushLogger.addMessage("Users extracted: %s", Joiner.on(",").join(usernames));
        } else {
            return status(CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getBbCode(),
                    CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getDescription());
        }

        JsonNode pushProfilesNodes = bodyJson.get("profiles");
        pushLogger.addMessage("profiles: %s",
                pushProfilesNodes == null ? "null" : pushProfilesNodes.toString());

        List<Integer> pushProfiles = new ArrayList<Integer>();
        if (!(pushProfilesNodes == null)) {
            if (!(pushProfilesNodes.isArray()))
                return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
            for (JsonNode pushProfileNode : pushProfilesNodes) {
                if (pushProfileNode.isTextual())
                    return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                            CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
                pushProfiles.add(pushProfileNode.asInt());
            }

            HashSet<Integer> hs = new HashSet<Integer>();
            hs.addAll(pushProfiles);
            pushProfiles.clear();
            pushProfiles.addAll(hs);
        } else {
            pushProfiles.add(1);
        }
        pushLogger.addMessage("Profiles computed: %s", Joiner.on(",").join(pushProfiles));

        boolean[] withError = new boolean[6];
        PushService ps = new PushService();
        Result toRet = null;
        try {
            boolean isValid = (ps.validate(pushProfiles));
            pushLogger.addMessage("Profiles validation: %s", isValid);
            if (isValid)
                withError = ps.send(message, usernames, pushProfiles, bodyJson, withError);
            pushLogger.addMessage("Service result: %s", Booleans.join(", ", withError));
        } catch (UserNotFoundException e) {
            return notFound("Username not found");
        } catch (SqlInjectionException e) {
            return badRequest("The supplied name appears invalid (Sql Injection Attack detected)");
        } catch (PushNotInitializedException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONFIG_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONFIG_INVALID.getDescription());
        } catch (PushProfileDisabledException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_DISABLED.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_DISABLED.getDescription());
        } catch (PushProfileInvalidException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
        } catch (PushInvalidApiKeyException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_APIKEY.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_APIKEY.getDescription());
        } catch (UnknownHostException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_HOST_UNREACHABLE.getBbCode(),
                    CustomHttpCode.PUSH_HOST_UNREACHABLE.getDescription());
        } catch (InvalidRequestException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_REQUEST.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_REQUEST.getDescription());
        } catch (IOException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return badRequest(ExceptionUtils.getMessage(e));
        } catch (PushSoundKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getDescription());
        } catch (PushBadgeFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getDescription());
        } catch (PushActionLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedArgumentsFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushCollapseKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getDescription());
        } catch (PushTimeToLiveFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getDescription());
        } catch (PushContentAvailableFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getDescription());
        } catch (PushCategoryFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getDescription());
        }
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method End");

        for (int i = 0; i < withError.length; i++) {
            if (withError[i] == true)
                return status(CustomHttpCode.PUSH_SENT_WITH_ERROR.getBbCode(),
                        CustomHttpCode.PUSH_SENT_WITH_ERROR.getDescription());
        }
        PushLogger.getInstance().messages();
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        } else {
            return ok("Push Notification(s) has been sent");
        }
    } finally {
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        }
        BaasBoxLogger.debug("Push execution flow:\n{}", PushLogger.getInstance().toString());
    }
}

From source file:com.smartsheet.tin.filters.pkpublish.TransactionFilter.java

static public TransactionFilter newFromJson(JsonNode node) throws JsonFilterException, JsonProcessingException {
    confirmNodeType(node, JsonNodeType.OBJECT, "TransactionFilter", logger);

    TransactionFilter tf = new TransactionFilter();
    tf.setName(fetchChildString(node, "name", false));
    tf.setFilterMatchRule(fetchChildString(node, "filter_match_rule", false));
    tf.setRowMatchRule(fetchChildString(node, "row_match_rule", false));

    JsonNode row_filters_jn = fetchChildByName(node, "row_filters", "array");
    for (JsonNode row_filter_jn : row_filters_jn) {
        confirmNodeType(row_filter_jn, JsonNodeType.OBJECT, "row_filter", logger);
        RowFilter rf = RowFilter.newFromJson(row_filter_jn);
        tf.row_filters.add(rf);/*from  ww  w  . j av a  2s  . co m*/
    }

    JsonNode actions_jn = null;
    try {
        actions_jn = fetchChildByName(node, "actions", "array");
    } catch (JsonFilterChildNotFound e) {
        // Do nothing.
    }
    if (actions_jn != null) {
        for (JsonNode action_jn : actions_jn) {
            confirmNodeType(action_jn, JsonNodeType.OBJECT, "action", logger);
            String action_type = fetchChildString(action_jn, "type", true);
            if (action_type.equals("publish")) {
                PublishAction pa = PublishAction.newFromJson(action_jn);
                tf.setPublish(true);
                tf.setRoutingKey(pa.getRoutingKey());
                tf.setMessage(pa.getMessage());
                tf.actions.add(pa);
            } else {
                String err = String.format("Unknown action type: '%s', " + "in node: '%s'", action_type,
                        action_jn.toString());
                logger.error(err);
                throw new JsonFilterException(err);
            }
        }
    }
    return tf;
}

From source file:org.wisdom.test.http.RequestBodyEntity.java

/**
 * Sets the actual body content.// w  ww .ja v  a 2  s.c o m
 *
 * @param body the content as JSON
 * @return the current {@link org.wisdom.test.http.RequestBodyEntity}
 */
public RequestBodyEntity body(JsonNode body) {
    this.body = body.toString();
    return this;
}