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.ProjectDatabaseAdapter.java

public static Project createProject(Project p) throws IOException, MalformedURLException {
    // Server URL setup
    String _url = getBaseUri().build().toString();

    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    addRequestHeader(conn, true);// w  ww  . j a va2s  .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();
    jgen.writeStringField(Keys.Project.TITLE, p.getProjectTitle());
    jgen.writeArrayFieldStart(Keys.Project.MEETINGS);
    for (Meeting meeting : p.getMeetings()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Meeting.ID, meeting.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeArrayFieldStart(Keys.Project.NOTES);
    for (Note note : p.getNotes()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Note.ID, note.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeArrayFieldStart(Keys.Project.MEMBERS);
    for (User member : p.getMembers()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.User.ID, member.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();

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

    // send payload
    sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // prepare to get the id of the created Meeting
    // Map<String, String> responseMap = new HashMap<String, String>();

    /*
     * result should get valid={"meetingID":"##"}
     */
    String result = new String();
    if (!response.isEmpty()) {
        // responseMap = MAPPER.readValue(response,
        // new TypeReference<HashMap<String, String>>() {
        // });
        JsonNode projectNode = MAPPER.readTree(response);
        if (!projectNode.has(Keys.Project.ID)) {
            result = "invalid";
        } else
            result = projectNode.get(Keys.Project.ID).asText();
    }

    if (!result.equalsIgnoreCase("invalid"))
        p.setProjectID(result);

    conn.disconnect();
    return p;
}

From source file:com.nebhale.cyclinglibrary.web.json.AbstractJsonSerializerTest.java

@Test
public final void test() throws IOException, ParseException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new SimpleModule().addSerializer(new LinkJsonSerializer()));

    T value = getValue();//w  w  w.j  ava 2s  .c o  m
    StringWriter out = new StringWriter();
    JsonGenerator jsonGenerator = objectMapper.getFactory().createJsonGenerator(out);
    SerializerProvider serializerProvider = objectMapper.getSerializerProvider();

    try {
        getJsonSerializer().serialize(value, jsonGenerator, serializerProvider);
        jsonGenerator.flush();
        assertResult(out.toString());
    } finally {
        out.close();
        jsonGenerator.close();
    }
}

From source file:com.github.jonpeterson.jackson.module.versioning.VersionedModelSerializer.java

private void doSerialize(T value, JsonGenerator generator, SerializerProvider provider,
        TypeSerializer typeSerializer) throws IOException {
    // serialize the value into a byte array buffer then parse it back out into a JsonNode tree
    // TODO: find a better way to convert the value into a tree
    JsonFactory factory = generator.getCodec().getFactory();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
    JsonGenerator bufferGenerator = factory.createGenerator(buffer);
    try {/*from   w  w  w.j  a va 2 s .co m*/
        if (typeSerializer != null)
            delegate.serializeWithType(value, bufferGenerator, provider, typeSerializer);
        else
            delegate.serialize(value, bufferGenerator, provider);
    } finally {
        bufferGenerator.close();
    }

    ObjectNode modelData = factory.createParser(buffer.toByteArray()).readValueAsTree();

    // set target version to @SerializeToVersion's value, @JsonVersionModel's defaultSerializeToVersion, or
    //   @JsonVersionModel's currentVersion in that order
    String targetVersion = null;
    if (serializeToVersionProperty != null) {
        targetVersion = (String) serializeToVersionProperty.getAccessor().getValue(value);
        modelData.remove(serializeToVersionProperty.getName());
    }
    if (targetVersion == null)
        targetVersion = jsonVersionedModel.defaultSerializeToVersion();
    if (targetVersion.isEmpty())
        targetVersion = jsonVersionedModel.currentVersion();

    // convert model data if there is a converter and targetVersion is different than the currentVersion or if
    //   alwaysConvert is true
    if (converter != null && (jsonVersionedModel.alwaysConvert()
            || !targetVersion.equals(jsonVersionedModel.currentVersion())))
        modelData = converter.convert(modelData, jsonVersionedModel.currentVersion(), targetVersion,
                JsonNodeFactory.instance);

    // add target version to model data if it wasn't the version to suppress
    if (!targetVersion.equals(jsonVersionedModel.versionToSuppressPropertySerialization()))
        modelData.put(jsonVersionedModel.propertyName(), targetVersion);

    // write node
    generator.writeTree(modelData);
}

From source file:de.terrestris.shogun.security.ShogunAuthProcessingFilter.java

/**
 * On successful authentication by an Authentication Manager of Spring Security
 * we intercept with this method  and change the respone to include the ROLES of
 * the logged in user./*from w  w  w .j  av  a2s  . com*/
 * This way we can react on the ROLES and redirect accordingly within the requesting login form (here login.js)
 *
 * @see WebContent/client/login.js
 */
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException, ServletException {
    SecurityContextHolder.getContext().setAuthentication(authResult);

    SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler();
    this.setAuthenticationSuccessHandler(srh);
    srh.setRedirectStrategy(new RedirectStrategy() {
        @Override
        public void sendRedirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                String s) throws IOException {
            //do nothing, no redirect
        }
    });
    super.successfulAuthentication(request, response, authResult);

    // build a comma separated string of the ROLES
    String authorityText = StringUtils.join(authResult.getAuthorities(), ",");

    // write the servlet return object
    HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
    Writer out = responseWrapper.getWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(out);
    jsonGenerator.writeStartObject();
    jsonGenerator.writeBooleanField("success", true);
    jsonGenerator.writeStringField("name", authResult.getName());
    jsonGenerator.writeStringField("role", authorityText);
    jsonGenerator.writeEndObject();
    jsonGenerator.close();
}

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

