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.googlecode.jsonrpc4j.JsonRpcServer.java

/**
 * Finds the {@link Method} from the supplied {@link Set} that
 * best matches the rest of the arguments supplied and returns
 * it as a {@link MethodAndArgs} class.//from   ww  w .ja v  a2s  .c o  m
 *
 * @param methods the {@link Method}s
 * @param paramsNode the {@link JsonNode} passed as the parameters
 * @return the {@link MethodAndArgs}
 */
private MethodAndArgs findBestMethodByParamsNode(Set<Method> methods, JsonNode paramsNode) {

    // no parameters
    if (paramsNode == null || paramsNode.isNull()) {
        return findBestMethodUsingParamIndexes(methods, 0, null);

        // array parameters
    } else if (paramsNode.isArray()) {
        return findBestMethodUsingParamIndexes(methods, paramsNode.size(), ArrayNode.class.cast(paramsNode));

        // named parameters
    } else if (paramsNode.isObject()) {
        Set<String> fieldNames = new HashSet<String>();
        Iterator<String> itr = paramsNode.fieldNames();
        while (itr.hasNext()) {
            fieldNames.add(itr.next());
        }
        return findBestMethodUsingParamNames(methods, fieldNames, ObjectNode.class.cast(paramsNode));

    }

    // unknown params node type
    throw new IllegalArgumentException("Unknown params node type: " + paramsNode.toString());
}

From source file:com.servioticy.api.commons.data.SO.java

/** Return the subscriptions in output format
 *
 * @param streamId/* www . j  a v a2s  .  c  o  m*/
 * @return subscriptions in output format
 */
