Example usage for com.fasterxml.jackson.databind.node ObjectNode put

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode put

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode put.

Prototype

public ObjectNode put(String paramString1, String paramString2) 

Source Link

Usage

From source file:api.JsonAPI.java

/**
 * Guardar un pegote/*from   w  ww.  jav a2 s .c o  m*/
 */
@BodyParser.Of(BodyParser.Json.class)
public static Result save() {
    JsonNode json = request().body().asJson();
    ObjectNode result = Json.newObject();
    if (json == null) {
        result.put("message", "Se esperaba Json");
        return badRequest(result);
    } else {
        String content = json.findPath("content").asText();
        ;
        if (content == null || content.isEmpty()) {
            result.put("message", "Se esperaba Json con algn contenido");
            return badRequest(result);
        } else {
            String key = PastesManager.getAviableKey();
            PastesManager.save(key, content, request().remoteAddress());
            result.put("key", key);
            return created(result);
        }
    }
}

From source file:controllers.FormsController.java

public static Result getRegistrationForm() {
    ObjectNode obj = Json.newObject();
    obj.put("prename", generateFieldFromProperty("prename"));
    obj.put("surname", generateFieldFromProperty("surname"));
    obj.put("gender", generateFieldFromProperty("gender"));
    obj.put("birthday", generateFieldFromProperty("birthday"));
    obj.put("nationality", generateFieldFromProperty("nationality"));
    obj.put("mail", generateFieldFromProperty("mail"));
    obj.put("password", generateFieldFromProperty("password"));
    obj.put("repeatpassword", generateFieldFromProperty("repeatpassword"));
    obj.put("narrowbox", generateFieldFromProperty("narrowbox"));
    return ok(obj);
}

From source file:controllers.api.v1.Search.java

public static Result getSearchAutoComplete() {
    ObjectNode result = Json.newObject();
    result.put("status", "ok");
    result.set("source", Json.toJson(SearchDAO.getAutoCompleteList()));

    return ok(result);
}

From source file:net.hamnaberg.json.Error.java

public static Error create(Optional<String> title, Optional<String> code, Optional<String> message) {
    final ObjectNode obj = JsonNodeFactory.instance.objectNode();
    title.ifPresent(value -> obj.put("title", value));
    code.ifPresent(value -> obj.put("code", value));
    message.ifPresent(value -> obj.put("message", value));
    return new Error(obj);
}

From source file:controllers.api.v1.ScriptFinder.java

public static Result getAllScriptTypes() {
    ObjectNode result = Json.newObject();

    result.put("status", "ok");
    result.set("scriptTypes", Json.toJson(ScriptFinderDAO.getAllScriptTypes()));
    return ok(result);
}

From source file:controllers.DataController.java

@BodyParser.Of(BodyParser.Raw.class)
public static Result receiveMessage() {

    /* let's see what is happening here */

    System.out.println("Just to be sure that it receives the bytes properly");

    if (request().body().asRaw() != null) {
        System.out.println(request().body().asRaw().size());

        GeneralMessage yourObject = (GeneralMessage) SerializationUtils
                .deserialize(request().body().asRaw().asBytes());
        System.out.println("Destination_: " + yourObject.getDestination());
        System.out.println("Origin: _" + yourObject.getOrigin());
        System.out.println("message type_ " + yourObject.getMessageType());

        MongoManager.store(request().body().asRaw().asBytes(), yourObject.getDestination());
        WebSocket.Out<String> wsOut = WebSocketsStore.connectionsMap
                .get(ParseHandling.calculateDestination(yourObject.getDestination()));
        System.out.println(WebSocketsStore.connectionsMap);
        System.out.println(ParseHandling.calculateDestination(yourObject.getDestination()));
        if (wsOut != null) {
            System.out/*w w w  .j a  v  a  2  s.c  o  m*/
                    .println(ParseHandling.receiveMessage(yourObject.getOrigin(), yourObject.getDestination()));
            wsOut.write(ParseHandling.receiveMessage(yourObject.getOrigin(), yourObject.getDestination()));
        }

        else
            System.out.println("Does not receive sockets :(((");
    } else {
        System.out.println("Cannot read the raw data");
    }

    JsonNode json = request().body().asJson();
    ObjectNode result = Json.newObject();
    result.put("status", "receiveMessage");
    return ok(result);

}

From source file:eu.trentorise.opendata.commons.test.jackson.OdtJacksonTester.java

