Example usage for com.fasterxml.jackson.databind.node JsonNodeFactory objectNode

List of usage examples for com.fasterxml.jackson.databind.node JsonNodeFactory objectNode

Introduction

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

Prototype

public ObjectNode objectNode() 

Source Link

Usage

From source file:squash.tools.FakeBookingCreator.java

public static void main(String[] args) throws IOException {
    int numberOfDays = 21;
    int numberOfCourts = 5;
    int maxCourtSpan = 5;
    int numberOfSlots = 16;
    int maxSlotSpan = 3;
    int minSurnameLength = 2;
    int maxSurnameLength = 20;
    int minBookingsPerDay = 0;
    int maxBookingsPerDay = 8;
    LocalDate startDate = LocalDate.of(2016, 7, 5);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<Booking> bookings = new ArrayList<>();
    for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) {
        int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1);
        List<Booking> daysBookings = new ArrayList<>();
        for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) {
            String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));
            String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));

            Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>();
            daysBookings.forEach((booking) -> {
                addBookingToSet(booking, bookedCourts);
            });//from ww  w.  j  av  a  2 s  .  c o  m

            Booking booking;
            Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>();
            do {
                // Loop until we create a booking of free courts
                int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1);
                int courtSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxCourtSpan + 1, numberOfCourts - court + 2));
                int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1);
                int slotSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2));
                booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2);
                booking.setDate(date.format(formatter));
                courtsToBook.clear();
                addBookingToSet(booking, courtsToBook);
            } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0));

            daysBookings.add(booking);
        }
        bookings.addAll(daysBookings);
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingNode.put("date", booking.getDate());
        bookingsNode.add(bookingNode);
    }
    // Add empty booking rules array - just so restore works
    rootNode.putArray("bookingRules");
    rootNode.put("clearBeforeRestore", true);

    try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"),
            JsonEncoding.UTF8)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapper.writeTree(generator, rootNode);
    }
}

From source file:edumsg.core.CommandsHelp.java