public String responseSubscriptions(String streamId, boolean externalOnly) {

    JsonNode stream = getStream(streamId);

    // Check if exist this streamId in the Service Object
    if (stream == null)
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST,
                "There is no Stream: " + streamId + " in the Service Object");

    // Get the Subscriptions
    List<String> IDs = externalOnly ? SearchEngine.getExternalSubscriptionsByStream(soId, streamId)
            : SearchEngine.getAllSubscriptionsByStream(soId, streamId);

    ArrayList<JsonNode> subsArray = new ArrayList<JsonNode>();

    JsonNode root = mapper.createObjectNode();
    if (root == null) {
        LOG.error("Could not create JSON mapper...");
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                "Could not create JSON mapper...");
    }
    try {
        for (String id : IDs) {
            Subscription tmp = CouchBase.getSubscription(id);
            if (tmp != null)
                subsArray.add(mapper.readTree(CouchBase.getSubscription(id).getString()));
            else
                LOG.error("Subscription id: " + id
                        + ", reported by search engine but not found in CouchBase. Skipping...");
        }
        ((ObjectNode) root).put("subscriptions", mapper.readTree(mapper.writeValueAsString(subsArray)));
    } catch (JsonProcessingException e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST,
                "Error parsing subscriptions array");
    } catch (IOException e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, "Error in subscriptions array");
    } catch (Exception e) {
        LOG.error("Error:", e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return root.toString();

    // [TODO] No well formated - To check //
    // use mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data)
    //  Map<String, Object> data = new LinkedHashMap<String, Object>();
    //    Map<String, Object> map = new HashMap<String, Object>();
    //    List<Object> list = new ArrayList<Object>();
    //    while (subs.hasNext()) {
    //      subscription = cb.getSO(user_id, subs.next().asText());
    //      list.add(subscription.getString());
    //    }
    //    map.put("subscriptions", list);
    //
    //    try {
    //      return mapper.writeValueAsString(map.toString());
    //    } catch (JsonProcessingException e) {
    //      e.printStackTrace();
    //    }
    //
    //    return null;
    ////    return map.toString();
}

From source file:core.AbstractTest.java

private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) {
    Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: "
            + mParameters + "\nPayload: " + payload + "\n");
    HttpURLConnection conn = null;
    BufferedReader br = null;/*from   w ww  . j  a va 2  s.  c o m*/
    int nRet = 0;
    boolean fIsMultipart = false;

    try {
        setStatusCode(-1);
        setResponse(null);
        conn = getHttpConnection(sUrl, sMethod);
        if (mHeaders.size() > 0) {
            Set<String> keys = mHeaders.keySet();
            for (String sKey : keys) {
                conn.addRequestProperty(sKey, mHeaders.get(sKey));
                if (sKey.equals(HTTP.CONTENT_TYPE)) {
                    if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) {
                        fIsMultipart = true;
                    }
                }
            }
        }

        if (payload != null || mParameters != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            try {
                if (payload != null) {
                    //conn.setRequestProperty("Content-Length", "" + node.toString().length());
                    out.writeBytes(payload.toString());
                }

                if (mParameters != null) {
                    Set<String> sKeys = mParameters.keySet();

                    if (fIsMultipart) {
                        out.writeBytes("--" + BOUNDARY + "\r\n");
                    }

                    for (String sKey : sKeys) {
                        if (fIsMultipart) {
                            out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n");
                            out.writeBytes(mParameters.get(sKey));
                            out.writeBytes("\r\n");
                            out.writeBytes("--" + BOUNDARY + "--\r\n");
                        } else {
                            out.writeBytes(URLEncoder.encode(sKey, "UTF-8"));
                            out.writeBytes("=");
                            out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8"));
                            out.writeBytes("&");
                        }
                    }

                    if (fIsMultipart) {
                        if (nvpFile != null) {
                            File f = Play.application().getFile(nvpFile.getName());
                            if (f == null) {
                                assertFail("Cannot find file <" + nvpFile.getName() + ">");
                            }
                            FileBody fb = new FileBody(f);
                            out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE
                                    + "\";filename=\"" + fb.getFilename() + "\"\r\n");
                            out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n");
                            out.write(getResource(nvpFile.getName()));
                        }
                        out.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
                    }
                }
            } catch (Exception ex) {
                assertFail("Send request: " + ex.getMessage());
            } finally {
                try {
                    out.flush();
                } catch (Exception ex) {
                }
                try {
                    out.close();
                } catch (Exception ex) {
                }
            }
        }

        nRet = conn.getResponseCode();
        setStatusCode(nRet);
        if (nRet / 100 != 2) {
            if (conn.getErrorStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
        } else {
            if (conn.getInputStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
        }

        if (br != null) {
            String temp = null;
            StringBuilder sb = new StringBuilder(1024);
            while ((temp = br.readLine()) != null) {
                sb.append(temp).append("\n");
            }
            setResponse(sb.toString().trim());
        }
        Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n");
    } catch (Exception ex) {
        assertFail("httpRequest: " + ex.getMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception ex) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return nRet;
}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

@Override
public Validation<BasicMessageBean, JsonNode> sendObjectToStreamingPipeline(
        final Optional<DataBucketBean> bucket, final AnalyticThreadJobBean job,
        final Either<JsonNode, Map<String, Object>> object, final Optional<AnnotationBean> annotations) {
    if (annotations.isPresent()) {
        throw new RuntimeException(ErrorUtils.get(ErrorUtils.NOT_YET_IMPLEMENTED, "annotations"));
    }/*from w  ww .  j  ava2 s. c o m*/
    final JsonNode obj_json = object.either(__ -> __,
            map -> (JsonNode) _mapper.convertValue(map, JsonNode.class));

    return this.getOutputTopic(bucket, job).<Validation<BasicMessageBean, JsonNode>>map(topic -> {
        if (_distributed_services.doesTopicExist(topic)) {
            // (ie someone is listening in on our output data, so duplicate it for their benefit)
            _distributed_services.produce(topic, obj_json.toString());
            return Validation.success(obj_json);
        } else {
            return Validation.fail(ErrorUtils.buildSuccessMessage(this.getClass().getSimpleName(),
                    "sendObjectToStreamingPipeline", "Bucket:job {0}:{1} topic {2} has no listeners",
                    bucket.map(b -> b.full_name()).orElse("(unknown)"), job.name(), topic));
        }
    }).orElseGet(() -> {
        return Validation.fail(ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(),
                "sendObjectToStreamingPipeline", "Bucket:job {0}:{1} has no output topic",
                bucket.map(b -> b.full_name()).orElse("(unknown)"), job.name()));
    });
}

From source file:de.jlo.talendcomp.json.JsonDocument.java

public String getValueAsString(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing,
        String missingNodeValue) throws Exception {
    JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);
    if (valueNode != null) {
        if (valueNode.isMissingNode()) {
            if (isNullable == false && missingNodeValue == null) {
                throw new Exception(currentPath + ": Attribute: " + fieldName
                        + " is missing and configured as not-nullable but the replacement value is also null!");
            } else {
                return missingNodeValue;
            }//w  w  w .j  a  v  a2  s .  c om
        }
        if (valueNode.isValueNode()) {
            return valueNode.asText();
        } else {
            return valueNode.toString();
        }
    } else {
        return null;
    }
}

From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcEndpoint.java