/**
* Converts {@code obj} to an {@link ObjectNode}, sets field
* {@code fieldName} to {@code newNode} and returns the json string
* representation of such new object. Also logs the json with the provided logger at FINE
* level.//from   www. j ava  2  s.  co  m
*/
public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName,
        JsonNode newNode) {
    checkNotNull(obj);
    checkNotEmpty(fieldName, "Invalid field name!");

    String string;
    try {
        string = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Error while jacksonizing object to json node!", ex);
    }
    TreeNode treeNode;
    try {
        treeNode = (ObjectNode) objectMapper.readTree(string);
    } catch (IOException ex) {
        throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex);
    }
    if (!treeNode.isObject()) {
        throw new OdtException(
                "The provided object was jacksonized to a string which does not represent a JSON object! String is "
                        + string);
    }
    ObjectNode jo = (ObjectNode) treeNode;
    jo.put(fieldName, newNode);

    String json = jo.toString();

    logger.log(Level.FINE, "converted json = {0}", json);

    return json;

}

From source file:controllers.Reconcile.java

/** @return Reconciliation data for the queries in the request */
public static Result reconcile() {
    JsonNode request = Json.parse(request().body().asFormUrlEncoded().get("queries")[0]);
    Iterator<Entry<String, JsonNode>> inputQueries = request.fields();
    ObjectNode response = Json.newObject();
    while (inputQueries.hasNext()) {
        Entry<String, JsonNode> inputQuery = inputQueries.next();
        Logger.debug("q: " + inputQuery);
        SearchResponse searchResponse = executeQuery(inputQuery, buildQueryString(inputQuery));
        List<JsonNode> results = mapToResults(searchResponse.getHits());
        ObjectNode resultsForInputQuery = Json.newObject();
        resultsForInputQuery.put("result", Json.toJson(results));
        Logger.debug("r: " + resultsForInputQuery);
        response.put(inputQuery.getKey(), resultsForInputQuery);
    }//from  w  ww.j  a  v  a  2  s  .  c  om
    return ok(response);
}

From source file:Main.java

public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException {
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    List<Map<String, Object>> threads = new ArrayList<>();

    for (ThreadInfo thread : threadInfos) {
        Map<String, Object> threadMap = new HashMap<>();
        threadMap.put("name", thread.getThreadName());
        threadMap.put("id", thread.getThreadId());
        threadMap.put("state", thread.getThreadState().name());
        List<String> stacktrace = new ArrayList<>();
        for (StackTraceElement element : thread.getStackTrace()) {
            stacktrace.add(element.toString());
        }/*w ww  .  jav  a2 s  .  c  o  m*/
        threadMap.put("stack", stacktrace);

        if (thread.getLockName() != null) {
            threadMap.put("lock_name", thread.getLockName());
        }
        if (thread.getLockOwnerId() != -1) {
            threadMap.put("lock_owner_id", thread.getLockOwnerId());
        }
        if (thread.getBlockedTime() > 0) {
            threadMap.put("blocked_time", thread.getBlockedTime());
        }
        if (thread.getBlockedCount() > 0) {
            threadMap.put("blocked_count", thread.getBlockedCount());
        }
        if (thread.getLockedMonitors().length > 0) {
            threadMap.put("locked_monitors", thread.getLockedMonitors());
        }
        if (thread.getLockedSynchronizers().length > 0) {
            threadMap.put("locked_synchronizers", thread.getLockedSynchronizers());
        }
        threads.add(threadMap);
    }
    ObjectMapper om = new ObjectMapper();
    ObjectNode json = om.createObjectNode();
    json.put("date", new Date().toString());
    json.putPOJO("threads", threads);

    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        json.putPOJO("deadlocked_thread_ids", deadlockedThreads);
    }
    if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) {
        json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads);
    }
    om.enable(SerializationFeature.INDENT_OUTPUT);
    return om.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}

From source file:com.ibm.watson.catalyst.corpus.tfidf.CorpusTfidf.java

private static ObjectNode printGoodWords(TermDocument d, TermCorpus c) {
    ObjectNode result = MAPPER.createObjectNode();
    result.put("document", d.getContext(0));
    WordFrequencyHashtable f = d.getFrequencies();

    SortedArrayList<String> importantWords = new SortedArrayList<String>();

    {/*from   w  w w.jav  a 2  s. c  o m*/
        Iterator<String> words = f.sortedIterator(1);
        while (words.hasNext()) {
            String word = words.next();
            //if (d.frequency(word) < 5) continue;
            importantWords.sortedAdd(word, tfidf(word, d, c));
        }
    }

    SortedArrayList<String> wordList;
    switch (sortedBy) {
    case TFIDF:
        wordList = importantWords;
        break;
    case FREQ:
        wordList = new SortedArrayList<String>();
        for (String word : importantWords)
            wordList.sortedAdd(word, f.get(word));
        break;
    default:
        throw new IllegalStateException();
    }

    ArrayNode wordNodes = MAPPER.createArrayNode();
    for (String word : wordList) {
        ObjectNode wordNode = MAPPER.createObjectNode();
        wordNode.put("string", word);
        wordNode.put("frequency", f.get(word));
        wordNode.put("tfidf", tfidf(word, d, c));
        wordNodes.add(wordNode);
    }

    result.set("words", wordNodes);
    return result;
}