Example usage for com.fasterxml.jackson.core JsonFactory _getBufferRecycler

List of usage examples for com.fasterxml.jackson.core JsonFactory _getBufferRecycler

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory _getBufferRecycler.

Prototype

public BufferRecycler _getBufferRecycler() 

Source Link

Document

Method used by factory to create buffer recycler instances for parsers and generators.

Usage

From source file:com.github.jknack.handlebars.Jackson2Helper.java

@Override
public CharSequence apply(final Object context, final Options options) throws IOException {
    if (context == null) {
        return options.hash("default", "");
    }//from   w  w  w.  j av  a  2s . c  o  m
    String viewName = options.hash("view", "");
    JsonGenerator generator = null;
    try {
        final ObjectWriter writer;
        // do we need to use a view?
        if (!isEmpty(viewName)) {
            Class<?> viewClass = alias.get(viewName);
            if (viewClass == null) {
                viewClass = getClass().getClassLoader().loadClass(viewName);
            }
            writer = mapper.writerWithView(viewClass);
        } else {
            writer = mapper.writer();
        }
        JsonFactory jsonFactory = mapper.getFactory();

        SegmentedStringWriter output = new SegmentedStringWriter(jsonFactory._getBufferRecycler());

        // creates a json generator.
        generator = jsonFactory.createJsonGenerator(output);

        Boolean escapeHtml = options.hash("escapeHTML", Boolean.FALSE);
        // do we need to escape html?
        if (escapeHtml) {
            generator.setCharacterEscapes(new HtmlEscapes());
        }

        Boolean pretty = options.hash("pretty", Boolean.FALSE);

        // write the JSON output.
        if (pretty) {
            writer.withDefaultPrettyPrinter().writeValue(generator, context);
        } else {
            writer.writeValue(generator, context);
        }

        generator.close();

        return new Handlebars.SafeString(output.getAndClear());
    } catch (ClassNotFoundException ex) {
        throw new IllegalArgumentException(viewName, ex);
    } finally {
        if (generator != null && !generator.isClosed()) {
            generator.close();
        }
    }
}