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:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static Agenda createAgenda(Agenda create) throws IOException {
    Agenda newAgenda = new Agenda(create);
    // Server URL setup
    String _url = getBaseUri().build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, true);//  w w w  .j a  v  a2 s  .  com

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject(); // start agenda
    jgen.writeStringField(Keys.Agenda.TITLE, create.getTitle());
    jgen.writeStringField(Keys.Agenda.MEETING, create.getAttachedMeetingID());
    jgen.writeArrayFieldStart(Keys.Agenda.TOPIC); // start topics
    MAPPER.writeValue(jgen, create.getTopics()); // recursively does
    // subtopics
    jgen.writeEndArray(); // end topics
    jgen.writeEndObject(); // end agenda
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    newAgenda = parseAgenda(MAPPER.readTree(response));
    return newAgenda;
}

From source file:io.protostuff.JsonIOUtil.java

/**
 * Serializes the {@code message} into an {@link OutputStream} using the given {@code schema}.
 *//*from  www.jav a  2s.  c o m*/
public static <T> void writeTo(OutputStream out, T message, Schema<T> schema, boolean numeric)
        throws IOException {
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), out, false);

    final JsonGenerator generator = newJsonGenerator(out, context.allocWriteEncodingBuffer(), 0, true, context);

    /*
     * final JsonGenerator generator = DEFAULT_JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
     */
    try {
        writeTo(generator, message, schema, numeric);
    } finally {
        generator.close();
    }
}

From source file:io.protostuff.JsonIOUtil.java

/**
 * Serializes the {@code messages} into the stream using the given schema.
 *//*w  ww .  j  av  a2  s  .co m*/
public static <T> void writeListTo(OutputStream out, List<T> messages, Schema<T> schema, boolean numeric)
        throws IOException {
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), out, false);

    final JsonGenerator generator = newJsonGenerator(out, context.allocWriteEncodingBuffer(), 0, true, context);
    /*
     * final JsonGenerator generator = DEFAULT_JSON_FACTORY.createJsonGenerator(out, JsonEncoding.UTF8);
     */
    try {
        writeListTo(generator, messages, schema, numeric);
    } finally {
        generator.close();
    }
}

From source file:io.seldon.spark.actions.JobUtils.java

public static String getJsonFromActionData(ActionData actionData) {
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {/*from w  ww  . j  a  v a  2s .  co m*/
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        jg.writeStartObject();
        jg.writeStringField("timestamp_utc", actionData.timestamp_utc);
        jg.writeStringField("client", actionData.client);
        jg.writeStringField("client_userid", actionData.client_userid);
        jg.writeNumberField("userid", actionData.userid);
        jg.writeNumberField("itemid", actionData.itemid);
        jg.writeStringField("client_itemid", actionData.client_itemid);
        jg.writeStringField("rectag", actionData.rectag);
        jg.writeNumberField("type", actionData.type);
        jg.writeNumberField("value", actionData.value);
        jg.writeEndObject();
        jg.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sw.toString();
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

public static String dumpConfigurationAsJson() {
    ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jfactory = mapper.getJsonFactory();
    StringWriter sw = new StringWriter();
    try {//w w w  .jav a  2 s. c o m
        JsonGenerator gen = jfactory.createJsonGenerator(sw);
        gen.writeStartArray();
        for (String v : keys) {
            String st = dumpConfigurationAsJson(v);
            ObjectMapper op = new ObjectMapper();
            JsonNode p = op.readTree(st);
            BaasBoxLogger.debug("OBJECT:" + p.toString());
            BaasBoxLogger.debug("STRING:" + st);
            //JsonParser jp = jfactory.createJsonParser(st);
            gen.writeTree(p);
        }
        gen.writeEndArray();
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for the configuration", e);
    }
    return "[]";
}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * Bean to json string//from  w  w w .j  ava 2s .c  o  m
 * 
 * @param obj obj
 *            bean object
 * @param <T> t           
 * @return json string
 */
public static <T> String toJson(T obj) {
    StringWriter writer = new StringWriter();
    String jsonStr = "";
    JsonGenerator gen = null;
    try {
        gen = getJsonFactory().createGenerator(writer);
        getMapper().writeValue(gen, obj);
        writer.flush();
        jsonStr = writer.toString();

    } catch (IOException e) {
        log.error("{}", e.getMessage(), e);
    } finally {
        if (gen != null) {
            try {
                gen.close();
            } catch (IOException e) {
            }
        }

    }
    return jsonStr;
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static String login(String email, String pass) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Login").build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, true);//from   w  ww  .  j  a  v  a  2  s  .c  o m

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    try {
        // hash the password
        pass = Utilities.computeHash(pass);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.EMAIL, email);
    jgen.writeStringField("password", pass);
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    /*
     * result should get valid={"userID":"##"}
     * invalid={"errorID":"3","errorMessage":"invalid username or password"}
     */
    String result = "";
    if (!response.isEmpty()) {
        JsonNode tree = MAPPER.readTree(response);
        if (!tree.has(Keys.User.ID)) {
            logError(TAG, tree);
            result = "invalid username or password";
        } else
            result = tree.get(Keys.User.ID).asText();
    }

    conn.disconnect();
    return result;

}

From source file:com.netflix.hystrix.serial.SerialHystrixDashboardData.java

private static void writeDashboardData(JsonGenerator json, HystrixDashboardStream.DashboardData dashboardData) {
    try {/*from   w w  w  .  j  a  v a  2s. c om*/
        json.writeStartArray();

        for (HystrixCommandMetrics commandMetrics : dashboardData.getCommandMetrics()) {
            writeCommandMetrics(commandMetrics, json);
        }

        for (HystrixThreadPoolMetrics threadPoolMetrics : dashboardData.getThreadPoolMetrics()) {
            writeThreadPoolMetrics(threadPoolMetrics, json);
        }

        for (HystrixCollapserMetrics collapserMetrics : dashboardData.getCollapserMetrics()) {
            writeCollapserMetrics(collapserMetrics, json);
        }

        json.writeEndArray();

        json.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.webpda.server.core.servermessage.PingMessage.java

@Override
public String createJson() throws JsonProcessingException {
    try {//  ww  w . j  a  v  a  2 s  .c  om
        JsonGenerator jg = createJsonGenerator();
        jg.writeNumberField("Count", count);

        jg.writeEndObject();
        jg.close();
        ByteArrayOutputStream outputStream = (ByteArrayOutputStream) jg.getOutputTarget();
        String s = outputStream.toString(Constants.CHARSET);
        outputStream.close();
        return s;
    } catch (Exception e) {
        LoggerUtil.getLogger().log(Level.SEVERE, "Failed to create json.", e);
    }

    return null;
}

From source file:io.encoded.jersik.runtime.JsonCodec.java

public <T> void encode(T instance, OutputStream out, ObjectCodec<T> codec) throws IOException {
    JsonGenerator generator = JSON_FACTORY.createGenerator(out);
    try {//  w  ww .j a  va 2s  .c  om
        codec.encode(generator, instance);
    } finally {
        generator.close();
    }
}