public static void handleError(String app, String method, String errorMsg, String correlationID,
        Logger logger) {//from  w  w w  . ja v  a2  s . c o  m
    JsonNodeFactory nf = JsonNodeFactory.instance;
    MyObjectMapper mapper = new MyObjectMapper();
    ObjectNode node = nf.objectNode();
    node.put("app", app);
    node.put("method", method);
    node.put("status", "Bad Request");
    node.put("code", "400");
    node.put("message", errorMsg);
    try {
        submit(app, mapper.writeValueAsString(node), correlationID, logger);
    } catch (JsonGenerationException e) {
        //logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (JsonMappingException e) {
        //logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        //logger.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.flipkart.zjsonpatch.JsonDiff.java

private static ObjectNode getJsonNode(JsonNodeFactory FACTORY, Diff diff) {
    ObjectNode jsonNode = FACTORY.objectNode();
    jsonNode.put(Constants.OP, diff.getOperation().rfcName());
    jsonNode.put(Constants.PATH, getArrayNodeRepresentation(diff.getPath()));
    if (Operation.MOVE.equals(diff.getOperation())) {
        jsonNode.put(Constants.FROM, getArrayNodeRepresentation(diff.getPath())); //required {from} only in case of Move Operation
        jsonNode.put(Constants.PATH, getArrayNodeRepresentation(diff.getToPath())); // destination Path
    }/*from w  w  w  .  ja v a2  s .  c o  m*/
    if (!Operation.REMOVE.equals(diff.getOperation()) && !Operation.MOVE.equals(diff.getOperation())) { // setting only for Non-Remove operation
        jsonNode.put(Constants.VALUE, diff.getValue());
    }
    return jsonNode;
}

From source file:io.fabric8.collector.elasticsearch.JsonNodes.java

/**
 * Creates nested objects if they don't exist on the given paths.
 *
 * @returns the last object or null if it could not be created
 */// w w  w  .j ava  2 s  .c  o m
public static ObjectNode setObjects(JsonNode node, String... paths) {
    JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    JsonNode iter = node;
    for (String path : paths) {
        if (!iter.isObject()) {
            return null;
        }
        ObjectNode object = (ObjectNode) iter;
        iter = object.get(path);
        if (iter == null || !iter.isObject()) {
            iter = nodeFactory.objectNode();
            object.set(path, iter);
        }
    }
    return (ObjectNode) iter;
}

From source file:me.tfeng.play.avro.AvroHelper.java

private static JsonNode convertFromSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory)
        throws IOException {
    if (json.isObject() && schema.getType() == Type.RECORD) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        for (Field field : schema.getFields()) {
            String fieldName = field.name();
            if (node.has(fieldName)) {
                newNode.put(fieldName, convertFromSimpleRecord(field.schema(), node.get(fieldName), factory));
            } else if (field.defaultValue() != null) {
                newNode.put(fieldName, Json.parse(field.defaultValue().toString()));
            } else {
                newNode.put(fieldName, factory.nullNode());
            }/*from   w w w  . java  2s. com*/
        }
        return newNode;
    } else if (json.isObject() && schema.getType() == Type.MAP) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        Schema valueType = schema.getValueType();
        Iterator<Entry<String, JsonNode>> entries = node.fields();
        while (entries.hasNext()) {
            Entry<String, JsonNode> entry = entries.next();
            newNode.put(entry.getKey(), convertFromSimpleRecord(valueType, entry.getValue(), factory));
        }
        return newNode;
    } else if (schema.getType() == Type.UNION) {
        Schema type = AvroHelper.getSimpleUnionType(schema);
        if (type == null) {
            if (json.isNull()) {
                return json;
            } else {
                ObjectNode node = (ObjectNode) json;
                Entry<String, JsonNode> entry = node.fields().next();
                for (Schema unionType : schema.getTypes()) {
                    if (unionType.getFullName().equals(entry.getKey())) {
                        ObjectNode newNode = factory.objectNode();
                        newNode.put(entry.getKey(),
                                convertFromSimpleRecord(unionType, entry.getValue(), factory));
                        return newNode;
                    }
                }
                throw new IOException("Unable to get schema for type " + entry.getKey() + " in union");
            }
        } else if (json.isNull()) {
            return json;
        } else {
            ObjectNode newNode = factory.objectNode();
            newNode.put(type.getFullName(), convertFromSimpleRecord(type, json, factory));
            return newNode;
        }
    } else if (json.isArray() && schema.getType() == Type.ARRAY) {
        ArrayNode node = (ArrayNode) json;
        ArrayNode newNode = factory.arrayNode();
        Iterator<JsonNode> iterator = node.elements();
        while (iterator.hasNext()) {
            newNode.add(convertFromSimpleRecord(schema.getElementType(), iterator.next(), factory));
        }
        return newNode;
    } else {
        return json;
    }
}

From source file:me.tfeng.play.avro.AvroHelper.java

private static JsonNode convertToSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory)
        throws IOException {
    if (json.isObject() && schema.getType() == Type.RECORD) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        for (Field field : schema.getFields()) {
            String fieldName = field.name();
            if (node.has(fieldName)) {
                JsonNode value = convertToSimpleRecord(field.schema(), node.get(fieldName), factory);
                if (!value.isNull()) {
                    newNode.put(fieldName, value);
                }//  ww w  . j  a  v a 2s.co  m
            }
        }
        return newNode;
    } else if (json.isObject() && schema.getType() == Type.MAP) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        Schema valueType = schema.getValueType();
        Iterator<Entry<String, JsonNode>> entries = node.fields();
        while (entries.hasNext()) {
            Entry<String, JsonNode> entry = entries.next();
            JsonNode value = convertToSimpleRecord(valueType, entry.getValue(), factory);
            if (value.isNull()) {
                newNode.put(entry.getKey(), value);
            }
        }
        return newNode;
    } else if (schema.getType() == Type.UNION) {
        Schema type = AvroHelper.getSimpleUnionType(schema);
        if (type == null) {
            if (json.isNull()) {
                return json;
            } else {
                ObjectNode node = (ObjectNode) json;
                Entry<String, JsonNode> entry = node.fields().next();
                for (Schema unionType : schema.getTypes()) {
                    if (unionType.getFullName().equals(entry.getKey())) {
                        ObjectNode newNode = factory.objectNode();
                        newNode.put(entry.getKey(),
                                convertToSimpleRecord(unionType, entry.getValue(), factory));
                        return newNode;
                    }
                }
                throw new IOException("Unable to get schema for type " + entry.getKey() + " in union");
            }
        } else if (json.isNull()) {
            return json;
        } else {
            return convertToSimpleRecord(type, json.get(type.getFullName()), factory);
        }
    } else if (json.isArray() && schema.getType() == Type.ARRAY) {
        ArrayNode node = (ArrayNode) json;
        ArrayNode newNode = factory.arrayNode();
        Iterator<JsonNode> iterator = node.elements();
        while (iterator.hasNext()) {
            newNode.add(convertToSimpleRecord(schema.getElementType(), iterator.next(), factory));
        }
        return newNode;
    } else {
        return json;
    }
}