public void processRequest(Object context, JsonNode requestJson) {
    JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
    request.setMethod(requestJson.get("method").asText());
    logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));
    OvsdbRPC.Callback callback = requestCallbacks.get(context);
    if (callback != null) {
        Method[] methods = callback.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(request.getMethod())) {
                Class<?>[] parameters = method.getParameterTypes();
                JsonNode params = requestJson.get("params");
                Object param = objectMapper.convertValue(params, parameters[1]);
                try {
                    Invokable from = Invokable.from(method);
                    from.setAccessible(true);
                    from.invoke(callback, context, param);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    logger.error("Unable to invoke callback " + method.getName(), e);
                }//from   w ww.  j a  v a  2  s  .  c  om
                return;
            }
        }
    }

    // Echo dont need any special processing. hence handling it internally.

    if (request.getMethod().equals("echo")) {
        JsonRpc10Response response = new JsonRpc10Response(request.getId());
        response.setError(null);
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(response);
            nettyChannel.writeAndFlush(jsonString);
        } catch (JsonProcessingException e) {
            logger.error("Exception while processing JSON string " + jsonString, e);
        }
        return;
    }

    logger.error("No handler for Request : {} on {}", requestJson.toString(), context);
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void parseTest() throws IOException {
    Object r = cut.parse("rdbms", p, JsonUtils.json(expectedJSON).get("rdbms"));
    JsonNode parent = p.newNode();
    cut.convert(p, parent, r);/*  w w w.  ja va  2s .  c o  m*/
    assertEqualJson(expectedJSON, parent.toString());
}

From source file:io.liveoak.pgsql.HttpPgSqlTest.java

private String packMembers(List<JsonNode> nodes) {
    StringBuilder sb = new StringBuilder("{ \"members\": [");

    for (int i = 0; i < nodes.size(); i++) {
        JsonNode node = nodes.get(i);
        if (i > 0) {
            sb.append(",\n");
        }// w  ww  .j av a2  s. c  o  m
        sb.append(node.toString());
    }
    sb.append("]}");

    return sb.toString();
}

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

public static Result createUser() {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("signUp bodyJson: " + bodyJson);

    //check and validate input
    if (!bodyJson.has("username"))
        return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password"))
        return badRequest("The 'password' field is missing");
    if (!bodyJson.has("role"))
        return badRequest("The 'role' field is missing");

    //extract fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    JsonNode userID = bodyJson.get(BaasBoxPrivateFields.ID.toString());

    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);
    String role = (String) bodyJson.findValuesAsText("role").get(0);
    String id = (userID != null && userID.isTextual()) ? userID.asText() : null;

    if (privateAttributes != null && privateAttributes.has("email")) {
        //check if email address is valid
        if (!Util.validateEmail((String) (String) privateAttributes.findValuesAsText("email").get(0)))
            return badRequest("The email address must be valid.");
    }//  w w  w . java2 s .co  m

    //try to signup new user
    try {
        UserService.signUp(username, password, null, role, nonAppUserAttributes, privateAttributes,
                friendsAttributes, appUsersAttributes, false, id);
    } catch (InvalidParameterException e) {
        return badRequest(ExceptionUtils.getMessage(e));
    } catch (InvalidJsonException e) {
        return badRequest("Body is not a valid JSON: " + ExceptionUtils.getMessage(e) + "\nyou sent:\n"
                + bodyJson.toString() + "\nHint: check the fields "
                + UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER + ", "
                + UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER + " they must be an object, not a value.");
    } catch (UserAlreadyExistsException e) {
        return badRequest(ExceptionUtils.getMessage(e));
    } catch (EmailAlreadyUsedException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("signUp", e);
        return badRequest(username + ": the email provided is already in use");
    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
        throw new RuntimeException(e);
    }
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method End");
    return created();
}

From source file:com.ikanow.aleph2.graph.titan.utils.TestTitanGraphBuildingUtils.java

@Test
public void test_getElementProperties() {
    // Graph schema
    final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
            .with(GraphSchemaBean::deduplication_fields,
                    Arrays.asList(GraphAnnotationBean.name, GraphAnnotationBean.type))
            .done().get();/*  w  w w  .  j av  a2  s .  co  m*/

    final TitanGraph titan = getSimpleTitanGraph();
    final TitanTransaction tx = titan.buildTransaction().start();

    Vertex v = tx.addVertex("test");
    v.property("name", "name_val");
    v.property("type", "type_val");
    v.property("misc", "misc_val");
    final JsonNode result = TitanGraphBuildingUtils.getElementProperties(v,
            graph_schema.deduplication_fields());

    final ObjectNode key = _mapper.createObjectNode();
    key.put("name", "name_val");
    key.put("type", "type_val");

    assertEquals(key.toString(), result.toString());

    tx.commit();
}