Example usage for com.fasterxml.jackson.core JsonGenerator close

List of usage examples for com.fasterxml.jackson.core JsonGenerator close

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator close.

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Method called to close this generator, so that no more content can be written.

Usage

From source file:org.eclipse.winery.repository.resources.servicetemplates.boundarydefinitions.interfaces.ExportedOperationResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from   w  w w. j  a va 2  s.c  om
public Response getJSON() {
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        jg.writeStartObject();
        String type = this.getType();
        jg.writeStringField("type", type);
        jg.writeStringField("ref", this.getReference());
        if ((type != null) && (!type.equals("Plan"))) {
            jg.writeStringField("interfacename", this.getInterfaceName());
            jg.writeStringField("operationname", this.getOperationName());
        }
        jg.writeEndObject();
        jg.close();
    } catch (Exception e) {
        ExportedOperationResource.LOGGER.error(e.getMessage(), e);
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build());
    }
    return Response.ok(sw.toString()).build();
}

From source file:com.example.MessageList.java

/**
 * Build message list dependent on the format Message Hub requires. The
 * message list is in the form: [{ "value": base_64_string }, ...]
 * /*www. j av  a2  s.  c om*/
 * @return {String} String representation of a JSON object.
 * @throws IOException
 */
public String build() throws IOException {
    final JsonFactory jsonFactory = new JsonFactory();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    JsonGenerator jsonGenerator = null;

    jsonGenerator = jsonFactory.createGenerator(outputStream);

    // [
    jsonGenerator.writeStartArray();

    // Write each message as a JSON object in
    // the form:
    // { "value": base_64_string }
    for (int i = 0; i < this.messages.size(); i++) {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("value");
        jsonGenerator.writeObject(this.messages.get(i));
        jsonGenerator.writeEndObject();
    }

    // ]
    jsonGenerator.writeEndArray();

    // Close underlying streams and return string representation.
    jsonGenerator.close();
    outputStream.close();

    return new String(outputStream.toByteArray());
}

From source file:com.cedarsoft.couchdb.io.ViewResponseSerializer.java

public <K, V> void serialize(@Nonnull ViewResponse<K, V, ?> viewResponse,
        @Nonnull JacksonSerializer<? super K> keySerializer,
        @Nonnull JacksonSerializer<? super V> valueSerializer, @Nonnull OutputStream out) throws IOException {
    JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
    JsonGenerator generator = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8);

    generator.writeStartObject();/* ww w.ja va  2s. com*/

    generator.writeNumberField(PROPERTY_TOTAL_ROWS, viewResponse.getTotalRows());
    generator.writeNumberField(PROPERTY_OFFSET, viewResponse.getOffset());

    //Now the rows
    generator.writeFieldName(PROPERTY_ROWS);
    generator.writeStartArray();

    for (Row<K, V, ?> row : viewResponse.getRows()) {
        rowSerializer.serialize(row, keySerializer, valueSerializer, generator);
    }

    generator.writeEndArray();

    generator.writeEndObject();
    generator.close();
}

From source file:com.netflix.hystrix.contrib.sample.stream.HystrixConfigurationJsonStream.java

public static String convertToString(HystrixConfiguration config) throws IOException {
    StringWriter jsonString = new StringWriter();
    JsonGenerator json = jsonFactory.createGenerator(jsonString);

    json.writeStartObject();//from www .  j a  v  a  2  s .  c om
    json.writeStringField("type", "HystrixConfig");
    json.writeObjectFieldStart("commands");
    for (Map.Entry<HystrixCommandKey, HystrixCommandConfiguration> entry : config.getCommandConfig()
            .entrySet()) {
        final HystrixCommandKey key = entry.getKey();
        final HystrixCommandConfiguration commandConfig = entry.getValue();
        writeCommandConfigJson(json, key, commandConfig);

    }
    json.writeEndObject();

    json.writeObjectFieldStart("threadpools");
    for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> entry : config.getThreadPoolConfig()
            .entrySet()) {
        final HystrixThreadPoolKey threadPoolKey = entry.getKey();
        final HystrixThreadPoolConfiguration threadPoolConfig = entry.getValue();
        writeThreadPoolConfigJson(json, threadPoolKey, threadPoolConfig);
    }
    json.writeEndObject();

    json.writeObjectFieldStart("collapsers");
    for (Map.Entry<HystrixCollapserKey, HystrixCollapserConfiguration> entry : config.getCollapserConfig()
            .entrySet()) {
        final HystrixCollapserKey collapserKey = entry.getKey();
        final HystrixCollapserConfiguration collapserConfig = entry.getValue();
        writeCollapserConfigJson(json, collapserKey, collapserConfig);
    }
    json.writeEndObject();
    json.writeEndObject();
    json.close();

    return jsonString.getBuffer().toString();
}

From source file:com.medvision360.medrecord.pv.PVSerializer.java

@Override
public void serialize(Locatable locatable, OutputStream os, String encoding)
        throws IOException, SerializeException {
    final JsonGenerator jg = getJsonGenerator(os, encoding);

    // I feel like not putting the archetype in the path makes things a lot easier
    // String prefix = "[" + archetypeIdString + "]/";
    String prefix = "/";

    SerializeVisitor visitor = new PVSerializeVisitor(jg);

    jg.writeStartObject();/*from   w ww  . j av  a 2  s . c  o  m*/
    try {
        walk(locatable, visitor, prefix);
    } catch (InvocationTargetException e) {
        throw new SerializeException("Problem walking the RM object model", e);
    } catch (IllegalAccessException e) {
        throw new SerializeException("Problem walking the RM object model", e);
    }
    jg.writeEndObject();
    jg.close();
}