From source file:me.tfeng.toolbox.avro.AvroHelper.java

private static JsonNode convertFromSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory)
        throws IOException {
    if (json.isObject() && schema.getType() == Type.RECORD) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        for (Field field : schema.getFields()) {
            String fieldName = field.name();
            if (node.has(fieldName)) {
                newNode.set(fieldName, convertFromSimpleRecord(field.schema(), node.get(fieldName), factory));
            } else if (field.defaultValue() != null) {
                newNode.set(fieldName, MAPPER.readTree(field.defaultValue().toString()));
            } else {
                newNode.set(fieldName, factory.nullNode());
            }/* w  w  w  .  ja va2s. co m*/
        }
        return newNode;
    } else if (json.isObject() && schema.getType() == Type.MAP) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        Schema valueType = schema.getValueType();
        Iterator<Entry<String, JsonNode>> entries = node.fields();
        while (entries.hasNext()) {
            Entry<String, JsonNode> entry = entries.next();
            newNode.set(entry.getKey(), convertFromSimpleRecord(valueType, entry.getValue(), factory));
        }
        return newNode;
    } else if (schema.getType() == Type.UNION) {
        Schema type = getSimpleUnionType(schema);
        if (type == null) {
            if (json.isNull()) {
                return json;
            } else {
                ObjectNode node = (ObjectNode) json;
                Entry<String, JsonNode> entry = node.fields().next();
                for (Schema unionType : schema.getTypes()) {
                    if (unionType.getFullName().equals(entry.getKey())) {
                        ObjectNode newNode = factory.objectNode();
                        newNode.set(entry.getKey(),
                                convertFromSimpleRecord(unionType, entry.getValue(), factory));
                        return newNode;
                    }
                }
                throw new IOException("Unable to get schema for type " + entry.getKey() + " in union");
            }
        } else if (json.isNull()) {
            return json;
        } else {
            ObjectNode newNode = factory.objectNode();
            newNode.set(type.getFullName(), convertFromSimpleRecord(type, json, factory));
            return newNode;
        }
    } else if (json.isArray() && schema.getType() == Type.ARRAY) {
        ArrayNode node = (ArrayNode) json;
        ArrayNode newNode = factory.arrayNode();
        Iterator<JsonNode> iterator = node.elements();
        while (iterator.hasNext()) {
            newNode.add(convertFromSimpleRecord(schema.getElementType(), iterator.next(), factory));
        }
        return newNode;
    } else {
        return json;
    }
}

From source file:me.tfeng.toolbox.avro.AvroHelper.java

private static JsonNode convertToSimpleRecord(Schema schema, JsonNode json, JsonNodeFactory factory)
        throws IOException {
    if (json.isObject() && schema.getType() == Type.RECORD) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        for (Field field : schema.getFields()) {
            String fieldName = field.name();
            if (node.has(fieldName)) {
                JsonNode value = convertToSimpleRecord(field.schema(), node.get(fieldName), factory);
                if (!value.isNull()) {
                    newNode.set(fieldName, value);
                }//from  w  w  w .  j av  a  2s. c  o m
            }
        }
        return newNode;
    } else if (json.isObject() && schema.getType() == Type.MAP) {
        ObjectNode node = (ObjectNode) json;
        ObjectNode newNode = factory.objectNode();
        Schema valueType = schema.getValueType();
        Iterator<Entry<String, JsonNode>> entries = node.fields();
        while (entries.hasNext()) {
            Entry<String, JsonNode> entry = entries.next();
            JsonNode value = convertToSimpleRecord(valueType, entry.getValue(), factory);
            if (value.isNull()) {
                newNode.set(entry.getKey(), value);
            }
        }
        return newNode;
    } else if (schema.getType() == Type.UNION) {
        Schema type = getSimpleUnionType(schema);
        if (type == null) {
            if (json.isNull()) {
                return json;
            } else {
                ObjectNode node = (ObjectNode) json;
                Entry<String, JsonNode> entry = node.fields().next();
                for (Schema unionType : schema.getTypes()) {
                    if (unionType.getFullName().equals(entry.getKey())) {
                        ObjectNode newNode = factory.objectNode();
                        newNode.set(entry.getKey(),
                                convertToSimpleRecord(unionType, entry.getValue(), factory));
                        return newNode;
                    }
                }
                throw new IOException("Unable to get schema for type " + entry.getKey() + " in union");
            }
        } else if (json.isNull()) {
            return json;
        } else {
            return convertToSimpleRecord(type, json.get(type.getFullName()), factory);
        }
    } else if (json.isArray() && schema.getType() == Type.ARRAY) {
        ArrayNode node = (ArrayNode) json;
        ArrayNode newNode = factory.arrayNode();
        Iterator<JsonNode> iterator = node.elements();
        while (iterator.hasNext()) {
            newNode.add(convertToSimpleRecord(schema.getElementType(), iterator.next(), factory));
        }
        return newNode;
    } else {
        return json;
    }
}

