Example usage for com.fasterxml.jackson.databind ObjectMapper writeTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writeTree.

Prototype

public void writeTree(JsonGenerator jgen, JsonNode rootNode) throws IOException, JsonProcessingException 

Source Link

Document

Method to serialize given JSON Tree, using generator provided.

Usage

From source file:squash.booking.lambdas.core.PageManager.java

/**
 * Returns JSON-encoded valid-dates data for a specified date.
 * //from   w w w . j av a 2s  . c o  m
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @throws IOException
 */
protected String createValidDatesData(List<String> validDates) throws IllegalArgumentException, IOException {

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached valid dates data");

    // Encode valid dates 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 validDatesNode = rootNode.putArray("dates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }

    ByteArrayOutputStream validDatesStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(validDatesStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String validDatesString = validDatesStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached valid dates data : " + validDatesString);

    return validDatesString;
}

From source file:squash.booking.lambdas.core.PageManager.java

/**
 * Returns JSON-encoded booking data for a specified date.
 * /*  ww w  .jav a 2 s .co  m*/
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param date the date in YYYY-MM-DD format.
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @param bookings the bookings for the specified date.
 * @throws Exception 
 */
protected String createCachedBookingData(String date, List<String> validDates, List<Booking> bookings)
        throws Exception {

    ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager.getLifecycleState();

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create cached booking data");
    logger.log("Lifecycle state is: " + lifecycleState.left.name());
    if (lifecycleState.left.equals(LifecycleState.RETIRED)) {
        logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get());
    }

    // 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();

    rootNode.put("date", date);
    ArrayNode validDatesNode = rootNode.putArray("validdates");
    for (int i = 0; i < validDates.size(); i++) {
        validDatesNode.add(validDates.get(i));
    }
    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());
        bookingsNode.add(bookingNode);
    }
    // This gives the Angularjs app access to the lifecycle state.
    ObjectNode lifecycleStateNode = rootNode.putObject("lifecycleState");
    lifecycleStateNode.put("state", lifecycleState.left.name());
    lifecycleStateNode.put("url", lifecycleState.right.isPresent() ? lifecycleState.right.get() : "");

    ByteArrayOutputStream bookingDataStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(bookingDataStream);
    try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeTree(generator, rootNode);
    }
    String bookingData = bookingDataStream.toString(StandardCharsets.UTF_8.name());
    logger.log("Created cached booking data: " + bookingData);

    return bookingData;
}

From source file:ru.histone.HistoneOptimizeAstMojo.java

public void execute() throws MojoExecutionException {
    try {// w  ww . j a  v  a  2s .  c om

        getLog().info(MessageFormat.format("Running DirectoryScanner with params: baseDir={0}, includes=[{1}]",
                baseDir, StringUtils.join(includes, ", ")));
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(baseDir);
        scanner.setIncludes(includes);
        scanner.scan();

        List<OptimizationTypes> optimizationTypeses = new ArrayList<OptimizationTypes>();
        for (String optimizationType : optimizationTypes) {
            optimizationTypeses.add(OptimizationTypes.valueOf(optimizationType));
        }
        OptimizationTypes[] array = optimizationTypeses
                .toArray(new OptimizationTypes[optimizationTypeses.size()]);
        getLog().info(MessageFormat.format("Optimizations to be run: [{0}]",
                "" + StringUtils.join(optimizationTypes, ", ")));

        String[] includedFiles = scanner.getIncludedFiles();
        getLog().info(MessageFormat.format("Files found:\n{0}", StringUtils.join(includedFiles, "\n")));

        HistoneBuilder builder = new HistoneBuilder();
        Histone histone = builder.build();
        ObjectMapper jackson = new ObjectMapper();
        JsonFactory jsonFactory = new JsonFactory();

        for (String includedFile : includedFiles) {
            ArrayNode ast = histone.parseTemplateToAST(new FileReader(new File(baseDir, includedFile)));

            ObjectNode context = builder.getNodeFactory().jsonObject();

            int astCount1 = ASTTreeElementsCounter.count(ast);
            ArrayNode optimizedAst = histone.optimizeAST(ast, context, array);
            int astCount2 = ASTTreeElementsCounter.count(ast);

            getLog().info(MessageFormat.format("Processing {0}, before: {1}, after: {2}", includedFile,
                    astCount1, astCount2));

            JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File(baseDir, includedFile + ".ast"),
                    JsonEncoding.UTF8);
            jackson.writeTree(jsonGenerator, optimizedAst);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error parsing templates to AST", e);
    }

}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String write_tostring(JsonNode json) {
    ObjectMapper mapper = new ObjectMapper();
    StringWriter out = new StringWriter();

    try {//  w w w . j  a v a 2s.  c om
        JsonFactory fac = new JsonFactory();
        JsonGenerator gen = fac.createJsonGenerator(out);

        // Now write:
        mapper.writeTree(gen, json);
        gen.flush();
        gen.close();
        return out.toString();
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception in write_tostring: " + e);
    }
    return (null);
}