@Override
public String createJson() throws JsonProcessingException {
    try {//  w ww .jav a 2 s. com
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JsonGenerator jg = JsonUtil.jsonFactory.createGenerator(outputStream);
        jg.writeStartObject();
        jg.writeNumberField(PVID, id);
        jg.writeStringField(EVENT, evt.name());
        jg.writeFieldName(DATA);
        if (isRawJson)
            jg.writeRaw(":" + data);
        else
            jg.writeObject(data);
        jg.writeEndObject();
        jg.close();
        String s = outputStream.toString(Constants.CHARSET);
        //         System.out.println(s.length() + s);
        outputStream.close();
        return s;
    } catch (Exception e) {
        LoggerUtil.getLogger().log(Level.SEVERE, "Failed to create json.", e);
    }

    return null;
}

From source file:com.predic8.membrane.core.transport.http.AbstractHttpHandler.java

private Response generateErrorResponse(Exception e) {
    String msg;//  w w w. java 2  s .co  m
    boolean printStackTrace = transport.isPrintStackTrace();
    if (printStackTrace) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        msg = sw.toString();
    } else {
        msg = e.toString();
    }
    String comment = "Stack traces can be " + (printStackTrace ? "dis" : "en") + "abled by setting the "
            + "@printStackTrace attribute on <a href=\"http://membrane-soa.org/esb-doc/current/configuration/reference/transport.htm\">transport</a>. "
            + "More details might be found in the log.";

    Response error = null;
    ResponseBuilder b = null;
    if (e instanceof URISyntaxException)
        b = Response.badRequest();
    if (b == null)
        b = Response.internalServerError();
    switch (ContentTypeDetector.detect(exchange.getRequest()).getEffectiveContentType()) {
    case XML:
        error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8))
                .body(("<error><message>" + StringEscapeUtils.escapeXml(msg) + "</message><comment>"
                        + StringEscapeUtils.escapeXml(comment) + "</comment></error>")
                                .getBytes(Constants.UTF_8_CHARSET))
                .build();
        break;
    case JSON:
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            JsonGenerator jg = new JsonFactory().createGenerator(baos);
            jg.writeStartObject();
            jg.writeFieldName("error");
            jg.writeString(msg);
            jg.writeFieldName("comment");
            jg.writeString(comment);
            jg.close();
        } catch (Exception f) {
            log.error("Error generating JSON error response", f);
        }

        error = b.header(HttpUtil.createHeaders(MimeType.APPLICATION_JSON_UTF8)).body(baos.toByteArray())
                .build();
        break;
    case SOAP:
        error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8))
                .body(HttpUtil.getFaultSOAPBody("Internal Server Error", msg + " " + comment)
                        .getBytes(Constants.UTF_8_CHARSET))
                .build();
        break;
    case UNKNOWN:
        error = HttpUtil.setHTMLErrorResponse(b, msg, comment);
        break;
    }
    return error;
}

From source file:org.cloudcoder.dataanalysis.ProgsnapExport.java

private String encodeLine(String tagname, Object value) throws IOException {
    StringWriter sw = new StringWriter();
    JsonFactory factory = new JsonFactory();
    JsonGenerator jg = factory.createGenerator(sw);
    jg.writeStartObject();// w ww.  ja v a2  s. c o  m
    jg.writeStringField("tag", tagname);
    jg.writeFieldName("value");
    writeJsonFieldValue(jg, value);
    jg.writeEndObject();
    jg.close();
    return sw.toString();
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an JSON resource, leaving the stream open
 * for additional writing.//  w  w  w  . j a v a 2s. c o  m
 * 
 * @param outStream
 *            The <code>OutputStream</code> to write the entity to.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing.
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws StorageException
 *             if a Storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 */
private static void writeSingleJsonEntity(final OutputStream outStream, TablePayloadFormat format,
        final TableEntity entity, final boolean isTableEntry, final OperationContext opContext)
        throws StorageException, IOException {
    JsonGenerator generator = jsonFactory.createGenerator(outStream);

    try {
        // write to stream
        writeJsonEntity(generator, format, entity, isTableEntry, opContext);
    } finally {
        generator.close();
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an JSON resource, leaving the stream open
 * for additional writing.//from  w w  w.jav  a 2s  .  com
 * 
 * @param strWriter
 *            The <code>StringWriter</code> to write the entity to.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing.
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws StorageException
 *             if a Storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 */
private static void writeSingleJsonEntity(final StringWriter strWriter, TablePayloadFormat format,
        final TableEntity entity, final boolean isTableEntry, final OperationContext opContext)
        throws StorageException, IOException {
    JsonGenerator generator = jsonFactory.createGenerator(strWriter);

    try {
        // write to stream
        writeJsonEntity(generator, format, entity, isTableEntry, opContext);
    } finally {
        generator.close();
    }
}

From source file:org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkDecoded.java

@JsonValue
@Override//  www . j a  v  a 2s.  c  o m
public String toString() {
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(out);
        generator.writeStartObject();

        generator.writeFieldName("metric");
        generator.writeNumber(chunk.getMetricId());

        generator.writeFieldName("decodedSamples");
        generator.writeString(getDecodedSamples());

        generator.writeEndObject();
        generator.close();
        return out.toString();
    } catch (IOException e) {
        log.error("IOException in toString()", e);
    }

    return null;
}