From source file:uk.ac.ucl.excites.sapelli.collector.SapColCmdLn.java

/**
 * @param sapFile//from  w  ww . j a  v  a2 s  .  co  m
 * @param project
 * @throws IOException
 * @see https://github.com/ExCiteS/geokey-sapelli
 */
static public void printProjectInfoForGeoKey(File sapFile, Project project) throws IOException {
    GeoKeyFormDescriber gkFormDescriber = new GeoKeyFormDescriber();

    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);

    // create a json factory to write the treenode as json. for the example
    // we just write to console
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator generator = jsonFactory.createGenerator(System.out);
    ObjectMapper mapper = new ObjectMapper();

    // the root node
    ObjectNode projectJSON = factory.objectNode();

    // describe project:
    projectJSON.put("name", project.getName());
    projectJSON.put("variant", project.getVariant());
    projectJSON.put("version", project.getVersion());
    projectJSON.put("display_name", project.toString(false));
    projectJSON.put("sapelli_id", project.getID());
    projectJSON.put("sapelli_fingerprint", project.getFingerPrint());
    projectJSON.put("sapelli_model_id", project.getModel().id);
    projectJSON.put("installation_path", fsp.getProjectInstallationFolder(project, false).getAbsolutePath());
    ArrayNode formsJSON = factory.arrayNode();
    for (Form frm : project.getForms()) {
        ObjectNode formNode = gkFormDescriber.getFormJSON(frm);
        if (formNode != null)
            formsJSON.add(formNode);
    }
    projectJSON.set("forms", formsJSON);

    // Serialise:
    mapper.writeTree(generator, projectJSON);
}

From source file:uk.ac.ucl.excites.sapelli.collector.SapColCmdLn.java

static public void printProjectInfoJSON(File sapFile, Project project) throws IOException {
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);

    // create a json factory to write the treenode as json. for the example
    // we just write to console
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator generator = jsonFactory.createGenerator(System.out);
    ObjectMapper mapper = new ObjectMapper();

    // the root node
    ObjectNode projectJSON = factory.objectNode();

    // describe project:
    projectJSON.put("source", sapFile.getAbsolutePath());
    projectJSON.put("id", project.getID());
    projectJSON.put("fingerprint", project.getFingerPrint());
    projectJSON.put("name", project.getName());
    projectJSON.put("variant", project.getVariant());
    projectJSON.put("version", project.getVersion());
    projectJSON.put("display-name", project.toString(false));
    projectJSON.put("model-id", project.getModel().id);
    projectJSON.put("install-path", fsp.getProjectInstallationFolder(project, false).getAbsolutePath());
    ArrayNode formsJSON = factory.arrayNode();
    for (Form frm : project.getForms()) {
        ObjectNode formJSON = factory.objectNode();
        formJSON.put("id", frm.id);
        formJSON.put("produces-data", frm.isProducesRecords());
        formJSON.put("model-schema-number",
                (frm.isProducesRecords() ? frm.getSchema().getModelSchemaNumber() : null));
        formsJSON.add(formJSON);/*from w  w  w  .j  av a  2  s .  com*/
    }
    projectJSON.set("forms", formsJSON);

    // Serialise:
    mapper.writeTree(generator, projectJSON);
}