From source file:net.solarnetwork.web.support.JSONView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PropertyEditorRegistrar registrar = this.propertyEditorRegistrar;
    Enumeration<String> attrEnum = request.getAttributeNames();
    while (attrEnum.hasMoreElements()) {
        String key = attrEnum.nextElement();
        Object val = request.getAttribute(key);
        if (val instanceof PropertyEditorRegistrar) {
            registrar = (PropertyEditorRegistrar) val;
            break;
        }//  w  w  w .  j a  va2  s . c o  m
    }

    response.setCharacterEncoding(UTF8_CHAR_ENCODING);
    response.setContentType(getContentType());
    Writer writer = response.getWriter();
    if (this.includeParentheses) {
        writer.write('(');
    }
    JsonGenerator json = new JsonFactory().createGenerator(writer);
    json.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (indentAmount > 0) {
        json.useDefaultPrettyPrinter();
    }
    json.writeStartObject();
    for (String key : model.keySet()) {
        Object val = model.get(key);
        writeJsonValue(json, key, val, registrar);
    }
    json.writeEndObject();
    json.close();
    if (this.includeParentheses) {
        writer.write(')');
    }
}

From source file:org.mashti.jetson.json.JsonResponseEncoder.java

void encodeResultOrException(final Integer id, final Object result, final Throwable exception,
        final ByteBuf out, final boolean error) throws RPCException {

    JsonGenerator generator = null;
    try {/* w w w  . j  av a  2s. c  om*/
        generator = createJsonGenerator(out);
        generator.writeStartObject();
        generator.writeObjectField(JsonRequestEncoder.ID_KEY, id);
        generator.writeObjectField(JsonRequestEncoder.VERSION_KEY, JsonRequestEncoder.DEFAULT_VERSION);
        if (error) {
            final JsonRpcError json_rpc_error = JsonRpcExceptions.toJsonRpcError(exception);
            generator.writeObjectField(ERROR_KEY, json_rpc_error);
        } else {
            generator.writeObjectField(RESULT_KEY, result);
        }
        generator.writeEndObject();
        generator.flush();
        generator.close();
    } catch (final JsonProcessingException e) {
        LOGGER.debug("failed to encode response", e);
        throw new InternalServerException(e);
    } catch (final IOException e) {
        LOGGER.debug("IO error occurred while encoding response", e);
        throw new TransportException(e);
    } finally {
        CloseableUtil.closeQuietly(generator);
    }
}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

@GET
@Path("bundles")
@Produces(MediaType.APPLICATION_JSON)//  w w w. j a v a 2s  .  c  om
public Response listBundles(@Context UriInfo uriInfo) throws Exception {
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    List<String> patterns = queryParams.get("pattern");
    if (patterns == null || patterns.isEmpty())
        return Response.status(Status.BAD_REQUEST).entity("Bundle listing requires 'pattern' query parameter.")
                .build();

    UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder().path("{bsn}");
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
    generator.writeStartArray();

    for (String pattern : patterns) {
        List<String> list = repo.list(pattern);
        for (String bsn : list) {
            generator.writeStartObject();
            generator.writeStringField("bsn", bsn);
            generator.writeStringField("href", uriBuilder.build(bsn).toString());
            generator.writeEndObject();
        }
    }
    generator.writeEndArray();
    generator.close();

    return Response.ok(writer.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.ning.metrics.serialization.event.TestSmileEnvelopeEvent.java

@BeforeTest
public void setUp() throws IOException {
    // Use same configuration as SmileEnvelopeEvent
    final SmileFactory f = new SmileFactory();
    f.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, true);
    f.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, true);
    f.configure(SmileParser.Feature.REQUIRE_HEADER, false);

    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final JsonGenerator g = f.createJsonGenerator(stream);

    g.writeStartObject();//from   ww w .  j  a  v  a  2  s .c  o  m
    g.writeStringField(SmileEnvelopeEvent.SMILE_EVENT_GRANULARITY_TOKEN_NAME, eventGranularity.toString());
    g.writeObjectFieldStart("name");
    g.writeStringField("first", "Joe");
    g.writeStringField("last", "Sixpack");
    g.writeEndObject(); // for field 'name'
    g.writeStringField("gender", "MALE");
    g.writeNumberField(SmileEnvelopeEvent.SMILE_EVENT_DATETIME_TOKEN_NAME, eventDateTime.getMillis());
    g.writeBooleanField("verified", false);
    g.writeEndObject();
    g.close(); // important: will force flushing of output, close underlying output stream

    serializedBytes = stream.toByteArray();
    // one sanity check; should be able to round-trip via String (iff using latin-1!)
    serializedString = stream.toString(SmileEnvelopeEvent.CHARSET.toString());
}

From source file:net.opentsdb.tree.Leaf.java

/**
 * Writes the leaf to a JSON object for storage. This is necessary for the CAS
 * calls and to reduce storage costs since we don't need to store UID names
 * (particularly as someone may rename a UID)
 * @return The byte array to store//w w w. j a  va2s  . c o m
 */
private byte[] toStorageJson() {
    final ByteArrayOutputStream output = new ByteArrayOutputStream(display_name.length() + tsuid.length() + 30);
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);

        json.writeStartObject();

        // we only need to write a small amount of information
        json.writeObjectField("displayName", display_name);
        json.writeObjectField("tsuid", tsuid);

        json.writeEndObject();
        json.close();

        // TODO zero copy?
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}